Java 类com.amazonaws.util.DateUtils 实例源码

项目:ibm-cos-sdk-java    文件:DateTimeJsonSerializer.java   
@Override
public void serialize(
        DateTime value,
        JsonGenerator jgen,
        SerializerProvider provider) throws IOException {

    jgen.writeString(DateUtils.formatISO8601Date(value));
}
项目:ibm-cos-sdk-java    文件:EC2CredentialsFetcherTest.java   
/** Tests that the credentials provider reloads credentials appropriately */
@Test
public void testNeedsToLoadCredentialsMethod() throws Exception {
    TestCredentialsProvider credentialsProvider = new TestCredentialsProvider();

    // The provider should not refresh credentials when they aren't close to expiring and are recent
    stubForSuccessResonseWithCustomExpirationDate(200, DateUtils.formatISO8601Date(new Date(System.currentTimeMillis() + ONE_MINUTE * 60 * 24)).toString());
    credentialsProvider.getCredentials();
    assertFalse(credentialsProvider.needsToLoadCredentials());

    // The provider should refresh credentials when they aren't close to expiring, but are more than an hour old
    stubForSuccessResonseWithCustomExpirationDate(200, DateUtils.formatISO8601Date(new Date(System.currentTimeMillis() + ONE_MINUTE * 16)).toString());
    credentialsProvider.getCredentials();
    credentialsProvider.setLastInstanceProfileCheck(new Date(System.currentTimeMillis() - ONE_MINUTE * 61));
    assertTrue(credentialsProvider.needsToLoadCredentials());

    // The provider should refresh credentials when they are close to expiring
    stubForSuccessResonseWithCustomExpirationDate(200, DateUtils.formatISO8601Date(new Date(System.currentTimeMillis() + ONE_MINUTE * 14)).toString());
    credentialsProvider.getCredentials();
    assertTrue(credentialsProvider.needsToLoadCredentials());
}
项目:amazon-cognito-developer-authentication-sample    文件:Utilities.java   
/**
 * Checks to see if the request has valid timestamp. If given timestamp
 * falls in 30 mins window from current server timestamp
 */
public static boolean isTimestampValid(String timestamp) {
    long timestampLong = 0L;
    final long window = 15 * 60 * 1000L;

    if (null == timestamp) {
        return false;
    }

    timestampLong = DateUtils.parseISO8601Date(timestamp).getTime();

    Long now = new Date().getTime();

    long before15Mins = new Date(now - window).getTime();
    long after15Mins = new Date(now + window).getTime();

    return (timestampLong >= before15Mins && timestampLong <= after15Mins);
}
项目:reinvent2013-mobile-photo-share    文件:Utilities.java   
/**
 * Checks to see if the request has valid timestamp. If given timestamp
 * falls in 30 mins window from current server timestamp
 */
public static boolean isTimestampValid(String timestamp) {
    long timestampLong = 0L;
    final long window = 15 * 60 * 1000L;

    if (null == timestamp) {
        return false;
    }

    try {
        timestampLong = new DateUtils().parseIso8601Date(timestamp).getTime();
    } catch (ParseException exception) {
        log.warning("Error parsing timestamp sent from client : " + timestamp);
        return false;
    }

    Long now = new Date().getTime();

    long before15Mins = new Date(now - window).getTime();
    long after15Mins = new Date(now + window).getTime();

    return (timestampLong >= before15Mins && timestampLong <= after15Mins);
}
项目:ibm-cos-sdk-java    文件:SimpleTypeStaxUnmarshallers.java   
public Date unmarshall(StaxUnmarshallerContext unmarshallerContext) throws Exception {
    String dateString = unmarshallerContext.readText();
    if (dateString == null) return null;

    try {
        return DateUtils.parseISO8601Date(dateString);
    } catch (Exception e) {
        log.warn("Unable to parse date '" + dateString + "':  " + e.getMessage(), e);
        return null;
    }
}
项目:ibm-cos-sdk-java    文件:SdkJsonGenerator.java   
@Override
public StructuredJsonGenerator writeValue(Date date) {
    try {
        generator.writeNumber(DateUtils.formatServiceSpecificDate(date));
    } catch (IOException e) {
        throw new JsonGenerationException(e);
    }
    return this;
}
项目:ibm-cos-sdk-java    文件:AmazonHttpClient.java   
/**
 * Returns the difference between the client's clock time and the service clock time in unit
 * of seconds.
 */
private int parseClockSkewOffset(org.apache.http.HttpResponse response,
                                 SdkBaseException exception) {
    final long currentTimeMilli = System.currentTimeMillis();
    Date serverDate;
    String serverDateStr = null;
    Header[] responseDateHeader = response.getHeaders("Date");

    try {
        if (responseDateHeader.length == 0) {
            // SQS doesn't return Date header
            final String errmsg = exception.getMessage();
            serverDateStr = getServerDateFromException(errmsg);
            if (serverDateStr == null) {
                log.warn("Unable to parse clock skew offset from errmsg: " + errmsg);
                return 0;
            }
            serverDate = DateUtils.parseCompressedISO8601Date(serverDateStr);
        } else {
            serverDateStr = responseDateHeader[0].getValue();
            serverDate = DateUtils.parseRFC822Date(serverDateStr);
        }
    } catch (RuntimeException e) {
        log.warn("Unable to parse clock skew offset from response: " + serverDateStr, e);
        return 0;
    }

    long diff = currentTimeMilli - serverDate.getTime();
    return (int) (diff / 1000);
}
项目:ibm-cos-sdk-java    文件:AWS4Signer.java   
/**
 * Step 3 of the AWS Signature version 4 calculation. It involves deriving
 * the signing key and computing the signature. Refer to
 * http://docs.aws.amazon
 * .com/general/latest/gr/sigv4-calculate-signature.html
 */
private final byte[] deriveSigningKey(AWSCredentials credentials,
        AWS4SignerRequestParams signerRequestParams) {

    final String cacheKey = computeSigningCacheKeyName(credentials,
            signerRequestParams);
    final long daysSinceEpochSigningDate = DateUtils
            .numberOfDaysSinceEpoch(signerRequestParams
                    .getSigningDateTimeMilli());

    SignerKey signerKey = signerCache.get(cacheKey);

    if (signerKey != null) {
        if (daysSinceEpochSigningDate == signerKey
                .getNumberOfDaysSinceEpoch()) {
            return signerKey.getSigningKey();
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Generating a new signing key as the signing key not available in the cache for the date "
                + TimeUnit.DAYS.toMillis(daysSinceEpochSigningDate));
    }
    byte[] signingKey = newSigningKey(credentials,
            signerRequestParams.getFormattedSigningDate(),
            signerRequestParams.getRegionName(),
            signerRequestParams.getServiceName());
    signerCache.add(cacheKey, new SignerKey(
            daysSinceEpochSigningDate, signingKey));
    return signingKey;
}
项目:ibm-cos-sdk-java    文件:XmlResponsesSaxParser.java   
@Override
protected void doEndElement(String uri, String name, String qName) {
    if (in("ListAllMyBucketsResult", "Owner")) {
        if (name.equals("ID")) {
            bucketsOwner.setId(getText());

        } else if (name.equals("DisplayName")) {
            bucketsOwner.setDisplayName(getText());
        }
    }

    else if (in("ListAllMyBucketsResult", "Buckets")) {
        if (name.equals("Bucket")) {
            buckets.add(currentBucket);
            currentBucket = null;
        }
    }

    else if (in("ListAllMyBucketsResult", "Buckets", "Bucket")) {
        if (name.equals("Name")) {
            currentBucket.setName(getText());

        } else if (name.equals("CreationDate")) {
            Date creationDate = DateUtils.parseISO8601Date(getText());
            currentBucket.setCreationDate(creationDate);
        }
    }
}
项目:libre    文件:AwsAttributes.java   
@Override
public Date created() throws IOException {
    final Date dat;
    if (this.meta.getRawMetadataValue(Headers.DATE) == null) {
        dat = this.meta.getLastModified();
    } else {
        dat = DateUtils.cloneDate(
            (Date) this.meta.getRawMetadataValue(Headers.DATE)
        );
    }
    return dat;
}
项目:Cheddar    文件:DynamoDBUnmarshallerUtil.java   
public static SSUnmarshaller getDateSSUnmarshaller() {
    return new SSUnmarshaller() {

        @Override
        public Object unmarshall(final AttributeValue value) throws ParseException {
            final Set<Date> argument = new HashSet<Date>();
            for (final String s : value.getSS()) {
                argument.add(DateUtils.parseISO8601Date(s));
            }
            return argument;
        }
    };
}
项目:Cheddar    文件:DynamoDBUnmarshallerUtil.java   
public static SUnmarshaller getDateSUnmarshaller() {
    return new SUnmarshaller() {

        @Override
        public Object unmarshall(final AttributeValue value) throws ParseException {
            return DateUtils.parseISO8601Date(value.getS());
        }
    };
}
项目:Cheddar    文件:DynamoDBUnmarshallerUtil.java   
public static SSUnmarshaller getCalendarSSUnmarshaller() {
    return new SSUnmarshaller() {

        @Override
        public Object unmarshall(final AttributeValue value) throws ParseException {
            final Set<Calendar> argument = new HashSet<Calendar>();
            for (final String s : value.getSS()) {
                final Calendar cal = GregorianCalendar.getInstance();
                cal.setTime(DateUtils.parseISO8601Date(s));
                argument.add(cal);
            }
            return argument;
        }
    };
}
项目:Cheddar    文件:DynamoDBUnmarshallerUtil.java   
public static SUnmarshaller getCalendarSUnmarshaller() {
    return new SUnmarshaller() {

        @Override
        public Object unmarshall(final AttributeValue value) throws ParseException {
            final Calendar cal = GregorianCalendar.getInstance();
            cal.setTime(DateUtils.parseISO8601Date(value.getS()));
            return cal;
        }
    };
}
项目:ibm-cos-sdk-java    文件:SimpleTypeJsonUnmarshallers.java   
public Date unmarshall(JsonUnmarshallerContext unmarshallerContext)
        throws Exception {
    return DateUtils.parseServiceSpecificDate(unmarshallerContext
            .readText());
}
项目:ibm-cos-sdk-java    文件:AWS3Signer.java   
/**
 * Signs the specified request with the AWS3 signing protocol by using the
 * AWS account credentials specified when this object was constructed and
 * adding the required AWS3 headers to the request.
 *
 * @param request
 *            The request to sign.
 */
@Override
public void sign(SignableRequest<?> request, AWSCredentials credentials) throws SdkClientException {
    // annonymous credentials, don't sign
    if ( credentials instanceof AnonymousAWSCredentials ) {
        return;
    }

    AWSCredentials sanitizedCredentials = sanitizeCredentials(credentials);

    SigningAlgorithm algorithm = SigningAlgorithm.HmacSHA256;
    String nonce = UUID.randomUUID().toString();

    int timeOffset = request.getTimeOffset();
    Date dateValue = getSignatureDate(timeOffset);
    String date = DateUtils.formatRFC822Date(dateValue);
    boolean isHttps = false;

    if (overriddenDate != null) date = overriddenDate;
    request.addHeader("Date", date);
    request.addHeader("X-Amz-Date", date);

    // AWS3 HTTP requires that we sign the Host header
    // so we have to have it in the request by the time we sign.
    String hostHeader = request.getEndpoint().getHost();
    if (SdkHttpUtils.isUsingNonDefaultPort(request.getEndpoint())) {
        hostHeader += ":" + request.getEndpoint().getPort();
    }
    request.addHeader("Host", hostHeader);

    if ( sanitizedCredentials instanceof AWSSessionCredentials ) {
        addSessionCredentials(request, (AWSSessionCredentials) sanitizedCredentials);
    }
    byte[] bytesToSign;
    String stringToSign;
    if (isHttps) {
        request.addHeader(NONCE_HEADER, nonce);
        stringToSign = date + nonce;
        bytesToSign = stringToSign.getBytes(UTF8);
    } else {
        String path = SdkHttpUtils.appendUri(request.getEndpoint().getPath(), request.getResourcePath());

        /*
         * AWS3 requires all query params to be listed on the third line of
         * the string to sign, even if those query params will be sent in
         * the request body and not as a query string. POST formatted query
         * params should *NOT* be included in the request payload.
         */
        stringToSign = request.getHttpMethod().toString() + "\n"
                + getCanonicalizedResourcePath(path) + "\n"
                + getCanonicalizedQueryString(request.getParameters()) + "\n"
                + getCanonicalizedHeadersForStringToSign(request) + "\n"
                + getRequestPayloadWithoutQueryParams(request);
        bytesToSign = hash(stringToSign);
    }
    if (log.isDebugEnabled())
        log.debug("Calculated StringToSign: " + stringToSign);

    String signature = signAndBase64Encode(bytesToSign,
            sanitizedCredentials.getAWSSecretKey(), algorithm);

    StringBuilder builder = new StringBuilder();
    builder.append(isHttps ? HTTPS_SCHEME : HTTP_SCHEME).append(" ");
    builder.append("AWSAccessKeyId=" + sanitizedCredentials.getAWSAccessKeyId() + ",");
    builder.append("Algorithm=" + algorithm.toString() + ",");

    if (!isHttps) {
        builder.append(getSignedHeadersComponent(request) + ",");
    }

    builder.append("Signature=" + signature);
    request.addHeader(AUTHORIZATION_HEADER, builder.toString());
}
项目:ibm-cos-sdk-java    文件:ServiceUtils.java   
public static Date parseIso8601Date(String dateString) {
    return DateUtils.parseISO8601Date(dateString);
}
项目:ibm-cos-sdk-java    文件:ServiceUtils.java   
public static String formatIso8601Date(Date date) {
    return DateUtils.formatISO8601Date(date);
}
项目:ibm-cos-sdk-java    文件:ServiceUtils.java   
public static Date parseRfc822Date(String dateString) {
    if (StringUtils.isNullOrEmpty(dateString)) {
        return null;
    }
    return DateUtils.parseRFC822Date(dateString);
}
项目:ibm-cos-sdk-java    文件:ServiceUtils.java   
public static String formatRfc822Date(Date date) {
    return DateUtils.formatRFC822Date(date);
}
项目:ExerciseMe    文件:Utilities.java   
public static String getTimestamp() {
    return new DateUtils().formatIso8601Date( new Date() );
}
项目:aws-sdk-android-samples    文件:Utilities.java   
public static String getTimestamp() {
    return DateUtils.formatISO8601Date(new Date());
}
项目:ibm-cos-sdk-java    文件:DateCondition.java   
/**
 * Constructs a new access policy condition that compares the current time
 * (on the AWS servers) to the specified date.
 *
 * @param type
 *            The type of comparison to perform. For example,
 *            {@link DateComparisonType#DateLessThan} will cause this policy
 *            condition to evaluate to true if the current date is less than
 *            the date specified in the second argument.
 * @param date
 *            The date to compare against.
 */
public DateCondition(DateComparisonType type, Date date) {
    super.type = type.toString();
    super.conditionKey = ConditionFactory.CURRENT_TIME_CONDITION_KEY;
    super.values = Arrays.asList(new String[] {DateUtils.formatISO8601Date(date)});
}