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:de.ingrid.interfaces.csw.server.impl.GenericServer.java

@Override
public Document process(GetRecordsRequest request) throws CSWException {
    try {/*from   ww  w. j a va  2  s. c  om*/
        CSWQuery query = request.getQuery();
        CSWRecordResults result = this.searcher.search(query);

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        DOMImplementation domImpl = docBuilder.getDOMImplementation();
        Document doc = domImpl.createDocument(RESPONSE_NAMESPACE, "csw:GetRecordsResponse", null);

        Element searchStatus = doc.createElementNS(RESPONSE_NAMESPACE, "csw:SearchStatus");

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone("ThreeLetterISO8601TimeZone"));
        searchStatus.setAttribute("timestamp", df.format(new Date()));
        doc.getDocumentElement().appendChild(searchStatus);

        Element searchResults = doc.createElementNS(RESPONSE_NAMESPACE, "csw:SearchResults");
        searchResults.setAttribute("elementSet", request.getQuery().getElementSetName().name().toLowerCase());
        searchResults.setAttribute("numberOfRecordsMatched", String.valueOf(result.getTotalHits()));
        searchResults.setAttribute("numberOfRecordsReturned",
                String.valueOf((result.getResults() == null) ? 0 : result.getResults().size()));
        int nextRecord = query.getStartPosition()
                + ((result.getResults() == null) ? 0 : result.getResults().size());
        if (nextRecord > result.getTotalHits()) {
            nextRecord = 0;
        }
        searchResults.setAttribute("nextRecord", String.valueOf(nextRecord));
        doc.getDocumentElement().appendChild(searchResults);

        if (query.getResultType() == ResultType.RESULTS && result.getResults() != null) {
            for (CSWRecord record : result.getResults()) {
                Node recordNode = record.getDocument().getFirstChild();
                doc.adoptNode(recordNode);
                searchResults.appendChild(recordNode);
            }
        }
        return doc;
    } catch (CSWException ex) {
        log.error("An error occured processing GetRecordsRequest", ex);
        throw ex;
    } catch (Exception ex) {
        log.error("An error occured processing GetRecordsRequest", ex);
        throw new CSWException("An error occured processing GetRecordsRequest");
    }
}

From source file:org.mot.common.util.DateBuilder.java

public String getTimeStampWithPattern(String pattern, String timezone) {

    Date date = new Date();
    DateFormat df = new SimpleDateFormat(pattern);

    df.setTimeZone(TimeZone.getTimeZone(timezone));

    return df.format(date);
}

From source file:com.clustercontrol.snmp.factory.RunMonitorSnmp.java

/**
 * OID?//from  www  .  jav  a2 s.c  o  m
 * 
 * @param facilityId ID
 * @return ???????true
 * @throws HinemosUnknown
 */
@Override
public boolean collect(String facilityId) throws HinemosUnknown {

    if (m_now != null) {
        m_nodeDate = m_now.getTime();
    }
    m_value = 0;

    // 
    m_message = "";
    m_messageOrg = MessageConstant.OID.getMessage() + " : " + m_snmpOid;

    NodeInfo info = null;
    try {
        // ??
        info = new RepositoryControllerBean().getNode(facilityId);
    } catch (FacilityNotFound e) {
        m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NODE_ATTRIBUTES.getMessage();
        m_messageOrg = m_messageOrg + " (" + e.getMessage() + ")";
        resetCache(m_monitorId, facilityId);
        return false;
    }

    // SNMP?
    RequestSnmp4j m_request = new RequestSnmp4j();

    m_log.debug("version=" + info.getSnmpVersion());
    boolean result = false;
    try {
        result = m_request.polling(info.getAvailableIpAddress(), info.getSnmpCommunity(), info.getSnmpPort(),
                m_snmpOid, info.getSnmpVersion(), info.getSnmpTimeout(), info.getSnmpRetryCount(),
                info.getSnmpSecurityLevel(), info.getSnmpUser(), info.getSnmpAuthPassword(),
                info.getSnmpPrivPassword(), info.getSnmpAuthProtocol(), info.getSnmpPrivProtocol());
    } catch (Exception e) {
        m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NODE_ATTRIBUTES.getMessage();
        m_messageOrg = m_message + ", " + e.getMessage() + " (" + e.getClass().getName() + ")";
        if (e instanceof NumberFormatException) {
            m_log.warn(m_messageOrg);
        } else {
            m_log.warn(m_messageOrg, e);
        }
        resetCache(m_monitorId, facilityId);
        return false;
    }

    if (result) {

        // ??
        double value = -1;
        try {
            if (m_request.getValue() == null) {
                m_log.debug("collect() : m_request.getValue() is null");
                return false;
            }
            value = Double.parseDouble(m_request.getValue());
        } catch (NumberFormatException e) {
            m_log.info("collect() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
            String[] args = { m_request.getValue() };
            m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NUMERIC_VALUE.getMessage(args);
            resetCache(m_monitorId, facilityId);
            return false;
        } catch (Exception e) {
            m_log.warn("collect() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
            String[] args = { m_request.getValue() };
            m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NUMERIC_VALUE.getMessage(args);
            resetCache(m_monitorId, facilityId);
            return false;
        }
        long date = m_request.getDate();

        // ????
        if (m_convertFlg == ConvertValueConstant.TYPE_NO) {
            m_value = value;
            m_nodeDate = date;
        }
        // ??
        else if (m_convertFlg == ConvertValueConstant.TYPE_DELTA) {
            // ??
            MonitorSnmpValue valueEntity = null;
            Double prevValue = 0d;
            Long prevDate = 0l;
            if (!m_isMonitorJob) {
                // ??
                // cache??
                valueEntity = MonitorSnmpCache.getMonitorSnmpValue(m_monitorId, facilityId);

                // ???
                prevValue = valueEntity.getValue();
                if (valueEntity.getGetDate() != null) {
                    prevDate = valueEntity.getGetDate();
                }
            } else {
                // ??
                valueEntity = new MonitorSnmpValue(new MonitorSnmpValuePK(m_monitorId, facilityId));
                if (m_prvData instanceof MonitorSnmpValue) {
                    // ????
                    prevValue = ((MonitorSnmpValue) m_prvData).getValue();
                    prevDate = ((MonitorSnmpValue) m_prvData).getGetDate();
                }
            }

            if (prevValue != null) {
                if (prevValue > value) {
                    if (m_request.getType() == SMIConstants.SYNTAX_COUNTER32) {
                        value += ((double) Integer.MAX_VALUE + 1) * 2;
                    } else if (m_request.getType() == SMIConstants.SYNTAX_COUNTER64) {
                        value += ((double) Long.MAX_VALUE + 1) * 2;
                    }
                }
            }

            // SNMP????
            valueEntity.setValue(Double.valueOf(value));
            valueEntity.setGetDate(date);

            if (!m_isMonitorJob) {
                // ???ID?????
                if (m_monitor.getMonitorFlg())
                    MonitorSnmpCache.update(m_monitorId, facilityId, valueEntity);

                // ???SNMP????????
                int tolerance = (m_runInterval + SnmpProperties.getProperties().getValidSecond()) * 1000;

                if (prevDate > date - tolerance) {

                    // ??null???
                    if (prevValue == null) {
                        m_log.debug("collect() : prevValue is null");
                        return false;
                    }

                    m_value = value - prevValue;
                    m_nodeDate = m_request.getDate();
                } else {
                    if (prevDate != 0l) {
                        DateFormat df = DateFormat.getDateTimeInstance();
                        df.setTimeZone(HinemosTime.getTimeZone());
                        String[] args = { df.format(new Date(prevDate)) };
                        m_message = MessageConstant.MESSAGE_TOO_OLD_TO_CALCULATE.getMessage(args);
                        return false;
                    } else {
                        // ???0??
                        m_nodeDate = 0l;
                    }
                }
            } else {
                m_value = value - prevValue;
                m_nodeDate = m_request.getDate();
                m_curData = valueEntity;
            }

        }
        m_message = MessageConstant.SELECT_VALUE.getMessage() + " : " + m_value;
    } else {
        m_message = m_request.getMessage();
        resetCache(m_monitorId, facilityId);
    }
    return result;
}

From source file:org.sakaiproject.assignment2.logic.impl.ExternalLogicImpl.java

public void setLocalTimeZone(DateFormat df) {
    if (df != null) {
        df.setTimeZone(timeService.getLocalTimeZone());
    }
}

From source file:org.agiso.tempel.Tempel.java

/**
 * /*w w w. j  a  v a 2s. co  m*/
 * 
 * @param properties
 * @throws Exception 
 */
private Map<String, Object> addRuntimeProperties(Map<String, Object> properties) throws Exception {
    Map<String, Object> props = new HashMap<String, Object>();

    // Okrelanie lokalizacji daty/czasu uywanej do wypenienia paramtrw szablonw
    // zawierajcych dat/czas w formatach DateFormat.SHORT, .MEDIUM, .LONG i .FULL:
    Locale date_locale;
    if (properties.containsKey(UP_DATE_LOCALE)) {
        date_locale = LocaleUtils.toLocale((String) properties.get(UP_DATE_LOCALE));
        Locale.setDefault(date_locale);
    } else {
        date_locale = Locale.getDefault();
    }

    TimeZone time_zone;
    if (properties.containsKey(UP_TIME_ZONE)) {
        time_zone = TimeZone.getTimeZone((String) properties.get(UP_DATE_LOCALE));
        TimeZone.setDefault(time_zone);
    } else {
        time_zone = TimeZone.getDefault();
    }

    // Wyznaczanie daty, na podstawie ktrej zostan wypenione parametry szablonw
    // przechowujce dat/czas w formatach DateFormat.SHORT, .MEDIUM, .LONG i .FULL.
    // Odbywa si w oparciu o wartoci parametrw 'date_format' i 'date'. Parametr
    // 'date_format' definiuje format uywany do parsowania acucha reprezentujcego
    // dat okrelon parametrem 'date'. Parametr 'date_format' moe nie by okrelony.
    // W takiej sytuacji uyty jest format DateFormat.LONG aktywnej lokalizacji (tj.
    // systemowej, ktra moe by przedefiniowana przez parametr 'date_locale'), ktry
    // moe by przedefiniowany przez parametry 'date_format_long' i 'time_format_long':
    Calendar calendar = Calendar.getInstance(date_locale);
    if (properties.containsKey(RP_DATE)) {
        String date_string = (String) properties.get(RP_DATE);
        if (properties.containsKey(RP_DATE_FORMAT)) {
            String date_format = (String) properties.get(RP_DATE_FORMAT);
            DateFormat formatter = new SimpleDateFormat(date_format);
            formatter.setTimeZone(time_zone);
            calendar.setTime(formatter.parse(date_string));
        } else if (properties.containsKey(UP_DATE_FORMAT_LONG) && properties.containsKey(UP_TIME_FORMAT_LONG)) {
            // TODO: Zaoenie, e format data-czas jest zoony z acucha daty i czasu rozdzelonych spacj:
            // 'UP_DATE_FORMAT_LONG UP_TIME_FORMAT_LONG'
            DateFormat formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_LONG) + " "
                    + (String) properties.get(UP_TIME_FORMAT_LONG), date_locale);
            formatter.setTimeZone(time_zone);
            calendar.setTime(formatter.parse(date_string));
        } else {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG,
                    date_locale);
            formatter.setTimeZone(time_zone);
            calendar.setTime(formatter.parse(date_string));
        }
    }

    // Jeli nie okrelono, wypenianie parametrw przechowujcych poszczeglne
    // skadniki daty, tj. rok, miesic i dzie:
    if (!properties.containsKey(TP_YEAR)) {
        props.put(TP_YEAR, calendar.get(Calendar.YEAR));
    }
    if (!properties.containsKey(TP_MONTH)) {
        props.put(TP_MONTH, calendar.get(Calendar.MONTH));
    }
    if (!properties.containsKey(TP_DAY)) {
        props.put(TP_DAY, calendar.get(Calendar.DAY_OF_MONTH));
    }

    // Jeli nie okrelono, wypenianie parametrw przechowujcych dat i czas w
    // formatach SHORT, MEDIUM, LONG i FULL (na podstawie wyznaczonej lokalizacji):
    Date date = calendar.getTime();
    if (!properties.containsKey(TP_DATE_SHORT)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_SHORT)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_SHORT), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.SHORT, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_SHORT, formatter.format(date));
    }
    if (!properties.containsKey(TP_DATE_MEDIUM)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_MEDIUM)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_MEDIUM), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_MEDIUM, formatter.format(date));
    }
    if (!properties.containsKey(TP_DATE_LONG)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_LONG)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_LONG), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.LONG, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_LONG, formatter.format(date));
    }
    if (!properties.containsKey(TP_DATE_FULL)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_FULL)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_FULL), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.FULL, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_FULL, formatter.format(date));
    }

    if (!properties.containsKey(TP_TIME_SHORT)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_SHORT)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_SHORT), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.SHORT, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_SHORT, formatter.format(date));
    }
    if (!properties.containsKey(TP_TIME_MEDIUM)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_MEDIUM)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_MEDIUM), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.MEDIUM, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_MEDIUM, formatter.format(date));
    }
    if (!properties.containsKey(TP_TIME_LONG)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_LONG)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_LONG), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.LONG, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_LONG, formatter.format(date));
    }
    if (!properties.containsKey(TP_TIME_FULL)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_FULL)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_FULL), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.FULL, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_FULL, formatter.format(date));
    }

    return props;
}

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

/**
 * Tests if the modification date of a page can properly be adjusted by a
 * pagelet that is using the <code>&lt;modified&gt;</code> tag.
 * /*  w  w w . jav a  2s .co m*/
 * @param serverUrl
 *          the server url
 * @throws Exception
 *           if the test fails
 */
private void testPageletModifcationDate(String serverUrl) throws Exception {
    logger.info("Preparing test of cache headers influenced by the 'modified' tag");

    // Load the page's modification date

    String requestUrl = UrlUtils.concat(serverUrl, "system/weblounge/pages", modificationTestPageId);
    HttpGet getPageRequest = new HttpGet(requestUrl);
    HttpClient httpClient = new DefaultHttpClient();
    Page page = null;
    logger.info("Requesting the page's modification date at {}", requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, getPageRequest, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        PageReader reader = new PageReader();
        page = reader.read(response.getEntity().getContent(), site);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

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

    // Regularly load the page

    requestUrl = UrlUtils.concat(serverUrl, modificationTestPage);

    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 = 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 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();

        // Make sure the page is advertised as being more recent than the page's
        // modification date
        assertTrue(hostModified.after(page.getModificationDate()));

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

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

/**
 * Returns the GTM date/time String for the specified value using the RFC1123 pattern.
 * /*from  www.ja v  a2  s. c  o  m*/
 * @param date
 *            A <code>Date</code> object that represents the date to convert to GMT date/time in the RFC1123
 *            pattern.
 * 
 * @return A <code>String</code> that represents the GMT date/time for the specified value using the RFC1123
 *         pattern.
 */
public static String getGMTTime(final Date date) {
    final DateFormat formatter = new SimpleDateFormat(RFC1123_PATTERN, LOCALE_US);
    formatter.setTimeZone(GMT_ZONE);
    return formatter.format(date);
}

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

/**
 * Returns the UTC date/time String for the specified value using Java's version of the ISO8601 pattern,
 * which is limited to millisecond precision.
 * /* w  w  w  .  j  av a 2s  . com*/
 * @param date
 *            A <code>Date</code> object that represents the date to convert to UTC date/time in Java's version
 *            of the ISO8601 pattern.
 * 
 * @return A <code>String</code> that represents the UTC date/time for the specified value using Java's version
 *            of the ISO8601 pattern.
 */
public static String getJavaISO8601Time(Date date) {
    final DateFormat formatter = new SimpleDateFormat(JAVA_ISO8601_PATTERN, LOCALE_US);
    formatter.setTimeZone(UTC_ZONE);
    return formatter.format(date);
}

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

/**
 * Returns a GMT date for the specified string in the RFC1123 pattern.
 * /*  w w w .  j  a  v a 2  s . c o m*/
 * @param value
 *            A <code>String</code> that represents the string to parse.
 * 
 * @return A <code>Date</code> object that represents the GMT date in the RFC1123 pattern.
 * 
 * @throws ParseException
 *             If the specified string is invalid.
 */
public static Date parseRFC1123DateFromStringInGMT(final String value) throws ParseException {
    final DateFormat format = new SimpleDateFormat(RFC1123_PATTERN, Utility.LOCALE_US);
    format.setTimeZone(GMT_ZONE);
    return format.parse(value);
}

From source file:org.apache.jena.graph.test.TestTypedLiterals.java

private static Date getDateFromPattern(String ts, String[] formats, TimeZone tz) throws Exception {
    java.util.Date date = null;//from  w w w  .j a va 2s.co m
    java.text.DateFormat sdf = java.text.DateFormat.getInstance();
    {
        sdf.setTimeZone(tz == null ? java.util.TimeZone.getDefault() : tz);
        for (int i = 0; date == null && i < formats.length; i++) {
            ((java.text.SimpleDateFormat) sdf).applyPattern(formats[i]);
            try {
                date = sdf.parse(ts);
            } catch (java.text.ParseException pe) {
            } // keep trying
        }
    }
    return date;
}