public static void setupLocalSolver(String codeBase, String host, int port) {
    if (sInstance == null || sLocalSolverInitialized) return;
    synchronized (sInstance) {
      try {
        File webInfDir = new File(ApplicationProperties.getBasePath());
        File timetablingDir = webInfDir.getParentFile();
        File solverDir = new File(timetablingDir, "solver");
        File solverJnlp = new File(solverDir, "solver.jnlp");

        Document document = (new SAXReader()).read(solverJnlp);
        Element root = document.getRootElement();
        root.attribute("codebase")
            .setValue(codeBase + (codeBase.endsWith("/") ? "" : "/") + "solver");

        boolean hostSet = false, portSet = false;
        Element resources = root.element("resources");
        for (Iterator i = resources.elementIterator("property"); i.hasNext(); ) {
          Element property = (Element) i.next();
          if ("tmtbl.solver.register.host".equals(property.attributeValue("name"))) {
            property.attribute("value").setValue(host);
            hostSet = true;
          }
          if ("tmtbl.solver.register.port".equals(property.attributeValue("name"))) {
            property.attribute("value").setValue(String.valueOf(port));
            portSet = true;
          }
        }

        if (!hostSet) {
          resources
              .addElement("property")
              .addAttribute("name", "tmtbl.solver.register.host")
              .addAttribute("value", host);
        }
        if (!portSet) {
          resources
              .addElement("property")
              .addAttribute("name", "tmtbl.solver.register.port")
              .addAttribute("value", String.valueOf(port));
        }

        FileOutputStream fos = null;
        try {
          fos = new FileOutputStream(solverJnlp);
          (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document);
          fos.flush();
          fos.close();
          fos = null;
        } finally {
          try {
            if (fos != null) fos.close();
          } catch (IOException e) {
          }
        }
      } catch (Exception e) {
        sLog.debug("Unable to alter solver.jnlp, reason: " + e.getMessage(), e);
      }
      sLocalSolverInitialized = true;
    }
  }
  public void test(int nrTasks, int... nrConcurrent) {
    try {
      configureLogging();

      HibernateUtil.configureHibernate(ApplicationProperties.getProperties());

      startServer();

      List<Operation> operations = operations();

      Collections.shuffle(operations);

      for (int c : nrConcurrent) {
        run(
            nrTasks <= 0 || operations.size() <= nrTasks
                ? operations
                : operations.subList(0, nrTasks),
            c);
      }

      logCounters();

      writeReports();

      stopServer();
    } catch (Exception e) {
      sLog.fatal("Test failed: " + e.getMessage(), e);
    } finally {
      close();
    }
  }
Example #3
0
  public static void main(String[] args) {
    try {
      HibernateUtil.configureHibernate(ApplicationProperties.getProperties());

      Long sessionId =
          Long.valueOf(ApplicationProperties.getProperty("tmtbl.pdf.worksheet.session", "165924"));
      Session session = new SessionDAO().get(sessionId);
      if (session == null) {
        System.err.println(
            "Academic session "
                + sessionId
                + " not found, use property tmtbl.pdf.worksheet.session to set academic session.");
        System.exit(0);
      } else {
        System.out.println("Session: " + session);
      }
      TreeSet subjectAreas = null;
      if (args.length > 0) {
        subjectAreas = new TreeSet();
        for (int i = 0; i < args.length; i++) {
          SubjectArea sa = SubjectArea.findByAbbv(sessionId, args[i]);
          if (sa == null) System.err.println("Subject area " + args[i] + " not found.");
          else subjectAreas.add(sa);
        }
      } else {
        subjectAreas = new TreeSet(SubjectArea.getSubjectAreaList(sessionId));
      }

      for (Iterator i = subjectAreas.iterator(); i.hasNext(); ) {
        SubjectArea sa = (SubjectArea) i.next();
        System.out.println("Printing subject area " + sa.getSubjectAreaAbbreviation() + " ...");
        FileOutputStream out = new FileOutputStream(sa.getSubjectAreaAbbreviation() + ".pdf");
        List<SubjectArea> sas = new ArrayList<SubjectArea>();
        sas.add(sa);
        PdfWorksheet.print(out, sas);
        out.flush();
        out.close();
      }

      HibernateUtil.closeHibernate();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #4
0
  public JavaMailWrapper() {
    Properties p = ApplicationProperties.getProperties();
    if (p.getProperty("mail.smtp.host") == null && p.getProperty("tmtbl.smtp.host") != null)
      p.setProperty("mail.smtp.host", p.getProperty("tmtbl.smtp.host"));

    final String user = ApplicationProperty.EmailSmtpUser.value();
    final String password = ApplicationProperty.EmailSmtpPassword.value();

    Authenticator a = null;
    if (user != null && password != null) {
      p.setProperty("mail.smtp.user", user);
      p.setProperty("mail.smtp.auth", "true");
      a =
          new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
              return new PasswordAuthentication(user, password);
            }
          };
    }

    iMailSession = javax.mail.Session.getDefaultInstance(p, a);
    iMail = new MimeMessage(iMailSession);
    iBody = new MimeMultipart();
  }
Example #5
0
 public Properties getProperties() {
   if (iProperties == null) iProperties = ApplicationProperties.getProperties();
   return iProperties;
 }
  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;
    }
  }
/** @author Tomas Muller */
public class SolverRegisterService extends Thread {
  static Log sLog = LogFactory.getLog(SolverRegisterService.class);
  private static SolverRegisterService sInstance = null;
  private ServerSocket iServerSocket = null;
  private Set iServers = new HashSet();
  public static File sBackupDir = ApplicationProperties.getRestoreFolder();
  public static File sPassivationDir = ApplicationProperties.getPassivationFolder();
  private static ShutdownHook sHook = null;
  private static int sTimeout = 300000; // 5 minutes
  private static boolean sLocalSolverInitialized = false;
  private Date iStartTime = null;

  private SolverRegisterService() {
    setDaemon(true);
    setName("SolverRegister.Service");
  }

  public static int getPort() {
    if (sInstance == null || sInstance.iServerSocket == null) return -1;
    return sInstance.iServerSocket.getLocalPort();
  }

  public static synchronized void startService() {
    if (sInstance != null) stopService();

    sInstance = new SolverRegisterService();
    sInstance.start();
    sLog.info("service started");
  }

  public static synchronized void stopService() {
    if (sInstance == null) return;
    try {
      synchronized (sInstance.iServers) {
        for (Iterator i = sInstance.iServers.iterator(); i.hasNext(); ) {
          RemoteSolverServerProxy server = (RemoteSolverServerProxy) i.next();
          execute(new DisconnectProxyCallback(server), 10000);
        }
        sInstance.iServers.clear();
      }
      if (sInstance.iServerSocket != null) sInstance.iServerSocket.close();
      sInstance.join(30000);
    } catch (Exception e) {
      sLog.warn("Unable to stop service, reason: " + e.getMessage(), e);
    }
    sInstance = null;
    sLog.info("service stopped");
  }

  public static void setupLocalSolver(String codeBase, String host, int port) {
    if (sInstance == null || sLocalSolverInitialized) return;
    synchronized (sInstance) {
      try {
        File webInfDir = new File(ApplicationProperties.getBasePath());
        File timetablingDir = webInfDir.getParentFile();
        File solverDir = new File(timetablingDir, "solver");
        File solverJnlp = new File(solverDir, "solver.jnlp");

        Document document = (new SAXReader()).read(solverJnlp);
        Element root = document.getRootElement();
        root.attribute("codebase")
            .setValue(codeBase + (codeBase.endsWith("/") ? "" : "/") + "solver");

        boolean hostSet = false, portSet = false;
        Element resources = root.element("resources");
        for (Iterator i = resources.elementIterator("property"); i.hasNext(); ) {
          Element property = (Element) i.next();
          if ("tmtbl.solver.register.host".equals(property.attributeValue("name"))) {
            property.attribute("value").setValue(host);
            hostSet = true;
          }
          if ("tmtbl.solver.register.port".equals(property.attributeValue("name"))) {
            property.attribute("value").setValue(String.valueOf(port));
            portSet = true;
          }
        }

        if (!hostSet) {
          resources
              .addElement("property")
              .addAttribute("name", "tmtbl.solver.register.host")
              .addAttribute("value", host);
        }
        if (!portSet) {
          resources
              .addElement("property")
              .addAttribute("name", "tmtbl.solver.register.port")
              .addAttribute("value", String.valueOf(port));
        }

        FileOutputStream fos = null;
        try {
          fos = new FileOutputStream(solverJnlp);
          (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document);
          fos.flush();
          fos.close();
          fos = null;
        } finally {
          try {
            if (fos != null) fos.close();
          } catch (IOException e) {
          }
        }
      } catch (Exception e) {
        sLog.debug("Unable to alter solver.jnlp, reason: " + e.getMessage(), e);
      }
      sLocalSolverInitialized = true;
    }
  }

  public void run() {
    iStartTime = new Date();
    try {
      ConnectionFactory.init(
          ApplicationProperties.getProperties(), ApplicationProperties.getDataFolder());
      try {
        while (true) {
          try {
            iServerSocket =
                ConnectionFactory.getServerSocketFactory()
                    .createServerSocket(
                        Integer.parseInt(
                            ApplicationProperties.getProperty(
                                "tmtbl.solver.register.port", "9998")));
            sLog.info(
                "Service is running at "
                    + iServerSocket.getInetAddress().getHostName()
                    + ":"
                    + iServerSocket.getLocalPort());
            break;
          } catch (BindException e) {
            try {
              sLog.warn("Prior instance of service still running");
              Socket socket =
                  ConnectionFactory.getSocketFactory()
                      .createSocket(
                          "localhost",
                          Integer.parseInt(
                              ApplicationProperties.getProperty(
                                  "tmtbl.solver.register.port", "9998")));
              RemoteIo.writeObject(socket, "quit");
              Object answer = RemoteIo.readObject(socket);
              sLog.warn("quit command sent, answer: " + answer);
              socket.close();
            } catch (Exception f) {
              sLog.warn("Unable to connect to prior instance", f);
            }
            sleep(1000);
          }
        }
      } catch (IOException io) {
        sLog.error("Unable to start service, reason: " + io.getMessage(), io);
        return;
      }
      while (!iServerSocket.isClosed()) {
        try {
          Socket socket = iServerSocket.accept();
          socket.setKeepAlive(true);
          sLog.debug("Client " + socket.getInetAddress() + " connected.");
          (new Thread(new SolverConnection(socket))).start();
        } catch (Exception e) {
          if (!iServerSocket.isClosed())
            sLog.warn("Unable to accept new connection, reason:" + e.getMessage(), e);
        }
      }
    } catch (Exception e) {
      sLog.error("Unexpected exception occured, reason: " + e.getMessage(), e);
    } finally {
      try {
        if (iServerSocket != null && !iServerSocket.isClosed()) iServerSocket.close();
      } catch (Exception e) {
        sLog.warn("Unable to close socket, reason: " + e.getMessage(), e);
      }
    }
  }

  public Set getServers() {
    return iServers;
  }

  public static SolverRegisterService getInstance() {
    return sInstance;
  }

  public static class ShutdownHook extends Thread {
    public ShutdownHook() {
      setName("SolverRegister.ShutdownHook");
    }

    public void run() {
      sLog.info("shutdown");
      stopService();
    }
  }

  public class SolverConnection extends Thread {
    private Socket iSocket;
    private boolean iFinish = false;
    private RemoteSolverServerProxy iProxy = null;
    private long iLastPing = -1;

    protected SolverConnection(Socket socket) {
      iSocket = socket;
      setName("SolverRegister.SolverConnection");
    }

    public Socket getSocket() {
      return iSocket;
    }

    public void stopConnection() {
      iFinish = true;
    }

    public void unregister() {
      if (iProxy != null) {
        synchronized (iServers) {
          if (iServers.remove(iProxy)) sLog.info("Sever " + iProxy + " disconnected.");
        }
      }
      iProxy = null;
    }

    public boolean isConnected() {
      return (iSocket != null && !iSocket.isClosed());
    }

    public void run() {
      try {
        while (!iFinish) {
          Object command = null;
          try {
            command = RemoteIo.readObject(iSocket);
          } catch (java.io.EOFException ex) {
          }
          ;
          if (command == null) continue;
          Object ret = null;
          try {
            ret = answer(command);
          } catch (Exception e) {
            ret = e;
          }
          RemoteIo.writeObject(iSocket, ret);
        }
      } catch (Exception e) {
        sLog.error(e.getMessage(), e);
      }
      unregister();
      try {
        iSocket.close();
      } catch (Exception e) {
      }
    }

    public long lastActive() {
      return (System.currentTimeMillis() - iLastPing);
    }

    public boolean isActive() {
      return (lastActive() < sTimeout);
    }

    private Object answer(Object command) throws Exception {
      if ("quit".equals(command)) {
        stopConnection();
        stopService();
        return "ack";
      }
      if ("ping".equals(command)) {
        iLastPing = System.currentTimeMillis();
        if (iProxy != null && !iServers.contains(iProxy)) {
          sLog.warn("Server " + iProxy + " is alive, but it is not registered.");
          iServers.add(iProxy);
        }
        return "ack";
      }
      if ("url".equals(command)) {
        return HibernateUtil.getConnectionUrl();
      }
      if ("properties".equals(command)) {
        return ApplicationProperties.getProperties();
      }
      if ("disconnect".equals(command)) {
        unregister();
        stopConnection();
        return "ack";
      }
      if (command instanceof Object[]) {
        Object cmd[] = (Object[]) command;
        if ("connect".equals(cmd[0])) {
          int port = ((Integer) cmd[1]).intValue();
          iProxy = new RemoteSolverServerProxy(iSocket.getInetAddress(), port, this);
          sLog.debug("Sever " + iProxy + " connected.");
          synchronized (iServers) {
            if (iServers.contains(iProxy)) {
              sLog.warn("Previous run of the server " + iProxy + " was not properly disconnected.");
              for (Iterator i = iServers.iterator(); i.hasNext(); ) {
                RemoteSolverServerProxy oldProxy = (RemoteSolverServerProxy) i.next();
                if (oldProxy.equals(iProxy)) {
                  try {
                    execute(new DisconnectProxyCallback(oldProxy), 10000);
                  } catch (Exception e) {
                  }
                }
              }
              iServers.remove(iProxy);
            }
            iServers.add(iProxy);
          }
          return "ack";
        }
        if ("saveToFile".equals(cmd[0])) {
          TimetableInfoUtil.getInstance().saveToFile((String) cmd[1], (TimetableInfo) cmd[2]);
          return "ack";
        }
        if ("loadFromFile".equals(cmd[0])) {
          return TimetableInfoUtil.getInstance().loadFromFile((String) cmd[1]);
        }
        if ("deleteFile".equals(cmd[0])) {
          TimetableInfoUtil.getInstance().deleteFile((String) cmd[1]);
          return "ack";
        }
        if ("resource".equals(cmd[0])) {
          URL resource = SolverRegisterService.class.getClassLoader().getResource((String) cmd[1]);
          if (resource == null) return null;
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          InputStream in = resource.openStream();
          byte[] buffer = new byte[1024];
          int read = 0;
          while ((read = in.read(buffer)) >= 0) out.write(buffer, 0, read);
          out.flush();
          out.close();
          in.close();
          return out.toByteArray();
        }
        if ("refreshSolution".equals(cmd[0])) {
          try {
            Solution.refreshSolution((Long) cmd[1]);
          } finally {
            _BaseRootDAO.closeCurrentThreadSessions();
          }
          return null;
        }
        if ("hasRoomAvailability".equals(cmd[0])) {
          return new Boolean(RoomAvailability.getInstance() != null);
        }
        if ("activateRoomAvailability".equals(cmd[0])) {
          if (RoomAvailability.getInstance() != null) {
            RoomAvailability.getInstance()
                .activate(
                    new SessionDAO().get((Long) cmd[1]),
                    (Date) cmd[2],
                    (Date) cmd[3],
                    (String) cmd[4],
                    "true"
                        .equals(
                            ApplicationProperties.getProperty(
                                "tmtbl.room.availability.solver.waitForSync", "true")));
            return "ack";
          }
          return null;
        }
        if ("getRoomAvailability".equals(cmd[0])) {
          if (RoomAvailability.getInstance() != null) {
            return RoomAvailability.getInstance()
                .getRoomAvailability(
                    new LocationDAO().get((Long) cmd[1]),
                    (Date) cmd[2],
                    (Date) cmd[3],
                    (String) cmd[4]);
          }
          return null;
        }
        if ("getRoomAvailabilityTimeStamp".equals(cmd[0])) {
          if (RoomAvailability.getInstance() != null) {
            return RoomAvailability.getInstance()
                .getTimeStamp((Date) cmd[1], (Date) cmd[2], (String) cmd[3]);
          }
          return null;
        }
      }
      sLog.warn("Unknown command " + command);
      return null;
    }
  }

  protected void finalize() throws Throwable {
    try {
      if (iServerSocket != null) iServerSocket.close();
    } catch (Exception e) {
    }
    iServerSocket = null;
    super.finalize();
  }

  public static void addShutdownHook() {
    if (sHook != null) removeShutdownHook();
    sHook = new ShutdownHook();
    Runtime.getRuntime().addShutdownHook(sHook);
  }

  public static void removeShutdownHook() {
    if (sHook == null) return;
    Runtime.getRuntime().removeShutdownHook(sHook);
    sHook = null;
  }

  public static Object execute(Callback callback, long timeout) throws Exception {
    Exec ex = new Exec(callback);
    if (timeout <= 0) {
      ex.run();
    } else {
      Thread et = new Thread(ex);
      et.start();
      et.join(timeout);
      if (et.isAlive()) et.interrupt();
    }
    if (ex.getAnswer() != null && ex.getAnswer() instanceof Exception)
      throw (Exception) ex.getAnswer();
    return ex.getAnswer();
  }

  static class Exec implements Runnable {
    Callback iCallback = null;
    Object iAnswer = null;

    Exec(Callback callback) {
      iCallback = callback;
    }

    public void run() {
      try {
        iCallback.execute();
        iAnswer = null;
      } catch (Exception e) {
        sLog.error("Unable to execute a callback, reason: " + e.getMessage(), e);
        iAnswer = e;
      }
    }

    public Object getAnswer() {
      return iAnswer;
    }
  }

  static class DisconnectProxyCallback implements Callback {
    RemoteSolverServerProxy iProxy = null;

    DisconnectProxyCallback(RemoteSolverServerProxy proxy) {
      iProxy = proxy;
    }

    public void execute() {
      iProxy.disconnectProxy();
    }
  }

  public Date getStartTime() {
    return iStartTime;
  }
}
 private Object answer(Object command) throws Exception {
   if ("quit".equals(command)) {
     stopConnection();
     stopService();
     return "ack";
   }
   if ("ping".equals(command)) {
     iLastPing = System.currentTimeMillis();
     if (iProxy != null && !iServers.contains(iProxy)) {
       sLog.warn("Server " + iProxy + " is alive, but it is not registered.");
       iServers.add(iProxy);
     }
     return "ack";
   }
   if ("url".equals(command)) {
     return HibernateUtil.getConnectionUrl();
   }
   if ("properties".equals(command)) {
     return ApplicationProperties.getProperties();
   }
   if ("disconnect".equals(command)) {
     unregister();
     stopConnection();
     return "ack";
   }
   if (command instanceof Object[]) {
     Object cmd[] = (Object[]) command;
     if ("connect".equals(cmd[0])) {
       int port = ((Integer) cmd[1]).intValue();
       iProxy = new RemoteSolverServerProxy(iSocket.getInetAddress(), port, this);
       sLog.debug("Sever " + iProxy + " connected.");
       synchronized (iServers) {
         if (iServers.contains(iProxy)) {
           sLog.warn("Previous run of the server " + iProxy + " was not properly disconnected.");
           for (Iterator i = iServers.iterator(); i.hasNext(); ) {
             RemoteSolverServerProxy oldProxy = (RemoteSolverServerProxy) i.next();
             if (oldProxy.equals(iProxy)) {
               try {
                 execute(new DisconnectProxyCallback(oldProxy), 10000);
               } catch (Exception e) {
               }
             }
           }
           iServers.remove(iProxy);
         }
         iServers.add(iProxy);
       }
       return "ack";
     }
     if ("saveToFile".equals(cmd[0])) {
       TimetableInfoUtil.getInstance().saveToFile((String) cmd[1], (TimetableInfo) cmd[2]);
       return "ack";
     }
     if ("loadFromFile".equals(cmd[0])) {
       return TimetableInfoUtil.getInstance().loadFromFile((String) cmd[1]);
     }
     if ("deleteFile".equals(cmd[0])) {
       TimetableInfoUtil.getInstance().deleteFile((String) cmd[1]);
       return "ack";
     }
     if ("resource".equals(cmd[0])) {
       URL resource = SolverRegisterService.class.getClassLoader().getResource((String) cmd[1]);
       if (resource == null) return null;
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       InputStream in = resource.openStream();
       byte[] buffer = new byte[1024];
       int read = 0;
       while ((read = in.read(buffer)) >= 0) out.write(buffer, 0, read);
       out.flush();
       out.close();
       in.close();
       return out.toByteArray();
     }
     if ("refreshSolution".equals(cmd[0])) {
       try {
         Solution.refreshSolution((Long) cmd[1]);
       } finally {
         _BaseRootDAO.closeCurrentThreadSessions();
       }
       return null;
     }
     if ("hasRoomAvailability".equals(cmd[0])) {
       return new Boolean(RoomAvailability.getInstance() != null);
     }
     if ("activateRoomAvailability".equals(cmd[0])) {
       if (RoomAvailability.getInstance() != null) {
         RoomAvailability.getInstance()
             .activate(
                 new SessionDAO().get((Long) cmd[1]),
                 (Date) cmd[2],
                 (Date) cmd[3],
                 (String) cmd[4],
                 "true"
                     .equals(
                         ApplicationProperties.getProperty(
                             "tmtbl.room.availability.solver.waitForSync", "true")));
         return "ack";
       }
       return null;
     }
     if ("getRoomAvailability".equals(cmd[0])) {
       if (RoomAvailability.getInstance() != null) {
         return RoomAvailability.getInstance()
             .getRoomAvailability(
                 new LocationDAO().get((Long) cmd[1]),
                 (Date) cmd[2],
                 (Date) cmd[3],
                 (String) cmd[4]);
       }
       return null;
     }
     if ("getRoomAvailabilityTimeStamp".equals(cmd[0])) {
       if (RoomAvailability.getInstance() != null) {
         return RoomAvailability.getInstance()
             .getTimeStamp((Date) cmd[1], (Date) cmd[2], (String) cmd[3]);
       }
       return null;
     }
   }
   sLog.warn("Unknown command " + command);
   return null;
 }
 public void run() {
   iStartTime = new Date();
   try {
     ConnectionFactory.init(
         ApplicationProperties.getProperties(), ApplicationProperties.getDataFolder());
     try {
       while (true) {
         try {
           iServerSocket =
               ConnectionFactory.getServerSocketFactory()
                   .createServerSocket(
                       Integer.parseInt(
                           ApplicationProperties.getProperty(
                               "tmtbl.solver.register.port", "9998")));
           sLog.info(
               "Service is running at "
                   + iServerSocket.getInetAddress().getHostName()
                   + ":"
                   + iServerSocket.getLocalPort());
           break;
         } catch (BindException e) {
           try {
             sLog.warn("Prior instance of service still running");
             Socket socket =
                 ConnectionFactory.getSocketFactory()
                     .createSocket(
                         "localhost",
                         Integer.parseInt(
                             ApplicationProperties.getProperty(
                                 "tmtbl.solver.register.port", "9998")));
             RemoteIo.writeObject(socket, "quit");
             Object answer = RemoteIo.readObject(socket);
             sLog.warn("quit command sent, answer: " + answer);
             socket.close();
           } catch (Exception f) {
             sLog.warn("Unable to connect to prior instance", f);
           }
           sleep(1000);
         }
       }
     } catch (IOException io) {
       sLog.error("Unable to start service, reason: " + io.getMessage(), io);
       return;
     }
     while (!iServerSocket.isClosed()) {
       try {
         Socket socket = iServerSocket.accept();
         socket.setKeepAlive(true);
         sLog.debug("Client " + socket.getInetAddress() + " connected.");
         (new Thread(new SolverConnection(socket))).start();
       } catch (Exception e) {
         if (!iServerSocket.isClosed())
           sLog.warn("Unable to accept new connection, reason:" + e.getMessage(), e);
       }
     }
   } catch (Exception e) {
     sLog.error("Unexpected exception occured, reason: " + e.getMessage(), e);
   } finally {
     try {
       if (iServerSocket != null && !iServerSocket.isClosed()) iServerSocket.close();
     } catch (Exception e) {
       sLog.warn("Unable to close socket, reason: " + e.getMessage(), 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;
                }
              });
    }
  }