Example usage for org.apache.http.impl.client RequestWrapper RequestWrapper

List of usage examples for org.apache.http.impl.client RequestWrapper RequestWrapper

Introduction

In this page you can find the example usage for org.apache.http.impl.client RequestWrapper RequestWrapper.

Prototype

public RequestWrapper(final HttpRequest request) throws ProtocolException 

Source Link

Usage

From source file:com.clarionmedia.infinitum.http.rest.impl.CachingEnabledRestfulClient.java

@Override
public RestResponse executePut(String uri, String messageBody, String contentType,
        Map<String, String> headers) {
    HttpPut httpPut = new HttpPut(uri);
    for (Entry<String, String> header : headers.entrySet()) {
        httpPut.addHeader(header.getKey(), header.getValue());
    }//  w w w .  ja  v  a 2s  .  c o  m
    httpPut.addHeader("content-type", contentType);
    try {
        httpPut.setEntity(new StringEntity(messageBody, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        mLogger.error("Unable to send PUT request (could not encode message body)", e);
        return null;
    }
    try {
        RequestWrapper request = new RequestWrapper(httpPut);
        return executeRequest(new HashableHttpRequest(request));
    } catch (ProtocolException e) {
        throw new InfinitumRuntimeException("Unable to execute request", e);
    }
}

From source file:com.clarionmedia.infinitum.http.rest.impl.CachingEnabledRestfulClient.java

@Override
public RestResponse executePut(String uri, HttpEntity httpEntity) {
    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader("content-type", httpEntity.getContentType().getValue());
    httpPut.setEntity(httpEntity);//from ww w  .j  ava2 s.c  o m
    try {
        RequestWrapper request = new RequestWrapper(httpPut);
        return executeRequest(new HashableHttpRequest(request));
    } catch (ProtocolException e) {
        throw new InfinitumRuntimeException("Unable to execute request", e);
    }
}

From source file:com.clarionmedia.infinitum.http.rest.impl.CachingEnabledRestfulClient.java

@Override
public RestResponse executePut(String uri, HttpEntity httpEntity, Map<String, String> headers) {
    HttpPut httpPut = new HttpPut(uri);
    for (Entry<String, String> header : headers.entrySet()) {
        httpPut.addHeader(header.getKey(), header.getValue());
    }// www  .ja va 2s  .  com
    httpPut.setEntity(httpEntity);
    try {
        RequestWrapper request = new RequestWrapper(httpPut);
        return executeRequest(new HashableHttpRequest(request));
    } catch (ProtocolException e) {
        throw new InfinitumRuntimeException("Unable to execute request", e);
    }
}

From source file:com.clarionmedia.infinitum.http.rest.impl.CachingEnabledRestfulClient.java

@Override
public RestResponse executePut(String uri, InputStream messageBody, int messageBodyLength, String contentType) {
    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader("content-type", contentType);
    httpPut.setEntity(new InputStreamEntity(messageBody, messageBodyLength));
    try {/* w w  w . j a  va 2s  .c  o  m*/
        RequestWrapper request = new RequestWrapper(httpPut);
        return executeRequest(new HashableHttpRequest(request));
    } catch (ProtocolException e) {
        throw new InfinitumRuntimeException("Unable to execute request", e);
    }
}

From source file:org.robolectric.shadows.httpclient.DefaultRequestDirector.java

private RequestWrapper wrapRequest(final HttpRequest request) throws ProtocolException {
    if (request instanceof HttpEntityEnclosingRequest) {
        return new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request);
    } else {// www  . ja  v  a  2s .  c  o m
        return new RequestWrapper(request);
    }
}

From source file:com.clarionmedia.infinitum.http.rest.impl.CachingEnabledRestfulClient.java

@Override
public RestResponse executePut(String uri, InputStream messageBody, int messageBodyLength, String contentType,
        Map<String, String> headers) {
    HttpPut httpPut = new HttpPut(uri);
    for (Entry<String, String> header : headers.entrySet()) {
        httpPut.addHeader(header.getKey(), header.getValue());
    }//  w w w.j a  va  2 s . c  o  m
    httpPut.addHeader("content-type", contentType);
    httpPut.setEntity(new InputStreamEntity(messageBody, messageBodyLength));
    try {
        RequestWrapper request = new RequestWrapper(httpPut);
        return executeRequest(new HashableHttpRequest(request));
    } catch (ProtocolException e) {
        throw new InfinitumRuntimeException("Unable to execute request", e);
    }
}

From source file:com.clarionmedia.infinitum.http.rest.impl.CachingEnabledRestfulClient.java

@Override
public RestResponse executeRequest(HttpUriRequest request) {
    try {/*from   ww  w . j  a va 2 s.  c om*/
        RequestWrapper wrapped = new RequestWrapper(request);
        return executeRequest(new HashableHttpRequest(wrapped));
    } catch (ProtocolException e) {
        throw new InfinitumRuntimeException("Unable to execute request", e);
    }
}

From source file:org.robolectric.shadows.httpclient.DefaultRequestDirector.java

/**
 * Analyzes a response to check need for a followup.
 *
 * @param roureq    the request and route.
 * @param response  the response to analayze
 * @param context   the context used for the current request execution
 *
 * @return  the followup request and route if there is a followup, or
 *          <code>null</code> if the response should be returned as is
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 *//*  w  ww .ja v  a2 s .c o  m*/
protected RoutedRequest handleResponse(RoutedRequest roureq, HttpResponse response, HttpContext context)
        throws HttpException, IOException {

    HttpRoute route = roureq.getRoute();
    RequestWrapper request = roureq.getRequest();

    HttpParams params = request.getParams();
    if (HttpClientParams.isRedirecting(params) && this.redirectHandler.isRedirectRequested(response, context)) {

        if (redirectCount >= maxRedirects) {
            throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
        }
        redirectCount++;

        // Virtual host cannot be used any longer
        virtualHost = null;

        URI uri = this.redirectHandler.getLocationURI(response, context);

        HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

        // Unset auth scope
        targetAuthState.setAuthScope(null);
        proxyAuthState.setAuthScope(null);

        // Invalidate auth states if redirecting to another host
        if (!route.getTargetHost().equals(newTarget)) {
            targetAuthState.invalidate();
            AuthScheme authScheme = proxyAuthState.getAuthScheme();
            if (authScheme != null && authScheme.isConnectionBased()) {
                proxyAuthState.invalidate();
            }
        }

        HttpRedirect redirect = new HttpRedirect(request.getMethod(), uri);
        HttpRequest orig = request.getOriginal();
        redirect.setHeaders(orig.getAllHeaders());

        RequestWrapper wrapper = new RequestWrapper(redirect);
        wrapper.setParams(params);

        HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
        RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);

        if (this.log.isDebugEnabled()) {
            this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
        }

        return newRequest;
    }

    CredentialsProvider credsProvider = (CredentialsProvider) context
            .getAttribute(ClientContext.CREDS_PROVIDER);

    if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {

        if (this.targetAuthHandler.isAuthenticationRequested(response, context)) {

            HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (target == null) {
                target = route.getTargetHost();
            }

            this.log.debug("Target requested authentication");
            Map<String, Header> challenges = this.targetAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.targetAuthState, this.targetAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.targetAuthState, target, credsProvider);

            if (this.targetAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset target auth scope
            this.targetAuthState.setAuthScope(null);
        }

        if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {

            HttpHost proxy = route.getProxyHost();

            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());
                    return null;
                }
            }
            updateAuthState(this.proxyAuthState, proxy, credsProvider);

            if (this.proxyAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset proxy auth scope
            this.proxyAuthState.setAuthScope(null);
        }
    }
    return null;
}

From source file:org.apache.http.impl.client.cache.ConditionalRequestBuilder.java

/**
 * When a {@link HttpCacheEntry} does not exist for a specific {@link HttpRequest}
 * we attempt to see if an existing {@link HttpCacheEntry} is appropriate by building
 * a conditional {@link HttpRequest} using the variants' ETag values.  If no such values
 * exist, the request is unmodified/*from w  w w . j a v a 2  s . co  m*/
 *
 * @param request the original request from the caller
 * @param variants
 * @return the wrapped request
 */
public HttpRequest buildConditionalRequestFromVariants(HttpRequest request, Map<String, Variant> variants) {
    RequestWrapper wrapperRequest;
    try {
        wrapperRequest = new RequestWrapper(request);
    } catch (ProtocolException pe) {
        log.warn("unable to build conditional request", pe);
        return request;
    }
    wrapperRequest.resetHeaders();

    // we do not support partial content so all etags are used
    StringBuilder etags = new StringBuilder();
    boolean first = true;
    for (String etag : variants.keySet()) {
        if (!first) {
            etags.append(",");
        }
        first = false;
        etags.append(etag);
    }

    wrapperRequest.setHeader(HeaderConstants.IF_NONE_MATCH, etags.toString());
    return wrapperRequest;
}

From source file:org.apache.http.impl.client.cache.ConditionalRequestBuilder.java

/**
 * Returns a request to unconditionally validate a cache entry with
 * the origin. In certain cases (due to multiple intervening caches)
 * our cache may actually receive a response to a normal conditional
 * validation where the Date header is actually older than that of
 * our current cache entry. In this case, the protocol recommendation
 * is to retry the validation and force syncup with the origin.
 * @param request client request we are trying to satisfy
 * @param entry existing cache entry we are trying to validate
 * @return an unconditional validation request
 *///from ww w . j a  va 2s .c  om
public HttpRequest buildUnconditionalRequest(HttpRequest request, HttpCacheEntry entry) {
    RequestWrapper wrapped;
    try {
        wrapped = new RequestWrapper(request);
    } catch (ProtocolException e) {
        log.warn("unable to build proper unconditional request", e);
        return request;
    }
    wrapped.resetHeaders();
    wrapped.addHeader("Cache-Control", "no-cache");
    wrapped.addHeader("Pragma", "no-cache");
    wrapped.removeHeaders("If-Range");
    wrapped.removeHeaders("If-Match");
    wrapped.removeHeaders("If-None-Match");
    wrapped.removeHeaders("If-Unmodified-Since");
    wrapped.removeHeaders("If-Modified-Since");
    return wrapped;
}