Search in sources :

Example 1 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity in project android_frameworks_base by ParanoidAndroid.

the class AndroidHttpClientConnection method receiveResponseEntity.

/**
     * Return the next response entity.
     * @param headers contains values for parsing entity
     * @see HttpClientConnection#receiveResponseEntity(HttpResponse response)
     */
public HttpEntity receiveResponseEntity(final Headers headers) {
    assertOpen();
    BasicHttpEntity entity = new BasicHttpEntity();
    long len = determineLength(headers);
    if (len == ContentLengthStrategy.CHUNKED) {
        entity.setChunked(true);
        entity.setContentLength(-1);
        entity.setContent(new ChunkedInputStream(inbuffer));
    } else if (len == ContentLengthStrategy.IDENTITY) {
        entity.setChunked(false);
        entity.setContentLength(-1);
        entity.setContent(new IdentityInputStream(inbuffer));
    } else {
        entity.setChunked(false);
        entity.setContentLength(len);
        entity.setContent(new ContentLengthInputStream(inbuffer, len));
    }
    String contentTypeHeader = headers.getContentType();
    if (contentTypeHeader != null) {
        entity.setContentType(contentTypeHeader);
    }
    String contentEncodingHeader = headers.getContentEncoding();
    if (contentEncodingHeader != null) {
        entity.setContentEncoding(contentEncodingHeader);
    }
    return entity;
}
Also used : ContentLengthInputStream(org.apache.http.impl.io.ContentLengthInputStream) ChunkedInputStream(org.apache.http.impl.io.ChunkedInputStream) IdentityInputStream(org.apache.http.impl.io.IdentityInputStream) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity)

Example 2 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity in project aws-xray-sdk-java by aws.

the class TracingHandlerTest method mockHttpClient.

private void mockHttpClient(Object client, String responseContent) {
    AmazonHttpClient amazonHttpClient = new AmazonHttpClient(new ClientConfiguration());
    ConnectionManagerAwareHttpClient apacheHttpClient = Mockito.mock(ConnectionManagerAwareHttpClient.class);
    HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    BasicHttpEntity responseBody = new BasicHttpEntity();
    InputStream in = EmptyInputStream.INSTANCE;
    if (null != responseContent && !responseContent.isEmpty()) {
        in = new ByteArrayInputStream(responseContent.getBytes(StandardCharsets.UTF_8));
    }
    responseBody.setContent(in);
    httpResponse.setEntity(responseBody);
    try {
        Mockito.doReturn(httpResponse).when(apacheHttpClient).execute(Mockito.any(HttpUriRequest.class), Mockito.any(HttpContext.class));
    } catch (IOException e) {
        System.err.println("Exception during mock: " + e);
    }
    Whitebox.setInternalState(amazonHttpClient, "httpClient", apacheHttpClient);
    Whitebox.setInternalState(client, "client", amazonHttpClient);
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) EmptyInputStream(org.apache.http.impl.io.EmptyInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) AmazonHttpClient(com.amazonaws.http.AmazonHttpClient) HttpContext(org.apache.http.protocol.HttpContext) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) IOException(java.io.IOException) ConnectionManagerAwareHttpClient(com.amazonaws.http.apache.client.impl.ConnectionManagerAwareHttpClient) ClientConfiguration(com.amazonaws.ClientConfiguration) BasicStatusLine(org.apache.http.message.BasicStatusLine)

Example 3 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity in project nifi by apache.

the class SiteToSiteRestApiClient method initiateTransactionForSend.

/**
 * <p>
 * Initiate a transaction for sending data.
 * </p>
 *
 * <p>
 * If a proxy server requires auth, the proxy server returns 407 response with available auth schema such as basic or digest.
 * Then client has to resend the same request with its credential added.
 * This mechanism is problematic for sending data from NiFi.
 * </p>
 *
 * <p>
 * In order to resend a POST request with auth param,
 * NiFi has to either read flow-file contents to send again, or keep the POST body somewhere.
 * If we store that in memory, it would causes OOM, or storing it on disk slows down performance.
 * Rolling back processing session would be overkill.
 * Reading flow-file contents only when it's ready to send in a streaming way is ideal.
 * </p>
 *
 * <p>
 * Additionally, the way proxy authentication is done is vary among Proxy server software.
 * Some requires 407 and resend cycle for every requests, while others keep a connection between a client and
 * the proxy server, then consecutive requests skip auth steps.
 * The problem is, that how should we behave is only told after sending a request to the proxy.
 * </p>
 *
 * In order to handle above concerns correctly and efficiently, this method do the followings:
 *
 * <ol>
 * <li>Send a GET request to controller resource, to initiate an HttpAsyncClient. The instance will be used for further requests.
 *      This is not required by the Site-to-Site protocol, but it can setup proxy auth state safely.</li>
 * <li>Send a POST request to initiate a transaction. While doing so, it captures how a proxy server works.
 * If 407 and resend cycle occurs here, it implies that we need to do the same thing again when we actually send the data.
 * Because if the proxy keeps using the same connection and doesn't require an auth step, it doesn't do so here.</li>
 * <li>Then this method stores whether the final POST request should wait for the auth step.
 * So that {@link #openConnectionForSend} can determine when to produce contents.</li>
 * </ol>
 *
 * <p>
 * The above special sequence is only executed when a proxy instance is set, and its username is set.
 * </p>
 *
 * @param post a POST request to establish transaction
 * @return POST request response
 * @throws IOException thrown if the post request failed
 */
private HttpResponse initiateTransactionForSend(final HttpPost post) throws IOException {
    if (shouldCheckProxyAuth()) {
        final CloseableHttpAsyncClient asyncClient = getHttpAsyncClient();
        final HttpGet get = createGetControllerRequest();
        final Future<HttpResponse> getResult = asyncClient.execute(get, null);
        try {
            final HttpResponse getResponse = getResult.get(readTimeoutMillis, TimeUnit.MILLISECONDS);
            logger.debug("Proxy auth check has done. getResponse={}", getResponse.getStatusLine());
        } catch (final ExecutionException e) {
            logger.debug("Something has happened at get controller requesting thread for proxy auth check. {}", e.getMessage());
            throw toIOException(e);
        } catch (TimeoutException | InterruptedException e) {
            throw new IOException(e);
        }
    }
    final HttpAsyncRequestProducer asyncRequestProducer = new HttpAsyncRequestProducer() {

        private boolean requestHasBeenReset = false;

        @Override
        public HttpHost getTarget() {
            return URIUtils.extractHost(post.getURI());
        }

        @Override
        public HttpRequest generateRequest() throws IOException, HttpException {
            final BasicHttpEntity entity = new BasicHttpEntity();
            post.setEntity(entity);
            return post;
        }

        @Override
        public void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException {
            encoder.complete();
            if (shouldCheckProxyAuth() && requestHasBeenReset) {
                logger.debug("Produced content again, assuming the proxy server requires authentication.");
                proxyAuthRequiresResend.set(true);
            }
        }

        @Override
        public void requestCompleted(HttpContext context) {
            debugProxyAuthState(context);
        }

        @Override
        public void failed(Exception ex) {
            final String msg = String.format("Failed to create transaction for %s", post.getURI());
            logger.error(msg, ex);
            eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg);
        }

        @Override
        public boolean isRepeatable() {
            return true;
        }

        @Override
        public void resetRequest() throws IOException {
            requestHasBeenReset = true;
        }

        @Override
        public void close() throws IOException {
        }
    };
    final Future<HttpResponse> responseFuture = getHttpAsyncClient().execute(asyncRequestProducer, new BasicAsyncResponseConsumer(), null);
    final HttpResponse response;
    try {
        response = responseFuture.get(readTimeoutMillis, TimeUnit.MILLISECONDS);
    } catch (final ExecutionException e) {
        logger.debug("Something has happened at initiate transaction requesting thread. {}", e.getMessage());
        throw toIOException(e);
    } catch (TimeoutException | InterruptedException e) {
        throw new IOException(e);
    }
    return response;
}
Also used : ContentEncoder(org.apache.http.nio.ContentEncoder) HttpGet(org.apache.http.client.methods.HttpGet) IOControl(org.apache.http.nio.IOControl) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) IOException(java.io.IOException) HandshakeException(org.apache.nifi.remote.exception.HandshakeException) HttpException(org.apache.http.HttpException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) ProtocolException(org.apache.nifi.remote.exception.ProtocolException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) PortNotRunningException(org.apache.nifi.remote.exception.PortNotRunningException) MalformedURLException(java.net.MalformedURLException) UnknownPortException(org.apache.nifi.remote.exception.UnknownPortException) CertificateException(java.security.cert.CertificateException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) BasicAsyncResponseConsumer(org.apache.http.nio.protocol.BasicAsyncResponseConsumer) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 4 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity in project CodeUtils by boredream.

the class LeanCloudHttpUtils method entityFromConnection.

/**
	 * Initializes an {@link HttpEntity} from the given
	 * {@link HttpURLConnection}.
	 *
	 * @param connection
	 * @return an HttpEntity populated with data from <code>connection</code>.
	 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}
Also used : BasicHttpEntity(org.apache.http.entity.BasicHttpEntity)

Example 5 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity in project wso2-synapse by wso2.

the class TargetRequest method processChunking.

/**
 * Handles the chuking messages in Passthough context, create a temporary buffer and calculate the message
 * size before writing to the external buffer, which is required the context of handling DISABLED chunking
 * messages
 *
 * @param conn
 * @param requestMsgCtx
 * @throws IOException
 * @throws AxisFault
 */
private void processChunking(NHttpClientConnection conn, MessageContext requestMsgCtx) throws IOException, AxisFault {
    String disableChunking = (String) requestMsgCtx.getProperty(PassThroughConstants.DISABLE_CHUNKING);
    String forceHttp10 = (String) requestMsgCtx.getProperty(PassThroughConstants.FORCE_HTTP_1_0);
    if ("true".equals(disableChunking) || "true".equals(forceHttp10)) {
        if (requestMsgCtx.getEnvelope().getBody().getFirstElement() == null) {
            BasicHttpEntity entity = (BasicHttpEntity) ((BasicHttpEntityEnclosingRequest) request).getEntity();
            try {
                RelayUtils.buildMessage(requestMsgCtx);
                this.hasEntityBody = true;
                Pipe pipe = (Pipe) requestMsgCtx.getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
                if (pipe != null) {
                    pipe.attachConsumer(conn);
                    this.connect(pipe);
                    if (Boolean.TRUE.equals(requestMsgCtx.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED))) {
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(requestMsgCtx);
                        OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(requestMsgCtx);
                        formatter.writeTo(requestMsgCtx, format, out, false);
                        OutputStream _out = pipe.getOutputStream();
                        IOUtils.write(out.toByteArray(), _out);
                        entity.setContentLength(new Long(out.toByteArray().length));
                        entity.setChunked(false);
                    }
                }
            // pipe.setSerializationComplete(true);
            } catch (XMLStreamException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MessageFormatter(org.apache.axis2.transport.MessageFormatter) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Aggregations

BasicHttpEntity (org.apache.http.entity.BasicHttpEntity)135 ByteArrayInputStream (java.io.ByteArrayInputStream)100 Test (org.junit.Test)85 InputStream (java.io.InputStream)60 IOException (java.io.IOException)48 HttpResponse (org.apache.http.HttpResponse)13 BasicStatusLine (org.apache.http.message.BasicStatusLine)10 StatusLine (org.apache.http.StatusLine)9 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)9 HttpException (org.apache.http.HttpException)8 HttpContext (org.apache.http.protocol.HttpContext)8 URISyntaxException (java.net.URISyntaxException)7 Map (java.util.Map)7 Header (org.apache.http.Header)7 URI (java.net.URI)6 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)6 ChunkedInputStream (org.apache.http.impl.io.ChunkedInputStream)6 ContentLengthInputStream (org.apache.http.impl.io.ContentLengthInputStream)6 IdentityInputStream (org.apache.http.impl.io.IdentityInputStream)6 ExecutionException (java.util.concurrent.ExecutionException)5