Example usage for com.amazonaws.util DateUtils formatISO8601Date

List of usage examples for com.amazonaws.util DateUtils formatISO8601Date

Introduction

In this page you can find the example usage for com.amazonaws.util DateUtils formatISO8601Date.

Prototype

public static String formatISO8601Date(DateTime date) 

Source Link

Document

Formats the specified date as an ISO 8601 string.

Usage

From source file:com.deploymentio.cfnstacker.CloudFormationClient.java

License:Apache License

private String createStackEventLogMessage(StackEvent evt, Date startDate, String message) {
    return message + ": StartDate=" + DateUtils.formatISO8601Date(startDate) + " EventStatus="
            + evt.getResourceStatus() + " EventDate=" + DateUtils.formatISO8601Date(evt.getTimestamp())
            + " EventId=" + evt.getEventId() + " EventResourceId=" + evt.getLogicalResourceId()
            + " EventResourceType=" + evt.getResourceType();
}

From source file:com.deploymentio.cfnstacker.OperationTracker.java

License:Apache License

/**
 * Adds a new ongoing stack operation to track. If a task (based on
 * taskName) is already tracked, it is silently ignored.
 * /*from www  .  j a v a  2 s . co m*/
 * @param client
 *            the CFN client
 * @param stackName
 *            stack name
 * @param stackId
 *            stack ID
 * @param checkIntervalSeconds
 *            how often to check the stack operation's progress
 */
public OperationTracker track(final CloudFormationClient client, final String stackName, final String stackId,
        final int checkIntervalSeconds) {

    if (stackNames.add(stackName)) {
        logger.debug("Tracking Stack: Name=" + stackName + " ID=" + stackId);
        Future<String> future = executor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                // set the time to be a minute in the past - this is to account for any
                // time differences between the local clock and clock on CFN servers
                Date startTime = new Date(System.currentTimeMillis() - 60000);
                while (true) {

                    if (logger.isTraceEnabled()) {
                        logger.trace(
                                "Waiting for completion: StartDate=" + DateUtils.formatISO8601Date(startTime));
                    }

                    // display all events and look for the final event for the stack itself
                    boolean getOutLater = false;
                    for (StackEvent evt : client.getStackEvents(stackId, startTime, OperationTracker.this,
                            checkIntervalSeconds)) {

                        if (evt.getResourceType().equals("AWS::CloudFormation::Stack")) {

                            if (evt.getPhysicalResourceId().equals(stackId)) {
                                getOutLater = true;
                            }
                        }

                        // record the latest timestamp
                        if (evt.getTimestamp().after(startTime))
                            startTime = evt.getTimestamp();

                        if (logger.isDebugEnabled()) {
                            logger.info("EventDate=" + DateUtils.formatISO8601Date(evt.getTimestamp())
                                    + " Stack=" + stackName + " Type=" + evt.getResourceType() + " ID="
                                    + evt.getLogicalResourceId() + " Status=" + evt.getResourceStatus());
                        } else {
                            logger.info("Stack=" + stackName + " Type=" + evt.getResourceType() + " ID="
                                    + evt.getLogicalResourceId() + " Status=" + evt.getResourceStatus());
                        }
                    }

                    if (getOutLater) {
                        break;
                    } else {
                        Thread.sleep(checkIntervalSeconds * 1000);
                    }
                }

                return stackId;
            }
        });
        trackerRecords.put(stackId, new ProgressTrackerRecord(stackName, future));
    } else {
        logger.trace("Ignoring Stack: Name=" + stackName);
    }

    return this;
}

From source file:com.mobilis.android.nfc.aws.cognito.Utilities.java

License:Open Source License

public static String getTimestamp() {
    return DateUtils.formatISO8601Date(new Date());
}

From source file:jp.xet.uncommons.spring.DynamoPersistentTokenRepository.java

License:Apache License

@Override
public void createNewToken(PersistentRememberMeToken token) {
    Assert.notNull(token);//w  ww. j a v a 2s  . com
    if (logger.isTraceEnabled()) {
        logger.trace("Create token: username={}, series={}, tokenValue={}, date={}", new Object[] {
                token.getUsername(), token.getSeries(), token.getTokenValue(), token.getDate() });
    }

    try {
        Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
        item.put(USERNAME, new AttributeValue(token.getUsername()));
        item.put(SERIES, new AttributeValue(token.getSeries()));
        item.put(TOKEN, new AttributeValue(token.getTokenValue()));
        item.put(LAST_USED, new AttributeValue(DateUtils.formatISO8601Date(token.getDate())));

        PutItemRequest putRequest = new PutItemRequest().withTableName(persistentLoginTable).withItem(item);
        PutItemResult result = dynamoDb.putItem(putRequest);
        if (logger.isDebugEnabled()) {
            logger.debug("Token created: {}", result);
        }
    } catch (Exception e) {
        logger.error("unknown exception", e);
    }
}

From source file:jp.xet.uncommons.spring.DynamoPersistentTokenRepository.java

License:Apache License

@Override
public void updateToken(String series, String tokenValue, Date lastUsed) {
    if (logger.isTraceEnabled()) {
        logger.trace("Update token: series={}, tokenValue={}, lastUsed={}",
                new Object[] { series, tokenValue, lastUsed });
    }//  www  . j av a 2  s. co m

    try {
        String now = DateUtils.formatISO8601Date(new Date());
        Map<String, AttributeValueUpdate> attributeUpdates = Maps.newHashMapWithExpectedSize(2);
        attributeUpdates.put(TOKEN,
                new AttributeValueUpdate(new AttributeValue(tokenValue), AttributeAction.PUT));
        attributeUpdates.put(LAST_USED, new AttributeValueUpdate(new AttributeValue(now), AttributeAction.PUT));

        UpdateItemRequest updateRequest = new UpdateItemRequest().withTableName(persistentLoginTable)
                .withKey(Collections.singletonMap(SERIES, new AttributeValue(series)))
                .withAttributeUpdates(attributeUpdates);
        UpdateItemResult result = dynamoDb.updateItem(updateRequest);
        if (logger.isDebugEnabled()) {
            logger.debug("Token updated: {}", result);
        }
    } catch (Exception e) {
        logger.error("unknown exception", e);
    }
}

From source file:org.elasticsearch.repositories.s3.AmazonS3Fixture.java

License:Apache License

/** Builds the default request handlers **/
private PathTrie<RequestHandler> defaultHandlers(final Map<String, Bucket> buckets, final Bucket ec2Bucket,
        final Bucket ecsBucket) {
    final PathTrie<RequestHandler> handlers = new PathTrie<>(RestUtils.REST_DECODER);

    // HEAD Object
    ////from ww w.  j a v  a2  s  . c om
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html
    objectsPaths(authPath(HttpHead.METHOD_NAME, "/{bucket}"))
            .forEach(path -> handlers.insert(path, (request) -> {
                final String bucketName = request.getParam("bucket");

                final Bucket bucket = buckets.get(bucketName);
                if (bucket == null) {
                    return newBucketNotFoundError(request.getId(), bucketName);
                }

                final String objectName = objectName(request.getParameters());
                for (Map.Entry<String, byte[]> object : bucket.objects.entrySet()) {
                    if (object.getKey().equals(objectName)) {
                        return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE);
                    }
                }
                return newObjectNotFoundError(request.getId(), objectName);
            }));

    // PUT Object
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html
    objectsPaths(authPath(HttpPut.METHOD_NAME, "/{bucket}"))
            .forEach(path -> handlers.insert(path, (request) -> {
                final String destBucketName = request.getParam("bucket");

                final Bucket destBucket = buckets.get(destBucketName);
                if (destBucket == null) {
                    return newBucketNotFoundError(request.getId(), destBucketName);
                }

                final String destObjectName = objectName(request.getParameters());

                // This is a chunked upload request. We should have the header "Content-Encoding : aws-chunked,gzip"
                // to detect it but it seems that the AWS SDK does not follow the S3 guidelines here.
                //
                // See https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html
                //
                String headerDecodedContentLength = request.getHeader("X-amz-decoded-content-length");
                if (headerDecodedContentLength != null) {
                    int contentLength = Integer.valueOf(headerDecodedContentLength);

                    // Chunked requests have a payload like this:
                    //
                    // 105;chunk-signature=01d0de6be013115a7f4794db8c4b9414e6ec71262cc33ae562a71f2eaed1efe8
                    // ...  bytes of data ....
                    // 0;chunk-signature=f890420b1974c5469aaf2112e9e6f2e0334929fd45909e03c0eff7a84124f6a4
                    //
                    try (BufferedInputStream inputStream = new BufferedInputStream(
                            new ByteArrayInputStream(request.getBody()))) {
                        int b;
                        // Moves to the end of the first signature line
                        while ((b = inputStream.read()) != -1) {
                            if (b == '\n') {
                                break;
                            }
                        }

                        final byte[] bytes = new byte[contentLength];
                        inputStream.read(bytes, 0, contentLength);

                        destBucket.objects.put(destObjectName, bytes);
                        return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE);
                    }
                }

                return newInternalError(request.getId(), "Something is wrong with this PUT request");
            }));

    // DELETE Object
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html
    objectsPaths(authPath(HttpDelete.METHOD_NAME, "/{bucket}"))
            .forEach(path -> handlers.insert(path, (request) -> {
                final String bucketName = request.getParam("bucket");

                final Bucket bucket = buckets.get(bucketName);
                if (bucket == null) {
                    return newBucketNotFoundError(request.getId(), bucketName);
                }

                final String objectName = objectName(request.getParameters());
                bucket.objects.remove(objectName);
                return new Response(RestStatus.NO_CONTENT.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE);
            }));

    // GET Object
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html
    objectsPaths(authPath(HttpGet.METHOD_NAME, "/{bucket}"))
            .forEach(path -> handlers.insert(path, (request) -> {
                final String bucketName = request.getParam("bucket");

                final Bucket bucket = buckets.get(bucketName);
                if (bucket == null) {
                    return newBucketNotFoundError(request.getId(), bucketName);
                }

                final String objectName = objectName(request.getParameters());
                if (bucket.objects.containsKey(objectName)) {
                    return new Response(RestStatus.OK.getStatus(), contentType("application/octet-stream"),
                            bucket.objects.get(objectName));

                }
                return newObjectNotFoundError(request.getId(), objectName);
            }));

    // HEAD Bucket
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html
    handlers.insert(authPath(HttpHead.METHOD_NAME, "/{bucket}"), (request) -> {
        String bucket = request.getParam("bucket");
        if (Strings.hasText(bucket) && buckets.containsKey(bucket)) {
            return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE);
        } else {
            return newBucketNotFoundError(request.getId(), bucket);
        }
    });

    // GET Bucket (List Objects) Version 1
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
    handlers.insert(authPath(HttpGet.METHOD_NAME, "/{bucket}/"), (request) -> {
        final String bucketName = request.getParam("bucket");

        final Bucket bucket = buckets.get(bucketName);
        if (bucket == null) {
            return newBucketNotFoundError(request.getId(), bucketName);
        }

        String prefix = request.getParam("prefix");
        if (prefix == null) {
            prefix = request.getHeader("Prefix");
        }
        return newListBucketResultResponse(request.getId(), bucket, prefix);
    });

    // Delete Multiple Objects
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/multiobjectdeleteapi.html
    handlers.insert(nonAuthPath(HttpPost.METHOD_NAME, "/"), (request) -> {
        final List<String> deletes = new ArrayList<>();
        final List<String> errors = new ArrayList<>();

        if (request.getParam("delete") != null) {
            // The request body is something like:
            // <Delete><Object><Key>...</Key></Object><Object><Key>...</Key></Object></Delete>
            String requestBody = Streams
                    .copyToString(new InputStreamReader(new ByteArrayInputStream(request.getBody()), UTF_8));
            if (requestBody.startsWith("<Delete>")) {
                final String startMarker = "<Key>";
                final String endMarker = "</Key>";

                int offset = 0;
                while (offset != -1) {
                    offset = requestBody.indexOf(startMarker, offset);
                    if (offset > 0) {
                        int closingOffset = requestBody.indexOf(endMarker, offset);
                        if (closingOffset != -1) {
                            offset = offset + startMarker.length();
                            final String objectName = requestBody.substring(offset, closingOffset);

                            boolean found = false;
                            for (Bucket bucket : buckets.values()) {
                                if (bucket.objects.containsKey(objectName)) {
                                    final Response authResponse = authenticateBucket(request, bucket);
                                    if (authResponse != null) {
                                        return authResponse;
                                    }
                                    bucket.objects.remove(objectName);
                                    found = true;
                                }
                            }

                            if (found) {
                                deletes.add(objectName);
                            } else {
                                errors.add(objectName);
                            }
                        }
                    }
                }
                return newDeleteResultResponse(request.getId(), deletes, errors);
            }
        }
        return newInternalError(request.getId(), "Something is wrong with this POST multiple deletes request");
    });

    // non-authorized requests

    TriFunction<String, String, String, Response> credentialResponseFunction = (profileName, key, token) -> {
        final Date expiration = new Date(new Date().getTime() + TimeUnit.DAYS.toMillis(1));
        final String response = "{" + "\"AccessKeyId\": \"" + key + "\"," + "\"Expiration\": \""
                + DateUtils.formatISO8601Date(expiration) + "\"," + "\"RoleArn\": \""
                + randomAsciiAlphanumOfLengthBetween(random, 1, 20) + "\"," + "\"SecretAccessKey\": \""
                + randomAsciiAlphanumOfLengthBetween(random, 1, 20) + "\"," + "\"Token\": \"" + token + "\""
                + "}";

        final Map<String, String> headers = new HashMap<>(contentType("application/json"));
        return new Response(RestStatus.OK.getStatus(), headers, response.getBytes(UTF_8));
    };

    // GET
    //
    // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
    handlers.insert(nonAuthPath(HttpGet.METHOD_NAME, "/latest/meta-data/iam/security-credentials/"),
            (request) -> {
                final String response = EC2_PROFILE;

                final Map<String, String> headers = new HashMap<>(contentType("text/plain"));
                return new Response(RestStatus.OK.getStatus(), headers, response.getBytes(UTF_8));
            });

    // GET
    //
    // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
    handlers.insert(
            nonAuthPath(HttpGet.METHOD_NAME, "/latest/meta-data/iam/security-credentials/{profileName}"),
            (request) -> {
                final String profileName = request.getParam("profileName");
                if (EC2_PROFILE.equals(profileName) == false) {
                    return new Response(RestStatus.NOT_FOUND.getStatus(), new HashMap<>(),
                            "unknown profile".getBytes(UTF_8));
                }
                return credentialResponseFunction.apply(profileName, ec2Bucket.key, ec2Bucket.token);
            });

    // GET
    //
    // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html
    handlers.insert(nonAuthPath(HttpGet.METHOD_NAME, "/ecs_credentials_endpoint"),
            (request) -> credentialResponseFunction.apply("CPV_ECS", ecsBucket.key, ecsBucket.token));

    return handlers;
}

From source file:org.elasticsearch.repositories.s3.AmazonS3Fixture.java

License:Apache License

/**
 * S3 ListBucketResult Response//from   w  ww  .j a  v  a 2s  .co  m
 */
private static Response newListBucketResultResponse(final long requestId, final Bucket bucket,
        final String prefix) {
    final String id = Long.toString(requestId);
    final StringBuilder response = new StringBuilder();
    response.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    response.append("<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">");
    response.append("<Prefix>");
    if (prefix != null) {
        response.append(prefix);
    }
    response.append("</Prefix>");
    response.append("<Marker/>");
    response.append("<MaxKeys>1000</MaxKeys>");
    response.append("<IsTruncated>false</IsTruncated>");

    int count = 0;
    for (Map.Entry<String, byte[]> object : bucket.objects.entrySet()) {
        String objectName = object.getKey();
        if (prefix == null || objectName.startsWith(prefix)) {
            response.append("<Contents>");
            response.append("<Key>").append(objectName).append("</Key>");
            response.append("<LastModified>").append(DateUtils.formatISO8601Date(new Date()))
                    .append("</LastModified>");
            response.append("<ETag>&quot;").append(count++).append("&quot;</ETag>");
            response.append("<Size>").append(object.getValue().length).append("</Size>");
            response.append("</Contents>");
        }
    }
    response.append("</ListBucketResult>");

    final Map<String, String> headers = new HashMap<>(contentType("application/xml"));
    headers.put("x-amz-request-id", id);

    return new Response(RestStatus.OK.getStatus(), headers, response.toString().getBytes(UTF_8));
}

From source file:org.elasticsearch.repositories.s3.AmazonS3TestServer.java

License:Apache License

/**
 * S3 ListBucketResult Response/*from   w ww .  j  av a2 s  .c o m*/
 */
private static Response newListBucketResultResponse(final long requestId, final Bucket bucket,
        final String prefix) {
    final String id = Long.toString(requestId);
    final StringBuilder response = new StringBuilder();
    response.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    response.append("<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">");
    response.append("<Prefix>");
    if (prefix != null) {
        response.append(prefix);
    }
    response.append("</Prefix>");
    response.append("<Marker/>");
    response.append("<MaxKeys>1000</MaxKeys>");
    response.append("<IsTruncated>false</IsTruncated>");

    int count = 0;
    for (Map.Entry<String, byte[]> object : bucket.objects.entrySet()) {
        String objectName = object.getKey();
        if (prefix == null || objectName.startsWith(prefix)) {
            response.append("<Contents>");
            response.append("<Key>").append(objectName).append("</Key>");
            response.append("<LastModified>").append(DateUtils.formatISO8601Date(new Date()))
                    .append("</LastModified>");
            response.append("<ETag>&quot;").append(count++).append("&quot;</ETag>");
            response.append("<Size>").append(object.getValue().length).append("</Size>");
            response.append("</Contents>");
        }
    }
    response.append("</ListBucketResult>");
    return new Response(RestStatus.OK, singletonMap("x-amz-request-id", id), "application/xml",
            response.toString().getBytes(UTF_8));
}

From source file:org.elasticsearch.repositories.s3.AmazonS3TestServer.java

License:Apache License

/**
 * S3 Copy Result Response/*from  w  w w . j  a  v  a  2s  .c om*/
 */
private static Response newCopyResultResponse(final long requestId) {
    final String id = Long.toString(requestId);
    final StringBuilder response = new StringBuilder();
    response.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    response.append("<CopyObjectResult>");
    response.append("<LastModified>").append(DateUtils.formatISO8601Date(new Date())).append("</LastModified>");
    response.append("<ETag>").append(requestId).append("</ETag>");
    response.append("</CopyObjectResult>");
    return new Response(RestStatus.OK, singletonMap("x-amz-request-id", id), "application/xml",
            response.toString().getBytes(UTF_8));
}