Example usage for com.google.common.net HttpHeaders ETAG

List of usage examples for com.google.common.net HttpHeaders ETAG

Introduction

In this page you can find the example usage for com.google.common.net HttpHeaders ETAG.

Prototype

String ETAG

To view the source code for com.google.common.net HttpHeaders ETAG.

Click Source Link

Document

The HTTP ETag header field name.

Usage

From source file:com.trc.core2.web.Servlets.java

/**
 * Etag Header.
 */
public static void setEtag(HttpServletResponse response, String etag) {
    response.setHeader(HttpHeaders.ETAG, etag);
}

From source file:com.zkai.xxbs.shiro.Servlets.java

/**
 * Etag Header.
 */
public static void setEtag(HttpServletResponse response, String etag) {

    response.setHeader(HttpHeaders.ETAG, etag);
}

From source file:org.sonatype.nexus.repository.view.handlers.ContentHeadersHandler.java

@Nonnull
@Override/*www  .j  a  v a 2s  .  c o m*/
public Response handle(@Nonnull final Context context) throws Exception {
    final Response response = context.proceed();
    Payload payload = response.getPayload();

    if (response.getStatus().isSuccessful() && payload instanceof Content) {
        final Content content = (Content) payload;
        final DateTime lastModified = content.getAttributes().get(Content.CONTENT_LAST_MODIFIED,
                DateTime.class);
        if (lastModified != null) {
            response.getHeaders().set(HttpHeaders.LAST_MODIFIED, DateUtils.formatDate(lastModified.toDate()));
        }
        final String etag = content.getAttributes().get(Content.CONTENT_ETAG, String.class);
        if (etag != null) {
            response.getHeaders().set(HttpHeaders.ETAG, "\"" + etag + "\"");
        }
    }
    return response;
}

From source file:org.ardverk.dropwizard.assets.AssetsDirectoryServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestURI = request.getRequestURI();

    try {//from   w  ww  .j  a  v a  2 s.c om
        AssetsDirectory.Entry entry = directory.getFileEntry(requestURI);

        if (isCurrent(request, entry)) {
            response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }

        response.setDateHeader(HttpHeaders.LAST_MODIFIED, entry.getLastModified());
        response.setHeader(HttpHeaders.ETAG, entry.getETag());

        MediaType mediaType = DEFAULT_MEDIA_TYPE;

        Buffer mimeType = mimeTypes.getMimeByExtension(requestURI);
        if (mimeType != null) {
            try {
                mediaType = MediaType.parse(mimeType.toString());
                if (charset != null && mediaType.is(MediaType.ANY_TEXT_TYPE)) {
                    mediaType = mediaType.withCharset(charset);
                }
            } catch (IllegalArgumentException ignore) {
            }
        }

        response.setContentType(mediaType.type() + "/" + mediaType.subtype());

        if (mediaType.charset().isPresent()) {
            response.setCharacterEncoding(mediaType.charset().get().toString());
        }

        long contentLength = entry.length();
        if (contentLength >= 0L && contentLength < Integer.MAX_VALUE) {
            response.setContentLength((int) contentLength);
        }

        OutputStream out = response.getOutputStream();
        entry.writeTo(out);
        out.flush();

    } catch (FileNotFoundException err) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.sonatype.nexus.repository.maven.internal.MavenHeadersHandler.java

@Nonnull
@Override/*from  w  w w . j a v a  2 s  . c  om*/
public Response handle(final @Nonnull Context context) throws Exception {
    final Response response = context.proceed();
    if (response.getStatus().isSuccessful() && response instanceof PayloadResponse) {
        final Payload payload = ((PayloadResponse) response).getPayload();
        if (payload instanceof Content) {
            final Content content = (Content) payload;
            final DateTime lastModified = content.getAttributes().get(Content.CONTENT_LAST_MODIFIED,
                    DateTime.class);
            if (lastModified != null) {
                response.getHeaders().set(HttpHeaders.LAST_MODIFIED, Iso8601Date.format(lastModified.toDate()));
            }
            if (response.getStatus().getCode() == HttpStatus.OK) {
                final String etag = content.getAttributes().get(Content.CONTENT_ETAG, String.class);
                if (etag != null) {
                    response.getHeaders().set(HttpHeaders.ETAG, "\"" + etag + "\"");
                }
            }
        }
    }
    return response;
}

From source file:com.googlesource.gerrit.plugins.lfs.fs.LfsFsContentServlet.java

@Override
protected void doHead(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
    String verifyId = req.getHeader(HttpHeaders.IF_NONE_MATCH);
    if (Strings.isNullOrEmpty(verifyId)) {
        doGet(req, rsp);/*from   w  w  w  .  ja v a2 s  . c  om*/
        return;
    }

    Optional<AnyLongObjectId> obj = validateGetRequest(req, rsp);
    if (obj.isPresent() && obj.get().getName().equalsIgnoreCase(verifyId)) {
        rsp.addHeader(HttpHeaders.ETAG, obj.get().getName());
        rsp.setStatus(HttpStatus.SC_NOT_MODIFIED);
        return;
    }

    getObject(req, rsp, obj);
}

From source file:uk.org.iay.mdq.server.ResultRawView.java

@Override
public void render(final Map<String, ?> model, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final Result result = (Result) model.get("result");
    log.debug("rendering as {}", getContentType());

    if (result.isNotFound()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/* ww  w  .j  a v a  2  s.  co  m*/
    }

    // select the representation to provide
    Representation rep = null;
    final String acceptEncoding = request.getHeader(HttpHeaders.ACCEPT_ENCODING);
    if (acceptEncoding != null) {
        if (acceptEncoding.contains("gzip")) {
            rep = result.getGZIPRepresentation();
        } else if (acceptEncoding.contains("compress")) {
            rep = result.getDeflateRepresentation();
        }
    }

    // default to the normal representation
    if (rep == null) {
        rep = result.getRepresentation();
    }

    // Set response headers
    String contentEncoding = rep.getContentEncoding();
    if (contentEncoding != null) {
        response.setHeader(HttpHeaders.CONTENT_ENCODING, contentEncoding);
    } else {
        // for logging only
        contentEncoding = "normal";
    }
    response.setContentType(getContentType());
    response.setContentLength(rep.getBytes().length);
    response.setHeader(HttpHeaders.ETAG, rep.getETag());

    log.debug("selected ({}) representation is {} bytes", contentEncoding, rep.getBytes().length);

    response.getOutputStream().write(rep.getBytes());
}

From source file:com.cnksi.core.web.utils.Servlets.java

/**
 * ?? If-None-Match Header, Etag?./*from ww w .ja va  2 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:org.eclipse.hawkbit.rest.util.RestResourceConversionHelper.java

/**
 * <p>//from w w  w .  j  ava 2 s . c om
 * Write response with target relation and publishes events concerning the
 * download progress based on given update action status.
 * </p>
 *
 * <p>
 * The request supports RFC7233 range requests.
 * </p>
 *
 * @param artifact
 *            the artifact
 * @param response
 *            to be sent back to the requesting client
 * @param request
 *            from the client
 * @param file
 *            to be write to the client response
 * @param controllerManagement
 *            to write progress updates to
 * @param statusId
 *            of the {@link ActionStatus}
 *
 * @return http code
 *
 * @see <a href="https://tools.ietf.org/html/rfc7233">https://tools.ietf.org
 *      /html/rfc7233</a>
 */
public static ResponseEntity<InputStream> writeFileResponse(final Artifact artifact,
        final HttpServletResponse response, final HttpServletRequest request, final DbArtifact file,
        final ControllerManagement controllerManagement, final Long statusId) {

    ResponseEntity<InputStream> result;

    final String etag = artifact.getSha1Hash();
    final Long lastModified = artifact.getLastModifiedAt() != null ? artifact.getLastModifiedAt()
            : artifact.getCreatedAt();
    final long length = file.getSize();

    response.reset();
    response.setBufferSize(BUFFER_SIZE);
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + artifact.getFilename());
    response.setHeader(HttpHeaders.ETAG, etag);
    response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
    response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified);
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

    final ByteRange full = new ByteRange(0, length - 1, length);
    final List<ByteRange> ranges = new ArrayList<>();

    // Validate and process Range and If-Range headers.
    final String range = request.getHeader("Range");
    if (range != null) {
        LOG.debug("range header for filename ({}) is: {}", artifact.getFilename(), range);

        // Range header matches"bytes=n-n,n-n,n-n..."
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + length);
            LOG.debug("range header for filename ({}) is not satisfiable: ", artifact.getFilename());
            return new ResponseEntity<>(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
        }

        // RFC: if the representation is unchanged, send me the part(s) that
        // I am requesting in
        // Range; otherwise, send me the entire representation.
        checkForShortcut(request, etag, lastModified, full, ranges);

        // it seems there are valid ranges
        result = extractRange(response, length, ranges, range);
        // return if range extraction turned out to be invalid
        if (result != null) {
            return result;
        }
    }

    // full request - no range
    if (ranges.isEmpty() || ranges.get(0).equals(full)) {
        LOG.debug("filename ({}) results into a full request: ", artifact.getFilename());
        handleFullFileRequest(artifact, response, file, controllerManagement, statusId, full);
        result = new ResponseEntity<>(HttpStatus.OK);
    }
    // standard range request
    else if (ranges.size() == 1) {
        LOG.debug("filename ({}) results into a standard range request: ", artifact.getFilename());
        handleStandardRangeRequest(artifact, response, file, controllerManagement, statusId, ranges);
        result = new ResponseEntity<>(HttpStatus.PARTIAL_CONTENT);
    }
    // multipart range request
    else {
        LOG.debug("filename ({}) results into a multipart range request: ", artifact.getFilename());
        handleMultipartRangeRequest(artifact, response, file, controllerManagement, statusId, ranges);
        result = new ResponseEntity<>(HttpStatus.PARTIAL_CONTENT);
    }

    return result;
}

From source file:com.trc.core2.web.Servlets.java

/**
 * ?? If-None-Match Header, Etag?.//from   ww w  .  ja  v  a 2  s . co 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;
}