Example usage for java.util SimpleTimeZone SimpleTimeZone

List of usage examples for java.util SimpleTimeZone SimpleTimeZone

Introduction

In this page you can find the example usage for java.util SimpleTimeZone SimpleTimeZone.

Prototype

public SimpleTimeZone(int rawOffset, String ID) 

Source Link

Document

Constructs a SimpleTimeZone with the given base time zone offset from GMT and time zone ID with no daylight saving time schedule.

Usage

From source file:com.amazonaws.services.ec2.util.S3UploadPolicy.java

/**
 * Creates a new S3 upload policy object from the specified parameters. Once
 * constructed, callers can access the policy string and policy signature to
 * use with the EC2 bundling API./*  w ww  .  j  a va 2  s . c o m*/
 *
 * @param awsAccessKeyId
 *            The AWS access key ID for the S3 bucket the bundling artifacts
 *            should be stored in.
 * @param awsSecretKey
 *            The AWS secret key for the specified access key.
 * @param bucketName
 *            The name of the bucket to store the bundling artifacts in.
 * @param prefix
 *            The prefix for the bundling artifacts.
 * @param expireInMinutes
 *            The number of minutes before the upload policy expires and is
 *            unable to be used.
 */
public S3UploadPolicy(String awsAccessKeyId, String awsSecretKey, String bucketName, String prefix,
        int expireInMinutes) {
    Calendar expirationDate = Calendar.getInstance();
    expirationDate.add(Calendar.MINUTE, expireInMinutes);
    SimpleDateFormat ISO8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    ISO8601.setTimeZone(new SimpleTimeZone(0, "GMT"));
    StringBuilder builder = new StringBuilder();
    builder.append("{").append("\"expiration\": \"").append(ISO8601.format(expirationDate.getTime()))
            .append("\",").append("\"conditions\": [").append("{\"bucket\": \"").append(bucketName)
            .append("\"},").append("{\"acl\": \"").append("ec2-bundle-read").append("\"},")
            .append("[\"starts-with\", \"$key\", \"").append(prefix).append("\"]").append("]}");
    try {
        this.policyString = base64Encode(builder.toString().getBytes("UTF-8"));
        this.policySignature = signPolicy(awsSecretKey, policyString);
    } catch (Exception ex) {
        throw new RuntimeException("Unable to generate S3 upload policy", ex);
    }
}

From source file:com.amazonaws.util.JodaTime.java

private static boolean checkFormatIso8601Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String expected = sdf.format(date);
    String actual = DateUtils.iso8601DateFormat.print(date.getTime());
    if (expected.equals(actual)) {
        Date expectedDate = sdf.parse(expected);
        Date actualDate = DateUtils.doParseISO8601Date(actual);
        return expectedDate.equals(actualDate);
    }//from   www  .ja  v a 2  s.co m
    return false;
}

From source file:pt.lunacloud.auth.AWS4Signer.java

public void sign(Request<?> request, LunacloudCredentials credentials) throws LunacloudClientException {
    // annonymous credentials, don't sign
    if (credentials instanceof AnonymousAWSCredentials) {
        return;/*  ww w .  java2s  . co  m*/
    }

    LunacloudCredentials sanitizedCredentials = sanitizeCredentials(credentials);
    if (sanitizedCredentials instanceof AWSSessionCredentials) {
        addSessionCredentials(request, (AWSSessionCredentials) sanitizedCredentials);
    }

    SimpleDateFormat dateStampFormat = new SimpleDateFormat("yyyyMMdd");
    dateStampFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));

    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
    dateTimeFormat.setTimeZone(new SimpleTimeZone(0, "UTC"));

    String regionName = extractRegionName(request.getEndpoint());
    String serviceName = extractServiceName(request.getEndpoint());

    // AWS4 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 (HttpUtils.isUsingNonDefaultPort(request.getEndpoint())) {
        hostHeader += ":" + request.getEndpoint().getPort();
    }
    request.addHeader("Host", hostHeader);

    Date date = getSignatureDate(request.getTimeOffset());
    if (overriddenDate != null)
        date = overriddenDate;

    String dateTime = dateTimeFormat.format(date);
    String dateStamp = dateStampFormat.format(date);

    InputStream payloadStream = getBinaryRequestPayloadStream(request);
    payloadStream.mark(-1);
    String contentSha256 = BinaryUtils.toHex(hash(payloadStream));
    try {
        payloadStream.reset();
    } catch (IOException e) {
        throw new LunacloudClientException("Unable to reset stream after calculating AWS4 signature", e);
    }

    request.addHeader("X-Amz-Date", dateTime);
    request.addHeader("x-amz-content-sha256", contentSha256);

    String canonicalRequest = request.getHttpMethod().toString() + "\n"
            + super.getCanonicalizedResourcePath(request.getResourcePath()) + "\n"
            + getCanonicalizedQueryString(request) + "\n" + getCanonicalizedHeaderString(request) + "\n"
            + getSignedHeadersString(request) + "\n" + contentSha256;

    log.debug("AWS4 Canonical Request: '\"" + canonicalRequest + "\"");

    String scope = dateStamp + "/" + regionName + "/" + serviceName + "/" + TERMINATOR;
    String signingCredentials = sanitizedCredentials.getLunacloudAccessKeyId() + "/" + scope;
    String stringToSign = ALGORITHM + "\n" + dateTime + "\n" + scope + "\n"
            + BinaryUtils.toHex(hash(canonicalRequest));
    log.debug("AWS4 String to Sign: '\"" + stringToSign + "\"");

    // AWS4 uses a series of derived keys, formed by hashing different pieces of data
    byte[] kSecret = ("AWS4" + sanitizedCredentials.getLunacloudSecretKey()).getBytes();
    byte[] kDate = sign(dateStamp, kSecret, SigningAlgorithm.HmacSHA256);
    byte[] kRegion = sign(regionName, kDate, SigningAlgorithm.HmacSHA256);
    byte[] kService = sign(serviceName, kRegion, SigningAlgorithm.HmacSHA256);
    byte[] kSigning = sign(TERMINATOR, kService, SigningAlgorithm.HmacSHA256);

    byte[] signature = sign(stringToSign.getBytes(), kSigning, SigningAlgorithm.HmacSHA256);

    String credentialsAuthorizationHeader = "Credential=" + signingCredentials;
    String signedHeadersAuthorizationHeader = "SignedHeaders=" + getSignedHeadersString(request);
    String signatureAuthorizationHeader = "Signature=" + BinaryUtils.toHex(signature);

    String authorizationHeader = ALGORITHM + " " + credentialsAuthorizationHeader + ", "
            + signedHeadersAuthorizationHeader + ", " + signatureAuthorizationHeader;

    request.addHeader("Authorization", authorizationHeader);
}

From source file:org.infoscoop.web.GadgetResourceServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String reqUri = req.getRequestURI();
    String resUri = reqUri.substring(reqUri.indexOf("/gadget/") + "/gadget/".length());

    String type = resUri.substring(0, resUri.indexOf("/"));
    String typeUri = resUri.substring(type.length());

    String path = typeUri.substring(0, typeUri.lastIndexOf("/") + 1);
    String name = typeUri.substring(path.length());

    if (path.length() > 1 && path.charAt(path.length() - 1) == '/')
        path = path.substring(0, path.length() - 1);

    if (name.equals(type + ".xml") && "/".equals(path)) {
        resp.sendError(403);//from  w  w  w.  ja  v  a  2 s  .  co  m
        return;
    }

    String ifModifiedSinceStr = req.getHeader("if-modified-since");

    GadgetResourceService service = GadgetResourceService.getHandle();
    Gadget gadget = service.getResource(type, path, name);
    if (gadget == null) {
        log.info("Gadget Resource: [" + type + "]@[" + path + "]/[" + name + "]" + " 404 Not Found");

        resp.sendError(404);
        return;
    }

    DateFormat dateFormat = DateUtility.newGMTDateFormat();
    // IE does not consider time zone
    dateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));

    if (ifModifiedSinceStr != null) {
        try {
            long ifModifiedSince = dateFormat.parse(ifModifiedSinceStr).getTime();

            // Delete millisecond 
            Calendar c = Calendar.getInstance();
            c.setTime(gadget.getLastmodified());
            c.set(Calendar.MILLISECOND, 0);
            long lastModified = c.getTimeInMillis();

            if (lastModified <= ifModifiedSince) {
                log.info("Gadget Resource: [" + type + "]@[" + path + "]/[" + name + "]" + " 302 Not Modified");

                resp.sendError(304);
                return;
            }
        } catch (Exception e) {
            log.error("", e);
        }
    }

    log.info("Gadget Resource: [" + type + "]@[" + path + "]/[" + name + "]" + " 200 Success");

    resp.setContentType(getServletContext().getMimeType(name));
    if (gadget.getLastmodified() != null)
        resp.setHeader("Last-Modified", dateFormat.format(gadget.getLastmodified()));

    byte[] data = gadget.getData();
    resp.setContentLength(data.length);
    resp.getOutputStream().write(data);
    resp.getOutputStream().flush();
}

From source file:com.amazonaws.util.JodaTime.java

private static boolean checkFormatRfc822Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String expected = sdf.format(date);
    String actual = DateUtils.rfc822DateFormat.print(date.getTime());
    if (expected.equals(actual)) {
        Date expectedDate = sdf.parse(expected);
        Date actualDate2 = new Date(DateUtils.rfc822DateFormat.parseMillis(actual));
        return expectedDate.equals(actualDate2);
    }/*from   ww w. j  a va  2s. c o m*/
    return false;
}

From source file:org.alfresco.service.cmr.calendar.CalendarTimezoneHelper.java

/**
 * Internal version that takes the parameters from {@link #getICalParams(String)}
 *  and builds a TimeZone from it.//from  www.j  a va2  s. co m
 * This is not public as it will be refactored when {@link #getICalParams(String)}
 *  is replaced.
 * Note - because it uses the icalParams, we can't handle cases where we're
 *  given historic TZ info (eg until 2004 it was that, now it's this)
 */
protected static SimpleTimeZone buildTimeZone(Map<String, String> icalParams) {
    // Pull out the interesting TZ parts
    Map<String, String> tzCore = new HashMap<String, String>();
    Map<String, String> tzStandard = new HashMap<String, String>();
    Map<String, String> tzDaylight = new HashMap<String, String>();

    for (String key : icalParams.keySet()) {
        if (key.startsWith("TZ-")) {
            String value = icalParams.get(key);

            // Assign
            key = key.substring(3);
            Map<String, String> dst = tzCore;

            if (key.startsWith(ICAL_SECTION_TZ_STANDARD)) {
                dst = tzStandard;
                key = key.substring(ICAL_SECTION_TZ_STANDARD.length() + 1);
            } else if (key.startsWith(ICAL_SECTION_TZ_DAYLIGHT)) {
                dst = tzDaylight;
                key = key.substring(ICAL_SECTION_TZ_DAYLIGHT.length() + 1);
            }

            dst.put(key, value);
        }
    }

    // Do we have any timezone info?
    if (tzStandard.isEmpty() && tzDaylight.isEmpty()) {
        logger.warn("No Standard/Daylight info found for " + tzCore);
        return null;
    }

    // Grab the name of it
    String tzID = tzCore.get("TZID");
    if (tzID == null || tzID.isEmpty()) {
        tzID = "(unknown)";
    }
    // De-escape commans
    tzID = tzID.replace("\\,", ",");

    // Does it have daylight savings?
    if (tzDaylight.isEmpty()) {
        // Life is easy!
        int offset = getOffset(tzStandard.get("TZOFFSETTO"));
        return new SimpleTimeZone(offset, tzID);
    }

    // Get the offsets
    int stdOffset = getOffset(tzDaylight.get("TZOFFSETFROM"));
    int dstOffset = getOffset(tzDaylight.get("TZOFFSETTO"));

    // Turn the rules into SimpleTimeZone ones
    int[] stdRules = getRuleForSimpleTimeZone(tzStandard.get("RRULE"));
    int[] dstRules = getRuleForSimpleTimeZone(tzDaylight.get("RRULE"));

    // Build it up
    return new SimpleTimeZone(stdOffset, tzID, dstRules[0], dstRules[1], dstRules[2], // When DST starts
            1 * 60 * 60 * 1000, // TODO Pull out the exact change time from DTSTART
            stdRules[0], stdRules[1], stdRules[2], // When DST ends
            2 * 60 * 60 * 1000 // TODO Pull out the exact change time from DTSTART
    );
}

From source file:com.amazonaws.util.JodaTime.java

private static boolean checkParseCompressedIso8601Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String formatted = sdf.format(date);
    Date expected = sdf.parse(formatted);
    Date actual = new Date(DateUtils.compressedIso8601DateFormat.parseMillis(formatted));
    return expected.equals(actual);
}

From source file:wsattacker.sso.openid.attacker.evaluation.attack.ReplayAttack.java

private String generateResponseNonceOfCurrentDateMinus(int years, int days, int hours) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(Calendar.HOUR_OF_DAY, (0 - hours));
    calendar.add(Calendar.DAY_OF_YEAR, (0 - days));
    calendar.add(Calendar.YEAR, (0 - years));

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    dateFormat.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));
    String timestamp = dateFormat.format(calendar.getTime());

    String randomString = RandomStringUtils.random(8, true, true);
    return timestamp + randomString;
}

From source file:com.amazonaws.util.JodaTime.java

private static boolean checkParseRfc822Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String formatted = sdf.format(date);
    Date expected = sdf.parse(formatted);
    Date actual2 = new Date(DateUtils.rfc822DateFormat.parseMillis(formatted));
    return expected.equals(actual2);
}

From source file:com.qut.middleware.saml2.SAML2Test.java

private AuthnRequest generateAuthnRequest() {
    AudienceRestriction audienceRestriction = new AudienceRestriction();
    Conditions conditions = new Conditions();
    NameIDType nameID = new NameIDType();
    Subject subject = new Subject();
    Signature signature = new Signature();
    AuthnRequest authnRequest = new AuthnRequest();

    /* GMT timezone */
    SimpleTimeZone gmt = new SimpleTimeZone(0, "UTC");

    /* GregorianCalendar with the GMT time zone */
    GregorianCalendar calendar = new GregorianCalendar(gmt);
    XMLGregorianCalendar xmlCalander = new XMLGregorianCalendarImpl(calendar);

    audienceRestriction.getAudiences().add("spep-n1.qut.edu.au");
    audienceRestriction.getAudiences().add("spep-n2.qut.edu.au");
    conditions.getConditionsAndOneTimeUsesAndAudienceRestrictions().add(audienceRestriction);

    nameID.setValue("beddoes@qut.com");
    nameID.setFormat("urn:oasis:names:tc:SAML:2.0:something");

    subject.setNameID(nameID);/*from w  ww  . j a v a2 s  .c o  m*/

    authnRequest.setSignature(signature);
    authnRequest.setSubject(subject);
    authnRequest.setConditions(conditions);

    authnRequest.setForceAuthn(false);
    authnRequest.setAssertionConsumerServiceURL("http://spep-n1.qut.edu.au/sso/aa");
    authnRequest.setAttributeConsumingServiceIndex(0);
    authnRequest.setProviderName("spep-n1-itscandy-you-like-it");
    authnRequest.setID("abe567de6-122wert67");
    authnRequest.setVersion("2.0");
    authnRequest.setIssueInstant(xmlCalander);

    return authnRequest;
}