public static List<org.exoplatform.calendar.service.Calendar> getAllOfCalendars(String username)
      throws Exception {
    List<org.exoplatform.calendar.service.Calendar> calendars =
        new ArrayList<org.exoplatform.calendar.service.Calendar>();
    CalendarService calendarService = getCalendarService();
    /*---- get private calendars ----*/
    List<GroupCalendarData> groupCalendars;
    for (org.exoplatform.calendar.service.Calendar calendar :
        calendarService.getUserCalendars(username, true)) {
      calendars.add(calendar);
    }

    /*---- get public calendars ----*/
    String[] groups = CalendarUtils.getUserGroups(username);
    groupCalendars =
        calendarService.getGroupCalendars(groups, true, CalendarUtils.getCurrentUser());
    Map<String, org.exoplatform.calendar.service.Calendar> mapCal =
        new HashMap<String, org.exoplatform.calendar.service.Calendar>();
    for (GroupCalendarData group : groupCalendars) {
      for (org.exoplatform.calendar.service.Calendar cal : group.getCalendars()) {
        mapCal.put(cal.getId(), cal);
      }
    }
    calendars.addAll(mapCal.values());

    /*---- get shared calendars ----*/
    GroupCalendarData groupCalendar = calendarService.getSharedCalendars(username, true);
    if (groupCalendar != null) {
      for (org.exoplatform.calendar.service.Calendar calendar : groupCalendar.getCalendars()) {
        calendars.add(calendar);
      }
    }
    return calendars;
  }
 public static List<org.exoplatform.calendar.service.Calendar> getAllOfCurrentUserCalendars()
     throws Exception {
   List<org.exoplatform.calendar.service.Calendar> list =
       new ArrayList<org.exoplatform.calendar.service.Calendar>();
   CalendarService calendarService = getCalendarService();
   String username = getCurrentUser();
   List<org.exoplatform.calendar.service.Calendar> calendars =
       calendarService.getUserCalendars(username, true);
   for (org.exoplatform.calendar.service.Calendar c : calendars) {
     list.add(c);
   }
   GroupCalendarData gcd = calendarService.getSharedCalendars(username, true);
   if (gcd != null) {
     for (org.exoplatform.calendar.service.Calendar c : gcd.getCalendars()) {
       if (Utils.hasPermission(Utils.getEditPerUsers(c))) {
         list.add(c);
       }
     }
   }
   List<GroupCalendarData> lgcd =
       calendarService.getGroupCalendars(CalendarUtils.getUserGroups(username), true, username);
   if (lgcd != null) {
     for (GroupCalendarData g : lgcd) {
       for (org.exoplatform.calendar.service.Calendar c : g.getCalendars()) {
         if (Utils.hasPermission(c.getEditPermission())) {
           list.add(c);
         }
       }
     }
   }
   return list;
 }
  public static List<SelectItemOption<String>> getCategory() throws Exception {
    List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>();
    CalendarService calendarService = getCalendarService();
    List<EventCategory> eventCategories = calendarService.getEventCategories(getCurrentUser());
    for (EventCategory category : eventCategories) {
      // Check if EventCategory is default event category
      boolean isDefaultEventCategory = false;
      for (int i = 0; i < NewUserListener.defaultEventCategoryIds.length; i++) {
        if (category.getId().equals(NewUserListener.defaultEventCategoryIds[i])
            && category.getName().equals(NewUserListener.defaultEventCategoryNames[i])) {
          isDefaultEventCategory = true;
          break;
        }
      }

      if (isDefaultEventCategory) {
        String newName =
            getResourceBundle("UICalendarView.label." + category.getId(), category.getId());
        options.add(new SelectItemOption<String>(newName, category.getId()));
      } else {
        options.add(new SelectItemOption<String>(category.getName(), category.getId()));
      }
    }
    return options;
  }
 private TimeZone getUserTimeZone() {
   try {
     String username = ConversationState.getCurrent().getIdentity().getUserId();
     CalendarService calService =
         (CalendarService)
             PortalContainer.getInstance().getComponentInstanceOfType(CalendarService.class);
     CalendarSetting setting = calService.getCalendarSetting(username);
     return TimeZone.getTimeZone(setting.getTimeZone());
   } catch (Exception e) {
     if (LOG.isDebugEnabled()) LOG.error("Can not get time zone from user setting ", e);
     return null;
   }
 }
 public static org.exoplatform.calendar.service.Calendar getCalendar(
     String calType, String calendarId) throws Exception {
   CalendarService calService = CalendarUtils.getCalendarService();
   String currentUser = CalendarUtils.getCurrentUser();
   org.exoplatform.calendar.service.Calendar calendar = null;
   if (CalendarUtils.PRIVATE_TYPE.equals(calType)) {
     calendar = calService.getUserCalendar(currentUser, calendarId);
   } else if (CalendarUtils.SHARED_TYPE.equals(calType)) {
     GroupCalendarData gCalendarData = calService.getSharedCalendars(currentUser, true);
     if (gCalendarData != null) calendar = gCalendarData.getCalendarById(calendarId);
   } else if (CalendarUtils.PUBLIC_TYPE.equals(calType)) {
     calendar = calService.getGroupCalendar(calendarId);
   }
   return calendar;
 }
 private void saveHistoryInject() throws Exception {
   baseURL = publicCalendar.toString();
   baseURL += ";" + privateCalendar.toString();
   baseURL += ";" + eventCategorys.toString();
   baseURL += ";" + categoryIds.toString();
   setting.setBaseURL(baseURL);
   calService.saveCalendarSetting(currentUser, setting);
 }
  private void removePrivateData() throws Exception {
    try {
      log.info(
          String.format(
              "removing private datas..... \n  removing %s calendars.....",
              privateCalendar.size()));
      for (String calId : privateCalendar) {
        if (!isEmpty(calId)) {
          calService.removeUserCalendar(currentUser, calId);
        }
      }
      log.info(String.format("removing %s event catetories.....", eventCategorys.size()));
      for (String evCatId : eventCategorys) {
        if (!isEmpty(evCatId)) {
          calService.removeEventCategory(currentUser, evCatId);
        }
      }

    } catch (Exception e) {
      log.debug("Failed to remove private injecter datas", e);
    }
  }
 private void removePublicData() throws Exception {
   try {
     log.info(
         String.format(
             "remove public datas..... \n  removing %s calendars.....", publicCalendar.size()));
     for (String calId : publicCalendar) {
       if (!isEmpty(calId)) {
         calService.removePublicCalendar(calId);
       }
     }
   } catch (Exception e) {
     log.debug("Failed to remove public injecter datas", e);
   }
 }
 private void setHistoryInject() {
   initDatas();
   try {
     String s = calService.getCalendarSetting(currentUser).getBaseURL();
     if (!isEmpty(s) && s.indexOf(";") > 0) {
       String[] strs = s.split(";");
       publicCalendar.addAll(convertStringToList(strs[0]));
       privateCalendar.addAll(convertStringToList(strs[1]));
       eventCategorys.addAll(convertStringToList(strs[2]));
       categoryIds.addAll(convertStringToList(strs[3]));
     }
   } catch (Exception e) {
     log.warn("Failed to get calendar settings", e);
   }
 }
  private void initPrivateCalendar() throws Exception {
    log.info("Inject private datas ....");
    // save setting
    try {
      setting = calService.getCalendarSetting(currentUser);
      log.info(String.format("Save calendar setting for user %s ....", currentUser));
    } catch (Exception e) {
      setting = newCalendarSetting();
      calService.saveCalendarSetting(currentUser, setting);
    }
    long t = System.currentTimeMillis(), t1 = t;

    t = System.currentTimeMillis();
    // save EventCategoy
    List<EventCategory> eventCategories = findEventCategorys();
    for (EventCategory evCat : eventCategories) {
      calService.saveEventCategory(currentUser, evCat, true);
      eventCategory.add(evCat);
      eventCategorys.add(evCat.getId());
    }
    log.info(
        String.format(
            "Saved %s eventCategories in %sms",
            eventCategories.size(), (System.currentTimeMillis() - t)));
    // save calendar
    List<Calendar> calendars = findCalendars(false);
    List<CalendarEvent> events;
    int index = 0, size = calendars.size(), evsCal, evs = 0, tas = 0;
    for (Calendar calendar : calendars) {
      t = System.currentTimeMillis();
      calService.saveUserCalendar(currentUser, calendar, true);
      privateCalendar.add(calendar.getId());
      // save Event
      events = findCalendarEvent(calendar.getId(), "0", CalendarEvent.TYPE_EVENT, false);
      for (CalendarEvent event : events) {
        calService.saveUserEvent(currentUser, calendar.getId(), event, true);
      }
      evsCal = events.size();
      evs += evsCal;
      // save Task
      events = findCalendarEvent(calendar.getId(), "0", CalendarEvent.TYPE_TASK, false);
      tas += events.size();
      for (CalendarEvent event : events) {
        calService.saveUserEvent(currentUser, calendar.getId(), event, true);
      }
      log.info(
          String.format(
              "Saved Calendar %s/%s with %s Events and %s Tasks in %sms",
              (++index), size, evsCal, events.size(), (System.currentTimeMillis()) - t));
    }
    log.info(
        String.format(
            "INITIALIZED EventCategorys=%s / Calendars=%s / Events=%s / Tasks=%s in %sms",
            eventCategories.size(), calendars.size(), evs, tas, (System.currentTimeMillis() - t1)));
    saveHistoryInject();
  }
 private void initPublicCalendar() throws Exception {
   // save public calendar
   List<Calendar> calendars = findCalendars(true);
   log.info("Inject public datas ....");
   int index = 0, size = calendars.size(), evsCal, tasCal, evs = 0, tas = 0;
   long t, t1 = System.currentTimeMillis();
   for (Calendar calendar : calendars) {
     t = System.currentTimeMillis();
     evsCal = tasCal = 0;
     calService.savePublicCalendar(calendar, true);
     publicCalendar.add(calendar.getId());
     // save event in public calendar
     for (CalendarEvent event :
         findCalendarEvent(calendar.getId(), "2", CalendarEvent.TYPE_EVENT, true)) {
       calService.savePublicEvent(calendar.getId(), event, true);
       evsCal++;
     }
     // save task in public calendar
     for (CalendarEvent event :
         findCalendarEvent(calendar.getId(), "2", CalendarEvent.TYPE_TASK, true)) {
       calService.savePublicEvent(calendar.getId(), event, true);
       tasCal++;
     }
     log.info(
         String.format(
             "Saved Calendar %s/%s with %s Events and %s Tasks in %sms",
             (++index), size, evsCal, tasCal, (System.currentTimeMillis()) - t));
     evs += evsCal;
     tas += tasCal;
   }
   log.info(
       String.format(
           "INITIALIZED: Calendars=%s / Events=%s / Tasks=%s in %sms",
           publicCalendar.size(), evs, tas, (System.currentTimeMillis() - t1)));
   saveHistoryInject();
 }
  /**
   * convert date to user date format using calendar setting
   *
   * @param date
   * @return
   */
  private String getDateFormattedAfterUserSetting(String date) {
    try {
      String userId = ConversationState.getCurrent().getIdentity().getUserId();
      calService_ =
          (CalendarService)
              PortalContainer.getInstance().getComponentInstance(CalendarService.class); // not null
      CalendarSetting calSetting = calService_.getCalendarSetting(userId); // not null
      WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance();
      Locale locale = requestContext.getParentAppRequestContext().getLocale();
      DateFormat format = new SimpleDateFormat(calSetting.getDateFormat(), locale);

      /* recurrenceId to Date then re-convert it to user date format */
      DateFormat format1 = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
      Date eventDate = format1.parse(date);

      return format.format(eventDate);
    } catch (Exception e) {
      LOG.debug(e.getMessage());
    }
    return null;
  }
Exemple #13
0
  @Override
  public void refresh() throws Exception {
    init();
    eventData_.clear();
    allDayEvent.clear();
    int i = 0;
    Calendar c = getBeginDateOfWeek();
    int maxDay = 7;
    if (isShowCustomView_) maxDay = 5;
    while (i++ < maxDay) {
      List<CalendarEvent> list = new ArrayList<CalendarEvent>();
      String key = keyGen(c.get(Calendar.DATE), c.get(Calendar.MONTH), c.get(Calendar.YEAR));
      eventData_.put(key, list);
      c.add(Calendar.DATE, 1);
    }
    CalendarService calendarService = CalendarUtils.getCalendarService();
    String username = CalendarUtils.getCurrentUser();
    EventQuery eventQuery = new EventQuery();
    eventQuery.setFromDate(getBeginDateOfWeek());
    Calendar endDateOfWeek = getEndDateOfWeek();
    Date toDate = endDateOfWeek.getTime();
    toDate.setTime(toDate.getTime() - 1);
    endDateOfWeek.setTime(toDate);
    eventQuery.setToDate(endDateOfWeek);
    eventQuery.setExcludeRepeatEvent(true);

    /** get all norepeat events */
    List<CalendarEvent> allEvents;
    String[] publicCalendars = getPublicCalendars();
    String[] privateCalendars = getPrivateCalendars().toArray(new String[] {});

    if (isInSpace()) {
      eventQuery.setCalendarId(publicCalendars);
      allEvents = calendarService.getPublicEvents(eventQuery);
    } else {
      allEvents =
          calendarService.getAllNoRepeatEventsSQL(
              username, eventQuery, privateCalendars, publicCalendars, emptyEventCalendars);
    }

    /** get exception occurrences, exclude original recurrence events */
    List<CalendarEvent> originalRecurEvents =
        calendarService.getHighLightOriginalRecurrenceEventsSQL(
            username,
            eventQuery.getFromDate(),
            eventQuery.getToDate(),
            eventQuery,
            privateCalendars,
            publicCalendars,
            emptyRecurrentEventCalendars);

    String timezone = CalendarUtils.getCurrentUserCalendarSetting().getTimeZone();
    if (originalRecurEvents != null && originalRecurEvents.size() > 0) {
      Iterator<CalendarEvent> recurEventsIter = originalRecurEvents.iterator();
      while (recurEventsIter.hasNext()) {
        CalendarEvent recurEvent = recurEventsIter.next();
        Map<String, CalendarEvent> tempMap =
            calendarService.getOccurrenceEvents(
                recurEvent, eventQuery.getFromDate(), eventQuery.getToDate(), timezone);
        if (tempMap != null) {
          recurrenceEventsMap.put(recurEvent.getId(), tempMap);
          allEvents.addAll(tempMap.values());
        }
      }
    }

    Iterator<CalendarEvent> iter = allEvents.iterator();
    while (iter.hasNext()) {
      CalendarEvent event = iter.next();
      Date beginEvent = event.getFromDateTime();
      Date endEvent = event.getToDateTime();
      long eventAmount = endEvent.getTime() - beginEvent.getTime();
      i = 0;
      c = getBeginDateOfWeek();
      while (i++ < maxDay) {
        String key = keyGen(c.get(Calendar.DATE), c.get(Calendar.MONTH), c.get(Calendar.YEAR));
        if (isSameDate(c.getTime(), beginEvent)
            && (isSameDate(c.getTime(), endEvent))
            && eventAmount < CalendarUtils.MILISECONS_OF_DAY) {
          eventData_.get(key).add(event);
          iter.remove();
        }
        c.add(Calendar.DATE, 1);
      }
    }

    for (CalendarEvent ce : allEvents) {
      allDayEvent.add(ce);
    }
  }
  /**
   * get all users calendars (private, public, shared)
   *
   * @return
   * @throws Exception
   */
  public static List<SelectItem> getCalendarOption() throws Exception {
    List<SelectItem> options = new ArrayList<SelectItem>();
    CalendarService calendarService = getCalendarService();
    String username = getCurrentUser();
    /*
     * hash map to check existence of a calendar in the list.
     */
    Map<String, String> hash = new HashMap<String, String>();
    /*
     * Modified by Philippe ([email protected])
     * Uses SelectItemOptionGroup to differienciate private, shared and public groups
     */

    // private calendars group
    SelectOptionGroup privGrp = new SelectOptionGroup(CalendarUtils.PRIVATE_CALENDARS);
    List<org.exoplatform.calendar.service.Calendar> calendars =
        calendarService.getUserCalendars(username, true);
    for (org.exoplatform.calendar.service.Calendar c : calendars) {
      if (!hash.containsKey(c.getId())) {
        hash.put(c.getId(), "");
        privGrp.addOption(
            new SelectOption(
                c.getName(), CalendarUtils.PRIVATE_TYPE + CalendarUtils.COLON + c.getId()));
      }
    }
    if (privGrp.getOptions().size() > 0) options.add(privGrp);
    // shared calendars group
    GroupCalendarData gcd = calendarService.getSharedCalendars(username, true);
    if (gcd != null) {
      SelectOptionGroup sharedGrp = new SelectOptionGroup(CalendarUtils.SHARED_CALENDARS);
      for (org.exoplatform.calendar.service.Calendar c : gcd.getCalendars()) {
        if (Utils.hasPermission(Utils.getEditPerUsers(c))) {
          if (!hash.containsKey(c.getId())) {
            hash.put(c.getId(), "");
            sharedGrp.addOption(
                new SelectOption(
                    c.getName(), CalendarUtils.SHARED_TYPE + CalendarUtils.COLON + c.getId()));
          }
        }
      }
      if (sharedGrp.getOptions().size() > 0) options.add(sharedGrp);
    }
    // public calendars group
    List<GroupCalendarData> lgcd =
        calendarService.getGroupCalendars(CalendarUtils.getUserGroups(username), true, username);

    if (lgcd != null) {
      SelectOptionGroup pubGrp = new SelectOptionGroup(CalendarUtils.PUBLIC_CALENDARS);
      for (GroupCalendarData g : lgcd) {
        for (org.exoplatform.calendar.service.Calendar c : g.getCalendars()) {
          if (Utils.hasPermission(c.getEditPermission())) {
            if (!hash.containsKey(c.getId())) {
              hash.put(c.getId(), "");
              pubGrp.addOption(
                  new SelectOption(
                      c.getName(), CalendarUtils.PUBLIC_TYPE + CalendarUtils.COLON + c.getId()));
            }
          }
        }
      }
      if (pubGrp.getOptions().size() > 0) options.add(pubGrp);
    }
    return options;
  }
  /**
   * Build the repeating summary, i.e: daily every 2 days, until 02/03/2011. <br>
   * The summary structure is defined in resource bundle, it contains some parameters and </br> will
   * be replaced by values from repeatEvent. <br>
   *
   * <p>There are 6 parameters: {count}, {until}, {interval}, {byDays}, {theDay}, {theNumber}.<br>
   * Some labels in resource bundle to define numbers (the first, the second, ...) which were used
   * in summary
   *
   * @param repeatEvent the repeating event
   * @return summary string about repeating event
   * @throws Exception
   */
  public String buildRepeatSummary(CalendarEvent repeatEvent) {
    if (repeatEvent == null) return "";
    String repeatType = repeatEvent.getRepeatType();
    if (CalendarEvent.RP_NOREPEAT.equals(repeatType) || repeatType == null) return "";

    try {
      String userId = ConversationState.getCurrent().getIdentity().getUserId();
      calService_ =
          (CalendarService)
              PortalContainer.getInstance().getComponentInstance(CalendarService.class);
      CalendarSetting calSetting = calService_.getCalendarSetting(userId);
      WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance();

      Locale locale = requestContext.getParentAppRequestContext().getLocale();
      DateFormat format = new SimpleDateFormat(calSetting.getDateFormat(), locale);
      DateFormatSymbols symbols = new DateFormatSymbols(locale);
      String[] dayOfWeeks = symbols.getWeekdays();

      int interval = (int) repeatEvent.getRepeatInterval();
      int count = (int) repeatEvent.getRepeatCount();
      Date until = repeatEvent.getRepeatUntilDate();
      String endType = RP_END_NEVER;
      if (count > 0) endType = RP_END_AFTER;
      if (until != null) endType = RP_END_BYDATE;

      StringBuilder pattern = new StringBuilder("");
      if (repeatType.equals(CalendarEvent.RP_DAILY)) {
        if (interval == 1) {
          // pattern = "Daily";
          pattern.append(CalendarUIActivity.getUICalendarLabel("daily"));
        } else {
          // pattern = "Every {interval} days";
          pattern.append(CalendarUIActivity.getUICalendarLabel("every-day"));
        }
        if (endType.equals(RP_END_AFTER)) {
          // pattern = "Daily, {count} times";
          // pattern = "Every {interval} days, {count} times";
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("count-times"));
        }
        if (endType.equals(RP_END_BYDATE)) {
          // pattern = "Daily, until {until}";
          // pattern = "Every {interval} days, until {until}";
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("until"));
        }

        return new String(pattern)
            .replace("{interval}", String.valueOf(interval))
            .replace("{count}", String.valueOf(repeatEvent.getRepeatCount()))
            .replace(
                "{until}",
                repeatEvent.getRepeatUntilDate() == null
                    ? ""
                    : format.format(repeatEvent.getRepeatUntilDate()));
      }

      if (repeatType.equals(CalendarEvent.RP_WEEKLY)) {
        if (interval == 1) {
          // pattern = "Weekly on {byDays}";
          pattern.append(CalendarUIActivity.getUICalendarLabel("weekly"));
        } else {
          // pattern = "Every {interval} weeks on {byDays}";
          pattern.append(CalendarUIActivity.getUICalendarLabel("every-week"));
        }
        if (endType.equals(RP_END_AFTER)) {
          // pattern = "Weekly on {byDays}, {count} times";
          // pattern = "Every {interval} weeks on {byDays}, {count} times";
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("count-times"));
        }
        if (endType.equals(RP_END_BYDATE)) {
          // pattern = "Weekly on {byDays}, until {until}";
          // pattern = "Every {interval} weeks on {byDays}, until {until}";
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("until"));
        }

        String[] weeklyByDays = repeatEvent.getRepeatByDay();
        StringBuffer byDays = new StringBuffer();
        for (int i = 0; i < weeklyByDays.length; i++) {
          if (i == 0) {
            byDays.append(dayOfWeeks[convertToDayOfWeek(weeklyByDays[0])]);
          } else {
            byDays.append(", ");
            byDays.append(dayOfWeeks[convertToDayOfWeek(weeklyByDays[i])]);
          }
        }
        return new String(pattern)
            .replace("{interval}", String.valueOf(interval))
            .replace("{count}", String.valueOf(repeatEvent.getRepeatCount()))
            .replace(
                "{until}",
                repeatEvent.getRepeatUntilDate() == null
                    ? ""
                    : format.format(repeatEvent.getRepeatUntilDate()))
            .replace("{byDays}", byDays.toString());
      }

      if (repeatType.equals(CalendarEvent.RP_MONTHLY)) {
        String monthlyType = RP_MONTHLY_BYMONTHDAY;
        if (repeatEvent.getRepeatByDay() != null && repeatEvent.getRepeatByDay().length > 0)
          monthlyType = RP_MONTHLY_BYDAY;

        if (interval == 1) {
          // pattern = "Monthly on"
          pattern.append(CalendarUIActivity.getUICalendarLabel("monthly"));
        } else {
          // pattern = "Every {interval} months on
          pattern.append(CalendarUIActivity.getUICalendarLabel("every-month"));
        }

        if (monthlyType.equals(RP_MONTHLY_BYDAY)) {
          // pattern = "Monthly on {theNumber} {theDay}
          // pattern = "Every {interval} months on {theNumber} {theDay}
          pattern.append(" " + CalendarUIActivity.getUICalendarLabel("monthly-by-day"));
        } else {
          // pattern = "Monthly on day {theDay}
          // pattern = "Every {interval} months on day {theDay}
          pattern.append(" " + CalendarUIActivity.getUICalendarLabel("monthly-by-month-day"));
        }

        if (endType.equals(RP_END_AFTER)) {
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("count-times"));
        }
        if (endType.equals(RP_END_BYDATE)) {
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("until"));
        }

        String theNumber = ""; // the first, the second, the third, ...
        String theDay =
            ""; // in monthly by day, it's Monday, Tuesday, ... (day of week), in monthly by
        // monthday, it's 1-31 (day of month)
        if (monthlyType.equals(RP_MONTHLY_BYDAY)) {
          java.util.Calendar temp = getCalendarInstanceBySetting(calSetting);
          temp.setTime(repeatEvent.getFromDateTime());
          int weekOfMonth = temp.get(java.util.Calendar.WEEK_OF_MONTH);
          java.util.Calendar temp2 = getCalendarInstanceBySetting(calSetting);
          temp2.setTime(temp.getTime());
          temp2.add(java.util.Calendar.DATE, 7);
          if (temp2.get(java.util.Calendar.MONTH) != temp.get(java.util.Calendar.MONTH))
            weekOfMonth = 5;
          int dayOfWeek = temp.get(java.util.Calendar.DAY_OF_WEEK);
          String[] weekOfMonths =
              new String[] {
                CalendarUIActivity.getUICalendarLabel("summary-the-first"),
                CalendarUIActivity.getUICalendarLabel("summary-the-second"),
                CalendarUIActivity.getUICalendarLabel("summary-the-third"),
                CalendarUIActivity.getUICalendarLabel("summary-the-fourth"),
                CalendarUIActivity.getUICalendarLabel("summary-the-last")
              };
          theNumber = weekOfMonths[weekOfMonth - 1];
          theDay = dayOfWeeks[dayOfWeek];
        } else {
          java.util.Calendar temp = getCalendarInstanceBySetting(calSetting);
          temp.setTime(repeatEvent.getFromDateTime());
          int dayOfMonth = temp.get(java.util.Calendar.DAY_OF_MONTH);
          theDay = String.valueOf(dayOfMonth);
        }
        return new String(pattern)
            .replace("{interval}", String.valueOf(interval))
            .replace("{count}", String.valueOf(repeatEvent.getRepeatCount()))
            .replace(
                "{until}",
                repeatEvent.getRepeatUntilDate() == null
                    ? ""
                    : format.format(repeatEvent.getRepeatUntilDate()))
            .replace("{theDay}", theDay)
            .replace("{theNumber}", theNumber);
      }

      if (repeatType.equals(CalendarEvent.RP_YEARLY)) {
        if (interval == 1) {
          // pattern = "Yearly on {theDay}"
          pattern.append(CalendarUIActivity.getUICalendarLabel("yearly"));
        } else {
          // pattern = "Every {interval} years on {theDay}"
          pattern.append(CalendarUIActivity.getUICalendarLabel("every-year"));
        }

        if (endType.equals(RP_END_AFTER)) {
          // pattern = "Yearly on {theDay}, {count} times"
          // pattern = "Every {interval} years on {theDay}, {count} times"
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("count-times"));
        }
        if (endType.equals(RP_END_BYDATE)) {
          // pattern = "Yearly on {theDay}, until {until}"
          // pattern = "Every {interval} years on {theDay}, until {until}"
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("until"));
        }

        String theDay = format.format(repeatEvent.getFromDateTime()); //
        return new String(pattern)
            .replace("{interval}", String.valueOf(interval))
            .replace("{count}", String.valueOf(repeatEvent.getRepeatCount()))
            .replace(
                "{until}",
                repeatEvent.getRepeatUntilDate() == null
                    ? ""
                    : format.format(repeatEvent.getRepeatUntilDate()))
            .replace("{theDay}", theDay);
      }
    } catch (Exception e) {
      LOG.info(e.getLocalizedMessage());
    }
    return null;
  }
Exemple #16
0
 @Override
 public void execute(Event<UIWeekView> event) throws Exception {
   UIWeekView calendarview = event.getSource();
   String eventId = event.getRequestContext().getRequestParameter(OBJECTID);
   String calendarId = event.getRequestContext().getRequestParameter(eventId + CALENDARID);
   String calType = event.getRequestContext().getRequestParameter(eventId + CALTYPE);
   String startTime = event.getRequestContext().getRequestParameter(eventId + START_TIME);
   String finishTime = event.getRequestContext().getRequestParameter(eventId + FINISH_TIME);
   Boolean isOccur = false;
   if (!Utils.isEmpty(event.getRequestContext().getRequestParameter(eventId + ISOCCUR))) {
     isOccur =
         Boolean.parseBoolean(event.getRequestContext().getRequestParameter(eventId + ISOCCUR));
   }
   String recurId = null;
   if (isOccur) recurId = event.getRequestContext().getRequestParameter(eventId + RECURID);
   try {
     String username = CalendarUtils.getCurrentUser();
     CalendarEvent eventCalendar = null;
     if (isOccur && !Utils.isEmpty(recurId)) {
       eventCalendar = calendarview.getRecurrenceMap().get(eventId).get(recurId);
     } else {
       eventCalendar = calendarview.getDataMap().get(eventId);
     }
     if (eventCalendar != null) {
       CalendarService calendarService = CalendarUtils.getCalendarService();
       Calendar calBegin = calendarview.getInstanceTempCalendar();
       Calendar calEnd = calendarview.getInstanceTempCalendar();
       long unit = 15 * 60 * 1000;
       calBegin.setTimeInMillis((Long.parseLong(startTime) / unit) * unit);
       eventCalendar.setFromDateTime(calBegin.getTime());
       calEnd.setTimeInMillis((Long.parseLong(finishTime) / unit) * unit);
       eventCalendar.setToDateTime(calEnd.getTime());
       if (eventCalendar.getToDateTime().before(eventCalendar.getFromDateTime())) {
         return;
       }
       org.exoplatform.calendar.service.Calendar calendar = null;
       if (CalendarUtils.PRIVATE_TYPE.equals(calType)) {
         calendar = calendarService.getUserCalendar(username, calendarId);
       } else if (CalendarUtils.SHARED_TYPE.equals(calType)) {
         if (calendarService.getSharedCalendars(username, true) != null)
           calendar =
               calendarService.getSharedCalendars(username, true).getCalendarById(calendarId);
       } else if (CalendarUtils.PUBLIC_TYPE.equals(calType)) {
         calendar = calendarService.getGroupCalendar(calendarId);
       }
       if (calendar == null) {
         event
             .getRequestContext()
             .getUIApplication()
             .addMessage(new ApplicationMessage("UICalendars.msg.have-no-calendar", null, 1));
       } else {
         if ((CalendarUtils.SHARED_TYPE.equals(calType)
                 && !CalendarUtils.canEdit(
                     calendarview.getApplicationComponent(OrganizationService.class),
                     Utils.getEditPerUsers(calendar),
                     username))
             || (CalendarUtils.PUBLIC_TYPE.equals(calType)
                 && !CalendarUtils.canEdit(
                     calendarview.getApplicationComponent(OrganizationService.class),
                     calendar.getEditPermission(),
                     username))) {
           event
               .getRequestContext()
               .getUIApplication()
               .addMessage(
                   new ApplicationMessage(
                       "UICalendars.msg.have-no-permission-to-edit-event", null, 1));
           calendarview.refresh();
           event.getRequestContext().addUIComponentToUpdateByAjax(calendarview.getParent());
           return;
         }
         // if it's a 'virtual' occurrence
         if (isOccur && !Utils.isEmpty(recurId)) {
           List<CalendarEvent> listEvent = new ArrayList<CalendarEvent>();
           listEvent.add(eventCalendar);
           calendarService.updateOccurrenceEvent(
               calendarId, calendarId, calType, calType, listEvent, username);
         } else {
           if (calType.equals(CalendarUtils.PRIVATE_TYPE)) {
             calendarService.saveUserEvent(username, calendarId, eventCalendar, false);
           } else if (calType.equals(CalendarUtils.SHARED_TYPE)) {
             calendarService.saveEventToSharedCalendar(
                 username, calendarId, eventCalendar, false);
           } else if (calType.equals(CalendarUtils.PUBLIC_TYPE)) {
             calendarService.savePublicEvent(calendarId, eventCalendar, false);
           }
         }
         calendarview.setLastUpdatedEventId(eventId);
         calendarview.refresh();
         UIMiniCalendar uiMiniCalendar =
             calendarview
                 .getAncestorOfType(UICalendarPortlet.class)
                 .findFirstComponentOfType(UIMiniCalendar.class);
         event.getRequestContext().addUIComponentToUpdateByAjax(uiMiniCalendar);
         event.getRequestContext().addUIComponentToUpdateByAjax(calendarview.getParent());
       }
     }
   } catch (Exception e) {
     if (log.isDebugEnabled()) {
       log.debug("Fail to save the event to the calendar", e);
     }
     return;
   }
 }
Exemple #17
0
    @Override
    public void execute(Event<UIWeekView> event) throws Exception {

      UIWeekView calendarview = event.getSource();
      UICalendarPortlet uiCalendarPortlet = calendarview.getAncestorOfType(UICalendarPortlet.class);
      String eventId = event.getRequestContext().getRequestParameter(OBJECTID);
      String calendarId = event.getRequestContext().getRequestParameter(eventId + CALENDARID);
      String calType = event.getRequestContext().getRequestParameter(eventId + CALTYPE);
      String startTime = event.getRequestContext().getRequestParameter(eventId + START_TIME);
      String finishTime = event.getRequestContext().getRequestParameter(eventId + FINISH_TIME);
      String currentDate = event.getRequestContext().getRequestParameter(eventId + CURRENT_DATE);

      Boolean isOccur = false;
      if (!Utils.isEmpty(event.getRequestContext().getRequestParameter(eventId + ISOCCUR))) {
        isOccur =
            Boolean.parseBoolean(event.getRequestContext().getRequestParameter(eventId + ISOCCUR));
      }
      String recurId = null;
      if (isOccur) recurId = event.getRequestContext().getRequestParameter(eventId + RECURID);

      String username = CalendarUtils.getCurrentUser();
      CalendarService calendarService = CalendarUtils.getCalendarService();

      CalendarEvent eventCalendar = calendarview.getDataMap().get(eventId);
      if (isOccur && !Utils.isEmpty(recurId)) {
        eventCalendar = calendarview.getRecurrenceMap().get(eventId).get(recurId);
      }

      if (eventCalendar != null) {
        CalendarService calService = CalendarUtils.getCalendarService();
        boolean isMove = false;
        try {
          org.exoplatform.calendar.service.Calendar calendar = null;
          if (eventCalendar.getCalType().equals(CalendarUtils.PRIVATE_TYPE)) {
            calendar = calService.getUserCalendar(username, calendarId);
          } else if (eventCalendar.getCalType().equals(CalendarUtils.SHARED_TYPE)) {
            if (calService.getSharedCalendars(username, true) != null)
              calendar = calService.getSharedCalendars(username, true).getCalendarById(calendarId);
          } else if (eventCalendar.getCalType().equals(CalendarUtils.PUBLIC_TYPE)) {
            calendar = calService.getGroupCalendar(calendarId);
          }
          if (calendar == null) {
            event
                .getRequestContext()
                .getUIApplication()
                .addMessage(new ApplicationMessage("UICalendars.msg.have-no-calendar", null, 1));
          } else {
            Calendar cal = calendarview.getInstanceTempCalendar();
            int hoursBg = (Integer.parseInt(startTime) / 60);
            int minutesBg = (Integer.parseInt(startTime) % 60);
            int hoursEnd = (Integer.parseInt(finishTime) / 60);
            int minutesEnd = (Integer.parseInt(finishTime) % 60);
            try {
              cal.setTimeInMillis(Long.parseLong(currentDate));
              if (hoursBg < cal.getMinimum(Calendar.HOUR_OF_DAY)) {
                hoursBg = 0;
                minutesBg = 0;
              }
              cal.set(Calendar.HOUR_OF_DAY, hoursBg);
              cal.set(Calendar.MINUTE, minutesBg);
              isMove = (eventCalendar.getFromDateTime().getTime() != cal.getTimeInMillis());
              eventCalendar.setFromDateTime(cal.getTime());
              if (hoursEnd >= 24) {
                hoursEnd = 23;
                minutesEnd = 59;
              }
              cal.set(Calendar.HOUR_OF_DAY, hoursEnd);
              cal.set(Calendar.MINUTE, minutesEnd);
              eventCalendar.setToDateTime(cal.getTime());
            } catch (Exception e) {
              if (log.isDebugEnabled()) {
                log.debug("Fail when calculate the time for calendar", e);
              }
              return;
            }
            if (eventCalendar.getToDateTime().before(eventCalendar.getFromDateTime())) {
              return;
            }
            // if it's a 'virtual' occurrence
            if (isOccur && !Utils.isEmpty(recurId)) {
              if (!isMove) {
                UIPopupAction pAction = uiCalendarPortlet.getChild(UIPopupAction.class);
                UIConfirmForm confirmForm = pAction.activate(UIConfirmForm.class, 480);
                confirmForm.setConfirmMessage("update-recurrence-event-confirm-msg");
                confirmForm.setDelete(false);
                confirmForm.setConfig_id(calendarview.getId());
                calendarview.setCurrentOccurrence(eventCalendar);
                event.getRequestContext().addUIComponentToUpdateByAjax(pAction);
              } else {
                calService = CalendarUtils.getCalendarService();
                CalendarEvent originEvent = calService.getRepetitiveEvent(eventCalendar);
                calService.saveOneOccurrenceEvent(originEvent, eventCalendar, username);
              }
              // return;
              // List<CalendarEvent> listEvent = new ArrayList<CalendarEvent>();
              // listEvent.add(eventCalendar);
              // calendarService.updateOccurrenceEvent(calendarId, calendarId, calType, calType,
              // listEvent, username);
            } else {
              if (calType.equals(CalendarUtils.PRIVATE_TYPE)) {
                calendarService.saveUserEvent(username, calendarId, eventCalendar, false);
              } else if (calType.equals(CalendarUtils.SHARED_TYPE)) {
                calendarService.saveEventToSharedCalendar(
                    username, calendarId, eventCalendar, false);
              } else if (calType.equals(CalendarUtils.PUBLIC_TYPE)) {
                calendarService.savePublicEvent(calendarId, eventCalendar, false);
              }
            }
            calendarview.setLastUpdatedEventId(eventId);
            calendarview.refresh();
            UIMiniCalendar uiMiniCalendar =
                uiCalendarPortlet.findFirstComponentOfType(UIMiniCalendar.class);
            event.getRequestContext().addUIComponentToUpdateByAjax(uiMiniCalendar);
            if (isOccur) {
              event.getRequestContext().addUIComponentToUpdateByAjax(calendarview);
            } else {
              JavascriptManager jsManager = event.getRequestContext().getJavascriptManager();
              RequireJS requireJS = jsManager.getRequireJS();
              requireJS.require("PORTLET/calendar/CalendarPortlet", "cal");
              requireJS.addScripts("cal.UIWeekView.setSize();cal.UIWeekView.cleanUp();");
            }
          }
        } catch (PathNotFoundException e) {
          if (log.isDebugEnabled()) {
            log.debug("The calendar is not found", e);
          }
          event
              .getRequestContext()
              .getUIApplication()
              .addMessage(new ApplicationMessage("UICalendars.msg.have-no-calendar", null, 1));
        } catch (Exception ex) {
          if (log.isDebugEnabled()) {
            log.debug("The calendar is not found", ex);
          }
        }
      }
    }