List of usage examples for org.joda.time DateMidnight DateMidnight
public DateMidnight(Object instant)
From source file:org.easy.scrum.model.embedded.PersistentPeriod.java
License:Apache License
public int getMonthsBetween() { return Months.monthsBetween(new DateMidnight(start.getTime()), new DateMidnight(end.getTime())).getMonths(); }
From source file:org.encuestame.business.service.StreamService.java
License:Apache License
/** * Classify notifications by {@link DateClasificatedEnum}. * @throws EnMeNoResultsFoundException/*w w w.j a v a 2 s . co m*/ */ public HashMap<DateClasificatedEnum, List<UtilNotification>> classifyNotificationList( final List<UtilNotification> utilNotifications, final HttpServletRequest request) throws EnMeNoResultsFoundException { final HashMap<DateClasificatedEnum, List<UtilNotification>> response = new HashMap<DateClasificatedEnum, List<UtilNotification>>(); // today notification final List<Notification> todayNotifications = filterByDate(DateUtil.getTodayStartDate(), DateUtil.getNextDayMidnightDate()); // this week (minus today) DateTime thisWeek = new DateTime(DateUtil.getTodayStartDate()); thisWeek = thisWeek.minusMinutes(1); Date finalThisWeek = thisWeek.minusWeeks(1).toDate(); final List<Notification> thisWeekList = filterByDate(finalThisWeek, thisWeek.toDate()); // this months notifications final DateTime finalThisWeekMinusOne = new DateTime(finalThisWeek).minusMinutes(1); final DateTime finalThisMonth = finalThisWeekMinusOne.minusWeeks(3); final List<Notification> thisMonth = filterByDate(finalThisMonth.toDate(), finalThisWeekMinusOne.toDate()); // last months notifications final DateTime lastMontFinal = finalThisMonth.minusMinutes(1); final DateTime lastMontInit = lastMontFinal.minusDays(DateClasificatedEnum.THIS_MONTH.toNumber()); final List<Notification> lastMonth = filterByDate(lastMontInit.toDate(), lastMontFinal.toDate()); // few months ago final DateTime lastFewMontFinal = lastMontInit.minusMinutes(1); final DateTime lastFewMontInit = lastFewMontFinal.minusMonths(4); // 4 months, 4 + (1) last + 1 (current) = 6 final List<Notification> fewMonth = filterByDate(lastFewMontInit.toDate(), lastFewMontFinal.toDate()); // last year final DateTime lastYearFinal = lastFewMontInit.minusMinutes(1); final DateMidnight lastYeaInit = new DateMidnight(lastYearFinal).withWeekOfWeekyear(1).withDayOfWeek(1); final List<Notification> lastYear = filterByDate(lastYeaInit.toDate(), lastYearFinal.toDate()); // long time ago final DateTime longTimeFinal = new DateTime(lastYeaInit).minusMinutes(1); final DateMidnight longTimeInit = new DateMidnight(longTimeFinal).minusYears(3).withWeekOfWeekyear(1) .withDayOfWeek(1); final List<Notification> longtime = filterByDate(longTimeInit.toDate(), longTimeFinal.toDate()); response.put(DateClasificatedEnum.TODAY, convertNotificationList(todayNotifications, request)); response.put(DateClasificatedEnum.THIS_WEEK, convertNotificationList(thisWeekList, request)); response.put(DateClasificatedEnum.THIS_MONTH, convertNotificationList(thisMonth, request)); response.put(DateClasificatedEnum.LAST_MONTH, convertNotificationList(lastMonth, request)); response.put(DateClasificatedEnum.FEW_MONTHS_AGO, convertNotificationList(fewMonth, request)); response.put(DateClasificatedEnum.LAST_YEAR, convertNotificationList(lastYear, request)); response.put(DateClasificatedEnum.LONG_TIME_AGO, convertNotificationList(longtime, request)); return response; }
From source file:org.fam.ejb.model.FamPlayer.java
@PostLoad @PostPersist/*from w w w. ja v a2 s . c o m*/ @PostUpdate void afterLoad() { StringBuilder builder = new StringBuilder(); if (firstName != null) { builder.append(firstName); } if (lastName != null) { builder.append(" ").append(lastName); } displayName = builder.toString(); if (this.getDtBirth() != null) { DateMidnight date = new DateMidnight(this.getDtBirth()); DateTime now = new DateTime(); Years y = Years.yearsBetween(date, now); age = y.getYears(); } if (this.getDtArrival() != null) { DateMidnight date = new DateMidnight(this.getDtArrival()); DateTime now = new DateTime(); Years y = Years.yearsBetween(date, now); seniority = y.getYears(); } }
From source file:org.helianto.security.controller.AbstractVerifyController.java
License:Apache License
/** * Find a valid previous signup attempt. * //w w w.j a va2 s . co m * @param confirmationToken * @param expirationLimit */ protected int findPreviousSignupAttempt(String confirmationToken, int expirationLimit) { Signup signup = signupTmpRepository.findByToken(confirmationToken); if (signup != null) { if (expirationLimit > 0 && signup.getIssueDate() != null) { DateMidnight expirationDate = new DateMidnight(signup.getIssueDate()).plusDays(expirationLimit + 1); logger.debug("Previous signup attempt valid to {} ", expirationDate); if (expirationDate.isAfterNow()) { return identityRepository.findByPrincipal(signup.getPrincipal()).getId(); } } } logger.debug("Unable to detect any valid previous signup attempt with token {} ", confirmationToken); return 0; }
From source file:org.helianto.security.controller.VerifyController.java
License:Apache License
/** * Find a valid previous signup attempt. * /* w w w . java2 s . c o m*/ * @param confirmationToken * @param expirationLimit */ protected int findPreviousSignupAttempt(String confirmationToken, int expirationLimit) { Signup signup = signupTmpRepository.findByToken(confirmationToken); if (signup != null) { if (expirationLimit > 0 && signup.getIssueDate() != null) { DateMidnight expirationDate = new DateMidnight(signup.getIssueDate()).plusDays(expirationLimit + 1); logger.debug("Previous signup attempt valid to {} ", expirationDate); if (expirationDate.isAfterNow()) { return identityRepository.findByPrincipal(signup.getPrincipal()).getId(); } } } logger.debug("Unable to detect any valid previous signup attempt with token {} ", confirmationToken); return 0; }
From source file:org.jasig.portal.io.xml.eventaggr.EventAggregationConfigurationImporterExporter.java
License:Apache License
@Transactional("aggrEventsTransactionManager") @Override//ww w.j ava 2s . com public void importData(ExternalEventAggregationConfiguration data) { //Import interval configs final Set<AggregatedIntervalConfig> oldAggregatedIntervalConfigs = new HashSet<AggregatedIntervalConfig>( this.aggregationManagementDao.getAggregatedIntervalConfigs()); for (final ExternalAggregatedIntervalConfig extAggregatedIntervalConfig : data .getAggregatedIntervalConfigs()) { final String aggregatorTypeName = extAggregatedIntervalConfig.getAggregatorType(); final Class<? extends IPortalEventAggregator> aggregatorType = getAggregatorType(aggregatorTypeName); AggregatedIntervalConfig aggregatedIntervalConfig = this.aggregationManagementDao .getAggregatedIntervalConfig(aggregatorType); if (aggregatedIntervalConfig == null) { aggregatedIntervalConfig = this.aggregationManagementDao .createAggregatedIntervalConfig(aggregatorType); } //Remove the config from the old configs set, marking it as updated oldAggregatedIntervalConfigs.remove(aggregatedIntervalConfig); //Copy over excludes final Set<AggregationInterval> excluded = aggregatedIntervalConfig.getExcluded(); excluded.clear(); for (final ExternalAggregationInterval extInterval : extAggregatedIntervalConfig.getExcludes()) { excluded.add(convert(extInterval)); } //Copy over includes final Set<AggregationInterval> included = aggregatedIntervalConfig.getIncluded(); included.clear(); for (final ExternalAggregationInterval extInterval : extAggregatedIntervalConfig.getIncludes()) { included.add(convert(extInterval)); } this.aggregationManagementDao.updateAggregatedIntervalConfig(aggregatedIntervalConfig); } //Delete interval configs that were not updated for (final AggregatedIntervalConfig aggregatedIntervalConfig : oldAggregatedIntervalConfigs) { this.aggregationManagementDao.deleteAggregatedIntervalConfig(aggregatedIntervalConfig); } //Import Group configs final Set<AggregatedGroupConfig> oldAggregatedGroupConfigs = new HashSet<AggregatedGroupConfig>( this.aggregationManagementDao.getAggregatedGroupConfigs()); for (final ExternalAggregatedGroupConfig extAggregatedGroupConfig : data.getAggregatedGroupConfigs()) { final String aggregatorTypeName = extAggregatedGroupConfig.getAggregatorType(); final Class<? extends IPortalEventAggregator> aggregatorType = getAggregatorType(aggregatorTypeName); AggregatedGroupConfig aggregatedGroupConfig = this.aggregationManagementDao .getAggregatedGroupConfig(aggregatorType); if (aggregatedGroupConfig == null) { aggregatedGroupConfig = this.aggregationManagementDao.createAggregatedGroupConfig(aggregatorType); } //Remove the config from the old configs set, marking it as updated oldAggregatedGroupConfigs.remove(aggregatedGroupConfig); //Copy over excludes final Set<AggregatedGroupMapping> excluded = aggregatedGroupConfig.getExcluded(); excluded.clear(); for (final ExternalAggregatedGroupMapping extGroup : extAggregatedGroupConfig.getExcludes()) { excluded.add(convert(extGroup)); } //Copy over includes final Set<AggregatedGroupMapping> included = aggregatedGroupConfig.getIncluded(); included.clear(); for (final ExternalAggregatedGroupMapping extGroup : extAggregatedGroupConfig.getIncludes()) { included.add(convert(extGroup)); } this.aggregationManagementDao.updateAggregatedGroupConfig(aggregatedGroupConfig); } //Delete interval configs that were not updated for (final AggregatedGroupConfig aggregatedGroupConfig : oldAggregatedGroupConfigs) { this.aggregationManagementDao.deleteAggregatedGroupConfig(aggregatedGroupConfig); } //Set quarter details if configured or set default quarters final List<ExternalQuarterDetail> extQuarterDetails = data.getQuarterDetails(); final List<QuarterDetail> quarterDetails; if (!extQuarterDetails.isEmpty()) { quarterDetails = convertQuarterDetail(extQuarterDetails); } else { quarterDetails = EventDateTimeUtils.createStandardQuarters(); } this.aggregationManagementDao.setQuarterDetails(quarterDetails); //Set academic term if configured final List<AcademicTermDetail> academicTerms = Lists.transform(data.getTermDetails(), new Function<ExternalTermDetail, AcademicTermDetail>() { public AcademicTermDetail apply(ExternalTermDetail externalTermDetail) { return new AcademicTermDetailImpl(new DateMidnight(externalTermDetail.getStart()), new DateMidnight(externalTermDetail.getEnd()), externalTermDetail.getName()); } }); this.aggregationManagementDao.setAcademicTermDetails(academicTerms); }
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++)); }//from ww w.j ava2 s . com /* * 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) {/*from w ww . j a va 2s.com*/ 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.mvc.controller.SearchContentController.java
License:Apache License
private PortletUrl createPortletUrl(CalendarDisplayEvent event) { final DateMidnight midnight = new DateMidnight(event.getDayStart()); final Interval interval = DateUtil.getInterval(midnight, 1); final PortletUrl url = new PortletUrl(); final PortletUrlParameter param = new PortletUrlParameter(); param.setName("interval"); param.getValue().add(interval.toString()); url.getParam().add(param);/*from ww w .j av a2s .c om*/ return url; }
From source file:org.jasig.portlet.calendar.service.SessionSetupInitializationService.java
License:Apache License
public void initialize(PortletRequest request) { PortletSession session = request.getPortletSession(true); /**//from w ww . jav a 2 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"); }