Example usage for java.text DateFormat setTimeZone

List of usage examples for java.text DateFormat setTimeZone

Introduction

In this page you can find the example usage for java.text DateFormat setTimeZone.

Prototype

public void setTimeZone(TimeZone zone) 

Source Link

Document

Sets the time zone for the calendar of this DateFormat object.

Usage

From source file:com.microsoft.azure.storage.core.Utility.java

/**
 * Returns the UTC date/time for the specified value using the ISO8601 pattern.
 * //  w w w. j  a va2  s. c  o m
 * @param value
 *            A <code>Date</code> object that represents the date to convert to UTC date/time in the ISO8601
 *            pattern. If this value is <code>null</code>, this method returns an empty string.
 * 
 * @return A <code>String</code> that represents the UTC date/time for the specified value using the ISO8601
 *         pattern, or an empty string if <code>value</code> is <code>null</code>.
 */
public static String getUTCTimeOrEmpty(final Date value) {
    if (value == null) {
        return Constants.EMPTY_STRING;
    }

    final DateFormat iso8601Format = new SimpleDateFormat(ISO8601_PATTERN, LOCALE_US);
    iso8601Format.setTimeZone(UTC_ZONE);

    return iso8601Format.format(value);
}

From source file:ch.entwine.weblounge.test.harness.content.CacheTest.java

/**
 * Test if the cache is returning proper header to enable caching on the
 * client side, such as <code>Last-Modified</code>, <code>Expires</code> or
 * <code>ETag</code>.//from ww  w .  j ava 2 s.c  o  m
 * 
 * @param serverUrl
 *          the server url
 * @throws Exception
 *           if the test fails
 */
private void testCacheHeaders(String serverUrl) throws Exception {
    logger.info("Preparing test of response caching");

    DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
    df.setTimeZone(TimeZone.getTimeZone("GMT"));

    // Prepare the request
    logger.info("Testing response cache");

    String requestUrl = UrlUtils.concat(serverUrl, contentTestPage, language.getIdentifier());

    logger.info("Sending request to the {} version of {}", language.getLocale().getDisplayName(), requestUrl);
    HttpGet request = new HttpGet(requestUrl);
    request.addHeader("X-Cache-Debug", "yes");
    String[][] params = new String[][] { { "language", language.getIdentifier() } };

    // Send and the request and examine the response. The first request might
    // not come out of the cache
    logger.debug("Sending request to {}", request.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, request, params);
        int statusCode = response.getStatusLine().getStatusCode();
        boolean okOrNotModified = statusCode == HttpServletResponse.SC_OK
                || statusCode == HttpServletResponse.SC_NOT_MODIFIED;
        assertTrue(okOrNotModified);

        // Get the ETag header
        assertNotNull(response.getHeaders("ETag"));
        assertEquals(1, response.getHeaders("ETag").length);
        String eTag = response.getHeaders("ETag")[0].getValue();

        // Get the Expires header
        assertNotNull(response.getHeaders("Expires"));
        assertEquals(1, response.getHeaders("Expires").length);
        Date expires = df.parse(response.getHeaders("Expires")[0].getValue());

        // Prepare the second request
        response.getEntity().consumeContent();
        httpClient.getConnectionManager().shutdown();

        // Give the cache time to persist the entry
        Thread.sleep(1000);

        httpClient = new DefaultHttpClient();

        request.setHeader("If-None-Match", eTag);
        request.setHeader("If-Modified-Since", df.format(System.currentTimeMillis()));

        response = TestUtils.request(httpClient, request, params);
        assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode());

        // Get the Expires header
        assertNotNull(response.getHeaders("Expires"));
        assertEquals(1, response.getHeaders("Expires").length);

        // We are explicitly not checking for equality with the previously
        // received value, since on first request, that value is not yet correct

        // Get the ETag header
        assertNotNull(response.getHeaders("ETag"));
        assertEquals(0, response.getHeaders("ETag").length);

        // Test the Cache header
        assertNotNull(response.getHeaders("X-Cache-Key"));
        assertEquals(1, response.getHeaders("X-Cache-Key").length);

        // Test the expires header
        Date newExpires = df.parse(response.getHeaders("Expires")[0].getValue());
        assertTrue(expires.before(newExpires) || expires.equals(newExpires));

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:ch.entwine.weblounge.test.harness.content.CacheTest.java

/**
 * Tests if the modification date matches that of the most recent element on a
 * page rather than the page's modification date.
 * /*from   ww w .j  ava2 s .c o  m*/
 * @param serverUrl
 *          the server url
 * @throws Exception
 *           if the test fails
 */
private void testInheritedModifcation(String serverUrl) throws Exception {
    logger.info("Preparing test of cache headers influenced by inherited updated content");

    DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
    df.setTimeZone(TimeZone.getTimeZone("GMT"));

    // Prepare the request
    logger.info("Gathering original modification date");

    String requestUrl = UrlUtils.concat(serverUrl, hostPage, language.getIdentifier());

    logger.info("Sending request to {}", requestUrl);
    HttpGet request = new HttpGet(requestUrl);
    request.addHeader("X-Cache-Debug", "yes");
    String[][] params = new String[][] { {} };

    // Send and the request and examine the response. Keep the modification
    // date.
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, request, params);

        int statusCode = response.getStatusLine().getStatusCode();
        boolean okOrNotModified = statusCode == HttpServletResponse.SC_OK
                || statusCode == HttpServletResponse.SC_NOT_MODIFIED;
        assertTrue(okOrNotModified);

        // Get the ETag header
        assertNotNull(response.getHeaders("ETag"));
        assertEquals(1, response.getHeaders("ETag").length);
        String hostOrignalETag = response.getHeaders("ETag")[0].getValue();

        // Get the Modified header
        assertNotNull(response.getHeaders("Last-Modified"));
        assertEquals(1, response.getHeaders("Last-Modified").length);
        Date hostModified = df.parse(response.getHeaders("Last-Modified")[0].getValue());
        response.getEntity().consumeContent();
        httpClient.getConnectionManager().shutdown();

        logger.info("Updating linked page");
        update(serverUrl, linkedPageId);

        // Give the cache time to persist the entry
        Thread.sleep(1000);

        httpClient = new DefaultHttpClient();

        // Test using ETag and modified header
        request.setHeader("If-None-Match", hostOrignalETag);
        request.setHeader("If-Modified-Since", df.format(hostModified));

        response = TestUtils.request(httpClient, request, params);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

        // Get the Expires header
        assertNotNull(response.getHeaders("Expires"));
        assertEquals(1, response.getHeaders("Expires").length);
        // We are explicitly not checking for equality with the previously
        // received value, since on first request, that value is not yet correct

        // Get the ETag header and make sure it has been updated
        assertNotNull(response.getHeaders("ETag"));
        assertEquals(1, response.getHeaders("ETag").length);
        assertFalse(hostOrignalETag.equals(response.getHeaders("ETag")[0].getValue()));

        // Test the modified header and make sure it has been updated
        assertNotNull(response.getHeaders("Last-Modified"));
        assertEquals(1, response.getHeaders("Last-Modified").length);
        Date newModified = df.parse(response.getHeaders("Last-Modified")[0].getValue());
        assertTrue(hostModified.before(newModified));

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.apache.falcon.workflow.WorkflowExecutionContext.java

/**
 * Returns timestamp as a long.//from  w w  w  . ja v  a 2  s.c o  m
 * @return Date as long (milliseconds since epoch) for the timestamp.
 */
public long getTimeStampAsLong() {
    String dateString = getTimestamp();
    try {
        DateFormat dateFormat = new SimpleDateFormat(INSTANCE_FORMAT.substring(0, dateString.length()));
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        return dateFormat.parse(dateString).getTime();
    } catch (java.text.ParseException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.ws.security.message.token.Timestamp.java

/**
 * Constructs a <code>Timestamp</code> object according
 * to the defined parameters./*from   w w  w  . j  a v  a 2  s. c o m*/
 *
 * @param doc the SOAP envelope as <code>Document</code>
 * @param ttl the time to live (validity of the security semantics) in seconds
 */
public Timestamp(boolean milliseconds, Document doc, int ttl) {

    customElements = new ArrayList<Element>();
    element = doc.createElementNS(WSConstants.WSU_NS,
            WSConstants.WSU_PREFIX + ":" + WSConstants.TIMESTAMP_TOKEN_LN);

    DateFormat zulu = null;
    if (milliseconds) {
        zulu = new XmlSchemaDateFormat();
    } else {
        zulu = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        zulu.setTimeZone(TimeZone.getTimeZone("UTC"));
    }
    Element elementCreated = doc.createElementNS(WSConstants.WSU_NS,
            WSConstants.WSU_PREFIX + ":" + WSConstants.CREATED_LN);
    createdDate = new Date();
    elementCreated.appendChild(doc.createTextNode(zulu.format(createdDate)));
    element.appendChild(elementCreated);
    if (ttl != 0) {
        expiresDate = new Date();
        expiresDate.setTime(createdDate.getTime() + ((long) ttl * 1000L));

        Element elementExpires = doc.createElementNS(WSConstants.WSU_NS,
                WSConstants.WSU_PREFIX + ":" + WSConstants.EXPIRES_LN);
        elementExpires.appendChild(doc.createTextNode(zulu.format(expiresDate)));
        element.appendChild(elementExpires);
    }
}

From source file:com.ternup.caddisfly.fragment.ResultFragment.java

public JSONObject getJson() {
    JSONObject object = new JSONObject();

    TimeZone tz = TimeZone.getTimeZone("UTC");
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
    df.setTimeZone(tz);
    String nowAsISO = df.format(new Date());

    try {/* w  w  w . j a va  2 s  . c om*/
        object.put("date", nowAsISO);
        object.put("test", Integer.valueOf(1));
        object.put("value", Double.valueOf(12.334232));
        object.put("method", Integer.valueOf(1));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return object;
}

From source file:com.microsoft.azure.storage.core.Utility.java

/**
 * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it
 * with up to millisecond precision. /*  ww w .j a  v a 2s .  co m*/
 * 
 * @param dateString
 *              the <code>String</code> to be interpreted as a <code>Date</code>
 *              
 * @return the corresponding <code>Date</code> object
 */
public static Date parseDate(String dateString) {
    String pattern = MAX_PRECISION_PATTERN;
    switch (dateString.length()) {
    case 28: // "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"-> [2012-01-04T23:21:59.1234567Z] length = 28
    case 27: // "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"-> [2012-01-04T23:21:59.123456Z] length = 27
    case 26: // "yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'"-> [2012-01-04T23:21:59.12345Z] length = 26
    case 25: // "yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'"-> [2012-01-04T23:21:59.1234Z] length = 25
    case 24: // "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"-> [2012-01-04T23:21:59.123Z] length = 24
        dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH);
        break;
    case 23: // "yyyy-MM-dd'T'HH:mm:ss.SS'Z'"-> [2012-01-04T23:21:59.12Z] length = 23
        // SS is assumed to be milliseconds, so a trailing 0 is necessary
        dateString = dateString.replace("Z", "0");
        break;
    case 22: // "yyyy-MM-dd'T'HH:mm:ss.S'Z'"-> [2012-01-04T23:21:59.1Z] length = 22
        // S is assumed to be milliseconds, so trailing 0's are necessary
        dateString = dateString.replace("Z", "00");
        break;
    case 20: // "yyyy-MM-dd'T'HH:mm:ss'Z'"-> [2012-01-04T23:21:59Z] length = 20
        pattern = Utility.ISO8601_PATTERN;
        break;
    case 17: // "yyyy-MM-dd'T'HH:mm'Z'"-> [2012-01-04T23:21Z] length = 17
        pattern = Utility.ISO8601_PATTERN_NO_SECONDS;
        break;
    default:
        throw new IllegalArgumentException(String.format(SR.INVALID_DATE_STRING, dateString));
    }

    final DateFormat format = new SimpleDateFormat(pattern, Utility.LOCALE_US);
    format.setTimeZone(UTC_ZONE);
    try {
        return format.parse(dateString);
    } catch (final ParseException e) {
        throw new IllegalArgumentException(String.format(SR.INVALID_DATE_STRING, dateString), e);
    }
}

From source file:org.callimachusproject.behaviours.AuthenticationManagerSupport.java

public HttpResponse openIDProviderReturn(String parameters, String identity)
        throws OpenRDFException, IOException, GeneralSecurityException {
    Map<String, String> map = keyByName(parameters);
    String return_to = map.get("openid.return_to");
    StringBuilder sb = new StringBuilder();
    if (return_to != null && return_to.length() > 0) {
        String self = this.getResource().stringValue();
        StringBuilder hash = new StringBuilder(identity);
        String[] nameEmail = getNameEmail(identity);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        String now = df.format(new Date());
        sb.append(return_to);
        if (return_to.indexOf('?') >= 0) {
            sb.append('&');
        } else {/*from   ww  w . j a  v  a2  s .  co  m*/
            sb.append('?');
        }
        sb.append("openid.ns=http://specs.openid.net/auth/2.0");
        sb.append("&openid.mode=id_res");
        if (nameEmail != null) {
            sb.append("&openid.ns.ax=http://openid.net/srv/ax/1.0");
            sb.append("&openid.ax.mode=fetch_response");
            sb.append("&openid.ax.type.email=http://axschema.org/contact/email");
            sb.append("&openid.ax.type.fullname=http://axschema.org/namePerson");
            sb.append("&openid.ax.value.email=").append(encode(nameEmail[1]));
            sb.append("&openid.ax.value.fullname=").append(encode(nameEmail[0]));
            hash.append(':').append(nameEmail[0]).append(':').append(nameEmail[1]);
        }
        String response_nonce = now + hash(hash.toString(), "MD5");
        StringBuilder sig = new StringBuilder();
        sig.append("openid.op_endpoint=").append(encode(self));
        sig.append("&openid.identity=").append(encode(identity));
        sig.append("&openid.claimed_id=").append(encode(identity));
        sig.append("&openid.return_to=").append(encode(return_to));
        sig.append("&openid.response_nonce=").append(encode(response_nonce));
        sb.append("&").append(sig);
        sb.append("&openid.signed=").append("op_endpoint,identity,claimed_id,return_to,response_nonce");
        sb.append("&openid.sig=").append(encode(sig(sig.toString())));
    } else {
        sb.append("/");
    }
    String location = sb.toString();
    BasicHttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, 303, "See Other");
    resp.setHeader("Location", location);
    resp.setHeader("Cache-Control", "no-store");
    resp.setHeader("Content-Type", "text/plain");
    resp.setEntity(new StringEntity(location));
    return resp;

}

From source file:gov.wa.wsdot.android.wsdot.ui.amtrakcascades.AmtrakCascadesSchedulesActivity.java

/**
 * //from  ww  w . j a  v a 2  s .co m
 */
@SuppressLint("SimpleDateFormat")
private void getDaysOfWeek() {
    DateFormat dayOfWeekFormat = new SimpleDateFormat("EEEE");
    DateFormat statusDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dayOfWeekFormat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
    statusDateFormat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
    daySpinner = findViewById(R.id.day_spinner);
    List<String> daysOfWeek = new ArrayList<String>();

    Date startDate = new Date();

    for (int i = 0; i < 7; i++) {
        Date nextDay = new Date(startDate.getTime() + i * 24 * 3600 * 1000);
        daysOfWeek.add(dayOfWeekFormat.format(nextDay));
        daysOfWeekMap.put(dayOfWeekFormat.format(nextDay), statusDateFormat.format(nextDay));
    }

    ArrayAdapter<String> dayOfWeekArrayAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, daysOfWeek);

    dayOfWeekArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    daySpinner.setAdapter(dayOfWeekArrayAdapter);
}

From source file:org.apache.falcon.entity.FileSystemStorage.java

private void fileSystemEvictor(String feedPath, String retentionLimit, TimeZone timeZone, Path logFilePath)
        throws IOException, ELException, FalconException {
    Path normalizedPath = new Path(feedPath);
    FileSystem fs = HadoopClientFactory.get().createProxiedFileSystem(normalizedPath.toUri());
    feedPath = normalizedPath.toUri().getPath();
    LOG.info("Normalized path: {}", feedPath);

    Pair<Date, Date> range = EvictionHelper.getDateRange(retentionLimit);

    List<Path> toBeDeleted = discoverInstanceToDelete(feedPath, timeZone, range.first, fs);
    if (toBeDeleted.isEmpty()) {
        LOG.info("No instances to delete.");
        return;/*  ww w.j  ava 2  s.c o m*/
    }

    DateFormat dateFormat = new SimpleDateFormat(FeedHelper.FORMAT);
    dateFormat.setTimeZone(timeZone);
    Path feedBasePath = fs.makeQualified(FeedHelper.getFeedBasePath(feedPath));
    for (Path path : toBeDeleted) {
        deleteInstance(fs, path, feedBasePath);
        Date date = FeedHelper.getDate(feedPath, new Path(path.toUri().getPath()), timeZone);
        instanceDates.append(dateFormat.format(date)).append(',');
        instancePaths.append(path).append(EvictedInstanceSerDe.INSTANCEPATH_SEPARATOR);
    }
}