List of usage examples for java.util Hashtable isEmpty
public synchronized boolean isEmpty()
From source file:org.lexevs.dao.database.sqlimplementedmethods.SQLImplementedMethodsDao.java
/** * Builds the coded entry./*from w ww . ja v a2 s . co m*/ * * @param internalCodingSchemeName the internal coding scheme name * @param internalVersionString the internal version string * @param code the code * @param namespace the namespace * @param restrictToProperties the restrict to properties * @param restrictToPropertyTypes the restrict to property types * * @return the entity * * @throws UnexpectedInternalError the unexpected internal error * @throws MissingResourceException the missing resource exception */ public Entity buildCodedEntry(String internalCodingSchemeName, String internalVersionString, String code, String namespace, LocalNameList restrictToProperties, PropertyType[] restrictToPropertyTypes) throws UnexpectedInternalError, MissingResourceException { try { Entity concept = new Entity(); concept.setEntityCode(code); SQLInterface si = resourceManager.getSQLInterface(internalCodingSchemeName, internalVersionString); //if the namespace is null (and its 2009 model), set it to the default (which is //equal to the codingSchemeName. //This shouldn't ever happen -- all classes that call this method should provide //a namespace. if (si.supports2009Model() && StringUtils.isBlank(namespace)) { namespace = internalCodingSchemeName; } ArrayList<Definition> definitions = new ArrayList<Definition>(); ArrayList<Presentation> presentations = new ArrayList<Presentation>(); ArrayList<Property> properties = new ArrayList<Property>(); ArrayList<Comment> comments = new ArrayList<Comment>(); ArrayList<PropertyLink> links = new ArrayList<PropertyLink>(); PreparedStatement getEntityCode = null; PreparedStatement getEntityType = null; PreparedStatement getEntityProperties = null; PreparedStatement getPropertyLinks = null; try { StringBuffer buildEntity = new StringBuffer(); buildEntity .append("Select * " + " from " + si.getTableName(SQLTableConstants.ENTITY) + " {AS} t1 "); if (si.supports2009Model()) { buildEntity.append("left join " + si.getTableName(SQLTableConstants.ENTRY_STATE) + " {AS} t2 " + "on t1." + SQLTableConstants.TBLCOL_ENTRYSTATEID + " = t2." + SQLTableConstants.TBLCOL_ENTRYSTATEID); } buildEntity.append(" where " + si.getSQLTableConstants().codingSchemeNameOrId + " = ? AND " + si.getSQLTableConstants().entityCodeOrId + " = ?"); if (si.supports2009Model()) { buildEntity.append(" AND " + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?"); } getEntityCode = si.modifyAndCheckOutPreparedStatement(buildEntity.toString()); getEntityCode.setString(1, internalCodingSchemeName); getEntityCode.setString(2, code); if (si.supports2009Model()) { getEntityCode.setString(3, namespace); } ResultSet results = getEntityCode.executeQuery(); // one and only one result if (results.next()) { concept.setIsDefined( DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISDEFINED)); concept.setIsAnonymous( DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISANONYMOUS)); concept.setIsActive( DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISACTIVE)); if (!si.supports2009Model()) { concept.setStatus(results.getString(SQLTableConstants.TBLCOL_CONCEPTSTATUS)); } else { concept.setEntityCodeNamespace(namespace); } EntityDescription ed = new EntityDescription(); ed.setContent(results.getString(SQLTableConstants.TBLCOL_ENTITYDESCRIPTION)); concept.setEntityDescription(ed); if (si.supports2009Model()) { String owner = results.getString(SQLTableConstants.TBLCOL_OWNER); String status = results.getString(SQLTableConstants.TBLCOL_STATUS); Timestamp effectiveDate = results.getTimestamp(SQLTableConstants.TBLCOL_EFFECTIVEDATE); Timestamp expirationDate = results.getTimestamp(SQLTableConstants.TBLCOL_EXPIRATIONDATE); String revisionId = results.getString(SQLTableConstants.TBLCOL_REVISIONID); String prevRevisionId = results.getString(SQLTableConstants.TBLCOL_PREVREVISIONID); String changeType = results.getString(SQLTableConstants.TBLCOL_CHANGETYPE); String relativeOrder = results.getString(SQLTableConstants.TBLCOL_RELATIVEORDER); EntryState es = new EntryState(); if (!StringUtils.isBlank(changeType)) { es.setChangeType(org.LexGrid.versions.types.ChangeType.valueOf(changeType)); } es.setContainingRevision(revisionId); es.setPrevRevision(prevRevisionId); es.setRelativeOrder(computeRelativeOrder(relativeOrder)); concept.setEntryState(es); if (owner != null) { concept.setOwner(owner); } concept.setStatus(status); concept.setEffectiveDate(effectiveDate); concept.setExpirationDate(expirationDate); } } results.close(); si.checkInPreparedStatement(getEntityCode); if (si.supports2009Model()) { getEntityType = si.checkOutPreparedStatement( "Select * " + " from " + si.getTableName(SQLTableConstants.ENTITY_TYPE) + " where " + si.getSQLTableConstants().codingSchemeNameOrId + " = ? AND " + si.getSQLTableConstants().entityCodeOrId + " = ? AND " + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?"); getEntityType.setString(1, internalCodingSchemeName); getEntityType.setString(2, code); getEntityType.setString(3, namespace); results = getEntityType.executeQuery(); while (results.next()) { concept.addEntityType(results.getString(SQLTableConstants.TBLCOL_ENTITYTYPE)); } results.close(); si.checkInPreparedStatement(getEntityType); } else { concept.addEntityType(SQLTableConstants.ENTITYTYPE_CONCEPT); } // populate the property links String addWhereSegment = (!si.supports2009Model() ? (si.getSQLTableConstants().entityType + " = '" + SQLTableConstants.ENTITYTYPE_CONCEPT + "' and ") : ""); getPropertyLinks = si .checkOutPreparedStatement("Select " + SQLTableConstants.TBLCOL_SOURCEPROPERTYID + ", " + SQLTableConstants.TBLCOL_LINK + ", " + SQLTableConstants.TBLCOL_TARGETPROPERTYID + " from " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_LINKS) + " where " + addWhereSegment + si.getSQLTableConstants().entityCodeOrEntityId + " = ? and " + si.getSQLTableConstants().codingSchemeNameOrId + " = ?"); getPropertyLinks.setString(1, code); getPropertyLinks.setString(2, internalCodingSchemeName); results = getPropertyLinks.executeQuery(); while (results.next()) { String sourcePropertyId = results.getString(SQLTableConstants.TBLCOL_SOURCEPROPERTYID); String link = results.getString(SQLTableConstants.TBLCOL_LINK); String targetPropertyId = results.getString(SQLTableConstants.TBLCOL_TARGETPROPERTYID); PropertyLink pl = new PropertyLink(); pl.setPropertyLink(link); pl.setSourceProperty(sourcePropertyId); pl.setTargetProperty(targetPropertyId); links.add(pl); } results.close(); si.checkInPreparedStatement(getPropertyLinks); // codedEntry.setModVersion(null); StringBuffer propertyQuery = new StringBuffer(); // I'm constructing a left join query to get the property // results I need from 3 (or 2 in 1.5 table version) different // tables at once, rather than doing a query on each. propertyQuery.append("SELECT a." + SQLTableConstants.TBLCOL_PROPERTYID + ", a." + SQLTableConstants.TBLCOL_PROPERTYNAME + ", a." + SQLTableConstants.TBLCOL_LANGUAGE + ", a." + SQLTableConstants.TBLCOL_FORMAT + ", a." + SQLTableConstants.TBLCOL_ISPREFERRED + ", a." + SQLTableConstants.TBLCOL_DEGREEOFFIDELITY + ", a." + SQLTableConstants.TBLCOL_MATCHIFNOCONTEXT + ", a." + SQLTableConstants.TBLCOL_REPRESENTATIONALFORM + ", a." + SQLTableConstants.TBLCOL_PROPERTYVALUE + ", a." + SQLTableConstants.TBLCOL_PROPERTYTYPE + (si.supports2009Model() ? (", a." + SQLTableConstants.TBLCOL_ENTRYSTATEID) : "") + (si.supports2009Model() ? ", es.*" : "") + ", b." + SQLTableConstants.TBLCOL_TYPENAME + ", b." + SQLTableConstants.TBLCOL_ATTRIBUTEVALUE + ", b." + SQLTableConstants.TBLCOL_VAL1 + ", b." + SQLTableConstants.TBLCOL_VAL2); propertyQuery.append(" FROM "); String codingSchemeName = si.getSQLTableConstants().codingSchemeNameOrId; String concptCode = si.getSQLTableConstants().entityCodeOrEntityId; propertyQuery.append(si.getTableName(SQLTableConstants.ENTITY_PROPERTY) + " {AS} a "); propertyQuery.append( " left join " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_MULTI_ATTRIBUTES)); propertyQuery.append(" {AS} b on a." + codingSchemeName + " = b." + codingSchemeName + " and a." + concptCode + " = b." + concptCode + " and a." + SQLTableConstants.TBLCOL_PROPERTYID + " = b." + SQLTableConstants.TBLCOL_PROPERTYID); if (si.supports2009Model()) { propertyQuery .append(" left join " + si.getTableName(SQLTableConstants.ENTRY_STATE) + " {AS} es "); propertyQuery.append("on a." + SQLTableConstants.TBLCOL_ENTRYSTATEID); propertyQuery.append(" = es." + SQLTableConstants.TBLCOL_ENTRYSTATEID); } propertyQuery.append(" where a." + concptCode + " = ? " + "and a." + codingSchemeName + " = ?"); if (si.supports2009Model()) { propertyQuery.append(" and a." + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?"); } if (restrictToProperties != null && restrictToProperties.getEntryCount() > 0) { propertyQuery.append(" AND ("); for (int i = 0; i < restrictToProperties.getEntryCount(); i++) { propertyQuery.append(" " + si.getSQLTableConstants().propertyOrPropertyName + " = ? "); if (i + 1 < restrictToProperties.getEntryCount()) { propertyQuery.append(" OR "); } } propertyQuery.append(")"); } if (restrictToPropertyTypes != null && restrictToPropertyTypes.length > 0) { propertyQuery.append(" AND ("); for (int i = 0; i < restrictToPropertyTypes.length; i++) { propertyQuery.append(" " + SQLTableConstants.TBLCOL_PROPERTYTYPE + " = ? "); if (i + 1 < restrictToPropertyTypes.length) { propertyQuery.append(" OR "); } } propertyQuery.append(")"); } getEntityProperties = si.modifyAndCheckOutPreparedStatement(propertyQuery.toString()); int i = 1; getEntityProperties.setString(i++, code); getEntityProperties.setString(i++, internalCodingSchemeName); if (si.supports2009Model()) { getEntityProperties.setString(i++, namespace); } if (restrictToProperties != null && restrictToProperties.getEntryCount() > 0) { for (int j = 0; j < restrictToProperties.getEntryCount(); j++) { getEntityProperties.setString(i++, restrictToProperties.getEntry(j)); } } if (restrictToPropertyTypes != null && restrictToPropertyTypes.length > 0) { for (int j = 0; j < restrictToPropertyTypes.length; j++) { String pts = DaoUtility.propertyTypeToStringMap.get(restrictToPropertyTypes[j]); getEntityProperties.setString(i++, pts); } } results = getEntityProperties.executeQuery(); // store the property from the last row org.LexGrid.commonTypes.Property newProperty = null; // all of the fields that come from the Property table String propertyType, property, propertyValue, language, presentationFormat, degreeOfFidelity, propertyId, representationalForm; Boolean matchIfNoContext, isPreferred; // holders for attributes, qualifiers Hashtable<String, Source> sources = null; HashSet<String> usageContexts = null; Hashtable<String, PropertyQualifier> propertyQualifiers = null; // As I process the result rows, I will get back duplicates of // the property information // if the property has more than one qualifer and/or source , // etc. while (results.next()) { propertyId = results.getString(SQLTableConstants.TBLCOL_PROPERTYID); if (newProperty == null || !propertyId.equals(newProperty.getPropertyId())) { // not equal means we have started a new property property = results.getString(si.getSQLTableConstants().propertyOrPropertyName); propertyType = results.getString(SQLTableConstants.TBLCOL_PROPERTYTYPE); propertyValue = results.getString(SQLTableConstants.TBLCOL_PROPERTYVALUE); language = results.getString(SQLTableConstants.TBLCOL_LANGUAGE); presentationFormat = results .getString(si.getSQLTableConstants().formatOrPresentationFormat); degreeOfFidelity = results.getString(SQLTableConstants.TBLCOL_DEGREEOFFIDELITY); representationalForm = results.getString(SQLTableConstants.TBLCOL_REPRESENTATIONALFORM); matchIfNoContext = DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_MATCHIFNOCONTEXT); isPreferred = DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISPREFERRED); // add all of the collected sources, usage contexts, and // qualifiers to // the previous property if (newProperty != null) { newProperty.setSource(sources.values().toArray(new Source[sources.size()])); newProperty.setUsageContext(usageContexts.toArray(new String[usageContexts.size()])); if (!propertyQualifiers.isEmpty()) newProperty.setPropertyQualifier(propertyQualifiers.values() .toArray(new PropertyQualifier[propertyQualifiers.size()])); } // we are starting a new property, so clear out the old // holders. sources = new Hashtable<String, Source>(); usageContexts = new HashSet<String>(); propertyQualifiers = new Hashtable<String, PropertyQualifier>(); // process the property portion of the result if (propertyType.equals(SQLTableConstants.TBLCOLVAL_DEFINITION)) { Definition def = new Definition(); def.setIsPreferred(isPreferred); def.setLanguage(language); def.setPropertyName(property); def.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); def.setValue(text); definitions.add(def); newProperty = def; } else if (propertyType.equals(SQLTableConstants.TBLCOLVAL_PRESENTATION)) { Presentation presentation = new Presentation(); presentation.setIsPreferred(isPreferred); presentation.setLanguage(language); presentation.setPropertyName(property); presentation.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); presentation.setValue(text); presentation.setDegreeOfFidelity(degreeOfFidelity); presentation.setMatchIfNoContext(matchIfNoContext); presentation.setRepresentationalForm(representationalForm); presentations.add(presentation); newProperty = presentation; } else if (propertyType.equals(SQLTableConstants.TBLCOLVAL_COMMENT)) { Comment comment = new Comment(); comment.setLanguage(language); comment.setPropertyName(property); comment.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); comment.setValue(text); comments.add(comment); newProperty = comment; } else { Property theProperty = new Property(); theProperty.setLanguage(language); theProperty.setPropertyName(property); theProperty.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); theProperty.setValue(text); properties.add(theProperty); newProperty = theProperty; } newProperty.setPropertyType(propertyType); if (si.supports2009Model()) { String owner = results.getString(SQLTableConstants.TBLCOL_OWNER); String status = results.getString(SQLTableConstants.TBLCOL_STATUS); Timestamp effectiveDate = results.getTimestamp(SQLTableConstants.TBLCOL_EFFECTIVEDATE); Timestamp expirationDate = results .getTimestamp(SQLTableConstants.TBLCOL_EXPIRATIONDATE); String revisionId = results.getString(SQLTableConstants.TBLCOL_REVISIONID); String prevRevisionId = results.getString(SQLTableConstants.TBLCOL_PREVREVISIONID); String changeType = results.getString(SQLTableConstants.TBLCOL_CHANGETYPE); String relativeOrder = results.getString(SQLTableConstants.TBLCOL_RELATIVEORDER); if (revisionId != null) { EntryState es = new EntryState(); if (!StringUtils.isBlank(changeType)) { es.setChangeType(org.LexGrid.versions.types.ChangeType.valueOf(changeType)); } es.setContainingRevision(revisionId); es.setPrevRevision(prevRevisionId); es.setRelativeOrder(computeRelativeOrder(relativeOrder)); newProperty.setEntryState(es); } if (owner != null) { newProperty.setOwner(owner); } if (status != null) newProperty.setStatus(status); if (effectiveDate != null) newProperty.setEffectiveDate(effectiveDate); if (expirationDate != null) newProperty.setExpirationDate(expirationDate); } } String type = null; String value = null; String val1 = null; String val2 = null; // collect values from the multiAttributes table type = results.getString(SQLTableConstants.TBLCOL_TYPENAME); value = results.getString(SQLTableConstants.TBLCOL_ATTRIBUTEVALUE); val1 = results.getString(SQLTableConstants.TBLCOL_VAL1); if (StringUtils.isBlank(val1)) val1 = null; val2 = results.getString(SQLTableConstants.TBLCOL_VAL2); if (StringUtils.isBlank(val2)) val2 = null; // hashsets to remove dupes (table doesn't allow dupes, but // left join will create some) if (type != null) { if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_SOURCE)) { if (!sources.containsKey(createUniqueKeyForSource(value, val1))) { Source s = new Source(); s.setContent(value); s.setRole(val2); s.setSubRef(val1); sources.put(createUniqueKeyForSource(value, val1), s); } } else if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_USAGECONTEXT)) { usageContexts.add(value); } else if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_QUALIFIER)) { // nulls are a side affect of left join if (!propertyQualifiers.containsKey(val1 + ":" + value)) { PropertyQualifier pq = new PropertyQualifier(); Text txt = new Text(); txt.setContent(val1); pq.setValue(txt); pq.setPropertyQualifierName(value); propertyQualifiers.put(val1 + ":" + value, pq); } } else { getLogger().warn("There is invalid data in the 'typeName' column in the table " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_MULTI_ATTRIBUTES) + " for the concept code: " + code + " propertyId: " + propertyId + " codingSchemeName: " + internalCodingSchemeName); } } } // add all of the collected sources, usage contexts, and // qualifiers to // the previous property before exiting ... if (newProperty != null) { newProperty.setSource(sources.values().toArray(new Source[sources.size()])); newProperty.setUsageContext(usageContexts.toArray(new String[usageContexts.size()])); if (!propertyQualifiers.isEmpty()) newProperty.setPropertyQualifier(propertyQualifiers.values() .toArray(new PropertyQualifier[propertyQualifiers.size()])); } results.close(); } finally { si.checkInPreparedStatement(getEntityCode); si.checkInPreparedStatement(getEntityProperties); si.checkInPreparedStatement(getPropertyLinks); } concept.setComment(comments.toArray(new Comment[comments.size()])); concept.setDefinition(definitions.toArray(new Definition[definitions.size()])); concept.setPropertyLink(links.toArray(new PropertyLink[links.size()])); concept.setPresentation(presentations.toArray(new Presentation[presentations.size()])); concept.setProperty(properties.toArray(new Property[properties.size()])); return concept; } catch (MissingResourceException e) { throw e; } catch (Exception e) { throw new UnexpectedInternalError("There was an unexpected internal error.", e); } }
From source file:org.sakaiproject.dav.DavServlet.java
/** * Copy a resource./* w w w.j a va 2 s .co m*/ * * @param req * Servlet request * @param resp * Servlet response * @param move * This is actually a move operation * @return boolean true if the copy is successful */ private boolean copyResource(HttpServletRequest req, HttpServletResponse resp, boolean move) throws ServletException, IOException { String destinationPath = getDestinationPath(req); if (destinationPath == null) { resp.sendError(SakaidavStatus.SC_BAD_REQUEST); return false; } if (M_log.isDebugEnabled()) M_log.debug("Dest path :" + destinationPath); if ((destinationPath.toUpperCase().startsWith("/WEB-INF")) || (destinationPath.toUpperCase().startsWith("/META-INF"))) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return false; } String path = getRelativePath(req); if (prohibited(path) || (path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return false; } if (prohibited(destinationPath) || destinationPath.equals(path)) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return false; } // Parsing overwrite header boolean overwrite = true; String overwriteHeader = req.getHeader("Overwrite"); if (overwriteHeader != null) { if (overwriteHeader.equalsIgnoreCase("T")) { overwrite = true; } else { overwrite = false; } } // Overwriting the destination // Retrieve the resources // DirContext resources = getResources(); DirContextSAKAI resources = getResourcesSAKAI(); if (resources == null) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; } boolean exists = true; try { resources.lookup(destinationPath); } catch (NamingException e) { exists = false; } if (overwrite) { // Delete destination resource, if it exists if (exists) { if (!deleteResource(destinationPath, req, resp)) { return false; } else { resp.setStatus(SakaidavStatus.SC_NO_CONTENT); } } else { resp.setStatus(SakaidavStatus.SC_CREATED); } } else { // If the destination exists, then it's a conflict if (exists) { resp.sendError(SakaidavStatus.SC_PRECONDITION_FAILED); return false; } } // Check to see if the parent collection of the destination exists. ContentHosting // will create a parent folder if it does not exist, but the WebDAV spec requires // this operation to fail (rfc2518, 8.3.1). String destParentId = isolateContainingId(adjustId(destinationPath)); try { contentHostingService.getCollection(destParentId); } catch (IdUnusedException e1) { resp.sendError(SakaidavStatus.SC_CONFLICT); return false; } catch (TypeException e1) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return false; } catch (PermissionException e1) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return false; } // Copying source to destination Hashtable<String, Integer> errorList = new Hashtable<String, Integer>(); boolean result = copyResource(resources, errorList, path, destinationPath, move); if ((!result) || (!errorList.isEmpty())) { sendReport(req, resp, errorList); return false; } // kernel's copyResource copies the resource name. That's inappropriate. // pick a new one based on filename. try { String filename = null; if (destinationPath.indexOf('/') >= 0) filename = destinationPath.substring(destinationPath.lastIndexOf('/') + 1); else filename = destinationPath; // hopefully this can't happen. if (filename.length() == 0) filename = "null"; ContentResourceEdit edit = contentHostingService .editResource(adjustId(fixDirPathSAKAI(destinationPath))); ResourcePropertiesEdit newProps = edit.getPropertiesEdit(); newProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, Validator.escapeResourceName(filename)); contentHostingService.commitResource(edit, NotificationService.NOTI_NONE); } catch (Exception e) { M_log.info("copyResource unable to set new displayname " + e); } ; // Removing any lock-null resource which would be present at // the destination path lockNullResources.remove(destinationPath); if (overwrite) resp.setStatus(SakaidavStatus.SC_NO_CONTENT); else resp.setStatus(SakaidavStatus.SC_CREATED); return true; }
From source file:org.unitime.timetable.solver.studentsct.StudentSectioningDatabaseLoader.java
public void load(Session session, org.hibernate.Session hibSession) { iFreeTimePattern = getFreeTimeBitSet(session); iDatePatternFirstDate = getDatePatternFirstDay(session); Hashtable<Long, Course> courseTable = new Hashtable<Long, Course>(); final Hashtable<Long, Section> classTable = new Hashtable<Long, Section>(); List<InstructionalOffering> offerings = hibSession .createQuery("select distinct io from InstructionalOffering io " + "left join fetch io.courseOfferings as co " + "left join fetch io.instrOfferingConfigs as ioc " + "left join fetch ioc.schedulingSubparts as ss " + "left join fetch ss.classes as c " + "left join fetch io.reservations as r " + "where " + "io.session.uniqueId = :sessionId and io.notOffered = false and co.subjectArea.department.allowStudentScheduling = true") .setLong("sessionId", session.getUniqueId().longValue()).setFetchSize(1000).list(); iProgress.setPhase("Loading course offerings...", offerings.size()); for (InstructionalOffering io : offerings) { iProgress.incProgress();//from ww w . ja v a 2s.co m Offering offering = loadOffering(io, courseTable, classTable); if (offering != null) getModel().addOffering(offering); } if (iIncludeCourseDemands || iProjections) { List students = hibSession.createQuery("select distinct s from Student s " + "left join fetch s.courseDemands as cd " + "left join fetch cd.courseRequests as cr " + "left join fetch cr.classWaitLists as cw " + "left join fetch s.classEnrollments as e " + "left join fetch s.waitlists as w " + (iLoadStudentInfo ? "left join fetch s.academicAreaClassifications as a left join fetch s.posMajors as mj left join fetch s.groups as g " : "") + "where s.session.uniqueId=:sessionId").setLong("sessionId", session.getUniqueId().longValue()) .setFetchSize(1000).list(); iProgress.setPhase("Loading student requests...", students.size()); for (Iterator i = students.iterator(); i.hasNext();) { org.unitime.timetable.model.Student s = (org.unitime.timetable.model.Student) i.next(); iProgress.incProgress(); if (s.getCourseDemands().isEmpty() && s.getClassEnrollments().isEmpty() && s.getWaitlists().isEmpty()) continue; Student student = loadStudent(s, courseTable, classTable); if (student == null) continue; updateCurriculumCounts(student); if (iProjections) { // Decrease the limits accordingly for (Request request : student.getRequests()) { if (request.getInitialAssignment() != null && request.getInitialAssignment().isCourseRequest()) { Enrollment enrollment = request.getInitialAssignment(); if (enrollment.getConfig().getLimit() > 0) enrollment.getConfig().setLimit(enrollment.getConfig().getLimit() - 1); for (Section section : enrollment.getSections()) if (section.getLimit() > 0) section.setLimit(section.getLimit() - 1); if (enrollment.getCourse() != null && enrollment.getCourse().getLimit() > 0) enrollment.getCourse().setLimit(enrollment.getCourse().getLimit() - 1); if (enrollment.getReservation() != null) { if (enrollment.getReservation() instanceof GroupReservation && enrollment.getReservation().getReservationLimit() >= 1.0) { ((GroupReservation) enrollment.getReservation()).getStudentIds() .remove(student.getId()); ((GroupReservation) enrollment.getReservation()).setReservationLimit( ((GroupReservation) enrollment.getReservation()).getReservationLimit() - 1.0); } else if (enrollment.getReservation() instanceof IndividualReservation) { ((IndividualReservation) enrollment.getReservation()).getStudentIds() .remove(student.getId()); } else if (enrollment.getReservation() instanceof CurriculumReservation && enrollment.getReservation().getReservationLimit() >= 1.0) { ((CurriculumReservation) enrollment.getReservation()).setReservationLimit( enrollment.getReservation().getReservationLimit() - 1.0); } } } if (request instanceof CourseRequest) { for (Course course : ((CourseRequest) request).getCourses()) { course.getRequests().remove(request); } } } } else { if (iLoadRequestGroups) loadRequestGroups(student, s); getModel().addStudent(student); // assignStudent(student); } } } List<DistributionPref> distPrefs = hibSession.createQuery( "select p from DistributionPref p, Department d where p.distributionType.reference in (:ref1, :ref2) and d.session.uniqueId = :sessionId" + " and p.owner = d and p.prefLevel.prefProlog = :pref") .setString("ref1", GroupConstraint.ConstraintType.LINKED_SECTIONS.reference()) .setString("ref2", IgnoreStudentConflictsConstraint.REFERENCE) .setString("pref", PreferenceLevel.sRequired).setLong("sessionId", iSessionId).list(); if (!distPrefs.isEmpty()) { iProgress.setPhase("Loading distribution preferences...", distPrefs.size()); SectionProvider p = new SectionProvider() { @Override public Section get(Long classId) { return classTable.get(classId); } }; for (DistributionPref pref : distPrefs) { iProgress.incProgress(); for (Collection<Section> sections : getSections(pref, p)) { if (GroupConstraint.ConstraintType.LINKED_SECTIONS.reference() .equals(pref.getDistributionType().getReference())) { getModel().addLinkedSections(iLinkedClassesMustBeUsed, sections); } else { for (Section s1 : sections) for (Section s2 : sections) if (!s1.equals(s2)) s1.addIgnoreConflictWith(s2.getId()); } } } } iProgress.setPhase("Assigning students...", getModel().getStudents().size()); for (Student student : getModel().getStudents()) { iProgress.incProgress(); assignStudent(student); } iProgress.setPhase("Checking for student conflicts...", getModel().getStudents().size()); for (Student student : getModel().getStudents()) { iProgress.incProgress(); checkForConflicts(student); } if (iStudentCourseDemands != null) { iStudentCourseDemands.init(hibSession, iProgress, SessionDAO.getInstance().get(iSessionId, hibSession), offerings); Hashtable<Long, Student> students = new Hashtable<Long, Student>(); Hashtable<Long, Set<Long>> classAssignments = null; if (iIncludeUseCommittedAssignments && !iStudentCourseDemands.isMakingUpStudents()) { classAssignments = new Hashtable(); List enrollments = hibSession.createQuery( "select distinct se.studentId, se.clazz.uniqueId from StudentEnrollment se where " + "se.solution.commited=true and se.solution.owner.session.uniqueId=:sessionId") .setLong("sessionId", session.getUniqueId().longValue()).setFetchSize(1000).list(); iProgress.setPhase("Loading projected class assignments...", enrollments.size()); for (Iterator i = enrollments.iterator(); i.hasNext();) { Object[] o = (Object[]) i.next(); iProgress.incProgress(); Long studentId = (Long) o[0]; Long classId = (Long) o[1]; Set<Long> classIds = classAssignments.get(studentId); if (classIds == null) { classIds = new HashSet<Long>(); classAssignments.put(studentId, classIds); } classIds.add(classId); } } iProgress.setPhase("Loading projected course requests...", offerings.size()); long requestId = -1; for (InstructionalOffering io : offerings) { iProgress.incProgress(); for (CourseOffering co : io.getCourseOfferings()) { Course course = courseTable.get(co.getUniqueId()); if (course == null) continue; Set<WeightedStudentId> demands = iStudentCourseDemands.getDemands(co); if (demands == null) continue; for (WeightedStudentId demand : demands) { Student student = (Student) students.get(demand.getStudentId()); if (student == null) { student = new Student(demand.getStudentId(), true); if (demand.getArea() != null && demand.getClasf() != null) student.getAcademicAreaClasiffications() .add(new AcademicAreaCode(demand.getArea(), demand.getClasf())); if (demand.getArea() != null && demand.getMajor() != null && !demand.getMajor().isEmpty()) for (String mj : demand.getMajor().split("\\|")) student.getMajors().add(new AcademicAreaCode(demand.getArea(), mj)); students.put(demand.getStudentId(), student); } List<Course> courses = new ArrayList<Course>(); courses.add(course); CourseRequest request = new CourseRequest(requestId--, 0, false, student, courses, false, null); request.setWeight(demand.getWeight()); if (classAssignments != null && !classAssignments.isEmpty()) { Set<Long> classIds = classAssignments.get(demand.getStudentId()); if (classIds != null) { enrollments: for (Enrollment enrollment : request.values(getAssignment())) { for (Section section : enrollment.getSections()) if (!classIds.contains(section.getId())) continue enrollments; request.setInitialAssignment(enrollment); break; } } } } } } for (Student student : students.values()) { getModel().addStudent(student); assignStudent(student); } for (Student student : students.values()) { checkForConflicts(student); } if (iFixWeights) fixWeights(hibSession, courseTable.values()); getModel().createAssignmentContexts(getAssignment(), true); } /* if (iIncludeLastLikeStudents) { Hashtable<Long, Set<Long>> classAssignments = null; if (iIncludeUseCommittedAssignments) { classAssignments = new Hashtable(); List enrollments = hibSession.createQuery("select distinct se.studentId, se.clazz.uniqueId from StudentEnrollment se where "+ "se.solution.commited=true and se.solution.owner.session.uniqueId=:sessionId"). setLong("sessionId",session.getUniqueId().longValue()).setFetchSize(1000).list(); iProgress.setPhase("Loading last-like class assignments...", enrollments.size()); for (Iterator i=enrollments.iterator();i.hasNext();) { Object[] o = (Object[])i.next(); iProgress.incProgress(); Long studentId = (Long)o[0]; Long classId = (Long)o[1]; Set<Long> classIds = classAssignments.get(studentId); if (classIds==null) { classIds = new HashSet<Long>(); classAssignments.put(studentId, classIds); } classIds.add(classId); } } Hashtable<Long, org.unitime.timetable.model.Student> students = new Hashtable<Long, org.unitime.timetable.model.Student>(); List enrollments = hibSession.createQuery( "select d, c.uniqueId from LastLikeCourseDemand d left join fetch d.student s, CourseOffering c left join c.demandOffering cx " + "where d.subjectArea.session.uniqueId=:sessionId and c.subjectArea.session.uniqueId=:sessionId and " + "((c.permId=null and d.subjectArea=c.subjectArea and d.courseNbr=c.courseNbr ) or "+ " (c.permId!=null and c.permId=d.coursePermId) or "+ " (cx.permId=null and d.subjectArea=cx.subjectArea and d.courseNbr=cx.courseNbr) or "+ " (cx.permId!=null and cx.permId=d.coursePermId)) "+ "order by s.uniqueId, d.priority, d.uniqueId"). setLong("sessionId",session.getUniqueId().longValue()).setFetchSize(1000).list(); iProgress.setPhase("Loading last-like course requests...", enrollments.size()); Hashtable lastLikeStudentTable = new Hashtable(); for (Iterator i=enrollments.iterator();i.hasNext();) { Object[] o = (Object[])i.next();iProgress.incProgress(); LastLikeCourseDemand d = (LastLikeCourseDemand)o[0]; org.unitime.timetable.model.Student s = (org.unitime.timetable.model.Student)d.getStudent(); Long courseOfferingId = (Long)o[1]; if (s.getExternalUniqueId()!=null && loadedStudentIds.contains(s.getExternalUniqueId())) continue; loadLastLikeStudent(hibSession, d, s, courseOfferingId, lastLikeStudentTable, courseTable, classTable, classAssignments); students.put(s.getUniqueId(), s); } for (Enumeration e=lastLikeStudentTable.elements();e.hasMoreElements();) { Student student = (Student)e.nextElement(); getModel().addStudent(student); assignStudent(student, students.get(student.getId())); } } */ if (iLoadSectioningInfos) { List<SectioningInfo> infos = hibSession.createQuery( "select i from SectioningInfo i where i.clazz.schedulingSubpart.instrOfferingConfig.instructionalOffering.session.uniqueId = :sessionId") .setLong("sessionId", iSessionId).list(); iProgress.setPhase("Loading sectioning infos...", infos.size()); for (SectioningInfo info : infos) { iProgress.incProgress(); Section section = classTable.get(info.getClazz().getUniqueId()); if (section != null) { section.setSpaceExpected(info.getNbrExpectedStudents()); section.setSpaceHeld(info.getNbrHoldingStudents()); if (section.getLimit() >= 0 && (section.getLimit() - section.getEnrollments(getAssignment()).size()) <= section .getSpaceExpected()) iProgress.info("Section " + section.getSubpart().getConfig().getOffering().getName() + " " + section.getSubpart().getName() + " " + section.getName() + " has high demand (limit: " + section.getLimit() + ", enrollment: " + section.getEnrollments(getAssignment()).size() + ", expected: " + section.getSpaceExpected() + ")"); } } } iProgress.setPhase("Done", 1); iProgress.incProgress(); }
From source file:org.adl.sequencer.impl.ADLSequencer.java
/** * Displays the values of the <code>ADLTOC</code> objects that constitute * table of contents. This method is used for diagnostic purposes. * /*from w ww.j a v a2 s . c o m*/ * @param iOldTOC * A List of <code>ADLTOC</code> objects describing the * 'first pass' TOC. * * @param oNewTOC * A List of <code>ADLTOC</code> objects describing the * 'final pass' TOC. * * @return The set of valid activity IDs for 'Choice' navigation requests. */ private Hashtable<String, ActivityNode> getChoiceSet(TreeModel treeModel) { Hashtable<String, ActivityNode> set = null; String lastLeaf = null; if (treeModel != null) { ActivityNode tempNode = null; set = new Hashtable<String, ActivityNode>(); ActivityNode rootNode = (ActivityNode) treeModel.getRoot(); if (rootNode != null) { @SuppressWarnings("unchecked") Enumeration<ActivityNode> breadthFirst = rootNode.breadthFirstEnumeration(); List<ActivityNode> bfList = Collections.list(breadthFirst); // Traverse the breadth-first search backwards for (int i = bfList.size() - 1; i > 0; i--) { tempNode = bfList.get(i); if (tempNode.getDepth() == -1) { if (tempNode.isSelectable()) { set.put(tempNode.getActivity().getID(), tempNode); } } else if (!tempNode.isHidden()) { set.put(tempNode.getActivity().getID(), tempNode); } if (lastLeaf == null) { if (tempNode.isLeaf() && tempNode.isEnabled()) { lastLeaf = tempNode.getActivity().getID(); } } } } } if (lastLeaf != null) { if (_Debug) { System.out.println(" ::--> Setting last leaf --> " + lastLeaf); } mSeqTree.setLastLeaf(lastLeaf); } // If there are no items in the set, there is no TOC. if (set != null && set.isEmpty()) { set = null; } // TODO: JLR -- think we might be able to live without this... 9/10/2007 // If there is only one item in the set, it must be the root -- remove // it // If there is only one item in the set, it is the parent of a // choiceExit == false cluster, it cannot be selected -- no TOC /*if (oNewTOC.size() == 1) { ADLTOC temp = (ADLTOC) oNewTOC.get(0); if (!temp.mIsEnabled) { if (_Debug) { System.out.println(" ::--> Clearing single non-enabled " + " activity"); } oNewTOC.remove(0); } else if (!temp.mLeaf) { if (_Debug) { System.out.println(" ::--> Clearing root activity"); } oNewTOC.remove(0); } }*/ return set; }
From source file:ParseURL.java
/************************************************************************** * Parse the given URL into its components. * <p>// w w w . j ava 2 s .c o m * This method parses a munged URL such as: * * http://jpw.creare.com:80/RBNB/TestSource?r=newest&t=1.5 * * In this case: * "http" is the protocol * "jpw.creare.com:80/RBNB/TestSource" is the request * "newest" is the reference * "1.5" is the time * * @author John P. Wilson * * @param urlStrI The URL to parse. * @param bDebugI Print debug? * * @version 09/15/2006 */ /* * * Date By Description * MM/DD/YYYY * ---------- -- ----------- * 09/15/2006 JPW Switch over to using KeyValueHash to parse the munge * 05/10/2006 JPW Created * */ public void parse(String urlStrI, boolean bDebugI) { // Reset all member variables resetMemberData(); if ((urlStrI == null) || (urlStrI.trim().equals(""))) { if (bDebugI) { System.err.println("Unable to parse URL: empty string"); } return; } url = new String(urlStrI); if (bDebugI) { System.err.println("URL = \"" + urlStrI + "\""); } //////////////////////////////////////////// // See if a protocol is specified in the URL //////////////////////////////////////////// int colonIndex = urlStrI.indexOf(':'); String requestAndMungeStr = urlStrI; if (colonIndex >= 0) { protocol = urlStrI.substring(0, colonIndex); if ((protocol != null) && (protocol.trim().equals(""))) { protocol = null; } if ((protocol != null) && (bDebugI)) { System.err.println("Protocol = \"" + protocol + "\""); } else if (bDebugI) { System.err.println("Protocol = null"); } requestAndMungeStr = urlStrI.substring(colonIndex + 1); } //////////////////////////////////////////////// // Strip off leading '/' from requestAndMungeStr //////////////////////////////////////////////// while ((requestAndMungeStr != null) && (!requestAndMungeStr.equals("")) && (requestAndMungeStr.charAt(0) == '/')) { requestAndMungeStr = requestAndMungeStr.substring(1); } /////////////////////////////////////////////////////////// // Separate the request from the munge; munge portion could // begin with either '?' or '@' /////////////////////////////////////////////////////////// request = null; munge = null; int mungeStartCharIndex = requestAndMungeStr.indexOf('@'); if (mungeStartCharIndex < 0) { mungeStartCharIndex = requestAndMungeStr.indexOf('?'); } if (mungeStartCharIndex >= 0) { request = requestAndMungeStr.substring(0, mungeStartCharIndex); if ((request != null) && (request.trim().equals(""))) { request = null; } munge = requestAndMungeStr.substring(mungeStartCharIndex + 1); if ((munge != null) && (munge.trim().equals(""))) { munge = null; } } else { //EMF 5/11/06: no munge, all request request = requestAndMungeStr; munge = null; } if (bDebugI) { if (request == null) { System.err.println("Request = null"); } else { System.err.println("Request = \"" + request + "\""); } if (munge == null) { System.err.println("Munge = null"); } else { System.err.println("Munge = \"" + munge + "\""); } } ////////////////////////// // Parse the munge options ////////////////////////// if (munge == null) { // We're all done return; } // JPW 09/15/2006: Use KeyValueHash to parse the munge char[] terminatorChars = { '&' }; KeyValueHash kvh = new KeyValueHash(munge, terminatorChars); Hashtable fullHashtable = kvh.getHash(); if (kvh.get("time") != null) { // Store time as a Double object try { time = new Double(kvh.get("time")); if (bDebugI) { System.err.println("time = " + time); } hasRBNBMunge = true; } catch (NumberFormatException e) { // Nothing to do time = null; } // Remove this entry from the hashtable fullHashtable.remove("time"); } if (kvh.get("t") != null) { // Store time as a Double object try { time = new Double(kvh.get("t")); if (bDebugI) { System.err.println("time = " + time); } hasRBNBMunge = true; } catch (NumberFormatException e) { // Nothing to do time = null; } // Remove this entry from the hashtable fullHashtable.remove("t"); } if (kvh.get("duration") != null) { // Store duration as a Double object try { duration = new Double(kvh.get("duration")); if (bDebugI) { System.err.println("duration = " + duration); } hasRBNBMunge = true; } catch (NumberFormatException e) { // Nothing to do duration = null; } // Remove this entry from the hashtable fullHashtable.remove("duration"); } if (kvh.get("d") != null) { // Store duration as a Double object try { duration = new Double(kvh.get("d")); if (bDebugI) { System.err.println("duration = " + duration); } hasRBNBMunge = true; } catch (NumberFormatException e) { // Nothing to do duration = null; } // Remove this entry from the hashtable fullHashtable.remove("d"); } if (kvh.get("reference") != null) { reference = kvh.get("reference"); if (bDebugI) { System.err.println("reference = " + reference); } hasRBNBMunge = true; // Remove this entry from the hashtable fullHashtable.remove("reference"); } if (kvh.get("r") != null) { reference = kvh.get("r"); if (bDebugI) { System.err.println("reference = " + reference); } hasRBNBMunge = true; // Remove this entry from the hashtable fullHashtable.remove("r"); } if (kvh.get("fetch") != null) { fetch = kvh.get("fetch"); if (bDebugI) { System.err.println("fetch = " + fetch); } hasRBNBMunge = true; // Remove this entry from the hashtable fullHashtable.remove("fetch"); } if (kvh.get("f") != null) { fetch = kvh.get("f"); if (bDebugI) { System.err.println("fetch = " + fetch); } hasRBNBMunge = true; // Remove this entry from the hashtable fullHashtable.remove("f"); } if (kvh.get("byteorder") != null) { byteorder = kvh.get("byteorder"); if (bDebugI) { System.err.println("byteorder = " + byteorder); } hasRBNBMunge = true; // Remove this entry from the hashtable fullHashtable.remove("byteorder"); } if (kvh.get("bo") != null) { byteorder = kvh.get("bo"); if (bDebugI) { System.err.println("byteorder = " + byteorder); } hasRBNBMunge = true; // Remove this entry from the hashtable fullHashtable.remove("bo"); } if (kvh.get("datatype") != null) { datatype = kvh.get("datatype"); if (bDebugI) { System.err.println("datatype = " + datatype); } hasRBNBMunge = true; // Remove this entry from the hashtable fullHashtable.remove("datatype"); } if (kvh.get("dt") != null) { datatype = kvh.get("dt"); if (bDebugI) { System.err.println("datatype = " + datatype); } hasRBNBMunge = true; // Remove this entry from the hashtable fullHashtable.remove("dt"); } if (kvh.get("mux") != null) { // Store mux as an Integer object try { mux = new Integer(kvh.get("mux")); if (bDebugI) { System.err.println("mux = " + mux); } hasRBNBMunge = true; } catch (NumberFormatException e) { // Nothing to do mux = null; } // Remove this entry from the hashtable fullHashtable.remove("mux"); } if (kvh.get("x") != null) { // Store mux as an Integer object try { mux = new Integer(kvh.get("x")); if (bDebugI) { System.err.println("mux = " + mux); } hasRBNBMunge = true; } catch (NumberFormatException e) { // Nothing to do mux = null; } // Remove this entry from the hashtable fullHashtable.remove("x"); } if (kvh.get("blocksize") != null) { // Store blocksize as an Integer object try { blocksize = new Integer(kvh.get("blocksize")); if (bDebugI) { System.err.println("blocksize = " + blocksize); } hasRBNBMunge = true; } catch (NumberFormatException e) { // Nothing to do blocksize = null; } // Remove this entry from the hashtable fullHashtable.remove("blocksize"); } if (kvh.get("bs") != null) { // Store blocksize as an Integer object try { blocksize = new Integer(kvh.get("bs")); if (bDebugI) { System.err.println("blocksize = " + blocksize); } hasRBNBMunge = true; } catch (NumberFormatException e) { // Nothing to do blocksize = null; } // Remove this entry from the hashtable fullHashtable.remove("bs"); } if (kvh.get("mime") != null) { mime = kvh.get("mime"); if (bDebugI) { System.err.println("mime = " + mime); } hasRBNBMunge = true; // Remove this entry from the hashtable fullHashtable.remove("mime"); } if (kvh.get("m") != null) { mime = kvh.get("m"); if (bDebugI) { System.err.println("mime = " + mime); } hasRBNBMunge = true; // Remove this entry from the hashtable fullHashtable.remove("m"); } // What remains in fullHashtable must be the non-RBNB munges if ((fullHashtable != null) && (!fullHashtable.isEmpty())) { nonRBNBMunge = fullHashtable; if (bDebugI) { for (Enumeration e = nonRBNBMunge.keys(); e.hasMoreElements();) { String key = (String) e.nextElement(); String value = (String) nonRBNBMunge.get(key); System.err.println("Non-RBNB munge: key = \"" + key + "\", value = \"" + value + "\""); } } } }
From source file:org.unitime.timetable.solver.TimetableDatabaseLoader.java
private void load(org.hibernate.Session hibSession) throws Exception { iProgress.setStatus("Loading input data ..."); TravelTime.populateTravelTimes(getModel().getDistanceMetric(), iSessionId, hibSession); iSolverGroup = null;/*from ww w. j ava 2 s.com*/ iSession = null; if (iSolverGroup == null) { iSolverGroup = new SolverGroup[iSolverGroupId.length]; for (int i = 0; i < iSolverGroupId.length; i++) { iSolverGroup[i] = SolverGroupDAO.getInstance().get(iSolverGroupId[i], hibSession); if (iSolverGroup[i] == null) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "Unable to load solver group " + iSolverGroupId[i] + "."); return; } iProgress.debug("solver group[" + (i + 1) + "]: " + iSolverGroup[i].getName()); } } if (iSolverGroup == null || iSolverGroup.length == 0) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "No solver group loaded."); return; } iDepartmentIds = ""; for (int j = 0; j < iSolverGroup.length; j++) { for (Iterator i = iSolverGroup[j].getDepartments().iterator(); i.hasNext();) { Department d = (Department) i.next(); if (iDepartmentIds.length() > 0) iDepartmentIds += ","; iDepartmentIds += d.getUniqueId().toString(); } } getModel().getProperties().setProperty("General.DepartmentIds", iDepartmentIds); Hashtable<Long, Solution> solutions = null; if (iSolutionId != null && iSolutionId.length > 0) { solutions = new Hashtable<Long, Solution>(); String note = ""; for (int i = 0; i < iSolutionId.length; i++) { Solution solution = (new SolutionDAO()).get(iSolutionId[i], hibSession); if (solution == null) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "Unable to load solution " + iSolutionId[i] + "."); return; } iProgress.debug("solution[" + (i + 1) + "] version: " + solution.getUniqueId() + " (created " + solution.getCreated() + ", solver group " + solution.getOwner().getName() + ")"); if (solution.getNote() != null) { if (note.length() > 0) note += "\n"; note += solution.getNote(); } solutions.put(solution.getOwner().getUniqueId(), solution); } getModel().getProperties().setProperty("General.Note", note); String solutionIdStr = ""; for (int i = 0; i < iSolverGroupId.length; i++) { Solution solution = solutions.get(iSolverGroupId[i]); if (solution != null) { if (solutionIdStr.length() > 0) solutionIdStr += ","; solutionIdStr += solution.getUniqueId().toString(); } } getModel().getProperties().setProperty("General.SolutionId", solutionIdStr); } if (iSession == null) iSession = (new SessionDAO()).get(iSessionId, hibSession); if (iSession == null) { iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "No session loaded."); return; } iProgress.debug("session: " + iSession.getLabel()); getModel().getProperties().setProperty("Data.Term", iSession.getAcademicYearTerm()); getModel().getProperties().setProperty("Data.Initiative", iSession.getAcademicInitiative()); getModel().setYear(iSession.getSessionStartYear()); getModel().getProperties().setProperty("DatePattern.DayOfWeekOffset", String.valueOf(Constants.getDayOfWeek( DateUtils.getDate(1, iSession.getPatternStartMonth(), iSession.getSessionStartYear())))); if (iSession.getDefaultDatePattern() != null) { BitSet pattern = iSession.getDefaultDatePattern().getPatternBitSet(); String patternStr = ""; for (int i = 0; i < pattern.length(); i++) patternStr += (pattern.get(i) ? "1" : "0"); getModel().getProperties().setProperty("DatePattern.Default", patternStr); } iAllClasses = new TreeSet(new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY)); for (int i = 0; i < iSolverGroup.length; i++) { for (Iterator j = iSolverGroup[i].getDepartments().iterator(); j.hasNext();) { Department d = (Department) j.next(); iAllClasses.addAll(d.getClassesFetchWithStructure()); } } if (iAllClasses == null || iAllClasses.isEmpty()) { iProgress.message(msglevel("noClasses", Progress.MSGLEVEL_FATAL), "No classes to load."); return; } iProgress.debug("classes to load: " + iAllClasses.size()); iProgress.setPhase("Loading classes ...", iAllClasses.size()); int ord = 0; HashSet<SchedulingSubpart> subparts = new HashSet<SchedulingSubpart>(); for (Iterator i1 = iAllClasses.iterator(); i1.hasNext();) { Class_ clazz = (Class_) i1.next(); Lecture lecture = loadClass(clazz, hibSession); subparts.add(clazz.getSchedulingSubpart()); if (lecture != null) lecture.setOrd(ord++); iClasses.put(clazz.getUniqueId(), clazz); iProgress.incProgress(); } loadInstructorAvailabilities(hibSession); loadRoomAvailabilities(hibSession); iProgress.setPhase("Loading offerings ...", iAllClasses.size()); Set<Long> loadedOfferings = new HashSet<Long>(); for (Class_ clazz : iAllClasses) { Lecture lecture = (Lecture) iLectures.get(clazz.getUniqueId()); iProgress.incProgress(); if (lecture == null) continue; //skip classes that were not loaded InstructionalOffering offering = clazz.getSchedulingSubpart().getInstrOfferingConfig() .getInstructionalOffering(); if (!loadedOfferings.add(offering.getUniqueId())) continue; // already loaded iOfferings.put(offering, loadOffering(offering, false)); } List<DistributionPref> distPrefs = new ArrayList<DistributionPref>(); for (int i = 0; i < iSolverGroup.length; i++) { distPrefs.addAll(iSolverGroup[i].getDistributionPreferences()); } iProgress.setPhase("Loading distribution preferences ...", distPrefs.size()); for (Iterator i = distPrefs.iterator(); i.hasNext();) { DistributionPref distributionPref = (DistributionPref) i.next(); if (!PreferenceLevel.sNeutral.equals(distributionPref.getPrefLevel().getPrefProlog())) loadGroupConstraint(distributionPref); iProgress.incProgress(); } Set<Long> checkedDistPrefIds = new HashSet<Long>(); for (int i = 0; i < iSolverGroup.length; i++) { for (Iterator j = iSolverGroup[i].getDepartments().iterator(); j.hasNext();) { loadInstructorGroupConstraints((Department) j.next(), checkedDistPrefIds, hibSession); } } if (iAutoSameStudents) { iProgress.setPhase("Posting automatic same_students constraints ...", iAllClasses.size()); for (Iterator i1 = iAllClasses.iterator(); i1.hasNext();) { Class_ clazz = (Class_) i1.next(); Lecture lecture = (Lecture) iLectures.get(clazz.getUniqueId()); if (lecture == null) continue; if (!lecture.hasAnyChildren()) postSameStudentConstraint(clazz, iAutoSameStudentsConstraint); iProgress.incProgress(); } } if (iAutoPrecedence != null) { PreferenceLevel pref = PreferenceLevel.getPreferenceLevel(iAutoPrecedence); if (pref == null) { // Lookup preference if needed for (PreferenceLevel p : PreferenceLevel.getPreferenceLevelList()) if (iAutoPrecedence.equalsIgnoreCase(p.getPrefProlog()) || iAutoPrecedence.equalsIgnoreCase(p.getPrefName()) || iAutoPrecedence.equals(p.getAbbreviation())) { pref = p; break; } } if (pref == null) { iProgress.message(msglevel("autoPrecedence", Progress.MSGLEVEL_WARN), "Preference " + iAutoPrecedence + " not recognized."); } else if (!PreferenceLevel.sNeutral.equals(pref.getPrefProlog())) { iProgress.setPhase("Posting automatic precedence constraints ...", iAllClasses.size()); for (Iterator i1 = iAllClasses.iterator(); i1.hasNext();) { Class_ clazz = (Class_) i1.next(); Lecture lecture = (Lecture) iLectures.get(clazz.getUniqueId()); if (lecture == null) continue; if (!lecture.hasAnyChildren()) postPrecedenceConstraint(clazz, pref.getPrefProlog()); iProgress.incProgress(); } } } postAutomaticHierarchicalConstraints(); assignCommited(); iProgress.setPhase("Posting class limit constraints ...", iOfferings.size()); for (Map.Entry<InstructionalOffering, Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>>> entry : iOfferings .entrySet()) { Hashtable<InstrOfferingConfig, Set<SchedulingSubpart>> topSubparts = entry.getValue(); for (Map.Entry<InstrOfferingConfig, Set<SchedulingSubpart>> subpartEntry : topSubparts.entrySet()) { InstrOfferingConfig config = subpartEntry.getKey(); Set<SchedulingSubpart> topSubpartsThisConfig = subpartEntry.getValue(); for (SchedulingSubpart subpart : topSubpartsThisConfig) { boolean isMakingSense = false; for (Class_ clazz : subpart.getClasses()) { Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture == null) continue; createChildrenClassLimitConstraits(lecture); if (!lecture.isCommitted() && lecture.minClassLimit() != lecture.maxClassLimit()) isMakingSense = true; } if (!isMakingSense) continue; if (subpart.getParentSubpart() == null) { ClassLimitConstraint clc = new ClassLimitConstraint(config.getLimit(), getClassLimitConstraitName(subpart)); for (Class_ clazz : subpart.getClasses()) { Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture == null || lecture.isCommitted()) { clc.setClassLimitDelta(clc.getClassLimitDelta() - clazz.getClassLimit()); continue; } clc.addVariable(lecture); } if (clc.variables().isEmpty()) continue; iProgress.trace("Added constraint " + clc.getName() + " between " + clc.variables()); getModel().addConstraint(clc); } else { Hashtable<Long, ClassLimitConstraint> clcs = new Hashtable<Long, ClassLimitConstraint>(); for (Class_ clazz : subpart.getClasses()) { Lecture lecture = iLectures.get(clazz.getUniqueId()); Class_ parentClazz = clazz.getParentClass(); ClassLimitConstraint clc = clcs.get(parentClazz.getUniqueId()); if (clc == null) { clc = new ClassLimitConstraint(parentClazz.getClassLimit(), parentClazz.getClassLabel()); clcs.put(parentClazz.getUniqueId(), clc); } if (lecture == null || lecture.isCommitted()) { clc.setClassLimitDelta(clc.getClassLimitDelta() - clazz.getClassLimit()); } else { clc.addVariable(lecture); } } for (ClassLimitConstraint clc : clcs.values()) { if (!clc.variables().isEmpty()) { iProgress .trace("Added constraint " + clc.getName() + " between " + clc.variables()); getModel().addConstraint(clc); } } } } } iProgress.incProgress(); } iStudentCourseDemands.init(hibSession, iProgress, iSession, iOfferings.keySet()); iProgress.setPhase("Loading students ...", iOfferings.size()); for (InstructionalOffering offering : iOfferings.keySet()) { boolean unlimitedOffering = false; int offeringLimit = 0; for (InstrOfferingConfig config : offering.getInstrOfferingConfigs()) if (config.isUnlimitedEnrollment()) unlimitedOffering = true; else offeringLimit += config.getLimit(); Double factor = null; if (!unlimitedOffering) { int totalCourseLimit = 0; for (CourseOffering course : offering.getCourseOfferings()) { int courseLimit = -1; if (course.getReservation() != null) courseLimit = course.getReservation(); if (courseLimit < 0) { if (offering.getCourseOfferings().size() == 1) courseLimit = offeringLimit; else { iProgress.message(msglevel("crossListWithoutReservation", Progress.MSGLEVEL_INFO), "Cross-listed course " + getOfferingLabel(course) + " does not have any course reservation."); if (course.getProjectedDemand() != null && offering.getProjectedDemand() > 0) courseLimit = course.getProjectedDemand(); else if (course.getDemand() != null && offering.getDemand() > 0) courseLimit = course.getDemand(); else courseLimit = offeringLimit / offering.getCourseOfferings().size(); } } totalCourseLimit += courseLimit; } if (totalCourseLimit < offeringLimit) iProgress.message( msglevel("courseReservationsBelowLimit", totalCourseLimit == 0 ? Progress.MSGLEVEL_INFO : Progress.MSGLEVEL_WARN), "Total number of course reservations is below the offering limit for instructional offering " + getOfferingLabel(offering) + " (" + totalCourseLimit + "<" + offeringLimit + ")."); if (totalCourseLimit > offeringLimit) iProgress.message(msglevel("courseReservationsOverLimit", Progress.MSGLEVEL_INFO), "Total number of course reservations exceeds the offering limit for instructional offering " + getOfferingLabel(offering) + " (" + totalCourseLimit + ">" + offeringLimit + ")."); if (totalCourseLimit == 0) continue; if (totalCourseLimit != offeringLimit) factor = new Double(((double) offeringLimit) / totalCourseLimit); } for (CourseOffering course : offering.getCourseOfferings()) { Set<WeightedStudentId> studentIds = iStudentCourseDemands.getDemands(course); float studentWeight = 0.0f; if (studentIds != null) for (WeightedStudentId studentId : studentIds) studentWeight += studentId.getWeight(); int courseLimit = -1; if (course.getReservation() != null) courseLimit = course.getReservation(); if (courseLimit < 0) { if (offering.getCourseOfferings().size() == 1 && !unlimitedOffering) courseLimit = offeringLimit; else { courseLimit = Math.round(studentWeight); } } if (factor != null) courseLimit = (int) Math.round(courseLimit * factor); if (studentIds == null || studentIds.isEmpty()) { iProgress.message(msglevel("offeringWithoutDemand", Progress.MSGLEVEL_INFO), "No student enrollments for course " + getOfferingLabel(course) + "."); continue; } if (courseLimit == 0 && offering.getCourseOfferings().size() > 1) { iProgress.message(msglevel("noCourseReservation", Progress.MSGLEVEL_WARN), "No reserved space for students of course " + getOfferingLabel(course) + "."); } double weight = (iStudentCourseDemands.isWeightStudentsToFillUpOffering() && courseLimit != 0 ? (double) courseLimit / studentWeight : 1.0); Set<Lecture> cannotAttendLectures = null; if (offering.getCourseOfferings().size() > 1) { Set<Long> reservedClasses = new HashSet<Long>(); int limit = 0; boolean unlimited = false; for (Reservation r : offering.getReservations()) { if (r instanceof CourseReservation && course.equals(((CourseReservation) r).getCourse())) { for (Class_ clazz : r.getClasses()) { limit += clazz.getMaxExpectedCapacity(); propagateReservedClasses(clazz, reservedClasses); Class_ parent = clazz.getParentClass(); while (parent != null) { reservedClasses.add(parent.getUniqueId()); parent = parent.getParentClass(); } } for (InstrOfferingConfig config : r.getConfigurations()) { if (config.isUnlimitedEnrollment()) unlimited = true; else limit += config.getLimit(); for (SchedulingSubpart subpart : config.getSchedulingSubparts()) for (Class_ clazz : subpart.getClasses()) reservedClasses.add(clazz.getUniqueId()); } } } if (!reservedClasses.isEmpty()) { iProgress.debug("Course requests for course " + getOfferingLabel(course) + " are " + reservedClasses); if (!unlimited && courseLimit > limit) iProgress.message(msglevel("insufficientCourseReservation", Progress.MSGLEVEL_WARN), "Too little space reserved in for course " + getOfferingLabel(course) + " (" + limit + "<" + courseLimit + ")."); cannotAttendLectures = new HashSet<Lecture>(); for (InstrOfferingConfig config : course.getInstructionalOffering() .getInstrOfferingConfigs()) { boolean hasConfigReservation = false; subparts: for (SchedulingSubpart subpart : config.getSchedulingSubparts()) for (Class_ clazz : subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasConfigReservation = true; break subparts; } for (SchedulingSubpart subpart : config.getSchedulingSubparts()) { boolean hasSubpartReservation = false; for (Class_ clazz : subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasSubpartReservation = true; break; } // !hasConfigReservation >> all lectures are cannot attend (there is a reservation on a different config) // otherwise if !hasSubpartReservation >> there is reservation on some other subpoart --> can attend any of the classes of this subpart if (!hasConfigReservation || hasSubpartReservation) for (Class_ clazz : subpart.getClasses()) { if (reservedClasses.contains(clazz.getUniqueId())) continue; Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture != null && !lecture.isCommitted()) cannotAttendLectures.add(lecture); } } } if (!cannotAttendLectures.isEmpty()) { iProgress.debug("Prohibited lectures for course " + getOfferingLabel(course) + " are " + cannotAttendLectures); checkReservation(course, cannotAttendLectures, iAltConfigurations.get(offering)); } } } for (WeightedStudentId studentId : studentIds) { Student student = iStudents.get(studentId.getStudentId()); if (student == null) { student = new Student(studentId.getStudentId()); student.setAcademicArea(studentId.getArea()); student.setAcademicClassification(studentId.getClasf()); student.setMajor(studentId.getMajor()); student.setCurriculum(studentId.getCurriculum()); getModel().addStudent(student); iStudents.put(studentId.getStudentId(), student); } student.addOffering(offering.getUniqueId(), weight * studentId.getWeight(), iStudentCourseDemands.getEnrollmentPriority(studentId.getStudentId(), course.getUniqueId())); Set<Student> students = iCourse2students.get(course); if (students == null) { students = new HashSet<Student>(); iCourse2students.put(course, students); } students.add(student); student.addCanNotEnroll(offering.getUniqueId(), cannotAttendLectures); Set<Long> reservedClasses = new HashSet<Long>(); for (Reservation reservation : offering.getReservations()) { if (reservation.getClasses().isEmpty() && reservation.getConfigurations().isEmpty()) continue; if (reservation instanceof CourseReservation) continue; if (reservation instanceof CurriculumReservation) { CurriculumReservation cr = (CurriculumReservation) reservation; if (studentId.getArea() == null) continue; if (!studentId.hasArea(cr.getArea().getAcademicAreaAbbreviation())) continue; if (!cr.getClassifications().isEmpty()) { boolean match = false; for (AcademicClassification clasf : cr.getClassifications()) { if (studentId.hasClassification(cr.getArea().getAcademicAreaAbbreviation(), clasf.getCode())) { match = true; break; } } if (!match) continue; } if (!cr.getMajors().isEmpty()) { if (studentId.getMajor() == null) continue; boolean match = false; for (PosMajor major : cr.getMajors()) { if (studentId.hasMajor(cr.getArea().getAcademicAreaAbbreviation(), major.getCode())) { match = true; break; } } if (!match) continue; } } else continue; for (Class_ clazz : reservation.getClasses()) { propagateReservedClasses(clazz, reservedClasses); Class_ parent = clazz.getParentClass(); while (parent != null) { reservedClasses.add(parent.getUniqueId()); parent = parent.getParentClass(); } } for (InstrOfferingConfig config : reservation.getConfigurations()) { for (SchedulingSubpart subpart : config.getSchedulingSubparts()) for (Class_ clazz : subpart.getClasses()) reservedClasses.add(clazz.getUniqueId()); } } if (!reservedClasses.isEmpty()) { iProgress.debug(course.getCourseName() + ": Student " + student.getId() + " has reserved classes " + reservedClasses); Set<Lecture> prohibited = new HashSet<Lecture>(); for (InstrOfferingConfig config : course.getInstructionalOffering() .getInstrOfferingConfigs()) { boolean hasConfigReservation = false; subparts: for (SchedulingSubpart subpart : config.getSchedulingSubparts()) for (Class_ clazz : subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasConfigReservation = true; break subparts; } for (SchedulingSubpart subpart : config.getSchedulingSubparts()) { boolean hasSubpartReservation = false; for (Class_ clazz : subpart.getClasses()) if (reservedClasses.contains(clazz.getUniqueId())) { hasSubpartReservation = true; break; } // !hasConfigReservation >> all lectures are cannot attend (there is a reservation on a different config) // otherwise if !hasSubpartReservation >> there is reservation on some other subpoart --> can attend any of the classes of this subpart if (!hasConfigReservation || hasSubpartReservation) for (Class_ clazz : subpart.getClasses()) { if (reservedClasses.contains(clazz.getUniqueId())) continue; Lecture lecture = iLectures.get(clazz.getUniqueId()); if (lecture != null && !lecture.isCommitted()) prohibited.add(lecture); } } } iProgress.debug(course.getCourseName() + ": Student " + student.getId() + " cannot attend classes " + prohibited); student.addCanNotEnroll(offering.getUniqueId(), prohibited); } } } iProgress.incProgress(); } iProgress.debug(iStudents.size() + " students loaded."); if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (iCommittedStudentConflictsMode == CommittedStudentConflictsMode.Load && !iStudentCourseDemands.isMakingUpStudents()) loadCommittedStudentConflicts(hibSession, loadedOfferings); else if (iCommittedStudentConflictsMode != CommittedStudentConflictsMode.Ignore) makeupCommittedStudentConflicts(loadedOfferings); if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); Hashtable<Student, Set<Lecture>> iPreEnrollments = new Hashtable<Student, Set<Lecture>>(); if (iLoadStudentEnrlsFromSolution) { if (iStudentCourseDemands.canUseStudentClassEnrollmentsAsSolution()) { // Load real student enrollments (not saved last-like) List<Object[]> enrollments = (List<Object[]>) hibSession .createQuery("select distinct e.student.uniqueId, e.clazz.uniqueId from " + "StudentClassEnrollment e, Class_ c where " + "e.courseOffering.instructionalOffering = c.schedulingSubpart.instrOfferingConfig.instructionalOffering and " + "c.managingDept.solverGroup.uniqueId in (" + iSolverGroupIds + ")") .list(); iProgress.setPhase("Loading current student enrolments ...", enrollments.size()); int totalEnrollments = 0; for (Object[] o : enrollments) { Long studentId = (Long) o[0]; Long clazzId = (Long) o[1]; Student student = (Student) iStudents.get(studentId); if (student == null) continue; Lecture lecture = (Lecture) iLectures.get(clazzId); if (lecture != null) { Set<Lecture> preEnrollments = iPreEnrollments.get(student); if (preEnrollments == null) { preEnrollments = new HashSet<Lecture>(); iPreEnrollments.put(student, preEnrollments); } preEnrollments.add(lecture); if (student.hasOffering(lecture.getConfiguration().getOfferingId()) && student.canEnroll(lecture)) { student.addLecture(lecture); lecture.addStudent(getAssignment(), student); totalEnrollments++; } } iProgress.incProgress(); } iProgress.message(msglevel("enrollmentsLoaded", Progress.MSGLEVEL_INFO), "Loaded " + totalEnrollments + " enrollments of " + iPreEnrollments.size() + " students."); } else { // Load enrollments from selected / committed solutions for (int idx = 0; idx < iSolverGroupId.length; idx++) { Solution solution = (solutions == null ? null : solutions.get(iSolverGroupId[idx])); List studentEnrls = null; if (solution != null) { studentEnrls = hibSession.createQuery( "select distinct e.studentId, e.clazz.uniqueId from StudentEnrollment e where e.solution.uniqueId=:solutionId") .setLong("solutionId", solution.getUniqueId()).list(); } else { studentEnrls = hibSession.createQuery( "select distinct e.studentId, e.clazz.uniqueId from StudentEnrollment e where e.solution.owner.uniqueId=:sovlerGroupId and e.solution.commited = true") .setLong("sovlerGroupId", iSolverGroupId[idx]).list(); } iProgress.setPhase("Loading student enrolments [" + (idx + 1) + "] ...", studentEnrls.size()); for (Iterator i1 = studentEnrls.iterator(); i1.hasNext();) { Object o[] = (Object[]) i1.next(); Long studentId = (Long) o[0]; Long clazzId = (Long) o[1]; Student student = (Student) iStudents.get(studentId); if (student == null) continue; Lecture lecture = (Lecture) iLectures.get(clazzId); if (lecture != null && lecture.getConfiguration() != null) { Set<Lecture> preEnrollments = iPreEnrollments.get(student); if (preEnrollments == null) { preEnrollments = new HashSet<Lecture>(); iPreEnrollments.put(student, preEnrollments); } preEnrollments.add(lecture); if (student.hasOffering(lecture.getConfiguration().getOfferingId()) && student.canEnroll(lecture)) { student.addLecture(lecture); lecture.addStudent(getAssignment(), student); } } iProgress.incProgress(); } } if (getModel().getProperties().getPropertyBoolean("Global.LoadOtherCommittedStudentEnrls", true)) { // Other committed enrollments List<Object[]> enrollments = (List<Object[]>) hibSession .createQuery("select distinct e.studentId, e.clazz.uniqueId from " + "StudentEnrollment e, Class_ c where " + "e.solution.commited = true and e.solution.owner.uniqueId not in (" + iSolverGroupIds + ") and " + "e.clazz.schedulingSubpart.instrOfferingConfig.instructionalOffering = c.schedulingSubpart.instrOfferingConfig.instructionalOffering and " + "c.managingDept.solverGroup.uniqueId in (" + iSolverGroupIds + ")") .list(); iProgress.setPhase("Loading other committed student enrolments ...", enrollments.size()); for (Object[] o : enrollments) { Long studentId = (Long) o[0]; Long clazzId = (Long) o[1]; Student student = (Student) iStudents.get(studentId); if (student == null) continue; Lecture lecture = (Lecture) iLectures.get(clazzId); if (lecture != null && lecture.getConfiguration() != null) { Set<Lecture> preEnrollments = iPreEnrollments.get(student); if (preEnrollments == null) { preEnrollments = new HashSet<Lecture>(); iPreEnrollments.put(student, preEnrollments); } preEnrollments.add(lecture); if (student.hasOffering(lecture.getConfiguration().getOfferingId()) && student.canEnroll(lecture)) { student.addLecture(lecture); lecture.addStudent(getAssignment(), student); } } iProgress.incProgress(); } } } } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); RoomAvailabilityInterface availability = null; if (SolverServerImplementation.getInstance() != null) availability = SolverServerImplementation.getInstance().getRoomAvailability(); else availability = RoomAvailability.getInstance(); if (availability != null) { Date[] startEnd = initializeRoomAvailability(availability); if (startEnd != null) { loadRoomAvailability(availability, startEnd); loadInstructorAvailability(availability, startEnd); } } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); iProgress.setPhase("Initial sectioning ...", iOfferings.size()); for (InstructionalOffering offering : iOfferings.keySet()) { Set<Student> students = new HashSet<Student>(); for (CourseOffering course : offering.getCourseOfferings()) { Set<Student> courseStudents = iCourse2students.get(course); if (courseStudents != null) students.addAll(courseStudents); } if (students.isEmpty()) continue; getModel().getStudentSectioning().initialSectioning(getAssignment(), offering.getUniqueId(), offering.getCourseName(), students, iAltConfigurations.get(offering)); iProgress.incProgress(); } for (Enumeration e = iStudents.elements(); e.hasMoreElements();) { ((Student) e.nextElement()).clearDistanceCache(); } if (!iPreEnrollments.isEmpty()) { iProgress.setPhase("Checking loaded enrollments ....", iPreEnrollments.size()); for (Map.Entry<Student, Set<Lecture>> entry : iPreEnrollments.entrySet()) { iProgress.incProgress(); Student student = entry.getKey(); Set<Lecture> lectures = entry.getValue(); for (Lecture lecture : lectures) { if (!lecture.students().contains(student)) { iProgress.message(msglevel("studentNotEnrolled", Progress.MSGLEVEL_WARN), "Student " + student.getId() + " is supposed to be enrolled to " + getClassLabel(lecture)); } } for (Lecture lecture : student.getLectures()) { if (!lectures.contains(lecture)) { Lecture instead = null; if (lecture.sameStudentsLectures() != null) { for (Lecture other : lecture.sameStudentsLectures()) { if (lectures.contains(other)) instead = other; } } if (instead != null) iProgress.message(msglevel("studentEnrolled", Progress.MSGLEVEL_WARN), "Student " + student.getId() + " is NOT supposed to be enrolled to " + getClassLabel(lecture) + ", he/she should have " + getClassLabel(instead) + " instead."); else iProgress.message(msglevel("studentEnrolled", Progress.MSGLEVEL_INFO), "Student " + student.getId() + " is NOT supposed to be enrolled to " + getClassLabel(lecture) + "."); } } } } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (iLoadStudentInstructorConflicts) loadInstructorStudentConflicts(hibSession); iProgress.setPhase("Computing jenrl ...", iStudents.size()); Hashtable jenrls = new Hashtable(); for (Iterator i1 = iStudents.values().iterator(); i1.hasNext();) { Student st = (Student) i1.next(); for (Iterator i2 = st.getLectures().iterator(); i2.hasNext();) { Lecture l1 = (Lecture) i2.next(); for (Iterator i3 = st.getLectures().iterator(); i3.hasNext();) { Lecture l2 = (Lecture) i3.next(); if (l1.getId() >= l2.getId()) continue; Hashtable x = (Hashtable) jenrls.get(l1); if (x == null) { x = new Hashtable(); jenrls.put(l1, x); } JenrlConstraint jenrl = (JenrlConstraint) x.get(l2); if (jenrl == null) { jenrl = new JenrlConstraint(); getModel().addConstraint(jenrl); jenrl.addVariable(l1); jenrl.addVariable(l2); x.put(l2, jenrl); } jenrl.incJenrl(getAssignment(), st); } } iProgress.incProgress(); } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (solutions != null) { for (int idx = 0; idx < iSolverGroupId.length; idx++) { Solution solution = (Solution) solutions.get(iSolverGroupId[idx]); if (solution == null) continue; iProgress.setPhase("Creating initial assignment [" + (idx + 1) + "] ...", solution.getAssignments().size()); for (Iterator i1 = solution.getAssignments().iterator(); i1.hasNext();) { Assignment assignment = (Assignment) i1.next(); loadAssignment(assignment); iProgress.incProgress(); } } } else if (iLoadCommittedAssignments) { iProgress.setPhase("Creating initial assignment ...", getModel().variables().size()); for (Lecture lecture : getModel().variables()) { if (lecture.isCommitted()) continue; Class_ clazz = iClasses.get(lecture.getClassId()); if (clazz != null && clazz.getCommittedAssignment() != null) loadAssignment(clazz.getCommittedAssignment()); iProgress.incProgress(); } } if (!hibSession.isOpen()) iProgress.message(msglevel("hibernateFailure", Progress.MSGLEVEL_FATAL), "Hibernate session not open."); if (iSpread) { iProgress.setPhase("Posting automatic spread constraints ...", subparts.size()); for (SchedulingSubpart subpart : subparts) { if (subpart.getClasses().size() <= 1) { iProgress.incProgress(); continue; } if (!subpart.isAutoSpreadInTime().booleanValue()) { iProgress.debug("Automatic spread constraint disabled for " + getSubpartLabel(subpart)); iProgress.incProgress(); continue; } SpreadConstraint spread = new SpreadConstraint(getModel().getProperties(), subpart.getCourseName() + " " + subpart.getItypeDesc().trim()); for (Iterator i2 = subpart.getClasses().iterator(); i2.hasNext();) { Class_ clazz = (Class_) i2.next(); Lecture lecture = (Lecture) getLecture(clazz); if (lecture == null) continue; spread.addVariable(lecture); } if (spread.variables().isEmpty()) iProgress.message(msglevel("courseWithNoClasses", Progress.MSGLEVEL_WARN), "No class for course " + getSubpartLabel(subpart)); else getModel().addConstraint(spread); iProgress.incProgress(); } } if (iDeptBalancing) { iProgress.setPhase("Creating dept. spread constraints ...", getModel().variables().size()); Hashtable<Long, DepartmentSpreadConstraint> depSpreadConstraints = new Hashtable<Long, DepartmentSpreadConstraint>(); for (Lecture lecture : getModel().variables()) { if (lecture.getDepartment() == null) continue; DepartmentSpreadConstraint deptConstr = (DepartmentSpreadConstraint) depSpreadConstraints .get(lecture.getDepartment()); if (deptConstr == null) { deptConstr = new DepartmentSpreadConstraint(getModel().getProperties(), lecture.getDepartment(), (String) iDeptNames.get(lecture.getDepartment())); depSpreadConstraints.put(lecture.getDepartment(), deptConstr); getModel().addConstraint(deptConstr); } deptConstr.addVariable(lecture); iProgress.incProgress(); } } if (iSubjectBalancing) { iProgress.setPhase("Creating subject spread constraints ...", getModel().variables().size()); Hashtable<Long, SpreadConstraint> subjectSpreadConstraints = new Hashtable<Long, SpreadConstraint>(); for (Lecture lecture : getModel().variables()) { Class_ clazz = iClasses.get(lecture.getClassId()); if (clazz == null) continue; for (CourseOffering co : clazz.getSchedulingSubpart().getInstrOfferingConfig() .getInstructionalOffering().getCourseOfferings()) { Long subject = co.getSubjectArea().getUniqueId(); SpreadConstraint subjectSpreadConstr = subjectSpreadConstraints.get(subject); if (subjectSpreadConstr == null) { subjectSpreadConstr = new SpreadConstraint(getModel().getProperties(), co.getSubjectArea().getSubjectAreaAbbreviation()); subjectSpreadConstraints.put(subject, subjectSpreadConstr); getModel().addConstraint(subjectSpreadConstr); } subjectSpreadConstr.addVariable(lecture); } iProgress.incProgress(); } } if (getModel().getProperties().getPropertyBoolean("General.PurgeInvalidPlacements", true)) purgeInvalidValues(); /* for (Constraint c: getModel().constraints()) { if (c instanceof SpreadConstraint) ((SpreadConstraint)c).init(); if (c instanceof DiscouragedRoomConstraint) ((DiscouragedRoomConstraint)c).setEnabled(true); if (c instanceof MinimizeNumberOfUsedRoomsConstraint) ((MinimizeNumberOfUsedRoomsConstraint)c).setEnabled(true); if (c instanceof MinimizeNumberOfUsedGroupsOfTime) ((MinimizeNumberOfUsedGroupsOfTime)c).setEnabled(true); } */ iProgress.setPhase("Checking for inconsistencies...", getModel().variables().size()); for (Lecture lecture : getModel().variables()) { iProgress.incProgress(); for (Iterator i = lecture.students().iterator(); i.hasNext();) { Student s = (Student) i.next(); if (!s.canEnroll(lecture)) iProgress.message(msglevel("badStudentEnrollment", Progress.MSGLEVEL_INFO), "Invalid student enrollment of student " + s.getId() + " in class " + getClassLabel(lecture) + " found."); } //check same instructor constraint if (!lecture.values(getAssignment()).isEmpty() && lecture.timeLocations().size() == 1 && !lecture.getInstructorConstraints().isEmpty()) { for (Lecture other : getModel().variables()) { if (other.values(getAssignment()).isEmpty() || other.timeLocations().size() != 1 || lecture.getClassId().compareTo(other.getClassId()) <= 0) continue; Placement p1 = lecture.values(getAssignment()).get(0); Placement p2 = other.values(getAssignment()).get(0); if (!other.getInstructorConstraints().isEmpty()) { for (InstructorConstraint ic : lecture.getInstructorConstraints()) { if (!other.getInstructorConstraints().contains(ic)) continue; if (p1.canShareRooms(p2) && p1.sameRooms(p2)) continue; if (p1.getTimeLocation().hasIntersection(p2.getTimeLocation())) { iProgress.message(msglevel("reqInstructorOverlap", Progress.MSGLEVEL_WARN), "Same instructor and overlapping time required:" + "<br> " + getClassLabel(lecture) + " ← " + p1.getLongName(iUseAmPm) + "<br> " + getClassLabel(other) + " ← " + p2.getLongName(iUseAmPm)); } else if (ic.getDistancePreference(p1, p2) == PreferenceLevel.sIntLevelProhibited && lecture.roomLocations().size() == 1 && other.roomLocations().size() == 1) { iProgress.message(msglevel("reqInstructorBackToBack", Progress.MSGLEVEL_WARN), "Same instructor, back-to-back time and rooms too far (distance=" + Math.round(10.0 * Placement.getDistanceInMeters( getModel().getDistanceMetric(), p1, p2)) + "m) required:" + "<br> " + getClassLabel(lecture) + " ← " + p1.getLongName(iUseAmPm) + "<br> " + getClassLabel(other) + " ← " + p2.getLongName(iUseAmPm)); } } } } } if (!lecture.isSingleton()) continue; for (Lecture other : getModel().variables()) { if (!other.isSingleton() || lecture.getClassId().compareTo(other.getClassId()) <= 0) continue; Placement p1 = new Placement(lecture, lecture.timeLocations().get(0), lecture.roomLocations()); Placement p2 = new Placement(other, other.timeLocations().get(0), other.roomLocations()); if (p1.shareRooms(p2) && p1.getTimeLocation().hasIntersection(p2.getTimeLocation()) && !p1.canShareRooms(p2)) { iProgress.message(msglevel("reqRoomOverlap", Progress.MSGLEVEL_WARN), "Same room and overlapping time required:" + "<br> " + getClassLabel(lecture) + " ← " + p1.getLongName(iUseAmPm) + "<br> " + getClassLabel(other) + " ← " + p2.getLongName(iUseAmPm)); } } if (getAssignment().getValue(lecture) == null) { Placement placement = new Placement(lecture, lecture.timeLocations().get(0), lecture.roomLocations()); if (!placement.isValid()) { String reason = ""; for (InstructorConstraint ic : lecture.getInstructorConstraints()) { if (!ic.isAvailable(lecture, placement)) reason += "<br> instructor " + ic.getName() + " not available"; } if (lecture.getNrRooms() > 0) { if (placement.isMultiRoom()) { for (RoomLocation roomLocation : placement.getRoomLocations()) { if (!roomLocation.getRoomConstraint().isAvailable(lecture, placement.getTimeLocation(), lecture.getScheduler())) reason += "<br> room " + roomLocation.getName() + " not available"; } } else { if (!placement.getRoomLocation().getRoomConstraint().isAvailable(lecture, placement.getTimeLocation(), lecture.getScheduler())) reason += "<br> room " + placement.getRoomLocation().getName() + " not available"; } } Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel() .conflictConstraints(getAssignment(), placement); if (!conflictConstraints.isEmpty()) { for (Constraint<Lecture, Placement> c : conflictConstraints.keySet()) { Set<Placement> vals = conflictConstraints.get(c); for (Placement p : vals) { Lecture l = p.variable(); if (l.isCommitted()) reason += "<br> conflict with committed assignment " + getClassLabel(l) + " = " + p.getLongName(iUseAmPm) + " (in constraint " + c + ")"; if (p.equals(placement)) reason += "<br> constraint " + c; } } } iProgress.message(msglevel("reqInvalidPlacement", Progress.MSGLEVEL_WARN), "Class " + getClassLabel(lecture) + " requires an invalid placement " + placement.getLongName(iUseAmPm) + (reason.length() == 0 ? "." : ":" + reason)); } else if (iAssignSingleton && getModel().conflictValues(getAssignment(), placement).isEmpty()) getAssignment().assign(0, placement); } } getModel().createAssignmentContexts(getAssignment(), true); if (getModel().getProperties().getPropertyBoolean("General.EnrollmentCheck", true)) new EnrollmentCheck(getModel(), getAssignment(), msglevel("enrollmentCheck", Progress.MSGLEVEL_WARN)) .checkStudentEnrollments(iProgress); if (getModel().getProperties().getPropertyBoolean("General.SwitchStudents", true) && getAssignment().nrAssignedVariables() != 0 && !iLoadStudentEnrlsFromSolution) getModel().switchStudents(getAssignment()); iProgress.setPhase("Done", 1); iProgress.incProgress(); iProgress.message(msglevel("allDone", Progress.MSGLEVEL_INFO), "Model successfully loaded."); }