Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package it.unitn.elisco.dao; import it.unitn.elisco.bean.ContextBasics; import it.unitn.elisco.bean.CourseBasics; import it.unitn.elisco.bean.TaskBasics; import it.unitn.elisco.bean.ajax.PersonBasics; import it.unitn.elisco.bean.ajax.StudentBasics; import it.unitn.elisco.bean.hibernate.Administrator; import it.unitn.elisco.bean.hibernate.Context; import it.unitn.elisco.bean.hibernate.Course; import it.unitn.elisco.bean.hibernate.Person; import it.unitn.elisco.bean.hibernate.Sector; import it.unitn.elisco.bean.hibernate.Student; import it.unitn.elisco.bean.hibernate.Student_Course; import it.unitn.elisco.utils.HibernateUtil; import it.unitn.elisco.utils.Utilities; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.hibernate.*; import org.hibernate.criterion.*; import org.hibernate.transform.Transformers; /** * * @author Andrea Marcolin */ public class CourseDAO extends DAO<Course, Long> { public void addCourse(String name, String year, boolean open_subscription, Sector sector) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); insertCourse(s, name, year, open_subscription, sector); tx.commit(); s.close(); } public void deleteCourse(Course course) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); delete(s, course); tx.commit(); s.close(); } public void openSubscriptions(Course c, boolean open_subscriptions) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); c.setOpen_subscription(open_subscriptions); s.update(c); tx.commit(); s.close(); } public void addAdminToCourse(Course c, Administrator admin) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Since admins collection is lazy loaded, we need to reattach course to the session before the lazy load s.update(c); c.getAdmins().add(admin); s.update(c); tx.commit(); s.close(); } public void removeAdminFromCourse(Course course, Administrator admin) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Since admins collection is lazy loaded, we need to reattach course to the session before the lazy load s.update(course); course.getAdmins().remove(admin); s.update(course); tx.commit(); s.close(); } public Course findCourseByNameAndYear(String name, String year) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Fetch course: // - which has the specified name // - which has the specified year Criteria criteria = s.createCriteria(Course.class); criteria.add(Restrictions.eq("name", name)); criteria.add(Restrictions.eq("year", year)); Course res = (Course) criteria.uniqueResult(); tx.commit(); s.close(); return res; } public List<String> findCourseNames(String name) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Fetch courses: // - which name begins with the specified query (optional, otherwise return all courses) Criteria criteria = s.createCriteria(Course.class); if (name != null && !name.equals("")) { criteria.add(Restrictions.like("name", name, MatchMode.START)); } // Then return results as Strings, returning distinct names criteria.setProjection(Projections.distinct(Projections.property("name"))); List<String> res = criteria.list(); tx.commit(); s.close(); return res; } public List<String> findCourseYears(String name, String year) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Fetch courses years of courses: // - which have the specified name // - which year begins with the specified query (optional, otherwise return all course years) Criteria criteria = s.createCriteria(Course.class); criteria.add(Restrictions.eq("name", name)); if (year != null && !year.equals("")) { criteria.add(Restrictions.like("year", year, MatchMode.START)); } // Then return results as Strings criteria.setProjection(Projections.property("year")); List<String> res = criteria.list(); tx.commit(); s.close(); return res; } public List<String> findCourseNamesByAdmin(Administrator admin, String name) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Fetch courses: // - which are administrated by specified admin // - which name begins with the specified query (optional, otherwise return all courses) Criteria criteria = s.createCriteria(Course.class); criteria.createCriteria("admins").add(Restrictions.eq("email", admin.getEmail())); if (name != null && !name.equals("")) { criteria.add(Restrictions.like("name", name, MatchMode.START)); } // Then return results as Strings, returning distinct names criteria.setProjection(Projections.distinct(Projections.property("name"))); List<String> res = criteria.list(); tx.commit(); s.close(); return res; } public List<String> findCourseYearsByAdmin(Administrator admin, String name, String year) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Fetch courses years of courses: // - which are administrated by specified admin // - which have the specified name // - which year begins with the specified query (optional, otherwise return all years) Criteria criteria = s.createCriteria(Course.class); criteria.createCriteria("admins").add(Restrictions.eq("email", admin.getEmail())); criteria.add(Restrictions.eq("name", name)); if (year != null && !year.equals("")) { criteria.add(Restrictions.like("year", year, MatchMode.START)); } // Then return results as Strings, returning distinct names criteria.setProjection(Projections.property("year")); List<String> res = criteria.list(); tx.commit(); s.close(); return res; } public List<PersonBasics> findAdminsLikeForCourse(String name, String year, String adminEmail) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Fetch admins: // - which administrates the specified course // - which email begins with the specified query (optional, otherwise return all admins for the course) Criteria criteria = s.createCriteria(Course.class); criteria.add(Restrictions.eq("name", name)).add(Restrictions.eq("year", year)); criteria.createAlias("admins", "a"); if (adminEmail != null && !adminEmail.equals("")) { criteria.add(Restrictions.like("a.email", adminEmail, MatchMode.START)); } // Then return results as PersonBasics objects criteria.setProjection(Projections.projectionList().add(Projections.property("a.name"), "name") .add(Projections.property("a.surname"), "surname").add(Projections.property("a.email"), "email")) .setResultTransformer(Transformers.aliasToBean(PersonBasics.class)); List<PersonBasics> res = criteria.list(); tx.commit(); s.close(); return res; } public List<ContextBasics> findContextsLikeForCourse(String name, String year, String title) { ContextDAO ctxdao = new ContextDAO(); Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Fetch contexts: // - which belong to the specified course // - which title starts with the specified query (optional, otherwise return all contexts for the course) Criteria criteria = s.createCriteria(Context.class); criteria.createCriteria("course").add(Restrictions.eq("name", name)).add(Restrictions.eq("year", year)); if (title != null && !title.equals("")) { criteria.add(Restrictions.like("title", title, MatchMode.START)); } List<Context> contexts = criteria.list(); tx.commit(); s.close(); List<ContextBasics> res = new ArrayList<>(); for (Context ctx : contexts) { ContextBasics basics = ctxdao.getContextBasics(ctx); switch (ctx.getCurrentTaskType()) { case BEGIN: case WAITING: // In these two cases, admin can immediately start a task // We also need to set the last completed task basics.setNextTaskType(ctxdao.getNextTaskType(ctx).getDescription()); basics.setReadyForNextTask(true); break; default: // In all other cases, admin needs to wait until the task ends basics.setNextTaskType(ctx.getCurrentTaskType().getDescription()); basics.setReadyForNextTask(false); break; } basics.setCurrentTask(ctxdao.getCurrentTaskInfo(ctx)); res.add(basics); } return res; } public List<StudentBasics> getRankings(String name, String year) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Fetch rankings (student info) for specified course Criteria criteria = s.createCriteria(Course.class); criteria.add(Restrictions.eq("name", name)).add(Restrictions.eq("year", year)); criteria.createAlias("students", "sc").createAlias("sc.student", "s") .addOrder(Property.forName("sc.score").desc()); // Then return results as PersonBasics objects criteria.setProjection(Projections.projectionList().add(Projections.property("s.id"), "id") .add(Projections.property("s.email"), "email").add(Projections.property("s.name"), "name") .add(Projections.property("s.surname"), "surname") .add(Projections.property("s.imagePath"), "imagePath") .add(Projections.property("s.student_number"), "student_number") .add(Projections.property("sc.score"), "score")) .setResultTransformer(Transformers.aliasToBean(StudentBasics.class)); List<StudentBasics> res = criteria.list(); tx.commit(); s.close(); return res; } public List<Student> getStudents(Course course) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Fetch students which are subscribed to the specified course Criteria criteria = s.createCriteria(Student_Course.class); criteria.add(Restrictions.eq("course", course)).setProjection(Projections.property("student")); List<Student> res = criteria.list(); tx.commit(); s.close(); return res; } public List<String> getStudentEmails(Course course) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Fetch email addresses of students subscribed to the specified course Criteria criteria = s.createCriteria(Student_Course.class); criteria.add(Restrictions.eq("course", course)); criteria.createAlias("student", "s"); criteria.setProjection(Projections.property("s.email")); List<String> res = criteria.list(); tx.commit(); s.close(); return res; } public List<String> getAdminsEmails(Course course) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Fetch email addresses of admins of the specified course Set<Administrator> admins = course.getAdmins(); List<String> res = new ArrayList<>(); for (Administrator admin : admins) { res.add(admin.getEmail()); } tx.commit(); s.close(); return res; } public Course getCourse(long id) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); Course res = findCourse(s, id); tx.commit(); s.close(); return res; } public List<CourseBasics> getCourses(Person person) { ContextDAO ctxdao = new ContextDAO(); Student_CourseDAO scdao = new Student_CourseDAO(); Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Get courses based on the person List<Course> courses; if (person instanceof Administrator) { if (((Administrator) person).isIsSysAdmin()) { courses = scdao.getAllCourses(s); } else { Administrator admin = (Administrator) person; courses = scdao.getCoursesForAdmin(s, admin); } } else { Student student = (Student) person; courses = scdao.getCoursesForStudent(s, student); } List<CourseBasics> res = new ArrayList<>(); Context fullContext; // Get active contexts data for each course for (Course fullCourse : courses) { CourseBasics course = new CourseBasics(fullCourse.getId(), fullCourse.getName(), fullCourse.getSector().getCssClassName()); // Get basic info of last context for this course (the "younger" one, the last inserted context) course.setCurrentContext(getCurrentContextBasics(s, fullCourse)); // If the course has at least one context, get some other infos if (course.getCurrentContext() != null) { // Fetch all infos about the last context from database fullContext = ctxdao.getContext(course.getCurrentContext().getId()); // Get context's current task type and set it to the result course.getCurrentContext().setCurrentTask(new TaskBasics()); course.getCurrentContext().getCurrentTask() .setType(fullContext.getCurrentTaskType().getDescription()); // If the tasktype is question, answer or evaluation, also get the deadline switch (fullContext.getCurrentTaskType()) { case QUESTION: course.getCurrentContext().getCurrentTask() .setDeadline(Utilities.parseCalendarDate(fullContext.getQuestion_end(), "dd/MM/YYYY")); break; case ANSWER: course.getCurrentContext().getCurrentTask() .setDeadline(Utilities.parseCalendarDate(fullContext.getAnswer_end(), "dd/MM/YYYY")); break; case EVALUATION: course.getCurrentContext().getCurrentTask().setDeadline( Utilities.parseCalendarDate(fullContext.getEvaluation_end(), "dd/MM/YYYY")); break; default: break; } } res.add(course); } tx.commit(); s.close(); return res; } public List<Course> getCourses() { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); List<Course> res = s.createCriteria(Course.class).list(); for (Course c : res) { Hibernate.initialize(c.getStudents()); } tx.commit(); s.close(); return res; } public List<CourseBasics> getCourseSubscriptions(Student student) { Student_CourseDAO scdao = new Student_CourseDAO(); CourseDAO cdao = new CourseDAO(); Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); // Get all courses Criteria criteria = s.createCriteria(Course.class); criteria.add(Restrictions.eq("open_subscription", true)); criteria.createAlias("sector", "sec"); criteria.setProjection(Projections.projectionList().add(Projections.property("id"), "id") .add(Projections.property("name"), "name").add(Projections.property("sec.cssClassName"), "sector")) .setResultTransformer(Transformers.aliasToBean(CourseBasics.class)); List<CourseBasics> res = criteria.list(); for (CourseBasics course : res) { course.setSubscribed(scdao.getSubscription(s, student, cdao.findCourse(s, course.getId())) != null); } tx.commit(); s.close(); return res; } public CourseBasics getCourseBasics(Course c) { return new CourseBasics(c.getId(), c.getName(), c.getSector().getCssClassName()); } // Auxiliary methods private void insertCourse(Session s, String name, String year, boolean open_subscription, Sector sector) { Course course = new Course(); course.setName(name); course.setYear(year); course.setOpen_subscription(open_subscription); course.setSector(sector); insert(s, course); } private ContextBasics getCurrentContextBasics(Session s, Course course) { DetachedCriteria maxId = DetachedCriteria.forClass(Context.class).add(Restrictions.eq("course", course)) .setProjection(Projections.max("id")); Criteria criteria = s.createCriteria(Context.class); criteria.add(Property.forName("id").eq(maxId)); criteria.setProjection(Projections.projectionList().add(Projections.property("id"), "id") .add(Projections.property("title"), "title").add(Projections.property("subtitle"), "subtitle")) .setResultTransformer(Transformers.aliasToBean(ContextBasics.class)); return (ContextBasics) criteria.uniqueResult(); } private Course findCourse(Session s, long id) { return getByPrimarykey(s, Course.class, id); } }