Example usage for org.hibernate Session refresh

List of usage examples for org.hibernate Session refresh

Introduction

In this page you can find the example usage for org.hibernate Session refresh.

Prototype

void refresh(Object object);

Source Link

Document

Re-read the state of the given instance from the underlying database.

Usage

From source file:org.unitime.colleague.model.ColleagueSection.java

License:Apache License

public void updateClassSuffixForClassesIfNecessaryRefreshClasses(Session hibSession, boolean refresh) {

    CourseOffering co = this.getCourseOffering(hibSession);
    if (co == null) {
        return;// ww w .j a  va2 s. c o m
    }
    Boolean control = co.isIsControl();
    if (control.booleanValue()) {
        if (this.getColleagueSectionToClasses() == null || this.getColleagueSectionToClasses().isEmpty()
                || this.isDeleted().booleanValue()) {
            return;
        }
        for (Iterator<?> it = this.getColleagueSectionToClasses().iterator(); it.hasNext();) {
            ColleagueSectionToClass bsc = (ColleagueSectionToClass) it.next();
            Class_ clazz = Class_DAO.getInstance().get(bsc.getClassId(), hibSession);
            if (clazz != null) {
                String classSuffix = this.classSuffixFor(clazz);
                if (clazz.getClassSuffix() == null || !clazz.getClassSuffix().equals(classSuffix)) {
                    clazz.setClassSuffix(classSuffix);
                    clazz.setExternalUniqueId(this.externalUniqueIdFor(clazz, hibSession));
                    hibSession.update(clazz);
                    hibSession.flush();
                    if (refresh) {
                        hibSession.refresh(clazz);
                    }
                }
            }
        }
    }

}

From source file:org.unitime.colleague.util.ColleagueChangeAction.java

License:Apache License

public void performExternalCourseOfferingEditAction(InstructionalOffering instructionalOffering,
        Session hibSession) {
    List<ColleagueSection> sections = ColleagueSection
            .findColleagueSectionsForInstructionalOffering(instructionalOffering, hibSession);
    for (ColleagueSection colleagueSection : sections) {
        if (colleagueSection.isDeleted().booleanValue()) {
            continue;
        }//from w  w  w  . j a va  2s.c o  m
        Class_ cls = null;
        for (Class_ c1 : colleagueSection.getClasses(hibSession)) {
            cls = c1;
            break;
        }
        if (cls != null) {
            String crsNbr = (ColleagueSection
                    .calculateColleagueCourseNumber(colleagueSection.getCourseOffering(hibSession), cls));
            if (!colleagueSection.getColleagueCourseNumber().equals(crsNbr)) {
                try {
                    colleagueSection.setColleagueCourseNumber(crsNbr);
                    hibSession.update(colleagueSection);
                    hibSession.flush();
                    hibSession.refresh(colleagueSection);
                } catch (Exception e) {
                    Debug.info("failed to generate a new course number");
                    e.printStackTrace();
                }
            }
        }
        if (!colleagueSection.isSectionIndexStillValid(hibSession)) {
            try {
                colleagueSection.setSectionIndex(ColleagueSection.findNextUnusedActiveSectionIndexFor(
                        colleagueSection.getSession(), colleagueSection.getCourseOffering(hibSession),
                        colleagueSection.getFirstClass().getSchedulingSubpart().getItype(), hibSession));
                hibSession.update(colleagueSection);
                hibSession.flush();
                hibSession.refresh(colleagueSection);
                colleagueSection.updateClassSuffixForClassesIfNecessaryRefreshClasses(hibSession, true);
            } catch (Exception e) {
                Debug.info("failed to generate a new section index");
                e.printStackTrace();
            }
        }
    }
    SendColleagueMessage.sendColleagueMessage(sections, MessageAction.UPDATE, hibSession);
}

From source file:org.unitime.timetable.action.AddNonUnivLocationAction.java

License:Open Source License

/**
 * /*  w  ww  . j a va2 s.  c o  m*/
 * @param request
 * @param nonUnivLocationForm
 * @throws Exception
 */
private void update(HttpServletRequest request, NonUnivLocationForm nonUnivLocationForm) throws Exception {

    org.hibernate.Session hibSession = (new NonUniversityLocationDAO()).getSession();
    Transaction tx = null;
    try {
        tx = hibSession.beginTransaction();
        NonUniversityLocation nonUniv = new NonUniversityLocation();

        nonUniv.setSession(
                SessionDAO.getInstance().get(sessionContext.getUser().getCurrentAcademicSessionId()));

        if (nonUnivLocationForm.getName() != null
                && !nonUnivLocationForm.getName().trim().equalsIgnoreCase("")) {
            nonUniv.setName(nonUnivLocationForm.getName());
        }

        if (nonUnivLocationForm.getCapacity() != null
                && !nonUnivLocationForm.getCapacity().trim().equalsIgnoreCase("")) {
            nonUniv.setCapacity(Integer.valueOf(nonUnivLocationForm.getCapacity()));
        }

        nonUniv.setIgnoreTooFar(Boolean.valueOf(nonUnivLocationForm.isIgnoreTooFar()));
        nonUniv.setIgnoreRoomCheck(Boolean.valueOf(nonUnivLocationForm.isIgnoreRoomCheck()));

        nonUniv.setCoordinateX(
                nonUnivLocationForm.getCoordX() == null || nonUnivLocationForm.getCoordX().length() == 0 ? null
                        : Double.valueOf(nonUnivLocationForm.getCoordX()));
        nonUniv.setCoordinateY(
                nonUnivLocationForm.getCoordY() == null || nonUnivLocationForm.getCoordY().length() == 0 ? null
                        : Double.valueOf(nonUnivLocationForm.getCoordY()));

        if (nonUnivLocationForm.getExternalId() != null && !nonUnivLocationForm.getExternalId().isEmpty())
            nonUniv.setExternalUniqueId(nonUnivLocationForm.getExternalId());

        Double area = null;
        if (nonUnivLocationForm.getArea() != null && !nonUnivLocationForm.getArea().isEmpty()) {
            try {
                area = new DecimalFormat(ApplicationProperty.RoomAreaUnitsFormat.value())
                        .parse(nonUnivLocationForm.getArea()).doubleValue();
            } catch (NumberFormatException e) {
            }
        }
        nonUniv.setArea(area);

        nonUniv.setFeatures(new HashSet());
        nonUniv.setAssignments(new HashSet());
        nonUniv.setRoomGroups(new HashSet());
        nonUniv.setRoomDepts(new HashSet());
        nonUniv.setExamCapacity(0);
        nonUniv.setRoomType(RoomTypeDAO.getInstance().get(nonUnivLocationForm.getType()));

        LocationPermIdGenerator.setPermanentId(nonUniv);

        hibSession.saveOrUpdate(nonUniv);

        //set room department for location
        RoomDept rd = new RoomDept();
        rd.setRoom(nonUniv);
        rd.setControl(Boolean.TRUE);

        Department d = Department.findByDeptCode(nonUnivLocationForm.getDeptCode(),
                sessionContext.getUser().getCurrentAcademicSessionId(), hibSession);
        rd.setDepartment(d);

        hibSession.saveOrUpdate(rd);

        nonUniv.getRoomDepts().add(rd);
        hibSession.saveOrUpdate(nonUniv);

        ChangeLog.addChange(hibSession, sessionContext, (Location) nonUniv, ChangeLog.Source.ROOM_EDIT,
                ChangeLog.Operation.CREATE, null, d);

        tx.commit();

        hibSession.refresh(d);
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();
        throw e;
    }
}

From source file:org.unitime.timetable.action.AddSpecialUseRoomAction.java

License:Open Source License

/**
 * /*from   w  w  w.j  a v  a2  s  .  c om*/
 * @param request
 * @param specialUseRoomForm
 * @param mapping
 * @return
 * @throws Exception
 */
private String update(HttpServletRequest request, SpecialUseRoomForm specialUseRoomForm) throws Exception {

    ActionMessages errors = new ActionMessages();

    Long sessionId = sessionContext.getUser().getCurrentAcademicSessionId();
    Long bldgUniqueId = Long.valueOf(specialUseRoomForm.getBldgId().split("-")[0]);
    String bldgAbbv = specialUseRoomForm.getBldgId().split("-")[1];
    String roomNum = specialUseRoomForm.getRoomNum().trim();

    //check if room already exists
    Room existingRoom = Room.findByBldgIdRoomNbr(bldgUniqueId, roomNum, sessionId);
    if (existingRoom != null) {
        errors.add("specialUseRoom", new ActionMessage("errors.exists", "Room "));
        saveErrors(request, errors);
        return null;
    }

    //get room
    ExternalBuilding extBldg = ExternalBuilding.findByAbbv(sessionId, bldgAbbv);
    ExternalRoom extRoom = null;
    if (extBldg != null)
        extRoom = extBldg.findRoom(roomNum);
    if (extRoom == null) {
        errors.add("specialUseRoom", new ActionMessage("errors.invalid", "Room number "));
        saveErrors(request, errors);
        return null;
    }

    if (!sessionContext.hasPermission(extRoom, Right.AddSpecialUseRoomExternalRoom)) {
        errors.add("specialUseRoom", new ActionMessage("errors.room.ownership"));
        saveErrors(request, errors);
        return null;
    }

    org.hibernate.Session hibSession = (new RoomDAO()).getSession();
    Transaction tx = null;
    try {
        tx = hibSession.beginTransaction();
        Room room = new Room();

        room.setSession(SessionDAO.getInstance().get(sessionContext.getUser().getCurrentAcademicSessionId(),
                hibSession));
        room.setIgnoreTooFar(Boolean.FALSE);
        room.setIgnoreRoomCheck(Boolean.FALSE);
        room.setCoordinateX(extRoom.getCoordinateX());
        room.setCoordinateY(extRoom.getCoordinateY());
        room.setArea(extRoom.getArea());
        room.setCapacity(extRoom.getCapacity());
        room.setExamCapacity(0);
        room.setRoomNumber(roomNum);
        room.setRoomType(extRoom.getRoomType());
        room.setExternalUniqueId(extRoom.getExternalUniqueId());
        room.setClassification(extRoom.getClassification());
        room.setDisplayName(extRoom.getDisplayName());

        BuildingDAO bldgDAO = new BuildingDAO();
        Building bldg = bldgDAO.get(Long.valueOf(bldgUniqueId));
        room.setBuildingAbbv(bldgAbbv);
        room.setBuilding(bldg);

        room.setFeatures(new HashSet());
        room.setAssignments(new HashSet());
        room.setRoomGroups(new HashSet());
        room.setRoomDepts(new HashSet());

        LocationPermIdGenerator.setPermanentId(room);

        hibSession.saveOrUpdate(room);

        Set extRoomFeatures = extRoom.getRoomFeatures();
        if (!extRoomFeatures.isEmpty()) {
            addRoomFeatures(extRoomFeatures, room, hibSession);
            hibSession.saveOrUpdate(room);
        }

        Department dept = null;
        if (specialUseRoomForm.getDeptCode() != null && specialUseRoomForm.getDeptCode().length() > 0) {
            String deptSelected = specialUseRoomForm.getDeptCode();
            RoomDept roomdept = new RoomDept();
            roomdept.setRoom(room);
            roomdept.setControl(Boolean.TRUE);
            dept = Department.findByDeptCode(deptSelected, sessionId);
            roomdept.setDepartment(dept);
            hibSession.saveOrUpdate(roomdept);
        }

        ChangeLog.addChange(hibSession, sessionContext, (Location) room, ChangeLog.Source.ROOM_EDIT,
                ChangeLog.Operation.CREATE, null, dept);

        tx.commit();

        if (dept != null) {
            hibSession.refresh(dept);
        }
        hibSession.refresh(room);
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();
        throw e;
    }

    return ("showRoomList");
}

From source file:org.unitime.timetable.action.AssignedClassesAction.java

License:Open Source License

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    AssignedClassesForm myForm = (AssignedClassesForm) form;

    // Check Access
    sessionContext.checkPermission(Right.AssignedClasses);

    String op = (myForm.getOp() != null ? myForm.getOp() : request.getParameter("op"));

    SuggestionsModel model = (SuggestionsModel) request.getSession().getAttribute("Suggestions.model");
    if (model == null) {
        model = new SuggestionsModel();
        model.load(sessionContext.getUser());
        request.getSession().setAttribute("Suggestions.model", model);
    }/*from   ww w .j a  v a 2s  . com*/

    if ("Apply".equals(op) || "Export PDF".equals(op) || "Export CSV".equals(op)) {
        myForm.save(model);
        model.save(sessionContext.getUser());
    }
    if ("Refresh".equals(op)) {
        myForm.reset(mapping, request);
    }

    myForm.load(model);
    try {
        myForm.setSubjectAreas(new TreeSet(
                SubjectArea.getSubjectAreaList(sessionContext.getUser().getCurrentAcademicSessionId())));
    } catch (Exception e) {
    }

    if ("Apply".equals(op) || "Export PDF".equals(op) || "Export CSV".equals(op)) {
        if (myForm.getSubjectArea() == null)
            sessionContext.removeAttribute(SessionAttribute.OfferingsSubjectArea);
        else if (myForm.getSubjectArea() < 0)
            sessionContext.setAttribute(SessionAttribute.OfferingsSubjectArea, Constants.ALL_OPTION_VALUE);
        else
            sessionContext.setAttribute(SessionAttribute.OfferingsSubjectArea,
                    myForm.getSubjectArea().toString());
    } else {
        try {
            String sa = (String) sessionContext.getAttribute(SessionAttribute.OfferingsSubjectArea);
            if (Constants.ALL_OPTION_VALUE.equals(sa))
                myForm.setSubjectArea(-1l);
            else if (sa != null) {
                if (sa.indexOf(',') >= 0)
                    sa = sa.substring(0, sa.indexOf(','));
                myForm.setSubjectArea(Long.valueOf(sa));
            }
        } catch (Exception e) {
        }
    }
    if (myForm.getSubjectArea() == null && myForm.getSubjectAreas().size() == 1) {
        myForm.setSubjectArea(((SubjectArea) myForm.getSubjectAreas().iterator().next()).getUniqueId());
    }

    Vector assignedClasses = null;
    if (myForm.getSubjectArea() != null && myForm.getSubjectArea() != 0) {
        String prefix = myForm.getSubjectArea() > 0 ? myForm.getSubjectAreaAbbv() + " " : null;
        SolverProxy solver = courseTimetablingSolverService.getSolver();
        if (solver != null) {
            assignedClasses = solver.getAssignedClasses(prefix);
        } else {
            String instructorNameFormat = UserProperty.NameFormat.get(sessionContext.getUser());
            String solutionIdsStr = (String) request.getSession().getAttribute("Solver.selectedSolutionId");
            assignedClasses = new Vector();
            if (solutionIdsStr != null && solutionIdsStr.length() > 0) {
                SolutionDAO dao = new SolutionDAO();
                org.hibernate.Session hibSession = dao.getSession();
                for (StringTokenizer s = new StringTokenizer(solutionIdsStr, ","); s.hasMoreTokens();) {
                    Long solutionId = Long.valueOf(s.nextToken());
                    Solution solution = dao.get(solutionId, hibSession);
                    try {
                        for (Iterator i = solution.getAssignments().iterator(); i.hasNext();) {
                            Assignment a = (Assignment) i.next();
                            if (prefix != null && !a.getClassName().startsWith(prefix))
                                continue;
                            assignedClasses.add(new ClassAssignmentDetails(solution, a, false, hibSession,
                                    instructorNameFormat));
                        }
                    } catch (ObjectNotFoundException e) {
                        hibSession.refresh(solution);
                        for (Iterator i = solution.getAssignments().iterator(); i.hasNext();) {
                            Assignment a = (Assignment) i.next();
                            assignedClasses.add(new ClassAssignmentDetails(solution, a, false, hibSession,
                                    instructorNameFormat));
                        }
                    }
                }
            } else {
                request.setAttribute("AssignedClasses.message",
                        "Neither a solver is started nor solution is selected.");
                return mapping.findForward("showAssignedClasses");
            }
        }
    } else {
        request.setAttribute("AssignedClasses.message", "No subject area is selected.");
        return mapping.findForward("showAssignedClasses");
    }

    String assignedTable = getAssignmentTable(model.getSimpleMode(), request, "Assigned Classes",
            assignedClasses);
    if (assignedTable != null) {
        request.setAttribute("AssignedClasses.table", assignedTable);
        request.setAttribute("AssignedClasses.table.colspan", new Integer(model.getSimpleMode() ? 6 : 15));
    } else
        request.setAttribute("AssignedClasses.message", "No assigned class.");

    if ("Export PDF".equals(op)) {
        PdfWebTable table = exportPdf(model.getSimpleMode(), request, "Assigned Classes", assignedClasses);
        if (table != null) {
            ExportUtils.exportPDF(table, WebTable.getOrder(sessionContext, "assignedClasses.ord"), response,
                    "assigned");
            return null;
        }
    }
    if ("Export CSV".equals(op)) {
        PdfWebTable table = exportPdf(model.getSimpleMode(), request, "Assigned Classes", assignedClasses);
        if (table != null) {
            ExportUtils.exportCSV(table, WebTable.getOrder(sessionContext, "assignedClasses.ord"), response,
                    "assigned");
            return null;
        }
    }

    return mapping.findForward("showAssignedClasses");
}

From source file:org.unitime.timetable.action.CrossListsModifyAction.java

License:Open Source License

/**
 * Update the instructional offering// w w  w. j av a 2 s .c o m
 * @param request
 * @param frm
 */
private void doUpdate(HttpServletRequest request, CrossListsModifyForm frm) throws Exception {

    // Get the modified offering
    List ids = frm.getCourseOfferingIds();
    String courseIds = Constants.arrayToStr(ids.toArray(), "", " ");
    String origCourseIds = frm.getOriginalOfferings();

    // Get Offering
    CourseOfferingDAO cdao = new CourseOfferingDAO();
    InstructionalOfferingDAO idao = new InstructionalOfferingDAO();
    InstructionalOffering io = idao.get(frm.getInstrOfferingId());
    Session hibSession = idao.getSession();
    hibSession.setFlushMode(FlushMode.MANUAL);
    Transaction tx = null;
    HashMap saList = new HashMap();
    List<CurriculumCourse> cc = new ArrayList<CurriculumCourse>();

    try {
        tx = hibSession.beginTransaction();
        StringTokenizer strTok = new StringTokenizer(origCourseIds);

        while (strTok.hasMoreTokens()) {

            String origCrs = strTok.nextToken();

            // 1. For all deleted courses - create new offering and make 'not offered'
            if (courseIds.indexOf(origCrs) < 0) {
                Debug.debug("Course removed from offering: " + origCrs);

                // Create new instructional offering 
                InstructionalOffering io1 = new InstructionalOffering();
                CourseOffering co1 = cdao.get(new Long(origCrs.trim()));

                // Copy attributes of old instr offering - make not offered
                io1.setDemand(io.getDemand());
                io1.setLimit(io.getLimit());
                io1.setNotOffered(new Boolean(true));
                io1.setSession(io.getSession());
                io1.setByReservationOnly(io.getByReservationOnly());

                // Copy attributes of old crs offering - set controlling                   
                CourseOffering co2 = (CourseOffering) co1.clone();
                co2.setIsControl(new Boolean(true));

                for (CurriculumCourse x : (List<CurriculumCourse>) hibSession
                        .createQuery("from CurriculumCourse where course.uniqueId = :courseId")
                        .setLong("courseId", co1.getUniqueId()).list()) {
                    cc.add(x.clone(co2));
                    x.getClassification().getCourses().remove(x);
                    hibSession.delete(x);
                }

                /*                   
                                   hibSession.saveOrUpdate(io1);
                                   hibSession.flush();
                */
                // Remove from original inst offr
                Set offerings = io.getCourseOfferings();
                for (Iterator i = offerings.iterator(); i.hasNext();) {

                    CourseOffering co3 = (CourseOffering) i.next();
                    if (co3.equals(co1)) {
                        // Remove from Subject Area
                        SubjectArea sa = co3.getSubjectArea();
                        sa.getCourseOfferings().remove(co1);
                        hibSession.saveOrUpdate(sa);
                        saList.put(sa.getSubjectAreaAbbreviation(), sa);
                    }
                }

                // Delete old course offering
                io.removeCourseOffering(co1);

                Event.deleteFromEvents(hibSession, co1);
                Exam.deleteFromExams(hibSession, co1);

                String className = ApplicationProperty.ExternalActionCourseOfferingRemove.value();
                if (className != null && className.trim().length() > 0) {
                    ExternalCourseOfferingRemoveAction removeAction = (ExternalCourseOfferingRemoveAction) (Class
                            .forName(className).newInstance());
                    removeAction.performExternalCourseOfferingRemoveAction(co1, hibSession);
                }
                hibSession.delete(co1);

                //io.setCourseOfferings(offerings);

                hibSession.saveOrUpdate(io);
                hibSession.flush();

                // Add course to instructional offering
                co2.setInstructionalOffering(io1);
                io1.addTocourseOfferings(co2);

                // Update
                if (io1.getInstrOfferingPermId() == null)
                    io1.generateInstrOfferingPermId();
                hibSession.saveOrUpdate(io1);
                hibSession.flush();

                hibSession.refresh(io);
                hibSession.refresh(io1);
                className = ApplicationProperty.ExternalActionInstructionalOfferingInCrosslistAdd.value();
                if (className != null && className.trim().length() > 0) {
                    ExternalInstructionalOfferingInCrosslistAddAction addAction = (ExternalInstructionalOfferingInCrosslistAddAction) (Class
                            .forName(className).newInstance());
                    addAction.performExternalInstructionalOfferingInCrosslistAddAction(io1, hibSession);
                }
            }

            // 2. For all existing courses - update controlling attribute and reservation limits
            else {
                Debug.debug("Updating controlling course  and course reservation: " + origCrs);

                // Update controlling course attribute
                CourseOffering co = cdao.get(new Long(origCrs));
                if (frm.getCtrlCrsOfferingId().equals(co.getUniqueId()))
                    co.setIsControl(new Boolean(true));
                else
                    co.setIsControl(new Boolean(false));

                // Update course reservation
                int indx = frm.getIndex(origCrs);
                try {
                    co.setReservation(ids.size() > 1 ? Integer.valueOf(frm.getLimits(indx)) : null);
                } catch (NumberFormatException e) {
                    co.setReservation(null);
                }

                hibSession.saveOrUpdate(co);

                hibSession.flush();
                hibSession.refresh(co);
            }
        }

        // 3. For all added courses - delete all preferences and change the instr offering id  
        Vector addedOfferings = new Vector();
        StringTokenizer strTok2 = new StringTokenizer(courseIds);

        while (strTok2.hasMoreTokens()) {
            String course = strTok2.nextToken();

            // Course added to offering
            if (origCourseIds.indexOf(course) < 0) {

                Debug.debug("Course added to offering: " + course);

                CourseOffering co1 = cdao.get(new Long(course.trim()));
                InstructionalOffering io1 = co1.getInstructionalOffering();
                SubjectArea sa = io1.getControllingCourseOffering().getSubjectArea();
                Set offerings = io1.getCourseOfferings();

                // Copy course offerings
                for (Iterator i = offerings.iterator(); i.hasNext();) {
                    CourseOffering co2 = (CourseOffering) i.next();
                    SubjectArea sa2 = co2.getSubjectArea();

                    // Create a copy
                    CourseOffering co3 = (CourseOffering) co2.clone();
                    if (frm.getCtrlCrsOfferingId().equals(co2.getUniqueId()))
                        co3.setIsControl(new Boolean(true));
                    else
                        co3.setIsControl(new Boolean(false));

                    for (CurriculumCourse x : (List<CurriculumCourse>) hibSession
                            .createQuery("from CurriculumCourse where course.uniqueId = :courseId")
                            .setLong("courseId", co2.getUniqueId()).list()) {
                        cc.add(x.clone(co3));
                        x.getClassification().getCourses().remove(x);
                        hibSession.delete(x);
                    }

                    addedOfferings.addElement(co3);

                    int indx = frm.getIndex(course);
                    try {
                        co3.setReservation(Integer.valueOf(frm.getLimits(indx)));
                    } catch (NumberFormatException e) {
                        co3.setReservation(null);
                    }

                    // Remove from collection
                    //i.remove();

                    sa2.getCourseOfferings().remove(co2);
                    hibSession.saveOrUpdate(sa2);
                    saList.put(sa2.getSubjectAreaAbbreviation(), sa2);

                    // Delete course offering
                    io1.removeCourseOffering(co2);
                    Event.deleteFromEvents(hibSession, co2);
                    Exam.deleteFromExams(hibSession, co2);
                    String className = ApplicationProperty.ExternalActionCourseOfferingRemove.value();
                    if (className != null && className.trim().length() > 0) {
                        ExternalCourseOfferingRemoveAction removeAction = (ExternalCourseOfferingRemoveAction) (Class
                                .forName(className).newInstance());
                        removeAction.performExternalCourseOfferingRemoveAction(co2, hibSession);
                    }

                    hibSession.delete(co2);
                    hibSession.flush();

                    //hibSession.refresh(sa2);

                }

                //io1.setCourseOfferings(offerings);
                //hibSession.saveOrUpdate(io1);
                Event.deleteFromEvents(hibSession, io1);
                Exam.deleteFromExams(hibSession, io1);

                hibSession.delete(io1);
                hibSession.flush();

                hibSession.saveOrUpdate(sa);
                saList.put(sa.getSubjectAreaAbbreviation(), sa);

                //hibSession.refresh(sa);

            }
        }

        hibSession.flush();

        // Update Offering - Added Offerings       
        for (int i = 0; i < addedOfferings.size(); i++) {
            CourseOffering co3 = (CourseOffering) addedOfferings.elementAt(i);
            co3.setInstructionalOffering(io);
            io.addTocourseOfferings(co3);
            hibSession.saveOrUpdate(co3);

            hibSession.flush();
            hibSession.refresh(co3);

            hibSession.saveOrUpdate(io);
        }
        for (CurriculumCourse x : cc)
            hibSession.saveOrUpdate(x);

        // Update managing department on all classes
        Department dept = io.getControllingCourseOffering().getDepartment();
        Set cfgs = io.getInstrOfferingConfigs();
        for (Iterator iterCfg = cfgs.iterator(); iterCfg.hasNext();) {
            InstrOfferingConfig cfg = (InstrOfferingConfig) iterCfg.next();
            Set subparts = cfg.getSchedulingSubparts();
            for (Iterator iterSbp = subparts.iterator(); iterSbp.hasNext();) {
                SchedulingSubpart subpart = (SchedulingSubpart) iterSbp.next();
                Set classes = subpart.getClasses();
                for (Iterator iterCls = classes.iterator(); iterCls.hasNext();) {
                    Class_ cls = (Class_) iterCls.next();
                    // Only change departmental class managing dept and not externally managed
                    if (!cls.getManagingDept().isExternalManager()) {
                        cls.setManagingDept(dept);
                        hibSession.saveOrUpdate(cls);
                    }
                }
            }
        }

        ChangeLog.addChange(hibSession, sessionContext, io, ChangeLog.Source.CROSS_LIST,
                ChangeLog.Operation.UPDATE, io.getControllingCourseOffering().getSubjectArea(), null);

        tx.commit();
        hibSession.flush();
        hibSession.clear();
        hibSession.refresh(io);

        // Refresh objects
        for (Iterator i1 = io.getInstrOfferingConfigs().iterator(); i1.hasNext();) {
            InstrOfferingConfig cfg = (InstrOfferingConfig) i1.next();
            for (Iterator i2 = cfg.getSchedulingSubparts().iterator(); i2.hasNext();) {
                SchedulingSubpart ss = (SchedulingSubpart) i2.next();
                for (Iterator i3 = ss.getClasses().iterator(); i3.hasNext();) {
                    Class_ c = (Class_) i3.next();
                    hibSession.refresh(c);
                }
                hibSession.refresh(ss);
            }
        }

        Set keys = saList.keySet();
        for (Iterator i1 = keys.iterator(); i1.hasNext();) {
            hibSession.refresh(saList.get(i1.next()));
        }
        String className = ApplicationProperty.ExternalActionCourseCrosslist.value();
        if (className != null && className.trim().length() > 0) {
            ExternalCourseCrosslistAction addAction = (ExternalCourseCrosslistAction) (Class.forName(className)
                    .newInstance());
            addAction.performExternalCourseCrosslistAction(io, hibSession);
        }

    } catch (Exception e) {
        Debug.error(e);
        try {
            if (tx != null && tx.isActive())
                tx.rollback();
        } catch (Exception e1) {
        }
        throw e;
    }
}

From source file:org.unitime.timetable.action.DatePatternEditAction.java

License:Open Source License

/** 
 * Method execute/*from ww  w .  j  a v a2  s.  c om*/
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return ActionForward
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    try {
        DatePatternEditForm myForm = (DatePatternEditForm) form;

        sessionContext.checkPermission(Right.DatePatterns);

        // Read operation to be performed
        String op = (myForm.getOp() != null ? myForm.getOp() : request.getParameter("op"));

        if (request.getParameterValues("depts") != null) {
            String[] depts = request.getParameterValues("depts");
            for (int i = 0; i < depts.length; i++)
                myForm.getDepartmentIds().add(new Long(depts[i]));
        }

        if (request.getParameterValues("prnts") != null) {
            String[] prnts = request.getParameterValues("prnts");
            for (int i = 0; i < prnts.length; i++) {
                myForm.getParentIds().add(new Long(prnts[i]));
            }
        }

        if (op == null) {
            myForm.load(null);
            myForm.setOp("List");
        }

        request.setAttribute(DatePattern.DATE_PATTERN_PARENT_LIST_ATTR,
                DatePattern.findAllParents(sessionContext.getUser().getCurrentAcademicSessionId()));

        List list = (new DepartmentDAO()).getSession().createCriteria(Department.class)
                .add(Restrictions.eq("session.uniqueId",
                        sessionContext.getUser().getCurrentAcademicSessionId()))
                .addOrder(Order.asc("deptCode")).list();
        Vector availableDepts = new Vector();
        for (Iterator iter = list.iterator(); iter.hasNext();) {
            Department d = (Department) iter.next();
            availableDepts
                    .add(new LabelValueBean(d.getDeptCode() + "-" + d.getName(), d.getUniqueId().toString()));
        }
        request.setAttribute(Department.DEPT_ATTR_NAME, availableDepts);

        // Reset Form
        if ("Back".equals(op)) {
            if (myForm.getUniqueId() != null)
                request.setAttribute("hash", myForm.getUniqueId());
            myForm.load(null);
            myForm.setOp("List");
        }

        if ("Add Date Pattern".equals(op)) {
            myForm.load(null);
            myForm.setSessionId(sessionContext.getUser().getCurrentAcademicSessionId());
            myForm.setOp("Save");
        }

        if ("Add Department".equals(op)) {
            ActionMessages errors = new ActionErrors();
            if (myForm.getDepartmentId() == null || myForm.getDepartmentId().longValue() < 0)
                errors.add("department", new ActionMessage("errors.generic", "No department selected."));
            else {
                boolean contains = myForm.getDepartmentIds().contains(myForm.getDepartmentId());
                if (contains)
                    errors.add("department", new ActionMessage("errors.generic",
                            "Department already present in the list of departments."));
            }
            if (errors.size() > 0) {
                saveErrors(request, errors);
            } else {
                myForm.getDepartmentIds().add(myForm.getDepartmentId());
            }
            myForm.setOp(myForm.getUniqueId().longValue() < 0 ? "Save" : "Update");
        }

        if ("Add Pattern Set".equals(op)) {
            ActionMessages errors = new ActionErrors();
            if (myForm.getParentId() == null || myForm.getParentId().longValue() < 0)
                errors.add("parent", new ActionMessage("errors.generic", "No date pattern selected."));
            else {
                boolean contains = myForm.getParentIds().contains(myForm.getParentId());
                if (contains)
                    errors.add("parent", new ActionMessage("errors.generic",
                            "Date pattern already present in the list of alternative pattern sets."));
            }
            if (errors.size() > 0) {
                saveErrors(request, errors);
            } else {
                myForm.getParentIds().add(myForm.getParentId());
            }
            myForm.setOp(myForm.getUniqueId().longValue() < 0 ? "Save" : "Update");
        }

        if ("Remove Department".equals(op)) {
            ActionMessages errors = new ActionErrors();
            if (myForm.getDepartmentId() == null || myForm.getDepartmentId().longValue() < 0)
                errors.add("department", new ActionMessage("errors.generic", "No department selected."));
            else {
                boolean contains = myForm.getDepartmentIds().contains(myForm.getDepartmentId());
                if (!contains)
                    errors.add("department", new ActionMessage("errors.generic",
                            "Department not present in the list of departments."));
            }
            if (errors.size() > 0) {
                saveErrors(request, errors);
            } else {
                myForm.getDepartmentIds().remove(myForm.getDepartmentId());
            }
            myForm.setOp(myForm.getUniqueId().longValue() < 0 ? "Save" : "Update");
        }

        if ("Remove Pattern Set".equals(op)) {
            ActionMessages errors = new ActionErrors();
            if (myForm.getParentId() == null || myForm.getParentId().longValue() < 0)
                errors.add("parent", new ActionMessage("errors.generic", "No date pattern selected."));
            else {
                boolean contains = myForm.getParentIds().contains(myForm.getParentId());
                if (!contains)
                    errors.add("parent", new ActionMessage("errors.generic",
                            "Date pattern not present in the list of alternative pattern sets."));
            }
            if (errors.size() > 0) {
                saveErrors(request, errors);
            } else {
                myForm.getParentIds().remove(myForm.getParentId());
            }
            myForm.setOp(myForm.getUniqueId().longValue() < 0 ? "Save" : "Update");
        }

        // Add / Update
        if ("Update".equals(op) || "Save".equals(op) || "Make Default".equals(op)) {
            // Validate input
            ActionMessages errors = myForm.validate(mapping, request);
            if (errors.size() > 0) {
                saveErrors(request, errors);
                myForm.setOp(myForm.getUniqueId().longValue() < 0 ? "Save" : "Update");
            } else {
                Transaction tx = null;

                try {
                    org.hibernate.Session hibSession = (new TimePatternDAO()).getSession();
                    if (hibSession.getTransaction() == null || !hibSession.getTransaction().isActive())
                        tx = hibSession.beginTransaction();

                    DatePattern dp = myForm.saveOrUpdate(request, hibSession);
                    if ("Make Default".equals(op)) {
                        dp.getSession().setDefaultDatePattern(dp);
                        hibSession.saveOrUpdate(dp.getSession());
                        myForm.setIsDefault(true);
                    }

                    ChangeLog.addChange(hibSession, sessionContext, dp, ChangeLog.Source.DATE_PATTERN_EDIT,
                            ("Save".equals(op) ? ChangeLog.Operation.CREATE : ChangeLog.Operation.UPDATE), null,
                            null);

                    if (tx != null)
                        tx.commit();
                } catch (Exception e) {
                    if (tx != null)
                        tx.rollback();
                    throw e;
                }

                myForm.setOp("List");
                if (myForm.getUniqueId() != null)
                    request.setAttribute("hash", myForm.getUniqueId());
            }
        }

        // Edit
        if ("Edit".equals(op)) {
            String id = request.getParameter("id");
            ActionMessages errors = new ActionMessages();
            if (id == null || id.trim().length() == 0) {
                errors.add("key", new ActionMessage("errors.invalid", "Unique Id : " + id));
                saveErrors(request, errors);
                request.setAttribute("DatePatterns.pattern",
                        myForm.getDatePattern(request).getPatternHtml(true, myForm.getUniqueId()));
                return mapping.findForward("list");
            } else {
                DatePattern pattern = (new DatePatternDAO()).get(new Long(id));

                if (pattern == null) {
                    errors.add("name", new ActionMessage("errors.invalid", "Unique Id : " + id));
                    saveErrors(request, errors);
                    request.setAttribute("DatePatterns.pattern",
                            myForm.getDatePattern(request).getPatternHtml(true, myForm.getUniqueId()));
                    return mapping.findForward("list");
                } else {
                    myForm.load(pattern);
                }
            }
        }

        // Delete 
        if ("Delete".equals(op)) {
            Transaction tx = null;

            try {
                org.hibernate.Session hibSession = (new TimePatternDAO()).getSession();
                if (hibSession.getTransaction() == null || !hibSession.getTransaction().isActive())
                    tx = hibSession.beginTransaction();

                DatePattern dp = (new DatePatternDAO()).get(myForm.getUniqueId(), hibSession);
                ChangeLog.addChange(hibSession, sessionContext, dp, ChangeLog.Source.DATE_PATTERN_EDIT,
                        ChangeLog.Operation.DELETE, null, null);

                myForm.delete(hibSession);

                tx.commit();
            } catch (Exception e) {
                if (tx != null)
                    tx.rollback();
                throw e;
            }

            myForm.load(null);
            myForm.setOp("List");
        }

        if ("Fix Generated".equals(op)) {
            Transaction tx = null;

            PrintWriter out = null;

            try {
                org.hibernate.Session hibSession = (new TimePatternDAO()).getSession();
                if (hibSession.getTransaction() == null || !hibSession.getTransaction().isActive())
                    tx = hibSession.beginTransaction();

                File file = ApplicationProperties.getTempFile("fix", "txt");
                out = new PrintWriter(new FileWriter(file));

                List<DatePattern> allDatePatterns = DatePattern
                        .findAll(sessionContext.getUser().getCurrentAcademicSessionId(), true, null, null);
                for (DatePattern dp : allDatePatterns) {
                    if (!dp.getName().startsWith("generated"))
                        continue;

                    out.println("Checking " + dp.getName() + " ...");

                    List classes = hibSession.createQuery(
                            "select distinct c from Class_ as c inner join c.datePattern as dp where dp.uniqueId=:uniqueId")
                            .setLong("uniqueId", dp.getUniqueId().longValue()).list();

                    List subparts = hibSession.createQuery(
                            "select distinct s from SchedulingSubpart as s inner join s.datePattern as dp where dp.uniqueId=:uniqueId")
                            .setLong("uniqueId", dp.getUniqueId().longValue()).list();

                    Vector allClasses = new Vector(classes);

                    for (Iterator j = subparts.iterator(); j.hasNext();) {
                        SchedulingSubpart s = (SchedulingSubpart) j.next();
                        for (Iterator k = s.getClasses().iterator(); k.hasNext();) {
                            Class_ c = (Class_) k.next();
                            if (c.getDatePattern() == null)
                                allClasses.add(c);
                        }
                    }

                    if (allClasses.isEmpty()) {
                        out.println("  -- date pattern is not used -> delete");
                        for (Iterator j = dp.getDepartments().iterator(); j.hasNext();) {
                            Department d = (Department) j.next();
                            d.getDatePatterns().remove(dp);
                            hibSession.saveOrUpdate(d);
                        }
                        ChangeLog.addChange(hibSession, sessionContext, dp, ChangeLog.Source.DATE_PATTERN_EDIT,
                                ChangeLog.Operation.DELETE, null, null);
                        hibSession.delete(dp);
                        continue;
                    }

                    for (Iterator j = allClasses.iterator(); j.hasNext();) {
                        Class_ clazz = (Class_) j.next();
                        out.println("  -- used by " + clazz.getClassLabel());
                    }

                    TreeSet days = dp.getUsage(allClasses);

                    out.println("    -- " + days);
                    if (days.isEmpty()) {
                        int offset = dp.getPatternOffset();
                        for (int x = 0; x < dp.getPattern().length(); x++) {
                            if (dp.getPattern().charAt(x) != '1')
                                continue;
                            days.add(new Integer(x + offset));
                        }
                    }

                    DatePattern likeDp = null;
                    int likeDiff = 0;

                    for (Iterator j = allDatePatterns.iterator(); j.hasNext();) {
                        DatePattern xdp = (DatePattern) j.next();
                        if (xdp.getName().startsWith("generated"))
                            continue;
                        TreeSet xdays = xdp.getUsage(allClasses);
                        if (xdays.isEmpty()) {
                            int offset = xdp.getPatternOffset();
                            for (int x = 0; x < xdp.getPattern().length(); x++) {
                                if (xdp.getPattern().charAt(x) != '1')
                                    continue;
                                xdays.add(new Integer(x + offset));
                            }
                        }

                        int diff = diff(days, xdays);
                        if (likeDp == null || likeDiff > diff || (likeDiff == diff && xdp.isDefault())) {
                            likeDp = xdp;
                            likeDiff = diff;
                        }
                    }

                    if (likeDp != null) {
                        if (likeDiff <= 5) {
                            out.println("      -- like " + likeDp.getName() + ", diff=" + likeDiff);
                            out.println("      -- " + likeDp.getUsage(allClasses));
                            out.println("    -- transfering all classes and subparts from " + dp.getName()
                                    + " to " + likeDp.getName());
                            for (Iterator j = classes.iterator(); j.hasNext();) {
                                Class_ clazz = (Class_) j.next();
                                clazz.setDatePattern(likeDp.isDefault() ? null : likeDp);
                                hibSession.saveOrUpdate(clazz);
                            }
                            for (Iterator j = subparts.iterator(); j.hasNext();) {
                                SchedulingSubpart subpart = (SchedulingSubpart) j.next();
                                subpart.setDatePattern(likeDp.isDefault() ? null : likeDp);
                                hibSession.saveOrUpdate(subpart);
                            }
                            out.println("    -- deleting date pattern " + dp.getName());
                            for (Iterator j = dp.getDepartments().iterator(); j.hasNext();) {
                                Department d = (Department) j.next();
                                d.getDatePatterns().remove(dp);
                                hibSession.saveOrUpdate(d);
                            }
                            ChangeLog.addChange(hibSession, sessionContext, dp,
                                    ChangeLog.Source.DATE_PATTERN_EDIT, ChangeLog.Operation.DELETE, null, null);
                            hibSession.delete(dp);
                        } else {
                            out.println("      -- like " + likeDp.getName() + ", diff=" + likeDiff);
                            out.println("      -- " + likeDp.getUsage(allClasses));
                            Formats.Format<Date> sdf = Formats.getDateFormat(Formats.Pattern.DATE_EVENT_SHORT);
                            dp.setName("generated " + sdf.format(dp.getStartDate()) + " - "
                                    + sdf.format(dp.getEndDate()));
                            hibSession.saveOrUpdate(dp);
                        }
                    }
                }

                out.flush();
                out.close();
                out = null;
                request.setAttribute(Constants.REQUEST_OPEN_URL, "temp/" + file.getName());

                tx.commit();
            } catch (Exception e) {
                if (tx != null)
                    tx.rollback();
                throw e;
            } finally {
                if (out != null)
                    out.close();
            }

            myForm.load(null);
            myForm.setOp("List");
        }

        if ("Generate SQL".equals(op)) {
            PrintWriter out = ExportUtils.getPlainTextWriter(response, "tp.sql");
            try {
                TreeSet patterns = new TreeSet(DatePattern.findAll(sessionContext.getUser(), null, null));

                boolean mysql = false;

                int line = 0;
                if (mysql) {
                    out.println(
                            "INSERT INTO `timetable`.`date_pattern`(`uniqueid`, `name`, `pattern`, `offset`, `type`, `visible`, `session_id`)");
                } else {
                    out.println("prompt Loading DATE_PATTERN...");
                }
                for (Iterator i = patterns.iterator(); i.hasNext();) {
                    DatePattern dp = (DatePattern) i.next();

                    if (dp.getType() == DatePattern.sTypeExtended)
                        continue;
                    if (!dp.isVisible())
                        continue;

                    if (mysql) {
                        if (line == 0)
                            out.print("VALUES");
                        else
                            out.println(",");

                        out.print(" (" + dp.getUniqueId() + ", '" + dp.getName() + "', '" + dp.getPattern()
                                + "', " + dp.getOffset() + ", " + dp.getType() + ", "
                                + (dp.isVisible() ? "1" : "0") + ", "
                                + sessionContext.getUser().getCurrentAcademicSessionId() + ")");
                    } else {
                        out.println(
                                "insert into DATE_PATTERN (UNIQUEID, NAME, PATTERN, OFFSET, TYPE, VISIBLE, SESSION_ID)");
                        out.println("values (" + dp.getUniqueId() + ", '" + dp.getName() + "', '"
                                + dp.getPattern() + "', " + dp.getOffset() + ", " + dp.getType() + ", "
                                + (dp.isVisible() ? "1" : "0") + ", "
                                + sessionContext.getUser().getCurrentAcademicSessionId() + ");");
                    }

                    line++;
                }
                if (mysql) {
                    out.println(";");
                } else {
                    out.println("commit;");
                    out.println("prompt " + line + " records loaded");
                }

                out.println();

                out.flush();
                out.close();
                out = null;
            } catch (Exception e) {
                throw e;
            } finally {
                if (out != null)
                    out.close();
            }

            return null;
        }

        if ("Push Up".equals(op)) {
            Transaction tx = null;

            PrintWriter out = null;

            try {
                org.hibernate.Session hibSession = (new TimePatternDAO()).getSession();
                if (hibSession.getTransaction() == null || !hibSession.getTransaction().isActive())
                    tx = hibSession.beginTransaction();

                File file = ApplicationProperties.getTempFile("push", "txt");
                out = new PrintWriter(new FileWriter(file));

                List subparts = hibSession.createQuery(
                        "select distinct c.schedulingSubpart from Class_ as c inner join c.datePattern as dp where dp.session.uniqueId=:sessionId")
                        .setLong("sessionId", sessionContext.getUser().getCurrentAcademicSessionId()).list();

                for (Iterator i = subparts.iterator(); i.hasNext();) {
                    SchedulingSubpart subpart = (SchedulingSubpart) i.next();

                    out.println("Checking " + subpart.getSchedulingSubpartLabel() + " ...");

                    boolean sameDatePattern = true;
                    DatePattern dp = null;

                    for (Iterator j = subpart.getClasses().iterator(); j.hasNext();) {
                        Class_ clazz = (Class_) j.next();
                        if (clazz.getDatePattern() == null) {
                            sameDatePattern = false;
                            break;
                        }
                        if (dp == null)
                            dp = clazz.getDatePattern();
                        else if (!dp.equals(clazz.getDatePattern())) {
                            sameDatePattern = false;
                            break;
                        }
                    }

                    if (!sameDatePattern)
                        continue;

                    out.println("  -- all classes share same date pattern " + dp.getName()
                            + " --> pushing it to subpart");

                    for (Iterator j = subpart.getClasses().iterator(); j.hasNext();) {
                        Class_ clazz = (Class_) j.next();
                        clazz.setDatePattern(null);
                        hibSession.saveOrUpdate(clazz);
                    }
                    subpart.setDatePattern(dp.isDefault() ? null : dp);
                    hibSession.saveOrUpdate(subpart);
                }

                out.flush();
                out.close();
                out = null;
                request.setAttribute(Constants.REQUEST_OPEN_URL, "temp/" + file.getName());

                tx.commit();
            } catch (Exception e) {
                if (tx != null)
                    tx.rollback();
                throw e;
            } finally {
                if (out != null)
                    out.close();
            }

            myForm.load(null);
            myForm.setOp("List");
        }

        if ("Assign Departments".equals(op)) {
            Transaction tx = null;

            PrintWriter out = null;
            HashSet refresh = new HashSet();

            try {
                org.hibernate.Session hibSession = (new TimePatternDAO()).getSession();
                if (hibSession.getTransaction() == null || !hibSession.getTransaction().isActive())
                    tx = hibSession.beginTransaction();

                File file = ApplicationProperties.getTempFile("assigndept", "txt");
                out = new PrintWriter(new FileWriter(file));

                TreeSet allDatePatterns = new TreeSet(DatePattern
                        .findAll(sessionContext.getUser().getCurrentAcademicSessionId(), true, null, null));
                for (Iterator i = allDatePatterns.iterator(); i.hasNext();) {
                    DatePattern dp = (DatePattern) i.next();

                    if (dp.getType().intValue() != DatePattern.sTypeExtended)
                        continue;

                    out.println("Checking " + dp.getName() + " ...");

                    List classes = hibSession.createQuery(
                            "select distinct c from Class_ as c inner join c.datePattern as dp where dp.uniqueId=:uniqueId")
                            .setLong("uniqueId", dp.getUniqueId().longValue()).list();

                    List subparts = hibSession.createQuery(
                            "select distinct s from SchedulingSubpart as s inner join s.datePattern as dp where dp.uniqueId=:uniqueId")
                            .setLong("uniqueId", dp.getUniqueId().longValue()).list();

                    HashSet depts = new HashSet();

                    for (Iterator j = classes.iterator(); j.hasNext();) {
                        Class_ c = (Class_) j.next();
                        depts.add(c.getManagingDept());
                    }

                    for (Iterator j = subparts.iterator(); j.hasNext();) {
                        SchedulingSubpart s = (SchedulingSubpart) j.next();
                        depts.add(s.getManagingDept());
                    }

                    out.println("  -- departments: " + depts);

                    boolean added = false;
                    for (Iterator j = depts.iterator(); j.hasNext();) {
                        Department d = (Department) j.next();
                        if (d.isExternalManager().booleanValue()) {
                            /*
                            if (dp.getDepartments().contains(d)) {
                               dp.getDepartments().remove(d);
                               d.getDatePatterns().remove(dp);
                               hibSession.saveOrUpdate(d);
                                out.println("    -- department "+d+" removed from "+dp.getName());
                                added=true;
                            }*/
                            continue;
                        }
                        if (!dp.getDepartments().contains(d)) {
                            dp.getDepartments().add(d);
                            d.getDatePatterns().add(dp);
                            hibSession.saveOrUpdate(d);
                            out.println("    -- department " + d + " added to " + dp.getName());
                            added = true;
                        }
                    }
                    if (added) {
                        hibSession.saveOrUpdate(dp);
                        ChangeLog.addChange(hibSession, sessionContext, dp, ChangeLog.Source.DATE_PATTERN_EDIT,
                                ChangeLog.Operation.UPDATE, null, null);
                        refresh.add(dp);
                    }
                }

                out.flush();
                out.close();
                out = null;
                request.setAttribute(Constants.REQUEST_OPEN_URL, "temp/" + file.getName());

                tx.commit();

                for (Iterator i = refresh.iterator(); i.hasNext();) {
                    hibSession.refresh(i.next());
                }

            } catch (Exception e) {
                if (tx != null)
                    tx.rollback();
                throw e;
            } finally {
                if (out != null)
                    out.close();
            }

            myForm.load(null);
            myForm.setOp("List");
        }

        if ("Export CSV".equals(op)) {
            Transaction tx = null;

            try {
                org.hibernate.Session hibSession = (new TimePatternDAO()).getSession();
                if (hibSession.getTransaction() == null || !hibSession.getTransaction().isActive())
                    tx = hibSession.beginTransaction();

                CSVFile csv = new CSVFile();
                csv.setHeader(new CSVFile.CSVField[] { new CSVFile.CSVField("Name"),
                        new CSVFile.CSVField("Type"), new CSVFile.CSVField("NrDays"),
                        new CSVFile.CSVField("From"), new CSVFile.CSVField("To"), new CSVFile.CSVField("Dates"),
                        new CSVFile.CSVField("Parent"), new CSVFile.CSVField("Departments"),
                        new CSVFile.CSVField("Classes") });

                Formats.Format<Date> sdf = Formats.getDateFormat(Formats.Pattern.DATE_EVENT_SHORT);
                TreeSet allDatePatterns = new TreeSet(DatePattern
                        .findAll(sessionContext.getUser().getCurrentAcademicSessionId(), true, null, null));
                for (Iterator i = allDatePatterns.iterator(); i.hasNext();) {
                    DatePattern dp = (DatePattern) i.next();

                    List classes = hibSession.createQuery(
                            "select distinct c from Class_ as c inner join c.datePattern as dp where dp.uniqueId=:uniqueId")
                            .setLong("uniqueId", dp.getUniqueId().longValue()).list();

                    List subparts = hibSession.createQuery(
                            "select distinct s from SchedulingSubpart as s inner join s.datePattern as dp where dp.uniqueId=:uniqueId")
                            .setLong("uniqueId", dp.getUniqueId().longValue()).list();

                    TreeSet allClasses = new TreeSet(new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY));
                    allClasses.addAll(classes);

                    for (Iterator j = subparts.iterator(); j.hasNext();) {
                        SchedulingSubpart s = (SchedulingSubpart) j.next();
                        for (Iterator k = s.getClasses().iterator(); k.hasNext();) {
                            Class_ c = (Class_) k.next();
                            if (c.getDatePattern() == null)
                                allClasses.add(c);
                        }
                    }

                    String deptStr = "";
                    TreeSet depts = new TreeSet(dp.getDepartments());
                    for (Iterator j = depts.iterator(); j.hasNext();) {
                        Department d = (Department) j.next();
                        deptStr += d.getShortLabel().trim();
                        if (j.hasNext()) {
                            deptStr += ", ";
                        }
                    }

                    String classStr = "";
                    for (Iterator j = allClasses.iterator(); j.hasNext();) {
                        Class_ clazz = (Class_) j.next();
                        classStr += clazz.getClassLabel();
                        if (j.hasNext()) {
                            classStr += ", ";
                        }
                    }

                    String datePattStr = "";
                    for (Iterator j = dp.getParents().iterator(); j.hasNext();) {
                        DatePattern d = (DatePattern) j.next();
                        datePattStr += d.getName();
                        if (j.hasNext()) {
                            datePattStr += ", ";
                        }
                    }

                    csv.addLine(new CSVFile.CSVField[] { new CSVFile.CSVField(dp.getName()),
                            new CSVFile.CSVField(DatePattern.sTypes[dp.getType().intValue()]),
                            new CSVFile.CSVField(String.valueOf(dp.size())),
                            new CSVFile.CSVField(sdf.format(dp.getStartDate())),
                            new CSVFile.CSVField(sdf.format(dp.getEndDate())),
                            new CSVFile.CSVField(dp.getPatternString()), new CSVFile.CSVField(datePattStr),
                            new CSVFile.CSVField(deptStr), new CSVFile.CSVField(classStr) });

                    /*
                    System.out.println(
                    "insert into date_pattern (uniqueid, name, pattern, offset, type, visible, session_id) values (" +
                    "DATE_PATTERN_SEQ.Nextval, "+
                    "'"+dp.getName()+"', "+
                    "'"+dp.getPattern()+"', "+
                    dp.getOffset()+", "+
                    dp.getType()+", "+
                    (dp.isVisible().booleanValue()?1:0)+", "+
                    dp.getSession().getUniqueId()+");");
                    */
                }

                ExportUtils.exportCSV(csv, response, "datePatterns");
                tx.commit();
                return null;
            } catch (Exception e) {
                if (tx != null)
                    tx.rollback();
                throw e;
            }
        }

        if ("List".equals(myForm.getOp())) {
            // Read all existing settings and store in request
            getDatePatterns(request);
            return mapping.findForward("list");
        }

        request.setAttribute("DatePatterns.pattern",
                myForm.getDatePattern(request).getPatternHtml(true, myForm.getUniqueId()));
        return mapping.findForward(myForm.getUniqueId().longValue() < 0 ? "add" : "edit");

    } catch (Exception e) {
        Debug.error(e);
        throw e;
    }
}

From source file:org.unitime.timetable.action.DesignatorEditAction.java

License:Open Source License

/**
 * @param request/*from  ww w . j av a 2s  . com*/
 * @param frm
 */
private void doSaveOrUpdate(HttpServletRequest request, DesignatorEditForm frm, MessageResources rsc, String op)
        throws Exception {

    org.hibernate.Session hibSession = null;
    Transaction tx = null;

    try {
        DesignatorDAO ddao = new DesignatorDAO();
        SubjectAreaDAO sdao = new SubjectAreaDAO();
        DepartmentalInstructorDAO didao = new DepartmentalInstructorDAO();

        hibSession = ddao.getSession();
        tx = hibSession.beginTransaction();

        SubjectArea sa = sdao.get(frm.getSubjectAreaId());
        DepartmentalInstructor di = didao.get(frm.getInstructorId());

        Designator d = null;
        if (op.equals(rsc.getMessage("button.saveDesignator"))) {
            d = new Designator();
        } else {
            d = ddao.get(frm.getUniqueId());
        }

        d.setInstructor(di);
        d.setSubjectArea(sa);
        d.setCode(frm.getCode().trim());

        di.addTodesignatorSubjectAreas(d);
        sa.addTodesignatorInstructors(d);

        hibSession.saveOrUpdate(d);
        hibSession.saveOrUpdate(di);
        hibSession.saveOrUpdate(sa);

        ChangeLog.addChange(hibSession, request, di, d.toString(), ChangeLog.Source.DESIGNATOR_EDIT,
                (op.equals(rsc.getMessage("button.saveDesignator")) ? ChangeLog.Operation.CREATE
                        : ChangeLog.Operation.UPDATE),
                sa, sa.getDepartment());

        hibSession.flush();
        tx.commit();

        hibSession.refresh(d);
        hibSession.refresh(di);
        hibSession.refresh(sa);
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();
        Debug.error(e);
        throw (e);
    }
}

From source file:org.unitime.timetable.action.DesignatorEditAction.java

License:Open Source License

/**
* @param request/*from   w  ww.j a  v a2s.  c o m*/
* @param frm
*/
private void doDelete(HttpServletRequest request, DesignatorEditForm frm) throws Exception {

    org.hibernate.Session hibSession = null;
    Transaction tx = null;

    try {
        DesignatorDAO ddao = new DesignatorDAO();
        hibSession = ddao.getSession();
        tx = hibSession.beginTransaction();

        Designator d = ddao.get(frm.getUniqueId());
        SubjectArea sa = d.getSubjectArea();
        DepartmentalInstructor di = d.getInstructor();

        sa.getDesignatorInstructors().remove(d);
        di.getDesignatorSubjectAreas().remove(d);

        hibSession.saveOrUpdate(di);
        hibSession.saveOrUpdate(sa);

        ChangeLog.addChange(hibSession, request, di, d.toString(), ChangeLog.Source.DESIGNATOR_EDIT,
                ChangeLog.Operation.DELETE, sa, sa.getDepartment());

        hibSession.delete(d);

        hibSession.flush();

        tx.commit();

        hibSession.refresh(di);
        hibSession.refresh(sa);
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();
        Debug.error(e);
        throw (e);
    }
}

From source file:org.unitime.timetable.action.DistributionPrefsAction.java

License:Open Source License

/**
 * Add new distribution pref/*from w ww  .  j av  a2 s. c o m*/
 * @param httpSession
 * @param frm
 */
private void doAddOrUpdate(HttpServletRequest request, DistributionPrefsForm frm) throws Exception {

    String distPrefId = frm.getDistPrefId();
    List saList = frm.getSubjectArea();
    List suList = frm.getItype();
    List clList = frm.getClassNumber();

    // Create distribution preference
    DistributionPref dp = null;
    Department oldOwner = null;
    DistributionPrefDAO dpDao = new DistributionPrefDAO();
    Transaction tx = null;
    org.hibernate.Session hibSession = dpDao.getSession();
    HashSet relatedInstructionalOfferings = new HashSet();

    try {
        tx = hibSession.beginTransaction();

        if (distPrefId != null && distPrefId.trim().length() > 0) {
            Long distPrefUid = new Long(distPrefId);
            if (distPrefUid.longValue() > 0) {
                dp = dpDao.get(distPrefUid, hibSession);
                Set s = dp.getDistributionObjects();
                for (Iterator i = s.iterator(); i.hasNext();) {
                    DistributionObject dObj = (DistributionObject) i.next();
                    PreferenceGroup pg = dObj.getPrefGroup();
                    relatedInstructionalOfferings
                            .add((pg instanceof Class_ ? ((Class_) pg).getSchedulingSubpart()
                                    : (SchedulingSubpart) pg).getInstrOfferingConfig()
                                            .getInstructionalOffering());
                    pg.getDistributionObjects().remove(dObj);
                    hibSession.saveOrUpdate(pg);
                }
                s.clear();
                dp.setDistributionObjects(s);
                oldOwner = (Department) dp.getOwner();
            }
        } else
            dp = new DistributionPref();

        dp.setDistributionType(new DistributionTypeDAO().get(new Long(frm.getDistType()), hibSession));
        dp.setGrouping(new Integer(frm.getGroupingInt()));
        dp.setPrefLevel(PreferenceLevel.getPreferenceLevel(Integer.parseInt(frm.getPrefLevel())));

        Department owningDept = null;

        // Create distribution objects
        for (int i = 0; i < saList.size(); i++) {
            String su = suList.get(i).toString();
            String cl = clList.get(i).toString();

            DistributionObject dObj = new DistributionObject();

            // Subpart
            if (cl.equals(DistributionPrefsForm.ALL_CLASSES_SELECT)) {
                SchedulingSubpart subpart = new SchedulingSubpartDAO().get(new Long(su), hibSession);
                if (owningDept == null)
                    owningDept = subpart.getManagingDept();
                else if (!owningDept.getUniqueId().equals(subpart.getManagingDept().getUniqueId())) {
                    if (owningDept.getDistributionPrefPriority().intValue() < subpart.getManagingDept()
                            .getDistributionPrefPriority().intValue())
                        owningDept = subpart.getManagingDept();
                    else if (owningDept.getDistributionPrefPriority().intValue() == subpart.getManagingDept()
                            .getDistributionPrefPriority().intValue()) {
                        if (!sessionContext.getUser().getCurrentAuthority().hasQualifier(owningDept)
                                && sessionContext.getUser().getCurrentAuthority()
                                        .hasQualifier(subpart.getManagingDept()))
                            owningDept = subpart.getManagingDept();
                    }
                }

                dObj.setPrefGroup(subpart);
                relatedInstructionalOfferings.add(subpart.getInstrOfferingConfig().getInstructionalOffering());
            }

            // Class
            else {
                Class_ clazz = new Class_DAO().get(new Long(cl), hibSession);
                if (owningDept == null)
                    owningDept = clazz.getManagingDept();
                else if (!owningDept.equals(clazz.getManagingDept())) {
                    if (owningDept.getDistributionPrefPriority().intValue() < clazz.getManagingDept()
                            .getDistributionPrefPriority().intValue())
                        owningDept = clazz.getManagingDept();
                    else if (owningDept.getDistributionPrefPriority().intValue() == clazz.getManagingDept()
                            .getDistributionPrefPriority().intValue()) {
                        if (!sessionContext.getUser().getCurrentAuthority().hasQualifier(owningDept)
                                && sessionContext.getUser().getCurrentAuthority()
                                        .hasQualifier(clazz.getManagingDept()))
                            owningDept = clazz.getManagingDept();
                    }
                }

                relatedInstructionalOfferings
                        .add(clazz.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering());
                dObj.setPrefGroup(clazz);
            }

            dObj.setSequenceNumber(new Integer(i + 1));
            dObj.setDistributionPref(dp);
            dObj.getPrefGroup().getDistributionObjects().add(dObj);

            dp.addTodistributionObjects(dObj);
        }

        dp.setOwner(owningDept);

        /*
                
        if (dp.getOwner()==null)
          throw new Exception("Creation of such constraint denied: no owner specified.");
                
        if (sessionContext.hasPermission(Right.) && !dp.getDistributionType().isApplicable(owningDept)) {
         throw new Exception("Creation of such constraint denied: distribution preference "+dp.getDistributionType().getLabel()+" not allowed for "+dp.getOwner()+".");
        }
                
          if (!sessionContext.hasPermission(dp.getOwner(), Right.DistributionPreferenceAdd))
         throw new Exception("Creation of such constraint denied: unable to create constraint owned by "+dp.getOwner()+".");
                
          if (!sessionContext.getUser().getCurrentAuthority().hasQualifier((Department)dp.getOwner()) && !((Department)dp.getOwner()).effectiveStatusType().canOwnerEdit())
         throw new Exception("Creation of such constraint denied: unable to create constraint owned by "+dp.getOwner()+".");
                
          if (currentMgr.isExternalManager() && !sessionContext.getUser().getCurrentAuthority().hasQualifier((Department)dp.getOwner()))
         throw new Exception("Creation of such constraint denied: unable to create constraint owned by "+dp.getOwner()+".");
                
          Department dept = (Department)dp.getOwner();
          if (dept.isExternalManager() && !dept.isAllowReqDistribution() && !sessionContext.getUser().getCurrentAuthority().hasQualifier((Department)dp.getOwner())) {
         if (dp.getPrefLevel().getPrefProlog().equals(PreferenceLevel.sRequired)) {
            if (dp.getDistributionType().getAllowedPref().indexOf(PreferenceLevel.sCharLevelStronglyPreferred)>=0)
               dp.setPrefLevel(PreferenceLevel.getPreferenceLevel(PreferenceLevel.sStronglyPreferred));
            else
               throw new Exception("Creation of such constraint denied: unable to create "+dp.getPrefLevel().getPrefName()+" constraint owned by "+dp.getOwner()+".");
         }
          if (dp.getPrefLevel().getPrefProlog().equals(PreferenceLevel.sProhibited)) {
             if (dp.getDistributionType().getAllowedPref().indexOf(PreferenceLevel.sCharLevelStronglyDiscouraged)>=0)
                dp.setPrefLevel(PreferenceLevel.getPreferenceLevel(PreferenceLevel.sStronglyDiscouraged));
             else
                throw new Exception("Creation of such constraint denied: unable to create "+dp.getPrefLevel().getPrefName()+" constraint owned by "+dp.getOwner()+".");
          }
          }
        }*/

        sessionContext.checkPermission(dp, Right.DistributionPreferenceEdit);

        // Save
        hibSession.saveOrUpdate(dp);

        for (Iterator i = relatedInstructionalOfferings.iterator(); i.hasNext();) {
            InstructionalOffering io = (InstructionalOffering) i.next();
            ChangeLog.addChange(hibSession, sessionContext, io, ChangeLog.Source.DIST_PREF_EDIT,
                    (distPrefId != null && distPrefId.trim().length() > 0 ? ChangeLog.Operation.UPDATE
                            : ChangeLog.Operation.CREATE),
                    io.getControllingCourseOffering().getSubjectArea(), null);
        }

        tx.commit();
        hibSession.flush();
        hibSession.refresh(dp.getOwner());
        if (oldOwner != null && !oldOwner.equals(dp.getOwner()))
            hibSession.refresh(oldOwner);
        frm.setDistPrefId(dp.getUniqueId().toString());
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();
        hibSession.clear();
        throw e;
    }
}