List of usage examples for org.joda.time DateTimeZone forID
@FromString public static DateTimeZone forID(String id)
From source file:org.ohmage.domain.Location.java
License:Apache License
/** * Creates a Location object from a Jackson JsonNode. * /*from ww w . j a v a 2 s .c om*/ * @param locationNode The location JsonNode. * * @throws DomainException The node was invalid. */ public Location(final JsonNode locationNode) throws DomainException { if (locationNode == null) { throw new DomainException("The location node is null."); } List<DateTime> timestampRepresentations = new LinkedList<DateTime>(); // Get the timestamp if the time and timezone fields were // specified. if (locationNode.has("time")) { JsonNode timeNode = locationNode.get("time"); if (!timeNode.isNumber()) { throw new DomainException("The time isn't a number."); } long time = timeNode.getNumberValue().longValue(); DateTimeZone timeZone = DateTimeZone.UTC; if (locationNode.has("timezone")) { JsonNode timeZoneNode = locationNode.get("timezone"); if (!timeZoneNode.isTextual()) { throw new DomainException("The time zone is not a string."); } try { timeZone = DateTimeZone.forID(timeZoneNode.getTextValue()); } catch (IllegalArgumentException e) { throw new DomainException("The time zone is unknown."); } } timestampRepresentations.add(new DateTime(time, timeZone)); } // Get the timestamp if the timestamp field was specified. if (locationNode.has("timestamp")) { JsonNode timestampNode = locationNode.get("timestamp"); if (!timestampNode.isTextual()) { throw new DomainException("The timestamp value was not a string."); } try { timestampRepresentations .add(ISOW3CDateTimeFormat.any().parseDateTime(timestampNode.getTextValue())); } catch (IllegalArgumentException e) { throw new DomainException("The timestamp was not a valid ISO 8601 timestamp.", e); } } // Ensure that all representations of time are equal. if (timestampRepresentations.size() > 0) { // Create an iterator to cycle through the representations. Iterator<DateTime> timestampRepresentationsIter = timestampRepresentations.iterator(); // The first timestamp will be set as the result. DateTime timestamp = timestampRepresentationsIter.next(); // Check against all subsequent timestamps to ensure that // they represent the same point in time. while (timestampRepresentationsIter.hasNext()) { if (timestamp.getMillis() != timestampRepresentationsIter.next().getMillis()) { throw new DomainException( "Multiple representations of the timestamp were given, and they are not equal."); } } // If we checked out all of the timestamps and they are // equal, then save this timestamp. this.timestamp = timestamp; } else { throw new DomainException("The timestamp is missing."); } /* // Get the time. JsonNode timeNode = locationNode.get("time"); if(timeNode == null) { throw new DomainException("The time is missing."); } else if(! timeNode.isNumber()) { throw new DomainException("The time is not a number."); } time = timeNode.getNumberValue().longValue(); // Get the time zone. JsonNode timeZoneNode = locationNode.get("timezone"); if(timeZoneNode == null) { throw new DomainException("The time zone is missing."); } else if(! timeZoneNode.isTextual()) { throw new DomainException("The time zone is not a string."); } try { timeZone = DateTimeZone.forID(timeZoneNode.getTextValue()); } catch(IllegalArgumentException e) { throw new DomainException("The time zone is unknown."); } */ // Get the latitude. JsonNode latitudeNode = locationNode.get("latitude"); if (latitudeNode == null) { throw new DomainException("The latitude is missing."); } else if (!latitudeNode.isNumber()) { throw new DomainException("The latitude is not a number."); } latitude = latitudeNode.getNumberValue().doubleValue(); // Get the longitude. JsonNode longitudeNode = locationNode.get("longitude"); if (longitudeNode == null) { throw new DomainException("The longitude is missing."); } else if (!longitudeNode.isNumber()) { throw new DomainException("The longitude is not a number."); } longitude = longitudeNode.getNumberValue().doubleValue(); // Get the accuracy. JsonNode accuracyNode = locationNode.get("accuracy"); if (accuracyNode == null) { throw new DomainException("The accuracy is missing."); } else if (!accuracyNode.isNumber()) { throw new DomainException("The accuracy is not a number."); } accuracy = accuracyNode.getNumberValue().doubleValue(); // Get the provider. JsonNode providerNode = locationNode.get("provider"); if (providerNode == null) { throw new DomainException("The provider is missing."); } else if (!providerNode.isTextual()) { throw new DomainException("The provider is not a string."); } provider = providerNode.getTextValue(); }
From source file:org.ohmage.query.impl.UserMobilityQueries.java
License:Apache License
@Override public List<MobilityPoint> getMobilityInformation(final String username, final DateTime startDate, final DateTime endDate, final PrivacyState privacyState, final LocationStatus locationStatus, final Mode mode) throws DataAccessException { StringBuilder sqlBuilder = new StringBuilder(SQL_GET_MOBILITY_DATA); List<Object> parameters = new LinkedList<Object>(); parameters.add(username);/*from ww w . j ava 2 s . c o m*/ if (startDate != null) { sqlBuilder.append(SQL_WHERE_ON_OR_AFTER_DATE); parameters.add(startDate.getMillis()); } if (endDate != null) { sqlBuilder.append(SQL_WHERE_ON_OR_BEFORE_DATE); parameters.add(endDate.getMillis()); } if (privacyState != null) { sqlBuilder.append(SQL_WHERE_PRIVACY_STATE); parameters.add(privacyState.toString()); } if (locationStatus != null) { sqlBuilder.append(SQL_WHERE_LOCATION_STATUS); parameters.add(locationStatus.toString()); } if (mode != null) { sqlBuilder.append(SQL_WHERE_MODE); parameters.add(mode.toString().toLowerCase()); } sqlBuilder.append(SQL_ORDER_BY_DATE); try { return getJdbcTemplate().query(sqlBuilder.toString(), parameters.toArray(), new RowMapper<MobilityPoint>() { @Override public MobilityPoint mapRow(ResultSet rs, int rowNum) throws SQLException { try { JSONObject location = null; String locationString = rs.getString("location"); if (locationString != null) { location = new JSONObject(locationString); } JSONObject sensorData = null; String sensorDataString = rs.getString("sensor_data"); if (sensorDataString != null) { sensorData = new JSONObject(sensorDataString); } JSONObject features = null; String featuresString = rs.getString("features"); if (featuresString != null) { features = new JSONObject(featuresString); } return new MobilityPoint(UUID.fromString(rs.getString("uuid")), rs.getLong("epoch_millis"), DateTimeZone.forID(rs.getString("phone_timezone")), LocationStatus.valueOf(rs.getString("location_status").toUpperCase()), location, Mode.valueOf(rs.getString("mode").toUpperCase()), MobilityPoint.PrivacyState.getValue(rs.getString("privacy_state")), sensorData, features, rs.getString("classifier_version")); } catch (JSONException e) { throw new SQLException("Error building a JSONObject.", e); } catch (DomainException e) { throw new SQLException( "Error building the MobilityInformation object. This suggests malformed data in the database.", e); } catch (IllegalArgumentException e) { throw new SQLException( "Error building the MobilityInformation object. This suggests malformed data in the database.", e); } } }); } catch (org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + sqlBuilder.toString() + "' with parameters: " + parameters, e); } }
From source file:org.ohmage.query.impl.UserMobilityQueries.java
License:Apache License
@Override public List<MobilityAggregatePoint> getMobilityAggregateInformation(final String username, final DateTime startDate, final DateTime endDate) throws DataAccessException { StringBuilder sqlBuilder = new StringBuilder("SELECT m.epoch_millis, m.phone_timezone, m.mode " + "FROM user u, mobility m " + "WHERE u.username = ? " + "AND u.id = m.user_id"); List<Object> parameters = new LinkedList<Object>(); parameters.add(username);/*from ww w.j ava2 s .c o m*/ if (startDate != null) { sqlBuilder.append(SQL_WHERE_ON_OR_AFTER_DATE); parameters.add(startDate.getMillis()); } if (endDate != null) { sqlBuilder.append(SQL_WHERE_ON_OR_BEFORE_DATE); parameters.add(endDate.getMillis()); } sqlBuilder.append(SQL_ORDER_BY_DATE); try { return getJdbcTemplate().query(sqlBuilder.toString(), parameters.toArray(), new RowMapper<MobilityAggregatePoint>() { @Override public MobilityAggregatePoint mapRow(ResultSet rs, int rowNum) throws SQLException { try { return new MobilityAggregatePoint( new DateTime(rs.getLong("epoch_millis"), DateTimeZone.forID(rs.getString("phone_timezone"))), Mode.valueOf(rs.getString("mode").toUpperCase())); } catch (DomainException e) { throw new SQLException( "Error building the MobilityAggregatePoint object. This suggests malformed data in the database.", e); } } }); } catch (org.springframework.dao.DataAccessException e) { throw new DataAccessException( "Error executing SQL '" + sqlBuilder.toString() + "' with parameters: " + parameters, e); } }
From source file:org.ohmage.query.impl.UserMobilityQueries.java
License:Apache License
@Override public Set<DateTime> getDates(final DateTime startDate, final DateTime endDate, final String username) throws DataAccessException { List<Object> parameters = new ArrayList<Object>(3); parameters.add(username);// ww w.ja va 2s. c om parameters.add(startDate.getMillis()); parameters.add(endDate.getMillis()); try { return getJdbcTemplate().query( SQL_GET_MIN_MAX_MILLIS_FOR_USER_WITHIN_RANGE_GROUPED_BY_TIME_AND_TIMEZONE, parameters.toArray(), new ResultSetExtractor<Set<DateTime>>() { /** * Gathers the applicable dates based on their time * zone. */ @Override public Set<DateTime> extractData(ResultSet rs) throws SQLException, org.springframework.dao.DataAccessException { Set<DateTime> result = new HashSet<DateTime>(); while (rs.next()) { DateTimeZone timeZone = DateTimeZone.forID(rs.getString("time_zone")); result.add(new DateTime(rs.getLong("time"), timeZone)); } return result; } }); } catch (org.springframework.dao.DataAccessException e) { throw new DataAccessException("Error executing SQL '" + SQL_GET_MIN_MAX_MILLIS_FOR_USER_WITHIN_RANGE_GROUPED_BY_TIME_AND_TIMEZONE + "' with parameters: " + parameters, e); } }
From source file:org.ohmage.util.DateTimeUtils.java
License:Apache License
/** * Sanitizes and decodes a time zone string. * // ww w . j a va 2 s .c o m * @param timeZone The time zone to be decoded. * * @return The DateTimeZone that represents this time zone. * * @throws IllegalArgumentException The date time zone is invalid. */ public static DateTimeZone getDateTimeZoneFromString(final String timeZone) { if (timeZone == null) { return null; } try { return DateTimeZone.forID(timeZone); } catch (IllegalArgumentException e) { // This is acceptable if it starts with "GMT" or "UTC". if (timeZone.startsWith("GMT") || timeZone.startsWith("UTC")) { return DateTimeZone.forID(timeZone.substring(3)); } else { throw e; } } }
From source file:org.onebusaway.nextbus.impl.util.DateUtil.java
License:Apache License
public static List<Long> getWeekdayDateTimes(String timeZoneId) { List<Long> weekdayTimes = new ArrayList<Long>(); DateTimeZone timeZone = DateTimeZone.forID(timeZoneId); DateTime today = new DateTime(timeZone).withTimeAtStartOfDay(); weekdayTimes.add(today.withDayOfWeek(DateTimeConstants.MONDAY).getMillis() + 60000); weekdayTimes.add(today.withDayOfWeek(DateTimeConstants.TUESDAY).getMillis() + 60000); weekdayTimes.add(today.withDayOfWeek(DateTimeConstants.WEDNESDAY).getMillis() + 60000); weekdayTimes.add(today.withDayOfWeek(DateTimeConstants.THURSDAY).getMillis() + 60000); weekdayTimes.add(today.withDayOfWeek(DateTimeConstants.FRIDAY).getMillis() + 60000); return weekdayTimes; }
From source file:org.onebusaway.nextbus.impl.util.DateUtil.java
License:Apache License
public static List<Long> getWeekendDateTimes(String timeZoneId) { List<Long> weekendTimes = new ArrayList<Long>(); DateTimeZone timeZone = DateTimeZone.forID(timeZoneId); DateTime today = new DateTime(timeZone).withTimeAtStartOfDay(); weekendTimes.add(today.withDayOfWeek(DateTimeConstants.SATURDAY).getMillis() + 60000); weekendTimes.add(today.withDayOfWeek(DateTimeConstants.SUNDAY).getMillis() + 60000); return weekendTimes; }
From source file:org.openhab.io.caldav.internal.CalDavLoaderImpl.java
License:Open Source License
@Override public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true); // just temporary Map<String, CalDavConfig> configMap = new HashMap<String, CalDavConfig>(); Enumeration<String> iter = config.keys(); while (iter.hasMoreElements()) { String key = iter.nextElement(); log.trace("configuration parameter: " + key); if (key.equals("service.pid")) { continue; } else if (key.equals(PROP_TIMEZONE)) { log.debug("overriding default timezone {} with {}", defaultTimeZone, config.get(key)); defaultTimeZone = DateTimeZone.forID(config.get(key) + ""); if (defaultTimeZone == null) { throw new ConfigurationException(PROP_TIMEZONE, "invalid timezone value: " + config.get(key)); }//www. j a v a 2s .com log.debug("found timeZone: {}", defaultTimeZone); continue; } String[] keys = key.split(":"); if (keys.length != 2) { throw new ConfigurationException(key, "unknown identifier"); } String id = keys[0]; String paramKey = keys[1]; CalDavConfig calDavConfig = configMap.get(id); if (calDavConfig == null) { calDavConfig = new CalDavConfig(); configMap.put(id, calDavConfig); } String value = config.get(key) + ""; calDavConfig.setKey(id); if (paramKey.equals(PROP_USERNAME)) { calDavConfig.setUsername(value); } else if (paramKey.equals(PROP_PASSWORD)) { calDavConfig.setPassword(value); } else if (paramKey.equals(PROP_URL)) { calDavConfig.setUrl(value); } else if (paramKey.equals(PROP_RELOAD_INTERVAL)) { calDavConfig.setReloadMinutes(Integer.parseInt(value)); } else if (paramKey.equals(PROP_PRELOAD_TIME)) { calDavConfig.setPreloadMinutes(Integer.parseInt(value)); } else if (paramKey.equals(PROP_HISTORIC_LOAD_TIME)) { calDavConfig.setHistoricLoadMinutes(Integer.parseInt(value)); } else if (paramKey.equals(PROP_LAST_MODIFIED_TIMESTAMP_VALID)) { calDavConfig.setLastModifiedFileTimeStampValid(BooleanUtils.toBoolean(value)); } else if (paramKey.equals(PROP_DISABLE_CERTIFICATE_VERIFICATION)) { calDavConfig.setDisableCertificateVerification(BooleanUtils.toBoolean(value)); } else if (paramKey.equals(PROP_CHARSET)) { try { Charset.forName(value); calDavConfig.setCharset(value); } catch (UnsupportedCharsetException e) { log.error("charset not valid: {}", value); } } } // verify if all required parameters are set for (String id : configMap.keySet()) { if (configMap.get(id).getUrl() == null) { throw new ConfigurationException(PROP_URL, PROP_URL + " must be set"); } if (configMap.get(id).getUsername() == null) { throw new ConfigurationException(PROP_USERNAME, PROP_USERNAME + " must be set"); } if (configMap.get(id).getPassword() == null) { throw new ConfigurationException(PROP_PASSWORD, PROP_PASSWORD + " must be set"); } log.trace("config for id '{}': {}", id, configMap.get(id)); } // initialize event cache for (CalDavConfig calDavConfig : configMap.values()) { final CalendarRuntime eventRuntime = new CalendarRuntime(); eventRuntime.setConfig(calDavConfig); File cachePath = Util.getCachePath(calDavConfig.getKey()); if (!cachePath.exists() && !cachePath.mkdirs()) { log.error("cannot create directory ({}) for calendar caching (missing rights?)", cachePath.getAbsoluteFile()); continue; } EventStorage.getInstance().getEventCache().put(calDavConfig.getKey(), eventRuntime); } setProperlyConfigured(true); } }
From source file:org.openhab.io.caldav.internal.job.EventReloaderJob.java
License:Open Source License
private org.joda.time.DateTime getDateTime(String dateType, DateTime date, Date rangeDate) { org.joda.time.DateTime start;/*ww w . j a v a 2 s. c om*/ if (date.getTimeZone() == null) { if (date.isUtc()) { log.trace("{} is without timezone, but UTC", dateType); start = new org.joda.time.DateTime(rangeDate, DateTimeZone.UTC).toLocalDateTime() .toDateTime(CalDavLoaderImpl.defaultTimeZone); } else { log.trace("{} is without timezone, not UTC", dateType); start = new LocalDateTime(rangeDate).toDateTime(); } } else if (DateTimeZone.getAvailableIDs().contains(date.getTimeZone().getID())) { log.trace("{} is with known timezone: {}", dateType, date.getTimeZone().getID()); start = new org.joda.time.DateTime(rangeDate, DateTimeZone.forID(date.getTimeZone().getID())); } else { // unknown timezone log.trace("{} is with unknown timezone: {}", dateType, date.getTimeZone().getID()); start = new org.joda.time.DateTime(rangeDate, CalDavLoaderImpl.defaultTimeZone); } return start; }