List of usage examples for com.google.common.net HttpHeaders ETAG
String ETAG
To view the source code for com.google.common.net HttpHeaders ETAG.
Click Source Link
From source file:com.khannedy.sajikeun.servlet.AssetServlet.java
protected void doHttp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/* w w w . j a v a 2s . c o m*/ final StringBuilder builder = new StringBuilder(req.getServletPath()); if (req.getPathInfo() != null) { builder.append(req.getPathInfo()); } final Asset asset = loadAsset(builder.toString()); if (asset == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (cache) { if (isCachedClientSide(req, asset)) { resp.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } } resp.setDateHeader(HttpHeaders.LAST_MODIFIED, asset.getLastModified()); resp.setHeader(HttpHeaders.ETAG, asset.getETag()); final String mimeTypeOfExtension = req.getServletContext().getMimeType(req.getRequestURI()); MediaType mediaType = DEFAULT_MEDIA_TYPE; if (mimeTypeOfExtension != null) { try { mediaType = MediaType.parse(mimeTypeOfExtension); if (defaultCharset != null && mediaType.is(MediaType.ANY_TEXT_TYPE)) { mediaType = mediaType.withCharset(defaultCharset); } } catch (IllegalArgumentException ignore) { } } resp.setContentType(mediaType.type() + '/' + mediaType.subtype()); if (mediaType.charset().isPresent()) { resp.setCharacterEncoding(mediaType.charset().get().toString()); } try (ServletOutputStream output = resp.getOutputStream()) { output.write(asset.getResource()); } } catch (RuntimeException | URISyntaxException ignored) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtDownloadResource.java
/** * Handles the GET request for downloading an artifact. * /*ww w. j av a 2s .co m*/ * @param downloadId * the generated download id * @return {@link ResponseEntity} with status {@link HttpStatus#OK} if * successful */ @Override @ResponseBody public ResponseEntity<Void> downloadArtifactByDownloadId(@PathVariable("downloadId") final String downloadId) { try { final DownloadArtifactCache artifactCache = downloadIdCache.get(downloadId); if (artifactCache == null) { LOGGER.warn("Download Id {} could not be found", downloadId); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } DbArtifact artifact = null; if (DownloadType.BY_SHA1.equals(artifactCache.getDownloadType())) { artifact = artifactRepository.getArtifactBySha1(artifactCache.getId()); } else { LOGGER.warn("Download Type {} not supported", artifactCache.getDownloadType()); } if (artifact == null) { LOGGER.warn("Artifact with cached id {} and download type {} could not be found.", artifactCache.getId(), artifactCache.getDownloadType()); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } final HttpServletResponse response = requestResponseContextHolder.getHttpServletResponse(); final String etag = artifact.getHashes().getSha1(); final long length = artifact.getSize(); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + downloadId); response.setHeader(HttpHeaders.ETAG, etag); response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); response.setContentLengthLong(length); try (InputStream inputstream = artifact.getFileInputStream()) { ByteStreams.copy(inputstream, requestResponseContextHolder.getHttpServletResponse().getOutputStream()); } catch (final IOException e) { LOGGER.error("Cannot copy streams", e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } finally { downloadIdCache.evict(downloadId); } return ResponseEntity.ok().build(); }
From source file:com.emaxcore.emaxdata.common.web.Servlets.java
/** * ?? If-None-Match Header, Etag?./*from www.j a va2 s. c o m*/ * * Etag, checkIfNoneMatchfalse, 304 not modify status. * * @param etag ETag. */ public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) { String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH); if (headerValue != null) { boolean conditionSatisfied = false; if (!"*".equals(headerValue)) { StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ","); while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) { String currentToken = commaTokenizer.nextToken(); if (currentToken.trim().equals(etag)) { conditionSatisfied = true; } } } else { conditionSatisfied = true; } if (conditionSatisfied) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader(HttpHeaders.ETAG, etag); return false; } } return true; }
From source file:com.sector91.wit.http.ETag.java
public boolean check(Request request, Response response) throws IOException { if (matches(request)) { response.setStatus(Status.NOT_MODIFIED); response.setValue(HttpHeaders.ETAG, str); response.close();//from www . jav a 2s. co m return true; } return false; }
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;// w ww.j a va2s. 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:org.sonatype.nexus.repository.view.handlers.ConditionalRequestHandler.java
@Nonnull private Response handleConditional(@Nonnull final Context context, @Nonnull final Predicate<Response> requestPredicate) throws Exception { final String action = context.getRequest().getAction(); log.debug("Conditional request: {} {}: {}", action, context.getRequest().getPath(), requestPredicate); switch (action) { case GET://from w w w .java2 s . co m case HEAD: { final Response response = context.proceed(); if (response.getStatus().isSuccessful() && !requestPredicate.apply(response)) { // copy only ETag header, leave out all other entity headers final Response.Builder responseBuilder = new Response.Builder() .status(Status.success(NOT_MODIFIED)); if (response.getHeaders().contains(HttpHeaders.ETAG)) { responseBuilder.header(HttpHeaders.ETAG, response.getHeaders().get(HttpHeaders.ETAG)); } return responseBuilder.build(); } else { return response; } } case POST: case PUT: case DELETE: { final Request getRequest = new Request.Builder().copy(context.getRequest()).action(GET).build(); final Response response = context.getRepository().facet(ViewFacet.class).dispatch(getRequest); if (response.getStatus().isSuccessful() && !requestPredicate.apply(response)) { // keep all response headers like Last-Modified and ETag, etc return new Response.Builder().copy(response).status(Status.failure(PRECONDITION_FAILED)) .payload(null).build(); } else { return context.proceed(); } } default: return context.proceed(); } }
From source file:org.wso2.carbon.mediator.cache.util.HttpCachingFilter.java
/** * This method returns the ETag value./*w ww . j av a2 s .co m*/ * * @param httpHeaders Http headers. * @return ETag value. */ private static String getETagValue(Map<String, Object> httpHeaders) { if (httpHeaders.get(HttpHeaders.ETAG) != null) { return String.valueOf(httpHeaders.get(HttpHeaders.ETAG)); } return null; }
From source file:io.soabase.admin.details.IndexServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestURI = ((request.getRequestURI() != null) && (request.getRequestURI().length() > 0)) ? request.getRequestURI()//from ww w .ja va 2 s . c om : "/"; if (requestURI.startsWith(FORCE)) { rebuild(); requestURI = (requestURI.length() > FORCE.length()) ? requestURI.substring(FORCE.length()) : "/"; } else { int componentManagerVersion = componentManager.getVersion(); int localBuiltFromVersion = builtFromVersion.get(); if (localBuiltFromVersion != componentManagerVersion) { if (builtFromVersion.compareAndSet(localBuiltFromVersion, componentManagerVersion)) { rebuild(); } } } Entry entry = files.get().get(requestURI); if (entry == null) { response.setStatus(404); return; } response.setStatus(200); response.setContentType("text/html"); response.setContentLength(entry.content.length()); response.setCharacterEncoding("UTF-8"); response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified.get()); response.setHeader(HttpHeaders.ETAG, entry.eTag); response.getWriter().print(entry.content); }
From source file:io.airlift.discovery.client.HttpDiscoveryLookupClient.java
private ListenableFuture<ServiceDescriptors> lookup(final String type, final String pool, final ServiceDescriptors serviceDescriptors) { Preconditions.checkNotNull(type, "type is null"); URI uri = discoveryServiceURI.get(); if (uri == null) { return Futures .immediateFailedCheckedFuture(new DiscoveryException("No discovery servers are available")); }//from www . j av a 2 s.com uri = URI.create(uri + "/v1/service/" + type + "/"); if (pool != null) { uri = uri.resolve(pool); } Builder requestBuilder = prepareGet().setUri(uri).setHeader("User-Agent", nodeInfo.getNodeId()); if (serviceDescriptors != null && serviceDescriptors.getETag() != null) { requestBuilder.setHeader(HttpHeaders.ETAG, serviceDescriptors.getETag()); } return httpClient.executeAsync(requestBuilder.build(), new DiscoveryResponseHandler<ServiceDescriptors>(format("Lookup of %s", type), uri) { @Override public ServiceDescriptors handle(Request request, Response response) { Duration maxAge = extractMaxAge(response); String eTag = response.getHeader(HttpHeaders.ETAG); if (NOT_MODIFIED.code() == response.getStatusCode() && serviceDescriptors != null) { return new ServiceDescriptors(serviceDescriptors, maxAge, eTag); } if (OK.code() != response.getStatusCode()) { throw new DiscoveryException(format("Lookup of %s failed with status code %s", type, response.getStatusCode())); } byte[] json; try { json = ByteStreams.toByteArray(response.getInputStream()); } catch (IOException e) { throw new DiscoveryException(format("Lookup of %s failed", type), e); } ServiceDescriptorsRepresentation serviceDescriptorsRepresentation = serviceDescriptorsCodec .fromJson(json); if (!environment.equals(serviceDescriptorsRepresentation.getEnvironment())) { throw new DiscoveryException(format("Expected environment to be %s, but was %s", environment, serviceDescriptorsRepresentation.getEnvironment())); } return new ServiceDescriptors(type, pool, serviceDescriptorsRepresentation.getServiceDescriptors(), maxAge, eTag); } }); }
From source file:controllers.ExpressionController.java
/** * Query for expressions./*from w w w. j av a 2 s . c o m*/ * * * @param contains The text to search for. Optional. * @param cluster The cluster of the statistic to evaluate as part of the exression. Optional. * @param service The service of the statistic to evaluate as part of the expression. Optional. * @param limit The maximum number of results to return. Optional. * @param offset The number of results to skip. Optional. * @return <code>Result</code> paginated matching expressions. */ // CHECKSTYLE.OFF: ParameterNameCheck - Names must match query parameters. public Result query(final String contains, final String cluster, final String service, final Integer limit, final Integer offset) { // CHECKSTYLE.ON: ParameterNameCheck // Convert and validate parameters final Optional<String> argContains = Optional.ofNullable(contains); final Optional<String> argCluster = Optional.ofNullable(cluster); final Optional<String> argService = Optional.ofNullable(service); final Optional<Integer> argOffset = Optional.ofNullable(offset); final int argLimit = Math.min(_maxLimit, Optional.of(MoreObjects.firstNonNull(limit, _maxLimit)).get()); if (argLimit < 0) { return badRequest("Invalid limit; must be greater than or equal to 0"); } if (argOffset.isPresent() && argOffset.get() < 0) { return badRequest("Invalid offset; must be greater than or equal to 0"); } // Build conditions map final Map<String, String> conditions = Maps.newHashMap(); if (argContains.isPresent()) { conditions.put("contains", argContains.get()); } if (argCluster.isPresent()) { conditions.put("cluster", argCluster.get()); } if (argService.isPresent()) { conditions.put("service", argService.get()); } // Build a host repository query final ExpressionQuery query = _expressionRepository.createQuery().contains(argContains).service(argService) .cluster(argCluster).limit(argLimit).offset(argOffset); // Execute the query final QueryResult<Expression> result; try { result = query.execute(); // CHECKSTYLE.OFF: IllegalCatch - Convert any exception to 500 } catch (final Exception e) { // CHECKSTYLE.ON: IllegalCatch LOGGER.error().setMessage("Expression query failed").setThrowable(e).log(); return internalServerError(); } // Wrap the query results and return as JSON if (result.etag().isPresent()) { response().setHeader(HttpHeaders.ETAG, result.etag().get()); } return ok(Json.toJson(new PagedContainer<>( result.values().stream().map(this::internalModelToViewModel).collect(Collectors.toList()), new Pagination(request().path(), result.total(), result.values().size(), argLimit, argOffset, conditions)))); }