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:org.haiku.haikudepotserver.pkg.controller.PkgIconController.java

/**
 * @param isAsFallback is true if the request was originally for a package, but fell back to this generic.
 *///  w w w  . j  a  va 2 s.  c  o  m

private void handleGenericHeadOrGet(RequestMethod requestMethod, HttpServletResponse response, Integer size,
        boolean isAsFallback) throws IOException {

    if (null == size) {
        size = 64; // largest natural size
    }

    size = normalizeSize(size);
    byte[] data = renderedPkgIconRepository.renderGeneric(size);
    response.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(data.length));
    response.setContentType(MediaType.PNG.toString());

    if (isAsFallback) {
        response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
        response.setHeader(HttpHeaders.PRAGMA, "no-cache");
        response.setHeader(HttpHeaders.EXPIRES, "0");
    } else {
        response.setDateHeader(HttpHeaders.LAST_MODIFIED, startupMillis);
    }

    if (requestMethod == RequestMethod.GET) {
        response.getOutputStream().write(data);
    }
}

From source file:org.ambraproject.wombat.controller.StaticResourceController.java

/**
 * Serves a .js or .css asset that has already been concatenated and minified. See {@link AssetService} for details on
 * this process.//from www.j  ava 2s  . c o  m
 *
 * @param filePath the path to the file (relative to the theme)
 * @param response response object
 * @throws IOException
 */
private void serveCompiledAsset(String filePath, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    // The hash is already included in the compiled asset's filename, so we take advantage
    // of that here and use it as the etag.
    Matcher matcher = COMPILED_ASSET_PATTERN.matcher(filePath);
    if (!matcher.matches()) {
        throw new IllegalArgumentException(filePath + " is not a valid compiled asset path");
    }
    String basename = filePath.substring(COMPILED_NAMESPACE.length());

    // This is a "strong" etag since it's based on a fingerprint of the contents.
    String etag = String.format("\"%s\"", matcher.group(1));
    long lastModified = assetService.getLastModifiedTime(basename);
    if (HttpMessageUtil.checkIfModifiedSince(request, lastModified, etag)) {
        response.setHeader("Etag", etag);
        response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified);
        assetService.serveCompiledAsset(basename, response.getOutputStream());
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("Etag", etag);
    }
}

From source file:org.haiku.haikudepotserver.pkg.controller.PkgIconController.java

private void handleHeadOrGetPkgIcon(RequestMethod requestMethod, HttpServletResponse response, Integer size,
        String format, String pkgName, Boolean fallback) throws IOException {

    if (null == format) {
        throw new MissingOrBadFormat();
    }// www  .j a  v a2 s  .  co m

    if (Strings.isNullOrEmpty(pkgName) || !Pkg.PATTERN_NAME.matcher(pkgName).matches()) {
        throw new MissingPkgName();
    }

    ObjectContext context = serverRuntime.newContext();
    Optional<Pkg> pkg = Pkg.tryGetByName(context, pkgName); // cached

    if (!pkg.isPresent()) {
        LOGGER.debug("request for icon for package '{}', but no such package was able to be found", pkgName);
        throw new PkgNotFound();
    }

    switch (format) {

    case org.haiku.haikudepotserver.dataobjects.MediaType.EXTENSION_HAIKUVECTORICONFILE:
        Optional<PkgIcon> hvifPkgIcon = pkg.get().getPkgIcon(
                org.haiku.haikudepotserver.dataobjects.MediaType.getByExtension(context, format).get(), null);

        if (hvifPkgIcon.isPresent()) {
            byte[] data = hvifPkgIcon.get().getPkgIconImage().getData();
            response.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(data.length));
            response.setContentType(
                    org.haiku.haikudepotserver.dataobjects.MediaType.MEDIATYPE_HAIKUVECTORICONFILE);
            response.setDateHeader(HttpHeaders.LAST_MODIFIED,
                    pkg.get().getModifyTimestampSecondAccuracy().getTime());

            if (requestMethod == RequestMethod.GET) {
                OutputStream outputStream = response.getOutputStream();
                outputStream.write(data);
                outputStream.flush();
            }
        } else {
            throw new PkgIconNotFound();
        }
        break;

    case org.haiku.haikudepotserver.dataobjects.MediaType.EXTENSION_PNG:

        if (null == size) {
            throw new IllegalArgumentException("the size must be provided when requesting a PNG");
        }

        size = normalizeSize(size);
        Optional<byte[]> pngImageData = renderedPkgIconRepository.render(size, context, pkg.get());

        if (!pngImageData.isPresent()) {
            if ((null == fallback) || !fallback) {
                throw new PkgIconNotFound();
            }

            handleGenericHeadOrGet(requestMethod, response, size, true);
        } else {
            byte[] data = pngImageData.get();
            response.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(data.length));
            response.setContentType(MediaType.PNG.toString());
            response.setDateHeader(HttpHeaders.LAST_MODIFIED,
                    pkg.get().getModifyTimestampSecondAccuracy().getTime());

            if (requestMethod == RequestMethod.GET) {
                OutputStream outputStream = response.getOutputStream();
                outputStream.write(data);
                outputStream.flush();
            }
        }
        break;

    default:
        throw new IllegalStateException("unexpected format; " + format);

    }

}

From source file:org.sonatype.nexus.repository.proxy.ProxyFacetSupport.java

/**
 * Extract Last-Modified date from response if possible, or {@code null}.
 *//*w ww. j a va2 s  .c om*/
@Nullable
private DateTime extractLastModified(final HttpRequestBase request, final HttpResponse response) {
    final Header lastModifiedHeader = response.getLastHeader(HttpHeaders.LAST_MODIFIED);
    if (lastModifiedHeader != null) {
        try {
            return new DateTime(DateUtils.parseDate(lastModifiedHeader.getValue()).getTime());
        } catch (Exception ex) {
            log.warn(
                    "Could not parse date '{}' received from {}; using system current time as item creation time",
                    lastModifiedHeader, request.getURI());
        }
    }
    return null;
}

From source file:org.apache.marmotta.platform.core.webservices.resource.InspectionWebService.java

private Response inspectResource(RepositoryConnection conn, Resource rsc, long subjOffset, long propOffset,
        long objOffset, long ctxOffset, int limit) throws UnsupportedEncodingException, RepositoryException {
    if (rsc == null)
        return Response.status(Status.NOT_FOUND).entity("Not found").build();
    URI uri = null;/*ww  w .j a va 2 s  .c om*/
    if (rsc instanceof URI) {
        uri = (URI) rsc;
    }
    // Well, this is rather hacky...
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(os);

    ps.println("<!DOCTYPE HTML><html><head>");

    ps.printf("<title>Inspect %s</title>%n", rsc.stringValue());
    ps.println("<style type='text/css'>");
    ps.println("table {border: 2px solid #006d8f;width: 100%;border-collapse: collapse;}"
            + "html, body{font-family: sans-serif;}" + "table th {background-color: #006d8f;color: white;}"
            + "table tr {}" + "table tr.even {background-color: #dff7ff;}"
            + "table tr.odd {background-color: lightBlue;}" + "table th, table td {padding: 2px;}"
            + "table tr:hover {background-color: white;}" + ".isDeleted { color: red; font-style: italic; }"
            + ".deleted {width: 20px; height: 20px; display: inline-block; border-radius: 10px; float: right}"
            + ".deleted.true {background-color: red;}" + ".deleted.false {background-color: darkGreen;}"
            + ".reasoned a { border-radius: 10px; display: inline-block; float: right; background-color: orange; width: 20px; height: 20px; color: white; text-decoration: none; margin-right: 5px; text-align: center; font-family: serif; font-weight: bolder;}"
            + ".info-dialog { border:1px solid black; width:50%; position:absolute; top:100px; left:25%; background-color:white; z-index:2; padding-top:10px; min-height:100px; overflow:auto; display:none;}"
            + ".info-dialog button.close-button { position:absolute; top:5px; right:5px; } "
            + ".info-dialog iframe { border:none; width:100%; }");

    ps.println("</style>");

    ps.println();
    ps.println("</head><body>");

    ps.printf("<h1>Inspect %s</h1>%n<div>ShortName: %s<span class='%s'>%<s</span></div>%n", rsc.stringValue(),
            getLabel(conn, rsc), "");
    Date created = ResourceUtils.getCreated(conn, rsc);
    if (created != null) {
        ps.printf("<div>Created: <span>%tF %<tT</span> by <span>%s</span></div>%n", created,
                createInspectLink(conn, null, null, ""));
    }
    ps.printf("<div>Last Modified: <span>%tF %<tT</span></div>%n", ResourceUtils.getLastModified(conn, rsc));

    // Outgoing
    printOutgoing(conn, rsc, ps, subjOffset, limit);

    // Incoming
    printIncoming(conn, rsc, ps, objOffset, limit);

    // Links
    printLinks(conn, uri, ps, propOffset, limit);

    // Context
    printContext(conn, uri, ps, ctxOffset, limit);

    ps.println();
    ps.println("</body></html>");
    return Response.ok().header(HttpHeaders.CONTENT_TYPE, "text/html;charset=" + CHARSET)
            .header(HttpHeaders.LAST_MODIFIED, ResourceUtils.getLastModified(conn, rsc))
            .entity(os.toString(CHARSET)).build();
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static void addMetadataToResponse(HttpServletResponse response, BlobMetadata metadata) {
    ContentMetadata contentMetadata = metadata.getContentMetadata();
    response.addHeader(HttpHeaders.CONTENT_DISPOSITION, contentMetadata.getContentDisposition());
    response.addHeader(HttpHeaders.CONTENT_ENCODING, contentMetadata.getContentEncoding());
    response.addHeader(HttpHeaders.CONTENT_LANGUAGE, contentMetadata.getContentLanguage());
    response.addHeader(HttpHeaders.CONTENT_LENGTH, contentMetadata.getContentLength().toString());
    response.setContentType(contentMetadata.getContentType());
    HashCode contentMd5 = contentMetadata.getContentMD5AsHashCode();
    if (contentMd5 != null) {
        byte[] contentMd5Bytes = contentMd5.asBytes();
        response.addHeader(HttpHeaders.CONTENT_MD5, BaseEncoding.base64().encode(contentMd5Bytes));
        response.addHeader(HttpHeaders.ETAG,
                "\"" + BaseEncoding.base16().lowerCase().encode(contentMd5Bytes) + "\"");
    }/*w  w  w .  j  a  v a2s .  c o m*/
    Date expires = contentMetadata.getExpires();
    if (expires != null) {
        response.addDateHeader(HttpHeaders.EXPIRES, expires.getTime());
    }
    response.addDateHeader(HttpHeaders.LAST_MODIFIED, metadata.getLastModified().getTime());
    for (Map.Entry<String, String> entry : metadata.getUserMetadata().entrySet()) {
        response.addHeader(USER_METADATA_PREFIX + entry.getKey(), entry.getValue());
    }
}