List of usage examples for com.google.common.net HttpHeaders IF_MODIFIED_SINCE
String IF_MODIFIED_SINCE
To view the source code for com.google.common.net HttpHeaders IF_MODIFIED_SINCE.
Click Source Link
From source file:org.haiku.haikudepotserver.pkg.controller.PkgIconController.java
/** * <p>This method will provide a tar-ball of all of the icons. This can be used by the desktop application. It * honours the typical <code>If-Modified-Since</code> header and will return the "Not Modified" (304) response * if the data that is held by the client is still valid and no new data need to be pulled down. Otherwise it * will return the data to the client; possibly via a re-direct.</p> *///from w w w . j a v a2 s.c om @RequestMapping(value = "/" + SEGMENT_PKGICON + "/" + SEGMENT_ALL_TAR_BALL, method = RequestMethod.GET) public void getAllAsTarBall(HttpServletResponse response, @RequestHeader(value = HttpHeaders.IF_MODIFIED_SINCE, required = false) String ifModifiedSinceHeader) throws IOException { JobController.handleRedirectToJobData(response, jobService, ifModifiedSinceHeader, pkgIconService.getLastPkgIconModifyTimestampSecondAccuracy(serverRuntime.newContext()), new PkgIconExportArchiveJobSpecification()); }
From source file:com.sector91.wit.responders.Page.java
@Override public final void respond(Zero params, Request request, Response response) throws IOException { boolean gzipSupported = request.getValue(HttpHeaders.ACCEPT_ENCODING).contains("gzip"); byte[] data = gzipSupported ? compressed : uncompressed; response.setValue(HttpHeaders.ETAG, etag); response.setDate(HttpHeaders.LAST_MODIFIED, timestamp); long ifModifiedSince = request.getDate(HttpHeaders.IF_MODIFIED_SINCE); if (ifModifiedSince >= timestamp || etag.equals(request.getValue(HttpHeaders.IF_NONE_MATCH))) { response.setStatus(Status.NOT_MODIFIED); response.getOutputStream().close(); return;// ww w .j a va 2 s . c o m } try (OutputStream stream = response.getOutputStream()) { response.setContentType(contentType); response.setContentLength(data.length); if (gzipSupported) response.setValue(HttpHeaders.CONTENT_ENCODING, "gzip"); if (!request.getMethod().equals("HEAD")) stream.write(data); } }
From source file:com.eucalyptus.tokens.oidc.OidcDiscoveryCache.java
private OidcDiscoveryCachedResource fetchResource(final String url, final long timeNow, final OidcDiscoveryCachedResource cached) throws IOException { final URL location = new URL(url); final OidcResource oidcResource; { // setup url connection and resolve final HttpURLConnection conn = (HttpURLConnection) location.openConnection(); conn.setAllowUserInteraction(false); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(READ_TIMEOUT); conn.setUseCaches(false);//from www . j a v a2s. c o m if (cached != null) { if (cached.lastModified.isDefined()) { conn.setRequestProperty(HttpHeaders.IF_MODIFIED_SINCE, cached.lastModified.get()); } if (cached.etag.isDefined()) { conn.setRequestProperty(HttpHeaders.IF_NONE_MATCH, cached.etag.get()); } } oidcResource = resolve(conn); } // build cache entry from resource if (oidcResource.statusCode == 304) { return new OidcDiscoveryCachedResource(timeNow, cached); } else { return new OidcDiscoveryCachedResource(timeNow, Option.of(oidcResource.lastModifiedHeader), Option.of(oidcResource.etagHeader), ImmutableList.copyOf(oidcResource.certs), url, new String(oidcResource.content, StandardCharsets.UTF_8)); } }
From source file:org.sonatype.nexus.repository.http.HttpConditions.java
@Nullable private static Predicate<Response> ifModifiedSince(final Request request) { final DateTime date = parseDateHeader(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE)); if (date != null) { return new Predicate<Response>() { @Override/*from w w w .ja v a 2 s .c o m*/ public boolean apply(final Response response) { final DateTime lastModified = parseDateHeader( response.getHeaders().get(HttpHeaders.LAST_MODIFIED)); if (lastModified != null) { return lastModified.isAfter(date); } return true; } @Override public String toString() { return HttpConditions.class.getSimpleName() + ".ifModifiedSince(" + date + ")"; } }; } return null; }
From source file:com.sector91.wit.responders.ResourceResponder.java
@Override public void respond(One<String> param, Request request, Response response) throws IOException, HttpException { Log.debug(TAG, "Starting ResourceResponder for path " + basePath); // Read basic information from the request. final String path = param.first(); Log.trace(TAG, "Responding with resource: " + path); final String mimetype = ContentTypes.forPath(path); final boolean gzipSupported = request.getValue(HttpHeaders.ACCEPT_ENCODING).contains("gzip"); final boolean shouldCompressFile = gzipIf.apply(mimetype); // EDGE CASE: If we're caching a compressed version of the resource, but // the client doesn't support compression, then don't bother caching, and // just read the resource directly. if (!gzipSupported && shouldCompressFile) { Log.debug(TAG, "Resource '" + basePath + path + "' is cached in gzipped form, but client does" + " not support gzip. Skipping cache."); final InputStream stream = context.getResourceAsStream(basePath + path); if (stream == null) throw new HttpException(Status.NOT_FOUND); response.setContentType(mimetype); response.setDate(HttpHeaders.LAST_MODIFIED, timestamp); try (OutputStream out = response.getOutputStream()) { ByteStreams.copy(stream, out); }/* w ww . j a v a2 s . c o m*/ return; } // Retrieve the resource from the cache, loading it if necessary final byte[] data; try { data = loader.load(path); } catch (ResourceNotFoundException ex) { throw new HttpException(Status.NOT_FOUND); } // Return a 304 Not Modified if the client already has a cached copy. response.setDate(HttpHeaders.LAST_MODIFIED, timestamp); final long ifModifiedSince = request.getDate(HttpHeaders.IF_MODIFIED_SINCE); if (ifModifiedSince >= timestamp) { Log.trace(TAG, "Resource not modified: " + path); response.setStatus(Status.NOT_MODIFIED); response.getOutputStream().close(); return; } // Otherwise, write the response headers and data. response.setContentType(mimetype); if (shouldCompressFile) response.setValue(HttpHeaders.CONTENT_ENCODING, "gzip"); response.setContentLength(data.length); try (OutputStream out = response.getOutputStream()) { out.write(data); } }
From source file:com.khannedy.sajikeun.servlet.AssetServlet.java
private boolean isCachedClientSide(HttpServletRequest req, Asset asset) { return asset.getETag().equals(req.getHeader(HttpHeaders.IF_NONE_MATCH)) || (req.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE) >= asset.getLastModified()); }
From source file:com.sector91.wit.responders.CachedResponder.java
@Override public final void respond(P params, Request request, Response response) throws HttpException, IOException { final CachedResponse cachedResponse; try {/*from w ww .ja va 2s.co m*/ localRequest.set(request); localResponse.set(response); cachedResponse = cache.get(params); } catch (ExecutionException ex) { try { throw ex.getCause(); } catch (TooLargeForCacheException ex2) { Log.debug(TAG, ex2.getMessage()); return; } catch (HttpException | IOException | RuntimeException ex2) { throw ex2; } catch (Throwable ex2) { throw new HttpException(Status.INTERNAL_SERVER_ERROR, ex2); } } finally { localRequest.set(null); localResponse.set(null); } if (!response.isCommitted()) { if (useETags) { final List<String> etags = request.getValues(HttpHeaders.IF_NONE_MATCH); if (etags.contains(cachedResponse.etag)) { Log.trace(TAG, "Response not modified for URL '" + request.getPath() + "', with params " + params + "."); response.setStatus(Status.NOT_MODIFIED); response.setValue(HttpHeaders.ETAG, cachedResponse.etag); response.close(); return; } } else { final long ifModifiedSince = request.getDate(HttpHeaders.IF_MODIFIED_SINCE); if (ifModifiedSince >= (cachedResponse.timestamp / 1000) * 1000) { Log.trace(TAG, "Response not modified for URL '" + request.getPath() + "', with params " + params + "."); response.setStatus(Status.NOT_MODIFIED); response.close(); return; } } cachedResponse.writeTo(response); } }
From source file:com.sector91.wit.responders.FileResponder.java
@Override public void respond(One<String> param, Request request, Response response) throws IOException, HttpException { // Read basic information from the request. String pathstr = param.first(); if (pathstr.startsWith("/")) pathstr = pathstr.substring(1);//from ww w . j a va2 s .c o m final Path path = root.resolve(pathstr); Log.debug(TAG, "Responding with file: " + path); final boolean gzipSupported = request.getValue(HttpHeaders.ACCEPT_ENCODING).contains("gzip"); // Get the file from the cache, loading it if necessary. FileEntry entry; while (true) { try { entry = cache.get(path, new FileLoader(path)); } catch (ExecutionException wrapper) { try { throw wrapper.getCause(); } catch (FileTooLargeForCacheException ex) { Log.debug(TAG, "File too large for cache: " + path); entry = ex.file; break; } catch (HttpException ex) { throw ex; } catch (Throwable ex) { throw new HttpException(Status.INTERNAL_SERVER_ERROR, ex); } } // Reload the cached file if it has been modified since it was cached. if (entry.data.length <= maxSize && Files.getLastModifiedTime(path).toMillis() > entry.timestamp) { Log.debug(TAG, "Reloading file " + path + " from cache."); cache.invalidate(path); } else { break; } } // Return a 304 Not Modified if the client already has a cached copy. response.setDate(HttpHeaders.LAST_MODIFIED, entry.timestamp); final long ifModifiedSince = request.getDate(HttpHeaders.IF_MODIFIED_SINCE); if (ifModifiedSince >= (entry.timestamp * 1000) / 1000) { Log.trace(TAG, "File not modified: " + path); response.setStatus(Status.NOT_MODIFIED); response.getOutputStream().close(); return; } // Set the HTTP headers. response.setDate(HttpHeaders.DATE, System.currentTimeMillis()); response.setContentType(entry.mimetype); // EDGE CASE: If we're caching a compressed version of the file, but the // client doesn't support compression, then don't bother caching, and just // read the file directly. if (!gzipSupported && entry.gzipped) { Log.debug(TAG, "File " + path + " is cached in gzipped form, but client does not support" + " gzip. Skipping cache."); checkPathValidity(path); try (final InputStream in = Files.newInputStream(path); final OutputStream out = response.getOutputStream()) { ByteStreams.copy(in, out); return; } } // Otherwise, write the response headers and data. if (entry.gzipped) response.setValue(HttpHeaders.CONTENT_ENCODING, "gzip"); response.setContentLength(entry.data.length); try (OutputStream out = response.getOutputStream()) { out.write(entry.data); } }
From source file:net.staticsnow.nexus.repository.apt.internal.proxy.AptProxyFacet.java
private HttpGet buildFetchRequest(Content oldVersion, URI fetchUri) { HttpGet getRequest = new HttpGet(fetchUri); if (oldVersion != null) { DateTime lastModified = oldVersion.getAttributes().get(Content.CONTENT_LAST_MODIFIED, DateTime.class); if (lastModified != null) { getRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified.toDate())); }//from w w w . ja v a 2s .c o m final String etag = oldVersion.getAttributes().get(Content.CONTENT_ETAG, String.class); if (etag != null) { getRequest.addHeader(HttpHeaders.IF_NONE_MATCH, "\"" + etag + "\""); } } return getRequest; }
From source file:org.sonatype.nexus.repository.proxy.ProxyFacetSupport.java
protected Content fetch(String url, Context context, @Nullable Content stale) throws IOException { HttpClient client = httpClient.getHttpClient(); URI uri = config.remoteUrl.resolve(url); HttpRequestBase request = buildFetchHttpRequest(uri, context); if (stale != null) { final DateTime lastModified = stale.getAttributes().get(Content.CONTENT_LAST_MODIFIED, DateTime.class); if (lastModified != null) { request.addHeader(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified.toDate())); }/* ww w . j a v a2 s.c o m*/ final String etag = stale.getAttributes().get(Content.CONTENT_ETAG, String.class); if (etag != null) { request.addHeader(HttpHeaders.IF_NONE_MATCH, "\"" + etag + "\""); } } log.debug("Fetching: {}", request); HttpResponse response = execute(context, client, request); log.debug("Response: {}", response); StatusLine status = response.getStatusLine(); log.debug("Status: {}", status); final CacheInfo cacheInfo = getCacheController(context).current(); if (status.getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); log.debug("Entity: {}", entity); final Content result = createContent(context, response); result.getAttributes().set(Content.CONTENT_LAST_MODIFIED, extractLastModified(request, response)); result.getAttributes().set(Content.CONTENT_ETAG, extractETag(response)); result.getAttributes().set(CacheInfo.class, cacheInfo); return result; } try { if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { checkState(stale != null, "Received 304 without conditional GET (bad server?) from %s", uri); indicateVerified(context, stale, cacheInfo); } mayThrowProxyServiceException(response); } finally { HttpClientUtils.closeQuietly(response); } return null; }