Search in sources :

Example 6 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project uavstack by uavorg.

the class AbstractHttpClientAdapter method handleSlowOperSupporter.

protected void handleSlowOperSupporter(HttpRequest request, Span span, InvokeChainContext context) {
    if (UAVServer.instance().isExistSupportor("com.creditease.uav.apm.supporters.SlowOperSupporter")) {
        SlowOperContext slowOperContext = new SlowOperContext();
        String queryParams = getParamsFromUri(request.getRequestLine().getUri());
        slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_HEADER, getRequestHeaders(request) + queryParams);
        try {
            // 通过此种方式判断是否存在body,通过httpclient类继承确定
            if (HttpEntityEnclosingRequestBase.class.isAssignableFrom(request.getClass())) {
                HttpEntityEnclosingRequestBase req = (HttpEntityEnclosingRequestBase) request;
                HttpEntity entity = req.getEntity();
                // 兼容不正当使用
                if (entity == null) {
                    slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_BODY, "");
                } else {
                    Header header = entity.getContentEncoding();
                    String encoding = header == null ? "utf-8" : header.getValue();
                    try {
                        BufferedHttpEntity httpEntityWrapper = new BufferedHttpEntity(entity);
                        req.setEntity(httpEntityWrapper);
                        slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_BODY, getHttpEntityContent(httpEntityWrapper, encoding));
                    } catch (IOException e) {
                        logger.warn("HttpEntityWrapper failed!", e);
                        slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_BODY, e.toString());
                    }
                }
            } else {
                slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_BODY, "");
            }
        } catch (Exception e) {
            // 由于会存在无法缓冲的情况,故此处添加捕获
            slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_BODY, e.toString());
        }
        Object[] params = { span, slowOperContext };
        UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.SlowOperSupporter", "runCap", span.getEndpointInfo().split(",")[0], InvokeChainConstants.CapturePhase.PRECAP, context, params);
    }
}
Also used : SlowOperContext(com.creditease.uav.apm.slowoper.spi.SlowOperContext) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) Header(org.apache.http.Header) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException)

Example 7 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project uavstack by uavorg.

the class ApacheHttpClientAdapter method beforeDoCap.

@Override
public void beforeDoCap(InvokeChainContext params, Object[] args) {
    if (UAVServer.instance().isExistSupportor("com.creditease.uav.apm.supporters.SlowOperSupporter")) {
        if (Throwable.class.isAssignableFrom(args[0].getClass())) {
        } else {
            HttpResponse response = (HttpResponse) args[0];
            HttpEntity entity = response.getEntity();
            /**
             * NOTE:the entity may be null. eg:in the springCloud when registering application into eureka, the
             * com.netflix.discovery.DiscoveryClient may return a null.
             */
            if (entity == null) {
                return;
            }
            try {
                BufferedHttpEntity httpEntityWrapper = new BufferedHttpEntity(entity);
                response.setEntity(httpEntityWrapper);
            } catch (IOException e) {
                logger.error("HttpEntityWrapper failed!", e);
            } catch (Exception e) {
                logger.warn("HttpEntityWrapper failed!", e);
            }
        }
    }
}
Also used : HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) IOException(java.io.IOException)

Example 8 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project iaf by ibissource.

the class CmisHttpSender method getMethod.

@Override
public HttpRequestBase getMethod(URI uri, Message message, ParameterValueList pvl, PipeLineSession session) throws SenderException {
    HttpRequestBase method = null;
    HttpMethod methodType = (HttpMethod) session.get("method");
    if (methodType == null) {
        throw new SenderException("unable to determine method from pipeline session");
    }
    try {
        switch(methodType) {
            case GET:
                method = new HttpGet(uri);
                break;
            case POST:
                HttpPost httpPost = new HttpPost(uri);
                // send data
                if (pvl.get("writer") != null) {
                    Output writer = (Output) pvl.get("writer").getValue();
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    Object clientCompression = pvl.get(SessionParameter.CLIENT_COMPRESSION);
                    if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                        httpPost.setHeader("Content-Encoding", "gzip");
                        writer.write(new GZIPOutputStream(out, 4096));
                    } else {
                        writer.write(out);
                    }
                    HttpEntity entity = new BufferedHttpEntity(new ByteArrayEntity(out.toByteArray()));
                    httpPost.setEntity(entity);
                    out.close();
                    method = httpPost;
                }
                break;
            case PUT:
                HttpPut httpPut = new HttpPut(uri);
                // send data
                if (pvl.get("writer") != null) {
                    Output writer = (Output) pvl.get("writer").getValue();
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    Object clientCompression = pvl.get(SessionParameter.CLIENT_COMPRESSION);
                    if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                        httpPut.setHeader("Content-Encoding", "gzip");
                        writer.write(new GZIPOutputStream(out, 4096));
                    } else {
                        writer.write(out);
                    }
                    HttpEntity entity = new BufferedHttpEntity(new ByteArrayEntity(out.toByteArray()));
                    httpPut.setEntity(entity);
                    out.close();
                    method = httpPut;
                }
                break;
            case DELETE:
                method = new HttpDelete(uri);
                break;
            default:
                throw new MethodNotSupportedException("method [" + methodType + "] not implemented");
        }
    } catch (Exception e) {
        throw new SenderException(e);
    }
    if (session.get("headers") != null) {
        @SuppressWarnings("unchecked") Map<String, String> headers = (Map<String, String>) session.get("headers");
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            if (log.isDebugEnabled())
                log.debug("append header [" + entry.getKey() + "] with value [" + entry.getValue() + "]");
            method.addHeader(entry.getKey(), entry.getValue());
        }
    }
    log.debug(getLogPrefix() + "HttpSender constructed " + methodType + "-method [" + method.getURI() + "] query [" + method.getURI().getQuery() + "] ");
    return method;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpGet(org.apache.http.client.methods.HttpGet) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpPut(org.apache.http.client.methods.HttpPut) TimeoutException(nl.nn.adapterframework.core.TimeoutException) CmisConnectionException(org.apache.chemistry.opencmis.commons.exceptions.CmisConnectionException) MethodNotSupportedException(org.apache.http.MethodNotSupportedException) IOException(java.io.IOException) SenderException(nl.nn.adapterframework.core.SenderException) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) GZIPOutputStream(java.util.zip.GZIPOutputStream) Output(org.apache.chemistry.opencmis.client.bindings.spi.http.Output) MethodNotSupportedException(org.apache.http.MethodNotSupportedException) SenderException(nl.nn.adapterframework.core.SenderException) Map(java.util.Map)

Example 9 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project telegram-notifications-plugin by jenkinsci.

the class TelegramBot method sendHttpPostRequest.

private String sendHttpPostRequest(HttpPost httpPost) throws IOException {
    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        HttpEntity httpEntity = response.getEntity();
        BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(httpEntity);
        return EntityUtils.toString(bufferedHttpEntity, StandardCharsets.UTF_8);
    }
}
Also used : HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 10 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project azure-tools-for-java by Microsoft.

the class WebHDFSDeploy method deploy.

@Override
public Observable<String> deploy(File src, Observer<SparkLogLine> logSubject) {
    // three steps to upload via webhdfs
    // 1.put request to create new dir
    // 2.put request to get 307 redirect uri from response
    // 3.put redirect request with file content as setEntity
    final URI dest = getUploadDir();
    final HttpPut req = new HttpPut(dest.toString());
    return http.request(req, null, this.createDirReqParams, null).doOnNext(resp -> {
        if (resp.getStatusLine().getStatusCode() != 200) {
            Exceptions.propagate(new UnknownServiceException("Can not create directory to save artifact using webHDFS storage type"));
        }
    }).map(ignored -> new HttpPut(dest.resolve(src.getName()).toString())).flatMap(put -> http.request(put, null, this.uploadReqParams, null)).map(resp -> resp.getFirstHeader("Location").getValue()).doOnNext(redirectedUri -> {
        if (StringUtils.isBlank(redirectedUri)) {
            Exceptions.propagate(new UnknownServiceException("Can not get valid redirect uri using webHDFS storage type"));
        }
    }).map(HttpPut::new).flatMap(put -> {
        try {
            InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(src), -1, ContentType.APPLICATION_OCTET_STREAM);
            reqEntity.setChunked(true);
            return http.request(put, new BufferedHttpEntity(reqEntity), URLEncodedUtils.parse(put.getURI(), "UTF-8"), null);
        } catch (IOException ex) {
            throw new RuntimeException(new IllegalArgumentException("Can not get local artifact when uploading" + ex.toString()));
        }
    }).map(ignored -> {
        try {
            return getArtifactUploadedPath(dest.resolve(src.getName()).toString());
        } catch (final URISyntaxException ex) {
            throw new RuntimeException(new IllegalArgumentException("Can not get valid artifact upload path" + ex.toString()));
        }
    });
}
Also used : NotNull(com.microsoft.azuretools.azurecommons.helpers.NotNull) Exceptions(rx.exceptions.Exceptions) URISyntaxException(java.net.URISyntaxException) RequestConfig(org.apache.http.client.config.RequestConfig) StringUtils(org.apache.commons.lang3.StringUtils) ILogger(com.microsoft.azure.hdinsight.common.logger.ILogger) Observable(rx.Observable) WebHdfsParamsBuilder(com.microsoft.azure.hdinsight.sdk.storage.webhdfs.WebHdfsParamsBuilder) URI(java.net.URI) IClusterDetail(com.microsoft.azure.hdinsight.sdk.cluster.IClusterDetail) Nullable(com.microsoft.azuretools.azurecommons.helpers.Nullable) URIBuilder(org.apache.http.client.utils.URIBuilder) JobUtils(com.microsoft.azure.hdinsight.spark.jobs.JobUtils) ContentType(org.apache.http.entity.ContentType) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Observer(rx.Observer) File(java.io.File) HttpObservable(com.microsoft.azure.hdinsight.sdk.common.HttpObservable) List(java.util.List) HttpPut(org.apache.http.client.methods.HttpPut) URLEncodedUtils(org.apache.http.client.utils.URLEncodedUtils) InputStreamEntity(org.apache.http.entity.InputStreamEntity) NameValuePair(org.apache.http.NameValuePair) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) SparkLogLine(com.microsoft.azure.hdinsight.spark.common.log.SparkLogLine) UnknownServiceException(java.net.UnknownServiceException) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) UnknownServiceException(java.net.UnknownServiceException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) HttpPut(org.apache.http.client.methods.HttpPut) FileInputStream(java.io.FileInputStream) InputStreamEntity(org.apache.http.entity.InputStreamEntity)

Aggregations

BufferedHttpEntity (org.apache.http.entity.BufferedHttpEntity)43 HttpEntity (org.apache.http.HttpEntity)31 IOException (java.io.IOException)21 HttpResponse (org.apache.http.HttpResponse)16 HttpGet (org.apache.http.client.methods.HttpGet)11 Header (org.apache.http.Header)9 InputStream (java.io.InputStream)8 HttpClient (org.apache.http.client.HttpClient)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 HttpException (org.apache.http.HttpException)6 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)6 File (java.io.File)5 FileOutputStream (java.io.FileOutputStream)5 URISyntaxException (java.net.URISyntaxException)5 HttpHost (org.apache.http.HttpHost)4 HttpRequest (org.apache.http.HttpRequest)4 StatusLine (org.apache.http.StatusLine)4 AuthenticationException (org.apache.http.auth.AuthenticationException)4 CredentialsProvider (org.apache.http.client.CredentialsProvider)4