/**
   * Updates an calendar inside an transaction.
   *
   * @throws Exception
   */
  public void updateCalendar(
      Calendar calendar,
      String name,
      String description,
      String[] roles,
      String groups[],
      EventType eventType,
      Session session)
      throws Exception {
    calendar.setName(name);
    calendar.setDescription(description);
    calendar.setEventType(eventType);

    Iterator oldRolesIterator = calendar.getOwningRoles().iterator();
    while (oldRolesIterator.hasNext()) {
      Role role = (Role) oldRolesIterator.next();
      session.delete(role);
      oldRolesIterator.remove();
    }

    Iterator oldGroupsIterator = calendar.getOwningGroups().iterator();
    while (oldGroupsIterator.hasNext()) {
      Group group = (Group) oldGroupsIterator.next();
      session.delete(group);
      oldGroupsIterator.remove();
    }

    if (roles != null) {
      for (int i = 0; i < roles.length; i++) {
        Role role = new Role();
        String roleName = roles[i];
        role.setCalendar(calendar);
        role.setName(roleName);
        session.save(role);
        calendar.getOwningRoles().add(role);
      }
    }

    if (groups != null) {
      for (int i = 0; i < groups.length; i++) {
        Group group = new Group();
        String groupName = groups[i];
        group.setCalendar(calendar);
        // log.debug("ID: " + calendar.getId());
        group.setName(groupName);
        session.save(group);
        calendar.getOwningGroups().add(group);
      }
    }

    session.update(calendar);
  }
  /** This method is used to create a new Calendar object in the database inside a transaction. */
  public Calendar createCalendar(
      String name,
      String description,
      String[] roles,
      String[] groups,
      Long eventTypeId,
      Session session)
      throws HibernateException, Exception {
    EventType eventType = EventTypeController.getController().getEventType(eventTypeId, session);

    Calendar calendar = new Calendar();
    calendar.setName(name);
    calendar.setDescription(description);

    calendar.setEventType(eventType);
    session.save(calendar);

    for (int i = 0; i < roles.length; i++) {
      Role role = new Role();
      String roleName = roles[i];
      role.setName(roleName);
      role.setCalendar(calendar);
      session.save(role);
      calendar.getOwningRoles().add(role);
    }

    for (int i = 0; i < groups.length; i++) {
      Group group = new Group();
      String groupName = groups[i];
      group.setName(groupName);
      group.setCalendar(calendar);
      session.save(group);
      calendar.getOwningGroups().add(group);
    }

    return calendar;
  }