Example usage for org.apache.http.client.methods CloseableHttpResponse addHeader

List of usage examples for org.apache.http.client.methods CloseableHttpResponse addHeader

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse addHeader.

Prototype

void addHeader(String str, String str2);

Source Link

Usage

From source file:bit.changepurse.wdk.http.TestHTTPResponse.java

@Test
public void testGetLocation() {
    CloseableHttpResponse rawResponse = new MockedApacheResponse();
    rawResponse.setStatusCode(HTTPStatusCode.SUCCESS.toInt());
    String location = "http://www.google.com";
    rawResponse.addHeader("Location", location);
    HTTPResponse response = new HTTPResponse(rawResponse);
    assertThat(response.getLocationFromHeaders(), equalTo(location));
    assertThat(response.toString(), notNullValue());
}

From source file:org.esigate.cache.CacheAdapter.java

public ClientExecChain wrapCachingHttpClient(final ClientExecChain wrapped) {
    return new ClientExecChain() {

        /**/*from w  w w  . j  a v a 2 s .  c o m*/
         * Removes client http cache directives like "Cache-control" and "Pragma". Users must not be able to bypass
         * the cache just by making a refresh in the browser. Generates X-cache header.
         * 
         */
        @Override
        public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request,
                HttpClientContext httpClientContext, HttpExecutionAware execAware)
                throws IOException, HttpException {
            OutgoingRequestContext context = OutgoingRequestContext.adapt(httpClientContext);

            // Switch route for the cache to generate the right cache key
            CloseableHttpResponse response = wrapped.execute(route, request, context, execAware);

            // Remove previously added Cache-control header
            if (request.getRequestLine().getMethod().equalsIgnoreCase("GET")
                    && (staleWhileRevalidate > 0 || staleIfError > 0)) {
                response.removeHeader(response.getLastHeader("Cache-control"));
            }
            // Add X-cache header
            if (xCacheHeader) {
                if (context != null) {
                    CacheResponseStatus cacheResponseStatus = (CacheResponseStatus) context
                            .getAttribute(HttpCacheContext.CACHE_RESPONSE_STATUS);
                    String xCacheString;
                    if (cacheResponseStatus.equals(CacheResponseStatus.CACHE_HIT)) {
                        xCacheString = "HIT";
                    } else if (cacheResponseStatus.equals(CacheResponseStatus.VALIDATED)) {
                        xCacheString = "VALIDATED";
                    } else {
                        xCacheString = "MISS";
                    }
                    xCacheString += " from " + route.getTargetHost().toHostString();
                    xCacheString += " (" + request.getRequestLine().getMethod() + " "
                            + request.getRequestLine().getUri() + ")";
                    response.addHeader("X-Cache", xCacheString);
                }
            }

            // Remove Via header
            if (!viaHeader && response.containsHeader("Via")) {
                response.removeHeaders("Via");
            }
            return response;
        }
    };
}

From source file:org.esigate.cache.CacheAdapter.java

public ClientExecChain wrapBackendHttpClient(final ClientExecChain wrapped) {
    return new ClientExecChain() {

        private boolean isCacheableStatus(int statusCode) {
            return (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_NOT_FOUND
                    || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR
                    || statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE
                    || statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_GATEWAY_TIMEOUT);
        }/*  w w  w .j  a  v  a 2 s  .c  om*/

        /**
         * Fire pre-fetch and post-fetch events Enables cache for all GET requests if cache ttl was forced to a
         * certain duration in the configuration. This is done even for non 200 return codes! This is a very
         * aggressive but efficient caching policy. Adds "stale-while-revalidate" and "stale-if-error" cache-control
         * directives depending on the configuration.
         * 
         * @throws HttpException
         * @throws IOException
         */
        @Override
        public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request,
                HttpClientContext httpClientContext, HttpExecutionAware execAware)
                throws IOException, HttpException {
            OutgoingRequestContext context = OutgoingRequestContext.adapt(httpClientContext);

            CloseableHttpResponse response = wrapped.execute(route, request, context, execAware);

            String method = request.getRequestLine().getMethod();
            int statusCode = response.getStatusLine().getStatusCode();

            // If ttl is set, force caching even for error pages
            if (ttl > 0 && method.equalsIgnoreCase("GET") && isCacheableStatus(statusCode)) {
                response.removeHeaders("Date");
                response.removeHeaders("Cache-control");
                response.removeHeaders("Expires");
                response.setHeader("Date", DateUtils.formatDate(new Date(System.currentTimeMillis())));
                response.setHeader("Cache-control", "public, max-age=" + ttl);
                response.setHeader("Expires",
                        DateUtils.formatDate(new Date(System.currentTimeMillis() + ((long) ttl) * 1000)));
            }
            if (request.getRequestLine().getMethod().equalsIgnoreCase("GET")) {
                String cacheControlHeader = "";
                if (staleWhileRevalidate > 0) {
                    cacheControlHeader += "stale-while-revalidate=" + staleWhileRevalidate;
                }
                if (staleIfError > 0) {
                    if (cacheControlHeader.length() > 0) {
                        cacheControlHeader += ",";
                    }
                    cacheControlHeader += "stale-if-error=" + staleIfError;
                }
                if (cacheControlHeader.length() > 0) {
                    response.addHeader("Cache-control", cacheControlHeader);
                }
            }

            return response;
        }

    };
}

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

private CloseableHttpResponse generateCachedResponse(final HttpRequestWrapper request,
        final HttpContext context, final HttpCacheEntry entry, final Date now) {
    final CloseableHttpResponse cachedResponse;
    if (request.containsHeader(HeaderConstants.IF_NONE_MATCH)
            || request.containsHeader(HeaderConstants.IF_MODIFIED_SINCE)) {
        cachedResponse = responseGenerator.generateNotModifiedResponse(entry);
    } else {//from w  ww  .  j  a v  a2  s  .co m
        cachedResponse = responseGenerator.generateResponse(entry);
    }
    setResponseStatus(context, CacheResponseStatus.CACHE_HIT);
    if (validityPolicy.getStalenessSecs(entry, now) > 0L) {
        cachedResponse.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\"");
    }
    return cachedResponse;
}

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

private CloseableHttpResponse unvalidatedCacheHit(final HttpContext context, final HttpCacheEntry entry) {
    final CloseableHttpResponse cachedResponse = responseGenerator.generateResponse(entry);
    setResponseStatus(context, CacheResponseStatus.CACHE_HIT);
    cachedResponse.addHeader(HeaderConstants.WARNING, "111 localhost \"Revalidation failed\"");
    return cachedResponse;
}

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

CloseableHttpResponse callBackend(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {

    final Date requestDate = getCurrentDate();

    log.trace("Calling the backend");
    final CloseableHttpResponse backendResponse = backend.execute(route, request, context, execAware);
    try {/* w w w  .j a va 2s.  co  m*/
        backendResponse.addHeader("Via", generateViaHeader(backendResponse));
        return handleBackendResponse(route, request, context, execAware, requestDate, getCurrentDate(),
                backendResponse);
    } catch (final IOException ex) {
        backendResponse.close();
        throw ex;
    } catch (final RuntimeException ex) {
        backendResponse.close();
        throw ex;
    }
}

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

CloseableHttpResponse negotiateResponseFromVariants(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware,
        final Map<String, Variant> variants) throws IOException, HttpException {
    final HttpRequestWrapper conditionalRequest = conditionalRequestBuilder
            .buildConditionalRequestFromVariants(request, variants);

    final Date requestDate = getCurrentDate();
    final CloseableHttpResponse backendResponse = backend.execute(route, conditionalRequest, context,
            execAware);//from   w  w  w  . ja  v a 2 s .c om
    try {
        final Date responseDate = getCurrentDate();

        backendResponse.addHeader("Via", generateViaHeader(backendResponse));

        if (backendResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_MODIFIED) {
            return handleBackendResponse(route, request, context, execAware, requestDate, responseDate,
                    backendResponse);
        }

        final Header resultEtagHeader = backendResponse.getFirstHeader(HeaderConstants.ETAG);
        if (resultEtagHeader == null) {
            log.warn("304 response did not contain ETag");
            IOUtils.consume(backendResponse.getEntity());
            backendResponse.close();
            return callBackend(route, request, context, execAware);
        }

        final String resultEtag = resultEtagHeader.getValue();
        final Variant matchingVariant = variants.get(resultEtag);
        if (matchingVariant == null) {
            log.debug("304 response did not contain ETag matching one sent in If-None-Match");
            IOUtils.consume(backendResponse.getEntity());
            backendResponse.close();
            return callBackend(route, request, context, execAware);
        }

        final HttpCacheEntry matchedEntry = matchingVariant.getEntry();

        if (revalidationResponseIsTooOld(backendResponse, matchedEntry)) {
            IOUtils.consume(backendResponse.getEntity());
            backendResponse.close();
            return retryRequestUnconditionally(route, request, context, execAware, matchedEntry);
        }

        recordCacheUpdate(context);

        final HttpCacheEntry responseEntry = getUpdatedVariantEntry(context.getTargetHost(), conditionalRequest,
                requestDate, responseDate, backendResponse, matchingVariant, matchedEntry);
        backendResponse.close();

        final CloseableHttpResponse resp = responseGenerator.generateResponse(responseEntry);
        tryToUpdateVariantMap(context.getTargetHost(), request, matchingVariant);

        if (shouldSendNotModifiedResponse(request, responseEntry)) {
            return responseGenerator.generateNotModifiedResponse(responseEntry);
        }
        return resp;
    } catch (final IOException ex) {
        backendResponse.close();
        throw ex;
    } catch (final RuntimeException ex) {
        backendResponse.close();
        throw ex;
    }
}

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

CloseableHttpResponse revalidateCacheEntry(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware, final HttpCacheEntry cacheEntry)
        throws IOException, HttpException {

    final HttpRequestWrapper conditionalRequest = conditionalRequestBuilder.buildConditionalRequest(request,
            cacheEntry);/*from w ww  . ja  va 2s  .c o m*/

    Date requestDate = getCurrentDate();
    CloseableHttpResponse backendResponse = backend.execute(route, conditionalRequest, context, execAware);
    Date responseDate = getCurrentDate();

    if (revalidationResponseIsTooOld(backendResponse, cacheEntry)) {
        backendResponse.close();
        final HttpRequestWrapper unconditional = conditionalRequestBuilder.buildUnconditionalRequest(request,
                cacheEntry);
        requestDate = getCurrentDate();
        backendResponse = backend.execute(route, unconditional, context, execAware);
        responseDate = getCurrentDate();
    }

    backendResponse.addHeader(HeaderConstants.VIA, generateViaHeader(backendResponse));

    final int statusCode = backendResponse.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_OK) {
        recordCacheUpdate(context);
    }

    if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
        final HttpCacheEntry updatedEntry = responseCache.updateCacheEntry(context.getTargetHost(), request,
                cacheEntry, backendResponse, requestDate, responseDate);
        if (suitabilityChecker.isConditional(request)
                && suitabilityChecker.allConditionalsMatch(request, updatedEntry, new Date())) {
            return responseGenerator.generateNotModifiedResponse(updatedEntry);
        }
        return responseGenerator.generateResponse(updatedEntry);
    }

    if (staleIfErrorAppliesTo(statusCode) && !staleResponseNotAllowed(request, cacheEntry, getCurrentDate())
            && validityPolicy.mayReturnStaleIfError(request, cacheEntry, responseDate)) {
        try {
            final CloseableHttpResponse cachedResponse = responseGenerator.generateResponse(cacheEntry);
            cachedResponse.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\"");
            return cachedResponse;
        } finally {
            backendResponse.close();
        }
    }
    return handleBackendResponse(route, conditionalRequest, context, execAware, requestDate, responseDate,
            backendResponse);
}