Example usage for org.apache.http.client.cache CacheResponseStatus CACHE_HIT

List of usage examples for org.apache.http.client.cache CacheResponseStatus CACHE_HIT

Introduction

In this page you can find the example usage for org.apache.http.client.cache CacheResponseStatus CACHE_HIT.

Prototype

CacheResponseStatus CACHE_HIT

To view the source code for org.apache.http.client.cache CacheResponseStatus CACHE_HIT.

Click Source Link

Document

A response was generated from the cache with no requests sent upstream.

Usage

From source file:fr.ippon.wip.http.hc.TransformerResponseInterceptor.java

/**
 * If httpResponse must be transformed, creates an instance of
 * WIPTransformer, executes WIPTransformer#transform on the response content
 * and updates the response entity accordingly.
 * //from   w w w .  jav  a2 s . c  o  m
 * @param httpResponse
 * @param context
 * @throws HttpException
 * @throws IOException
 */
public void process(HttpResponse httpResponse, HttpContext context) throws HttpException, IOException {
    PortletRequest portletRequest = HttpClientResourceManager.getInstance().getCurrentPortletRequest();
    PortletResponse portletResponse = HttpClientResourceManager.getInstance().getCurrentPortletResponse();
    WIPConfiguration config = WIPUtil.getConfiguration(portletRequest);
    RequestBuilder request = HttpClientResourceManager.getInstance().getCurrentRequest();

    if (httpResponse == null) {
        // No response -> no transformation
        LOG.warning("No response to transform.");
        return;
    }

    HttpEntity entity = httpResponse.getEntity();
    if (entity == null) {
        // No entity -> no transformation
        return;
    }

    ContentType contentType = ContentType.getOrDefault(entity);
    String mimeType = contentType.getMimeType();

    String actualURL;
    RedirectLocations redirectLocations = (RedirectLocations) context
            .getAttribute("http.protocol.redirect-locations");
    if (redirectLocations != null)
        actualURL = Iterables.getLast(redirectLocations.getAll()).toString();
    else if (context.getAttribute(CachingHttpClient.CACHE_RESPONSE_STATUS) == CacheResponseStatus.CACHE_HIT) {
        actualURL = request.getRequestedURL();
    } else {
        HttpRequest actualRequest = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        HttpHost actualHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        actualURL = actualHost.toURI() + actualRequest.getRequestLine().getUri();
    }

    // Check if actual URI must be transformed
    if (!config.isProxyURI(actualURL))
        return;

    // a builder for creating a WIPTransformer instance
    TransformerBuilder transformerBuilder = new TransformerBuilder().setActualURL(actualURL)
            .setMimeType(mimeType).setPortletRequest(portletRequest).setPortletResponse(portletResponse)
            .setResourceType(request.getResourceType()).setXmlReaderPool(xmlReaderPool);

    // Creates an instance of Transformer depending on ResourceType and
    // MimeType
    int status = transformerBuilder.build();
    if (status == TransformerBuilder.STATUS_NO_TRANSFORMATION)
        return;

    WIPTransformer transformer = transformerBuilder.getTransformer();
    // Call WIPTransformer#transform method and update the response Entity
    // object
    try {
        String content = EntityUtils.toString(entity);
        String transformedContent = ((AbstractTransformer) transformer).transform(content);

        StringEntity transformedEntity;
        if (contentType.getCharset() != null) {
            transformedEntity = new StringEntity(transformedContent, contentType);
        } else {
            transformedEntity = new StringEntity(transformedContent);
        }
        transformedEntity.setContentType(contentType.toString());
        httpResponse.setEntity(transformedEntity);

    } catch (SAXException e) {
        LOG.log(Level.SEVERE, "Could not transform HTML", e);
        throw new IllegalArgumentException(e);
    } catch (TransformerException e) {
        LOG.log(Level.SEVERE, "Could not transform HTML", e);
        throw new IllegalArgumentException(e);
    }
}

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

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

        /**// www  .j a  v  a2s  .  com
         * 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:fr.ippon.wip.http.hc.HttpClientExecutor.java

private String getActualUrl(PortletRequest portletRequest, HttpContext context, RequestBuilder request,
        HttpResponse response) {// w w w  .  ja  va2 s.  c  o  m
    boolean cacheUsed = (context
            .getAttribute(CachingHttpClient.CACHE_RESPONSE_STATUS) == CacheResponseStatus.CACHE_HIT);
    boolean notFoundResponse = (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND);

    /*
     * ExecutionContext.HTTP_REQUEST and ExecutionContext.HTTP_TARGET_HOST are not set when the cache is used
     * or when the resource is ignored by WIP
     */
    if (cacheUsed || notFoundResponse)
        return request.getRequestedURL();

    // Get final URL (ie. perhaps redirected)
    HttpUriRequest actualRequest = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
    HttpHost actualHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    return (actualRequest.getURI().isAbsolute()) ? actualRequest.getURI().toString()
            : (actualHost.toURI() + actualRequest.getURI());
}

From source file:it.tidalwave.bluemarine2.downloader.impl.DefaultDownloader.java

/*******************************************************************************************************************
 *
 *
 *
 ******************************************************************************************************************/
/* VisibleForTesting */ void onDownloadRequest(final @ListensTo @Nonnull DownloadRequest request)
        throws URISyntaxException {
    try {/*from   w w  w  .j a  va2  s  .co m*/
        log.info("onDownloadRequest({})", request);

        URL url = request.getUrl();

        for (;;) {
            final HttpCacheContext context = HttpCacheContext.create();
            @Cleanup
            final CloseableHttpResponse response = httpClient.execute(new HttpGet(url.toURI()), context);
            final byte[] bytes = bytesFrom(response);
            final CacheResponseStatus cacheResponseStatus = context.getCacheResponseStatus();
            log.debug(">>>> cacheResponseStatus: {}", cacheResponseStatus);

            final Origin origin = cacheResponseStatus.equals(CacheResponseStatus.CACHE_HIT) ? Origin.CACHE
                    : Origin.NETWORK;

            // FIXME: shouldn't do this by myself
            // FIXME: upon configuration, everything should be cached (needed for supporting integration tests)
            if (!origin.equals(Origin.CACHE)
                    && Arrays.asList(200, 303).contains(response.getStatusLine().getStatusCode())) {
                final Date date = new Date();
                final Resource resource = new HeapResource(bytes);
                cacheStorage.putEntry(url.toExternalForm(), new HttpCacheEntry(date, date,
                        response.getStatusLine(), response.getAllHeaders(), resource));
            }

            // FIXME: if the redirect were enabled, we could drop this check
            if (request.isOptionPresent(DownloadRequest.Option.FOLLOW_REDIRECT)
                    && response.getStatusLine().getStatusCode() == 303) // SEE_OTHER FIXME
            {
                url = new URL(response.getFirstHeader("Location").getValue());
                log.info(">>>> following 'see also' to {} ...", url);
            } else {
                messageBus.publish(new DownloadComplete(request.getUrl(),
                        response.getStatusLine().getStatusCode(), bytes, origin));
                return;
            }
        }
    } catch (IOException e) {
        log.error("{}: {}", request.getUrl(), e.toString());
        messageBus.publish(new DownloadComplete(request.getUrl(), -1, new byte[0], Origin.NETWORK));
    }
}

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 {/* w  ww .  j  a v a  2s.  c om*/
        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.CachingHttpAsyncClient.java

private HttpResponse generateCachedResponse(final HttpRequestWrapper request,
        final HttpCacheContext clientContext, final HttpCacheEntry entry, final Date now) {
    final HttpResponse cachedResponse;
    if (request.containsHeader(HeaderConstants.IF_NONE_MATCH)
            || request.containsHeader(HeaderConstants.IF_MODIFIED_SINCE)) {
        cachedResponse = this.responseGenerator.generateNotModifiedResponse(entry);
    } else {/*  w w w .j a va  2 s.  c om*/
        cachedResponse = this.responseGenerator.generateResponse(request, entry);
    }
    setResponseStatus(clientContext, CacheResponseStatus.CACHE_HIT);
    if (this.validityPolicy.getStalenessSecs(entry, now) > 0L) {
        cachedResponse.addHeader("Warning", "110 localhost \"Response is stale\"");
    }
    return cachedResponse;
}

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

private HttpResponse unvalidatedCacheHit(final HttpCacheContext clientContext, final HttpRequestWrapper request,
        final HttpCacheEntry entry) {
    final HttpResponse cachedResponse = this.responseGenerator.generateResponse(request, entry);
    setResponseStatus(clientContext, CacheResponseStatus.CACHE_HIT);
    cachedResponse.addHeader(HeaderConstants.WARNING, "111 localhost \"Revalidation failed\"");
    return cachedResponse;
}

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

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

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

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