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.gaul.s3proxy.S3ProxyHandler.java

private void doHandle(HttpServletRequest request, HttpServletResponse response)
        throws IOException, S3Exception {
    String method = request.getMethod();
    String uri = request.getRequestURI();
    logger.debug("request: {}", request);
    String hostHeader = request.getHeader(HttpHeaders.HOST);
    if (hostHeader != null && virtualHost.isPresent()) {
        hostHeader = HostAndPort.fromString(hostHeader).getHostText();
        String virtualHostSuffix = "." + virtualHost.get();
        if (!hostHeader.equals(virtualHost.get())) {
            if (hostHeader.endsWith(virtualHostSuffix)) {
                String bucket = hostHeader.substring(0, hostHeader.length() - virtualHostSuffix.length());
                uri = "/" + bucket + uri;
            } else {
                String bucket = hostHeader.toLowerCase();
                uri = "/" + bucket + uri;
            }/*w w w.jav a 2s  .  c o m*/
        }
    }

    boolean hasDateHeader = false;
    boolean hasXAmzDateHeader = false;
    for (String headerName : Collections.list(request.getHeaderNames())) {
        for (String headerValue : Collections.list(request.getHeaders(headerName))) {
            logger.trace("header: {}: {}", headerName, Strings.nullToEmpty(headerValue));
        }
        if (headerName.equalsIgnoreCase(HttpHeaders.DATE)) {
            hasDateHeader = true;
        } else if (headerName.equalsIgnoreCase("x-amz-date")) {
            hasXAmzDateHeader = true;
        }
    }

    // anonymous request
    if (method.equals("GET") && request.getHeader(HttpHeaders.AUTHORIZATION) == null
            && request.getParameter("AWSAccessKeyId") == null && defaultBlobStore != null) {
        doHandleAnonymous(request, response, uri, defaultBlobStore);
        return;
    }

    if (!anonymousIdentity && !hasDateHeader && !hasXAmzDateHeader && request.getParameter("Expires") == null) {
        throw new S3Exception(S3ErrorCode.ACCESS_DENIED,
                "AWS authentication requires a valid Date or" + " x-amz-date header");
    }

    // TODO: apply sanity checks to X-Amz-Date
    if (hasDateHeader) {
        long date;
        try {
            date = request.getDateHeader(HttpHeaders.DATE);
        } catch (IllegalArgumentException iae) {
            throw new S3Exception(S3ErrorCode.ACCESS_DENIED, iae);
        }
        if (date < 0) {
            throw new S3Exception(S3ErrorCode.ACCESS_DENIED);
        }
        long now = System.currentTimeMillis();
        if (now + TimeUnit.DAYS.toMillis(1) < date || now - TimeUnit.DAYS.toMillis(1) > date) {
            throw new S3Exception(S3ErrorCode.REQUEST_TIME_TOO_SKEWED);
        }
    }

    BlobStore blobStore;
    String requestIdentity = null;
    String requestSignature = null;
    String headerAuthorization = request.getHeader(HttpHeaders.AUTHORIZATION);

    if (headerAuthorization != null) {
        if (headerAuthorization.startsWith("AWS ")) {
            int colon = headerAuthorization.lastIndexOf(':', headerAuthorization.length() - 2);
            if (colon < 4) {
                throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT);
            }
            requestIdentity = headerAuthorization.substring(4, colon);
            requestSignature = headerAuthorization.substring(colon + 1);
        } else if (headerAuthorization.startsWith("AWS4-HMAC-SHA256 ")) {
            // Fail V4 signature requests to allow clients to retry with V2.
            throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT);
        }
    } else {
        requestIdentity = request.getParameter("AWSAccessKeyId");
        requestSignature = request.getParameter("Signature");
    }

    String[] path = uri.split("/", 3);
    for (int i = 0; i < path.length; i++) {
        path[i] = URLDecoder.decode(path[i], "UTF-8");
    }

    Map.Entry<String, BlobStore> provider = blobStoreLocator.locateBlobStore(requestIdentity,
            path.length > 1 ? path[1] : null, path.length > 2 ? path[2] : null);
    if (requestIdentity != null) {
        if (provider == null) {
            throw new S3Exception(S3ErrorCode.INVALID_ACCESS_KEY_ID);
        }

        String expectedSignature = createAuthorizationSignature(request, uri, requestIdentity,
                provider.getKey());
        if (!expectedSignature.equals(requestSignature)) {
            throw new S3Exception(S3ErrorCode.SIGNATURE_DOES_NOT_MATCH);
        }

        blobStore = provider.getValue();

        String expiresString = request.getParameter("Expires");
        if (expiresString != null) {
            long expires = Long.parseLong(expiresString);
            long nowSeconds = System.currentTimeMillis() / 1000;
            if (nowSeconds > expires) {
                throw new S3Exception(S3ErrorCode.ACCESS_DENIED);
            }
        }
    } else {
        if (!anonymousIdentity) {
            throw new S3Exception(S3ErrorCode.ACCESS_DENIED);
        } else {
            blobStore = provider.getValue();
        }
    }

    // emit NotImplemented for unknown parameters
    for (String parameter : Collections.list(request.getParameterNames())) {
        if (!SUPPORTED_PARAMETERS.contains(parameter)) {
            logger.error("Unknown parameters {} with URI {}", parameter, request.getRequestURI());
            throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED);
        }
    }

    String uploadId = request.getParameter("uploadId");
    switch (method) {
    case "DELETE":
        if (path.length <= 2 || path[2].isEmpty()) {
            handleContainerDelete(response, blobStore, path[1]);
            return;
        } else if (uploadId != null) {
            handleAbortMultipartUpload(request, response, blobStore, path[1], path[2], uploadId);
            return;
        } else {
            handleBlobRemove(response, blobStore, path[1], path[2]);
            return;
        }
    case "GET":
        if (uri.equals("/")) {
            handleContainerList(response, blobStore);
            return;
        } else if (path.length <= 2 || path[2].isEmpty()) {
            if ("".equals(request.getParameter("acl"))) {
                handleGetContainerAcl(response, blobStore, path[1]);
                return;
            } else if ("".equals(request.getParameter("location"))) {
                handleContainerLocation(response, blobStore, path[1]);
                return;
            } else if ("".equals(request.getParameter("uploads"))) {
                handleListMultipartUploads(response, blobStore, uploadId);
                return;
            }
            handleBlobList(request, response, blobStore, path[1]);
            return;
        } else {
            if ("".equals(request.getParameter("acl"))) {
                handleGetBlobAcl(response, blobStore, path[1], path[2]);
                return;
            } else if (uploadId != null) {
                handleListParts(request, response, blobStore, path[1], path[2], uploadId);
                return;
            }
            handleGetBlob(request, response, blobStore, path[1], path[2]);
            return;
        }
    case "HEAD":
        if (path.length <= 2 || path[2].isEmpty()) {
            handleContainerExists(response, blobStore, path[1]);
            return;
        } else {
            handleBlobMetadata(response, blobStore, path[1], path[2]);
            return;
        }
    case "POST":
        if ("".equals(request.getParameter("delete"))) {
            handleMultiBlobRemove(request, response, blobStore, path[1]);
            return;
        } else if ("".equals(request.getParameter("uploads"))) {
            handleInitiateMultipartUpload(request, response, blobStore, path[1], path[2]);
            return;
        } else if (uploadId != null) {
            handleCompleteMultipartUpload(request, response, blobStore, path[1], path[2], uploadId);
            return;
        }
        break;
    case "PUT":
        if (path.length <= 2 || path[2].isEmpty()) {
            if ("".equals(request.getParameter("acl"))) {
                handleSetContainerAcl(request, response, blobStore, path[1]);
                return;
            }
            handleContainerCreate(request, response, blobStore, path[1]);
            return;
        } else if (uploadId != null) {
            handleUploadPart(request, response, blobStore, path[1], path[2], uploadId);
            return;
        } else if (request.getHeader("x-amz-copy-source") != null) {
            handleCopyBlob(request, response, blobStore, path[1], path[2]);
            return;
        } else {
            if ("".equals(request.getParameter("acl"))) {
                handleSetBlobAcl(request, response, blobStore, path[1], path[2]);
                return;
            }
            handlePutBlob(request, response, blobStore, path[1], path[2]);
            return;
        }
    default:
        break;
    }
    logger.error("Unknown method {} with URI {}", method, request.getRequestURI());
    throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED);
}

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

/**
 * Create Amazon V2 signature.  Reference:
 * http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html
 *//*  www.j  a v  a2s.  c  o  m*/
private static String createAuthorizationSignature(HttpServletRequest request, String uri, String identity,
        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 Throwables.propagate(e);
    }
    return BaseEncoding.base64().encode(mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)));
}