Search in sources :

Example 26 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project robovm by robovm.

the class DefaultRequestDirector method createTunnelToTarget.

// establishConnection
/**
     * Creates a tunnel to the target server.
     * The connection must be established to the (last) proxy.
     * A CONNECT request for tunnelling through the proxy will
     * be created and sent, the response received and checked.
     * This method does <i>not</i> update the connection with
     * information about the tunnel, that is left to the caller.
     *
     * @param route     the route to establish
     * @param context   the context for request execution
     *
     * @return  <code>true</code> if the tunnelled route is secure,
     *          <code>false</code> otherwise.
     *          The implementation here always returns <code>false</code>,
     *          but derived classes may override.
     *
     * @throws HttpException    in case of a problem
     * @throws IOException      in case of an IO problem
     */
protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {
    HttpHost proxy = route.getProxyHost();
    HttpHost target = route.getTargetHost();
    HttpResponse response = null;
    boolean done = false;
    while (!done) {
        done = true;
        if (!this.managedConn.isOpen()) {
            this.managedConn.open(route, context, this.params);
        }
        HttpRequest connect = createConnectRequest(route, context);
        String agent = HttpProtocolParams.getUserAgent(params);
        if (agent != null) {
            connect.addHeader(HTTP.USER_AGENT, agent);
        }
        connect.addHeader(HTTP.TARGET_HOST, target.toHostString());
        AuthScheme authScheme = this.proxyAuthState.getAuthScheme();
        AuthScope authScope = this.proxyAuthState.getAuthScope();
        Credentials creds = this.proxyAuthState.getCredentials();
        if (creds != null) {
            if (authScope != null || !authScheme.isConnectionBased()) {
                try {
                    connect.addHeader(authScheme.authenticate(creds, connect));
                } catch (AuthenticationException ex) {
                    if (this.log.isErrorEnabled()) {
                        this.log.error("Proxy authentication error: " + ex.getMessage());
                    }
                }
            }
        }
        response = requestExec.execute(connect, this.managedConn, context);
        int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
            if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
                this.log.debug("Proxy requested authentication");
                Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
                try {
                    processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
                } catch (AuthenticationException ex) {
                    if (this.log.isWarnEnabled()) {
                        this.log.warn("Authentication error: " + ex.getMessage());
                        break;
                    }
                }
                updateAuthState(this.proxyAuthState, proxy, credsProvider);
                if (this.proxyAuthState.getCredentials() != null) {
                    done = false;
                    // Retry request
                    if (this.reuseStrategy.keepAlive(response, context)) {
                        this.log.debug("Connection kept alive");
                        // Consume response content
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            entity.consumeContent();
                        }
                    } else {
                        this.managedConn.close();
                    }
                }
            } else {
                // Reset proxy auth scope
                this.proxyAuthState.setAuthScope(null);
            }
        }
    }
    int status = response.getStatusLine().getStatusCode();
    if (status > 299) {
        // Buffer response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }
        this.managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }
    this.managedConn.markReusable();
    // Leave it to derived classes, consider insecure by default here.
    return false;
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) AbortableHttpRequest(org.apache.http.client.methods.AbortableHttpRequest) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) AuthenticationException(org.apache.http.auth.AuthenticationException) HttpResponse(org.apache.http.HttpResponse) CredentialsProvider(org.apache.http.client.CredentialsProvider) AuthScheme(org.apache.http.auth.AuthScheme) Header(org.apache.http.Header) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) HttpException(org.apache.http.HttpException) Credentials(org.apache.http.auth.Credentials)

Example 27 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project knox by apache.

the class RMHaBaseDispatcher method writeOutboundResponse.

/**
 * Checks for specific outbound response codes/content to trigger a retry or failover
 */
@Override
protected void writeOutboundResponse(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse, HttpResponse inboundResponse) throws IOException {
    int status = inboundResponse.getStatusLine().getStatusCode();
    if (status == 403 || status == 307) {
        BufferedHttpEntity entity = new BufferedHttpEntity(inboundResponse.getEntity());
        inboundResponse.setEntity(entity);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        inboundResponse.getEntity().writeTo(outputStream);
        String body = new String(outputStream.toByteArray());
        if (body.contains("This is standby RM")) {
            throw new StandbyException();
        }
        if (body.contains("SafeModeException") || body.contains("RetriableException")) {
            throw new SafeModeException();
        }
    }
    super.writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
}
Also used : BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 28 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project knox by apache.

the class WebHdfsHaDispatch method writeOutboundResponse.

/**
 * Checks for specific outbound response codes/content to trigger a retry or failover
 */
@Override
protected void writeOutboundResponse(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse, HttpResponse inboundResponse) throws IOException {
    if (inboundResponse.getStatusLine().getStatusCode() == 403) {
        BufferedHttpEntity entity = new BufferedHttpEntity(inboundResponse.getEntity());
        inboundResponse.setEntity(entity);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        inboundResponse.getEntity().writeTo(outputStream);
        String body = new String(outputStream.toByteArray());
        if (body.contains("StandbyException")) {
            throw new StandbyException();
        }
        if (body.contains("SafeModeException") || body.contains("RetriableException")) {
            throw new SafeModeException();
        }
    }
    super.writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
}
Also used : BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 29 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project knox by apache.

the class CappedBufferHttpEntityTest method testIsRepeatable.

@Test
public void testIsRepeatable() throws Exception {
    String text = "0123456789";
    BasicHttpEntity basic;
    CappedBufferHttpEntity replay;
    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(text.getBytes(UTF8)));
    replay = new CappedBufferHttpEntity(basic);
    assertThat(replay.isRepeatable(), is(true));
    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(text.getBytes(UTF8)));
    BufferedHttpEntity buffered = new BufferedHttpEntity(basic);
    replay = new CappedBufferHttpEntity(buffered);
    assertThat(replay.isRepeatable(), is(true));
}
Also used : BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) ByteArrayInputStream(java.io.ByteArrayInputStream) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) Test(org.junit.Test)

Example 30 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project connect-sdk-java by Ingenico-ePayments.

the class DefaultConnection method logResponse.

private void logResponse(final HttpResponse response, final String requestId, final long startTime, final CommunicatorLogger logger) {
    final long endTime = System.currentTimeMillis();
    final long duration = endTime - startTime;
    try {
        final int statusCode = response.getStatusLine().getStatusCode();
        final ResponseLogMessageBuilder logMessageBuilder = new ResponseLogMessageBuilder(requestId, statusCode, duration);
        addHeaders(logMessageBuilder, response.getAllHeaders());
        HttpEntity entity = response.getEntity();
        if (entity != null && !entity.isRepeatable()) {
            entity = new BufferedHttpEntity(entity);
            response.setEntity(entity);
        }
        setBody(logMessageBuilder, entity, response.getFirstHeader(HttpHeaders.CONTENT_TYPE));
        logger.log(logMessageBuilder.getMessage());
    } catch (Exception e) {
        logger.log(String.format("An error occurred trying to log response '%s'", requestId), e);
        return;
    }
}
Also used : HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) ResponseLogMessageBuilder(com.ingenico.connect.gateway.sdk.java.logging.ResponseLogMessageBuilder) CommunicationException(com.ingenico.connect.gateway.sdk.java.CommunicationException) HttpException(org.apache.http.HttpException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException)

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