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

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

Introduction

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

Prototype

String EXPIRES

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

Click Source Link

Document

The HTTP Expires header field name.

Usage

From source file:com.google.testing.security.firingrange.utils.Responses.java

/**
 * Sends an XSS response of a given type. 
 *///from  ww  w .  j  a  v a 2 s .c o  m
public static void sendXssed(HttpServletResponse response, String body, String contentType) throws IOException {
    response.setHeader(HttpHeaders.X_XSS_PROTECTION, "0");
    response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
    response.setHeader(HttpHeaders.PRAGMA, "no-cache");
    response.setDateHeader(HttpHeaders.EXPIRES, 0);
    response.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
    response.setStatus(200);
    response.getWriter().write(body);
}

From source file:org.libreoffice.ci.gerrit.buildbot.servlets.QueueServlet.java

static void setNotCacheable(HttpServletResponse res) {
    res.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate");
    res.setHeader(HttpHeaders.PRAGMA, "no-cache");
    res.setHeader(HttpHeaders.EXPIRES, "Fri, 01 Jan 1990 00:00:00 GMT");
    res.setDateHeader(HttpHeaders.DATE, new Instant().getMillis());
}

From source file:org.jclouds.aws.s3.blobstore.AWSS3BlobRequestSigner.java

private HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds) {
    // Update the 'DATE' header
    String dateString = request.getFirstHeaderOrNull(HttpHeaders.DATE);
    if (dateString == null) {
        dateString = timeStampProvider.get();
    }/* w w  w  .jav a 2 s  . co m*/
    Date date = dateService.rfc1123DateParse(dateString);
    String expiration = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(date.getTime()) + timeInSeconds);
    HttpRequest.Builder<?> builder = request.toBuilder().replaceHeader(HttpHeaders.DATE, expiration);
    String stringToSign = authSigner.createStringToSign(builder.build());
    // We MUST encode the signature because addQueryParam internally _always_ decodes values
    // and if we don't encode the signature here, the decoding may change the signature. For e.g.
    // any '+' characters in the signature will be converted to space ' ' on decoding.
    String signature = authSigner.sign(stringToSign);
    try {
        signature = URLEncoder.encode(signature, Charsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Bad encoding on input: " + signature, e);
    }
    HttpRequest ret = builder.addQueryParam(HttpHeaders.EXPIRES, expiration)
            .addQueryParam("AWSAccessKeyId", identity)
            // Signature MUST be the last parameter because if it isn't, even encoded '+' values in the
            // signature will be converted to a space by a subsequent addQueryParameter.
            // See HttpRequestTest.testAddBase64AndUrlEncodedQueryParams for more details.
            .addQueryParam(TEMPORARY_SIGNATURE_PARAM, signature).build();
    return ret;
}

From source file:com.google.gitiles.doc.DocServlet.java

@Override
protected void setCacheHeaders(HttpServletResponse res) {
    long now = System.currentTimeMillis();
    res.setDateHeader(HttpHeaders.EXPIRES, now);
    res.setDateHeader(HttpHeaders.DATE, now);
    res.setHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=0, must-revalidate");
}

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.
 *///from www.java2 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.haiku.haikudepotserver.job.controller.JobController.java

/**
 * <p>This URL can be used to download job data that has resulted from a job being run.</p>
 *///from  w ww.j a  va2  s.  com

@RequestMapping(value = "/" + SEGMENT_JOBDATA + "/{" + KEY_GUID + "}/"
        + SEGMENT_DOWNLOAD, method = RequestMethod.GET)
public void downloadGeneratedData(HttpServletRequest request, HttpServletResponse response,
        @PathVariable(value = KEY_GUID) String guid) throws IOException {

    Preconditions.checkArgument(PATTERN_GUID.matcher(guid).matches(),
            "the supplied guid does not match the required pattern");

    ObjectContext context = serverRuntime.newContext();

    JobSnapshot job = jobService.tryGetJobForData(guid).orElseThrow(() -> {
        LOGGER.warn("attempt to access job data {} for which no job exists", guid);
        return new JobDataAuthorizationFailure();
    });

    // If there is no user who is assigned to the job then the job is for nobody in particular and is thereby
    // secured by the GUID of the job's data; if you know the GUID then you can have the data.

    if (!Strings.isNullOrEmpty(job.getOwnerUserNickname())) {

        User user = tryObtainAuthenticatedUser(context).orElseThrow(() -> {
            LOGGER.warn("attempt to obtain job data {} with no authenticated user", guid);
            return new JobDataAuthorizationFailure();
        });

        User ownerUser = User.tryGetByNickname(context, job.getOwnerUserNickname()).orElseThrow(() -> {
            LOGGER.warn("owner of job does not seem to exist; {}", job.getOwnerUserNickname());
            return new JobDataAuthorizationFailure();
        });

        if (!authorizationService.check(context, user, ownerUser, Permission.USER_VIEWJOBS)) {
            LOGGER.warn("attempt to access jobs view for; {}", job.toString());
            throw new JobDataAuthorizationFailure();
        }
    } else {
        LOGGER.debug("access to job [{}] allowed for unauthenticated access", job.toString());
    }

    JobDataWithByteSource jobDataWithByteSink = jobService.tryObtainData(guid).orElseThrow(() -> {
        LOGGER.warn("requested job data {} not found", guid);
        return new JobDataAuthorizationFailure();
    });

    // finally access has been checked and the logic can move onto actual
    // delivery of the material.

    JobData jobData = jobDataWithByteSink.getJobData();

    if (!Strings.isNullOrEmpty(jobData.getMediaTypeCode())) {
        response.setContentType(jobData.getMediaTypeCode());
    } else {
        response.setContentType(MediaType.OCTET_STREAM.toString());
    }

    response.setContentType(MediaType.CSV_UTF_8.toString());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
            "attachment; filename=" + jobService.deriveDataFilename(guid));
    response.setDateHeader(HttpHeaders.EXPIRES, 0);
    response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");

    // now switch to async for the delivery of the data.

    AsyncContext async = request.startAsync();
    async.setTimeout(TIMEOUT_DOWNLOAD_MILLIS);
    ServletOutputStream outputStream = response.getOutputStream();
    outputStream.setWriteListener(new JobDataWriteListener(guid, jobService, async, outputStream));

    LOGGER.info("did start async stream job data; {}", guid);

}

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) + "\"");
    }//ww w  .  j  a va 2  s.  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());
    }
}

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

private static void addContentMetdataFromHttpRequest(BlobBuilder.PayloadBlobBuilder builder,
        HttpServletRequest request) {/*from   w  w  w  .  ja  va 2  s .c  o m*/
    ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder();
    for (String headerName : Collections.list(request.getHeaderNames())) {
        if (headerName.toLowerCase().startsWith(USER_METADATA_PREFIX)) {
            userMetadata.put(headerName.substring(USER_METADATA_PREFIX.length()),
                    Strings.nullToEmpty(request.getHeader(headerName)));
        }
    }
    builder.contentDisposition(request.getHeader(HttpHeaders.CONTENT_DISPOSITION))
            .contentEncoding(request.getHeader(HttpHeaders.CONTENT_ENCODING))
            .contentLanguage(request.getHeader(HttpHeaders.CONTENT_LANGUAGE))
            .userMetadata(userMetadata.build());
    String contentType = request.getContentType();
    if (contentType != null) {
        builder.contentType(contentType);
    }
    long expires = request.getDateHeader(HttpHeaders.EXPIRES);
    if (expires != -1) {
        builder.expires(new Date(expires));
    }
}