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.ocpsoft.rewrite.servlet.config.proxy.ProxyServlet.java

protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    /*//from w ww .  java  2s. c o  m
     * Note: we won't transfer the protocol version because I'm not sure it would truly be compatible
     */
    String method = servletRequest.getMethod();
    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, targetUri);
        /*
         * 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, targetUri);

    copyRequestHeaders(servletRequest, proxyRequest);

    try {
        /*
         * Execute the request
         */
        if (doLog) {
            logger.debug("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }
        HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUriObj), proxyRequest);

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

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            /*
             * just to be sure, but is probably a no-op
             */
            EntityUtils.consume(proxyResponse.getEntity());
            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);
    }
}

From source file:uk.ac.ebi.phenotype.web.proxy.ExternalUrlConfiguratbleProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    // Make the Request
    // note: we won't transfer the protocol version because I'm not sure it
    // would truly be compatible
    BasicHttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest(
            servletRequest.getMethod(), rewriteUrlFromRequest(servletRequest));

    copyRequestHeaders(servletRequest, proxyRequest);

    // Add the input entity (streamed) then execute the request.
    HttpResponse proxyResponse = null;//from  w w  w.  ja v a2  s  .com
    InputStream servletRequestInputStream = servletRequest.getInputStream();
    try {
        try {
            proxyRequest.setEntity(
                    new InputStreamEntity(servletRequestInputStream, servletRequest.getContentLength()));

            // Execute the request
            if (doLog) {
                log("proxy " + servletRequest.getMethod() + " uri: " + servletRequest.getRequestURI() + " -- "
                        + proxyRequest.getRequestLine().getUri());
            }
            proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest);
        } finally {
            closeQuietly(servletRequestInputStream);
        }

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

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            EntityUtils.consume(proxyResponse.getEntity());
            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;
        throw new RuntimeException(e);
    }
}

From source file:org.jclouds.http.apachehc.ApacheHCUtils.java

public void addEntityForContent(HttpEntityEnclosingRequest apacheRequest, Payload payload) {
    payload = payload instanceof DelegatingPayload ? DelegatingPayload.class.cast(payload).getDelegate()
            : payload;/*ww w  . j av a 2  s .  c  o  m*/
    if (payload instanceof StringPayload) {
        StringEntity nStringEntity = null;
        try {
            nStringEntity = new StringEntity((String) payload.getRawContent());
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedOperationException("Encoding not supported", e);
        }
        nStringEntity.setContentType(payload.getContentMetadata().getContentType());
        apacheRequest.setEntity(nStringEntity);
    } else if (payload instanceof FilePayload) {
        apacheRequest.setEntity(
                new FileEntity((File) payload.getRawContent(), payload.getContentMetadata().getContentType()));
    } else if (payload instanceof ByteArrayPayload) {
        ByteArrayEntity Entity = new ByteArrayEntity((byte[]) payload.getRawContent());
        Entity.setContentType(payload.getContentMetadata().getContentType());
        apacheRequest.setEntity(Entity);
    } else {
        InputStream inputStream = payload.getInput();
        if (payload.getContentMetadata().getContentLength() == null)
            throw new IllegalArgumentException("you must specify size when content is an InputStream");
        InputStreamEntity entity = new InputStreamEntity(inputStream,
                payload.getContentMetadata().getContentLength());
        entity.setContentType(payload.getContentMetadata().getContentType());
        apacheRequest.setEntity(entity);
    }

    // TODO Reproducing old behaviour exactly; ignoring Content-Type, Content-Length and Content-MD5
    Set<String> desiredHeaders = ImmutableSet.of("Content-Disposition", "Content-Encoding", "Content-Language",
            "Expires");
    MutableContentMetadata md = payload.getContentMetadata();
    for (Map.Entry<String, String> entry : contentMetadataCodec.toHeaders(md).entries()) {
        if (desiredHeaders.contains(entry.getKey())) {
            apacheRequest.addHeader(entry.getKey(), entry.getValue());
        }
    }

    assert apacheRequest.getEntity() != null;
}

From source file:com.kkbox.toolkit.internal.api.APIRequest.java

public void addGZIPPostParam(String key, String value) {
    try {// w w  w . ja  v  a  2  s .c  o  m
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add((new BasicNameValuePair(key, value)));
        GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream);
        gZIPOutputStream.write(EntityUtils.toByteArray(new UrlEncodedFormEntity(postParams, HTTP.UTF_8)));
        gZIPOutputStream.close();
        byte[] byteDataForGZIP = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();
        gzipStreamEntity = new InputStreamEntity(new ByteArrayInputStream(byteDataForGZIP),
                byteDataForGZIP.length);
        gzipStreamEntity.setContentType("application/x-www-form-urlencoded");
        gzipStreamEntity.setContentEncoding("gzip");
    } catch (Exception e) {
    }
}

From source file:org.apache.jena.fuseki.http.DatasetGraphAccessorHTTP.java

private Graph exec(String targetStr, Graph graphToSend, HttpUriRequest httpRequest, boolean processBody) {
    HttpClient httpclient = new SystemDefaultHttpClient(httpParams);

    if (graphToSend != null) {
        // ??? httpRequest isa Post
        // Impedence mismatch - is there a better way?
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Model model = ModelFactory.createModelForGraph(graphToSend);
        model.write(out, "RDF/XML");
        byte[] bytes = out.toByteArray();
        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
        InputStreamEntity reqEntity = new InputStreamEntity(in, bytes.length);
        reqEntity.setContentType(WebContent.contentTypeRDFXML);
        reqEntity.setContentEncoding(WebContent.charsetUTF8);
        HttpEntity entity = reqEntity;//from ww w . j  ava 2 s.  com
        ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(entity);
    }
    TypedInputStream ts = null;
    // httpclient.getParams().setXXX
    try {
        HttpResponse response = httpclient.execute(httpRequest);

        int responseCode = response.getStatusLine().getStatusCode();
        String responseMessage = response.getStatusLine().getReasonPhrase();

        if (HttpSC.isRedirection(responseCode))
            // Not implemented yet.
            throw FusekiRequestException.create(responseCode, responseMessage);

        // Other 400 and 500 - errors

        if (HttpSC.isClientError(responseCode) || HttpSC.isServerError(responseCode))
            throw FusekiRequestException.create(responseCode, responseMessage);

        if (responseCode == HttpSC.NO_CONTENT_204)
            return null;
        if (responseCode == HttpSC.CREATED_201)
            return null;

        if (responseCode != HttpSC.OK_200) {
            Log.warn(this, "Unexpected status code");
            throw FusekiRequestException.create(responseCode, responseMessage);
        }

        // May not have a body.
        String ct = getHeader(response, HttpNames.hContentType);
        if (ct == null) {
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream instream = entity.getContent();
                // Read to completion?
                instream.close();
            }
            return null;
        }

        // Tidy. See ConNeg / MediaType.
        String x = getHeader(response, HttpNames.hContentType);
        String y[] = x.split(";");
        String contentType = null;
        if (y[0] != null)
            contentType = y[0].trim();
        String charset = null;
        if (y.length > 1 && y[1] != null)
            charset = y[1].trim();

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            //                String mimeType = ConNeg.chooseContentType(request, rdfOffer, ConNeg.acceptRDFXML).getAcceptType() ;
            //                String charset = ConNeg.chooseCharset(request, charsetOffer, ConNeg.charsetUTF8).getAcceptType() ;
            ts = new TypedInputStream(instream, contentType, charset, null);
        }
        Graph graph = GraphFactory.createGraphMem();
        if (processBody)
            readGraph(graph, ts, null);
        if (ts != null)
            ts.close();
        Graph graph2 = new UnmodifiableGraph(graph);
        return graph2;
    } catch (IOException ex) {
        httpRequest.abort();
        return null;
    }
}

From source file:org.frontcache.hystrix.FC_BypassCache.java

/**
 * forward all kind of requests (GET, POST, PUT, ...)
 * /*from  w  w  w . j  a v a 2 s  .  c o m*/
 * @param httpclient
 * @param verb
 * @param uri
 * @param request
 * @param headers
 * @param params
 * @param requestEntity
 * @return
 * @throws Exception
 */
private HttpResponse forward(HttpClient httpclient, String verb, String uri, HttpServletRequest request,
        Map<String, List<String>> headers, InputStream requestEntity) throws Exception {

    URL host = context.getOriginURL();
    HttpHost httpHost = FCUtils.getHttpHost(host);
    uri = (host.getPath() + uri).replaceAll("/{2,}", "/");

    HttpRequest httpRequest;
    switch (verb.toUpperCase()) {
    case "POST":
        HttpPost httpPost = new HttpPost(uri + context.getRequestQueryString());
        httpRequest = httpPost;
        httpPost.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
        break;
    case "PUT":
        HttpPut httpPut = new HttpPut(uri + context.getRequestQueryString());
        httpRequest = httpPut;
        httpPut.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
        break;
    case "PATCH":
        HttpPatch httpPatch = new HttpPatch(uri + context.getRequestQueryString());
        httpRequest = httpPatch;
        httpPatch.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
        break;
    default:
        httpRequest = new BasicHttpRequest(verb, uri + context.getRequestQueryString());
    }

    try {
        httpRequest.setHeaders(FCUtils.convertHeaders(headers));
        Header acceptEncoding = httpRequest.getFirstHeader("accept-encoding");
        if (acceptEncoding != null && acceptEncoding.getValue().contains("gzip")) {
            httpRequest.setHeader("accept-encoding", "gzip");
        }
        HttpResponse originResponse = httpclient.execute(httpHost, httpRequest);
        return originResponse;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        // httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.bitrepository.protocol.http.HttpFileExchange.java

/**
 * Method for putting data on the HTTP-server of a given url.
 * /* w w  w. ja v  a2s.c  o m*/
 * TODO perhaps make it synchronized around the URL, to prevent data from 
 * trying to uploaded several times to the same location simultaneously. 
 * 
 * @param in The data to put into the url.
 * @param url The place to put the data.
 * @throws IOException If a problem with the connection occurs during the 
 * transaction. Also if the response code is 300 or above, which indicates
 * that the transaction has not been successful.
 */
private void performUpload(InputStream in, URL url) throws IOException {
    HttpClient httpClient = null;
    try {
        httpClient = getHttpClient();
        HttpPut httpPut = new HttpPut(url.toExternalForm());
        InputStreamEntity reqEntity = new InputStreamEntity(in, -1);
        reqEntity.setChunked(true);
        httpPut.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(httpPut);

        // HTTP code >= 300 means error!
        if (response.getStatusLine().getStatusCode() >= HTTP_ERROR_CODE_BARRIER) {
            throw new IOException("Could not upload file to URL '" + url.toExternalForm()
                    + "'. got status code '" + response.getStatusLine() + "'");
        }
        log.debug("Uploaded datastream to url '" + url.toString() + "' and " + "received the response line '"
                + response.getStatusLine() + "'.");
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
}

From source file:org.realityforge.proxy_servlet.AbstractProxyServlet.java

private HttpRequest newProxyRequest(final HttpServletRequest servletRequest, final String proxyRequestUri)
        throws IOException {
    final String method = servletRequest.getMethod();
    if (null != servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH)
            || null != servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING)) {
        //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
        final HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        r.setEntity(new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        return r;
    } else {// ww w.ja  va 2  s  .  com
        return new BasicHttpRequest(method, proxyRequestUri);
    }
}

From source file:io.mapzone.controller.vm.http.HttpRequestForwarder.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, URISyntaxException {
    targetUriObj = new URI(targetUri.get());
    targetHost = URIUtils.extractHost(targetUriObj);

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

    // spec: RFC 2616, sec 4.3: either of these two headers signal that there is
    // a message body.
    if (request.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || request.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(request.getInputStream(), request.getContentLength()));
        proxyRequest = eProxyRequest;/* w w w. j a  v a2 s  . c o m*/
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(request);

    setXForwardedForHeader(request);

    // Execute the request
    try {
        active.set(this);

        log.debug("REQUEST " + "[" + StringUtils.right(Thread.currentThread().getName(), 2) + "] " + method
                + ": " + request.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri());
        proxyResponse = proxyClient.execute(targetHost, proxyRequest);
    } 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 {
        active.set(null);
    }
    // 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.openrepose.commons.utils.http.ServiceClient.java

public ServiceClientResponse post(String uri, Map<String, String> headers, String body,
        MediaType contentMediaType) {// w w  w.  ja va 2  s  . c  om
    HttpPost post = new HttpPost(uri);

    Map<String, String> requestHeaders = new HashMap<>();
    requestHeaders.putAll(headers);
    String localContentType = contentMediaType.getType() + "/" + contentMediaType.getSubtype();
    requestHeaders.put(CommonHttpHeader.CONTENT_TYPE.toString(), localContentType);

    // TODO: Remove setting the accept type to XML by default
    if (!requestHeaders.containsKey(CommonHttpHeader.ACCEPT.toString())) {
        requestHeaders.put(CommonHttpHeader.ACCEPT.toString(), MediaType.APPLICATION_XML);
    }

    setHeaders(post, requestHeaders);

    if (body != null && !body.isEmpty()) {
        post.setEntity(new InputStreamEntity(new ByteArrayInputStream(body.getBytes()), body.length()));
    }
    return execute(post);
}