示例#1
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;
    }
  }
  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;
    }
  }
  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;
                }
              });
    }
  }