Search in sources :

Example 1 with TimeZone

use of java.util.TimeZone in project jetty.project by eclipse.

the class JSONTest method testConvertor.

/* ------------------------------------------------------------ */
@Test
public void testConvertor() {
    // test case#1 - force timezone to GMT
    JSON json = new JSON();
    json.addConvertor(Date.class, new JSONDateConvertor("MM/dd/yyyy HH:mm:ss zzz", TimeZone.getTimeZone("GMT"), false));
    json.addConvertor(Object.class, new JSONObjectConvertor());
    Woggle w0 = new Woggle();
    Gizmo g0 = new Gizmo();
    w0.name = "woggle0";
    w0.nested = g0;
    w0.number = 100;
    g0.name = "woggle1";
    g0.nested = null;
    g0.number = -101;
    g0.tested = true;
    HashMap map = new HashMap();
    Date dummyDate = new Date(1);
    map.put("date", dummyDate);
    map.put("w0", w0);
    StringBuffer buf = new StringBuffer();
    json.append(buf, map);
    String js = buf.toString();
    assertTrue(js.indexOf("\"date\":\"01/01/1970 00:00:00 GMT\"") >= 0);
    assertTrue(js.indexOf("org.eclipse.jetty.util.ajax.JSONTest$Woggle") >= 0);
    assertTrue(js.indexOf("org.eclipse.jetty.util.ajax.JSONTest$Gizmo") < 0);
    assertTrue(js.indexOf("\"tested\":true") >= 0);
    // test case#3
    TimeZone tzone = TimeZone.getTimeZone("JST");
    String tzone3Letter = tzone.getDisplayName(false, TimeZone.SHORT);
    String format = "EEE MMMMM dd HH:mm:ss zzz yyyy";
    Locale l = new Locale("ja", "JP");
    if (l != null) {
        json.addConvertor(Date.class, new JSONDateConvertor(format, tzone, false, l));
        buf = new StringBuffer();
        json.append(buf, map);
        js = buf.toString();
        //assertTrue(js.indexOf("\"date\":\"木 1月 01 09:00:00 JST 1970\"")>=0);
        assertTrue(js.indexOf(" 01 09:00:00 JST 1970\"") >= 0);
        assertTrue(js.indexOf("org.eclipse.jetty.util.ajax.JSONTest$Woggle") >= 0);
        assertTrue(js.indexOf("org.eclipse.jetty.util.ajax.JSONTest$Gizmo") < 0);
        assertTrue(js.indexOf("\"tested\":true") >= 0);
    }
    // test case#4
    json.addConvertor(Date.class, new JSONDateConvertor(true));
    w0.nested = null;
    buf = new StringBuffer();
    json.append(buf, map);
    js = buf.toString();
    assertTrue(js.indexOf("\"date\":\"Thu Jan 01 00:00:00 GMT 1970\"") < 0);
    assertTrue(js.indexOf("org.eclipse.jetty.util.ajax.JSONTest$Woggle") >= 0);
    assertTrue(js.indexOf("org.eclipse.jetty.util.ajax.JSONTest$Gizmo") < 0);
    map = (HashMap) json.parse(new JSON.StringSource(js));
    assertTrue(map.get("date") instanceof Date);
    assertTrue(map.get("w0") instanceof Woggle);
}
Also used : Locale(java.util.Locale) TimeZone(java.util.TimeZone) HashMap(java.util.HashMap) Date(java.util.Date) Test(org.junit.Test)

Example 2 with TimeZone

use of java.util.TimeZone in project android-betterpickers by code-troopers.

the class TimeZoneData method loadTzsInZoneTab.

private HashSet<String> loadTzsInZoneTab(Context context) {
    HashSet<String> processedTimeZones = new HashSet<String>();
    AssetManager am = context.getAssets();
    InputStream is = null;
    /*
         * The 'backward' file contain mappings between new and old time zone
         * ids. We will explicitly ignore the old ones.
         */
    try {
        is = am.open("backward");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            // Skip comment lines
            if (!line.startsWith("#") && line.length() > 0) {
                // 0: "Link"
                // 1: New tz id
                // Last: Old tz id
                String[] fields = line.split("\t+");
                String newTzId = fields[1];
                String oldTzId = fields[fields.length - 1];
                final TimeZone tz = TimeZone.getTimeZone(newTzId);
                if (tz == null) {
                    Log.e(TAG, "Timezone not found: " + newTzId);
                    continue;
                }
                processedTimeZones.add(oldTzId);
                if (DEBUG) {
                    Log.e(TAG, "# Dropping identical time zone from backward: " + oldTzId);
                }
                // Remember the cooler/newer time zone id
                if (mDefaultTimeZoneId != null && mDefaultTimeZoneId.equals(oldTzId)) {
                    mAlternateDefaultTimeZoneId = newTzId;
                }
            }
        }
    } catch (IOException ex) {
        Log.e(TAG, "Failed to read 'backward' file.");
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ignored) {
        }
    }
    /*
         * zone.tab contains a list of time zones and country code. They are
         * "sorted first by country, then an order within the country that (1)
         * makes some geographical sense, and (2) puts the most populous zones
         * first, where that does not contradict (1)."
         */
    try {
        String lang = Locale.getDefault().getLanguage();
        is = am.open("zone.tab");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            if (!line.startsWith("#")) {
                // Skip comment lines
                // 0: country code
                // 1: coordinates
                // 2: time zone id
                // 3: comments
                final String[] fields = line.split("\t");
                final String timeZoneId = fields[2];
                final String countryCode = fields[0];
                final TimeZone tz = TimeZone.getTimeZone(timeZoneId);
                if (tz == null) {
                    Log.e(TAG, "Timezone not found: " + timeZoneId);
                    continue;
                }
                /*
                     * Dropping non-GMT tzs without a country code. They are not
                     * really needed and they are dups but missing proper
                     * country codes. e.g. WET CET MST7MDT PST8PDT Asia/Khandyga
                     * Asia/Ust-Nera EST
                     */
                if (countryCode == null && !timeZoneId.startsWith("Etc/GMT")) {
                    processedTimeZones.add(timeZoneId);
                    continue;
                }
                // Remember the mapping between the country code and display
                // name
                String country = mCountryCodeToNameMap.get(countryCode);
                if (country == null) {
                    country = getCountryNames(lang, countryCode);
                    mCountryCodeToNameMap.put(countryCode, country);
                }
                // Find the country of the default tz
                if (mDefaultTimeZoneId != null && mDefaultTimeZoneCountry == null && timeZoneId.equals(mAlternateDefaultTimeZoneId)) {
                    mDefaultTimeZoneCountry = country;
                    TimeZone defaultTz = TimeZone.getTimeZone(mDefaultTimeZoneId);
                    if (defaultTz != null) {
                        mDefaultTimeZoneInfo = new TimeZoneInfo(defaultTz, country);
                        int tzToOverride = getIdenticalTimeZoneInTheCountry(mDefaultTimeZoneInfo);
                        if (tzToOverride == -1) {
                            if (DEBUG) {
                                Log.e(TAG, "Adding default time zone: " + mDefaultTimeZoneInfo.toString());
                            }
                            mTimeZones.add(mDefaultTimeZoneInfo);
                        } else {
                            mTimeZones.add(tzToOverride, mDefaultTimeZoneInfo);
                            if (DEBUG) {
                                TimeZoneInfo tzInfoToOverride = mTimeZones.get(tzToOverride);
                                String tzIdToOverride = tzInfoToOverride.mTzId;
                                Log.e(TAG, "Replaced by default tz: " + tzInfoToOverride.toString());
                                Log.e(TAG, "Adding default time zone: " + mDefaultTimeZoneInfo.toString());
                            }
                        }
                    }
                }
                // Add to the list of time zones if the time zone is unique
                // in the given country.
                TimeZoneInfo timeZoneInfo = new TimeZoneInfo(tz, country);
                int identicalTzIdx = getIdenticalTimeZoneInTheCountry(timeZoneInfo);
                if (identicalTzIdx == -1) {
                    if (DEBUG) {
                        Log.e(TAG, "# Adding time zone: " + timeZoneId + " ## " + tz.getDisplayName());
                    }
                    mTimeZones.add(timeZoneInfo);
                } else {
                    if (DEBUG) {
                        Log.e(TAG, "# Dropping identical time zone: " + timeZoneId + " ## " + tz.getDisplayName());
                    }
                }
                processedTimeZones.add(timeZoneId);
            }
        }
    } catch (IOException ex) {
        Log.e(TAG, "Failed to read 'zone.tab'.");
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ignored) {
        }
    }
    return processedTimeZones;
}
Also used : TimeZone(java.util.TimeZone) AssetManager(android.content.res.AssetManager) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) HashSet(java.util.HashSet)

Example 3 with TimeZone

use of java.util.TimeZone in project hive by apache.

the class TestDateWritable method testDaylightSavingsTime.

@Test
public void testDaylightSavingsTime() throws Exception {
    LinkedList<DtMismatch> bad = new LinkedList<>();
    for (String timeZone : TimeZone.getAvailableIDs()) {
        TimeZone previousDefault = TimeZone.getDefault();
        TimeZone.setDefault(TimeZone.getTimeZone(timeZone));
        assertEquals("Default timezone should now be " + timeZone, timeZone, TimeZone.getDefault().getID());
        ExecutorService threadPool = Executors.newFixedThreadPool(1);
        try {
            // TODO: pointless
            threadPool.submit(new DateTestCallable(bad, timeZone)).get();
        } finally {
            threadPool.shutdown();
            TimeZone.setDefault(previousDefault);
        }
    }
    StringBuilder errors = new StringBuilder("\nDATE MISMATCH:\n");
    for (DtMismatch dm : bad) {
        errors.append("E ").append(dm.tz).append(": ").append(dm.expected).append(" != ").append(dm.found).append("\n");
    }
    LOG.error(errors.toString());
    if (!bad.isEmpty())
        throw new Exception(bad.size() + " mismatches, see logs");
}
Also used : TimeZone(java.util.TimeZone) ExecutorService(java.util.concurrent.ExecutorService) LinkedList(java.util.LinkedList) ExecutionException(java.util.concurrent.ExecutionException)

Example 4 with TimeZone

use of java.util.TimeZone in project pinot by linkedin.

the class SegmentMetadataImpl method toJson.

/**
   * Converts segment metadata to json
   * @param columnFilter list only  the columns in the set. Lists all the columns if
   *                     the parameter value is null
   * @return json representation of segment metadata
   */
public JSONObject toJson(@Nullable Set<String> columnFilter) throws JSONException {
    JSONObject rootMeta = new JSONObject();
    try {
        rootMeta.put("segmentName", _segmentName);
        rootMeta.put("schemaName", _schema != null ? _schema.getSchemaName() : JSONObject.NULL);
        rootMeta.put("crc", _crc);
        rootMeta.put("creationTimeMillis", _creationTime);
        TimeZone timeZone = TimeZone.getTimeZone("UTC");
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS' UTC'");
        dateFormat.setTimeZone(timeZone);
        String creationTimeStr = _creationTime != Long.MIN_VALUE ? dateFormat.format(new Date(_creationTime)) : "";
        rootMeta.put("creationTimeReadable", creationTimeStr);
        rootMeta.put("timeGranularitySec", _timeGranularity != null ? _timeGranularity.getStandardSeconds() : null);
        if (_timeInterval == null) {
            rootMeta.put("startTimeMillis", (String) null);
            rootMeta.put("startTimeReadable", "null");
            rootMeta.put("endTimeMillis", (String) null);
            rootMeta.put("endTimeReadable", "null");
        } else {
            rootMeta.put("startTimeMillis", _timeInterval.getStartMillis());
            rootMeta.put("startTimeReadable", _timeInterval.getStart().toString());
            rootMeta.put("endTimeMillis", _timeInterval.getEndMillis());
            rootMeta.put("endTimeReadable", _timeInterval.getEnd().toString());
        }
        rootMeta.put("pushTimeMillis", _pushTime);
        String pushTimeStr = _pushTime != Long.MIN_VALUE ? dateFormat.format(new Date(_pushTime)) : "";
        rootMeta.put("pushTimeReadable", pushTimeStr);
        rootMeta.put("refreshTimeMillis", _refreshTime);
        String refreshTimeStr = _refreshTime != Long.MIN_VALUE ? dateFormat.format(new Date(_refreshTime)) : "";
        rootMeta.put("refreshTimeReadable", refreshTimeStr);
        rootMeta.put("segmentVersion", _segmentVersion.toString());
        rootMeta.put("hasStarTree", hasStarTree());
        rootMeta.put("creatorName", _creatorName == null ? JSONObject.NULL : _creatorName);
        rootMeta.put("paddingCharacter", String.valueOf(_paddingCharacter));
        rootMeta.put("hllLog2m", _hllLog2m);
        JSONArray columnsJson = new JSONArray();
        ObjectMapper mapper = new ObjectMapper();
        for (String column : _allColumns) {
            if (columnFilter != null && !columnFilter.contains(column)) {
                continue;
            }
            ColumnMetadata columnMetadata = _columnMetadataMap.get(column);
            JSONObject columnJson = new JSONObject(mapper.writeValueAsString(columnMetadata));
            columnsJson.put(columnJson);
        }
        rootMeta.put("columns", columnsJson);
        return rootMeta;
    } catch (Exception e) {
        LOGGER.error("Failed to convert field to json for segment: {}", _segmentName, e);
        throw new RuntimeException("Failed to convert segment metadata to json", e);
    }
}
Also used : TimeZone(java.util.TimeZone) JSONObject(org.json.JSONObject) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) JSONArray(org.json.JSONArray) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) JSONException(org.json.JSONException) IOException(java.io.IOException) ConfigurationException(org.apache.commons.configuration.ConfigurationException)

Example 5 with TimeZone

use of java.util.TimeZone in project morphia by mongodb.

the class CalendarConverter method decode.

@Override
public Object decode(final Class type, final Object o, final MappedField mf) {
    if (o == null) {
        return null;
    }
    final List values = (List) o;
    if (values.size() < 2) {
        return null;
    }
    //-- date --//
    final Date utcDate = (Date) values.get(0);
    final long millis = utcDate.getTime();
    //-- TimeZone --//
    final String timeZoneId = (String) values.get(1);
    final TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
    //-- GregorianCalendar construction --//
    final GregorianCalendar calendar = new GregorianCalendar(timeZone);
    calendar.setTimeInMillis(millis);
    return calendar;
}
Also used : TimeZone(java.util.TimeZone) GregorianCalendar(java.util.GregorianCalendar) List(java.util.List) ArrayList(java.util.ArrayList) Date(java.util.Date)

Aggregations

TimeZone (java.util.TimeZone)1223 Date (java.util.Date)340 Calendar (java.util.Calendar)268 Test (org.junit.Test)243 Locale (java.util.Locale)168 SimpleDateFormat (java.text.SimpleDateFormat)160 SimpleTimeZone (java.util.SimpleTimeZone)124 GregorianCalendar (java.util.GregorianCalendar)120 DateFormat (java.text.DateFormat)65 ArrayList (java.util.ArrayList)62 ParseException (java.text.ParseException)48 IOException (java.io.IOException)41 LocalDate (java.time.LocalDate)35 List (java.util.List)31 HashMap (java.util.HashMap)30 Timestamp (java.sql.Timestamp)28 Map (java.util.Map)25 Test (org.junit.jupiter.api.Test)23 HashSet (java.util.HashSet)20 DfTypeUtil.toLocalDate (org.dbflute.util.DfTypeUtil.toLocalDate)18