Example usage for java.util Hashtable entrySet

List of usage examples for java.util Hashtable entrySet

Introduction

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

Prototype

Set entrySet

To view the source code for java.util Hashtable entrySet.

Click Source Link

Usage

From source file:org.unitime.timetable.solver.exam.ExamSolver.java

public Collection<ExamAssignmentInfo> getPeriods(long examId, ExamProposedChange change) {
    Lock lock = currentSolution().getLock().readLock();
    lock.lock();/*from   w  w w  .ja  v  a2 s .  co m*/
    try {
        //lookup exam
        Exam exam = getExam(examId);
        if (exam == null)
            return null;

        //assign change
        Hashtable<Exam, ExamPlacement> undoAssign = new Hashtable();
        HashSet<Exam> undoUnassing = new HashSet();
        if (change != null) {
            for (ExamAssignment assignment : change.getConflicts()) {
                ExamPlacement placement = getPlacement(assignment);
                if (placement == null)
                    continue;
                undoAssign.put((Exam) placement.variable(), placement);
                currentSolution().getAssignment().unassign(0, placement.variable());
            }
            for (ExamAssignment assignment : change.getAssignments()) {
                ExamPlacement placement = getPlacement(assignment);
                if (placement == null)
                    continue;
                for (Iterator i = placement.variable().getModel()
                        .conflictValues(currentSolution().getAssignment(), placement).iterator(); i
                                .hasNext();) {
                    ExamPlacement conflict = (ExamPlacement) i.next();
                    if (conflict.variable().equals(placement.variable()))
                        continue;
                    Exam conflictingExam = (Exam) conflict.variable();
                    if (!undoAssign.containsKey(conflictingExam) && !undoUnassing.contains(conflictingExam))
                        undoAssign.put(conflictingExam, conflict);
                    currentSolution().getAssignment().unassign(0, conflict.variable());
                }
                if (currentSolution().getAssignment().getValue(placement.variable()) != null)
                    undoAssign.put((Exam) placement.variable(),
                            currentSolution().getAssignment().getValue(placement.variable()));
                else
                    undoUnassing.add((Exam) placement.variable());
                currentSolution().getAssignment().assign(0, placement);
            }
        }

        Vector<ExamAssignmentInfo> periods = new Vector<ExamAssignmentInfo>();
        for (ExamPeriodPlacement period : exam.getPeriodPlacements()) {
            Set rooms = exam.findBestAvailableRooms(currentSolution().getAssignment(), period);
            if (rooms == null)
                rooms = new HashSet();
            boolean conf = !exam.checkDistributionConstraints(currentSolution().getAssignment(), period);
            ExamAssignmentInfo assignment = new ExamAssignmentInfo(new ExamPlacement(exam, period, rooms),
                    currentSolution().getAssignment());
            if (conf)
                assignment.setPeriodPref("P");
            periods.add(assignment);
        }

        //undo change
        for (Exam undoExam : undoUnassing)
            if (currentSolution().getAssignment().getValue(undoExam) != null)
                currentSolution().getAssignment().unassign(0, undoExam);
        for (Map.Entry<Exam, ExamPlacement> entry : undoAssign.entrySet())
            currentSolution().getAssignment().unassign(0, entry.getKey());
        for (Map.Entry<Exam, ExamPlacement> entry : undoAssign.entrySet())
            currentSolution().getAssignment().assign(0, entry.getValue());

        return periods;
    } finally {
        lock.unlock();
    }
}

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;/* ww w . j  ava 2 s .c o  m*/
    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>&nbsp;&nbsp;&nbsp;&nbsp;" + getClassLabel(lecture)
                                            + " &larr; " + p1.getLongName(iUseAmPm)
                                            + "<br>&nbsp;&nbsp;&nbsp;&nbsp;" + getClassLabel(other) + " &larr; "
                                            + 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>&nbsp;&nbsp;&nbsp;&nbsp;"
                                            + getClassLabel(lecture) + " &larr; " + p1.getLongName(iUseAmPm)
                                            + "<br>&nbsp;&nbsp;&nbsp;&nbsp;" + getClassLabel(other) + " &larr; "
                                            + 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>&nbsp;&nbsp;&nbsp;&nbsp;"
                                + getClassLabel(lecture) + " &larr; " + p1.getLongName(iUseAmPm)
                                + "<br>&nbsp;&nbsp;&nbsp;&nbsp;" + getClassLabel(other) + " &larr; "
                                + 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>&nbsp;&nbsp;&nbsp;&nbsp;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>&nbsp;&nbsp;&nbsp;&nbsp;room " + roomLocation.getName()
                                        + " not available";
                        }
                    } else {
                        if (!placement.getRoomLocation().getRoomConstraint().isAvailable(lecture,
                                placement.getTimeLocation(), lecture.getScheduler()))
                            reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;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>&nbsp;&nbsp;&nbsp;&nbsp;conflict with committed assignment "
                                        + getClassLabel(l) + " = " + p.getLongName(iUseAmPm)
                                        + " (in constraint " + c + ")";
                            if (p.equals(placement))
                                reason += "<br>&nbsp;&nbsp;&nbsp;&nbsp;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.");
}

From source file:org.unitime.timetable.solver.exam.ExamSolver.java

public Vector<ExamRoomInfo> getRooms(long examId, long periodId, ExamProposedChange change, int minRoomSize,
        int maxRoomSize, String filter, boolean allowConflicts) {
    Lock lock = currentSolution().getLock().readLock();
    lock.lock();// ww w.  j a v  a2  s. c o  m
    try {
        //lookup exam, period etc.
        Exam exam = getExam(examId);
        if (exam == null)
            return null;
        ExamPeriodPlacement period = null;
        for (ExamPeriodPlacement p : exam.getPeriodPlacements()) {
            if (periodId == p.getId()) {
                period = p;
                break;
            }
        }
        if (period == null)
            return null;
        Vector<ExamRoomInfo> rooms = new Vector<ExamRoomInfo>();
        if (exam.getMaxRooms() == 0)
            return rooms;

        //assign change
        Hashtable<Exam, ExamPlacement> undoAssign = new Hashtable();
        HashSet<Exam> undoUnassing = new HashSet();
        if (change != null) {
            for (ExamAssignment assignment : change.getConflicts()) {
                ExamPlacement placement = getPlacement(assignment);
                if (placement == null)
                    continue;
                undoAssign.put((Exam) placement.variable(), placement);
                currentSolution().getAssignment().unassign(0, placement.variable());
            }
            for (ExamAssignment assignment : change.getAssignments()) {
                ExamPlacement placement = getPlacement(assignment);
                if (placement == null)
                    continue;
                for (Iterator i = placement.variable().getModel()
                        .conflictValues(currentSolution().getAssignment(), placement).iterator(); i
                                .hasNext();) {
                    ExamPlacement conflict = (ExamPlacement) i.next();
                    if (conflict.variable().equals(placement.variable()))
                        continue;
                    Exam conflictingExam = (Exam) conflict.variable();
                    if (!undoAssign.containsKey(conflictingExam) && !undoUnassing.contains(conflictingExam))
                        undoAssign.put(conflictingExam, conflict);
                    currentSolution().getAssignment().unassign(0, conflict.variable());
                }
                if (currentSolution().getAssignment().getValue(placement.variable()) != null)
                    undoAssign.put((Exam) placement.variable(),
                            currentSolution().getAssignment().getValue(placement.variable()));
                else
                    undoUnassing.add((Exam) placement.variable());
                currentSolution().getAssignment().assign(0, placement);
            }
        }

        ExamRoomSharing sharing = ((ExamModel) currentSolution().getModel()).getRoomSharing();

        //compute rooms
        for (ExamRoomPlacement room : exam.getRoomPlacements()) {

            int cap = room.getSize(exam.hasAltSeating());
            if (minRoomSize >= 0 && cap < minRoomSize)
                continue;
            if (maxRoomSize >= 0 && cap > maxRoomSize)
                continue;
            if (!ExamInfoModel.match(room.getName(), filter))
                continue;
            if (!room.isAvailable(period.getPeriod()))
                continue;

            boolean conf = !exam.checkDistributionConstraints(currentSolution().getAssignment(), room);
            if (sharing == null) {
                for (ExamPlacement p : room.getRoom().getPlacements(currentSolution().getAssignment(),
                        period.getPeriod()))
                    if (!p.variable().equals(exam))
                        conf = true;
            } else {
                if (sharing.inConflict(exam,
                        room.getRoom().getPlacements(currentSolution().getAssignment(), period.getPeriod()),
                        room.getRoom()))
                    conf = true;
            }

            if (!allowConflicts && conf)
                continue;

            rooms.add(new ExamRoomInfo(room.getRoom(), (conf ? 100 : 0) + room.getPenalty(period.getPeriod())));
        }

        //undo change
        for (Exam undoExam : undoUnassing)
            if (currentSolution().getAssignment().getValue(undoExam) != null)
                currentSolution().getAssignment().unassign(0, undoExam);
        for (Map.Entry<Exam, ExamPlacement> entry : undoAssign.entrySet())
            currentSolution().getAssignment().unassign(0, entry.getKey());
        for (Map.Entry<Exam, ExamPlacement> entry : undoAssign.entrySet())
            currentSolution().getAssignment().assign(0, entry.getValue());

        return rooms;
    } finally {
        lock.unlock();
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java

/**
 * @param editRow/*  w w w. j  a v a2  s  . c  o m*/
 * @param editCol (use -1 to validate entire row)
 */
protected void updateRowValidationStatus(int editRow, int editCol, Vector<Integer> badCats) {
    WorkbenchRow wbRow = workbench.getRow(editRow);
    List<UploadTableInvalidValue> issues = getIncremental() ? workbenchValidator.endCellEdit(editRow, editCol)
            : new Vector<UploadTableInvalidValue>();
    List<UploadTableMatchInfo> matchInfo = null;

    Hashtable<Short, Short> originalStats = new Hashtable<Short, Short>();
    Hashtable<Short, WorkbenchDataItem> originals = wbRow.getItems();
    for (Map.Entry<Short, WorkbenchDataItem> original : originals.entrySet()) {
        originalStats.put(original.getKey(), (short) original.getValue().getEditorValidationStatus());
    }

    //      if (workbenchValidator.getUploader().isUpdateUpload())
    //      {
    //         
    //      }

    if (doIncrementalMatching) {
        try {
            //XXX Really should avoid matching invalid columns. But that is tricky with trees.
            matchInfo = workbenchValidator.getUploader().matchData(editRow, editCol, issues);
        } catch (Exception ex) {
            //XXX what to do?, some exception might be caused by invalid data - filter out cols in exceptionalItems??
            //Maybe exceptions can be expected in general for a workbench-in-progress?
            //Or maybe we should blow up and force the workbench to close or something similarly drastic???
            ex.printStackTrace();
        }
    }

    List<CellStatusInfo> csis = new Vector<CellStatusInfo>(issues.size()
            + (matchInfo == null ? 0 : matchInfo.size()) + (badCats == null ? 0 : badCats.size()));
    for (UploadTableInvalidValue utiv : issues) {
        csis.add(new CellStatusInfo(utiv));
    }
    if (doIncrementalMatching && matchInfo != null) {
        for (UploadTableMatchInfo utmi : matchInfo) {
            if (utmi.getNumberOfMatches() != 1) //for now we don't care if a single match exists
            {
                csis.add(new CellStatusInfo(utmi));
            }
        }
    }
    if (badCats != null) {
        for (Integer badCat : badCats) {
            csis.add(createDupCatNumEntryCellStatus(badCat));
        }
    }

    Hashtable<Short, Short> exceptionalItems = updateCellStatuses(csis, wbRow);
    for (WorkbenchDataItem wbItem : wbRow.getWorkbenchDataItems()) {
        Short origstat = originalStats.get(new Short((short) wbItem.getColumnNumber()));
        if (origstat != null) {
            if (origstat != wbItem.getEditorValidationStatus()
                    || exceptionalItems.get(wbItem.getColumnNumber()) == null) {
                if (origstat == WorkbenchDataItem.VAL_MULTIPLE_MATCH
                        || origstat == WorkbenchDataItem.VAL_NEW_DATA) {
                    unmatchedCellCount.getAndDecrement();
                } else if (origstat == WorkbenchDataItem.VAL_ERROR
                        || origstat == WorkbenchDataItem.VAL_ERROR_EDIT) {
                    invalidCellCount.getAndDecrement();
                }
                if (exceptionalItems.get(wbItem.getColumnNumber()) == null) {
                    //XXX synchronization is not really necessary anymore, right??
                    synchronized (wbItem) {
                        wbItem.setStatusText(null);
                        wbItem.setEditorValidationStatus(WorkbenchDataItem.VAL_OK);
                    }
                }
            }
        }

    }
}

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

private void loadCommittedStudentConflicts(org.hibernate.Session hibSession, Set<Long> offeringsToAvoid) {
    //Load all committed assignment - student relations that may be relevant
    List<Object[]> assignmentEnrollments = (List<Object[]>) hibSession
            .createQuery("select distinct a, e.studentId, io.uniqueId from "
                    + "Solution s inner join s.assignments a inner join s.studentEnrollments e inner join a.clazz.schedulingSubpart.instrOfferingConfig.instructionalOffering io "
                    + "where " + "s.commited=true and s.owner.session.uniqueId=:sessionId and s.owner not in ("
                    + iSolverGroupIds + ") and " + "a.clazz=e.clazz")
            .setLong("sessionId", iSessionId.longValue()).list();

    // Filter out relevant relations (relations that are for loaded students)
    Hashtable<Assignment, Set<Student>> assignments = new Hashtable<Assignment, Set<Student>>();
    for (Object[] result : assignmentEnrollments) {
        Assignment assignment = (Assignment) result[0];
        Long studentId = (Long) result[1];
        Long offeringId = (Long) result[2];
        if (offeringsToAvoid.contains(offeringId))
            continue;
        Student student = (Student) iStudents.get(studentId);
        if (student != null) {
            Set<Student> students = assignments.get(assignment);
            if (students == null) {
                students = new HashSet<Student>();
                assignments.put(assignment, students);
            }//from   www . ja va2s.  co  m
            students.add(student);
        }
    }

    // Ensure no assignment-class relation is got from the cache
    for (Iterator i1 = assignmentEnrollments.iterator(); i1.hasNext();) {
        Object[] result = (Object[]) i1.next();
        Assignment assignment = (Assignment) result[0];
        if (!assignments.containsKey(assignment))
            hibSession.evict(assignment);
    }

    // Make up the appropriate committed placements and propagate those through the course structure
    iProgress.setPhase("Loading student conflicts with commited solutions ...", assignments.size());
    for (Iterator i1 = assignments.entrySet().iterator(); i1.hasNext();) {
        Map.Entry entry = (Map.Entry) i1.next();
        Assignment assignment = (Assignment) entry.getKey();
        HashSet students = (HashSet) entry.getValue();
        Placement committedPlacement = assignment.getPlacement();
        for (Iterator i2 = students.iterator(); i2.hasNext();) {
            Student student = (Student) i2.next();
            student.addCommitedPlacement(committedPlacement);
        }
        if (!iLectures.containsKey(assignment.getClassId())) {
            iLectures.put(assignment.getClassId(), committedPlacement.variable());
            getModel().addVariable(committedPlacement.variable());
        }
        propagateCommittedAssignment(students, assignment);
        iProgress.incProgress();
    }
}

From source file:org.opencms.workplace.tools.database.CmsHtmlImport.java

/**
 * Creates a file in the VFS.<p>//  w w  w  .jav a2  s  . c  o m
 * 
 * @param filename the complete filename in the real file system
 * @param position the default navigation position of this folder
 * @param content the HTML content of the file
 * @param properties the file properties
 */
private void createFile(String filename, int position, String content, Hashtable properties) {

    String vfsFileName = (String) m_fileIndex.get(filename.replace('\\', '/'));

    if (vfsFileName != null) {
        try {

            m_report.print(Messages.get().container(Messages.RPT_CREATE_FILE_0), I_CmsReport.FORMAT_NOTE);
            m_report.print(org.opencms.report.Messages.get()
                    .container(org.opencms.report.Messages.RPT_ARGUMENT_1, vfsFileName));
            m_report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));

            // check if we have to set the navpos property.
            if ((properties.get(CmsPropertyDefinition.PROPERTY_NAVPOS) == null)
                    && (properties.get(CmsPropertyDefinition.PROPERTY_NAVTEXT) != null)) {
                // set the position in the folder as navpos
                // we have to add one to the position, since it is counted from 0
                properties.put(CmsPropertyDefinition.PROPERTY_NAVPOS, (position + 1) + "");
            }

            // create new XML page
            Locale locale = CmsLocaleManager.getLocale(m_locale);
            CmsXmlPage page = new CmsXmlPage(locale, OpenCms.getSystemInfo().getDefaultEncoding());
            page.addValue(m_element, locale);
            page.setStringValue(m_cmsObject, m_element, locale, content);

            // check links
            CmsLinkTable linkTable = page.getLinkTable(m_element, locale);
            Iterator i = linkTable.iterator();
            while (i.hasNext()) {
                CmsLink link = (CmsLink) i.next();
                String target = link.getTarget();
                // do only update internal links 
                if (link.isInternal()) {
                    target = m_cmsObject.getRequestContext().getFileTranslator().translateResource(target);
                    // update link
                    link.updateLink(target, link.getAnchor(), link.getQuery());
                    link.checkConsistency(m_cmsObject);
                }
            }
            // marshal XML page and get the content
            byte[] contentByteArray = page.marshal();
            List oldProperties = new ArrayList();

            int xmlPageId = OpenCms.getResourceManager()
                    .getResourceType(CmsResourceTypeXmlPage.getStaticTypeName()).getTypeId();
            if (!m_overwrite) {
                m_cmsObject.createResource(vfsFileName, xmlPageId, contentByteArray, new ArrayList());
            } else {
                try {
                    // try if the file is there
                    oldProperties = m_cmsObject.readPropertyObjects(vfsFileName, false);
                    CmsLock lock = m_cmsObject.getLock(vfsFileName);
                    if (lock.getType() != CmsLockType.EXCLUSIVE) {
                        m_cmsObject.lockResource(vfsFileName);
                    }
                    m_cmsObject.deleteResource(vfsFileName, CmsResource.DELETE_PRESERVE_SIBLINGS);
                } catch (CmsException e) {
                    // the file did not exist, so we do not have to delete it                      
                } finally {
                    // create the new resource
                    m_report.print(Messages.get().container(Messages.RPT_OVERWRITE_0), I_CmsReport.FORMAT_NOTE);
                    m_report.print(org.opencms.report.Messages.get()
                            .container(org.opencms.report.Messages.RPT_DOTS_0));
                    m_cmsObject.createResource(vfsFileName, xmlPageId, contentByteArray, new ArrayList());
                }
            }
            // create all properties and put them in an ArrayList
            Iterator it = properties.entrySet().iterator();
            List propertyList = new ArrayList();
            while (it.hasNext()) {
                // get property and value
                Map.Entry entry = (Map.Entry) it.next();
                String propertyKey = (String) entry.getKey();
                String propertyVal = (String) entry.getValue();
                // create new Property Object
                CmsProperty property = new CmsProperty(propertyKey, propertyVal, propertyVal);
                // create implicitly if Property doesn't exist already
                property.setAutoCreatePropertyDefinition(true);
                // add new property to the list
                propertyList.add(property);
            }
            // try to write the properties
            try {
                m_cmsObject.writePropertyObjects(vfsFileName, propertyList);
                // write the old properties if available
                m_cmsObject.writePropertyObjects(vfsFileName, oldProperties);
            } catch (CmsException e1) {
                e1.printStackTrace();
            }
            m_report.println(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
                    I_CmsReport.FORMAT_OK);
        } catch (CmsException e) {
            m_report.println(e);
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
}

From source file:com.clustercontrol.nodemap.session.NodeMapControllerBean.java

/**
 * fping?ping?????<BR>//from  w  ww .  j  a v a2s . c o m
 * @param facilityId Ping?ID()collect?facilityID???
 * @return ping??
 * @throws HinemosUnknown
 * @throws NodeMapException 
 */
public List<String> pingToFacilityList(List<String> facilityList) throws HinemosUnknown, NodeMapException {

    String message = "";
    String messageOrg = "";
    //??????
    // hosts[] IP(String ??)
    // hostsv6[]  IPv6(String??)
    // node     IP????
    // target   nodo?
    HashSet<String> hosts = new HashSet<String>();
    HashSet<String> hostsv6 = new HashSet<String>();
    // ip?name
    Hashtable<String, List<String>> facilityNameTable = new Hashtable<>();

    String facilityId = null;
    int version = 4;
    String[] node;
    for (int index = 0; index < facilityList.size(); index++) {
        facilityId = facilityList.get(index);
        if (facilityId != null && !"".equals(facilityId)) {
            node = new String[2];
            try {

                // ??
                NodeInfo info = new RepositoryControllerBean().getNode(facilityId);

                if (info.getIpAddressVersion() != null) {
                    version = info.getIpAddressVersion();
                } else {
                    version = 4;
                }

                if (version == 6) {

                    InetAddress[] ip = InetAddress.getAllByName(info.getIpAddressV6());

                    if (ip.length != 1) {
                        //IPInetAddress??????1????????
                        //UnnownHostExcption
                        UnknownHostException e = new UnknownHostException();
                        m_log.info("pingToFacilityList() : " + e.getClass().getSimpleName() + ", "
                                + e.getMessage());
                        throw e;
                    }

                    node[0] = ip[0].getHostAddress();
                    if (node[0] != null && !node[0].equals("")) {
                        //IPHashSet?????
                        hostsv6.add(node[0]);
                    }
                } else {
                    node[0] = info.getIpAddressV4();
                    if (node[0] != null && !node[0].equals("")) {

                        //IPHashSet?????
                        hosts.add(node[0]);
                    }
                }
                if (node[0] != null && !node[0].equals("")) {
                    node[1] = info.getNodeName();
                    //target??????
                    List<String> facilitys = facilityNameTable.get(node[0]);
                    if (facilitys == null) {
                        facilitys = new ArrayList<>();
                    }
                    facilitys.add(facilityId);
                    facilityNameTable.put(node[0], facilitys);
                }
            } catch (FacilityNotFound e) {
                message = MessageConstant.MESSAGE_COULD_NOT_GET_NODE_ATTRIBUTES_PING.getMessage() + ","
                        + facilityId;
                messageOrg = e.getMessage();
                throw new NodeMapException(message + ", " + messageOrg, e);
            } catch (UnknownHostException e) {
                // ???
            }
        }
    }

    int runCount = 0;
    int runInterval = 0;
    int pingTimeout = 0;
    try {
        // [](default:1?19)
        String runCountKey = "nodemap.ping.runcount";
        runCount = HinemosPropertyUtil
                .getHinemosPropertyNum(runCountKey, Long.valueOf(PingRunCountConstant.TYPE_COUNT_01))
                .intValue();
        CommonValidator.validateInt(runCountKey, runCount, 1, 9);

        // [ms](default:1000?05000)
        String runIntervalKey = "nodemap.ping.runinterval";
        runInterval = HinemosPropertyUtil
                .getHinemosPropertyNum(runIntervalKey, Long.valueOf(PingRunIntervalConstant.TYPE_SEC_02))
                .intValue();
        CommonValidator.validateInt(runIntervalKey, runInterval, 0, 5 * 1000);

        // [ms](default:5000?13600000)
        String pintTimeoutKey = "nodemap.ping.timeout";
        pingTimeout = HinemosPropertyUtil
                .getHinemosPropertyNum(pintTimeoutKey, Long.valueOf(PingRunIntervalConstant.TYPE_SEC_05))
                .intValue();
        CommonValidator.validateInt(pintTimeoutKey, pingTimeout, 1, 60 * 60 * 1000);
    } catch (Exception e) {
        m_log.warn("pingToFacilityList() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
        throw new HinemosUnknown(e.getMessage(), e);
    }

    ReachAddressFping reachabilityFping = new ReachAddressFping(runCount, runInterval, pingTimeout);

    boolean result = true;
    boolean resultTmp = true;
    ArrayList<String> msgErr = new ArrayList<>();
    ArrayList<String> msgErrV6 = new ArrayList<>();
    Hashtable<String, PingResult> fpingResultSet = new Hashtable<String, PingResult>();
    Hashtable<String, PingResult> fpingResultSetV6 = new Hashtable<String, PingResult>();

    RunMonitorPing monitorPing = new RunMonitorPing();
    //IPv4???fping??
    if (hosts.size() != 0) {
        result = reachabilityFping.isReachable(hosts, 4);
        msgErr = reachabilityFping.getM_errMsg();
    }
    //IPv6???fping6??
    if (hostsv6.size() != 0) {
        resultTmp = reachabilityFping.isReachable(hostsv6, 6);
        msgErrV6 = reachabilityFping.getM_errMsg();
    }

    if (!result || !resultTmp) {
        return null;
    }
    List<String> retList = new ArrayList<>();
    fpingResultSet = monitorPing.wrapUpFping(msgErr, runCount, 4);
    fpingResultSetV6 = monitorPing.wrapUpFping(msgErrV6, runCount, 6);
    //IPv4????????IPv6?????
    m_log.debug("pingToFacilityList(): before fpingResultSet check");
    if (fpingResultSet.size() == 0) {
        m_log.debug("pingToFacilityList(): after fpingResultSet check");
        fpingResultSet = fpingResultSetV6;
    }
    //IPv4??????IPv6??
    else if (fpingResultSetV6.size() != 0) {
        fpingResultSet.putAll(fpingResultSetV6);
    }
    for (Map.Entry<String, List<String>> ipAdd : facilityNameTable.entrySet()) {
        PingResult pingResult = fpingResultSet.get(ipAdd.getKey());
        for (String facility : ipAdd.getValue()) {
            retList.add(facility + " : " + pingResult.getMesseageOrg());
        }
    }
    return retList;
}

From source file:com.crushpaper.Servlet.java

/**
 * Helper method. Adds the RTF for an entry to an export.
 *//*from   w  w  w  .  j a v a  2s. c  om*/
private void addEntryRtfToExport(Entry entry, StringBuilder result, SourcesHashList sources,
        boolean includeQuotations, boolean includeReferencesSection, boolean skipThisLevel) throws IOException {

    if (!skipThisLevel) {
        final Entry source = dbLogic.getEntryById(entry.getSourceId());
        int sourceId = 0;
        if (source != null) {
            sourceId = sources.add(source);
        }

        if (includeQuotations && entry.hasQuotation()) {
            appendRtfString(result, entry.getQuotation(""));
            result.append("\\par\n");
            if (includeReferencesSection) {
                if (sourceId != 0) {
                    result.append("[Reference " + sourceId + "]\\par\n");
                }
            }
            result.append("\\par\n");
        }

        if (entry.hasNote()) {
            appendRtfString(result, entry.getNote(""));
            result.append("\\par\n\\par\n");
        }
    }

    List<?> childrenFromDb = dbLogic.getEntriesByParentId(entry.getId());

    if (!childrenFromDb.isEmpty()) {
        final Hashtable<String, Entry> children = new Hashtable<String, Entry>();
        Entry first = null;
        for (final Object childObject : childrenFromDb) {
            final Entry child = (Entry) childObject;
            children.put(child.getId(), child);
            if (!child.hasPreviousSiblingId()) {
                first = child;
            }
        }

        if (first != null) {
            // This is the code path if there is no DB corruption.
            Entry child = first;
            for (int i = 0; i < children.size(); ++i) {
                if (child == null) {
                    break;
                }

                addEntryRtfToExport(child, result, sources, includeQuotations, includeReferencesSection, false);

                if (!child.hasNextSiblingId()) {
                    break;
                }

                final String nextId = child.getNextSiblingId();
                child = children.get(nextId);
            }
        } else {
            // This is an error code path. It should only happen if there is
            // DB corruption.
            final Iterator<Map.Entry<String, Entry>> iterator = children.entrySet().iterator();
            while (iterator.hasNext()) {
                final Map.Entry<String, Entry> mapEntry = iterator.next();
                final Entry child = mapEntry.getValue();

                addEntryRtfToExport(child, result, sources, includeQuotations, includeReferencesSection, false);
            }
        }
    }
}

From source file:com.crushpaper.Servlet.java

/**
 * Helper method. Adds the Markdown for an entry to an export.
 *//*from   ww w  . j  a va 2s . c  om*/
private void addEntryMarkdownToExport(Entry entry, StringBuilder result, SourcesHashList sources,
        boolean includeQuotations, boolean includeReferencesSection, boolean skipThisLevel) throws IOException {

    if (!skipThisLevel) {
        final Entry source = dbLogic.getEntryById(entry.getSourceId());
        int sourceId = 0;
        if (source != null) {
            sourceId = sources.add(source);
        }

        if (includeQuotations && entry.hasQuotation()) {
            result.append(markdownBlockquote(entry.getQuotation("")));
            if (includeReferencesSection) {
                if (sourceId != 0) {
                    result.append(" [Reference" + sourceId + "] [Reference" + sourceId + "]");
                }
            }
            result.append("\n\n");
        }

        if (entry.hasNote()) {
            result.append(entry.getNote("").replace("\n", "  \n") + "\n\n");
        }
    }

    List<?> childrenFromDb = dbLogic.getEntriesByParentId(entry.getId());

    if (!childrenFromDb.isEmpty()) {
        final Hashtable<String, Entry> children = new Hashtable<String, Entry>();
        Entry first = null;
        for (final Object childObject : childrenFromDb) {
            final Entry child = (Entry) childObject;
            children.put(child.getId(), child);
            if (!child.hasPreviousSiblingId()) {
                first = child;
            }
        }

        if (first != null) {
            // This is the code path if there is no DB corruption.
            Entry child = first;
            for (int i = 0; i < children.size(); ++i) {
                if (child == null) {
                    break;
                }

                addEntryMarkdownToExport(child, result, sources, includeQuotations, includeReferencesSection,
                        false);

                if (!child.hasNextSiblingId()) {
                    break;
                }

                final String nextId = child.getNextSiblingId();
                child = children.get(nextId);
            }
        } else {
            // This is an error code path. It should only happen if there is
            // DB corruption.
            final Iterator<Map.Entry<String, Entry>> iterator = children.entrySet().iterator();
            while (iterator.hasNext()) {
                final Map.Entry<String, Entry> mapEntry = iterator.next();
                final Entry child = mapEntry.getValue();

                addEntryMarkdownToExport(child, result, sources, includeQuotations, includeReferencesSection,
                        false);
            }
        }
    }
}

From source file:com.crushpaper.Servlet.java

/**
 * Helper method. Adds the HTML for an entry to an export.
 *///from www . j av  a2 s  .c  o m
private void addEntryHtmlToExport(Entry entry, StringBuilder result, SourcesHashList sources,
        boolean asNestedLists, boolean includeQuotations, boolean includeReferencesSection,
        boolean skipThisLevel) throws IOException {

    if (!skipThisLevel) {
        if (asNestedLists) {
            result.append("<div class=\"noteAndQuotation\">\n");
        }

        final Entry source = dbLogic.getEntryById(entry.getSourceId());
        int sourceId = 0;
        if (source != null) {
            sourceId = sources.add(source);
        }

        if (includeQuotations && entry.hasQuotation()) {
            result.append("<p class=\"quotation\">");
            result.append(textToPreishHtml(entry.getQuotation(), false));

            if (includeReferencesSection) {
                if (sourceId != 0) {
                    result.append(" <a href=\"#reference" + sourceId + "\">[" + sourceId + "]</a>");
                }
            }

            result.append("</p>\n");
        }

        if (entry.hasNote()) {
            String noteHtml = textToPreishHtml(entry.getNote(), false);
            if (!noteHtml.isEmpty()) {
                result.append("<p class=\"note\">");
                result.append(noteHtml);
                result.append("</p>\n");
            }
        }
    }

    List<?> childrenFromDb = dbLogic.getEntriesByParentId(entry.getId());

    if (!childrenFromDb.isEmpty()) {
        if (asNestedLists) {
            result.append("<ol class=\"subnotes\">\n");
        }

        final Hashtable<String, Entry> children = new Hashtable<String, Entry>();
        Entry first = null;
        for (final Object childObject : childrenFromDb) {
            final Entry child = (Entry) childObject;
            children.put(child.getId(), child);
            if (!child.hasPreviousSiblingId()) {
                first = child;
            }
        }

        if (first != null) {
            // This is the code path if there is no DB corruption.
            Entry child = first;
            for (int i = 0; i < children.size(); ++i) {
                if (child == null) {
                    break;
                }

                if (asNestedLists) {
                    result.append("<li>\n");
                }

                addEntryHtmlToExport(child, result, sources, asNestedLists, includeQuotations,
                        includeReferencesSection, false);

                if (asNestedLists) {
                    result.append("</li>\n");
                }

                if (!child.hasNextSiblingId()) {
                    break;
                }

                final String nextId = child.getNextSiblingId();
                child = children.get(nextId);
            }
        } else {
            // This is an error code path. It should only happen if there is
            // DB corruption.
            final Iterator<Map.Entry<String, Entry>> iterator = children.entrySet().iterator();
            while (iterator.hasNext()) {
                final Map.Entry<String, Entry> mapEntry = iterator.next();
                final Entry child = mapEntry.getValue();

                if (asNestedLists) {
                    result.append("<li>\n");
                }

                addEntryHtmlToExport(child, result, sources, asNestedLists, includeQuotations,
                        includeReferencesSection, false);

                if (asNestedLists) {
                    result.append("</li>\n");
                }
            }
        }

        if (asNestedLists) {
            result.append("</ol>\n");
        }
    }

    if (!skipThisLevel && asNestedLists) {
        result.append("</div>\n");
    }
}