예제 #1
0
 @Override
 public GwtRpcResponseList<WeekInterface> execute(
     WeekSelectorRequest command, SessionContext context) {
   GwtRpcResponseList<WeekInterface> ret = new GwtRpcResponseList<WeekInterface>();
   Session session = SessionDAO.getInstance().get(command.getSessionId());
   Calendar c = Calendar.getInstance(Locale.US);
   c.setTime(session.getEventBeginDate());
   while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
     c.add(Calendar.DAY_OF_YEAR, -1);
   }
   int sessionYear = session.getSessionStartYear();
   Formats.Format<Date> df = Formats.getDateFormat(Formats.Pattern.DATE_EVENT_SHORT);
   while (!c.getTime().after(session.getEventEndDate())) {
     int dayOfYear = c.get(Calendar.DAY_OF_YEAR);
     if (c.get(Calendar.YEAR) < sessionYear) {
       Calendar x = Calendar.getInstance(Locale.US);
       x.set(c.get(Calendar.YEAR), 11, 31, 0, 0, 0);
       dayOfYear -= x.get(Calendar.DAY_OF_YEAR);
     } else if (c.get(Calendar.YEAR) > sessionYear) {
       Calendar x = Calendar.getInstance(Locale.US);
       x.set(sessionYear, 11, 31, 0, 0, 0);
       dayOfYear += x.get(Calendar.DAY_OF_YEAR);
     }
     WeekInterface week = new WeekInterface();
     week.setDayOfYear(dayOfYear);
     for (int i = 0; i < 7; i++) {
       week.addDayName(
           new DateInterface(
               df.format(c.getTime()), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH)));
       c.add(Calendar.DAY_OF_YEAR, 1);
     }
     ret.add(week);
   }
   return ret;
 }
    @Override
    public boolean check(UserContext user, Session source) {
      if (!permissionSession.check(user, source)) return false;

      return source.getStatusType() == null
          || !source.getStatusType().isActive()
          || source.getStatusType().isTestSession();
    }
예제 #3
0
 @Override
 public void init(
     org.hibernate.Session hibSession,
     Progress progress,
     Session session,
     Collection<InstructionalOffering> offerings) {
   iHibSession = hibSession;
   iSessionId = session.getUniqueId();
 }
    @Override
    public boolean check(UserContext user, Session source) {
      if (!permissionSession.check(user, source)) return false;

      // Is there a mapping to show?
      if (EventDateMapping.hasMapping(source.getUniqueId())) return true;

      // Is there a mapping to add?
      if (user.getCurrentAuthority().hasRight(Right.EventDateMappingEdit)
          && permissionEventDateMappingEdit.check(user, source)) return true;

      return false;
    }
예제 #5
0
  public SubjectArea getSubjectAreaForSession(String subjectAreaAbbreviation, Session session) {
    StringBuffer sb = new StringBuffer();
    sb.append("select sa.* from SubjectArea as sa ");
    sb.append(" where sa.subjectAreaAbbreviation = '" + subjectAreaAbbreviation + "' ");
    sb.append(" and sa.session.getUniqueId = " + session.getUniqueId());

    List results = getQuery(sb.toString()).list();
    if (results.size() != 1) {
      return (null);
    } else {
      return ((SubjectArea) results.get(0));
    }
  }
    @Override
    public boolean check(UserContext user, Session source) {
      if (!permissionSession.check(user, source)) return false;

      int nrCommitted =
          ((Number)
                  SessionDAO.getInstance()
                      .getSession()
                      .createQuery(
                          "select count(s) from Solution s where s.owner.session.uniqueId = :sessionId and s.commited = true")
                      .setLong("sessionId", source.getUniqueId())
                      .setCacheable(true)
                      .uniqueResult())
              .intValue();

      return nrCommitted == 0;
    }
예제 #7
0
  @Override
  public SaveOrApproveEventRpcResponse execute(SaveEventRpcRequest request, EventContext context) {
    if (request.getEvent().hasContact()
        && (request.getEvent().getContact().getExternalId() == null
            || !request
                .getEvent()
                .getContact()
                .getExternalId()
                .equals(context.getUser().getExternalUserId()))) {
      switch (request.getEvent().getType()) {
        case Special:
        case Course:
        case Unavailabile:
          context.checkPermission(Right.EventLookupContact);
      }
    }
    if (request.getEvent().getId() == null) { // new even
      switch (request.getEvent().getType()) {
        case Special:
          context.checkPermission(Right.EventAddSpecial);
          break;
        case Course:
          context.checkPermission(Right.EventAddCourseRelated);
          break;
        case Unavailabile:
          context.checkPermission(Right.EventAddUnavailable);
          break;
        default:
          throw context.getException();
      }
    } else { // existing event
      context.checkPermission(request.getEvent().getId(), "Event", Right.EventEdit);
    }

    // Check main contact email
    if (request.getEvent().hasContact() && request.getEvent().getContact().hasEmail()) {
      try {
        new InternetAddress(request.getEvent().getContact().getEmail(), true);
      } catch (AddressException e) {
        throw new GwtRpcException(
            MESSAGES.badEmailAddress(request.getEvent().getContact().getEmail(), e.getMessage()));
      }
    }
    // Check additional emails
    if (request.getEvent().hasEmail()) {
      String suffix = ApplicationProperty.EmailDefaultAddressSuffix.value();
      for (String address : request.getEvent().getEmail().split("[\n,]")) {
        String email = address.trim();
        if (email.isEmpty()) continue;
        if (suffix != null && email.indexOf('@') < 0) email += suffix;
        try {
          new InternetAddress(email, true);
        } catch (AddressException e) {
          throw new GwtRpcException(MESSAGES.badEmailAddress(address, e.getMessage()));
        }
      }
    }

    org.hibernate.Session hibSession = SessionDAO.getInstance().getSession();
    Transaction tx = hibSession.beginTransaction();
    try {
      Session session = SessionDAO.getInstance().get(request.getSessionId(), hibSession);
      Date now = new Date();

      Event event = null;
      if (request.getEvent().getId() != null) {
        event = EventDAO.getInstance().get(request.getEvent().getId(), hibSession);
      } else {
        switch (request.getEvent().getType()) {
          case Special:
            event = new SpecialEvent();
            break;
          case Course:
            event = new CourseEvent();
            break;
          case Unavailabile:
            event = new UnavailableEvent();
            break;
          default:
            throw new GwtRpcException(
                MESSAGES.failedSaveEventWrongType(request.getEvent().getType().getName(CONSTANTS)));
        }
      }

      SaveOrApproveEventRpcResponse response = new SaveOrApproveEventRpcResponse();

      event.setEventName(request.getEvent().getName());
      if (event.getEventName() == null
          || event.getEventName().isEmpty()
              && request.getEvent().getType() == EventType.Unavailabile)
        event.setEventName(MESSAGES.unavailableEventDefaultName());
      event.setEmail(request.getEvent().getEmail());
      if (context.hasPermission(Right.EventSetExpiration) || event.getExpirationDate() != null)
        event.setExpirationDate(request.getEvent().getExpirationDate());
      event.setSponsoringOrganization(
          request.getEvent().hasSponsor()
              ? SponsoringOrganizationDAO.getInstance()
                  .get(request.getEvent().getSponsor().getUniqueId())
              : null);
      if (event instanceof UnavailableEvent) {
      } else if (event instanceof SpecialEvent) {
        event.setMinCapacity(request.getEvent().getMaxCapacity());
        event.setMaxCapacity(request.getEvent().getMaxCapacity());
      }
      if (event.getAdditionalContacts() == null) {
        event.setAdditionalContacts(new HashSet<EventContact>());
      }
      if (context.hasPermission(Right.EventLookupContact)) {
        Set<EventContact> existingContacts =
            new HashSet<EventContact>(event.getAdditionalContacts());
        event.getAdditionalContacts().clear();
        if (request.getEvent().hasAdditionalContacts())
          for (ContactInterface c : request.getEvent().getAdditionalContacts()) {
            if (c.getExternalId() == null) continue;
            EventContact contact = null;
            for (EventContact x : existingContacts)
              if (c.getExternalId().equals(x.getExternalUniqueId())) {
                contact = x;
                break;
              }
            if (contact == null) {
              contact =
                  (EventContact)
                      hibSession
                          .createQuery("from EventContact where externalUniqueId = :externalId")
                          .setString("externalId", c.getExternalId())
                          .setMaxResults(1)
                          .uniqueResult();
            }
            if (contact == null) {
              contact = new EventContact();
              contact.setExternalUniqueId(c.getExternalId());
              contact.setFirstName(c.getFirstName());
              contact.setMiddleName(c.getMiddleName());
              contact.setLastName(c.getLastName());
              contact.setAcademicTitle(c.getAcademicTitle());
              contact.setEmailAddress(c.getEmail());
              contact.setPhone(c.getPhone());
              hibSession.save(contact);
            }
            event.getAdditionalContacts().add(contact);
          }
      }

      EventContact main = event.getMainContact();
      if (main == null
          || main.getExternalUniqueId() == null
          || !main.getExternalUniqueId().equals(request.getEvent().getContact().getExternalId())) {
        main =
            (EventContact)
                hibSession
                    .createQuery("from EventContact where externalUniqueId = :externalId")
                    .setString("externalId", request.getEvent().getContact().getExternalId())
                    .setMaxResults(1)
                    .uniqueResult();
        if (main == null) {
          main = new EventContact();
          main.setExternalUniqueId(request.getEvent().getContact().getExternalId());
        }
      }
      main.setFirstName(request.getEvent().getContact().getFirstName());
      main.setMiddleName(request.getEvent().getContact().getMiddleName());
      main.setLastName(request.getEvent().getContact().getLastName());
      main.setAcademicTitle(request.getEvent().getContact().getAcademicTitle());
      main.setEmailAddress(request.getEvent().getContact().getEmail());
      main.setPhone(request.getEvent().getContact().getPhone());
      hibSession.saveOrUpdate(main);
      event.setMainContact(main);

      if (event.getNotes() == null) event.setNotes(new HashSet<EventNote>());

      if (event.getMeetings() == null) event.setMeetings(new HashSet<Meeting>());
      Set<Meeting> remove = new HashSet<Meeting>(event.getMeetings());
      TreeSet<Meeting> createdMeetings = new TreeSet<Meeting>();
      Set<Meeting> cancelledMeetings = new TreeSet<Meeting>();
      Set<Meeting> updatedMeetings = new TreeSet<Meeting>();
      for (MeetingInterface m : request.getEvent().getMeetings()) {
        Meeting meeting = null;
        if (m.getApprovalStatus() == ApprovalStatus.Deleted) {
          if (!context.hasPermission(meeting, Right.EventMeetingDelete)
              && context.hasPermission(meeting, Right.EventMeetingCancel)) {
            // Cannot delete, but can cancel --> cancel the meeting instead
            m.setApprovalStatus(ApprovalStatus.Cancelled);
          } else {
            continue;
          }
        }
        if (m.getId() != null)
          for (Iterator<Meeting> i = remove.iterator(); i.hasNext(); ) {
            Meeting x = i.next();
            if (m.getId().equals(x.getUniqueId())) {
              meeting = x;
              i.remove();
              break;
            }
          }
        if (meeting != null) {
          if (m.getApprovalStatus().ordinal() != meeting.getApprovalStatus()) {
            switch (m.getApprovalStatus()) {
              case Cancelled:
                switch (meeting.getEvent().getEventType()) {
                  case Event.sEventTypeFinalExam:
                  case Event.sEventTypeMidtermExam:
                    if (!context.hasPermission(meeting, Right.EventMeetingCancelExam))
                      throw new GwtRpcException(
                          MESSAGES.failedApproveEventNoRightsToCancel(toString(meeting)));
                    break;
                  case Event.sEventTypeClass:
                    if (!context.hasPermission(meeting, Right.EventMeetingCancelClass))
                      throw new GwtRpcException(
                          MESSAGES.failedApproveEventNoRightsToCancel(toString(meeting)));
                    break;
                  default:
                    if (!context.hasPermission(meeting, Right.EventMeetingCancel))
                      throw new GwtRpcException(
                          MESSAGES.failedApproveEventNoRightsToCancel(toString(meeting)));
                    break;
                }
                meeting.setStatus(Meeting.Status.CANCELLED);
                meeting.setApprovalDate(now);
                hibSession.update(meeting);
                cancelledMeetings.add(meeting);
                response.addCancelledMeeting(m);
            }
          } else {
            if (m.getStartOffset()
                    != (meeting.getStartOffset() == null ? 0 : meeting.getStartOffset())
                || m.getEndOffset()
                    != (meeting.getStopOffset() == null ? 0 : meeting.getStopOffset())) {
              if (!context.hasPermission(meeting, Right.EventMeetingEdit))
                throw new GwtRpcException(
                    MESSAGES.failedSaveEventCanNotEditMeeting(toString(meeting)));
              meeting.setStartOffset(m.getStartOffset());
              meeting.setStopOffset(m.getEndOffset());
              hibSession.update(meeting);
              response.addUpdatedMeeting(m);
              updatedMeetings.add(meeting);
            }
          }
        } else {
          response.addCreatedMeeting(m);
          meeting = new Meeting();
          meeting.setEvent(event);
          Location location = null;
          if (m.hasLocation()) {
            if (m.getLocation().getId() != null)
              location = LocationDAO.getInstance().get(m.getLocation().getId(), hibSession);
            else if (m.getLocation().getName() != null)
              location =
                  Location.findByName(
                      hibSession, request.getSessionId(), m.getLocation().getName());
          }
          if (location == null)
            throw new GwtRpcException(MESSAGES.failedSaveEventNoLocation(toString(m)));
          meeting.setLocationPermanentId(location.getPermanentId());
          meeting.setStatus(Meeting.Status.PENDING);
          meeting.setApprovalDate(null);
          if (!context.hasPermission(location, Right.EventLocation))
            throw new GwtRpcException(MESSAGES.failedSaveEventWrongLocation(m.getLocationName()));
          if (request.getEvent().getType() == EventType.Unavailabile
              && !context.hasPermission(location, Right.EventLocationUnavailable))
            throw new GwtRpcException(
                MESSAGES.failedSaveCannotMakeUnavailable(m.getLocationName()));
          if (m.getApprovalStatus() == ApprovalStatus.Approved
              && context.hasPermission(location, Right.EventLocationApprove)) {
            meeting.setStatus(Meeting.Status.APPROVED);
            meeting.setApprovalDate(now);
          }
          if (context.isPastOrOutside(m.getMeetingDate()))
            throw new GwtRpcException(
                MESSAGES.failedSaveEventPastOrOutside(getDateFormat().format(m.getMeetingDate())));
          if (!context.hasPermission(location, Right.EventLocationOverbook)) {
            List<MeetingConflictInterface> conflicts =
                computeConflicts(hibSession, m, event.getUniqueId());
            if (!conflicts.isEmpty())
              throw new GwtRpcException(
                  MESSAGES.failedSaveEventConflict(toString(m), toString(conflicts.get(0))));
          }
          m.setApprovalDate(meeting.getApprovalDate());
          m.setApprovalStatus(meeting.getApprovalStatus());
          meeting.setStartPeriod(m.getStartSlot());
          meeting.setStopPeriod(m.getEndSlot());
          meeting.setStartOffset(m.getStartOffset());
          meeting.setStopOffset(m.getEndOffset());
          meeting.setClassCanOverride(true);
          meeting.setMeetingDate(m.getMeetingDate());
          event.getMeetings().add(meeting);
          createdMeetings.add(meeting);
        }
        // automatic approval
        if (meeting.getApprovalDate() == null) {
          switch (request.getEvent().getType()) {
            case Unavailabile:
            case Class:
            case FinalExam:
            case MidtermExam:
              meeting.setStatus(Meeting.Status.APPROVED);
              meeting.setApprovalDate(now);
              break;
          }
        }
      }

      if (!remove.isEmpty()) {
        for (Iterator<Meeting> i = remove.iterator(); i.hasNext(); ) {
          Meeting m = i.next();
          if (!context.hasPermission(m, Right.EventMeetingDelete)) {
            if (m.getStatus() == Status.CANCELLED || m.getStatus() == Status.REJECTED) {
              i.remove();
              continue;
            }
            throw new GwtRpcException(MESSAGES.failedSaveEventCanNotDeleteMeeting(toString(m)));
          }
          MeetingInterface meeting = new MeetingInterface();
          meeting.setId(m.getUniqueId());
          meeting.setMeetingDate(m.getMeetingDate());
          meeting.setDayOfWeek(Constants.getDayOfWeek(m.getMeetingDate()));
          meeting.setStartTime(m.getStartTime().getTime());
          meeting.setStopTime(m.getStopTime().getTime());
          meeting.setDayOfYear(
              CalendarUtils.date2dayOfYear(session.getSessionStartYear(), m.getMeetingDate()));
          meeting.setStartSlot(m.getStartPeriod());
          meeting.setEndSlot(m.getStopPeriod());
          meeting.setStartOffset(m.getStartOffset() == null ? 0 : m.getStartOffset());
          meeting.setEndOffset(m.getStopOffset() == null ? 0 : m.getStopOffset());
          meeting.setPast(context.isPastOrOutside(m.getStartTime()));
          meeting.setApprovalDate(m.getApprovalDate());
          meeting.setApprovalStatus(m.getApprovalStatus());
          if (m.getLocation() != null) {
            ResourceInterface location = new ResourceInterface();
            location.setType(ResourceType.ROOM);
            location.setId(m.getLocation().getUniqueId());
            location.setName(m.getLocation().getLabel());
            location.setSize(m.getLocation().getCapacity());
            location.setRoomType(m.getLocation().getRoomTypeLabel());
            location.setBreakTime(m.getLocation().getEffectiveBreakTime());
            location.setMessage(m.getLocation().getEventMessage());
            location.setIgnoreRoomCheck(m.getLocation().isIgnoreRoomCheck());
            meeting.setLocation(location);
          }
          response.addDeletedMeeting(meeting);
        }
        event.getMeetings().removeAll(remove);
      }

      EventInterface.DateFormatter df =
          new EventInterface.DateFormatter() {
            Formats.Format<Date> dfShort = Formats.getDateFormat(Formats.Pattern.DATE_EVENT_SHORT);
            Formats.Format<Date> dfLong = Formats.getDateFormat(Formats.Pattern.DATE_EVENT_LONG);

            @Override
            public String formatFirstDate(Date date) {
              return dfShort.format(date);
            }

            @Override
            public String formatLastDate(Date date) {
              return dfLong.format(date);
            }
          };

      FileItem attachment = (FileItem) context.getAttribute(UploadServlet.SESSION_LAST_FILE);
      boolean attached = false;
      if (response.hasCreatedMeetings()) {
        EventNote note = new EventNote();
        note.setEvent(event);
        note.setNoteType(
            event.getUniqueId() == null
                ? EventNote.sEventNoteTypeCreateEvent
                : EventNote.sEventNoteTypeAddMeetings);
        note.setTimeStamp(now);
        note.setUser(context.getUser().getTrueName());
        note.setUserId(context.getUser().getTrueExternalUserId());
        if (request.hasMessage()) note.setTextNote(request.getMessage());
        note.setMeetings(
            EventInterface.toString(response.getCreatedMeetings(), CONSTANTS, "\n", df));
        note.setAffectedMeetings(createdMeetings);
        event.getNotes().add(note);
        NoteInterface n = new NoteInterface();
        n.setDate(now);
        n.setMeetings(note.getMeetings());
        n.setUser(context.getUser().getTrueName());
        n.setType(NoteInterface.NoteType.values()[note.getNoteType()]);
        n.setNote(note.getTextNote());
        if (attachment != null) {
          note.setAttachedName(attachment.getName());
          note.setAttachedFile(attachment.get());
          note.setAttachedContentType(attachment.getContentType());
          attached = true;
          n.setAttachment(attachment.getName());
        }
        response.addNote(n);
      }
      if (response.hasUpdatedMeetings()
          || (!response.hasCreatedMeetings()
              && !response.hasDeletedMeetings()
              && !response.hasCancelledMeetings())) {
        EventNote note = new EventNote();
        note.setEvent(event);
        note.setNoteType(EventNote.sEventNoteTypeEditEvent);
        note.setTimeStamp(now);
        note.setUser(context.getUser().getTrueName());
        note.setUserId(context.getUser().getTrueExternalUserId());
        note.setAffectedMeetings(updatedMeetings);
        if (request.hasMessage()) note.setTextNote(request.getMessage());
        if (response.hasUpdatedMeetings())
          note.setMeetings(
              EventInterface.toString(response.getUpdatedMeetings(), CONSTANTS, "\n", df));
        event.getNotes().add(note);
        NoteInterface n = new NoteInterface();
        n.setDate(now);
        n.setMeetings(note.getMeetings());
        n.setUser(context.getUser().getTrueName());
        n.setType(NoteInterface.NoteType.values()[note.getNoteType()]);
        n.setNote(note.getTextNote());
        if (attachment != null && !attached) {
          note.setAttachedName(attachment.getName());
          note.setAttachedFile(attachment.get());
          note.setAttachedContentType(attachment.getContentType());
          attached = true;
          n.setAttachment(attachment.getName());
        }
        response.addNote(n);
      }
      if (response.hasDeletedMeetings()) {
        EventNote note = new EventNote();
        note.setEvent(event);
        note.setNoteType(EventNote.sEventNoteTypeDeletion);
        note.setTimeStamp(now);
        note.setUser(context.getUser().getTrueName());
        note.setUserId(context.getUser().getTrueExternalUserId());
        if (request.hasMessage()) note.setTextNote(request.getMessage());
        note.setMeetings(
            EventInterface.toString(response.getDeletedMeetings(), CONSTANTS, "\n", df));
        event.getNotes().add(note);
        NoteInterface n = new NoteInterface();
        n.setDate(now);
        n.setMeetings(note.getMeetings());
        n.setUser(context.getUser().getTrueName());
        n.setType(NoteInterface.NoteType.values()[note.getNoteType()]);
        n.setNote(note.getTextNote());
        if (attachment != null && !attached) {
          note.setAttachedName(attachment.getName());
          note.setAttachedFile(attachment.get());
          note.setAttachedContentType(attachment.getContentType());
          attached = true;
          n.setAttachment(attachment.getName());
        }
        response.addNote(n);
      }
      if (response.hasCancelledMeetings()) {
        EventNote note = new EventNote();
        note.setEvent(event);
        note.setNoteType(EventNote.sEventNoteTypeCancel);
        note.setTimeStamp(now);
        note.setUser(context.getUser().getTrueName());
        note.setUserId(context.getUser().getTrueExternalUserId());
        note.setAffectedMeetings(cancelledMeetings);
        if (request.hasMessage()) note.setTextNote(request.getMessage());
        note.setMeetings(
            EventInterface.toString(response.getCancelledMeetings(), CONSTANTS, "\n", df));
        event.getNotes().add(note);
        NoteInterface n = new NoteInterface();
        n.setDate(now);
        n.setMeetings(note.getMeetings());
        n.setUser(context.getUser().getTrueName());
        n.setType(NoteInterface.NoteType.values()[note.getNoteType()]);
        n.setNote(note.getTextNote());
        if (attachment != null && !attached) {
          note.setAttachedName(attachment.getName());
          note.setAttachedFile(attachment.get());
          note.setAttachedContentType(attachment.getContentType());
          attached = true;
          n.setAttachment(attachment.getName());
        }
        response.addNote(n);
      }

      if (request.getEvent().getType() == EventType.Course) {
        CourseEvent ce = (CourseEvent) event;
        ce.setReqAttendance(request.getEvent().hasRequiredAttendance());
        if (ce.getRelatedCourses() == null) ce.setRelatedCourses(new HashSet<RelatedCourseInfo>());
        else ce.getRelatedCourses().clear();
        if (request.getEvent().hasRelatedObjects())
          for (RelatedObjectInterface r : request.getEvent().getRelatedObjects()) {
            RelatedCourseInfo related = new RelatedCourseInfo();
            related.setEvent(ce);
            if (r.getSelection() != null) {
              related.setOwnerId(r.getUniqueId());
              related.setOwnerType(r.getType().ordinal());
              related.setCourse(
                  CourseOfferingDAO.getInstance().get(r.getSelection()[1], hibSession));
            } else {
              switch (r.getType()) {
                case Course:
                  related.setOwner(CourseOfferingDAO.getInstance().get(r.getUniqueId()));
                  break;
                case Class:
                  related.setOwner(Class_DAO.getInstance().get(r.getUniqueId()));
                  break;
                case Config:
                  related.setOwner(InstrOfferingConfigDAO.getInstance().get(r.getUniqueId()));
                  break;
                case Offering:
                  related.setOwner(InstructionalOfferingDAO.getInstance().get(r.getUniqueId()));
                  break;
              }
            }
            ce.getRelatedCourses().add(related);
          }
      }

      if (event.getUniqueId() == null) {
        hibSession.save(event);
        response.setEvent(
            EventDetailBackend.getEventDetail(
                SessionDAO.getInstance().get(request.getSessionId(), hibSession), event, context));
      } else if (event.getMeetings().isEmpty()) {
        response.setEvent(
            EventDetailBackend.getEventDetail(
                SessionDAO.getInstance().get(request.getSessionId(), hibSession), event, context));
        response.getEvent().setId(null);
        hibSession.delete(event);
      } else {
        hibSession.update(event);
        response.setEvent(
            EventDetailBackend.getEventDetail(
                SessionDAO.getInstance().get(request.getSessionId(), hibSession), event, context));
      }

      tx.commit();

      new EventEmail(request, response).send(context);

      return response;
    } catch (Exception ex) {
      tx.rollback();
      if (ex instanceof GwtRpcException) throw (GwtRpcException) ex;
      throw new GwtRpcException(ex.getMessage(), ex);
    }
  }
  public void loadXml(Element root) throws Exception {
    String trimLeadingZeros =
        ApplicationProperties.getProperty("tmtbl.data.exchange.trim.externalId", "false");
    if (trimLeadingZeros.equals("true")) {
      trimLeadingZerosFromExternalId = true;
    }
    try {
      String rootElementName = "lastLikeCourseDemand";
      if (!root.getName().equalsIgnoreCase(rootElementName)) {
        throw new Exception("Given XML file is not a Course Offerings load file.");
      }

      String campus = root.attributeValue("campus");
      String year = root.attributeValue("year");
      String term = root.attributeValue("term");
      String created = getOptionalStringAttribute(root, "created");
      Session session = Session.getSessionUsingInitiativeYearTerm(campus, year, term);
      if (session == null) {
        throw new Exception("No session found for the given campus, year, and term.");
      }
      loadSubjectAreas(session.getSessionId());
      loadCourseOfferings(session.getSessionId());

      beginTransaction();
      if (created != null) {
        ChangeLog.addChange(
            getHibSession(),
            getManager(),
            session,
            session,
            created,
            ChangeLog.Source.DATA_IMPORT_LASTLIKE_DEMAND,
            ChangeLog.Operation.UPDATE,
            null,
            null);
      }

      getHibSession()
          .createQuery(
              "delete LastLikeCourseDemand ll where ll.subjectArea.uniqueId in "
                  + "(select s.uniqueId from SubjectArea s where s.session.uniqueId=:sessionId)")
          .setLong("sessionId", session.getUniqueId())
          .executeUpdate();

      flush(true);

      for (Iterator it = root.elementIterator(); it.hasNext(); ) {
        Element element = (Element) it.next();
        String externalId = element.attributeValue("externalId");
        if (trimLeadingZerosFromExternalId) {
          try {
            Integer num = new Integer(externalId);
            externalId = num.toString();
          } catch (Exception e) {
            // do nothing
          }
        }
        Student student = fetchStudent(externalId, session.getSessionId());
        if (student == null) {
          student = new Student();
          student.setFirstName("Unknown");
          student.setLastName("Student");
          student.setExternalUniqueId(externalId);
          student.setFreeTimeCategory(new Integer(0));
          student.setSchedulePreference(new Integer(0));
          student.setSession(session);
          getHibSession().save(student);
          getHibSession().flush();
          getHibSession().refresh(student);
        }
        loadCourses(element, student, session);
        flushIfNeeded(true);
      }

      flush(true);

      getHibSession()
          .createQuery(
              "update CourseOffering c set c.demand="
                  + "(select count(distinct d.student) from LastLikeCourseDemand d where "
                  + "(c.subjectArea=d.subjectArea and c.courseNbr=d.courseNbr)) where "
                  + "c.permId is null and c.subjectArea.uniqueId in (select sa.uniqueId from SubjectArea sa where sa.session.uniqueId=:sessionId)")
          .setLong("sessionId", session.getUniqueId())
          .executeUpdate();

      getHibSession()
          .createQuery(
              "update CourseOffering c set c.demand="
                  + "(select count(distinct d.student) from LastLikeCourseDemand d where "
                  + "d.student.session=c.subjectArea.session and c.permId=d.coursePermId) where "
                  + "c.permId is not null and c.subjectArea.uniqueId in (select sa.uniqueId from SubjectArea sa where sa.session.uniqueId=:sessionId)")
          .setLong("sessionId", session.getUniqueId())
          .executeUpdate();

      commitTransaction();
    } catch (Exception e) {
      fatal("Exception: " + e.getMessage(), e);
      rollbackTransaction();
      throw e;
    }
  }
예제 #9
0
  public void loadXml(Element root) throws Exception {
    if (!root.getName().equalsIgnoreCase("roomSharing")) {
      throw new Exception("Given XML file is not a Room Sharing load file.");
    }
    try {
      beginTransaction();

      String campus = root.attributeValue("campus");
      String year = root.attributeValue("year");
      String term = root.attributeValue("term");
      iTimeFormat = root.attributeValue("timeFormat");
      if (iTimeFormat == null) iTimeFormat = "HHmm";

      Session session = Session.getSessionUsingInitiativeYearTerm(campus, year, term);
      if (session == null) {
        throw new Exception("No session found for the given campus, year, and term.");
      }

      if (!"true".equals(root.attributeValue("force"))
          && Solution.hasTimetable(session.getUniqueId())) {
        info(
            "Note: set the attribute force='true' of the root element to override the following import eligibility check.");
        throw new Exception(
            "Room sharing import is disabled: "
                + session.getLabel()
                + " already has a committed timetable.");
      }

      info("Loading rooms...");
      Set<String> avoidRoomId = new HashSet<String>();
      Set<String> avoidRoomName = new HashSet<String>();
      Map<String, Location> id2location = new HashMap<String, Location>();
      Map<String, Location> name2location = new HashMap<String, Location>();
      for (Location location :
          (List<Location>)
              getHibSession()
                  .createQuery("from Location where session.uniqueId = :sessionId")
                  .setLong("sessionId", session.getUniqueId())
                  .list()) {
        if (location.getExternalUniqueId() != null && !avoidRoomId.contains(avoidRoomId)) {
          Location old = id2location.put(location.getExternalUniqueId(), location);
          if (old != null) {
            warn(
                "There are two or more rooms with the same external id "
                    + location.getExternalUniqueId()
                    + ": "
                    + location.getLabel()
                    + " and "
                    + old.getLabel()
                    + ".");
            avoidRoomId.add(location.getExternalUniqueId());
          }
        }
        if (!avoidRoomName.contains(location.getLabel())) {
          Location old = name2location.put(location.getLabel(), location);
          if (old != null) {
            warn("There are two or more rooms with the same name " + location.getLabel() + ".");
            avoidRoomName.add(location.getLabel());
          }
        }
      }

      info("Loading departments...");
      Map<String, Department> id2department = new HashMap<String, Department>();
      Map<String, Department> code2department = new HashMap<String, Department>();
      for (Department dept :
          (List<Department>)
              getHibSession()
                  .createQuery("from Department where session.uniqueId = :sessionId")
                  .setLong("sessionId", session.getUniqueId())
                  .list()) {
        if (dept.getExternalUniqueId() != null) {
          Department old = id2department.put(dept.getExternalUniqueId(), dept);
          if (old != null) {
            warn(
                "There are two departments with the same external id "
                    + dept.getExternalUniqueId()
                    + ": "
                    + dept.getLabel()
                    + " and "
                    + old.getLabel()
                    + ".");
          }
        }
        Department old = code2department.put(dept.getDeptCode(), dept);
        if (old != null) {
          warn(
              "There are two rooms with the same code "
                  + dept.getDeptCode()
                  + ": "
                  + dept.getName()
                  + " and "
                  + old.getName()
                  + ".");
        }
      }

      info("Importing room sharing...");
      int nrChanged = 0;
      for (Iterator i = root.elementIterator("location"); i.hasNext(); ) {
        Element locEl = (Element) i.next();
        Location location = null;

        String locId = locEl.attributeValue("id");
        if (locId != null && !avoidRoomId.contains(locId)) {
          location = id2location.get(locId);
          if (location == null) warn("Location of id " + locId + " does not exist.");
        }

        if (location == null) {
          String building = locEl.attributeValue("building");
          String roomNbr = locEl.attributeValue("roomNbr");
          if (building != null
              && roomNbr != null
              && !avoidRoomName.contains(building + " " + roomNbr)) {
            location = name2location.get(building + " " + roomNbr);
            if (location == null)
              warn(
                  "Location of building "
                      + building
                      + " and room number "
                      + roomNbr
                      + " does not exist.");
          }
        }

        if (location == null) {
          String name = locEl.attributeValue("name");
          if (name != null && !avoidRoomName.contains(name)) {
            location = name2location.get(name);
            if (location == null) warn("Location of name " + name + " does not exist.");
          }
        }

        if (location == null) continue;

        Set<RoomDept> existing = new HashSet<RoomDept>(location.getRoomDepts());
        Set<Department> departments = new HashSet<Department>();
        boolean changed = false;

        String note = locEl.attributeValue("note");
        if (note == null && location.getShareNote() != null) {
          location.setShareNote(null);
          info(location.getLabel() + ": share note removed.");
          changed = true;
        } else if (note != null && !note.equals(location.getShareNote())) {
          location.setShareNote(note);
          info(location.getLabel() + ": share note changed to '" + note + "'.");
          changed = true;
        }

        department:
        for (Iterator j = locEl.elementIterator("department"); j.hasNext(); ) {
          Element deptEl = (Element) j.next();
          Department dept = null;

          String deptId = deptEl.attributeValue("id");
          if (deptId != null) {
            dept = id2department.get(deptId);
            if (dept == null)
              warn(location.getLabel() + ": Department of id " + deptId + " does not exist.");
          }

          String deptCode = deptEl.attributeValue("code");
          if (deptCode != null) {
            dept = code2department.get(deptCode);
            if (dept == null)
              warn(location.getLabel() + ": Department of code " + deptCode + " does not exist.");
          }

          if (dept == null) continue;
          Boolean control = "true".equals(deptEl.attributeValue("control"));

          for (Iterator<RoomDept> k = existing.iterator(); k.hasNext(); ) {
            RoomDept rd = k.next();
            if (rd.getDepartment().equals(dept)) {
              if (!control.equals(rd.getControl())) {
                rd.setControl(control);
                getHibSession().update(rd);
                info(
                    location.getLabel()
                        + ": "
                        + (control
                            ? " control moved to " + dept.getLabel()
                            : " control removed from " + dept.getLabel()));
                changed = true;
              }
              k.remove();
              departments.add(dept);
              continue department;
            }
          }

          RoomDept rd = new RoomDept();
          rd.setControl(control);
          rd.setDepartment(dept);
          rd.setRoom(location);
          location.getRoomDepts().add(rd);
          dept.getRoomDepts().add(rd);
          getHibSession().save(rd);
          departments.add(dept);
          info(
              location.getLabel()
                  + ": added "
                  + (control ? "controlling " : "")
                  + " department"
                  + dept.getLabel());
          changed = true;
        }

        for (RoomDept rd : existing) {
          info(
              location.getLabel()
                  + ": removed "
                  + (rd.isControl() ? "controlling " : "")
                  + " department"
                  + rd.getDepartment().getLabel());
          location.getRoomDepts().remove(rd);
          rd.getDepartment().getRoomDepts().remove(rd);
          getHibSession().delete(rd);
          changed = true;
        }

        RoomSharingModel model = location.getRoomSharingModel();
        String oldModel = model.toString();
        model.setPreferences(null);

        Element sharingEl = locEl.element("sharing");
        if (sharingEl != null) {
          for (Iterator j = sharingEl.elementIterator(); j.hasNext(); ) {
            Element el = (Element) j.next();
            TimeObject time =
                new TimeObject(
                    el.attributeValue("start"),
                    el.attributeValue("end"),
                    el.attributeValue("days"));

            String pref = null;
            if ("unavailable".equals(el.getName())) {
              pref = RoomSharingModel.sNotAvailablePref.toString();
            } else if ("assigned".equals(el.getName())) {
              Department dept = null;

              String deptId = el.attributeValue("id");
              if (deptId != null) {
                dept = id2department.get(deptId);
                if (dept == null)
                  warn(location.getLabel() + ": Department of id " + deptId + " does not exist.");
              }

              String deptCode = el.attributeValue("code");
              if (deptCode != null) {
                dept = code2department.get(deptCode);
                if (dept == null)
                  warn(
                      location.getLabel()
                          + ": Department of code "
                          + deptCode
                          + " does not exist.");
              }

              if (dept == null) continue;
              if (!departments.contains(dept)) {
                warn(
                    location.getLabel()
                        + ": Department "
                        + dept.getLabel()
                        + " is not among the room sharing departments.");
                continue;
              }

              pref = dept.getUniqueId().toString();
            }

            if (pref == null) continue;

            if (time.hasDays()) {
              for (int d : time.getDays())
                for (int t = time.getStartPeriod(); t < time.getEndPeriod(); t++)
                  model.setPreference(d, t, pref);
            } else {
              for (int d = 0; d < model.getNrDays(); d++)
                for (int t = time.getStartPeriod(); t < time.getEndPeriod(); t++)
                  model.setPreference(d, t, pref);
            }
          }
        }

        String newModel = model.toString();
        if (!oldModel.equals(newModel)) {
          info(
              location.getLabel()
                  + ": room sharing changed to "
                  + (newModel.isEmpty() ? "free for all" : newModel));
          changed = true;
        }

        location.setRoomSharingModel(model);
        getHibSession().update(location);

        if (changed) nrChanged++;
      }

      if (nrChanged == 0) {
        info("No change detected.");
      } else {
        info(nrChanged + " locations have changed.");
      }
      info("All done.");

      commitTransaction();
    } catch (Exception e) {
      fatal("Exception: " + e.getMessage(), e);
      rollbackTransaction();
      throw e;
    }
  }
예제 #10
0
  protected void startServer() {
    final Session session =
        Session.getSessionUsingInitiativeYearTerm(
            ApplicationProperties.getProperty("initiative", "woebegon"),
            ApplicationProperties.getProperty("year", "2010"),
            ApplicationProperties.getProperty("term", "Fal"));

    boolean remote = "true".equalsIgnoreCase(ApplicationProperties.getProperty("remote", "true"));

    if (session == null) {
      sLog.error(
          "Academic session not found, use properties initiative, year, and term to set academic session.");
      System.exit(0);
    } else {
      sLog.info("Session: " + session);
    }

    iSessionId = session.getUniqueId();

    OnlineSectioningLogger.getInstance().setEnabled(false);

    if (remote) {
      try {
        iChannel =
            new JChannel(
                JGroupsUtils.getConfigurator(
                    ApplicationProperty.SolverClusterConfiguration.value()));
        iChannel.setUpHandler(new MuxUpHandler());

        iSolverServer = new DummySolverServer(iChannel);

        iChannel.connect("UniTime:rpc");
        iChannel.getState(null, 0);

        if (getServer() == null) throw new Exception(session.getLabel() + " is not available");
      } catch (Exception e) {
        sLog.error("Failed to access the solver server: " + e.getMessage(), e);
        if (iChannel != null && iChannel.isConnected()) iChannel.disconnect();
        if (iChannel != null && iChannel.isOpen()) iChannel.close();
        System.exit(0);
      }
    } else {
      iServer =
          new InMemoryServer(
              new OnlineSectioningServerContext() {
                @Override
                public boolean isWaitTillStarted() {
                  return true;
                }

                @Override
                public EmbeddedCacheManager getCacheManager() {
                  return null;
                }

                @Override
                public Long getAcademicSessionId() {
                  return session.getUniqueId();
                }

                @Override
                public LockService getLockService() {
                  return null;
                }
              });
    }
  }