List of usage examples for org.joda.time DateTimeZone forID
@FromString public static DateTimeZone forID(String id)
From source file:org.jahia.taglibs.functions.Functions.java
License:Open Source License
public static String formatISODate(java.lang.String dateToParse, String pattern, Locale locale) { try {//w w w .j av a 2s .c o m DateTime dateTime = ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(dateToParse); return DateTimeFormat.forPattern(pattern).withLocale(locale != null ? locale : Locale.ENGLISH) .print(!dateToParse.endsWith("Z") ? dateTime : dateTime.toDateTime(DateTimeZone.forID("UTC"))); } catch (Exception e) { logger.debug("Unable to parse date:" + dateToParse, e); return null; } }
From source file:org.jasig.cas.adaptors.ldap.lppe.AbstractLdapDateConverter.java
License:Apache License
public void setTimeZoneId(final String timeZoneId) { setTimeZone(DateTimeZone.forID(timeZoneId)); }
From source file:org.jasig.portlet.calendar.mvc.CalendarHelper.java
License:Apache License
public Set<CalendarDisplayEvent> getEventList(final List<String> errors, final Interval interval, final PortletRequest request) { final PortletSession session = request.getPortletSession(); /*//from ww w.j av a 2 s. com * Retrieve the calendar configurations defined for this user request * and sort them by display name. This sorting operation ensures that * the CSS color indices assigned to calendar events will be consistent * with the colors assigned in the main controller. */ // retrieve the calendars defined for this portlet instance CalendarSet<?> set = calendarSetDao.getCalendarSet(request); List<CalendarConfiguration> calendars = new ArrayList<CalendarConfiguration>(); calendars.addAll(set.getConfigurations()); // sort the calendars Collections.sort(calendars, new CalendarConfigurationByNameComparator()); // get the list of hidden calendars @SuppressWarnings("unchecked") HashMap<Long, String> hiddenCalendars = (HashMap<Long, String>) session.getAttribute("hiddenCalendars"); /* * For each unhidden calendar, get the list of associated events for * the requested time period. */ // get the user's configured time zone String timezone = (String) session.getAttribute("timezone"); DateTimeZone tz = DateTimeZone.forID(timezone); Set<CalendarDisplayEvent> events = new TreeSet<CalendarDisplayEvent>(); for (CalendarConfiguration callisting : calendars) { // don't bother to fetch hidden calendars if (hiddenCalendars.get(callisting.getId()) == null) { try { // get an instance of the adapter for this calendar ICalendarAdapter adapter = (ICalendarAdapter) applicationContext .getBean(callisting.getCalendarDefinition().getClassName()); events.addAll(calendarEventsDao.getEvents(adapter, callisting, interval, request, tz)); } catch (NoSuchBeanDefinitionException ex) { log.error("Calendar class instance could not be found: " + ex.getMessage()); } catch (UserFeedbackCalendarException sce) { // This CalendarException subclass carries a payload for the UI... StringBuilder msg = new StringBuilder(); msg.append(callisting.getCalendarDefinition().getName()).append(": ") .append(sce.getUserFeedback()); errors.add(msg.toString()); } catch (Exception ex) { log.warn("Unknown Error", ex); errors.add("The calendar \"" + callisting.getCalendarDefinition().getName() + "\" is currently unavailable."); } } } return events; }
From source file:org.jasig.portlet.calendar.mvc.controller.AjaxCalendarController.java
License:Apache License
@ResourceMapping public ModelAndView getEventList(ResourceRequest request, ResourceResponse response) throws Exception { // Pull parameters out of the resourceId final String resourceId = request.getResourceID(); final String[] resourceIdTokens = resourceId.split("-"); final String startDate = resourceIdTokens[0]; final int days = Integer.parseInt(resourceIdTokens[1]); final long startTime = System.currentTimeMillis(); final List<String> errors = new ArrayList<String>(); final Map<String, Object> model = new HashMap<String, Object>(); final PortletSession session = request.getPortletSession(); // get the user's configured time zone final String timezone = (String) session.getAttribute("timezone"); final DateTimeZone tz = DateTimeZone.forID(timezone); // get the period for this request final Interval interval = DateUtil.getInterval(startDate, days, request); final Set<CalendarDisplayEvent> calendarEvents = helper.getEventList(errors, interval, request); int index = 0; final Set<JsonCalendarEventWrapper> events = new TreeSet<JsonCalendarEventWrapper>(); for (CalendarDisplayEvent e : calendarEvents) { events.add(new JsonCalendarEventWrapper(e, index++)); }/* w w w . j a va2 s .c om*/ /* * Transform the event set into a map keyed by day. This code is * designed to separate events by day according to the user's configured * time zone. This ensures that we keep complicated time-zone handling * logic out of the JavaScript. * * Events are keyed by a string uniquely representing the date that is * still orderable. So that we can display a more user-friendly date * name, we also create a map representing date display names for each * date keyed in this response. */ // define a DateFormat object that uniquely identifies dates in a way // that can easily be ordered DateTimeFormatter orderableDf = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd").toFormatter() .withZone(tz); // define a DateFormat object that can produce user-facing display // as user-facing get it from i18N final String displayPattern = this.applicationContext.getMessage("date.formatter.display", null, "EEE MMM d", request.getLocale()); // names for dates DateTimeFormatter displayDf = new DateTimeFormatterBuilder().appendPattern(displayPattern).toFormatter() .withZone(tz); // define "today" and "tomorrow" so we can display these specially in the user interface DateMidnight now = new DateMidnight(tz); String today = orderableDf.print(now); String tomorrow = orderableDf.print(now.plusDays(1)); Map<String, String> dateDisplayNames = new HashMap<String, String>(); Map<String, List<JsonCalendarEventWrapper>> eventsByDay = new LinkedHashMap<String, List<JsonCalendarEventWrapper>>(); for (JsonCalendarEventWrapper event : events) { String day = orderableDf.print(event.getEvent().getDayStart()); // if we haven't seen this day before, add entries to the event and date name maps if (!eventsByDay.containsKey(day)) { // add a list for this day to the eventsByDay map eventsByDay.put(day, new ArrayList<JsonCalendarEventWrapper>()); // Add an appropriate day name for this date to the date names map. // If the day appears to be today or tomorrow display a special string value. // Otherwise, use the user-facing date format object. if (today.equals(day)) { dateDisplayNames.put(day, applicationContext.getMessage("today", null, "Today", request.getLocale())); } else if (tomorrow.equals(day)) { dateDisplayNames.put(day, this.applicationContext.getMessage("tomorrow", null, "Tomorrow", request.getLocale())); } else { dateDisplayNames.put(day, displayDf.print(event.getEvent().getDayStart())); } } // add the event to the by-day map eventsByDay.get(day).add(event); } log.trace("Prepared the following eventsByDay collection for user {}: {}", request.getRemoteUser(), eventsByDay); model.put("dateMap", eventsByDay); model.put("dateNames", dateDisplayNames); model.put("viewName", "jsonView"); model.put("errors", errors); // eTag processing, see https://wiki.jasig.org/display/UPM41/Portlet+Caching String etag = String.valueOf(model.hashCode()); String requestEtag = request.getETag(); // if the request ETag matches the hash for this response, send back // an empty response indicating that cached content should be used if (etag.equals(requestEtag)) { log.debug("Sending an empty response (due to matched ETag {} for user {})'", requestEtag, request.getRemoteUser()); // Must communicate new expiration time > 0 per Portlet Spec 22.2 response.getCacheControl().setExpirationTime(1); response.getCacheControl().setUseCachedContent(true); // Portal will return cached content or HTTP 304 // Return null so response is not committed before portal decides to return HTTP 304 or cached response. return null; } log.trace("Sending a full response for user {}", request.getRemoteUser()); // create new content with new validation tag response.getCacheControl().setETag(etag); // Must have expiration time > 0 to use response.getCacheControl().setUseCachedContent(true) response.getCacheControl().setExpirationTime(1); long overallTime = System.currentTimeMillis() - startTime; log.debug("AjaxCalendarController took {} ms to produce JSON model", overallTime); return new ModelAndView("json", model); }
From source file:org.jasig.portlet.calendar.mvc.controller.CalendarController.java
License:Apache License
@RequestMapping public ModelAndView getCalendar(@RequestParam(required = false, value = "interval") String intervalString, RenderRequest request) {// w w w .j a va2s .c o m PortletSession session = request.getPortletSession(true); PortletPreferences prefs = request.getPreferences(); Map<String, Object> model = new HashMap<String, Object>(); // get the list of hidden calendars @SuppressWarnings("unchecked") HashMap<Long, String> hiddenCalendars = (HashMap<Long, String>) session.getAttribute("hiddenCalendars"); // indicate if the current user is a guest (unauthenticated) user model.put("guest", request.getRemoteUser() == null); /** * Add and remove calendars from the hidden list. Hidden calendars * will be fetched, but rendered invisible in the view. */ // check the request parameters to see if we need to add any // calendars to the list of hidden calendars String hideCalendar = request.getParameter("hideCalendar"); if (hideCalendar != null) { hiddenCalendars.put(Long.valueOf(hideCalendar), "true"); session.setAttribute("hiddenCalendars", hiddenCalendars); } // check the request parameters to see if we need to remove // any calendars from the list of hidden calendars String showCalendar = request.getParameter("showCalendar"); if (showCalendar != null) { hiddenCalendars.remove(Long.valueOf(showCalendar)); session.setAttribute("hiddenCalendars", hiddenCalendars); } // See if we're configured to show or hide the jQueryUI DatePicker. // By default, we assume we are to show the DatePicker because that's // the classic behavior. String showDatePicker = prefs.getValue("showDatePicker", "true"); model.put("showDatePicker", showDatePicker); /** * Find our desired starting and ending dates. */ Interval interval = null; if (!StringUtils.isEmpty(intervalString)) { interval = Interval.parse(intervalString); model.put("startDate", new DateMidnight(interval.getStart()).toDate()); model.put("days", interval.toDuration().getStandardDays()); model.put("endDate", new DateMidnight(interval.getEnd())); } else { //StartDate can only be changed via an AJAX request DateMidnight startDate = (DateMidnight) session.getAttribute("startDate"); log.debug("startDate from session is: " + startDate); model.put("startDate", startDate.toDate()); // find how many days into the future we should display events int days = (Integer) session.getAttribute("days"); model.put("days", days); // set the end date based on our desired time period DateMidnight endDate = startDate.plusDays(days); model.put("endDate", endDate.toDate()); interval = new Interval(startDate, endDate); } // define "today" and "tomorrow" so we can display these specially in the // user interface // get the user's configured time zone String timezone = (String) session.getAttribute("timezone"); DateMidnight today = new DateMidnight(DateTimeZone.forID(timezone)); model.put("today", today.toDate()); model.put("tomorrow", today.plusDays(1).toDate()); /** * retrieve the calendars defined for this portlet instance */ CalendarSet<?> set = calendarSetDao.getCalendarSet(request); List<CalendarConfiguration> calendars = new ArrayList<CalendarConfiguration>(); calendars.addAll(set.getConfigurations()); Collections.sort(calendars, new CalendarConfigurationByNameComparator()); model.put("calendars", calendars); Map<Long, Integer> colors = new HashMap<Long, Integer>(); Map<Long, String> links = new HashMap<Long, String>(); int index = 0; for (CalendarConfiguration callisting : calendars) { // don't bother to fetch hidden calendars if (hiddenCalendars.get(callisting.getId()) == null) { try { // get an instance of the adapter for this calendar ICalendarAdapter adapter = (ICalendarAdapter) applicationContext .getBean(callisting.getCalendarDefinition().getClassName()); //get hyperlink to calendar String link = adapter.getLink(callisting, interval, request); if (link != null) { links.put(callisting.getId(), link); } } catch (NoSuchBeanDefinitionException ex) { log.error("Calendar class instance could not be found: " + ex.getMessage()); } catch (CalendarLinkException linkEx) { // Not an error. Ignore } catch (Exception ex) { log.error(ex); } } // add this calendar's id to the color map colors.put(callisting.getId(), index); index++; } model.put("timezone", session.getAttribute("timezone")); model.put("colors", colors); model.put("links", links); model.put("hiddenCalendars", hiddenCalendars); /* * Check if we need to disable either the preferences and/or administration links */ Boolean disablePrefs = Boolean.valueOf(prefs.getValue(PREFERENCE_DISABLE_PREFERENCES, "false")); model.put(PREFERENCE_DISABLE_PREFERENCES, disablePrefs); Boolean disableAdmin = Boolean.valueOf(prefs.getValue(PREFERENCE_DISABLE_ADMINISTRATION, "false")); model.put(PREFERENCE_DISABLE_ADMINISTRATION, disableAdmin); return new ModelAndView(viewSelector.getCalendarViewName(request), "model", model); }
From source file:org.jasig.portlet.calendar.service.SessionSetupInitializationService.java
License:Apache License
public void initialize(PortletRequest request) { PortletSession session = request.getPortletSession(true); /**// ww w . j a v a2 s .c o m * Set the subscribe ID used for associating calendar data with a user */ String subscribeId = null; if (userToken == null || userToken.equalsIgnoreCase("")) { subscribeId = request.getRemoteUser(); } else { // get the credentials for this portlet from the UserInfo map @SuppressWarnings("unchecked") Map<String, String> userinfo = (Map<String, String>) request.getAttribute(PortletRequest.USER_INFO); subscribeId = (String) userinfo.get(userToken); } // default to guest if (subscribeId == null) { subscribeId = "guest"; } session.setAttribute(USERNAME_KEY, subscribeId); /** * Set the list of calendar roles belonging to this user */ // get a set of all role names currently configured for // default calendars List<String> allRoles = calendarStore.getUserRoles(); // determine which of the above roles the user belongs to // and store the resulting list in the session Set<String> userRoles = new HashSet<String>(); for (String role : allRoles) { if (request.isUserInRole(role)) userRoles.add(role); } session.setAttribute("userRoles", userRoles); /** * Set whether this user is an admin */ // determine if this user belongs to the defined calendar // administration group and store the result in the session session.setAttribute("isAdmin", request.isUserInRole("calendarAdmin"), PortletSession.APPLICATION_SCOPE); /** * Update the user's calendar subscriptions to include * any calendars that have been associated with his or * her role */ calendarStore.initCalendar(subscribeId, userRoles); /** * Create a list of hidden calendars for the session */ HashMap<Long, String> hiddenCalendars = new HashMap<Long, String>(); session.setAttribute("hiddenCalendars", hiddenCalendars); /** * Initialize the start date, timezone, and duration of the calendar */ // get the timezone PortletPreferences prefs = request.getPreferences(); String timezone = prefs.getValue("timezone", "America/New_York"); session.setAttribute("timezone", timezone); // set now as the starting date final DateMidnight start = new DateMidnight(DateTimeZone.forID(timezone)); session.setAttribute("startDate", start); // set the default number of days to display // get days from preferences, or use the default if not found final String prefDays = prefs.getValue("days", String.valueOf(defaultDays)); final int tempDays = Integer.parseInt(prefDays); session.setAttribute("days", tempDays); // mark this session as initialized session.setAttribute("initialized", "true"); }
From source file:org.jasig.portlet.calendar.util.DateUtil.java
License:Apache License
public static Interval getInterval(String startDate, int days, PortletRequest request) throws ParseException { final PortletSession session = request.getPortletSession(); final String timezone = (String) session.getAttribute("timezone"); final DateTimeZone tz = DateTimeZone.forID(timezone); final DateTimeFormatter df = new DateTimeFormatterBuilder().appendPattern("MMddyyyy").toFormatter() .withZone(tz);// w w w . java2s . co m final DateMidnight start = new DateMidnight(df.parseDateTime(startDate), tz); return getInterval(start, days); }
From source file:org.jboss.seam.international.datetimezone.AvailableDateTimeZones.java
License:Apache License
@SuppressWarnings("unchecked") @PostConstruct// w w w . j a v a 2s . c o m public void init() { dateTimeZones = new ArrayList<ForwardingDateTimeZone>(); final Set timeZoneIds = DateTimeZone.getAvailableIDs(); for (Object object : timeZoneIds) { String id = (String) object; if (id.matches(TIMEZONE_ID_PREFIXES)) { final DateTimeZone dtz = DateTimeZone.forID(id); dateTimeZones.add(new ForwardingDateTimeZone(id) { @Override protected DateTimeZone delegate() { return dtz; } }); } } Collections.sort(dateTimeZones, new Comparator<ForwardingDateTimeZone>() { public int compare(final ForwardingDateTimeZone a, final ForwardingDateTimeZone b) { return a.getID().compareTo(b.getID()); } }); dateTimeZones = Collections.unmodifiableList(dateTimeZones); }
From source file:org.jboss.seam.international.datetimezone.DefaultDateTimeZoneProducer.java
License:Apache License
@PostConstruct public void init() { if (!defaultTimeZoneId.isUnsatisfied()) { try {//from w w w . j a v a2s. c o m String id = defaultTimeZoneId.get(); DateTimeZone dtz = DateTimeZone.forID(id); defaultDateTimeZone = constructTimeZone(dtz); } catch (IllegalArgumentException e) { log.warn("DefaultDateTimeZoneProducer: Default TimeZone Id of " + defaultTimeZoneId + " was not found"); } } if (null == defaultDateTimeZone) { DateTimeZone dtz = DateTimeZone.getDefault(); defaultDateTimeZone = constructTimeZone(dtz); } }
From source file:org.jevis.commons.dataprocessing.Options.java
License:Open Source License
/** * @return//from w w w.j a va 2 s. co m */ public static DateTime getOffset(Task task) { DateTimeZone zone = DateTimeZone.forID("Europe/Berlin"); // Chronology coptic = CopticChronology.getInstance(zone); DateTime _offset = new DateTime(2007, 1, 1, 0, 0, 0, zone); return _offset; }