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) 

Source Link

Usage

From source file:org.cerberus.service.rest.impl.RestService.java

@Override
public AnswerItem<AppService> callREST(String servicePath, String requestString, String method,
        List<AppServiceHeader> headerList, List<AppServiceContent> contentList, String token, int timeOutMs) {
    AnswerItem result = new AnswerItem();
    AppService serviceREST = factoryAppService.create("", AppService.TYPE_REST, method, "", "", "", "", "", "",
            "", "", null, "", null);
    MessageEvent message = null;//ww w .j a v  a  2 s  .c om

    if (StringUtils.isNullOrEmpty(servicePath)) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_SERVICEPATHMISSING);
        result.setResultMessage(message);
        return result;
    }
    if (StringUtils.isNullOrEmpty(method)) {
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_METHODMISSING);
        result.setResultMessage(message);
        return result;
    }
    // If token is defined, we add 'cerberus-token' on the http header.
    if (token != null) {
        headerList.add(
                factoryAppServiceHeader.create(null, "cerberus-token", token, "Y", 0, "", "", null, "", null));
    }
    CloseableHttpClient httpclient;
    httpclient = HttpClients.createDefault();
    try {

        // Timeout setup.
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeOutMs).build();

        AppService responseHttp = null;

        switch (method) {
        case AppService.METHOD_HTTPGET:

            LOG.info("Start preparing the REST Call (GET). " + servicePath + " - " + requestString);

            servicePath = StringUtil.addQueryString(servicePath, requestString);
            serviceREST.setServicePath(servicePath);
            HttpGet httpGet = new HttpGet(servicePath);

            // Timeout setup.
            httpGet.setConfig(requestConfig);

            // Header.
            for (AppServiceHeader contentHeader : headerList) {
                httpGet.addHeader(contentHeader.getKey(), contentHeader.getValue());
            }
            serviceREST.setHeaderList(headerList);
            // Saving the service before the call Just in case it goes wrong (ex : timeout).
            result.setItem(serviceREST);

            LOG.info("Executing request " + httpGet.getRequestLine());
            responseHttp = executeHTTPCall(httpclient, httpGet);

            if (responseHttp != null) {
                serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());
                serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());
                serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());
                serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());
            }

            break;
        case AppService.METHOD_HTTPPOST:

            LOG.info("Start preparing the REST Call (POST). " + servicePath);

            serviceREST.setServicePath(servicePath);
            HttpPost httpPost = new HttpPost(servicePath);

            // Timeout setup.
            httpPost.setConfig(requestConfig);

            // Content
            if (!(StringUtil.isNullOrEmpty(requestString))) {
                InputStream stream = new ByteArrayInputStream(requestString.getBytes(StandardCharsets.UTF_8));
                InputStreamEntity reqEntity = new InputStreamEntity(stream);
                reqEntity.setChunked(true);
                httpPost.setEntity(reqEntity);
                serviceREST.setServiceRequest(requestString);
            } else {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                for (AppServiceContent contentVal : contentList) {
                    nvps.add(new BasicNameValuePair(contentVal.getKey(), contentVal.getValue()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nvps));
                serviceREST.setContentList(contentList);
            }

            // Header.
            for (AppServiceHeader contentHeader : headerList) {
                httpPost.addHeader(contentHeader.getKey(), contentHeader.getValue());
            }
            serviceREST.setHeaderList(headerList);
            // Saving the service before the call Just in case it goes wrong (ex : timeout).
            result.setItem(serviceREST);

            LOG.info("Executing request " + httpPost.getRequestLine());
            responseHttp = executeHTTPCall(httpclient, httpPost);

            if (responseHttp != null) {
                serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());
                serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());
                serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());
                serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());
            } else {
                message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
                message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));
                message.setDescription(message.getDescription().replace("%DESCRIPTION%",
                        "Any issue was found when calling the service. Coud be a reached timeout during the call (."
                                + timeOutMs + ")"));
                result.setResultMessage(message);
                return result;

            }

            break;
        }

        // Get result Content Type.
        if (responseHttp != null) {
            serviceREST.setResponseHTTPBodyContentType(AppServiceService.guessContentType(serviceREST,
                    AppService.RESPONSEHTTPBODYCONTENTTYPE_JSON));
        }

        result.setItem(serviceREST);
        message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_CALLSERVICE);
        message.setDescription(message.getDescription().replace("%SERVICEMETHOD%", method));
        message.setDescription(message.getDescription().replace("%SERVICEPATH%", servicePath));
        result.setResultMessage(message);

    } catch (SocketTimeoutException ex) {
        LOG.info("Exception when performing the REST Call. " + ex.toString());
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_TIMEOUT);
        message.setDescription(message.getDescription().replace("%SERVICEURL%", servicePath));
        message.setDescription(message.getDescription().replace("%TIMEOUT%", String.valueOf(timeOutMs)));
        result.setResultMessage(message);
        return result;
    } catch (Exception ex) {
        LOG.error("Exception when performing the REST Call. " + ex.toString());
        message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
        message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));
        message.setDescription(
                message.getDescription().replace("%DESCRIPTION%", "Error on CallREST : " + ex.toString()));
        result.setResultMessage(message);
        return result;
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            LOG.error(ex.toString());
        }
    }

    return result;
}

From source file:org.commonjava.aprox.client.core.AproxClientHttp.java

public void putWithStream(final String path, final InputStream stream, final int... responseCodes)
        throws AproxClientException {
    connect();//w w  w  .  ja  v  a2 s . com

    final HttpPut put = newRawPut(buildUrl(baseUrl, path));
    final CloseableHttpClient client = newClient();
    try {
        put.setEntity(new InputStreamEntity(stream));

        client.execute(put, new ResponseHandler<Void>() {
            @Override
            public Void handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                try {
                    final StatusLine sl = response.getStatusLine();
                    if (!validResponseCode(sl.getStatusCode(), responseCodes)) {
                        throw new ClientProtocolException(
                                String.format("Error in response from: %s. Status was: %d %s (%s)", path,
                                        sl.getStatusCode(), sl.getReasonPhrase(), sl.getProtocolVersion()));
                    }

                    return null;
                } finally {
                    cleanupResources(put, response, client);
                }
            }
        });

    } catch (final IOException e) {
        throw new AproxClientException("AProx request failed: %s", e, e.getMessage());
    }
}

From source file:io.undertow.servlet.test.streams.AbstractServletInputStreamTestCase.java

public void runTestParallel(int concurrency, final String message, String url, boolean preamble,
        boolean offIOThread) throws Exception {

    CloseableHttpClient client = HttpClients.custom().setMaxConnPerRoute(1000)
            .setSSLContext(DefaultServer.createClientSslContext()).build();
    byte[] messageBytes = message.getBytes();
    try {/*from  w w w. j a  va  2  s.  com*/
        ExecutorService executorService = Executors.newFixedThreadPool(concurrency);
        Callable task = new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                String uri = getBaseUrl() + "/servletContext/" + url;
                HttpPost post = new HttpPost(uri);
                if (preamble && !message.isEmpty()) {
                    post.addHeader("preamble", Integer.toString(message.length() / 2));
                }
                if (offIOThread) {
                    post.addHeader("offIoThread", "true");
                }
                post.setEntity(new InputStreamEntity(
                        // Server should wait for events from the client
                        new RateLimitedInputStream(new ByteArrayInputStream(messageBytes))));
                CloseableHttpResponse result = client.execute(post);
                try {
                    Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                    final String response = HttpClientUtils.readResponse(result);
                    Assert.assertEquals(message.length(), response.length());
                    Assert.assertEquals(message, response);
                } finally {
                    result.close();
                }
                return null;
            }
        };
        List<Future<?>> results = new ArrayList<>();
        for (int i = 0; i < concurrency * 5; i++) {
            Future<?> future = executorService.submit(task);
            results.add(future);
        }
        for (Future<?> i : results) {
            i.get();
        }
        executorService.shutdown();
        Assert.assertTrue(executorService.awaitTermination(70, TimeUnit.SECONDS));
    } finally {
        client.close();
    }
}

From source file:org.commonjava.propulsor.client.http.ClientHttpSupport.java

public void putWithStream(final String path, final InputStream stream, final int... responseCodes)
        throws ClientHttpException {
    connect();/*  w  w  w . ja  v  a2 s .c om*/

    final HttpPut put = newRawPut(buildUrl(baseUrl, path));
    final CloseableHttpClient client = newClient();
    CloseableHttpResponse response = null;
    try {
        put.setEntity(new InputStreamEntity(stream));

        response = client.execute(put);
        final StatusLine sl = response.getStatusLine();
        if (!validResponseCode(sl.getStatusCode(), responseCodes)) {
            throw new ClientProtocolException(new ClientHttpException(sl.getStatusCode(),
                    "Error in response from: %s.\n%s", path, new ClientHttpResponseErrorDetails(response)));
        }

    } catch (final ClientProtocolException e) {
        final Throwable cause = e.getCause();
        if (cause != null && (cause instanceof ClientHttpException)) {
            throw (ClientHttpException) cause;
        }

        throw new ClientHttpException("Client request failed: %s", e, e.getMessage());
    } catch (final IOException e) {
        throw new ClientHttpException("Client request failed: %s", e, e.getMessage());
    } finally {
        cleanupResources(put, response, client);
    }
}

From source file:com.threatconnect.sdk.client.writer.AbstractWriterAdapter.java

protected <T extends ApiEntitySingleResponse> T uploadFile(String propName, Class<T> type, String ownerName,
        InputStream inputStream, Map<String, Object> paramMap, UploadMethodType uploadMethodType,
        Boolean updateIfExists) throws FailedResponseException, UnsupportedEncodingException {
    return uploadFile(propName, type, ownerName, new InputStreamEntity(inputStream), paramMap, uploadMethodType,
            updateIfExists);/*  w w w. j  ava 2s. c o m*/
}

From source file:nl.nn.adapterframework.extensions.akamai.NetStorageSender.java

@Override
public HttpRequestBase getMethod(URIBuilder uri, String message, ParameterValueList parameters,
        Map<String, String> headersParamsMap, IPipeLineSession session) throws SenderException {

    NetStorageAction netStorageAction = new NetStorageAction(getAction());
    netStorageAction.setVersion(actionVersion);
    netStorageAction.setHashAlgorithm(hashAlgorithm);

    if (parameters != null)
        netStorageAction.mapParameters(parameters);

    try {/*from ww  w .j a v a2  s.c  o m*/
        URL url = uri.build().toURL();

        setMethodType(netStorageAction.getMethod());
        log.debug("opening [" + netStorageAction.getMethod() + "] connection to [" + url + "] with action ["
                + getAction() + "]");

        NetStorageCmsSigner signer = new NetStorageCmsSigner(url, accessTokenCf.getUsername(),
                accessTokenCf.getPassword(), netStorageAction, getSignType());
        Map<String, String> headers = signer.computeHeaders();

        boolean queryParametersAppended = false;
        StringBuffer path = new StringBuffer(uri.getPath());

        if (getMethodType().equals("GET")) {
            if (parameters != null) {
                queryParametersAppended = appendParameters(queryParametersAppended, path, parameters,
                        headersParamsMap);
                log.debug(getLogPrefix() + "path after appending of parameters [" + path.toString() + "]");
            }
            HttpGet method = new HttpGet(uri.build());
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                log.debug("append header [" + entry.getKey() + "] with value [" + entry.getValue() + "]");

                method.setHeader(entry.getKey(), entry.getValue());
            }
            log.debug(getLogPrefix() + "HttpSender constructed GET-method [" + method.getURI() + "] query ["
                    + method.getURI().getQuery() + "] ");

            return method;
        } else if (getMethodType().equals("PUT")) {
            HttpPut method = new HttpPut(uri.build());

            for (Map.Entry<String, String> entry : headers.entrySet()) {
                log.debug("append header [" + entry.getKey() + "] with value [" + entry.getValue() + "]");

                method.setHeader(entry.getKey(), entry.getValue());
            }
            log.debug(getLogPrefix() + "HttpSender constructed GET-method [" + method.getURI() + "] query ["
                    + method.getURI().getQuery() + "] ");

            if (netStorageAction.getFile() != null) {
                HttpEntity entity = new InputStreamEntity(netStorageAction.getFile());
                method.setEntity(entity);
            }
            return method;
        } else if (getMethodType().equals("POST")) {
            HttpPost method = new HttpPost(uri.build());

            for (Map.Entry<String, String> entry : headers.entrySet()) {
                log.debug("append header [" + entry.getKey() + "] with value [" + entry.getValue() + "]");

                method.setHeader(entry.getKey(), entry.getValue());
            }
            log.debug(getLogPrefix() + "HttpSender constructed GET-method [" + method.getURI() + "] query ["
                    + method.getURI().getQuery() + "] ");

            if (netStorageAction.getFile() != null) {
                HttpEntity entity = new InputStreamEntity(netStorageAction.getFile());
                method.setEntity(entity);
            }
            return method;
        }

    } catch (Exception e) {
        throw new SenderException(e);
    }
    return null;
}

From source file:org.commonjava.indy.client.core.IndyClientHttp.java

public void putWithStream(final String path, final InputStream stream, final int... responseCodes)
        throws IndyClientException {
    connect();//from   w  ww  . j  ava  2s .  co m

    final HttpPut put = newRawPut(buildUrl(baseUrl, path));
    final CloseableHttpClient client = newClient();
    CloseableHttpResponse response = null;
    try {
        put.setEntity(new InputStreamEntity(stream));

        response = client.execute(put, newContext());
        final StatusLine sl = response.getStatusLine();
        if (!validResponseCode(sl.getStatusCode(), responseCodes)) {
            throw new ClientProtocolException(new IndyClientException(sl.getStatusCode(),
                    "Error in response from: %s.\n%s", path, new IndyResponseErrorDetails(response)));
        }

    } catch (final ClientProtocolException e) {
        final Throwable cause = e.getCause();
        if (cause != null && (cause instanceof IndyClientException)) {
            throw (IndyClientException) cause;
        }

        throw new IndyClientException("Indy request failed: %s", e, e.getMessage());
    } catch (final IOException e) {
        throw new IndyClientException("Indy request failed: %s", e, e.getMessage());
    } finally {
        cleanupResources(put, response, client);
    }
}

From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java

private <T> void writeContent(final Edm edm, HttpEntityEnclosingRequestBase httpEntityRequest,
        final UriInfoWithType uriInfo, final Object content, final Olingo2ResponseHandler<T> responseHandler) {

    try {// ww  w.ja v a2  s .c om
        // process resource by UriType
        final ODataResponse response = writeContent(edm, uriInfo, content);

        // copy all response headers
        for (String header : response.getHeaderNames()) {
            httpEntityRequest.setHeader(header, response.getHeader(header));
        }

        // get (http) entity which is for default Olingo2 implementation an InputStream
        if (response.getEntity() instanceof InputStream) {
            httpEntityRequest.setEntity(new InputStreamEntity((InputStream) response.getEntity()));
            /*
                            // avoid sending it without a header field set
                            if (!httpEntityRequest.containsHeader(HttpHeaders.CONTENT_TYPE)) {
            httpEntityRequest.addHeader(HttpHeaders.CONTENT_TYPE, getContentType());
                            }
            */
        }

        // execute HTTP request
        final Header requestContentTypeHeader = httpEntityRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE);
        final ContentType requestContentType = requestContentTypeHeader != null
                ? ContentType.parse(requestContentTypeHeader.getValue())
                : contentType;
        execute(httpEntityRequest, requestContentType, new AbstractFutureCallback<T>(responseHandler) {
            @SuppressWarnings("unchecked")
            @Override
            public void onCompleted(HttpResponse result)
                    throws IOException, EntityProviderException, BatchException, ODataApplicationException {

                // if a entity is created (via POST request) the response body contains the new created entity
                HttpStatusCodes statusCode = HttpStatusCodes
                        .fromStatusCode(result.getStatusLine().getStatusCode());

                // look for no content, or no response body!!!
                final boolean noEntity = result.getEntity() == null
                        || result.getEntity().getContentLength() == 0;
                if (statusCode == HttpStatusCodes.NO_CONTENT || noEntity) {
                    responseHandler.onResponse(
                            (T) HttpStatusCodes.fromStatusCode(result.getStatusLine().getStatusCode()));
                } else {

                    switch (uriInfo.getUriType()) {
                    case URI9:
                        // $batch
                        final List<BatchSingleResponse> singleResponses = EntityProvider.parseBatchResponse(
                                result.getEntity().getContent(),
                                result.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());

                        // parse batch response bodies
                        final List<Olingo2BatchResponse> responses = new ArrayList<Olingo2BatchResponse>();
                        Map<String, String> contentIdLocationMap = new HashMap<String, String>();

                        final List<Olingo2BatchRequest> batchRequests = (List<Olingo2BatchRequest>) content;
                        final Iterator<Olingo2BatchRequest> iterator = batchRequests.iterator();

                        for (BatchSingleResponse response : singleResponses) {
                            final Olingo2BatchRequest request = iterator.next();

                            if (request instanceof Olingo2BatchChangeRequest
                                    && ((Olingo2BatchChangeRequest) request).getContentId() != null) {

                                contentIdLocationMap.put(
                                        "$" + ((Olingo2BatchChangeRequest) request).getContentId(),
                                        response.getHeader(HttpHeaders.LOCATION));
                            }

                            try {
                                responses.add(parseResponse(edm, contentIdLocationMap, request, response));
                            } catch (Exception e) {
                                // report any parsing errors as error response
                                responses.add(new Olingo2BatchResponse(
                                        Integer.parseInt(response.getStatusCode()), response.getStatusInfo(),
                                        response.getContentId(), response.getHeaders(),
                                        new ODataApplicationException(
                                                "Error parsing response for " + request + ": " + e.getMessage(),
                                                Locale.ENGLISH, e)));
                            }
                        }
                        responseHandler.onResponse((T) responses);
                        break;

                    case URI4:
                    case URI5:
                        // simple property
                        // get the response content as Object for $value or Map<String, Object> otherwise
                        final List<EdmProperty> simplePropertyPath = uriInfo.getPropertyPath();
                        final EdmProperty simpleProperty = simplePropertyPath
                                .get(simplePropertyPath.size() - 1);
                        if (uriInfo.isValue()) {
                            responseHandler.onResponse((T) EntityProvider.readPropertyValue(simpleProperty,
                                    result.getEntity().getContent()));
                        } else {
                            responseHandler.onResponse((T) EntityProvider.readProperty(getContentType(),
                                    simpleProperty, result.getEntity().getContent(),
                                    EntityProviderReadProperties.init().build()));
                        }
                        break;

                    case URI3:
                        // complex property
                        // get the response content as Map<String, Object>
                        final List<EdmProperty> complexPropertyPath = uriInfo.getPropertyPath();
                        final EdmProperty complexProperty = complexPropertyPath
                                .get(complexPropertyPath.size() - 1);
                        responseHandler.onResponse((T) EntityProvider.readProperty(getContentType(),
                                complexProperty, result.getEntity().getContent(),
                                EntityProviderReadProperties.init().build()));
                        break;

                    case URI7A:
                        // $links with 0..1 cardinality property
                        // get the response content as String
                        final EdmEntitySet targetLinkEntitySet = uriInfo.getTargetEntitySet();
                        responseHandler.onResponse((T) EntityProvider.readLink(getContentType(),
                                targetLinkEntitySet, result.getEntity().getContent()));
                        break;

                    case URI7B:
                        // $links with * cardinality property
                        // get the response content as java.util.List<String>
                        final EdmEntitySet targetLinksEntitySet = uriInfo.getTargetEntitySet();
                        responseHandler.onResponse((T) EntityProvider.readLinks(getContentType(),
                                targetLinksEntitySet, result.getEntity().getContent()));
                        break;

                    case URI1:
                    case URI2:
                    case URI6A:
                    case URI6B:
                        // Entity
                        // get the response content as an ODataEntry object
                        responseHandler.onResponse((T) EntityProvider.readEntry(response.getContentHeader(),
                                uriInfo.getTargetEntitySet(), result.getEntity().getContent(),
                                EntityProviderReadProperties.init().build()));
                        break;

                    default:
                        throw new ODataApplicationException(
                                "Unsupported resource type " + uriInfo.getTargetType(), Locale.ENGLISH);
                    }

                }
            }
        });
    } catch (ODataException e) {
        responseHandler.onException(e);
    } catch (URISyntaxException e) {
        responseHandler.onException(e);
    } catch (UnsupportedEncodingException e) {
        responseHandler.onException(e);
    } catch (IOException e) {
        responseHandler.onException(e);
    }
}

From source file:net.community.chest.gitcloud.facade.frontend.git.GitController.java

private CloseableHttpResponse transferPostedData(HttpEntityEnclosingRequestBase postRequest,
        final HttpServletRequest req) throws IOException {
    InputStream postData = req.getInputStream();
    try {//w  ww. j av  a  2s  .c o m
        if (logger.isTraceEnabled()) {
            LineLevelAppender appender = new LineLevelAppender() {
                @Override
                @SuppressWarnings("synthetic-access")
                public void writeLineData(CharSequence lineData) throws IOException {
                    logger.trace("transferPostedData(" + req.getMethod() + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "] C: " + lineData);
                }

                @Override
                public boolean isWriteEnabled() {
                    return true;
                }
            };
            postData = new TeeInputStream(postData, new HexDumpOutputStream(appender), true);
        }
        postRequest.setEntity(new InputStreamEntity(postData));
        return client.execute(postRequest);
    } finally {
        postData.close();
    }
}