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

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

Introduction

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

Prototype

String DATE

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

Click Source Link

Document

The HTTP Date header field name.

Usage

From source file:org.jclouds.glacier.filters.RequestAuthorizeSignature.java

@Override
public HttpRequest filter(HttpRequest request) throws HttpException {
    request = request.toBuilder().removeHeader(HttpHeaders.DATE)
            .replaceHeader(GlacierHeaders.ALTERNATE_DATE, timeStampProvider.get())
            .replaceHeader(HttpHeaders.HOST, request.getEndpoint().getHost()).build();
    utils.logRequest(signatureLog, request, ">>");
    request = this.signer.sign(request);
    utils.logRequest(signatureLog, request, "<<");
    return request;
}

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

/**
 * Create Amazon V2 signature.  Reference:
 * http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html
 *//*from   ww  w. j  a  va 2s .  co m*/
static String createAuthorizationSignature(HttpServletRequest request, String uri, String credential) {
    // sort Amazon headers
    SortedSetMultimap<String, String> canonicalizedHeaders = TreeMultimap.create();
    for (String headerName : Collections.list(request.getHeaderNames())) {
        Collection<String> headerValues = Collections.list(request.getHeaders(headerName));
        headerName = headerName.toLowerCase();
        if (!headerName.startsWith("x-amz-")) {
            continue;
        }
        if (headerValues.isEmpty()) {
            canonicalizedHeaders.put(headerName, "");
        }
        for (String headerValue : headerValues) {
            canonicalizedHeaders.put(headerName, Strings.nullToEmpty(headerValue));
        }
    }

    // build string to sign
    StringBuilder builder = new StringBuilder().append(request.getMethod()).append('\n')
            .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_MD5))).append('\n')
            .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_TYPE))).append('\n');
    String expires = request.getParameter("Expires");
    if (expires != null) {
        builder.append(expires);
    } else if (!canonicalizedHeaders.containsKey("x-amz-date")) {
        builder.append(request.getHeader(HttpHeaders.DATE));
    }
    builder.append('\n');
    for (Map.Entry<String, String> entry : canonicalizedHeaders.entries()) {
        builder.append(entry.getKey()).append(':').append(entry.getValue()).append('\n');
    }
    builder.append(uri);

    char separator = '?';
    List<String> subresources = Collections.list(request.getParameterNames());
    Collections.sort(subresources);
    for (String subresource : subresources) {
        if (SIGNED_SUBRESOURCES.contains(subresource)) {
            builder.append(separator).append(subresource);

            String value = request.getParameter(subresource);
            if (!"".equals(value)) {
                builder.append('=').append(value);
            }
            separator = '&';
        }
    }

    String stringToSign = builder.toString();
    logger.trace("stringToSign: {}", stringToSign);

    // sign string
    Mac mac;
    try {
        mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(credential.getBytes(StandardCharsets.UTF_8), "HmacSHA1"));
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    return BaseEncoding.base64().encode(mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)));
}

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();
    }/*from   w  w  w  . j  a  v  a  2s .  c  o 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:org.apache.rya.export.client.conf.TimeUtils.java

/**
 * Gets the remote machine's system time by checking the DATE field in the header
 * from a HTTP HEAD method response./*from  w w  w . ja v  a2  s  .c o m*/
 * @param urlString the URL string of the remote machine's web server to connect to.
 * @return the remote machine's system {@link Date} or {@code null}.
 * @throws IOException
 * @throws ParseException
 */
public static Date getRemoteMachineDate(final String urlString) throws IOException, ParseException {
    Date remoteDate = null;
    HttpURLConnection conn = null;
    try {
        final URL url = new URL(urlString);

        // Set up the initial connection
        conn = (HttpURLConnection) url.openConnection();
        // Use HEAD instead of GET so content isn't returned.
        conn.setRequestMethod(HttpMethods.HEAD);
        conn.setDoOutput(false);
        conn.setReadTimeout(10000);

        conn.connect();

        final Map<String, List<String>> header = conn.getHeaderFields();
        for (final String key : header.keySet()) {
            if (key != null && HttpHeaders.DATE.equals(key)) {
                final List<String> data = header.get(key);
                final String dateString = data.get(0);
                final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
                remoteDate = sdf.parse(dateString);
                break;
            }
        }
    } finally {
        // Close the connection
        conn.disconnect();
    }

    return remoteDate;
}

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.wso2.carbon.mediator.cache.util.HttpCachingFilter.java

/**
 * Set the response fetched time in milliseconds.
 *
 * @param headers  Transport headers./*from ww  w .  j a  v  a2 s  .  c  o m*/
 * @param response Response to be cached.
 * @throws ParseException throws exception if exception happen while parsing the date.
 */
public static void setResponseCachedTime(Map<String, String> headers, CachableResponse response)
        throws ParseException {
    long responseFetchedTime;
    String dateHeaderValue;
    if (headers != null && (dateHeaderValue = headers.get(HttpHeaders.DATE)) != null) {
        SimpleDateFormat format = new SimpleDateFormat(CachingConstants.DATE_PATTERN);
        Date d = format.parse(dateHeaderValue);
        responseFetchedTime = d.getTime();
    } else {
        responseFetchedTime = System.currentTimeMillis();
    }
    response.setResponseFetchedTime(responseFetchedTime);
}

From source file:org.jclouds.s3.filters.RequestAuthorizeSignatureV2.java

HttpRequest replaceDateHeader(HttpRequest request) {
    request = request.toBuilder().replaceHeader(HttpHeaders.DATE, timeStampProvider.get()).build();
    return request;
}

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:com.sector91.wit.responders.FileResponder.java

@Override
public void respond(One<String> param, Request request, Response response) throws IOException, HttpException {

    // Read basic information from the request.
    String pathstr = param.first();
    if (pathstr.startsWith("/"))
        pathstr = pathstr.substring(1);//from   w  w  w  . jav a2 s.com
    final Path path = root.resolve(pathstr);
    Log.debug(TAG, "Responding with file: " + path);
    final boolean gzipSupported = request.getValue(HttpHeaders.ACCEPT_ENCODING).contains("gzip");

    // Get the file from the cache, loading it if necessary.
    FileEntry entry;
    while (true) {
        try {
            entry = cache.get(path, new FileLoader(path));
        } catch (ExecutionException wrapper) {
            try {
                throw wrapper.getCause();
            } catch (FileTooLargeForCacheException ex) {
                Log.debug(TAG, "File too large for cache: " + path);
                entry = ex.file;
                break;
            } catch (HttpException ex) {
                throw ex;
            } catch (Throwable ex) {
                throw new HttpException(Status.INTERNAL_SERVER_ERROR, ex);
            }
        }

        // Reload the cached file if it has been modified since it was cached.
        if (entry.data.length <= maxSize && Files.getLastModifiedTime(path).toMillis() > entry.timestamp) {
            Log.debug(TAG, "Reloading file " + path + " from cache.");
            cache.invalidate(path);
        } else {
            break;
        }
    }

    // Return a 304 Not Modified if the client already has a cached copy.
    response.setDate(HttpHeaders.LAST_MODIFIED, entry.timestamp);
    final long ifModifiedSince = request.getDate(HttpHeaders.IF_MODIFIED_SINCE);
    if (ifModifiedSince >= (entry.timestamp * 1000) / 1000) {
        Log.trace(TAG, "File not modified: " + path);
        response.setStatus(Status.NOT_MODIFIED);
        response.getOutputStream().close();
        return;
    }

    // Set the HTTP headers.
    response.setDate(HttpHeaders.DATE, System.currentTimeMillis());
    response.setContentType(entry.mimetype);

    // EDGE CASE: If we're caching a compressed version of the file, but the
    // client doesn't support compression, then don't bother caching, and just
    // read the file directly.
    if (!gzipSupported && entry.gzipped) {
        Log.debug(TAG, "File " + path + " is cached in gzipped form, but client does not support"
                + " gzip. Skipping cache.");
        checkPathValidity(path);
        try (final InputStream in = Files.newInputStream(path);
                final OutputStream out = response.getOutputStream()) {
            ByteStreams.copy(in, out);
            return;
        }
    }

    // Otherwise, write the response headers and data.
    if (entry.gzipped)
        response.setValue(HttpHeaders.CONTENT_ENCODING, "gzip");
    response.setContentLength(entry.data.length);
    try (OutputStream out = response.getOutputStream()) {
        out.write(entry.data);
    }
}

From source file:org.jclouds.s3.filters.RequestAuthorizeSignatureV2.java

@VisibleForTesting
void appendHttpHeaders(HttpRequest request, SortedSetMultimap<String, String> canonicalizedHeaders) {
    Multimap<String, String> headers = request.getHeaders();
    for (Map.Entry<String, String> header : headers.entries()) {
        if (header.getKey() == null) {
            continue;
        }//from www .  jav a 2s  . c  o  m
        String key = header.getKey().toString().toLowerCase(Locale.getDefault());
        // Ignore any headers that are not particularly interesting.
        if (key.equalsIgnoreCase(HttpHeaders.CONTENT_TYPE) || key.equalsIgnoreCase("Content-MD5")
                || key.equalsIgnoreCase(HttpHeaders.DATE) || key.startsWith("x-" + headerTag + "-")) {
            canonicalizedHeaders.put(key, header.getValue());
        }
    }
}