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.timetable.action.RoomFeatureAddAction.java

License:Open Source License

/**
 * /*  w ww  .j a  va 2 s  . co m*/
 * @param mapping
 * @param roomFeatureEditForm
 * @param request
 * @param response
 */
private void save(ActionMapping mapping, RoomFeatureEditForm roomFeatureEditForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    //if roomFeature is global
    if (roomFeatureEditForm.isGlobal()) {
        sessionContext.checkPermission(Right.GlobalRoomFeatureAdd);

        GlobalRoomFeatureDAO gdao = new GlobalRoomFeatureDAO();
        org.hibernate.Session hibSession = gdao.getSession();
        Transaction tx = null;

        GlobalRoomFeature rf = new GlobalRoomFeature();
        rf.setLabel(roomFeatureEditForm.getName());
        rf.setAbbv(roomFeatureEditForm.getAbbv());
        rf.setSession(SessionDAO.getInstance().get(sessionContext.getUser().getCurrentAcademicSessionId()));

        if (roomFeatureEditForm.getFeatureTypeId() != null && roomFeatureEditForm.getFeatureTypeId() >= 0)
            rf.setFeatureType(RoomFeatureTypeDAO.getInstance().get(roomFeatureEditForm.getFeatureTypeId()));

        try {
            tx = hibSession.beginTransaction();
            hibSession.saveOrUpdate(rf);

            ChangeLog.addChange(hibSession, sessionContext, rf, ChangeLog.Source.ROOM_FEATURE_EDIT,
                    ChangeLog.Operation.CREATE, null, null);

            tx.commit();
            hibSession.refresh(rf);
            request.setAttribute("hash", "A" + rf.getUniqueId());

        } catch (Exception e) {
            Debug.error(e);
            if (tx != null && tx.isActive())
                tx.rollback();
            throw e;
        }
    } else {
        Department department = Department.findByDeptCode(roomFeatureEditForm.getDeptCode(),
                sessionContext.getUser().getCurrentAcademicSessionId());
        sessionContext.checkPermission(department, Right.DepartmentRoomFeatureAdd);

        DepartmentRoomFeatureDAO ddao = new DepartmentRoomFeatureDAO();
        org.hibernate.Session hibSession = ddao.getSession();
        Transaction tx = null;

        DepartmentRoomFeature rf = new DepartmentRoomFeature();
        rf.setLabel(roomFeatureEditForm.getName());
        rf.setAbbv(roomFeatureEditForm.getAbbv());

        rf.setDepartment(department);

        if (roomFeatureEditForm.getFeatureTypeId() != null && roomFeatureEditForm.getFeatureTypeId() >= 0)
            rf.setFeatureType(RoomFeatureTypeDAO.getInstance().get(roomFeatureEditForm.getFeatureTypeId()));

        try {
            tx = hibSession.beginTransaction();
            hibSession.saveOrUpdate(rf);

            ChangeLog.addChange(hibSession, sessionContext, (RoomFeature) rf,
                    ChangeLog.Source.ROOM_FEATURE_EDIT, ChangeLog.Operation.CREATE, null, rf.getDepartment());

            tx.commit();
            hibSession.refresh(rf);
            request.setAttribute("hash", "A" + rf.getUniqueId());
        } catch (Exception e) {
            Debug.error(e);
            if (tx != null && tx.isActive())
                tx.rollback();
            throw e;
        }
    }

}

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

License:Open Source License

private void save(ActionMapping mapping, RoomGroupEditForm roomGroupEditForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    Department d = (roomGroupEditForm.isGlobal() ? null
            : Department.findByDeptCode(roomGroupEditForm.getDeptCode(),
                    sessionContext.getUser().getCurrentAcademicSessionId()));

    if (d == null)
        sessionContext.checkPermission(Right.GlobalRoomGroupAdd);
    else/*from   w  ww.j  av  a2  s .  c  om*/
        sessionContext.checkPermission(d, Right.DepartmentRoomFeatureAdd);

    //create new roomGroup
    RoomGroupDAO rgdao = new RoomGroupDAO();
    RoomGroup rg = new RoomGroup();

    rg.setName(roomGroupEditForm.getName());
    rg.setAbbv(roomGroupEditForm.getAbbv());
    rg.setSession(SessionDAO.getInstance().get(sessionContext.getUser().getCurrentAcademicSessionId()));
    rg.setDescription(roomGroupEditForm.getDesc().length() > 200 ? roomGroupEditForm.getDesc().substring(0, 200)
            : roomGroupEditForm.getDesc());

    rg.setGlobal(d == null);
    rg.setDepartment(d);

    rg.setDefaultGroup(roomGroupEditForm.isDeft());

    org.hibernate.Session hibSession = rgdao.getSession();
    Transaction tx = null;
    try {
        tx = hibSession.beginTransaction();
        checkDefault(hibSession, rg);
        hibSession.saveOrUpdate(rg);

        ChangeLog.addChange(hibSession, sessionContext, rg, ChangeLog.Source.ROOM_GROUP_EDIT,
                ChangeLog.Operation.CREATE, null, rg.getDepartment());

        tx.commit();
        hibSession.refresh(rg);
        request.setAttribute("hash", "A" + rg.getUniqueId());
    } 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.SolverParamDefAction.java

License:Open Source License

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

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

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

    if (request.getParameter("op2") != null && request.getParameter("op2").length() > 0)
        op = request.getParameter("op2");

    if (op == null) {
        myForm.reset(mapping, request);/*from   w  ww. java2 s  . c o  m*/
        myForm.setVisible(Boolean.TRUE);
    }

    // Reset Form
    if ("Back".equals(op)) {
        if (myForm.getUniqueId() != null)
            request.setAttribute("hash", myForm.getUniqueId());
        myForm.reset(mapping, request);
        myForm.setVisible(Boolean.TRUE);
    }

    if ("Add Solver Parameter".equals(op)) {
        myForm.reset(mapping, request);
        myForm.setVisible(Boolean.TRUE);
        myForm.setOp("Save");
        myForm.setGroup(request.getParameter("group"));
    }

    // Add / Update
    if ("Update".equals(op) || "Save".equals(op)) {
        // Validate input
        ActionMessages errors = myForm.validate(mapping, request);
        if (errors.size() > 0) {
            saveErrors(request, errors);
        } else {
            Transaction tx = null;
            try {
                SolverParameterDefDAO dao = new SolverParameterDefDAO();
                org.hibernate.Session hibSession = dao.getSession();
                if (hibSession.getTransaction() == null || !hibSession.getTransaction().isActive())
                    tx = hibSession.beginTransaction();

                SolverParameterDef def = null;
                if (op.equals("Save"))
                    def = new SolverParameterDef();
                else
                    def = dao.get(myForm.getUniqueId(), hibSession);

                def.setName(myForm.getName());
                def.setDescription(myForm.getDescription());
                def.setDefault(myForm.getDefault());
                def.setType(myForm.getType());
                def.setVisible(myForm.getVisible());
                SolverParameterGroup group = null;
                List groups = hibSession.createCriteria(SolverParameterGroup.class)
                        .add(Restrictions.eq("name", myForm.getGroup())).list();
                if (!groups.isEmpty())
                    group = (SolverParameterGroup) groups.get(0);
                if (def.getGroup() != null && !def.getGroup().equals(group)) {
                    List list = hibSession.createCriteria(SolverParameterDef.class)
                            .add(Restrictions.eq("group", def.getGroup()))
                            .add(Restrictions.gt("order", def.getOrder())).list();
                    for (Iterator i = list.iterator(); i.hasNext();) {
                        SolverParameterDef d = (SolverParameterDef) i.next();
                        d.setOrder(new Integer(d.getOrder().intValue() - 1));
                        dao.save(d, hibSession);
                    }
                    myForm.setOrder(-1);
                }
                if (myForm.getOrder() < 0) {
                    def.setOrder(new Integer(group == null ? 0 : group.getParameters().size()));
                }
                def.setGroup(group);
                dao.saveOrUpdate(def, hibSession);

                if (tx != null)
                    tx.commit();

                hibSession.refresh(def);
                request.setAttribute("hash", def.getUniqueId().toString());
            } catch (Exception e) {
                if (tx != null)
                    tx.rollback();
                Debug.error(e);
            }
            myForm.reset(mapping, request);
            myForm.setVisible(Boolean.TRUE);
        }
    }

    // Edit
    if (op.equals("Edit")) {
        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);
        } else {
            SolverParameterDefDAO dao = new SolverParameterDefDAO();
            SolverParameterDef def = dao.get(new Long(id));
            if (def == null) {
                errors.add("name", new ActionMessage("errors.invalid", "Unique Id : " + id));
                saveErrors(request, errors);
            } else {
                myForm.setUniqueId(def.getUniqueId());
                myForm.setName(def.getName());
                myForm.setOrder(def.getOrder().intValue());
                myForm.setDescription(def.getDescription());
                myForm.setGroup(def.getGroup().getName());
                myForm.setType(def.getType());
                myForm.setDefault(def.getDefault());
                myForm.setVisible(def.isVisible());
                myForm.setOp("Update");
            }
        }
    }

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

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

            SolverParameterDef def = dao.get(myForm.getUniqueId(), hibSession);

            List list = hibSession.createCriteria(SolverParameterDef.class)
                    .add(Restrictions.eq("group", def.getGroup())).add(Restrictions.gt("order", def.getOrder()))
                    .list();

            for (Iterator i = list.iterator(); i.hasNext();) {
                SolverParameterDef d = (SolverParameterDef) i.next();
                d.setOrder(new Integer(d.getOrder().intValue() - 1));
                dao.save(d, hibSession);
            }

            dao.delete(def, hibSession);

            if (tx != null)
                tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            Debug.error(e);
        }
        if (myForm.getGroup() != null)
            request.setAttribute("hash", myForm.getGroup());
        myForm.reset(mapping, request);
        myForm.setVisible(Boolean.TRUE);
    }

    // Move Up or Down
    if ("Move Up".equals(op) || "Move Down".equals(op)) {
        Transaction tx = null;

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

            SolverParameterDef def = dao.get(myForm.getUniqueId(), hibSession);
            if ("Move Up".equals(op)) {
                List list = hibSession.createCriteria(SolverParameterDef.class)
                        .add(Restrictions.eq("group", def.getGroup()))
                        .add(Restrictions.eq("order", new Integer(def.getOrder().intValue() - 1))).list();
                if (!list.isEmpty()) {
                    SolverParameterDef prior = (SolverParameterDef) list.get(0);
                    prior.setOrder(new Integer(prior.getOrder().intValue() + 1));
                    dao.save(prior, hibSession);
                    def.setOrder(new Integer(def.getOrder().intValue() - 1));
                    dao.save(def, hibSession);
                }
            } else {
                List list = hibSession.createCriteria(SolverParameterDef.class)
                        .add(Restrictions.eq("group", def.getGroup()))
                        .add(Restrictions.eq("order", new Integer(def.getOrder().intValue() + 1))).list();
                if (!list.isEmpty()) {
                    SolverParameterDef next = (SolverParameterDef) list.get(0);
                    next.setOrder(new Integer(next.getOrder().intValue() - 1));
                    dao.save(next, hibSession);
                    def.setOrder(new Integer(def.getOrder().intValue() + 1));
                    dao.save(def, hibSession);
                }
            }
            myForm.setOrder(def.getOrder().intValue());

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

            if (tx != null)
                tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            Debug.error(e);
        }
    }
    if ("List".equals(myForm.getOp())) {
        // Read all existing settings and store in request
        getSolverParameterDefs(request, myForm.getUniqueId());
        return mapping.findForward("list");
    }

    return mapping.findForward("Save".equals(myForm.getOp()) ? "add" : "edit");
}

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

License:Open Source License

/**
 * Update Subject Area//w w w  . j  ava 2s.co m
 * @param request
 * @param frm
 */
private void doUpdate(HttpServletRequest request, SubjectAreaEditForm frm) throws Exception {
    Session hibSession = null;
    Transaction tx = null;

    if (frm.getUniqueId() == null)
        sessionContext.checkPermission(Right.SubjectAreaAdd);
    else
        sessionContext.checkPermission(frm.getUniqueId(), "SubjectArea", Right.SubjectAreaEdit);

    try {
        SubjectAreaDAO sdao = new SubjectAreaDAO();
        DepartmentDAO ddao = new DepartmentDAO();

        SubjectArea sa = null;
        Department oldDept = null;

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

        if (frm.getUniqueId() != null)
            sa = sdao.get(frm.getUniqueId());
        else
            sa = new SubjectArea();

        Department dept = ddao.get(frm.getDepartment());
        HashSet<Class_> updatedClasses = new HashSet<Class_>();

        sa.setSession(SessionDAO.getInstance().get(sessionContext.getUser().getCurrentAcademicSessionId(),
                hibSession));
        sa.setSubjectAreaAbbreviation(frm.getAbbv());
        if (sa.getDepartment() != null && !dept.equals(sa.getDepartment())) {
            HashSet availableRooms = new HashSet();
            HashSet availableBuildings = new HashSet();
            for (Iterator i = dept.getRoomDepts().iterator(); i.hasNext();) {
                RoomDept roomDept = (RoomDept) i.next();
                availableRooms.add(roomDept.getRoom());
                if (roomDept.getRoom() instanceof Room)
                    availableBuildings.add(((Room) roomDept.getRoom()).getBuilding());
            }
            for (Iterator i = sa.getCourseOfferings().iterator(); i.hasNext();) {
                CourseOffering co = (CourseOffering) i.next();
                if (!co.getIsControl() || co.getInstructionalOffering() == null)
                    continue;
                for (Iterator j = co.getInstructionalOffering().getInstrOfferingConfigs().iterator(); j
                        .hasNext();) {
                    InstrOfferingConfig ioc = (InstrOfferingConfig) j.next();
                    for (Iterator k = ioc.getSchedulingSubparts().iterator(); k.hasNext();) {
                        SchedulingSubpart ss = (SchedulingSubpart) k.next();
                        if (!ss.getManagingDept().isExternalManager()) {
                            for (Iterator l = ss.getPreferences().iterator(); l.hasNext();) {
                                Preference p = (Preference) l.next();
                                if (p instanceof TimePref)
                                    continue;
                                if (p instanceof RoomPref) {
                                    RoomPref rp = (RoomPref) p;
                                    if (!availableRooms.contains(rp.getRoom()))
                                        l.remove();
                                } else if (p instanceof BuildingPref) {
                                    BuildingPref bp = (BuildingPref) p;
                                    if (!availableBuildings.contains(bp.getBuilding()))
                                        l.remove();
                                } else if (p instanceof RoomFeaturePref) {
                                    RoomFeaturePref rfp = (RoomFeaturePref) p;
                                    if (rfp.getRoomFeature() instanceof DepartmentRoomFeature)
                                        l.remove();
                                } else if (p instanceof RoomGroupPref) {
                                    RoomGroupPref rgp = (RoomGroupPref) p;
                                    if (!rgp.getRoomGroup().isGlobal())
                                        l.remove();
                                }
                            }
                            hibSession.saveOrUpdate(ss);
                        }
                        for (Iterator l = ss.getClasses().iterator(); l.hasNext();) {
                            Class_ c = (Class_) l.next();
                            if (!c.getManagingDept().isExternalManager()) {
                                for (Iterator m = c.getPreferences().iterator(); m.hasNext();) {
                                    Preference p = (Preference) m.next();
                                    if (p instanceof TimePref)
                                        continue;
                                    if (p instanceof RoomPref) {
                                        RoomPref rp = (RoomPref) p;
                                        if (!availableRooms.contains(rp.getRoom()))
                                            m.remove();
                                    } else if (p instanceof BuildingPref) {
                                        BuildingPref bp = (BuildingPref) p;
                                        if (!availableBuildings.contains(bp.getBuilding()))
                                            m.remove();
                                    } else if (p instanceof RoomFeaturePref) {
                                        RoomFeaturePref rfp = (RoomFeaturePref) p;
                                        if (rfp.getRoomFeature() instanceof DepartmentRoomFeature)
                                            m.remove();
                                    } else if (p instanceof RoomGroupPref) {
                                        RoomGroupPref rgp = (RoomGroupPref) p;
                                        if (!rgp.getRoomGroup().isGlobal())
                                            m.remove();
                                    }
                                }
                                c.setManagingDept(dept);
                            }
                            for (Iterator m = c.getClassInstructors().iterator(); m.hasNext();) {
                                ClassInstructor ci = (ClassInstructor) m.next();
                                DepartmentalInstructor newInstructor = null;
                                if (ci.getInstructor().getExternalUniqueId() != null) {
                                    newInstructor = DepartmentalInstructor.findByPuidDepartmentId(
                                            ci.getInstructor().getExternalUniqueId(), dept.getUniqueId());
                                }
                                ci.getInstructor().getClasses().remove(ci);
                                hibSession.saveOrUpdate(ci.getInstructor());
                                if (newInstructor != null) {
                                    ci.setInstructor(newInstructor);
                                    newInstructor.getClasses().add(ci);
                                    hibSession.saveOrUpdate(newInstructor);
                                } else {
                                    m.remove();
                                    hibSession.delete(ci);
                                }
                            }
                            hibSession.saveOrUpdate(c);
                            updatedClasses.add(c);
                        }
                    }
                }
            }

            for (Iterator i = sa.getDepartment().getPreferences().iterator(); i.hasNext();) {
                Preference p = (Preference) i.next();
                if (p instanceof DistributionPref) {
                    DistributionPref dp = (DistributionPref) p;
                    boolean change = true;
                    for (Iterator j = dp.getOrderedSetOfDistributionObjects().iterator(); j.hasNext();) {
                        DistributionObject dobj = (DistributionObject) j.next();
                        if (dobj.getPrefGroup() instanceof SchedulingSubpart) {
                            SchedulingSubpart ss = (SchedulingSubpart) dobj.getPrefGroup();
                            if (!ss.getControllingCourseOffering().getSubjectArea().equals(sa))
                                change = false;
                            break;
                        } else if (dobj.getPrefGroup() instanceof Class_) {
                            Class_ c = (Class_) dobj.getPrefGroup();
                            if (!c.getSchedulingSubpart().getControllingCourseOffering().getSubjectArea()
                                    .equals(sa))
                                change = false;
                            break;
                        }
                    }
                    if (change) {
                        dp.setOwner(dept);
                        hibSession.saveOrUpdate(dp);
                    }
                }
            }
            oldDept = sa.getDepartment();
            sa.setDepartment(dept);
        } else if (sa.getDepartment() == null) {
            sa.setDepartment(dept);
        }
        sa.setExternalUniqueId(frm.getExternalId());
        sa.setTitle(frm.getTitle());

        hibSession.saveOrUpdate(sa);

        ChangeLog.addChange(hibSession, sessionContext, sa, ChangeLog.Source.SUBJECT_AREA_EDIT,
                (frm.getUniqueId() == null ? ChangeLog.Operation.CREATE : ChangeLog.Operation.UPDATE), sa,
                dept);

        tx.commit();
        hibSession.refresh(sa);
        hibSession.flush();
        hibSession.refresh(sa.getSession());
        if (oldDept != null) {
            hibSession.refresh(oldDept);
            hibSession.refresh(sa.getDepartment());
        }
        String className = ApplicationProperty.ExternalActionClassEdit.value();
        if (className != null && className.trim().length() > 0) {
            ExternalClassEditAction editAction = (ExternalClassEditAction) (Class.forName(className)
                    .newInstance());
            for (Class_ c : updatedClasses) {
                editAction.performExternalClassEditAction(c, hibSession);
            }
        }
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();

        throw (e);
    }
}

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

License:Open Source License

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    try {//from w  w w  . ja v a  2 s .co  m
        TimePatternEditForm myForm = (TimePatternEditForm) form;

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

        // 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 (op == null) {
            myForm.load(null, null);
            myForm.setOp("List");
        }

        Long sessionId = sessionContext.getUser().getCurrentAcademicSessionId();

        List list = (new DepartmentDAO()).getSession().createCriteria(Department.class)
                .add(Restrictions.eq("session.uniqueId", sessionId)).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, null);
            myForm.setOp("List");
        }

        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 ("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");
        }

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

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

                    myForm.saveOrUpdate(sessionContext, hibSession);

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

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

        // 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);
                return mapping.findForward("list");
            } else {
                TimePattern pattern = (new TimePatternDAO()).get(new Long(id));

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

        // 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();

                myForm.delete(sessionContext, hibSession);

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

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

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

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

                TimePattern tp = TimePattern.findExactTime(sessionId);

                if (tp == null) {
                    myForm.load(null, null);
                    myForm.setOp("List");
                    getTimePatterns(request, sessionId);

                    ActionMessages errors = new ActionMessages();
                    errors.add("key", new ActionMessage("errors.generic",
                            "There is no Exact Time time pattern defined."));
                    saveErrors(request, errors);

                    return mapping.findForward("list");
                }

                List timePrefs = hibSession.createQuery(
                        "select distinct p from TimePref as p inner join p.timePattern as tp where tp.uniqueId=:uniqueid")
                        .setLong("uniqueid", tp.getUniqueId().longValue()).list();

                CSVFile csv = new CSVFile();
                csv.setHeader(new CSVFile.CSVField[] { new CSVFile.CSVField("Class"),
                        new CSVFile.CSVField("Pattern"), new CSVFile.CSVField("Time") });

                for (Iterator i = timePrefs.iterator(); i.hasNext();) {
                    TimePref tpref = (TimePref) i.next();
                    if (!(tpref.getOwner() instanceof Class_))
                        continue;
                    Class_ clazz = (Class_) tpref.getOwner();
                    if (!clazz.getSessionId().equals(sessionId))
                        continue;
                    int dayCode = tpref.getTimePatternModel().getExactDays();
                    String name = "";
                    int nrDays = 0;
                    for (int j = 0; j < Constants.DAY_CODES.length; j++) {
                        if ((Constants.DAY_CODES[j] & dayCode) != 0) {
                            name += Constants.DAY_NAMES_SHORT[j];
                            nrDays++;
                        }
                    }
                    name += " ";
                    int startSlot = tpref.getTimePatternModel().getExactStartSlot();
                    name += Constants
                            .toTime(Constants.FIRST_SLOT_TIME_MIN + (Constants.SLOT_LENGTH_MIN * startSlot));
                    int minPerMtg = (nrDays == 0 ? 0
                            : clazz.getSchedulingSubpart().getMinutesPerWk().intValue() / nrDays);
                    if (nrDays == 0)
                        Debug.warning("Class " + clazz.getClassLabel() + " has zero number of days.");

                    csv.addLine(new CSVFile.CSVField[] { new CSVFile.CSVField(clazz.getClassLabel()),
                            new CSVFile.CSVField(nrDays + " x " + minPerMtg), new CSVFile.CSVField(name) });
                }

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

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

                boolean mysql = false;

                int line = 0;
                if (mysql)
                    out.println(
                            "INSERT INTO `timetable`.`time_pattern`(`uniqueid`, `name`, `mins_pmt`, `slots_pmt`, `nr_mtgs`, `visible`, `type`, `break_time`, `session_id`)");
                else
                    out.println("prompt Loading TIME_PATTERN...");
                for (Iterator i = patterns.iterator(); i.hasNext();) {
                    TimePattern tp = (TimePattern) i.next();

                    if (tp.getType() == TimePattern.sTypeExtended)
                        continue;
                    if (!tp.isVisible())
                        continue;

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

                        out.print(" (" + tp.getUniqueId() + ", '" + tp.getName() + "', " + tp.getMinPerMtg()
                                + ", " + tp.getSlotsPerMtg() + ", " + tp.getNrMeetings() + ", "
                                + (tp.isVisible() ? "1" : "0") + ", " + tp.getType() + ", " + tp.getBreakTime()
                                + ", " + sessionId + ")");
                    } else {
                        out.println(
                                "insert into TIME_PATTERN (UNIQUEID, NAME, MINS_PMT, SLOTS_PMT, NR_MTGS, VISIBLE, TYPE, BREAK_TIME, SESSION_ID)");
                        out.println("values (" + tp.getUniqueId() + ", '" + tp.getName() + "', "
                                + tp.getMinPerMtg() + ", " + tp.getSlotsPerMtg() + ", " + tp.getNrMeetings()
                                + ", " + (tp.isVisible() ? "1" : "0") + ", " + tp.getType() + ", "
                                + tp.getBreakTime() + ", " + sessionId + ");");
                    }

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

                out.println();

                line = 0;
                if (mysql) {
                    out.println(
                            "INSERT INTO `timetable`.`time_pattern_days`(`uniqueid`, `day_code`, `time_pattern_id`)");
                } else {
                    out.println("prompt Loading TIME_PATTERN_DAYS...");
                }
                for (Iterator i = patterns.iterator(); i.hasNext();) {
                    TimePattern tp = (TimePattern) i.next();

                    if (tp.getType() == TimePattern.sTypeExtended)
                        continue;
                    if (!tp.isVisible())
                        continue;

                    for (Iterator j = tp.getDays().iterator(); j.hasNext();) {
                        TimePatternDays d = (TimePatternDays) j.next();

                        if (mysql) {
                            if (line == 0)
                                out.print("VALUES");
                            else
                                out.println(",");
                            out.print(" (" + d.getUniqueId() + ", " + d.getDayCode() + ", " + tp.getUniqueId()
                                    + ")");
                        } else {
                            out.println("insert into TIME_PATTERN_DAYS (UNIQUEID, DAY_CODE, TIME_PATTERN_ID)");
                            out.println("values (" + d.getUniqueId() + ", " + d.getDayCode() + ", "
                                    + tp.getUniqueId() + ");");
                        }

                        line++;

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

                line = 0;
                if (mysql) {
                    out.println(
                            "INSERT INTO `timetable`.`time_pattern_time`(`uniqueid`, `start_slot`, `time_pattern_id`)");
                } else {
                    out.println("prompt Loading TIME_PATTERN_TIME...");
                }
                for (Iterator i = patterns.iterator(); i.hasNext();) {
                    TimePattern tp = (TimePattern) i.next();

                    if (tp.getType() == TimePattern.sTypeExtended)
                        continue;
                    if (!tp.isVisible())
                        continue;

                    for (Iterator j = tp.getTimes().iterator(); j.hasNext();) {
                        TimePatternTime t = (TimePatternTime) j.next();

                        if (mysql) {
                            if (line == 0)
                                out.print("VALUES");
                            else
                                out.println(",");
                            out.print(" (" + t.getUniqueId() + ", " + t.getStartSlot() + ", " + tp.getUniqueId()
                                    + ")");
                        } else {
                            out.println(
                                    "insert into TIME_PATTERN_TIME (UNIQUEID, START_SLOT, TIME_PATTERN_ID)");
                            out.println("values (" + t.getUniqueId() + ", " + t.getStartSlot() + ", "
                                    + tp.getUniqueId() + ");");
                        }

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

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

        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 patterns = new TreeSet(TimePattern.findAll(sessionId, null));

                for (Iterator i = patterns.iterator(); i.hasNext();) {
                    TimePattern tp = (TimePattern) i.next();

                    if (tp.getType().intValue() != TimePattern.sTypeExtended)
                        continue;

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

                    List timePrefs = hibSession.createQuery(
                            "select distinct p from TimePref as p inner join p.timePattern as tp where tp.uniqueId=:uniqueid")
                            .setInteger("uniqueid", tp.getUniqueId().intValue()).list();

                    HashSet depts = new HashSet();

                    for (Iterator j = timePrefs.iterator(); j.hasNext();) {
                        TimePref timePref = (TimePref) j.next();
                        if (timePref.getOwner() instanceof Class_) {
                            Class_ c = (Class_) timePref.getOwner();
                            if (!c.getSession().getUniqueId().equals(sessionId))
                                continue;
                            depts.add(c.getManagingDept());
                        } else if (timePref.getOwner() instanceof SchedulingSubpart) {
                            SchedulingSubpart s = (SchedulingSubpart) timePref.getOwner();
                            if (!s.getSession().getUniqueId().equals(sessionId))
                                continue;
                            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 (tp.getDepartments().contains(d)) {
                               tp.getDepartments().remove(d);
                               d.getTimePatterns().remove(tp);
                               hibSession.saveOrUpdate(d);
                                out.println("    -- department "+d+" removed from "+tp.getName());
                                added=true;
                            }
                            */
                            continue;
                        }
                        if (!tp.getDepartments().contains(d)) {
                            tp.getDepartments().add(d);
                            d.getTimePatterns().add(tp);
                            hibSession.saveOrUpdate(d);
                            out.println("    -- department " + d + " added to " + tp.getName());
                            added = true;
                        }
                    }
                    if (added) {
                        hibSession.saveOrUpdate(tp);
                        refresh.add(tp);
                    }
                }

                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, 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("Visible"), new CSVFile.CSVField("Used"),
                                new CSVFile.CSVField("NbrMtgs"), new CSVFile.CSVField("MinPerMtg"),
                                new CSVFile.CSVField("SlotsPerMtg"), new CSVFile.CSVField("BreakTime"),
                                new CSVFile.CSVField("Days"), new CSVFile.CSVField("Times"),
                                new CSVFile.CSVField("Departments"), new CSVFile.CSVField("Classes") });

                TreeSet patterns = new TreeSet(TimePattern.findAll(sessionId, null));

                for (Iterator i = patterns.iterator(); i.hasNext();) {
                    TimePattern tp = (TimePattern) i.next();

                    String deptStr = "";
                    TreeSet depts = new TreeSet(tp.getDepartments());
                    for (Iterator j = depts.iterator(); j.hasNext();) {
                        Department d = (Department) j.next();
                        if (!d.getSessionId().equals(sessionId))
                            continue;
                        if (deptStr.length() > 0) {
                            deptStr += ", ";
                        }
                        deptStr += d.getShortLabel().trim();
                    }

                    String classStr = "";
                    if (tp.getType().intValue() != TimePattern.sTypeStandard) {
                        List timePrefs = hibSession.createQuery(
                                "select distinct p.owner from TimePref as p inner join p.timePattern as tp where tp.uniqueId=:uniqueid")
                                .setInteger("uniqueid", tp.getUniqueId().intValue()).list();

                        TreeSet allOwners = new TreeSet();

                        for (Iterator j = timePrefs.iterator(); j.hasNext();) {
                            Object owner = j.next();
                            if (owner instanceof Class_) {
                                Class_ c = (Class_) owner;
                                if (!c.getSession().getUniqueId().equals(sessionId))
                                    continue;
                                allOwners.add(c.getClassLabel());
                            } else if (owner instanceof SchedulingSubpart) {
                                SchedulingSubpart s = (SchedulingSubpart) owner;
                                if (!s.getSession().getUniqueId().equals(sessionId))
                                    continue;
                                allOwners.add(s.getSchedulingSubpartLabel());
                            }
                        }

                        if (allOwners.isEmpty()) {
                            classStr += "not used";
                        } else {
                            int idx = 0;
                            classStr += allOwners.size() + " / ";
                            for (Iterator j = allOwners.iterator(); j.hasNext(); idx++) {
                                if (idx == 20) {
                                    classStr += "...";
                                    break;
                                }
                                classStr += (String) j.next();
                                if (j.hasNext())
                                    classStr += ", ";
                            }
                        }
                    }

                    csv.addLine(new CSVFile.CSVField[] { new CSVFile.CSVField(tp.getName()),
                            new CSVFile.CSVField(TimePattern.sTypes[tp.getType().intValue()]),
                            new CSVFile.CSVField(tp.isVisible().booleanValue() ? "Y" : "N"),
                            new CSVFile.CSVField(tp.isEditable() ? "N" : "Y"),
                            new CSVFile.CSVField(tp.getNrMeetings()), new CSVFile.CSVField(tp.getMinPerMtg()),
                            new CSVFile.CSVField(tp.getSlotsPerMtg()), new CSVFile.CSVField(tp.getBreakTime()),
                            new CSVFile.CSVField(TimePatternEditForm.dayCodes2str(tp.getDays(), ", ")),
                            new CSVFile.CSVField(TimePatternEditForm.startSlots2str(tp.getTimes(), ", ")),
                            new CSVFile.CSVField(deptStr), new CSVFile.CSVField(classStr) });
                }

                tx.commit();

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

        if ("Add Time Pattern".equals(op)) {
            myForm.load(null, null);
            myForm.setOp("Save");
        }

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

        String example = myForm.getExample();
        if (example != null) {
            request.setAttribute("TimePatterns.example", example);
        }
        return mapping.findForward(myForm.getUniqueId().longValue() < 0 ? "add" : "edit");

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

From source file:org.unitime.timetable.dataexchange.BaseCourseOfferingImport.java

License:Open Source License

private boolean elementClass(Element element, InstrOfferingConfig ioc, Class_ parentClass,
        HashSet<Class_> allExistingClasses) throws Exception {
    boolean changed = false;
    HashMap<String, Class_> possibleClassesAtThisLevel = new HashMap<String, Class_>();
    ArrayList<SchedulingSubpart> possibleSubpartsAtThisLevel = new ArrayList<SchedulingSubpart>();
    if (parentClass == null) {
        allExistingClasses = new HashSet<Class_>();
        if (ioc.getSchedulingSubparts() != null) {
            for (Iterator<?> ssIt = ioc.getSchedulingSubparts().iterator(); ssIt.hasNext();) {
                SchedulingSubpart ss = (SchedulingSubpart) ssIt.next();
                if (ss.getClasses() != null) {
                    for (Iterator<?> cIt = ss.getClasses().iterator(); cIt.hasNext();) {
                        Class_ c = (Class_) cIt.next();
                        allExistingClasses.add(c);
                        if (c.getParentClass() == null) {
                            if (c.getExternalUniqueId() != null) {
                                possibleClassesAtThisLevel.put(c.getExternalUniqueId(), c);
                            } else {
                                possibleClassesAtThisLevel
                                        .put(c.getSchedulingSubpart().getItype().getAbbv().trim()
                                                + c.getClassSuffix(), c);
                            }//from  w w w.j a  v a  2 s.co  m
                        }
                    }
                }
                if (ss.getParentSubpart() == null) {
                    possibleSubpartsAtThisLevel.add(ss);
                }
            }
        }
    } else {
        if (parentClass.getChildClasses() != null) {
            for (Iterator<?> it = parentClass.getChildClasses().iterator(); it.hasNext();) {
                Class_ c = (Class_) it.next();
                if (c.getExternalUniqueId() != null) {
                    possibleClassesAtThisLevel.put(c.getExternalUniqueId(), c);
                } else {
                    possibleClassesAtThisLevel
                            .put(c.getSchedulingSubpart().getItype().getAbbv().trim() + c.getClassSuffix(), c);
                }
            }
        }
        if (parentClass.getSchedulingSubpart().getChildSubparts() != null) {
            possibleSubpartsAtThisLevel.addAll(parentClass.getSchedulingSubpart().getChildSubparts());
        }
    }

    String elementName = "class";
    if (element.element(elementName) != null) {
        if (parentClass == null
                && (ioc.getSchedulingSubparts() == null || ioc.getSchedulingSubparts().isEmpty())) {
            throw new Exception(ioc.getCourseName()
                    + " - If a 'config' has 'class' elements it must also have matching 'subpart' elements");
        }
        for (Iterator<?> cIt = element.elementIterator(elementName); cIt.hasNext();) {
            Element classElement = (Element) cIt.next();
            boolean isAdd = false;
            String id = getOptionalStringAttribute(classElement, "id");
            String managingDeptStr = getOptionalStringAttribute(classElement, "managingDept");
            Department managingDept = null;
            if (managingDeptStr != null && managingDeptStr.trim().length() > 0) {
                managingDept = Department.findByDeptCode(managingDeptStr.trim(), session.getUniqueId());
            }
            String limitStr = getRequiredStringAttribute(classElement, "limit", elementName);
            Integer limit = new Integer(0);
            if (!limitStr.equalsIgnoreCase("inf")) {
                limit = Integer.valueOf(limitStr);
            }
            String suffix = getRequiredStringAttribute(classElement, "suffix", elementName);
            String type = getRequiredStringAttribute(classElement, "type", elementName);
            String scheduleNote = getOptionalStringAttribute(classElement, "scheduleNote");
            Boolean enabledForStudentScheduling = getOptionalBooleanAttribute(classElement, "studentScheduling",
                    getOptionalBooleanAttribute(classElement, "displayInScheduleBook", true));
            Integer itypeId = findItypeForString(type).getItype();

            Class_ clazz = null;
            Class_ origClass = null;
            if (id != null) {
                origClass = (Class_) possibleClassesAtThisLevel.get(id);
                if (origClass != null) {
                    possibleClassesAtThisLevel.remove(id);
                    if (!origClass.getClassSuffix().equals(suffix)) {
                        changed = true;
                        origClass.setClassSuffix(suffix);
                        Integer origSectionNbr = origClass.getSectionNumberCache();
                        try {
                            origClass.setSectionNumberCache(new Integer(suffix));
                        } catch (Exception e) {
                            origClass.setSectionNumberCache(origSectionNbr);
                        }
                        addNote("\t suffix for class changed: " + origClass.getClassLabel());

                    }
                }
            }
            if (origClass == null) {
                origClass = (Class_) possibleClassesAtThisLevel.get(type + suffix);
                if (origClass != null && origClass.getExternalUniqueId() != null && id != null
                        && !origClass.getExternalUniqueId().equals(id)) {
                    origClass = null;
                } else if (origClass != null) {
                    possibleClassesAtThisLevel.remove(type + suffix);
                }
            }
            if (origClass != null) {
                clazz = origClass;
                allExistingClasses.remove(origClass);
                existingClasses.remove(clazz.getUniqueId());
                SchedulingSubpart prevSubpart = clazz.getSchedulingSubpart();
                if (!clazz.getSchedulingSubpart().getItype().getItype().equals(itypeId)
                        || !possibleSubpartsAtThisLevel.contains(clazz.getSchedulingSubpart())) {
                    for (Iterator<SchedulingSubpart> ssIt = possibleSubpartsAtThisLevel.iterator(); ssIt
                            .hasNext();) {
                        SchedulingSubpart ss = (SchedulingSubpart) ssIt.next();
                        if (ss.getItype().getItype().equals(itypeId)) {
                            org.hibernate.Session hSess = this.getHibSession();
                            clazz.setSchedulingSubpart(ss);
                            ss.addToclasses(clazz);
                            hSess.update(ss);
                            hSess.flush();
                            hSess.refresh(ss);
                            hSess.refresh(prevSubpart);
                            break;
                        }
                    }
                    prevSubpart.getClasses().remove(clazz);
                    addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix + " 'class' itype changed");
                    changed = true;
                }
                if ((clazz.getSchedulePrintNote() != null && !clazz.getSchedulePrintNote().equals(scheduleNote))
                        || (clazz.getSchedulePrintNote() == null && scheduleNote != null)) {
                    clazz.setSchedulePrintNote(scheduleNote);
                    addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                            + " 'class' schedule note changed");
                    changed = true;
                }
                if ((clazz.getExpectedCapacity() != null && !clazz.getExpectedCapacity().equals(limit))
                        || (clazz.getExpectedCapacity() == null && limit != null)) {
                    clazz.setExpectedCapacity(limit);
                    clazz.setMaxExpectedCapacity(limit);
                    addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix + " 'class' limit changed");
                    changed = true;
                }
                if ((clazz.getManagingDept() != null && managingDept != null
                        && !clazz.getManagingDept().getUniqueId().equals(managingDept.getUniqueId()))
                        || (clazz.getManagingDept() == null && managingDept != null)) {
                    clazz.setManagingDept(managingDept);
                    addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                            + " 'class' managing department changed");
                    changed = true;
                }
                if (!enabledForStudentScheduling.equals(clazz.isEnabledForStudentScheduling())) {
                    clazz.setEnabledForStudentScheduling(enabledForStudentScheduling);
                    addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                            + " 'class' display in schedule book changed");
                    changed = true;
                }
            } else {
                isAdd = true;
                clazz = new Class_();
                clazz.setExternalUniqueId(id);
                clazz.setClassSuffix(suffix);
                try {
                    clazz.setSectionNumberCache(new Integer(suffix));
                } catch (Exception e) {
                    // Ignore Exception                  
                }

                clazz.setExpectedCapacity(limit);
                clazz.setMaxExpectedCapacity(limit);
                clazz.setRoomRatio(new Float(1.0));
                clazz.setNbrRooms(new Integer(1));
                clazz.setEnabledForStudentScheduling(enabledForStudentScheduling);
                clazz.setSchedulePrintNote(scheduleNote);
                clazz.setDisplayInstructor(new Boolean(true));
                if (managingDept != null) {
                    clazz.setManagingDept(managingDept);
                }
                if (parentClass != null) {
                    clazz.setParentClass(parentClass);
                    parentClass.addTochildClasses(clazz);
                }
                for (Iterator<SchedulingSubpart> ssIt = possibleSubpartsAtThisLevel.iterator(); ssIt
                        .hasNext();) {
                    SchedulingSubpart ss = (SchedulingSubpart) ssIt.next();
                    if (ss.getItype().getItype().equals(itypeId)) {
                        clazz.setSchedulingSubpart(ss);
                        ss.addToclasses(clazz);
                        break;
                    }
                }
                addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                        + " 'class' matching class not found adding new class");
                changed = true;
            }
            if (clazz.getSchedulingSubpart() == null) {
                throw new Exception(ioc.getCourseName() + " " + type + " " + suffix
                        + " 'class' does not have matching 'subpart'");
            }

            if (elementInstructor(classElement, clazz)) {
                addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                        + " 'class' instructor data changed");
                changed = true;
            }

            DatePattern dp = null;
            if (classElement.element("time") != null
                    && classElement.element("time").attributeValue("datePattern") != null) {
                dp = DatePattern.findByName(session,
                        classElement.element("time").attributeValue("datePattern"));
            }
            HashMap<String, Vector<Calendar>> dates = elementDates(classElement);
            if (dp == null && dates != null) {
                dp = findDatePattern(dates.get("startDates"), dates.get("endDates"), clazz);
            }
            if (classElement.element("meeting") == null) {
                if (dp == null && clazz.getDatePattern() != null) {
                    if (!clazz.getDatePattern().isDefault()
                            && clazz.getSchedulingSubpart().effectiveDatePattern().isDefault()) {
                        clazz.setDatePattern(dp);
                        addNote("\t" + ioc.getCourseName() + " " + type + suffix
                                + " 'class' date pattern changed back to default");
                        changed = true;
                    } else if (!clazz.getDatePattern().isDefault()
                            && !clazz.getSchedulingSubpart().effectiveDatePattern().isDefault()) {
                        clazz.setDatePattern(session.getDefaultDatePatternNotNull());
                        addNote("\t" + ioc.getCourseName() + " " + type + suffix
                                + " 'class' date pattern changed to default");
                        changed = true;
                    }
                } else if (dp != null && clazz.getDatePattern() == null) {
                    clazz.setDatePattern(dp);
                    addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                            + "'class' date pattern changed from default");
                    changed = true;
                } else if (dp != null && clazz.getDatePattern() != null
                        && !clazz.getDatePattern().getUniqueId().equals(dp.getUniqueId())) {
                    clazz.setDatePattern(dp);
                    addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                            + " 'class' date pattern changed");
                    changed = true;
                }
            }
            if (changed) {
                this.getHibSession().saveOrUpdate(clazz);
            }

            if (elementMeetsWith(classElement, clazz)) {
                addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                        + " 'class' meets with preferences changed");
                changed = true;
            }

            if (elementCanShareRoom(classElement, clazz)) {
                addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                        + " 'class' can share room preferences changed");
                changed = true;
            }

            if (classElement.element("meeting") != null) {
                if (elementMeetings(classElement, clazz)) {
                    changed = true;
                }
                int numRooms = 1;
                if (clazz.getNbrRooms() != null && !clazz.getNbrRooms().equals(new Integer(numRooms))) {
                    clazz.setNbrRooms(new Integer(numRooms));
                    addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                            + " number of rooms changed");
                    changed = true;
                }

            } else if (classElement.element("time") != null) {
                TimeObject meetingTime = elementTime(classElement);
                Vector<Room> rooms = elementRoom(classElement, clazz);
                Vector<NonUniversityLocation> locations = elementLocation(classElement, clazz);
                int numRooms = 0;
                if (rooms != null && !rooms.isEmpty()) {
                    numRooms += rooms.size();
                }
                if (locations != null && !locations.isEmpty()) {
                    numRooms += locations.size();
                }
                if (clazz.getNbrRooms() != null && !clazz.getNbrRooms().equals(new Integer(numRooms))) {
                    clazz.setNbrRooms(new Integer(numRooms));
                    addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                            + " number of rooms changed");
                    changed = true;
                }
                if (addUpdateClassEvent(clazz, meetingTime, rooms, locations)) {
                    addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                            + " 'class' events for class changed");
                    changed = true;
                }
                TimePattern tp = findTimePatternForMeetingInfo(clazz, meetingTime);
                if (tp != null && clazz.getTimePatterns() != null && !clazz.getTimePatterns().contains(tp)) {
                    for (Iterator it = clazz.getTimePreferences().iterator(); it.hasNext();) {
                        TimePref pref = (TimePref) it.next();
                        clazz.getPreferences().remove(pref);
                    }
                    TimePref tpref = new TimePref();
                    tpref.setTimePattern(tp);
                    tpref.setOwner(clazz);
                    tpref.setPrefLevel(requiredPrefLevel);
                    clazz.addTopreferences(tpref);
                    addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                            + " 'class' time pattern for class changed");
                    changed = true;
                } else if (tp != null
                        && (clazz.getTimePatterns() == null || clazz.getTimePatterns().isEmpty())) {
                    TimePref tpref = new TimePref();
                    tpref.setTimePattern(tp);
                    tpref.setOwner(clazz);
                    tpref.setPrefLevel(requiredPrefLevel);
                    clazz.addTopreferences(tpref);
                    addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                            + " 'class' time pattern for class added");
                    changed = true;
                } else if (tp == null && clazz.getTimePatterns() != null
                        && !clazz.getTimePatterns().isEmpty()) {
                    for (Iterator it = clazz.getTimePreferences().iterator(); it.hasNext();) {
                        TimePref pref = (TimePref) it.next();
                        clazz.getPreferences().remove(pref);
                    }
                    addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                            + " 'class' time pattern for class removed");
                    changed = true;
                }
            }
            if (handleCustomClassChildElements(classElement, ioc, clazz)) {
                changed = true;
            }
            if (elementClass(classElement, ioc, clazz, allExistingClasses)) {
                addNote("\t" + ioc.getCourseName() + " " + type + " " + suffix
                        + " 'class' child classes changed");
                changed = true;
            }
            if (changed) {
                getHibSession().saveOrUpdate(clazz);
                getHibSession().flush();
                getHibSession().refresh(clazz);
            }
            if (changed) {
                ChangeLog.addChange(getHibSession(), getManager(), session, clazz,
                        ChangeLog.Source.DATA_IMPORT_OFFERINGS,
                        (isAdd ? ChangeLog.Operation.CREATE : ChangeLog.Operation.UPDATE),
                        ioc.getControllingCourseOffering().getSubjectArea(), ioc.getDepartment());
            }
        }
    }

    if (possibleClassesAtThisLevel.size() > 0) {
        addNote("\t" + ioc.getCourseName() + " 'class' not all classes at this level had matches");
        for (Iterator<Class_> cIt = possibleClassesAtThisLevel.values().iterator(); cIt.hasNext();) {
            Class_ c = (Class_) cIt.next();
            if (c.getParentClass() != null && c.getParentClass().equals(parentClass)) {
                parentClass.getChildClasses().remove(c);
                c.setParentClass(null);
            }
        }
        changed = true;
    }

    if (parentClass == null && allExistingClasses.size() > 0) {
        info(ioc.getCourseName() + " 'class' not all classes had matches, removing those without matches");
        for (Iterator<Class_> cIt = allExistingClasses.iterator(); cIt.hasNext();) {
            Class_ c = (Class_) cIt.next();
            deleteClass(c);
        }
    }
    return changed;
}

From source file:org.unitime.timetable.model.base._BaseRootDAO.java

License:Open Source License

/**
 * Re-read the state of the given instance from the underlying database. It is inadvisable to use this to implement
 * long-running sessions that span many business tasks. This method is, however, useful in certain special circumstances.
 *//*  w  ww.  ja va2  s.c  o  m*/
public void refresh(T obj, Session s) {
    s.refresh(obj);
}

From source file:org.unitime.timetable.server.hql.HQLStoreBackend.java

License:Open Source License

@Override
@PreAuthorize("(#query.id != null and checkPermission(#query.id, 'SavedHQL', 'HQLReportEdit')) or (#query.id == null and checkPermission('HQLReportAdd'))")
public GwtRpcResponseLong execute(HQLStoreRpcRequest query, SessionContext context) {
    if (SavedHQL.Flag.ADMIN_ONLY.isSet(query.getFlags()))
        sessionContext.checkPermission(Right.HQLReportsAdminOnly);
    org.hibernate.Session hibSession = SavedHQLDAO.getInstance().getSession();
    SavedHQL hql = null;/* w w w  .j a v a 2  s  .  co m*/
    if (query.getId() != null) {
        hql = SavedHQLDAO.getInstance().get(query.getId(), hibSession);
    }
    if (hql == null) {
        hql = new SavedHQL();
    }
    hql.setName(query.getName());
    hql.setDescription(query.getDescription());
    hql.setType(query.getFlags());
    hql.setQuery(query.getQuery());
    hibSession.saveOrUpdate(hql);
    hibSession.flush();
    hibSession.refresh(hql);
    return new GwtRpcResponseLong(hql.getUniqueId());
}

From source file:org.unitime.timetable.server.solver.AssignedClassesBackend.java

License:Apache License

@Override
public AssignedClassesResponse execute(AssignedClassesRequest request, SessionContext context) {
    context.checkPermission(Right.AssignedClasses);
    AssignedClassesResponse response = new AssignedClassesResponse();

    context.getUser().setProperty("SuggestionsModel.simpleMode",
            request.getFilter().getParameterValue("simpleMode"));
    boolean simple = "1".equals(request.getFilter().getParameterValue("simpleMode"));
    SuggestionsModel model = (SuggestionsModel) context.getAttribute(SessionAttribute.SuggestionsModel);
    if (model != null)
        model.setSimpleMode(simple);/*from  w ww. j  av a  2  s. c om*/

    SolverProxy solver = courseTimetablingSolverService.getSolver();
    String subjects = request.getFilter().getParameterValue("subjectArea");
    context.setAttribute(SessionAttribute.OfferingsSubjectArea,
            isAllSubjects(subjects) ? Constants.ALL_OPTION_VALUE
                    : request.getFilter().getParameterValue("subjectArea"));
    String instructorNameFormat = UserProperty.NameFormat.get(context.getUser());

    String solutionIdsStr = (String) context.getAttribute(SessionAttribute.SelectedSolution);
    if (solver == null) {
        if (solutionIdsStr == null || solutionIdsStr.isEmpty()) {
            for (SolverGroup g : SolverGroup.getUserSolverGroups(context.getUser())) {
                for (Long id : (List<Long>) SolutionDAO.getInstance().getSession().createQuery(
                        "select s.uniqueId from Solution s where s.commited = true and s.owner = :groupId")
                        .setLong("groupId", g.getUniqueId()).setCacheable(true).list()) {
                    if (solutionIdsStr == null)
                        solutionIdsStr = id.toString();
                    else
                        solutionIdsStr += (solutionIdsStr.isEmpty() ? "" : ",") + id;
                }
            }
        }
        if (solutionIdsStr == null || solutionIdsStr.isEmpty())
            throw new GwtRpcException(MESSAGES.errorAssignedClassesNoSolution());
    }

    List<ClassAssignmentDetails> assignedClasses = new ArrayList<ClassAssignmentDetails>();
    if (isAllSubjects(subjects)) {
        if (solver != null) {
            assignedClasses = solver.getAssignedClasses();
        } else {
            org.hibernate.Session hibSession = SolutionDAO.getInstance().getSession();
            for (String solutionId : solutionIdsStr.split(",")) {
                Solution solution = SolutionDAO.getInstance().get(Long.valueOf(solutionId));
                try {
                    for (Assignment a : solution.getAssignments()) {
                        assignedClasses.add(new ClassAssignmentDetails(solution, a, false, hibSession,
                                instructorNameFormat));
                    }
                } catch (ObjectNotFoundException e) {
                    hibSession.refresh(solution);
                    for (Assignment a : solution.getAssignments()) {
                        assignedClasses.add(new ClassAssignmentDetails(solution, a, false, hibSession,
                                instructorNameFormat));
                    }
                }
            }
        }
    } else {
        org.hibernate.Session hibSession = SolutionDAO.getInstance().getSession();
        for (String id : subjects.split(",")) {
            String prefix = request.getFilter().getParameter("subjectArea").getOptionText(id) + " ";
            if (solver != null) {
                assignedClasses.addAll(solver.getAssignedClasses(prefix));
            } else {
                for (String solutionId : solutionIdsStr.split(",")) {
                    Solution solution = SolutionDAO.getInstance().get(Long.valueOf(solutionId));
                    try {
                        for (Assignment a : solution.getAssignments()) {
                            if (prefix != null && !a.getClassName().startsWith(prefix))
                                continue;
                            assignedClasses.add(new ClassAssignmentDetails(solution, a, false, hibSession,
                                    instructorNameFormat));
                        }
                    } catch (ObjectNotFoundException e) {
                        hibSession.refresh(solution);
                        for (Assignment a : solution.getAssignments()) {
                            if (prefix != null && !a.getClassName().startsWith(prefix))
                                continue;
                            assignedClasses.add(new ClassAssignmentDetails(solution, a, false, hibSession,
                                    instructorNameFormat));
                        }
                    }
                }
            }
        }
    }

    Collections.sort(assignedClasses);
    for (ClassAssignmentDetails ca : assignedClasses) {
        AssignmentPreferenceInfo ci = ca.getInfo();

        TableCellMulti studentConfs = new TableCellMulti();
        studentConfs.add(dispNumber(ci.getNrStudentConflicts()));

        if (ci.getNrCommitedStudentConflicts() != 0) {
            if (studentConfs.getNrChunks() <= 1)
                studentConfs.add(" (");
            else
                studentConfs.add(",");
            studentConfs.add(dispNumber(ci.getNrCommitedStudentConflicts())
                    .setFormattedValue("c" + ci.getNrCommitedStudentConflicts()));
        }
        if (ci.getNrDistanceStudentConflicts() != 0) {
            if (studentConfs.getNrChunks() <= 1)
                studentConfs.add(" (");
            else
                studentConfs.add(",");
            studentConfs.add(dispNumber(ci.getNrDistanceStudentConflicts())
                    .setFormattedValue("d" + ci.getNrDistanceStudentConflicts()));
        }
        if (ci.getNrHardStudentConflicts() != 0) {
            if (studentConfs.getNrChunks() <= 1)
                studentConfs.add(" (");
            else
                studentConfs.add(",");
            studentConfs.add(dispNumber(ci.getNrHardStudentConflicts())
                    .setFormattedValue("h" + ci.getNrHardStudentConflicts()));
        }
        if (studentConfs.getNrChunks() > 1)
            studentConfs.add(")");

        TableInterface.TableCellRooms rooms = new TableInterface.TableCellRooms();
        if (ca.getAssignedRoom() != null) {
            for (int i = 0; i < ca.getAssignedRoom().length; i++) {
                rooms.add(ca.getAssignedRoom()[i].getName(), ca.getAssignedRoom()[i].getColor(),
                        ca.getAssignedRoom()[i].getId(),
                        PreferenceLevel.int2string(ca.getAssignedRoom()[i].getPref()));
            }
        } else if (ca.getRoom() != null) {
            for (int i = 0; i < ca.getRoom().length; i++) {
                rooms.add(ca.getRoom()[i].getName(), ca.getRoom()[i].getColor(), ca.getRoom()[i].getId(),
                        PreferenceLevel.int2string(ca.getRoom()[i].getPref()));
            }
        }
        TableInterface.TableCellItems instructors = new TableInterface.TableCellItems();
        if (ca.getInstructor() != null)
            for (int i = 0; i < ca.getInstructor().length; i++) {
                instructors.add(ca.getInstructor()[i].getName(), ca.getInstructor()[i].getColor(),
                        ca.getInstructor()[i].getId());
            }
        TimeInfo time = (ca.getAssignedTime() != null ? ca.getAssignedTime() : ca.getTime());

        boolean showClassDetail = (solver == null
                && context.hasPermission(ca.getClazz().getClassId(), "Class_", Right.ClassDetail));

        if (simple)
            response.addRow(new TableRowInterface(ca.getClazz().getClassId(),
                    (showClassDetail ? "classDetail.do?cid=" + ca.getClazz().getClassId()
                            : "gwt.jsp?page=suggestions&menu=hide&id=" + ca.getClazz().getClassId()),
                    (showClassDetail ? null : MESSAGES.dialogSuggestions()),
                    new TableInterface.TableCellClassName(ca.getClazz().getName())
                            .setColor(PreferenceLevel.prolog2color(ca.getClazz().getPref())),
                    new TableCellInterface(time.getDatePatternName())
                            .setColor(PreferenceLevel.int2color(time.getDatePatternPreference())),
                    new TableInterface.TableCellTime(
                            time.getDaysName() + " " + time.getStartTime() + " - " + time.getEndTime())
                                    .setOrder(getOrder(time))
                                    .setId(ca.getClazz().getClassId() + "," + time.getDays() + ","
                                            + time.getStartSlot())
                                    .setColor(PreferenceLevel.int2color(time.getPref())),
                    rooms, instructors, studentConfs));
        else
            response.addRow(new TableRowInterface(ca.getClazz().getClassId(),
                    (showClassDetail ? "classDetail.do?cid=" + ca.getClazz().getClassId()
                            : "gwt.jsp?page=suggestions&menu=hide&id=" + ca.getClazz().getClassId()),
                    (showClassDetail ? null : MESSAGES.dialogSuggestions()),
                    new TableInterface.TableCellClassName(ca.getClazz().getName())
                            .setColor(PreferenceLevel.prolog2color(ca.getClazz().getPref())),
                    new TableCellInterface(time.getDatePatternName())
                            .setColor(PreferenceLevel.int2color(time.getDatePatternPreference())),
                    new TableInterface.TableCellTime(
                            time.getDaysName() + " " + time.getStartTime() + " - " + time.getEndTime())
                                    .setOrder(getOrder(time))
                                    .setId(ca.getClazz().getClassId() + "," + time.getDays() + ","
                                            + time.getStartSlot())
                                    .setColor(PreferenceLevel.int2color(time.getPref())),
                    rooms, instructors, studentConfs, dispNumber(ci.getTimePreference()),
                    dispNumber(ci.sumRoomPreference()), dispNumber(ci.getGroupConstraintPref()),
                    dispNumber(ci.getBtbInstructorPreference()), dispNumber(ci.getUselessHalfHours()),
                    dispNumber(ci.getTooBigRoomPreference()), dispNumber(ci.getDeptBalancPenalty()),
                    dispNumber(ci.getSpreadPenalty()), dispNumber(ci.getPerturbationPenalty())));
    }

    if (simple)
        response.setHeader(new TableHeaderIterface(MESSAGES.colClass()),
                new TableHeaderIterface(MESSAGES.colDate()), new TableHeaderIterface(MESSAGES.colTime()),
                new TableHeaderIterface(MESSAGES.colRoom()), new TableHeaderIterface(MESSAGES.colInstructor()),
                new TableHeaderIterface(MESSAGES.colNrStudentConflicts()));
    else
        response.setHeader(new TableHeaderIterface(MESSAGES.colClass()),
                new TableHeaderIterface(MESSAGES.colDate()), new TableHeaderIterface(MESSAGES.colTime()),
                new TableHeaderIterface(MESSAGES.colRoom()), new TableHeaderIterface(MESSAGES.colInstructor()),
                new TableHeaderIterface(MESSAGES.colShortStudentConflicts()),
                new TableHeaderIterface(MESSAGES.colShortTimePref()),
                new TableHeaderIterface(MESSAGES.colShortRoomPref()),
                new TableHeaderIterface(MESSAGES.colShortDistPref()),
                new TableHeaderIterface(MESSAGES.colShortInstructorBtbPref()),
                new TableHeaderIterface(MESSAGES.colShortUselessHalfHours()),
                new TableHeaderIterface(MESSAGES.colShortTooBigRooms()),
                new TableHeaderIterface(MESSAGES.colShortDepartmentBalance()),
                new TableHeaderIterface(MESSAGES.colShortSameSubpartBalance()),
                new TableHeaderIterface(MESSAGES.colShortPerturbations()));

    SolverPageBackend.fillSolverWarnings(context, solver, SolverType.COURSE, response);
    BackTracker.markForBack(context, "gwt.jsp?page=assignedClasses", MESSAGES.pageAssignedClasses(), true,
            true);

    if (ApplicationProperty.TimeGridShowCrosslists.isTrue())
        addCrosslistedNames(response, ApplicationProperty.SolverShowClassSufix.isTrue(),
                ApplicationProperty.SolverShowConfiguratioName.isTrue());

    return response;
}

From source file:org.webcurator.domain.TargetInstanceDAOImpl.java

License:Apache License

public void deleteScheduledInstances(final AbstractTarget anAbstractTarget) {
    // Remove all the target instances from one of the schedules.
    txTemplate.execute(new UnscheduleTargetTransaction(anAbstractTarget));

    // Reload the target from the database.
    getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session aSession) {
            aSession.refresh(anAbstractTarget);
            return null;
        }//from   w  ww. j  a  va2s.c o  m
    });

}