Example usage for java.util Hashtable elements

List of usage examples for java.util Hashtable elements

Introduction

In this page you can find the example usage for java.util Hashtable elements.

Prototype

public synchronized Enumeration<V> elements() 

Source Link

Document

Returns an enumeration of the values in this hashtable.

Usage

From source file:org.hyperic.hq.product.RtPlugin.java

protected void combineUrls(Hashtable foundNew, Hashtable foundOld, String transforms) {
    Enumeration en = foundNew.elements();

    while (en.hasMoreElements()) {
        RtStat rs = (RtStat) en.nextElement();

        transformUrl(rs, transforms);/*from   w  w  w.ja  v a2s.  c  om*/
        RtStat saved = (RtStat) foundOld.get(rs.getIpUrlKey());

        rs.recompute(saved);
        foundOld.put(rs.getIpUrlKey(), rs);
    }
}

From source file:org.jasig.portal.layout.simple.RDBMUserLayoutStore.java

public Hashtable getSystemProfileList() {
    Hashtable pl = this.getUserProfileList(this.getSystemUser());
    for (Enumeration e = pl.elements(); e.hasMoreElements();) {
        IUserProfile up = (IUserProfile) e.nextElement();
        up.setSystemProfile(true);/*from  www  .j  a v a2s .c o  m*/
    }
    return pl;
}

From source file:org.jibble.pircbot.PircBot.java

/**
 * Returns an array of all users in the specified channel.
 * <p/>/*from  w ww.j av  a2s  . c o  m*/
 * There are some important things to note about this method:-
 * <ul>
 * <li>This method may not return a full list of users if you call it
 * before the complete nick list has arrived from the IRC server.
 * </li>
 * <li>If you wish to find out which users are in a channel as soon
 * as you join it, then you should override the onUserList method
 * instead of calling this method, as the onUserList method is only
 * called as soon as the full user list has been received.
 * </li>
 * <li>This method will return immediately, as it does not require any
 * interaction with the IRC server.
 * </li>
 * <li>The bot must be in a channel to be able to know which users are
 * in it.
 * </li>
 * </ul>
 *
 * @param channel The name of the channel to list.
 * @return An array of User objects. This array is empty if we are not
 * in the channel.
 * @see #onUserList(String, User[]) onUserList
 * @since PircBot 1.0.0
 */
public final User[] getUsers(String channel) {
    channel = channel.toLowerCase();
    User[] userArray = new User[0];
    synchronized (_channels) {
        Hashtable users = (Hashtable) _channels.get(channel);
        if (users != null) {
            userArray = new User[users.size()];
            Enumeration enumeration = users.elements();
            for (int i = 0; i < userArray.length; i++) {
                User user = (User) enumeration.nextElement();
                userArray[i] = user;
            }
        }
    }
    return userArray;
}

From source file:org.jibble.pircbot.PircBot.java

private final void updateUser(String channel, int userMode, String nick) {
    channel = channel.toLowerCase();/*from   w  w  w. j a v  a2 s.  c o m*/
    synchronized (_channels) {
        Hashtable users = (Hashtable) _channels.get(channel);
        User newUser = null;
        if (users != null) {
            Enumeration enumeration = users.elements();
            while (enumeration.hasMoreElements()) {
                User userObj = (User) enumeration.nextElement();
                if (userObj.getNick().equalsIgnoreCase(nick)) {
                    if (userMode == OP_ADD) {
                        if (userObj.hasVoice()) {
                            newUser = new User("@+", nick);
                        } else {
                            newUser = new User("@", nick);
                        }
                    } else if (userMode == OP_REMOVE) {
                        if (userObj.hasVoice()) {
                            newUser = new User("+", nick);
                        } else {
                            newUser = new User("", nick);
                        }
                    } else if (userMode == VOICE_ADD) {
                        if (userObj.isOp()) {
                            newUser = new User("@+", nick);
                        } else {
                            newUser = new User("+", nick);
                        }
                    } else if (userMode == VOICE_REMOVE) {
                        if (userObj.isOp()) {
                            newUser = new User("@", nick);
                        } else {
                            newUser = new User("", nick);
                        }
                    }
                }
            }
        }
        if (newUser != null) {
            users.put(newUser, newUser);
        } else {
            // just in case ...
            newUser = new User("", nick);
            users.put(newUser, newUser);
        }
    }
}

From source file:org.lexevs.system.ResourceManager.java

/**
 * Inits the./* w ww  .j a v  a2 s. c o m*/
 * 
 * @throws Exception the exception
 */
public void init() throws Exception {
    cache_ = Collections.synchronizedMap(new LRUMap(systemVars_.getCacheSize()));

    // This increases the ability of Lucene to do queries against
    // large indexes like the MetaThesaurus without getting errors.
    BooleanQuery.setMaxClauseCount(systemVars_.getLuceneMaxClauseCount());

    codingSchemeToServerMap_ = new Hashtable<String, String>();
    sqlServerInterfaces_ = new Hashtable<String, SQLInterface>();
    historySqlServerInterfaces_ = new Hashtable<String, SQLHistoryInterface>();
    codingSchemeLocalNamesToInternalNameMap_ = new Hashtable<String, Hashtable<String, String>>();
    internalCodingSchemeNameUIDMap_ = new Hashtable<String, List<LocalCodingScheme>>();
    supportedCodingSchemeToInternalMap_ = new Hashtable<String, String>();

    // populate the registry
    //registry_ = new XmlRegistry(systemVars_.getAutoLoadRegistryPath());

    // connect to the histories
    readHistories();

    // go through all of the sql servers and read all of the available code
    // systems.
    // initialize the SQL connections to each server.

    org.lexevs.registry.service.XmlRegistry.DBEntry[] entries = registry_.getDBEntries();
    for (int i = 0; i < entries.length; i++) {
        SQLConnectionInfo temp = new SQLConnectionInfo();
        temp.driver = systemVars_.getAutoLoadDBDriver();
        temp.password = systemVars_.getAutoLoadDBPassword();
        temp.server = entries[i].dbURL;
        temp.prefix = entries[i].prefix;
        temp.username = systemVars_.getAutoLoadDBUsername();
        readTerminologiesFromServer(temp);
    }

    logger_.debug("Reading available terminologies from SQL servers.");

    // same thing as above, this time for pre-configured servers
    Hashtable<String, SQLConnectionInfo> servers = systemVars_.getSqlServers();

    Enumeration<SQLConnectionInfo> e = servers.elements();
    while (e.hasMoreElements()) {
        SQLConnectionInfo server = e.nextElement();
        readTerminologiesFromServer(server);
    }

    logger_.debug("Reading available terminologies from the lucene index locations");

    // go through all of the index locations, finding the right index for
    // each code system.
    // initialize the index readers.
    HashSet<String> indexLocations = systemVars_.getIndexLocations();
    Iterator<String> iterator = indexLocations.iterator();

    indexInterfaces_ = new Hashtable<String, IndexInterface>();
    codingSchemeToIndexMap_ = new Hashtable<String, String>();

    while (iterator.hasNext()) {
        String location = iterator.next();

        File temp = new File(location);
        if (!temp.exists() || !temp.isDirectory()) {
            logger_.error("Bad index location " + location);
        } else {

            IndexInterface is = new IndexInterface(location);
            indexInterfaces_.put(location, is);

            ArrayList<String> keys = is.getCodeSystemKeys();
            for (int i = 0; i < keys.size(); i++) {
                codingSchemeToIndexMap_.put(keys.get(i), location);
            }
        }
    }

    // Start up a thread to handle scheduled deactivations
    fdt_ = new FutureDeactivatorThread();
    deactivatorThread_ = new Thread(fdt_);
    // This allows the JVM to exit while this thread is still active.
    deactivatorThread_.setDaemon(true);
    deactivatorThread_.start();
}

From source file:org.lexevs.system.ResourceManager.java

public String getInternalVersionStringForTag(String externalCodeSystemName, String tag)
        throws LBParameterException {
    if (externalCodeSystemName == null || externalCodeSystemName.length() == 0) {
        throw new LBParameterException("The parameter is required", SQLTableConstants.TBLCOL_CODINGSCHEMENAME);
    }//from  w w  w.  j a  va2  s  . com

    // I'm going to cache this, because it is kind of expensive, and may be
    // a frequent operation
    String key = "internalVersionStringForTag:" + externalCodeSystemName + ":"
            + (tag == null || tag.length() == 0 ? KnownTags.PRODUCTION.toString() : tag);

    String version = (String) cache_.get(key);

    if (version != null) {
        return version;
    }

    // not in the cache, find it.

    Hashtable<String, String> temp = codingSchemeLocalNamesToInternalNameMap_.get(externalCodeSystemName);
    if (temp == null) {
        throw new LBParameterException("No coding scheme could be located for the values you provided",
                SQLTableConstants.TBLCOL_CODINGSCHEMENAME + ", " + SQLTableConstants.TBLCOL_VERSION,
                externalCodeSystemName + ", " + tag);
    }

    // The hashtable that is returned is a mapping of versions to the
    // internal code system names.
    // it is likely but not guaranteed that all of the code system names
    // will be identical.
    // They should all map to the SAME urn however, so get the URN for the
    // first one.
    // ask the registry for the version number associated with the given tag
    // on the (found) urn.

    Enumeration<String> e = temp.elements();
    String urn = "";
    if (e.hasMoreElements()) {
        Set<String> uris = getAllURNsForInternalCodingSchemeName(e.nextElement());
        if (uris.size() == 1) {
            urn = uris.iterator().next();
        } else {
            if (uris.contains(externalCodeSystemName)) {
                for (String uri : uris) {
                    if (uri.equals(externalCodeSystemName)) {
                        urn = uri;
                    }
                }
            }
        }
    } else {
        throw new LBParameterException("No coding scheme could be located for the values you provided",
                SQLTableConstants.TBLCOL_CODINGSCHEMENAME + ", " + SQLTableConstants.TBLCOL_VERSION,
                externalCodeSystemName + ", " + tag);
    }

    // if the tag is missing or null, then we should use "PRODUCTION"
    version = registry_.getVersionForTag(urn,
            (tag == null || tag.length() == 0 ? KnownTags.PRODUCTION.toString() : tag));

    if (version == null) {
        if (tag != null && !tag.equals(KnownTags.PRODUCTION.toString())) {
            // if they specified a tag, and it wasn't the production tag,
            // and we didn't find it
            // then the tag is invalid.
            throw new LBParameterException(
                    "No version of the code system " + externalCodeSystemName + " is tagged as " + tag);
        }
        // they didn't specify a tag, or the specified production, but
        // nothing it tagged
        // as production. If we only have one that matches, return it. Else,
        // ask for clairification.
        else if (temp.size() > 1) {

            throw new LBParameterException(
                    "Multiple code systems matched the values you provided - please be more specific (or designate one of the code systems as 'PRODUCTION'",
                    SQLTableConstants.TBLCOL_CODINGSCHEMENAME + ", " + SQLTableConstants.TBLCOL_VERSION,
                    externalCodeSystemName + ", " + tag);
        } else {
            version = temp.keySet().toArray(new String[temp.size()])[0];
        }
    }

    cache_.put(key, version);
    return version;
}

From source file:org.openymsg.network.Session.java

/**
 * Process an incoming CHATJOIN packet. We get one of these: (a) as a way of finishing the login handshaking
 * process, containing room details (we already know) and a list of current members. (b) when the login process
 * fails (room full?), containing only a 114 field (set to '-35'?) - see error handling code elsewhere (c) as a
 * stripped down version when a new user enters the room (including ourselves!) (d) as a stripped down version when
 * an existing member updates their details. (e) when we need to deal with a chat captcha. Sometimes a login packet
 * is broken over several packets. The clue here appears to be that the first (and subsequent?) packets have a
 * status of 5, while the final packet has a status of 1.
 */// w w w. j a  va  2  s  .  c om
protected void receiveChatJoin(YMSG9Packet pkt) // 0x98
{
    boolean joining = false;
    try {
        // Is this an error packet, sent to us via processError() ?
        if (pkt.exists("114")) {
            this.loginException = new LoginRefusedException("User " + this.chatID + " refused chat login");
            joining = true;
            this.chatSessionStatus = SessionState.FAILED;
            return; // ...to finally block
        }

        // Returns null if more packets to come
        pkt = compoundChatLoginPacket(pkt);
        if (pkt == null)
            return;

        // As we need to load a room to get at its lobby data so we
        // can login, the next line *should* never fail... however :-)
        String netname = pkt.getValue("104"); // room:lobby
        YahooChatLobby ycl = this.chatroomManager.getLobby(netname);
        if (ycl == null)
            throw new NoSuchChatroomException("Chatroom/lobby " + netname + " not found.");

        // -----Process a captcha packet
        if (pkt.exists("105"))
            try {
                String captchaMsg = pkt.getValue("105");
                String captchaURL = null;
                int idx = (captchaMsg != null) ? captchaMsg.indexOf("http://captcha.") : -1;
                if (idx >= 0)
                    captchaURL = captchaMsg.substring(idx);

                SessionChatEvent se = new SessionChatEvent(this, captchaMsg, captchaURL, ycl);
                this.eventDispatchQueue.append(se, ServiceType.X_CHATCAPTCHA);
                return; // ...to finally block
            } catch (Exception e) {
                throw new YMSG9BadFormatException("chat captcha", pkt, e);
            }

        // Note: Yahoo sometimes lies about the '108' count of users!
        // Reduce count until to see how many users there *actually* are!
        int cnt = Integer.parseInt(pkt.getValue("108"));
        while (cnt > 0 && pkt.getNthValue("109", cnt - 1) == null)
            cnt--;

        // Is this an update packet, for an existing member?
        YahooChatUser ycu = ycl.getUser(pkt.getValue("109"));
        if (cnt == 1 && ycu != null) {
            // Count is one and user exists - UPDATE
            final int attributes = Integer.parseInt(pkt.getValue("113"));
            final String alias = pkt.getValue("141"); // optional
            final int age = Integer.parseInt(pkt.getValue("110"));
            final String location = pkt.getValue("142"); // optional

            ycu.setAttributes(attributes);
            ycu.setAlias(alias);
            ycu.setAge(age);
            ycu.setLocation(location);

            SessionChatEvent se = new SessionChatEvent(this, 1, ycl);
            se.setChatUser(0, ycu);
            this.eventDispatchQueue.append(se, ServiceType.X_CHATUPDATE);
            return; // ...to finally block
        }
        // Full sized packet, when joining room?
        joining = pkt.exists("61");
        // If we are joining, clear the array of users (just to be sure!)
        if (joining)
            ycl.clearUsers();

        // When sent in muliple parts the login packet usually
        // contains a high degree of duplicates. Remove using hash.
        Hashtable<String, YahooChatUser> ht = new Hashtable<String, YahooChatUser>();
        for (int i = 0; i < cnt; i++) {
            // Note: automatically creates YahooUser if necessary
            ycu = createChatUser(pkt, i);
            ht.put(ycu.getId(), ycu);
        }
        // Create event, add users
        SessionChatEvent se = new SessionChatEvent(this, cnt, ycl);
        int i = 0;
        for (Enumeration<YahooChatUser> en = ht.elements(); en.hasMoreElements();) {
            ycu = en.nextElement();
            // Does this user exist already? (This should always be
            // no, as update packets should always have only one member
            // who already exists - thus caught by the 'if' block above!
            if (!ycl.exists(ycu))
                ycl.addUser(ycu); // Add to lobby
            se.setChatUser(i++, ycu); // Add to event
        }

        // We don't send an event if we get the larger 'logging in'
        // type packet as the chat user list is brand new. We only send
        // events when someone joins and we need to signal an update.
        if (!joining) {
            // Did we actually accrue any *new* users in previous loop?
            if (se.getChatUsers().length > 0)
                this.eventDispatchQueue.append(se, ServiceType.CHATJOIN);
        } else
            this.chatSessionStatus = SessionState.LOGGED_ON;
        return; // ...to finally block
    } catch (RuntimeException e) {
        log.error("error on receveing Chat join ", e);
        throw new YMSG9BadFormatException("chat login", pkt, e);
    } finally {
        // FIX: Not thread safe if multiple chatroom supported!
        if (joining && this.chatSessionStatus != SessionState.FAILED)
            this.chatSessionStatus = SessionState.LOGGED_ON;
    }
}

From source file:org.tinygroup.jspengine.compiler.TagLibraryInfoImpl.java

private void parseTLD(JspCompilationContext ctxt, String uri, InputStream in, URL jarFileUrl)
        throws JasperException {
    Vector tagVector = new Vector();
    Vector tagFileVector = new Vector();
    Hashtable functionTable = new Hashtable();

    // Create an iterator over the child elements of our <taglib> element
    ParserUtils pu = new ParserUtils();
    TreeNode tld = pu.parseXMLDocument(uri, in);

    // Check to see if the <taglib> root element contains a 'version'
    // attribute, which was added in JSP 2.0 to replace the <jsp-version>
    // subelement
    this.jspversion = tld.findAttribute("version");

    // Process each child element of our <taglib> element
    Iterator list = tld.findChildren();

    while (list.hasNext()) {
        TreeNode element = (TreeNode) list.next();
        String tname = element.getName();

        if ("tlibversion".equals(tname) // JSP 1.1
                || "tlib-version".equals(tname)) { // JSP 1.2
            this.tlibversion = element.getBody();
        } else if ("jspversion".equals(tname) || "jsp-version".equals(tname)) {
            this.jspversion = element.getBody();
        } else if ("shortname".equals(tname) || "short-name".equals(tname))
            this.shortname = element.getBody();
        else if ("uri".equals(tname))
            this.urn = element.getBody();
        else if ("info".equals(tname) || "description".equals(tname))
            this.info = element.getBody();
        else if ("validator".equals(tname))
            this.tagLibraryValidator = createValidator(element);
        else if ("tag".equals(tname))
            tagVector.addElement(createTagInfo(element, jspversion));
        else if ("tag-file".equals(tname)) {
            TagFileInfo tagFileInfo = createTagFileInfo(element, uri, jarFileUrl);
            tagFileVector.addElement(tagFileInfo);
        } else if ("function".equals(tname)) { // JSP2.0
            FunctionInfo funcInfo = createFunctionInfo(element);
            String funcName = funcInfo.getName();
            if (functionTable.containsKey(funcName)) {
                err.jspError("jsp.error.tld.fn.duplicate.name", funcName, uri);

            }/*  w  w w  . j  a v a  2s.c o m*/
            functionTable.put(funcName, funcInfo);
        } else if ("display-name".equals(tname) || // Ignored elements
                "small-icon".equals(tname) || "large-icon".equals(tname) || "listener".equals(tname)) {
            ;
        } else if ("taglib-extension".equals(tname)) {
            // Recognized but ignored
        } else {
            err.jspError("jsp.error.unknown.element.in.taglib", tname);
        }
    }

    if (tlibversion == null) {
        err.jspError("jsp.error.tld.mandatory.element.missing", "tlib-version");
    }
    if (jspversion == null) {
        err.jspError("jsp.error.tld.mandatory.element.missing", "jsp-version");
    }

    this.tags = new TagInfo[tagVector.size()];
    tagVector.copyInto(this.tags);

    this.tagFiles = new TagFileInfo[tagFileVector.size()];
    tagFileVector.copyInto(this.tagFiles);

    this.functions = new FunctionInfo[functionTable.size()];
    int i = 0;
    Enumeration enumeration = functionTable.elements();
    while (enumeration.hasMoreElements()) {
        this.functions[i++] = (FunctionInfo) enumeration.nextElement();
    }
}

From source file:org.unitime.timetable.model.Solution.java

public boolean commitSolution(List<String> messages, org.hibernate.Session hibSession,
        String sendNotificationPuid) throws Exception {
    List solutions = hibSession.createCriteria(Solution.class).add(Restrictions.eq("owner", getOwner())).list();
    Solution uncommittedSolution = null;
    for (Iterator i = solutions.iterator(); i.hasNext();) {
        Solution s = (Solution) i.next();
        if (s.equals(this))
            continue;
        if (s.isCommited().booleanValue()) {
            uncommittedSolution = s;//from   w w  w . ja va 2s. c o m
            s.uncommitSolution(hibSession, null);
        }
    }
    if (DEBUG)
        sLog.debug("commit[" + getUniqueId() + "," + getOwner().getName()
                + "] -------------------------------------------------------");

    boolean isOK = true;
    for (Object[] o : (List<Object[]>) hibSession.createQuery(
            "select r, a1, a2 from Location r inner join r.assignments a1 inner join r.assignments a2 "
                    + "where a1.solution.uniqueId = :solutionId and a2.solution.commited = true and a2.solution.owner.uniqueId != :ownerId and "
                    + "bit_and(a1.days, a2.days) > 0 and (a1.timePattern.type = :exactType or a2.timePattern.type = :exactType or "
                    + "(a1.startSlot < a2.startSlot + a2.timePattern.slotsPerMtg and a2.startSlot < a1.startSlot + a1.timePattern.slotsPerMtg))")
            .setLong("ownerId", getOwner().getUniqueId()).setLong("solutionId", getUniqueId())
            .setInteger("exactType", TimePattern.sTypeExactTime).list()) {
        Location room = (Location) o[0];
        Assignment a = (Assignment) o[1];
        Assignment b = (Assignment) o[2];
        if (!room.isIgnoreRoomCheck() && a.getTimeLocation().hasIntersection(b.getTimeLocation())
                && !shareRooms(a, b)) {
            messages.add("Class " + a.getClassName() + " " + a.getTimeLocation().getName(CONSTANTS.useAmPm())
                    + " overlaps with " + b.getClassName() + " "
                    + b.getTimeLocation().getName(CONSTANTS.useAmPm()) + " (room " + room.getLabel() + ")");
            isOK = false;
        }
    }

    for (Object[] o : (List<Object[]>) hibSession.createQuery(
            "select i1, a1, a2 from ClassInstructor c1 inner join c1.instructor i1 inner join c1.classInstructing.assignments a1, "
                    + "ClassInstructor c2 inner join c2.instructor i2 inner join c2.classInstructing.assignments a2 where c1.lead = true and c2.lead = true and "
                    + "i1.department.solverGroup.uniqueId = :ownerId and i2.department.solverGroup.uniqueId != :ownerId and i2.department.session = :sessionId and "
                    + "i1.externalUniqueId is not null and i1.externalUniqueId = i2.externalUniqueId and "
                    + "a1.solution.uniqueId = :solutionId and a2.solution.commited = true and a2.solution.owner.uniqueId != :ownerId and "
                    + "bit_and(a1.days, a2.days) > 0 and (a1.timePattern.type = :exactType or a2.timePattern.type = :exactType or "
                    + "(a1.startSlot < a2.startSlot + a2.timePattern.slotsPerMtg and a2.startSlot < a1.startSlot + a1.timePattern.slotsPerMtg))")
            .setLong("ownerId", getOwner().getUniqueId()).setLong("solutionId", getUniqueId())
            .setLong("sessionId", getOwner().getSession().getUniqueId())
            .setInteger("exactType", TimePattern.sTypeExactTime).list()) {
        DepartmentalInstructor instructor = (DepartmentalInstructor) o[0];
        Assignment a = (Assignment) o[1];
        Assignment b = (Assignment) o[2];
        if (a.getTimeLocation().hasIntersection(b.getTimeLocation()) && !shareRooms(a, b)) {
            messages.add("Class " + a.getClassName() + " " + a.getTimeLocation().getName(CONSTANTS.useAmPm())
                    + " overlaps with " + b.getClassName() + " "
                    + b.getTimeLocation().getName(CONSTANTS.useAmPm()) + " (instructor "
                    + instructor.nameLastNameFirst() + ")");
            isOK = false;
        }
    }

    if (!isOK) {
        if (sendNotificationPuid != null)
            sendNotification(uncommittedSolution, this, sendNotificationPuid, false, messages);
        return false;
    }

    // NOTE: In order to decrease the amount of interaction between solutions persistance of committed student conflicts was disabled
    /*
    SolverInfoDef defJenrlInfo = SolverInfoDef.findByName(hibSession,"JenrlInfo");
    Hashtable solverInfos = new Hashtable();
    AssignmentDAO adao = new AssignmentDAO(); 
    q = hibSession.createQuery(
    "select a.uniqueId, oa.uniqueId, count(*) from "+
    "Solution s inner join s.assignments a inner join s.studentEnrollments as e, "+
    "Solution os inner join os.assignments oa inner join os.studentEnrollments as oe "+
    "where "+
    "s.uniqueId=:solutionId and os.owner.session.uniqueId=:sessionId and os.owner.uniqueId!=:ownerId and "+
    "a.clazz=e.clazz and oa.clazz=oe.clazz and a.clazz.schedulingSubpart!=oa.clazz.schedulingSubpart and e.studentId=oe.studentId "+
    "group by a.uniqueId, oa.uniqueId");
    q.setLong("ownerId",getOwner().getUniqueId().longValue());
    q.setLong("solutionId",getUniqueId());
    q.setLong("sessionId",getOwner().getSession().getUniqueId().longValue());
    Iterator otherAssignments = q.iterate();
    while (otherAssignments.hasNext()) {
       Object[] result = (Object[])otherAssignments.next();
       Assignment assignment = adao.get((Integer)result[0],hibSession);
       Assignment otherAssignment = adao.get((Integer)result[1],hibSession);
       int jenrl = ((Number)result[2]).intValue();
               
       if (assignment==null || otherAssignment==null || jenrl==0 || !assignment.isInConflict(otherAssignment)) continue;
       addCommitJenrl(hibSession, assignment, otherAssignment, jenrl, defJenrlInfo, solverInfos);
      }   
            
    for (Iterator i=solverInfos.values().iterator();i.hasNext();) {
       SolverInfo sInfo = (SolverInfo)i.next();
       hibSession.saveOrUpdate(sInfo);
    }
    */

    setCommitDate(new Date());
    setCommited(Boolean.TRUE);

    //      createDivSecNumbers(hibSession, messages);

    EventContact contact = null;
    if (sendNotificationPuid != null) {
        contact = EventContact.findByExternalUniqueId(sendNotificationPuid);
        if (contact == null) {
            TimetableManager manager = TimetableManager.findByExternalId(sendNotificationPuid);
            if (manager != null) {
                contact = new EventContact();
                contact.setFirstName(manager.getFirstName());
                contact.setMiddleName(manager.getMiddleName());
                contact.setLastName(manager.getLastName());
                contact.setExternalUniqueId(manager.getExternalUniqueId());
                contact.setEmailAddress(manager.getEmailAddress());
                hibSession.save(contact);
            }
        }
    }
    Hashtable<Long, ClassEvent> classEvents = new Hashtable();
    for (Iterator i = hibSession.createQuery(
            "select e from Solution s inner join s.assignments a, ClassEvent e where e.clazz=a.clazz and s.uniqueId=:solutionId")
            .setLong("solutionId", getUniqueId()).iterate(); i.hasNext();) {
        ClassEvent e = (ClassEvent) i.next();
        classEvents.put(e.getClazz().getUniqueId(), e);
    }
    for (Iterator i = getAssignments().iterator(); i.hasNext();) {
        Assignment a = (Assignment) i.next();
        ClassEvent event = a.generateCommittedEvent(classEvents.get(a.getClassId()), true);
        classEvents.remove(a.getClassId());
        if (event != null && !event.getMeetings().isEmpty()) {
            event.setMainContact(contact);
            if (event.getNotes() == null)
                event.setNotes(new HashSet<EventNote>());
            EventNote note = new EventNote();
            note.setEvent(event);
            note.setNoteType(event.getUniqueId() == null ? EventNote.sEventNoteTypeCreateEvent
                    : EventNote.sEventNoteTypeEditEvent);
            note.setTimeStamp(new Date());
            note.setUser(contact == null ? "System" : contact.getName());
            note.setUserId(sendNotificationPuid);
            note.setTextNote(getOwner().getName() + " committed");
            note.setMeetings(a.getPlacement().getLongName(CONSTANTS.useAmPm()));
            event.getNotes().add(note);
            hibSession.saveOrUpdate(event);
        }
        if (event != null && event.getMeetings().isEmpty() && event.getUniqueId() != null)
            hibSession.delete(event);
    }

    if (ApplicationProperty.ClassAssignmentChangePastMeetings.isTrue()) {
        for (Enumeration e = classEvents.elements(); e.hasMoreElements();) {
            ClassEvent event = (ClassEvent) e.nextElement();
            hibSession.delete(event);
        }
    } else {
        Calendar cal = Calendar.getInstance(Locale.US);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        Date today = cal.getTime();

        for (Enumeration e = classEvents.elements(); e.hasMoreElements();) {
            ClassEvent event = (ClassEvent) e.nextElement();
            for (Iterator<Meeting> i = event.getMeetings().iterator(); i.hasNext();)
                if (!i.next().getMeetingDate().before(today))
                    i.remove();
            if (event.getMeetings().isEmpty()) {
                hibSession.delete(event);
            } else {
                if (event.getNotes() == null)
                    event.setNotes(new HashSet<EventNote>());
                EventNote note = new EventNote();
                note.setEvent(event);
                note.setNoteType(EventNote.sEventNoteTypeDeletion);
                note.setTimeStamp(new Date());
                note.setUser(contact == null ? "System" : contact.getName());
                note.setUserId(sendNotificationPuid);
                note.setTextNote(getOwner().getName() + " committed, class was removed or unassigned");
                note.setMeetings("N/A");
                event.getNotes().add(note);
                hibSession.saveOrUpdate(event);
            }
        }
    }

    if (sendNotificationPuid != null)
        sendNotification(uncommittedSolution, this, sendNotificationPuid, true, messages);

    // Manually fix the Clazz_.committedAssignment cache.
    for (Assignment a : getAssignments())
        a.getClazz().setCommittedAssignment(a);

    return true;
}

From source file:org.unitime.timetable.solver.TimetableDatabaseSaver.java

private Long[] save(org.hibernate.Session hibSession) throws Exception {

    if (iStudentSectioning)
        getModel().switchStudents(getAssignment());

    iProgress.setStatus("Saving solution ...");

    if (iSolverGroupId == null || iSolverGroupId.length == 0) {
        iProgress.fatal("No solver group loaded.");
        return null;
    }//from w ww. ja v  a2 s  . c  o  m

    Hashtable solverGroups = new Hashtable();
    for (int i = 0; i < iSolverGroupId.length; i++) {
        SolverGroup solverGroup = SolverGroupDAO.getInstance().get(iSolverGroupId[i], hibSession);
        if (solverGroup == null) {
            iProgress.fatal("Unable to load solver group " + iSolverGroupId[i] + ".");
            return null;
        }
        solverGroups.put(solverGroup.getUniqueId(), solverGroup);
        iProgress.debug("solver group [" + (i + 1) + "]: " + solverGroup.getName());
    }

    iSolutions = new Hashtable();
    if (!iCreateNew && iSolutionId != null && iSolutionId.length >= 0) {
        for (int i = 0; i < iSolverGroupId.length; i++) {
            if (i < iSolutionId.length && iSolutionId[i] != null) {
                Solution solution = (new SolutionDAO()).get(iSolutionId[i], hibSession);
                if (solution == null) {
                    iProgress.warn("Unable to load solution " + iSolutionId[i]);
                    continue;
                }
                if (!solverGroups.containsKey(solution.getOwner().getUniqueId())) {
                    iProgress.warn("Solution " + iSolutionId[i]
                            + " ignored -- it does not match with the owner(s) of the problem");
                    continue;
                }
                if (solution.isCommited().booleanValue()) {
                    solution.uncommitSolution(hibSession,
                            getModel().getProperties().getProperty("General.OwnerPuid"));
                    if (!iCommitSolution) {
                        String className = ApplicationProperty.ExternalActionSolutionCommit.value();
                        if (className != null && className.trim().length() > 0) {
                            HashSet<Solution> touchedSolutions = new HashSet<Solution>();
                            touchedSolutions.add(solution);
                            ExternalSolutionCommitAction commitAction = (ExternalSolutionCommitAction) (Class
                                    .forName(className).newInstance());
                            commitAction.performExternalSolutionCommitAction(touchedSolutions, hibSession);
                        }

                    }
                }
                solution.empty(hibSession, getFileProxy());
                iSolutions.put(solution.getOwner().getUniqueId(), solution);
            }
        }
    }

    Session session = SessionDAO.getInstance().get(iSessionId, hibSession);
    if (session == null) {
        iProgress.fatal("No session loaded.");
        return null;
    }
    iProgress.debug("session: " + session.getLabel());

    for (Enumeration e = solverGroups.elements(); e.hasMoreElements();) {
        SolverGroup solverGroup = (SolverGroup) e.nextElement();
        Solution solution = (Solution) iSolutions.get(solverGroup.getUniqueId());
        if (solution == null) {
            solution = new Solution();
            iSolutions.put(solverGroup.getUniqueId(), solution);
        }
        solution.setCommitDate(null);
        solution.setCreated(new Timestamp((new Date()).getTime()));
        solution.setCreator(Test.getVersionString());
        solution.setNote(getModel().getProperties().getProperty("General.Note"));
        solution.setOwner(solverGroup);
        solverGroup.getSolutions().add(solution);
        solution.setValid(Boolean.TRUE);
        solution.setCommited(Boolean.FALSE);

        iProgress.setPhase("Saving solver parameters ...", getModel().getProperties().size());
        HashSet params = new HashSet();
        for (Iterator i1 = getModel().getProperties().entrySet().iterator(); i1.hasNext();) {
            Map.Entry entry = (Map.Entry) i1.next();
            String name = (String) entry.getKey();
            String value = (String) entry.getValue();
            SolverParameterDef def = SolverParameterDef.findByNameType(hibSession, name,
                    SolverParameterGroup.sTypeCourse);
            if (def != null) {
                iProgress.trace("save " + name + "=" + value);
                SolverParameter param = new SolverParameter();
                param.setDefinition(def);
                param.setValue(value);
                hibSession.save(param);
                params.add(param);
            }
            iProgress.incProgress();
        }
        solution.setParameters(params);

        hibSession.saveOrUpdate(solution);
    }

    hibSession.flush();
    hibSession.clear();
    int batchIdx = 0;

    iProgress.setPhase("Saving assignments ...", getModel().variables().size());
    for (Lecture lecture : getModel().variables()) {
        Placement placement = getAssignment().getValue(lecture);
        if (placement != null) {
            iProgress.trace("save " + lecture.getName() + " " + placement.getName());
            Class_ clazz = (new Class_DAO()).get(lecture.getClassId(), hibSession);
            if (clazz == null) {
                iProgress.warn("Unable to save assignment for class " + lecture + " ("
                        + placement.getLongName(iUseAmPm) + ") -- class (id:" + lecture.getClassId()
                        + ") does not exist.");
                continue;
            }
            HashSet rooms = new HashSet();
            if (placement.isMultiRoom()) {
                for (RoomLocation r : placement.getRoomLocations()) {
                    Location room = (new LocationDAO()).get(r.getId(), hibSession);
                    if (room == null) {
                        iProgress.warn("Unable to save assignment for class " + lecture + " ("
                                + placement.getLongName(iUseAmPm) + ") -- room (id:" + r.getId()
                                + ") does not exist.");
                        continue;
                    }
                    rooms.add(room);
                }
                if (rooms.size() != placement.getRoomLocations().size())
                    continue;
            } else {
                Location room = (new LocationDAO()).get(placement.getRoomLocation().getId(), hibSession);
                if (room == null) {
                    iProgress.warn("Unable to save assignment for class " + lecture + " ("
                            + placement.getLongName(iUseAmPm) + ") -- room (id:"
                            + placement.getRoomLocation().getId() + ") does not exist.");
                    continue;
                }
                rooms.add(room);
            }

            HashSet instructors = new HashSet();
            for (InstructorConstraint ic : lecture.getInstructorConstraints()) {
                DepartmentalInstructor instructor = null;
                if (ic.getPuid() != null && ic.getPuid().length() > 0) {
                    instructor = DepartmentalInstructor.findByPuidDepartmentId(ic.getPuid(),
                            clazz.getControllingDept().getUniqueId());
                } else if (ic.getResourceId() != null) {
                    instructor = (new DepartmentalInstructorDAO()).get(ic.getResourceId(), hibSession);
                }
                if (instructor != null)
                    instructors.add(instructor);
            }

            TimePattern pattern = (new TimePatternDAO()).get(placement.getTimeLocation().getTimePatternId(),
                    hibSession);
            if (pattern == null) {
                iProgress.warn("Unable to save assignment for class " + lecture + " ("
                        + placement.getLongName(iUseAmPm) + ") -- time pattern (id:"
                        + placement.getTimeLocation().getTimePatternId() + ") does not exist.");
                continue;
            }
            Solution solution = getSolution(lecture, hibSession);
            if (solution == null) {
                iProgress.warn("Unable to save assignment for class " + lecture + " ("
                        + placement.getLongName(iUseAmPm)
                        + ") -- none or wrong solution group assigned to the class");
                continue;
            }
            Assignment assignment = new Assignment();
            assignment.setClazz(clazz);
            assignment.setClassId(clazz.getUniqueId());
            assignment.setClassName(lecture.getName());
            assignment.setDays(new Integer(placement.getTimeLocation().getDayCode()));
            assignment.setStartSlot(new Integer(placement.getTimeLocation().getStartSlot()));
            assignment.setTimePattern(pattern);
            if (placement.getTimeLocation().getDatePatternId() != null)
                assignment.setDatePattern(DatePatternDAO.getInstance()
                        .get(placement.getTimeLocation().getDatePatternId(), hibSession));
            assignment.setRooms(rooms);
            assignment.setInstructors(instructors);
            assignment.setSolution(solution);
            hibSession.save(assignment);
            iAssignments.put(lecture.getClassId(), assignment);
            if (++batchIdx % BATCH_SIZE == 0) {
                hibSession.flush();
                hibSession.clear();
            }
        }
        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    if (getModel().getProperties().getPropertyBoolean("General.SaveStudentEnrollments", true)) {
        iProgress.setPhase("Saving student enrollments ...", getModel().variables().size());
        for (Lecture lecture : getModel().variables()) {
            Class_ clazz = (new Class_DAO()).get(lecture.getClassId(), hibSession);
            if (clazz == null)
                continue;
            iProgress.trace("save " + lecture.getName());
            Solution solution = getSolution(lecture, hibSession);
            if (solution == null) {
                iProgress.warn("Unable to save student enrollments for class " + lecture
                        + "  -- none or wrong solution group assigned to the class");
                continue;
            }

            for (Iterator i2 = lecture.students().iterator(); i2.hasNext();) {
                Student student = (Student) i2.next();
                StudentEnrollment enrl = new StudentEnrollment();
                enrl.setStudentId(student.getId());
                enrl.setClazz(clazz);
                enrl.setSolution(solution);
                hibSession.save(enrl);
                if (++batchIdx % BATCH_SIZE == 0) {
                    hibSession.flush();
                    hibSession.clear();
                }
            }

            iProgress.incProgress();
        }

        hibSession.flush();
        hibSession.clear();
        batchIdx = 0;
    }

    /**  // is this needed?
    iProgress.setPhase("Saving joint enrollments ...", getModel().getJenrlConstraints().size());
    for (Enumeration e1=getModel().getJenrlConstraints().elements();e1.hasMoreElements();) {
     JenrlConstraint jenrlConstraint = (JenrlConstraint)e1.nextElement();
             
     Class_ clazz1 = (new Class_DAO()).get(((Lecture)jenrlConstraint.first()).getClassId());
     Class_ clazz2 = (new Class_DAO()).get(((Lecture)jenrlConstraint.second()).getClassId());
             
     JointEnrollment jenrl = new JointEnrollment();
     jenrl.setJenrl(new Double(jenrlConstraint.getJenrl()));
     jenrl.setClass1(clazz1);
     jenrl.setClass2(clazz2);
     jenrl.setSolution(solution);
     hibSession.save(jenrl);
             
     iProgress.incProgress();
    }
    */

    SolverInfoDef defGlobalInfo = SolverInfoDef.findByName(hibSession, "GlobalInfo");
    if (defGlobalInfo == null)
        iProgress.warn("Global info is not registered.");
    SolverInfoDef defCbsInfo = SolverInfoDef.findByName(hibSession, "CBSInfo");
    if (defCbsInfo == null)
        iProgress.warn("Constraint-based statistics info is not registered.");
    SolverInfoDef defAssignmentInfo = SolverInfoDef.findByName(hibSession, "AssignmentInfo");
    if (defAssignmentInfo == null)
        iProgress.warn("Assignment info is not registered.");
    SolverInfoDef defDistributionInfo = SolverInfoDef.findByName(hibSession, "DistributionInfo");
    if (defDistributionInfo == null)
        iProgress.warn("Distribution constraint info is not registered.");
    SolverInfoDef defJenrlInfo = SolverInfoDef.findByName(hibSession, "JenrlInfo");
    if (defJenrlInfo == null)
        iProgress.warn("Joint enrollments info is not registered.");
    SolverInfoDef defLogInfo = SolverInfoDef.findByName(hibSession, "LogInfo");
    if (defLogInfo == null)
        iProgress.warn("Solver log info is not registered.");
    SolverInfoDef defBtbInstrInfo = SolverInfoDef.findByName(hibSession, "BtbInstructorInfo");
    if (defBtbInstrInfo == null)
        iProgress.warn("Back-to-back instructor info is not registered.");

    Hashtable<Solution, List<Lecture>> lectures4solution = new Hashtable<Solution, List<Lecture>>();
    for (Lecture lecture : getModel().variables()) {
        Solution s = getSolution(lecture, hibSession);
        if (s == null)
            continue;
        List<Lecture> lectures = lectures4solution.get(s);
        if (lectures == null) {
            lectures = new ArrayList<Lecture>();
            lectures4solution.put(s, lectures);
        }
        lectures.add(lecture);
    }

    iProgress.setPhase("Saving global info ...", solverGroups.size());
    for (Enumeration e = solverGroups.elements(); e.hasMoreElements();) {
        SolverGroup solverGroup = (SolverGroup) e.nextElement();
        Solution solution = (Solution) iSolutions.get(solverGroup.getUniqueId());
        List<Lecture> lectures = lectures4solution.get(solution);
        if (lectures == null)
            lectures = new ArrayList<Lecture>(0);
        SolutionInfo solutionInfo = new SolutionInfo();
        solutionInfo.setDefinition(defGlobalInfo);
        solutionInfo.setOpt(null);
        solutionInfo.setSolution(solution);
        solutionInfo.setInfo(new PropertiesInfo(getSolution().getInfo(lectures)), getFileProxy());
        hibSession.save(solutionInfo);
        solution.setGlobalInfo(solutionInfo);
        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    ConflictStatistics cbs = null;
    for (Extension ext : getSolver().getExtensions()) {
        if (ext instanceof ConflictStatistics) {
            cbs = (ConflictStatistics) ext;
            break;
        }
    }
    if (cbs != null && cbs.getNoGoods() != null) {
        ConflictStatisticsInfo cbsInfo = new ConflictStatisticsInfo();
        cbsInfo.load(getSolver(), cbs);
        iProgress.setPhase("Saving conflict-based statistics ...", 1);
        for (Enumeration e = iSolutions.elements(); e.hasMoreElements();) {
            Solution solution = (Solution) e.nextElement();
            List<Lecture> lectures = lectures4solution.get(solution);
            if (lectures == null)
                lectures = new ArrayList<Lecture>(0);
            SolutionInfo cbsSolutionInfo = new SolutionInfo();
            cbsSolutionInfo.setDefinition(defCbsInfo);
            cbsSolutionInfo.setOpt(null);
            cbsSolutionInfo.setSolution(solution);
            cbsSolutionInfo.setInfo(cbsInfo.getConflictStatisticsSubInfo(lectures), getFileProxy());
            hibSession.save(cbsSolutionInfo);
            if (++batchIdx % BATCH_SIZE == 0) {
                hibSession.flush();
                hibSession.clear();
            }
        }
        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving variable infos ...", getModel().variables().size());
    for (Lecture lecture : getModel().variables()) {
        Placement placement = getAssignment().getValue(lecture);
        if (placement != null) {
            Assignment assignment = (Assignment) iAssignments.get(lecture.getClassId());
            AssignmentInfo assignmentInfo = new AssignmentInfo();
            assignmentInfo.setAssignment(assignment);
            assignmentInfo.setDefinition(defAssignmentInfo);
            assignmentInfo.setOpt(null);
            assignmentInfo.setInfo(new AssignmentPreferenceInfo(getSolver(), placement, true, true),
                    getFileProxy());
            hibSession.save(assignmentInfo);
            if (++batchIdx % BATCH_SIZE == 0) {
                hibSession.flush();
                hibSession.clear();
            }
        }
        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving btb instructor infos ...", getModel().variables().size());
    for (Lecture lecture1 : getModel().variables()) {
        Placement placement1 = (Placement) getAssignment().getValue(lecture1);
        iProgress.incProgress();
        if (placement1 == null)
            continue;
        for (InstructorConstraint ic : lecture1.getInstructorConstraints()) {
            for (Lecture lecture2 : ic.variables()) {
                Placement placement2 = (Placement) getAssignment().getValue(lecture2);
                if (placement2 == null || lecture2.getClassId().compareTo(lecture1.getClassId()) <= 0)
                    continue;
                int pref = ic.getDistancePreference(placement1, placement2);
                if (pref == PreferenceLevel.sIntLevelNeutral)
                    continue;
                iProgress.trace("Back-to-back instructor constraint (" + pref + ") between " + placement1
                        + " and " + placement2);
                BtbInstructorConstraintInfo biInfo = new BtbInstructorConstraintInfo();
                biInfo.setPreference(pref);
                biInfo.setInstructorId(ic.getResourceId());
                ConstraintInfo constraintInfo = new ConstraintInfo();
                constraintInfo.setDefinition(defBtbInstrInfo);
                constraintInfo.setOpt(String.valueOf(ic.getResourceId()));
                HashSet biAssignments = new HashSet();
                Assignment assignment = (Assignment) iAssignments.get(lecture1.getClassId());
                if (assignment != null)
                    biAssignments.add(assignment);
                assignment = (Assignment) iAssignments.get(lecture2.getClassId());
                if (assignment != null)
                    biAssignments.add(assignment);
                if (!biAssignments.isEmpty()) {
                    constraintInfo.setAssignments(biAssignments);
                    constraintInfo.setInfo(biInfo, getFileProxy());
                    hibSession.save(constraintInfo);
                    if (++batchIdx % BATCH_SIZE == 0) {
                        hibSession.flush();
                        hibSession.clear();
                    }
                } else {
                    iProgress.trace("   NO ASSIGNMENTS !!!");
                }
            }
        }
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving group constraint infos ...", getModel().getGroupConstraints().size());
    for (GroupConstraint gc : getModel().getGroupConstraints()) {
        GroupConstraintInfo gcInfo = new GroupConstraintInfo(getAssignment(), gc);
        ConstraintInfo constraintInfo = new ConstraintInfo();
        constraintInfo.setDefinition(defDistributionInfo);
        constraintInfo.setOpt(gcInfo.isSatisfied() ? "1" : "0");
        iProgress.trace("Distribution constraint " + gcInfo.getName() + " (p:" + gcInfo.getPreference() + ", s:"
                + gcInfo.isSatisfied() + ") between");
        HashSet gcAssignments = new HashSet();
        for (Lecture lecture : gc.variables()) {
            Assignment assignment = (Assignment) iAssignments.get(lecture.getClassId());
            iProgress.trace("  " + getAssignment().getValue(lecture));
            if (assignment != null)
                gcAssignments.add(assignment);
        }

        if (!gcAssignments.isEmpty()) {
            constraintInfo.setAssignments(gcAssignments);
            constraintInfo.setInfo(gcInfo, getFileProxy());
            hibSession.save(constraintInfo);
            if (++batchIdx % BATCH_SIZE == 0) {
                hibSession.flush();
                hibSession.clear();
            }
        } else {
            iProgress.trace("   NO ASSIGNMENTS !!!");
        }

        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving student enrollment infos ...", getModel().getJenrlConstraints().size());
    for (JenrlConstraint jc : getModel().getJenrlConstraints()) {
        if (!jc.isInConflict(getAssignment()) || !jc.isOfTheSameProblem()) {
            iProgress.incProgress();
            continue;
        }
        JenrlInfo jInfo = new JenrlInfo(getSolver(), jc);
        ConstraintInfo constraintInfo = new ConstraintInfo();
        constraintInfo.setDefinition(defJenrlInfo);
        constraintInfo.setOpt((jInfo.isSatisfied() ? "S" : "") + (jInfo.isHard() ? "H" : "")
                + (jInfo.isDistance() ? "D" : "") + (jInfo.isFixed() ? "F" : "")
                + (jInfo.isImportant() ? "I" : "") + (jInfo.isInstructor() ? "X" : ""));
        Assignment firstAssignment = (Assignment) iAssignments.get(((Lecture) jc.first()).getClassId());
        Assignment secondAssignment = (Assignment) iAssignments.get(((Lecture) jc.second()).getClassId());
        if (firstAssignment == null || secondAssignment == null)
            continue;
        HashSet jAssignments = new HashSet();
        jAssignments.add(firstAssignment);
        jAssignments.add(secondAssignment);
        constraintInfo.setAssignments(jAssignments);
        constraintInfo.setInfo(jInfo, getFileProxy());
        hibSession.save(constraintInfo);
        if (++batchIdx % BATCH_SIZE == 0) {
            hibSession.flush();
            hibSession.clear();
        }

        iProgress.incProgress();
    }

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Saving committed student enrollment infos ...", iSolutions.size());
    for (Enumeration e = iSolutions.elements(); e.hasMoreElements();) {
        Solution solution = (Solution) e.nextElement();
        solution.updateCommittedStudentEnrollmentInfos(hibSession);
        iProgress.incProgress();
    }
    iProgress.incProgress();

    /*
    iProgress.setPhase("Saving committed student enrollment infos ...", getModel().assignedVariables().size());
    for (Enumeration e1=getModel().assignedVariables().elements();e1.hasMoreElements();) {
     Lecture lecture = (Lecture)e1.nextElement();
     Assignment assignment = (Assignment)iAssignments.get(lecture.getClassId());
    if (assignment==null) continue;
    Hashtable infos = JenrlInfo.getCommitedJenrlInfos(lecture);
     for (Iterator i2=infos.entrySet().iterator();i2.hasNext();) {
        Map.Entry entry = (Map.Entry)i2.next();
        Integer assignmentId = (Integer)entry.getKey();
        JenrlInfo jInfo = (JenrlInfo)entry.getValue();
        Assignment other = (new AssignmentDAO()).get(assignmentId,hibSession);
        if (other==null) continue;
         ConstraintInfo constraintInfo = new ConstraintInfo();
         constraintInfo.setDefinition(defJenrlInfo);
         constraintInfo.setOpt("C"+(jInfo.isSatisfied()?"S":"")+(jInfo.isHard()?"H":"")+(jInfo.isDistance()?"D":"")+(jInfo.isFixed()?"F":""));
         HashSet jAssignments = new HashSet();
         jAssignments.add(assignment);
         jAssignments.add(other);
         constraintInfo.setAssignments(jAssignments);
         constraintInfo.setInfo(jInfo,getFileProxy());
         hibSession.save(constraintInfo);
        if (++batchIdx % BATCH_SIZE == 0) {
           hibSession.flush(); hibSession.clear();
        }
     }
     iProgress.incProgress();
    }
    */

    hibSession.flush();
    hibSession.clear();
    batchIdx = 0;

    iProgress.setPhase("Done", 1);
    iProgress.incProgress();

    Long ret[] = new Long[iSolutions.size()];
    int idx = 0;
    for (Enumeration e = iSolutions.elements(); e.hasMoreElements();)
        ret[idx++] = ((Solution) e.nextElement()).getUniqueId();

    return ret;
}