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

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

Introduction

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

Prototype

String LAST_MODIFIED

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

Click Source Link

Document

The HTTP Last-Modified header field name.

Usage

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

/**
 * LastModified Header./*from   w ww.  j  av  a  2 s. c om*/
 */
public static void setLastModifiedHeader(HttpServletResponse response, long lastModifiedDate) {

    response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModifiedDate);
}

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

/**
 * LastModified Header./* ww w. java 2 s. c  om*/
 */
public static void setLastModifiedHeader(HttpServletResponse response, long lastModifiedDate) {
    response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModifiedDate);
}

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

@Nonnull
@Override/*from w w  w  .  j  a  v a 2 s.co 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.sonatype.nexus.repository.maven.internal.MavenHeadersHandler.java

@Nonnull
@Override//w  w  w .ja v  a2s  . com
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:org.ardverk.dropwizard.assets.AssetsDirectoryServlet.java

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

    try {//from w w  w.j  av a  2  s.co  m
        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.eclipse.hawkbit.rest.util.RestResourceConversionHelper.java

/**
 * <p>//from  w  w w .j  av  a2s .  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.khannedy.sajikeun.servlet.AssetServlet.java

protected void doHttp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {// www .  ja  va2  s. 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: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;/*from   w w  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:org.haiku.haikudepotserver.pkg.controller.PkgScreenshotController.java

private void handleHeadOrGet(RequestMethod requestMethod, HttpServletResponse response, Integer targetWidth,
        Integer targetHeight, String format, String screenshotCode) throws IOException {

    if (targetWidth <= 0 || targetWidth > SCREENSHOT_SIDE_LIMIT) {
        throw new BadSize();
    }/*from  w  w w.  j a va2 s  .co m*/

    if (targetHeight <= 0 || targetHeight > SCREENSHOT_SIDE_LIMIT) {
        throw new BadSize();
    }

    if (Strings.isNullOrEmpty(screenshotCode)) {
        throw new MissingScreenshotCode();
    }

    if (Strings.isNullOrEmpty(format) || !"png".equals(format)) {
        throw new MissingOrBadFormat();
    }

    ObjectContext context = serverRuntime.newContext();
    PkgScreenshot screenshot = PkgScreenshot.tryGetByCode(context, screenshotCode)
            .orElseThrow(ScreenshotNotFound::new);

    response.setContentType(MediaType.PNG.toString());
    response.setHeader(HttpHeaders.CACHE_CONTROL, "max-age=3600");

    response.setDateHeader(HttpHeaders.LAST_MODIFIED,
            screenshot.getPkg().getModifyTimestampSecondAccuracy().getTime());

    switch (requestMethod) {
    case HEAD:
        ByteCounterOutputStream byteCounter = new ByteCounterOutputStream(ByteStreams.nullOutputStream());
        pkgScreenshotService.writePkgScreenshotImage(byteCounter, context, screenshot, targetWidth,
                targetHeight);
        response.setHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(byteCounter.getCounter()));

        break;

    case GET:
        pkgScreenshotService.writePkgScreenshotImage(response.getOutputStream(), context, screenshot,
                targetWidth, targetHeight);
        break;

    default:
        throw new IllegalStateException("unhandled request method; " + requestMethod);
    }

}

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  ww w . java2s  . com*/
            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;
}