Example usage for java.util Hashtable values

List of usage examples for java.util Hashtable values

Introduction

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

Prototype

Collection values

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

Click Source Link

Usage

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  w ww  . j  av  a 2  s .co 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:edu.ku.brc.specify.config.SpecifyAppContextMgr.java

/**
 * Sets up the "current" Collection by first checking prefs for the most recent primary key,
 * @param userArg the user object of the current object
 * @param promptForCollection indicates the User should always be asked which Collection to use
 * @param collectionName name of collection to choose (can be null)
 * @return the current Collection or null
 *///ww w .  j  a va 2s . c o  m
protected Collection setupCurrentCollection(final SpecifyUser userArg, final boolean promptForCollection,
        final String collectionName) {
    DataProviderSessionIFace session = null;
    try {
        AppPreferences remotePrefs = AppPreferences.getRemote();

        session = DataProviderFactory.getInstance().createSession();

        SpecifyUser spUser = session.getData(SpecifyUser.class, "id", userArg.getId(), //$NON-NLS-1$
                DataProviderSessionIFace.CompareType.Equals);

        String alwaysAskPref = "ALWAYS.ASK.COLL"; //$NON-NLS-1$
        boolean askForColl = remotePrefs.getBoolean(alwaysAskPref, true);
        String prefName = mkUserDBPrefName("recent_collection_id"); //$NON-NLS-1$

        // First get the Collections the User has access to.
        Hashtable<String, Pair<String, Integer>> collectionHash = new Hashtable<String, Pair<String, Integer>>();

        String sqlStr = String.format(
                "SELECT DISTINCT cln.CollectionID, cln.CollectionName, cln.DisciplineID FROM collection AS cln "
                        + "Inner Join spprincipal AS p ON cln.UserGroupScopeId = p.userGroupScopeID "
                        + "Inner Join specifyuser_spprincipal AS su_pr ON p.SpPrincipalID = su_pr.SpPrincipalID "
                        + "WHERE su_pr.SpecifyUserID = %d AND GroupSubClass = '%s'", //$NON-NLS-1$
                spUser.getSpecifyUserId(), UserPrincipal.class.getName());

        //log.debug(sqlStr);

        for (Object[] row : BasicSQLUtils.query(sqlStr)) {
            String collName = row[1].toString();
            Integer collId = (Integer) row[0];

            if (collectionHash.get(collName) != null) {
                String dispName = BasicSQLUtils
                        .querySingleObj("SELECT Name FROM discipline WHERE DisciplineID = " + row[2]);
                collName += " - " + dispName;
                if (collectionHash.get(collName) != null) {
                    String sql = "SELECT d.DivisionID FROM collection c INNER JOIN discipline d ON c.DisciplineID = d.UserGroupScopeId WHERE d.DisciplineID = "
                            + row[2];
                    String divName = BasicSQLUtils.querySingleObj(sql);
                    collName += " - " + divName;
                }
            }
            collectionHash.put(collName, new Pair<String, Integer>(collName, collId));
        }

        Pair<String, Integer> currColl = null;

        if (collectionName == null) {
            String recentIds = askForColl || promptForCollection ? null : remotePrefs.get(prefName, null);
            if (StringUtils.isNotEmpty(recentIds)) {
                Vector<Object[]> rows = BasicSQLUtils.query(
                        "SELECT CollectionName, UserGroupScopeId FROM collection WHERE UserGroupScopeId = " //$NON-NLS-1$
                                + recentIds);
                if (rows.size() == 1) {
                    String collName = rows.get(0)[0].toString();
                    Integer collId = (Integer) rows.get(0)[1];
                    currColl = new Pair<String, Integer>(collName, collId);

                } else {
                    log.debug("could NOT find recent ids"); //$NON-NLS-1$
                }
            }

            if (currColl != null && collectionHash.get(currColl.first) == null) {
                currColl = null;
            }
        }

        if (currColl == null || (askForColl && promptForCollection)) {
            if (collectionHash.size() == 1) {
                currColl = collectionHash.elements().nextElement();

            } else if (collectionHash.size() > 0) {
                if (collectionName == null) {
                    List<Pair<String, Integer>> list = new Vector<Pair<String, Integer>>();
                    list.addAll(collectionHash.values());
                    Collections.sort(list, new Comparator<Pair<String, Integer>>() {
                        @Override
                        public int compare(Pair<String, Integer> o1, Pair<String, Integer> o2) {
                            return o1.first.compareTo(o2.first);
                        }
                    });

                    int selectColInx = -1;

                    ChooseCollectionDlg colDlg = null;
                    do {
                        colDlg = new ChooseCollectionDlg(list);
                        colDlg.setSelectedIndex(selectColInx);
                        colDlg.createUI();
                        colDlg.pack();
                        Dimension size = colDlg.getSize();
                        size.width = Math.max(size.width, 300);
                        if (size.height < 150) {
                            size.height += 100;
                        }
                        colDlg.setSize(size);

                        UIHelper.centerWindow(colDlg);
                        colDlg.setVisible(true);

                    } while (colDlg.getSelectedObject() == null || colDlg.isCancelled());

                    currColl = colDlg.getSelectedObject();
                } else {
                    Integer colId = BasicSQLUtils.getCount(String.format(
                            "SELECT CollectionID FROM collection WHERE CollectionName = '%s'", collectionName));
                    if (colId != null) {
                        currColl = new Pair<String, Integer>(collectionName, colId);
                    } else {
                        return null;
                    }
                }
            }
        }

        Collection collection = null;

        if (currColl != null) {
            collection = (Collection) session.getData("FROM Collection WHERE id = " + currColl.second);
            if (collection != null) {
                collection.forceLoad();
                remotePrefs.put(prefName, (Long.toString(collection.getCollectionId())));
                remotePrefs.flush();
            }
        }

        if (collection == null) {
            UIRegistry.showLocalizedError(L10N + "ERR_NO_COLL");
            return null;
        }

        setClassObject(Collection.class, collection);

        if (collectionName == null) {
            String colObjStr = "CollectionObject"; //$NON-NLS-1$
            String iconName = remotePrefs.get(FormattingPrefsPanel.getDisciplineImageName(), colObjStr);
            if (StringUtils.isEmpty(iconName) || iconName.equals(colObjStr)) {
                iconName = "colobj_backstop"; //$NON-NLS-1$
            }

            IconManager.aliasImages(iconName, // Source
                    colObjStr); // Dest //$NON-NLS-1$

            IconManager.aliasImages(iconName, // Source
                    colObjStr.toLowerCase()); // Dest //$NON-NLS-1$
        }

        Discipline discipline = collection.getDiscipline();
        session.attach(discipline);

        Institution institution = discipline.getDivision().getInstitution();
        session.attach(institution);

        setClassObject(Institution.class, institution);

        if (!Agent.setUserAgent(spUser, discipline.getDivision())) {
            return null;
        }

        AppContextMgr am = AppContextMgr.getInstance();
        discipline.getTaxonTreeDef().forceLoad();
        am.setClassObject(TaxonTreeDef.class, discipline.getTaxonTreeDef());
        discipline.getGeologicTimePeriodTreeDef().forceLoad();
        am.setClassObject(GeologicTimePeriodTreeDef.class, discipline.getGeologicTimePeriodTreeDef());
        institution.getStorageTreeDef().forceLoad();
        am.setClassObject(StorageTreeDef.class, institution.getStorageTreeDef());
        discipline.getLithoStratTreeDef().forceLoad();
        am.setClassObject(LithoStratTreeDef.class, discipline.getLithoStratTreeDef());
        discipline.getGeographyTreeDef().forceLoad();
        am.setClassObject(GeographyTreeDef.class, discipline.getGeographyTreeDef());

        return collection;

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyAppContextMgr.class, ex);
        ex.printStackTrace();
        showLocalizedError(ex.toString()); // Yes, I know it isn't localized.

    } finally {
        if (session != null) {
            session.close();
        }
    }

    return null;

}

From source file:edu.ku.brc.specify.tasks.subpane.qb.QueryBldrPane.java

/**
 * @param report/*from ww w. jav a2s.  c  om*/
 * 
 * Loads and runs the query that acts as data source for report. Then runs report.
 */
public static void runReport(final SpReport report, final String title, final RecordSetIFace rs) {
    //XXX This is now also used to run Workbench reports. Really should extract the general stuff out
    //to a higher level...
    boolean isQueryBuilderRep = report.getReportObject() instanceof SpQuery;
    if (isQueryBuilderRep) {
        UsageTracker.incrUsageCount("QB.RunReport." + report.getQuery().getContextName());
    } else {
        UsageTracker.incrUsageCount("WB.RunReport");
    }
    TableTree tblTree = null;
    Hashtable<String, TableTree> ttHash = null;
    QueryParameterPanel qpp = null;
    if (isQueryBuilderRep) {
        UsageTracker.incrUsageCount("QB.RunReport." + report.getQuery().getContextName());
        QueryTask qt = (QueryTask) ContextMgr.getTaskByClass(QueryTask.class);
        if (qt != null) {
            Pair<TableTree, Hashtable<String, TableTree>> trees = qt.getTableTrees();
            tblTree = trees.getFirst();
            ttHash = trees.getSecond();
        } else {
            log.error("Could not find the Query task when running report " + report.getName());
            //blow up
            throw new RuntimeException("Could not find the Query task when running report " + report.getName());
        }
        qpp = new QueryParameterPanel();
        qpp.setQuery(report.getQuery(), tblTree, ttHash);
    }
    boolean go = true;
    try {
        JasperCompilerRunnable jcr = new JasperCompilerRunnable(null, report.getName(), null);
        jcr.findFiles();
        if (jcr.isCompileRequired()) {
            jcr.get();
        }
        //if isCompileRequired() is still true, then an error probably occurred compiling the report.
        JasperReport jr = !jcr.isCompileRequired() ? (JasperReport) JRLoader.loadObject(jcr.getCompiledFile())
                : null;
        ReportParametersPanel rpp = jr != null ? new ReportParametersPanel(jr, true) : null;
        JRDataSource src = null;
        if (rs == null && ((qpp != null && qpp.getHasPrompts()) || (rpp != null && rpp.getParamCount() > 0))) {
            Component pane = null;
            if (qpp != null && qpp.getHasPrompts() && rpp != null && rpp.getParamCount() > 0) {
                pane = new JTabbedPane();
                ((JTabbedPane) pane).addTab(UIRegistry.getResourceString("QB_REP_RUN_CRITERIA_TAB_TITLE"),
                        new JScrollPane(qpp, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER));

                ((JTabbedPane) pane).addTab(UIRegistry.getResourceString("QB_REP_RUN_PARAM_TAB_TITLE"),
                        new JScrollPane(rpp, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER));
            } else if (qpp != null && qpp.getHasPrompts()) {
                pane = new JScrollPane(qpp, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            } else {
                pane = new JScrollPane(rpp, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            }
            CustomDialog cd = new CustomDialog((Frame) UIRegistry.getTopWindow(),
                    UIRegistry.getResourceString("QB_GET_REPORT_CONTENTS_TITLE"), true,
                    CustomDialog.OKCANCELHELP, pane);
            cd.setHelpContext("RepRunSettings");
            cd.createUI();
            Dimension ps = cd.getPreferredSize();
            ps.setSize(ps.getWidth() * 1.3, ps.getHeight());
            cd.setSize(ps);
            UIHelper.centerAndShow(cd);
            go = !cd.isCancelled();
            cd.dispose();
        }
        if (go) {
            if (isQueryBuilderRep) {
                TableQRI rootQRI = null;
                int cId = report.getQuery().getContextTableId();
                for (TableTree tt : ttHash.values()) {
                    if (cId == tt.getTableInfo().getTableId()) {
                        rootQRI = tt.getTableQRI();
                        break;
                    }
                }
                Vector<QueryFieldPanel> qfps = new Vector<QueryFieldPanel>(qpp.getFields());
                for (int f = 0; f < qpp.getFields(); f++) {
                    qfps.add(qpp.getField(f));
                }

                HQLSpecs sql = null;

                // XXX need to allow modification of SelectDistinct(etc) ???
                //boolean includeRecordIds = true;
                boolean includeRecordIds = !report.getQuery().isSelectDistinct();

                try {
                    //XXX Is it safe to assume that query is not an export query? 
                    sql = QueryBldrPane.buildHQL(rootQRI, !includeRecordIds, qfps, tblTree, rs,
                            report.getQuery().getSearchSynonymy() == null ? false
                                    : report.getQuery().getSearchSynonymy(),
                            false, null);
                } catch (Exception ex) {
                    String msg = StringUtils.isBlank(ex.getLocalizedMessage())
                            ? getResourceString("QB_RUN_ERROR")
                            : ex.getLocalizedMessage();
                    UIRegistry.getStatusBar().setErrorMessage(msg, ex);
                    UIRegistry.writeTimedSimpleGlassPaneMsg(msg, Color.RED);
                    return;
                }
                int smushedCol = (report.getQuery().getSmushed() != null && report.getQuery().getSmushed())
                        ? getSmushedCol(qfps) + 1
                        : -1;
                src = new QBDataSource(sql.getHql(), sql.getArgs(), sql.getSortElements(),
                        getColumnInfo(qfps, true, rootQRI.getTableInfo(), false), includeRecordIds,
                        report.getRepeats(), smushedCol, /*getRecordIdCol(qfps)*/0);
                ((QBDataSource) src).startDataAcquisition();
            } else {
                DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
                try {
                    boolean loadedWB = false;
                    if (rs != null && rs.getOnlyItem() != null) {
                        Workbench wb = session.get(Workbench.class, rs.getOnlyItem().getRecordId());
                        if (wb != null) {
                            wb.forceLoad();
                            src = new WorkbenchJRDataSource(wb, true, report.getRepeats());
                            loadedWB = true;
                        }
                    }
                    if (!loadedWB) {
                        UIRegistry.displayErrorDlgLocalized("QueryBldrPane.WB_LOAD_ERROR_FOR_REPORT",
                                rs != null ? rs.getName() : "[" + UIRegistry.getResourceString("NONE") + "]");
                        return;
                    }
                } finally {
                    session.close();
                }
            }

            final CommandAction cmd = new CommandAction(ReportsBaseTask.REPORTS, ReportsBaseTask.PRINT_REPORT,
                    src);
            cmd.setProperty("title", title);
            cmd.setProperty("file", report.getName());
            if (rs == null) {
                cmd.setProperty("skip-parameter-prompt", "true");
            }
            //if isCompileRequired is true then an error probably occurred while compiling,
            //and, if so, it will be caught again and reported in the report results pane.
            if (!jcr.isCompileRequired()) {
                cmd.setProperty("compiled-file", jcr.getCompiledFile());
            }
            if (rpp != null && rpp.getParamCount() > 0) {
                StringBuilder params = new StringBuilder();
                for (int p = 0; p < rpp.getParamCount(); p++) {
                    Pair<String, String> param = rpp.getParam(p);
                    if (StringUtils.isNotBlank(param.getSecond())) {
                        params.append(param.getFirst());
                        params.append("=");
                        params.append(param.getSecond());
                        params.append(";");
                    }
                    cmd.setProperty("params", params.toString());
                }
            }
            CommandDispatcher.dispatch(cmd);
        }
    } catch (JRException ex) {
        UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(QueryBldrPane.class, ex);
        log.error(ex);
        ex.printStackTrace();
    }
}

From source file:edu.ku.brc.specify.web.SpecifyExplorer.java

/**
 * @param clazz/*  w w  w .ja  va2 s .  c o m*/
 * @param fieldName
 */
public void doAlphaIndexPageSQL(final PrintWriter out, final String className, final String letter,
        final int numLetters, final UIFieldFormatterIFace fmt, final String sql) {
    boolean isNumeric = fmt != null && fmt.isNumeric();
    int inx = template.indexOf(contentTag);
    String subContent = template.substring(0, inx);

    out.println(StringUtils.replace(subContent, "<!-- Title -->", className));

    ClassDisplayInfo cdi = classHash.get(className);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
    boolean useLetter = true;

    Connection connection = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        connection = DBConnection.getInstance().createConnection();
        stmt = connection.createStatement();
        rs = stmt.executeQuery(sql);

        Vector<NameId> alphaList = new Vector<NameId>();
        Hashtable<String, NameId> alphaHash = new Hashtable<String, NameId>();

        boolean doingIndex = StringUtils.isEmpty(letter);
        System.out.println("\n\ndoingIndex " + doingIndex + " letter[" + letter + "]");

        int numMin = Integer.MAX_VALUE;
        int numMax = Integer.MIN_VALUE;
        int cnt = 0;

        while (rs.next()) {
            String name;
            int id = rs.getInt(1);

            if (isNumeric) {

                name = rs.getString(2);
                name = (String) fmt.formatToUI(name);
                Integer numAsInt = null;
                Integer floor = null;
                try {
                    numAsInt = Integer.parseInt(name);
                    floor = Integer.parseInt(letter);

                } catch (Exception ex) {
                }

                numMin = Math.min(numMin, numAsInt);
                numMax = Math.min(numMax, numAsInt);

                if (doingIndex) {
                    int numSegment = numAsInt / 1000;
                    String c = Integer.toString(numSegment);
                    NameId nis = alphaHash.get(c);
                    if (nis == null) {
                        nis = new NameId(c, 0, numSegment);
                        alphaHash.put(c, nis);
                    }
                    nis.add();

                } else {
                    if (numAsInt >= floor && numAsInt < (floor + 1000)) {
                        alphaList.add(new NameId(name, id, numAsInt));
                    }
                }

            } else {

                name = rs.getString(2);
                if (StringUtils.isEmpty(name)) {
                    name = rs.getString(1);
                }

                if (cdi.isUseIdentityTitle()) {
                    DataProviderSessionIFace session = null;
                    try {
                        session = DataProviderFactory.getInstance().createSession();
                        FormDataObjIFace fdi = (FormDataObjIFace) session
                                .createQuery("from " + className + " where id = " + id, false).list().get(0);
                        if (fdi != null) {
                            String title = fdi.getIdentityTitle();
                            if (StringUtils.isNotEmpty(title)) {
                                name = title;
                            }
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        //log.error(ex);

                    } finally {
                        session.close();
                    }

                } else if (cdi.getIndexClass() != null) {
                    if (cdi.getIndexClass() == Calendar.class) {
                        Date date = rs.getDate(2);
                        if (date != null) {
                            name = sdf.format(date);
                        } else {
                            name = "0000";
                        }
                        useLetter = false;
                    }
                }

                int len = Math.min(numLetters, name.length());
                if (doingIndex) {
                    String c = useLetter ? name.substring(0, len).toLowerCase() : name;
                    NameId nis = alphaHash.get(c);
                    if (nis == null) {
                        nis = new NameId(c, 0);
                        alphaHash.put(c, nis);
                    }
                    nis.add();

                } else {
                    if ((useLetter && name.substring(0, len).toUpperCase().equals(letter))
                            || (!useLetter && name.equals(letter))) {
                        alphaList.add(new NameId(name, id));
                    }
                }
            }

            cnt++;
        }

        System.out.println("alphaHash.size: " + alphaHash.size());
        if (doingIndex) {
            alphaList = new Vector<NameId>(alphaHash.values());
        }

        Collections.sort(alphaList);

        System.out.println("alphaList.size: " + alphaList.size());

        if (doingIndex) {
            DBTableInfo ti = DBTableIdMgr.getInstance().getByShortClassName(className);

            out.println("<center><br/><span style=\"font-size: 14pt;\">Index For " + ti.getTitle()
                    + "</span><br/>");
            out.println("<table class=\"brdr\" border=\"0\" cellpadding=\"4\" cellspacing=\"0\">\n");
            out.println("<tr><th class=\"brdr\" align=\"center\" nowrap=\"nowrap\">Index</th>");
            out.println("<th class=\"brdr\" align=\"center\" nowrap=\"nowrap\">Count</th></tr>\n");
            int i = 0;
            for (NameId nis : alphaList) {
                String ltrStr = nis.getNum() != null ? Integer.toString(nis.getNum() * 1000)
                        : nis.getName().toUpperCase();
                out.println("<tr>");
                out.println("<td nowrap=\"nowrap\" class=\"brdr" + (((i + 1) % 2 == 0) ? "even" : "odd")
                        + "\" align=\"center\">&nbsp;&nbsp;<a href=\"" + servletURL + "?cls=" + className
                        + "&ltr=" + ltrStr + "\">" + ltrStr + "</a>&nbsp;&nbsp;</td>\n");
                out.println("<td nowrap=\"nowrap\" class=\"brdr" + (((i + 1) % 2 == 0) ? "even" : "odd")
                        + "\"  align=\"center\"><a href=\"" + servletURL + "?cls=" + className + "&ltr="
                        + ltrStr + "\">" + nis.getId() + "</a></td>\n");
                out.println("</tr>");
                i++;
            }
            out.println("</table></center>\n");
        } else {
            if (alphaList.size() > 0) {
                if (useLetter) {
                    out.println("<br/>" + alphaList.get(0).getName().charAt(0) + "<br/>\n");
                }
                out.println("<table class=\"brdr\" border=\"0\" cellpadding=\4\" cellspacing=\"0\">\n");
                int i = 1;
                for (NameId nis : alphaList) {
                    out.println("<tr>");
                    out.println("<td nowrap=\"nowrap\" class=\"brdr" + (((i + 1) % 2 == 0) ? "even" : "odd")
                            + "\" >");
                    out.println("<a href=\"" + servletURL + "?cls=" + className + "&id=" + nis.getId() + "\">"
                            + nis.getName() + "</a>");
                    out.println("</td></tr>\n");
                    i++;
                }
                out.println("</table>\n");
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    out.println(template.substring(inx + contentTag.length() + 1, template.length()));

    log.info("Done");
}

From source file:edu.ku.brc.specify.web.SpecifyExplorer.java

/**
 * @param out//from   www  .jav a 2 s.  c o m
 * @param pointsStr
 * @param sortByCE
 */
protected void createMap(final PrintWriter out, final String pointsStr, final boolean sortByCE) {
    DataProviderSessionIFace session = null;
    try {
        session = DataProviderFactory.getInstance().createSession();

        String mapTemplate = "";
        try {
            File templateFile = new File(
                    UIRegistry.getDefaultWorkingPath() + File.separator + "site/map_template.html");
            mapTemplate = FileUtils.readFileToString(templateFile);

        } catch (IOException ex) {
            ex.printStackTrace();
            out.println(ex.toString());
        }

        if (StringUtils.isEmpty(template)) {
            out.println("The template file is empty!");
        }

        int inx = mapTemplate.indexOf(contentTag);
        String subContent = mapTemplate.substring(0, inx);
        out.println(StringUtils.replace(subContent, "<!-- Title -->", "Mapping Collection Objects"));

        String[] points = StringUtils.splitPreserveAllTokens(pointsStr, ';');
        /*System.out.println("["+pointsStr+"]");
        for (int i=0;i<points.length;i++)
        {
        System.out.println("i["+i+"]Loc["+points[i]+"] CO["+points[i+1]+"]");
        i++;
        }*/

        double maxLat = Double.MIN_VALUE;
        double minLat = Double.MAX_VALUE;

        double maxLon = Double.MIN_VALUE;
        double minLon = Double.MAX_VALUE;

        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Hashtable<Locality, CollectingEvent> locToCE = new Hashtable<Locality, CollectingEvent>();

        boolean drawLines = false;

        Hashtable<CollectingEvent, CEForPoly> hash = new Hashtable<CollectingEvent, CEForPoly>();
        StringBuilder locStr = new StringBuilder();

        int locCnt = 0;
        for (int i = 0; i < points.length; i++) {
            //System.out.println("i["+i+"]Loc["+points[i]+"]");
            if (StringUtils.isEmpty(points[i])) {
                break;
            }

            //String title = "";
            Locality locality = (Locality) session.createQuery("from Locality WHERE id = " + points[i], false)
                    .list().get(0);
            if (locality != null) {
                StringBuilder sb = new StringBuilder();
                String[] colObjsIds = StringUtils.splitPreserveAllTokens(points[i + 1], ',');
                for (String id : colObjsIds) {
                    //System.out.println("co["+id+"]");
                    if (StringUtils.isNotEmpty(id)) {
                        CollectionObject co = (CollectionObject) session
                                .createQuery("from CollectionObject WHERE id = " + id, false).list().get(0);
                        if (co != null) {
                            CollectingEvent ce = co.getCollectingEvent();
                            if (ce != null) {
                                CollectingEvent colEv = locToCE.get(locality);
                                if (colEv == null) {
                                    locToCE.put(locality, ce);

                                } else if (!ce.getCollectingEventId().equals(colEv.getCollectingEventId())) {
                                    drawLines = false;
                                }
                                //sb.append("<h3>"+sdf.format(ce.getStartDate().getTime())+"</h3>");
                                Locality loc = ce.getLocality();
                                if (loc != null && loc.getLatitude1() != null && loc.getLongitude1() != null) {
                                    CEForPoly cep = hash.get(ce);
                                    if (cep == null) {
                                        cep = new CEForPoly(ce.getStartDate(), loc.getLatitude1().doubleValue(),
                                                loc.getLongitude1().doubleValue(), "");
                                        hash.put(ce, cep);
                                    }
                                    cep.getColObjs().add(co);
                                }
                            }
                            for (Determination det : co.getDeterminations()) {
                                if (det.isCurrentDet()) {
                                    Taxon txn = det.getPreferredTaxon();
                                    if (txn != null) {
                                        sb.append("<a href='SpecifyExplorer?cls=CollectionObject&id="
                                                + co.getCollectionObjectId() + "'>" + txn.getFullName()
                                                + "</a>");
                                        sb.append("<br/>");
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }

                if (locality.getLatitude1() != null && locality.getLongitude1() != null) {
                    if (locCnt == 0) {
                        maxLat = locality.getLatitude1().doubleValue();
                        minLat = maxLat;

                        maxLon = locality.getLongitude1().doubleValue();
                        minLon = maxLon;

                    } else {
                        maxLat = Math.max(maxLat, locality.getLatitude1().doubleValue());
                        minLat = Math.min(minLat, locality.getLatitude1().doubleValue());

                        maxLon = Math.max(maxLon, locality.getLongitude1().doubleValue());
                        minLon = Math.min(minLon, locality.getLongitude1().doubleValue());
                    }

                    locStr.append("var point = new GLatLng(" + locality.getLatitude1() + ","
                            + locality.getLongitude1() + ");\n");
                    locStr.append("var marker = createMarker(point,\"" + locality.getLocalityName() + "\",\""
                            + sb.toString() + "\");\n");
                    locStr.append("map.addOverlay(marker);\n");
                    locCnt++;
                }

            }
            i++;
        }

        System.out.println("maxLat: " + maxLat);
        System.out.println("minLat: " + minLat);
        System.out.println("maxLon: " + maxLon);
        System.out.println("minLon: " + minLon);

        double halfLat = (maxLat - minLat) / 2;
        double halfLon = (maxLon - minLon) / 2;
        System.out.println("halfLat: " + halfLat);
        System.out.println("halfLon: " + halfLon);

        int zoom = 2;
        if (halfLat == 0.0 && halfLon == 0.0) {
            zoom = 12;

        } else if (halfLat < 0.5 && halfLon < 0.5) {
            zoom = 10;

        } else if (halfLat < 2.0 && halfLon < 2.0) {
            zoom = 8;

        } else if (halfLat < 7.0 && halfLon < 7.0) {
            zoom = 6;
        }

        out.println("        map.setCenter(new GLatLng( " + (minLat + halfLat) + "," + (minLon + halfLon)
                + "), " + zoom + ");\n");

        out.println(locStr.toString());

        if (drawLines) {
            if (hash.size() > 0) {
                out.println("var polyline = new GPolyline([");
                for (CEForPoly cep : hash.values()) {
                    out.println("new GLatLng(" + cep.getLat() + ", " + cep.getLon() + "),\n");
                }
            }
            out.println("], \"#FF0000\", 5);\n");
            out.println("map.addOverlay(polyline);\n");

        }

        if (false) {
            out.println("var polygon = new GPolygon([");
            for (CEForPoly cep : hash.values()) {
                out.println("new GLatLng(" + cep.getLat() + ", " + cep.getLon() + "),\n");
            }
            out.println("], \"#ff0000\", 5, 0.7, \"#0000ff\", 0.4);\n");
            out.println("map.addOverlay(polygon);\n");
        }

        out.println(mapTemplate.substring(inx + contentTag.length() + 1, mapTemplate.length()));

    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        if (session != null) {
            session.close();
        }
    }
}

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();// w  w w  . j  a  v  a 2 s  .c om
        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();
}