Index: lams_build/lib/lams/lams.jar
===================================================================
diff -u -r01cc9502760d6b2a784d254efc95adc700a15e25 -ref2417616a93e7d6f1eaee601fd78455a90564d6
Binary files differ
Index: lams_common/conf/hibernate/mappings/org/lamsfoundation/lams/lesson/Lesson.hbm.xml
===================================================================
diff -u -rfdca3605f0b782b19e214abbe94df6f4a457b88e -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_common/conf/hibernate/mappings/org/lamsfoundation/lams/lesson/Lesson.hbm.xml (.../Lesson.hbm.xml) (revision fdca3605f0b782b19e214abbe94df6f4a457b88e)
+++ lams_common/conf/hibernate/mappings/org/lamsfoundation/lams/lesson/Lesson.hbm.xml (.../Lesson.hbm.xml) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -123,6 +123,26 @@
AND ({lesson}.class_grouping_id IS NULL)
AND NOT ({lesson}.lesson_state_id = 7)
+
+
+
+ SELECT DISTINCT {user.*}
+ FROM lams_lesson,
+ lams_grouping,
+ lams_group,
+ lams_user_group,
+ lams_learning_design,
+ lams_tool_session,
+ lams_user {user}
+ WHERE (lams_lesson.class_grouping_id = lams_grouping.grouping_id)
+ AND (lams_grouping.staff_group_id = lams_group.group_id)
+ AND (lams_group.group_id = lams_user_group.group_id)
+ AND ({user}.user_id = lams_user_group.user_id)
+ AND (lams_tool_session.tool_session_id = :sessionId)
+ AND (lams_tool_session.lesson_id = lams_lesson.lesson_id)
+ AND (lams_lesson.learning_design_id = lams_learning_design.learning_design_id)
+ AND (lams_learning_design.copy_type_id=2)
+
Index: lams_common/src/java/org/lamsfoundation/lams/lesson/dao/ILessonDAO.java
===================================================================
diff -u -r6008e13a4cc3e08a3350be02c35a22eb6ee5a9c1 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_common/src/java/org/lamsfoundation/lams/lesson/dao/ILessonDAO.java (.../ILessonDAO.java) (revision 6008e13a4cc3e08a3350be02c35a22eb6ee5a9c1)
+++ lams_common/src/java/org/lamsfoundation/lams/lesson/dao/ILessonDAO.java (.../ILessonDAO.java) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -32,127 +32,160 @@
/**
* Inteface defines Lesson DAO Methods
+ *
* @author chris
*/
-public interface ILessonDAO extends IBaseDAO
-{
-
+public interface ILessonDAO extends IBaseDAO {
+
/**
* Retrieves the Lesson
- * @param lessonId identifies the lesson to get
+ *
+ * @param lessonId
+ * identifies the lesson to get
* @return the lesson
*/
public Lesson getLesson(Long lessonId);
-
+
/** Get all the lessons in the database. This includes the disabled lessons. */
public List getAllLessons();
-
+
public Lesson getLessonWithJoinFetchedProgress(Long lessonId);
+
/**
- * Gets all lessons that are active for a learner.
- * TODO to be removed when the dummy interface is no longer needed
- * @param learner a User that identifies the learner.
+ * Gets all lessons that are active for a learner. TODO to be removed when the dummy interface is no longer needed
+ *
+ * @param learner
+ * a User that identifies the learner.
* @return a Set with all active lessons in it.
*/
public List getActiveLessonsForLearner(User learner);
-
+
/**
* Gets all lessons that are active for a learner, in a given organisation
- * @param learnerId a User that identifies the learner.
- * @param organisationId the desired organisation .
+ *
+ * @param learnerId
+ * a User that identifies the learner.
+ * @param organisationId
+ * the desired organisation .
* @return a List with all active lessons in it.
*/
public List getActiveLessonsForLearner(final Integer learnerId, final Integer organisationID);
/**
* Saves or Updates a Lesson.
- * @param lesson the Lesson to save
+ *
+ * @param lesson
+ * the Lesson to save
*/
public void saveLesson(Lesson lesson);
-
+
/**
* Deletes a Lesson permanently.
- * @param lesson the Lesson to remove.
+ *
+ * @param lesson
+ * the Lesson to remove.
*/
public void deleteLesson(Lesson lesson);
-
+
/**
* Update a requested lesson.
+ *
* @param createdLesson
*/
public void updateLesson(Lesson lesson);
-
+
/**
- * Returns the list of available Lessons created by
- * a given user. Does not return disabled lessons or preview lessons.
- *
- * @param userID The user_id of the user
+ * Returns the list of available Lessons created by a given user. Does not return disabled lessons or preview
+ * lessons.
+ *
+ * @param userID
+ * The user_id of the user
* @return List The list of Lessons for the given user
*/
public List getLessonsCreatedByUser(Integer userID);
-
+
/**
- * Gets all lessons in the given organisation, for which this user is in the staff group. Does not return
- * disabled lessons or preview lessons. This is the list of lessons that a user may monitor/moderate/manage.
- * @param user a User that identifies the teacher/staff member.
+ * Gets all lessons in the given organisation, for which this user is in the staff group. Does not return disabled
+ * lessons or preview lessons. This is the list of lessons that a user may monitor/moderate/manage.
+ *
+ * @param user
+ * a User that identifies the teacher/staff member.
* @return a List with all appropriate lessons in it.
*/
public List getLessonsForMonitoring(final int userID, final int organisationID);
/**
* Returns the all the learners that have started the requested lesson.
*
- * @param lessonId the id of the requested lesson.
+ * @param lessonId
+ * the id of the requested lesson.
* @return the list of learners.
*/
public List getActiveLearnerByLesson(final long lessonId);
/**
- * Returns the all the learners that have started the requested lesson and
- * are in the given group.
- *
- * @param lessonId the id of the requested lesson.
- * @param groupId the id of the requested group.
+ * Returns the all the learners that have started the requested lesson and are in the given group.
+ *
+ * @param lessonId
+ * the id of the requested lesson.
+ * @param groupId
+ * the id of the requested group.
* @return the list of learners.
*/
public List getActiveLearnerByLessonAndGroup(final long lessonId, final long groupId);
-
+
/**
* Returns the count of all the learners that have started the requested lesson.
*
- * @param lessonId the id of the requested lesson.
+ * @param lessonId
+ * the id of the requested lesson.
* @return the count of the learners.
*/
public Integer getCountActiveLearnerByLesson(final long lessonId);
-
+
/**
* Get all the preview lessons more with the creation date before the given date.
*
- * @param startDate UTC date
+ * @param startDate
+ * UTC date
* @return the list of Lessons
*/
public List getPreviewLessonsBeforeDate(final Date startDate);
-
+
/**
* Get the lesson that applies to this activity. Not all activities have an attached lesson.
*/
public Lesson getLessonForActivity(final long activityId);
-
+
/**
- * Gets all non-removed lessons for a user in an org; set isStaff flag whether you want lessons where user
- * is in the staff list, or just in the learner list.
- * @param userId a user id that identifies the user.
- * @param orgId an org id that identifies the organisation.
- * @param isStaff boolean flag for whether user is staff in returned lessons.
+ * Gets all non-removed lessons for a user in an org; set isStaff flag whether you want lessons where user is in the
+ * staff list, or just in the learner list.
+ *
+ * @param userId
+ * a user id that identifies the user.
+ * @param orgId
+ * an org id that identifies the organisation.
+ * @param isStaff
+ * boolean flag for whether user is staff in returned lessons.
* @return a List containing a list of tuples containing lesson details and the lesson completed flag for the user.
*/
public List getLessonsByOrgAndUserWithCompletedFlag(final Integer userId, final Integer orgId, final boolean isStaff);
/**
* Get lessons based on learning designs where the original learning design has the given id.
+ *
* @param ldId
* @param orgId
* @return list of lessons
*/
public List getLessonsByOriginalLearningDesign(final Long ldId, final Integer orgId);
+
+ /**
+ * Finds out which lesson the given tool content belongs to and returns its monitoring users.
+ *
+ * @param sessionId
+ * tool session ID
+ * @return list of teachers that monitor the lesson which contains the tool with given session ID
+ */
+ public List getMonitorsByToolSessionId(Long sessionId);
}
Index: lams_common/src/java/org/lamsfoundation/lams/lesson/dao/hibernate/LessonDAO.java
===================================================================
diff -u -r6008e13a4cc3e08a3350be02c35a22eb6ee5a9c1 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_common/src/java/org/lamsfoundation/lams/lesson/dao/hibernate/LessonDAO.java (.../LessonDAO.java) (revision 6008e13a4cc3e08a3350be02c35a22eb6ee5a9c1)
+++ lams_common/src/java/org/lamsfoundation/lams/lesson/dao/hibernate/LessonDAO.java (.../LessonDAO.java) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -30,7 +30,7 @@
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
-import org.hibernate.criterion.Expression;
+import org.hibernate.criterion.Restrictions;
import org.lamsfoundation.lams.dao.hibernate.BaseDAO;
import org.lamsfoundation.lams.learningdesign.Activity;
import org.lamsfoundation.lams.learningdesign.LearningDesign;
@@ -40,304 +40,283 @@
import org.lamsfoundation.lams.usermanagement.User;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
+
/**
* Hibernate implementation of ILessonDAO
+ *
* @author chris
*/
-public class LessonDAO extends BaseDAO implements ILessonDAO
-{
- private final static String FIND_LESSON_BY_CREATOR="from "
- + Lesson.class.getName()
- + " lesson where lesson.user.userId=? and lesson.lessonStateId <= 6 and "
- +" lesson.learningDesign.copyTypeID="
- + LearningDesign.COPY_TYPE_LESSON;
- private final static String FIND_PREVIEW_BEFORE_START_DATE= "from "
- + Lesson.class.getName()
- + " lesson where lesson.learningDesign.copyTypeID="
- + LearningDesign.COPY_TYPE_PREVIEW
- + "and lesson.startDateTime is not null and lesson.startDateTime < ?";
- private final static String COUNT_ACTIVE_LEARNERS = "select count(distinct progress.user.id)"
- + " from "+LearnerProgress.class.getName()+" progress"
- + " where progress.lesson.id = :lessonId";
- private final static String FIND_LESSON_FOR_ACTIVITY = "select lesson from "
- + Lesson.class.getName()+" lesson, "+ Activity.class.getName() + " activity "
- + " where activity.activityId=:activityId and activity.learningDesign=lesson.learningDesign";
- private final static String LESSONS_WITH_ORIGINAL_LEARNING_DESIGN = "select l from "
- + Lesson.class.getName() + " l "
- + "where l.learningDesign.originalLearningDesign.learningDesignId = ? "
- + "and l.learningDesign.copyTypeID != " + LearningDesign.COPY_TYPE_PREVIEW + " "
- + "and l.lessonStateId = " + Lesson.STARTED_STATE + " "
- + "and l.organisation.organisationId = ? "
- + " order by l.lessonName";
+public class LessonDAO extends BaseDAO implements ILessonDAO {
+ private final static String FIND_LESSON_BY_CREATOR = "from " + Lesson.class.getName()
+ + " lesson where lesson.user.userId=? and lesson.lessonStateId <= 6 and "
+ + " lesson.learningDesign.copyTypeID=" + LearningDesign.COPY_TYPE_LESSON;
+ private final static String FIND_PREVIEW_BEFORE_START_DATE = "from " + Lesson.class.getName()
+ + " lesson where lesson.learningDesign.copyTypeID=" + LearningDesign.COPY_TYPE_PREVIEW
+ + "and lesson.startDateTime is not null and lesson.startDateTime < ?";
+ private final static String COUNT_ACTIVE_LEARNERS = "select count(distinct progress.user.id)" + " from "
+ + LearnerProgress.class.getName() + " progress" + " where progress.lesson.id = :lessonId";
+ private final static String FIND_LESSON_FOR_ACTIVITY = "select lesson from " + Lesson.class.getName() + " lesson, "
+ + Activity.class.getName() + " activity "
+ + " where activity.activityId=:activityId and activity.learningDesign=lesson.learningDesign";
+ private final static String LESSONS_WITH_ORIGINAL_LEARNING_DESIGN = "select l from " + Lesson.class.getName()
+ + " l " + "where l.learningDesign.originalLearningDesign.learningDesignId = ? "
+ + "and l.learningDesign.copyTypeID != " + LearningDesign.COPY_TYPE_PREVIEW + " " + "and l.lessonStateId = "
+ + Lesson.STARTED_STATE + " " + "and l.organisation.organisationId = ? " + " order by l.lessonName";
/**
- * Retrieves the Lesson. Used in instances where it cannot be lazy loaded so it forces
- * an initialize.
- * @param lessonId identifies the lesson to get
+ * Retrieves the Lesson. Used in instances where it cannot be lazy loaded so it forces an initialize.
+ *
+ * @param lessonId
+ * identifies the lesson to get
* @return the lesson
*/
- public Lesson getLesson(Long lessonId)
- {
- Lesson lesson = (Lesson)getHibernateTemplate().get(Lesson.class, lessonId);
- return lesson;
+ public Lesson getLesson(Long lessonId) {
+ Lesson lesson = (Lesson) getHibernateTemplate().get(Lesson.class, lessonId);
+ return lesson;
}
-
-
- public Lesson getLessonWithJoinFetchedProgress(final Long lessonId)
- {
- HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
- return (Lesson)hibernateTemplate.execute(
- new HibernateCallback()
- {
- public Object doInHibernate(Session session) throws HibernateException
- {
- return session.createCriteria(Lesson.class)
- .add(Expression.like("lessonId",lessonId))
- .setFetchMode("learnerProgresses",FetchMode.JOIN)
- .uniqueResult();
- }
- }
- );
+ public Lesson getLessonWithJoinFetchedProgress(final Long lessonId) {
+ HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
+
+ return (Lesson) hibernateTemplate.execute(new HibernateCallback() {
+ public Object doInHibernate(Session session) throws HibernateException {
+ return session.createCriteria(Lesson.class).add(Restrictions.like("lessonId", lessonId)).setFetchMode(
+ "learnerProgresses", FetchMode.JOIN).uniqueResult();
+ }
+ });
}
-
+
/** Get all the lessons in the database. This includes the disabled lessons. */
- public List getAllLessons()
- {
- return getHibernateTemplate().loadAll(Lesson.class);
+ public List getAllLessons() {
+ return getHibernateTemplate().loadAll(Lesson.class);
}
-
- /**
+
+ /**
* Gets all lessons that are active for a learner.
- * @param learner a User that identifies the learner.
+ *
+ * @param learner
+ * a User that identifies the learner.
* @return a List with all active lessons in it.
*/
- public List getActiveLessonsForLearner(final User learner)
- {
- List lessons = null;
-
- HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
- lessons = (List)hibernateTemplate.execute(
- new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- Query query = session.getNamedQuery("activeLessonsAllOrganisations");
- query.setInteger("userId", learner.getUserId().intValue());
- List result = query.list();
- return result;
- }
- }
- );
- return lessons;
+ public List getActiveLessonsForLearner(final User learner) {
+ List lessons = null;
+
+ HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
+ lessons = (List) hibernateTemplate.execute(new HibernateCallback() {
+ public Object doInHibernate(Session session) throws HibernateException {
+ Query query = session.getNamedQuery("activeLessonsAllOrganisations");
+ query.setInteger("userId", learner.getUserId().intValue());
+ List result = query.list();
+ return result;
+ }
+ });
+ return lessons;
}
-
+
/**
* Gets all lessons that are active for a learner, in a given organisation
- * @param learnerId a User that identifies the learner.
- * @param organisationId the desired organisation.
+ *
+ * @param learnerId
+ * a User that identifies the learner.
+ * @param organisationId
+ * the desired organisation.
* @return a List with all active lessons in it.
*/
- public List getActiveLessonsForLearner(final Integer learnerId, final Integer organisationId)
- {
- List lessons = null;
-
- HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
- lessons = (List)hibernateTemplate.execute(
- new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- Query query = session.getNamedQuery("activeLessons");
- query.setInteger("userId", learnerId);
- query.setInteger("organisationId", organisationId);
- List result = query.list();
- return result;
- }
- }
- );
- return lessons;
+ public List getActiveLessonsForLearner(final Integer learnerId, final Integer organisationId) {
+ List lessons = null;
+
+ HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
+ lessons = (List) hibernateTemplate.execute(new HibernateCallback() {
+ public Object doInHibernate(Session session) throws HibernateException {
+ Query query = session.getNamedQuery("activeLessons");
+ query.setInteger("userId", learnerId);
+ query.setInteger("organisationId", organisationId);
+ List result = query.list();
+ return result;
+ }
+ });
+ return lessons;
}
/**
* @see org.lamsfoundation.lams.lesson.dao.ILessonDAO#getActiveLearnerByLesson(long)
*/
- public List getActiveLearnerByLesson(final long lessonId)
- {
- List learners = null;
-
- HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
- learners = (List)hibernateTemplate.execute(
- new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- Query query = session.getNamedQuery("activeLearners");
- query.setLong("lessonId", lessonId);
- List result = query.list();
- return result;
- }
- }
- );
- return learners;
+ public List getActiveLearnerByLesson(final long lessonId) {
+ List learners = null;
+
+ HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
+ learners = (List) hibernateTemplate.execute(new HibernateCallback() {
+ public Object doInHibernate(Session session) throws HibernateException {
+ Query query = session.getNamedQuery("activeLearners");
+ query.setLong("lessonId", lessonId);
+ List result = query.list();
+ return result;
+ }
+ });
+ return learners;
}
/**
* @see org.lamsfoundation.lams.lesson.dao.ILessonDAO#getActiveLearnerByLessonAndGroup(long, long)
*/
- public List getActiveLearnerByLessonAndGroup(final long lessonId, final long groupId)
- {
- List learners = null;
-
- HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
- learners = (List)hibernateTemplate.execute(
- new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- Query query = session.getNamedQuery("activeLearnersByGroup");
- query.setLong("lessonId", lessonId);
- query.setLong("groupId", groupId);
- List result = query.list();
- return result;
- }
- }
- );
- return learners;
+ public List getActiveLearnerByLessonAndGroup(final long lessonId, final long groupId) {
+ List learners = null;
+
+ HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
+ learners = (List) hibernateTemplate.execute(new HibernateCallback() {
+ public Object doInHibernate(Session session) throws HibernateException {
+ Query query = session.getNamedQuery("activeLearnersByGroup");
+ query.setLong("lessonId", lessonId);
+ query.setLong("groupId", groupId);
+ List result = query.list();
+ return result;
+ }
+ });
+ return learners;
}
/**
- * @see org.lamsfoundation.lams.lesson.dao.ILessonDAO#getActiveLearnerByLesson(long)
- * Note: Hibernate 3.1 query.uniqueResult() returns Integer, Hibernate 3.2 query.uniqueResult() returns Long
+ * @see org.lamsfoundation.lams.lesson.dao.ILessonDAO#getActiveLearnerByLesson(long) Note: Hibernate 3.1
+ * query.uniqueResult() returns Integer, Hibernate 3.2 query.uniqueResult() returns Long
*/
- public Integer getCountActiveLearnerByLesson(final long lessonId)
- {
- HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
- return (Integer) hibernateTemplate.execute(new HibernateCallback() {
- public Object doInHibernate(Session session)
- throws HibernateException {
- Query query = session.createQuery(COUNT_ACTIVE_LEARNERS);
- query.setLong("lessonId", lessonId);
- Object value = query.uniqueResult();
- return new Integer (((Number)value).intValue());
- }
- });
+ public Integer getCountActiveLearnerByLesson(final long lessonId) {
+ HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
+ return (Integer) hibernateTemplate.execute(new HibernateCallback() {
+ public Object doInHibernate(Session session) throws HibernateException {
+ Query query = session.createQuery(LessonDAO.COUNT_ACTIVE_LEARNERS);
+ query.setLong("lessonId", lessonId);
+ Object value = query.uniqueResult();
+ return new Integer(((Number) value).intValue());
+ }
+ });
}
-/**f
- * Saves or Updates a Lesson.
+
+ /**
+ * f Saves or Updates a Lesson.
+ *
* @param lesson
*/
- public void saveLesson(Lesson lesson)
- {
- getHibernateTemplate().save(lesson);
+ public void saveLesson(Lesson lesson) {
+ getHibernateTemplate().save(lesson);
}
-
+
/**
* Deletes a Lesson permanently.
+ *
* @param lesson
*/
- public void deleteLesson(Lesson lesson)
- {
- getHibernateTemplate().delete(lesson);
+ public void deleteLesson(Lesson lesson) {
+ getHibernateTemplate().delete(lesson);
}
-
-
/**
* Update the lesson data
+ *
* @see org.lamsfoundation.lams.lesson.dao.ILessonDAO#updateLesson(org.lamsfoundation.lams.lesson.Lesson)
*/
- public void updateLesson(Lesson lesson)
- {
- getHibernateTemplate().update(lesson);
+ public void updateLesson(Lesson lesson) {
+ getHibernateTemplate().update(lesson);
}
-
+
/**
- * Returns the list of available Lessons created by
- * a given user. Does not return disabled lessons or preview lessons.
+ * Returns the list of available Lessons created by a given user. Does not return disabled lessons or preview
+ * lessons.
*
- * @param userID The user_id of the user
+ * @param userID
+ * The user_id of the user
* @return List The list of Lessons for the given user
*/
- public List getLessonsCreatedByUser(Integer userID){
- List lessons = this.getHibernateTemplate().find(FIND_LESSON_BY_CREATOR,userID);
- return lessons;
+ public List getLessonsCreatedByUser(Integer userID) {
+ List lessons = this.getHibernateTemplate().find(LessonDAO.FIND_LESSON_BY_CREATOR, userID);
+ return lessons;
}
-
- /**
- * Gets all lessons in the given organisation, for which this user is in the staff group. Does not return
- * disabled lessons or preview lessons. This is the list of lessons that a user may monitor/moderate/manage.
- * @param user a User that identifies the teacher/staff member.
- * @return a List with all appropriate lessons in it.
- */
- public List getLessonsForMonitoring(final int userID, final int organisationID)
- {
- List lessons = null;
-
- HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
- lessons = (List)hibernateTemplate.execute(
- new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- Query query = session.getNamedQuery("lessonsForMonitoring");
- query.setInteger("userId", userID);
- query.setInteger("organisationId", organisationID);
- List result = query.list();
- return result;
- }
- }
- );
- return lessons;
- }
- /**
- * Get all the preview lessons more with the creation date before the given date.
- *
- * @param startDate UTC date
- * @return the list of Lessons
- */
- public List getPreviewLessonsBeforeDate(final Date startDate){
- List lessons = this.getHibernateTemplate().find(FIND_PREVIEW_BEFORE_START_DATE,startDate);
+
+ /**
+ * Gets all lessons in the given organisation, for which this user is in the staff group. Does not return disabled
+ * lessons or preview lessons. This is the list of lessons that a user may monitor/moderate/manage.
+ *
+ * @param user
+ * a User that identifies the teacher/staff member.
+ * @return a List with all appropriate lessons in it.
+ */
+ public List getLessonsForMonitoring(final int userID, final int organisationID) {
+ List lessons = null;
+
+ HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
+ lessons = (List) hibernateTemplate.execute(new HibernateCallback() {
+ public Object doInHibernate(Session session) throws HibernateException {
+ Query query = session.getNamedQuery("lessonsForMonitoring");
+ query.setInteger("userId", userID);
+ query.setInteger("organisationId", organisationID);
+ List result = query.list();
+ return result;
+ }
+ });
return lessons;
- }
- /**
- * Get the lesson that applies to this activity. Not all activities have an attached lesson.
- */
- public Lesson getLessonForActivity(final long activityId)
- {
- HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
- return (Lesson) hibernateTemplate.execute(new HibernateCallback() {
- public Object doInHibernate(Session session)
- throws HibernateException {
- Query query = session.createQuery(FIND_LESSON_FOR_ACTIVITY);
- query.setLong("activityId", activityId);
- return query.uniqueResult();
- }
- });
- }
-
- /**
- * @see org.lamsfoundation.lams.lesson.dao.ILessonDAO#getLessonsByOrgAndUserWithCompletedFlag(Integer, Integer, boolean)
- */
- public List getLessonsByOrgAndUserWithCompletedFlag(final Integer userId, final Integer orgId, final boolean isStaff)
- {
- List dtos = null;
-
- HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
- dtos = (List)hibernateTemplate.execute(
- new HibernateCallback() {
- public Object doInHibernate(Session session) throws HibernateException {
- Query query = session.getNamedQuery(
- isStaff ? "staffLessonsByOrgAndUserWithCompletedFlag" : "learnerLessonsByOrgAndUserWithCompletedFlag"
- );
- query.setInteger("userId", userId.intValue());
- query.setInteger("orgId", orgId.intValue());
- List result = query.list();
- return result;
- }
- }
- );
- return dtos;
- }
-
- /**
- * @see org.lamsfoundation.lams.lesson.dao.ILessonDAO#getLessonsByOriginalLearningDesign(Integer)
- */
- public List getLessonsByOriginalLearningDesign(final Long ldId, final Integer orgId)
- {
- Object[] args = {ldId.longValue(), orgId.intValue()};
- List lessons = this.getHibernateTemplate().find(LESSONS_WITH_ORIGINAL_LEARNING_DESIGN, args);
- return lessons;
- }
+ }
+ /**
+ * Get all the preview lessons more with the creation date before the given date.
+ *
+ * @param startDate
+ * UTC date
+ * @return the list of Lessons
+ */
+ public List getPreviewLessonsBeforeDate(final Date startDate) {
+ List lessons = this.getHibernateTemplate().find(LessonDAO.FIND_PREVIEW_BEFORE_START_DATE, startDate);
+ return lessons;
+ }
+
+ /**
+ * Get the lesson that applies to this activity. Not all activities have an attached lesson.
+ */
+ public Lesson getLessonForActivity(final long activityId) {
+ HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
+ return (Lesson) hibernateTemplate.execute(new HibernateCallback() {
+ public Object doInHibernate(Session session) throws HibernateException {
+ Query query = session.createQuery(LessonDAO.FIND_LESSON_FOR_ACTIVITY);
+ query.setLong("activityId", activityId);
+ return query.uniqueResult();
+ }
+ });
+ }
+
+ /**
+ * @see org.lamsfoundation.lams.lesson.dao.ILessonDAO#getLessonsByOrgAndUserWithCompletedFlag(Integer, Integer,
+ * boolean)
+ */
+ public List getLessonsByOrgAndUserWithCompletedFlag(final Integer userId, final Integer orgId, final boolean isStaff) {
+ List dtos = null;
+
+ HibernateTemplate hibernateTemplate = new HibernateTemplate(this.getSessionFactory());
+ dtos = (List) hibernateTemplate.execute(new HibernateCallback() {
+ public Object doInHibernate(Session session) throws HibernateException {
+ Query query = session.getNamedQuery(isStaff ? "staffLessonsByOrgAndUserWithCompletedFlag"
+ : "learnerLessonsByOrgAndUserWithCompletedFlag");
+ query.setInteger("userId", userId.intValue());
+ query.setInteger("orgId", orgId.intValue());
+ List result = query.list();
+ return result;
+ }
+ });
+ return dtos;
+ }
+
+ /**
+ * @see org.lamsfoundation.lams.lesson.dao.ILessonDAO#getLessonsByOriginalLearningDesign(Integer)
+ */
+ public List getLessonsByOriginalLearningDesign(final Long ldId, final Integer orgId) {
+ Object[] args = { ldId.longValue(), orgId.intValue() };
+ List lessons = this.getHibernateTemplate().find(LessonDAO.LESSONS_WITH_ORIGINAL_LEARNING_DESIGN, args);
+ return lessons;
+ }
+
+ /**
+ * @see org.lamsfoundation.lams.lesson.dao.ILessonDAO#getMonitorsByToolSessionId(Long)
+ */
+ public List getMonitorsByToolSessionId(Long sessionId) {
+ return this.getHibernateTemplate().findByNamedQueryAndNamedParam("monitorsByToolSessionId", "sessionId",
+ sessionId);
+ }
+
}
Index: lams_common/src/java/org/lamsfoundation/lams/lesson/service/ILessonService.java
===================================================================
diff -u -rc209be8131f22f6fe37bd8d6c14b56425a78b766 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_common/src/java/org/lamsfoundation/lams/lesson/service/ILessonService.java (.../ILessonService.java) (revision c209be8131f22f6fe37bd8d6c14b56425a78b766)
+++ lams_common/src/java/org/lamsfoundation/lams/lesson/service/ILessonService.java (.../ILessonService.java) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -44,257 +44,314 @@
*
* A lesson has two different "lists" of learners.
*
- * - The learners who are in the learner group attached to the lesson. This is fixed
- * when the lesson is started and is a list of all the learners who could ever participate in
- * to the lesson. This is available via lesson.getAllLearners()
- *
- The learners who have started the lesson. They may or may not be logged in currently,
- * or if they are logged in they may or may not be doing this lesson. This is available
- * via getActiveLessonLearners().
+ *
- The learners who are in the learner group attached to the lesson. This is fixed when the lesson is started and
+ * is a list of all the learners who could ever participate in to the lesson. This is available via
+ * lesson.getAllLearners()
+ *
- The learners who have started the lesson. They may or may not be logged in currently, or if they are logged in
+ * they may or may not be doing this lesson. This is available via getActiveLessonLearners().
*
*
- * There used to be a list of all the learners who were logged into a lesson. This has been
- * removed as we do not need the functionality at present. If this is required later it should
- * be combined with the user's shared session logic and will need to purge users who haven't
- * done anything for a while - otherwise a user whose PC has crashed and then never returns
- * to a lesson will staying in the cache forever.
+ * There used to be a list of all the learners who were logged into a lesson. This has been removed as we do not need
+ * the functionality at present. If this is required later it should be combined with the user's shared session logic
+ * and will need to purge users who haven't done anything for a while - otherwise a user whose PC has crashed and then
+ * never returns to a lesson will staying in the cache forever.
*/
public interface ILessonService {
- /** Get all the learners who have started the lesson. They may not be currently online.*/
- public abstract List getActiveLessonLearners(Long lessonId);
+ /** Get all the learners who have started the lesson. They may not be currently online. */
+ public abstract List getActiveLessonLearners(Long lessonId);
- /** Get all the learners who have started the lesson and are part of a given group. They may not be currently online.*/
- public abstract List getActiveLessonLearnersByGroup(Long lessonId, Long groupId);
+ /** Get all the learners who have started the lesson and are part of a given group. They may not be currently online. */
+ public abstract List getActiveLessonLearnersByGroup(Long lessonId, Long groupId);
- /**
- * Get the count of all the learners who have started the lesson. They may not be currently online.
- */
- public Integer getCountActiveLessonLearners(Long lessonId);
+ /**
+ * Get the count of all the learners who have started the lesson. They may not be currently online.
+ */
+ public Integer getCountActiveLessonLearners(Long lessonId);
- /** Get the lesson details for the LAMS client. Suitable for the monitoring client.
- * Contains a count of the total number of learners in the lesson and the number of active learners.
- * This is a pretty intensive call as it counts all the learners in the
- * lessons' learner group, and determines the number of active learners.
- * @param lessonId
- * @return lesson details
- */
- public abstract LessonDetailsDTO getLessonDetails(Long lessonId);
+ /**
+ * Get the lesson details for the LAMS client. Suitable for the monitoring client. Contains a count of the total
+ * number of learners in the lesson and the number of active learners. This is a pretty intensive call as it counts
+ * all the learners in the lessons' learner group, and determines the number of active learners.
+ *
+ * @param lessonId
+ * @return lesson details
+ */
+ public abstract LessonDetailsDTO getLessonDetails(Long lessonId);
- /** Get the lesson object.
- * @param lessonId
- * @return lesson details
- */
- public abstract Lesson getLesson(Long lessonId);
+ /**
+ * Get the lesson object.
+ *
+ * @param lessonId
+ * @return lesson details
+ */
+ public abstract Lesson getLesson(Long lessonId);
- /** Get the lesson details for the LAMS client. Suitable for the learner client.
- * Contains a reduced number of fields compared to getLessonDetails.
- * @param lessonId
- * @return lesson details
- */
- public abstract LessonDTO getLessonData(Long lessonId);
+ /**
+ * Get the lesson details for the LAMS client. Suitable for the learner client. Contains a reduced number of fields
+ * compared to getLessonDetails.
+ *
+ * @param lessonId
+ * @return lesson details
+ */
+ public abstract LessonDTO getLessonData(Long lessonId);
- /**
- * If the supplied learner is not already in a group, then perform grouping for
- * the learners who have started the lesson, based on the grouping activity.
- * Currently used for random grouping.
- * This method should be used when we do have an grouping activity and learner that is
- * already part of the Hibernate session. (e.g. from the ForceComplete)
- *
- * @param lessonId lesson id (mandatory)
- * @param groupingActivity the activity that has create grouping. (mandatory)
- * @param learner the learner to be check before grouping. (mandatory)
- */
- public void performGrouping(Long lessonId, GroupingActivity groupingActivity, User learner) throws LessonServiceException;
+ /**
+ * If the supplied learner is not already in a group, then perform grouping for the learners who have started the
+ * lesson, based on the grouping activity. Currently used for random grouping. This method should be used when we do
+ * have an grouping activity and learner that is already part of the Hibernate session. (e.g. from the
+ * ForceComplete)
+ *
+ * @param lessonId
+ * lesson id (mandatory)
+ * @param groupingActivity
+ * the activity that has create grouping. (mandatory)
+ * @param learner
+ * the learner to be check before grouping. (mandatory)
+ */
+ public void performGrouping(Long lessonId, GroupingActivity groupingActivity, User learner)
+ throws LessonServiceException;
- /**
- * Perform the grouping, setting the given list of learners as one group.
- * @param groupingActivity the activity that has create grouping. (mandatory)
- * @param groupName (optional)
- * @param learners to form one group (mandatory)
- */
- public void performGrouping(GroupingActivity groupingActivity, String groupName, List learners) throws LessonServiceException;
+ /**
+ * Perform the grouping, setting the given list of learners as one group.
+ *
+ * @param groupingActivity
+ * the activity that has create grouping. (mandatory)
+ * @param groupName
+ * (optional)
+ * @param learners
+ * to form one group (mandatory)
+ */
+ public void performGrouping(GroupingActivity groupingActivity, String groupName, List learners)
+ throws LessonServiceException;
- /**
- * Perform the grouping, setting the given list of learners as one group. Used in suitations
- * where there is a grouping but no grouping activity (e.g. in branching).
- * @param grouping the object on which to perform the grouing. (mandatory)
- * @param groupName (optional)
- * @param learners to form one group (mandatory)
- */
- public void performGrouping(Grouping grouping, String groupName, List learners) throws LessonServiceException;
+ /**
+ * Perform the grouping, setting the given list of learners as one group. Used in suitations where there is a
+ * grouping but no grouping activity (e.g. in branching).
+ *
+ * @param grouping
+ * the object on which to perform the grouing. (mandatory)
+ * @param groupName
+ * (optional)
+ * @param learners
+ * to form one group (mandatory)
+ */
+ public void performGrouping(Grouping grouping, String groupName, List learners) throws LessonServiceException;
- /**
- * Perform grouping for all the learners who have started the lesson, based on the grouping.
- * Currently used for chosen grouping and branching
- * @param lessonId lesson id (mandatory)
- * @param groupId group id (mandatory)
- * @param grouping the object on which to perform the grouing. (mandatory)
- */
- public void performGrouping(Grouping grouping, Long groupId, List learners) throws LessonServiceException;
+ /**
+ * Perform grouping for all the learners who have started the lesson, based on the grouping. Currently used for
+ * chosen grouping and branching
+ *
+ * @param lessonId
+ * lesson id (mandatory)
+ * @param groupId
+ * group id (mandatory)
+ * @param grouping
+ * the object on which to perform the grouing. (mandatory)
+ */
+ public void performGrouping(Grouping grouping, Long groupId, List learners) throws LessonServiceException;
- /**
- * Perform grouping for the given learner.
- *
- * @param grouping the object on which to perform the grouing. (mandatory)
- * @param groupId group id (mandatory)
- * @param learner learner to group (mandatory)
- * @throws LessonServiceException
- */
- public void performGrouping(Grouping grouping, Long groupId, User learner) throws LessonServiceException;
+ /**
+ * Perform grouping for the given learner.
+ *
+ * @param grouping
+ * the object on which to perform the grouing. (mandatory)
+ * @param groupId
+ * group id (mandatory)
+ * @param learner
+ * learner to group (mandatory)
+ * @throws LessonServiceException
+ */
+ public void performGrouping(Grouping grouping, Long groupId, User learner) throws LessonServiceException;
- /**
- * Remove learners from the given group.
- * @param grouping the grouping from which to remove the learners (mandatory)
- * @param groupName if not null only remove user from this group, if null remove learner from any group.
- * @param learners the learners to be removed (mandatory)
- */
- public void removeLearnersFromGroup(Grouping grouping, Long groupId, List learners) throws LessonServiceException;
+ /**
+ * Remove learners from the given group.
+ *
+ * @param grouping
+ * the grouping from which to remove the learners (mandatory)
+ * @param groupName
+ * if not null only remove user from this group, if null remove learner from any group.
+ * @param learners
+ * the learners to be removed (mandatory)
+ */
+ public void removeLearnersFromGroup(Grouping grouping, Long groupId, List learners)
+ throws LessonServiceException;
- /** Create an empty group for the given grouping. If the group name already exists
- * then it will force the name to be unique.
- *
- * @param grouping the grouping. (mandatory)
- * @param groupName (mandatory)
- * @return the new group
- */
- public Group createGroup(Grouping grouping, String name) throws LessonServiceException;
+ /**
+ * Create an empty group for the given grouping. If the group name already exists then it will force the name to be
+ * unique.
+ *
+ * @param grouping
+ * the grouping. (mandatory)
+ * @param groupName
+ * (mandatory)
+ * @return the new group
+ */
+ public Group createGroup(Grouping grouping, String name) throws LessonServiceException;
- /**
- * Remove a group for the given grouping. If the group is already used (e.g. a tool session exists)
- * then it throws a GroupingException.
- *
- * @param grouping the grouping that contains the group to remove. (mandatory)
- * @param groupName (mandatory)
- */
- public void removeGroup(Grouping grouping, Long groupId) throws LessonServiceException;
+ /**
+ * Remove a group for the given grouping. If the group is already used (e.g. a tool session exists) then it throws a
+ * GroupingException.
+ *
+ * @param grouping
+ * the grouping that contains the group to remove. (mandatory)
+ * @param groupName
+ * (mandatory)
+ */
+ public void removeGroup(Grouping grouping, Long groupId) throws LessonServiceException;
- /**
- * Add a learner to the lesson class. Checks for duplicates.
- * @paran userId new learner id
- * @return true if added user, returns false if the user already a learner and hence not added.
- */
- public boolean addLearner(Long lessonId, Integer userId) throws LessonServiceException;
+ /**
+ * Add a learner to the lesson class. Checks for duplicates.
+ *
+ * @paran userId new learner id
+ * @return true if added user, returns false if the user already a learner and hence not added.
+ */
+ public boolean addLearner(Long lessonId, Integer userId) throws LessonServiceException;
- /**
- * Add a set of learners to the lesson class.
- *
- * If version of the method is designed to be called from Moodle or some other external system,
- * and is less efficient in that it has to look up the user from the user id.
- * If we don't do this, then we may get a a session closed issue if this code is called from the
- * LoginRequestValve (as the users will be from a previous session)
- *
- * @param lessonId new learner id
- * @param userIds array of new learner ids
- */
- public void addLearners(Long lessonId, Integer[] userIds) throws LessonServiceException;
+ /**
+ * Add a set of learners to the lesson class.
+ *
+ * If version of the method is designed to be called from Moodle or some other external system, and is less
+ * efficient in that it has to look up the user from the user id. If we don't do this, then we may get a a session
+ * closed issue if this code is called from the LoginRequestValve (as the users will be from a previous session)
+ *
+ * @param lessonId
+ * new learner id
+ * @param userIds
+ * array of new learner ids
+ */
+ public void addLearners(Long lessonId, Integer[] userIds) throws LessonServiceException;
- /**
- * Add a set of learners to the lesson class. To be called within LAMS - see
- * addLearners(Long lessonId, Integer[] userIds) if calling from an external system.
- *
- * @param lesson lesson
- * @param users the users to add as learners
- */
- public void addLearners(Lesson lesson, Collection users) throws LessonServiceException;
+ /**
+ * Add a set of learners to the lesson class. To be called within LAMS - see addLearners(Long lessonId, Integer[]
+ * userIds) if calling from an external system.
+ *
+ * @param lesson
+ * lesson
+ * @param users
+ * the users to add as learners
+ */
+ public void addLearners(Lesson lesson, Collection users) throws LessonServiceException;
- /**
- * Add a new staff member to the lesson class. Checks for duplicates.
- * @paran userId new learner id
- * @return true if added user, returns false if the user already a staff member and hence not added.
- */
- public boolean addStaffMember(Long lessonId, Integer userId) throws LessonServiceException;
+ /**
+ * Add a new staff member to the lesson class. Checks for duplicates.
+ *
+ * @paran userId new learner id
+ * @return true if added user, returns false if the user already a staff member and hence not added.
+ */
+ public boolean addStaffMember(Long lessonId, Integer userId) throws LessonServiceException;
- /**
- * Add a set of staff to the lesson class.
- *
- * If version of the method is designed to be called from Moodle or some other external system,
- * and is less efficient in that it has to look up the user from the user id.
- * If we don't do this, then we may get a a session closed issue if this code is called from the
- * LoginRequestValve (as the users will be from a previous session)
- *
- * @param lessonId
- * @param userIds array of new staff ids
- */
- public void addStaffMembers(Long lessonId, Integer[] userIds) throws LessonServiceException;
+ /**
+ * Add a set of staff to the lesson class.
+ *
+ * If version of the method is designed to be called from Moodle or some other external system, and is less
+ * efficient in that it has to look up the user from the user id. If we don't do this, then we may get a a session
+ * closed issue if this code is called from the LoginRequestValve (as the users will be from a previous session)
+ *
+ * @param lessonId
+ * @param userIds
+ * array of new staff ids
+ */
+ public void addStaffMembers(Long lessonId, Integer[] userIds) throws LessonServiceException;
- /**
- * Add a set of staff members to the lesson class. To be called within LAMS - see
- * addLearners(Long lessonId, Integer[] userIds) if calling from an external system.
- *
- * @param lesson lesson
- * @param users the users to add as learners
- */
- public void addStaffMembers(Lesson lesson, Collection users) throws LessonServiceException;
+ /**
+ * Add a set of staff members to the lesson class. To be called within LAMS - see addLearners(Long lessonId,
+ * Integer[] userIds) if calling from an external system.
+ *
+ * @param lesson
+ * lesson
+ * @param users
+ * the users to add as learners
+ */
+ public void addStaffMembers(Lesson lesson, Collection users) throws LessonServiceException;
- /**
- * Remove references to an activity from all learner progress entries.
- * Used by Live Edit, to remove any references to the system gates
- * @param activity The activity for which learner progress references should be removed.
- */
- public void removeProgressReferencesToActivity(Activity activity) throws LessonServiceException;
+ /**
+ * Remove references to an activity from all learner progress entries. Used by Live Edit, to remove any references
+ * to the system gates
+ *
+ * @param activity
+ * The activity for which learner progress references should be removed.
+ */
+ public void removeProgressReferencesToActivity(Activity activity) throws LessonServiceException;
- /**
- * Mark any learner progresses for this lesson as not completed. Called when Live Edit
- * ends, to ensure that if there were any completed progress records, and the design
- * was extended, then they are no longer marked as completed.
- * @param lessonId The lesson for which learner progress entries should be updated.
- */
- public void performMarkLessonUncompleted(Long lessonId) throws LessonServiceException;
+ /**
+ * Mark any learner progresses for this lesson as not completed. Called when Live Edit ends, to ensure that if there
+ * were any completed progress records, and the design was extended, then they are no longer marked as completed.
+ *
+ * @param lessonId
+ * The lesson for which learner progress entries should be updated.
+ */
+ public void performMarkLessonUncompleted(Long lessonId) throws LessonServiceException;
- /**
- * Get the list of users who have attempted an activity. This is based on the progress engine records.
- * This will give the users in all tool sessions for an activity (if it is a tool activity) or
- * it will give all the users who have attempted an activity that doesn't have any tool sessions, i.e.
- * system activities such as branching.
- */
- public List getLearnersHaveAttemptedActivity(Activity activity) throws LessonServiceException;
+ /**
+ * Get the list of users who have attempted an activity. This is based on the progress engine records. This will
+ * give the users in all tool sessions for an activity (if it is a tool activity) or it will give all the users who
+ * have attempted an activity that doesn't have any tool sessions, i.e. system activities such as branching.
+ */
+ public List getLearnersHaveAttemptedActivity(Activity activity) throws LessonServiceException;
- /**
- * Get the list of users who have completed an activity. This is based on the progress engine records.
- * This will give the users in all tool sessions for an activity (if it is a tool activity) or
- * it will give all the users who have attempted an activity that doesn't have any tool sessions, i.e.
- * system activities such as branching.
- */
- public List getLearnersHaveCompletedActivity(Activity activity) throws LessonServiceException;
+ /**
+ * Get the list of users who have completed an activity. This is based on the progress engine records. This will
+ * give the users in all tool sessions for an activity (if it is a tool activity) or it will give all the users who
+ * have attempted an activity that doesn't have any tool sessions, i.e. system activities such as branching.
+ */
+ public List getLearnersHaveCompletedActivity(Activity activity) throws LessonServiceException;
- /**
- * Gets the count of the users who have attempted an activity. This is based on the progress engine records.
- * This will work on all activities, including ones that don't have any tool sessions, i.e.
- * system activities such as branching.
- */
- public Integer getCountLearnersHaveAttemptedActivity(Activity activity) throws LessonServiceException;
+ /**
+ * Gets the count of the users who have attempted an activity. This is based on the progress engine records. This
+ * will work on all activities, including ones that don't have any tool sessions, i.e. system activities such as
+ * branching.
+ */
+ public Integer getCountLearnersHaveAttemptedActivity(Activity activity) throws LessonServiceException;
- /**
- * Gets the count of the users who have completed an activity. This is based on the progress engine records.
- * This will work on all activities, including ones that don't have any tool sessions, i.e.
- * system activities such as branching.
- */
- public Integer getCountLearnersHaveCompletedActivity(Activity activity) throws LessonServiceException;
+ /**
+ * Gets the count of the users who have completed an activity. This is based on the progress engine records. This
+ * will work on all activities, including ones that don't have any tool sessions, i.e. system activities such as
+ * branching.
+ */
+ public Integer getCountLearnersHaveCompletedActivity(Activity activity) throws LessonServiceException;
- /**
- * Returns map of lessons in an organisation for a particular learner or staff user.
- * @param userId user's id
- * @param orgId org's id
- * @param isStaff return lessons where user is staff, or where user is learner
- * @return map of lesson beans used in the index page
- */
- public Map getLessonsByOrgAndUserWithCompletedFlag(Integer userId, Integer orgId, boolean isStaff);
+ /**
+ * Returns map of lessons in an organisation for a particular learner or staff user.
+ *
+ * @param userId
+ * user's id
+ * @param orgId
+ * org's id
+ * @param isStaff
+ * return lessons where user is staff, or where user is learner
+ * @return map of lesson beans used in the index page
+ */
+ public Map getLessonsByOrgAndUserWithCompletedFlag(Integer userId, Integer orgId,
+ boolean isStaff);
- /**
- * Gets the learner's progress details for a particular lesson. Will return null if the user
- * has not started the lesson.
- *
- * @param learnerId user's id
- * @param lessonId lesson's id
- * @return learner's progress or null
- */
- public LearnerProgress getUserProgressForLesson(Integer learnerId, Long lessonId);
+ /**
+ * Gets the learner's progress details for a particular lesson. Will return null if the user has not started the
+ * lesson.
+ *
+ * @param learnerId
+ * user's id
+ * @param lessonId
+ * lesson's id
+ * @return learner's progress or null
+ */
+ public LearnerProgress getUserProgressForLesson(Integer learnerId, Long lessonId);
- /**
- * Gets list of lessons which are originally based on the given learning design id.
- * @param ldId
- * @param orgId
- * @return list of lessons
- */
- public List getLessonsByOriginalLearningDesign(Long ldId, Integer orgId);
+ /**
+ * Gets list of lessons which are originally based on the given learning design id.
+ *
+ * @param ldId
+ * @param orgId
+ * @return list of lessons
+ */
+ public List getLessonsByOriginalLearningDesign(Long ldId, Integer orgId);
+
+ /**
+ * Finds out which lesson the given tool content belongs to and returns its monitoring users.
+ *
+ * @param sessionId
+ * tool session ID
+ * @return list of teachers that monitor the lesson which contains the tool with given session ID
+ */
+ public List getMonitorsByToolSessionId(Long sessionId);
}
\ No newline at end of file
Index: lams_common/src/java/org/lamsfoundation/lams/lesson/service/LessonService.java
===================================================================
diff -u -rc209be8131f22f6fe37bd8d6c14b56425a78b766 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_common/src/java/org/lamsfoundation/lams/lesson/service/LessonService.java (.../LessonService.java) (revision c209be8131f22f6fe37bd8d6c14b56425a78b766)
+++ lams_common/src/java/org/lamsfoundation/lams/lesson/service/LessonService.java (.../LessonService.java) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -59,664 +59,715 @@
*
* A lesson has three different "lists" of learners.
*
- * - The learners who are in the learner group attached to the lesson. This is fixed
- * when the lesson is started and is a list of all the learners who could ever participate in
- * to the lesson. This is available via lesson.getAllLearners()
- *
- The learners who have started the lesson. They may or may not be logged in currently,
- * or if they are logged in they may or may not be doing this lesson. This is available
- * via getActiveLessonLearners().
+ *
- The learners who are in the learner group attached to the lesson. This is fixed when the lesson is started and
+ * is a list of all the learners who could ever participate in to the lesson. This is available via
+ * lesson.getAllLearners()
+ *
- The learners who have started the lesson. They may or may not be logged in currently, or if they are logged in
+ * they may or may not be doing this lesson. This is available via getActiveLessonLearners().
*
*
- * There used to be a list of all the learners who were logged into a lesson. This has been
- * removed as we do not need the functionality at present. If this is required later it should
- * be combined with the user's shared session logic and will need to purge users who haven't
- * done anything for a while - otherwise a user whose PC has crashed and then never returns
- * to a lesson will staying in the cache forever.
- *
+ * There used to be a list of all the learners who were logged into a lesson. This has been removed as we do not need
+ * the functionality at present. If this is required later it should be combined with the user's shared session logic
+ * and will need to purge users who haven't done anything for a while - otherwise a user whose PC has crashed and then
+ * never returns to a lesson will staying in the cache forever.
+ *
*/
public class LessonService implements ILessonService {
- private static Logger log = Logger.getLogger(LessonService.class);
+ private static Logger log = Logger.getLogger(LessonService.class);
- private ILessonDAO lessonDAO;
- private ILessonClassDAO lessonClassDAO;
- private IGroupingDAO groupingDAO;
- private MessageService messageService;
- private IBaseDAO baseDAO;
- private ILearnerProgressDAO learnerProgressDAO;
+ private ILessonDAO lessonDAO;
+ private ILessonClassDAO lessonClassDAO;
+ private IGroupingDAO groupingDAO;
+ private MessageService messageService;
+ private IBaseDAO baseDAO;
+ private ILearnerProgressDAO learnerProgressDAO;
- /* ******* Spring injection methods ***************************************/
- public void setLessonDAO(ILessonDAO lessonDAO) {
- this.lessonDAO = lessonDAO;
- }
+ /* ******* Spring injection methods ************************************** */
+ public void setLessonDAO(ILessonDAO lessonDAO) {
+ this.lessonDAO = lessonDAO;
+ }
- public void setLessonClassDAO(ILessonClassDAO lessonClassDAO) {
- this.lessonClassDAO = lessonClassDAO;
- }
+ public void setLessonClassDAO(ILessonClassDAO lessonClassDAO) {
+ this.lessonClassDAO = lessonClassDAO;
+ }
- public void setGroupingDAO(IGroupingDAO groupingDAO) {
- this.groupingDAO = groupingDAO;
- }
+ public void setGroupingDAO(IGroupingDAO groupingDAO) {
+ this.groupingDAO = groupingDAO;
+ }
- public void setLearnerProgressDAO(ILearnerProgressDAO learnerProgressDAO) {
- this.learnerProgressDAO = learnerProgressDAO;
- }
+ public void setLearnerProgressDAO(ILearnerProgressDAO learnerProgressDAO) {
+ this.learnerProgressDAO = learnerProgressDAO;
+ }
- public void setMessageService(MessageService messageService) {
- this.messageService = messageService;
- }
+ public void setMessageService(MessageService messageService) {
+ this.messageService = messageService;
+ }
- public void setBaseDAO(IBaseDAO baseDAO) {
- this.baseDAO = baseDAO;
- }
+ public void setBaseDAO(IBaseDAO baseDAO) {
+ this.baseDAO = baseDAO;
+ }
- /* *********** Service methods ***********************************************/
- /* (non-Javadoc)
- * @see org.lamsfoundation.lams.lesson.service.ILessonService#getActiveLessonLearners(java.lang.Long)
- */
- public List getActiveLessonLearners(Long lessonId) {
- return lessonDAO.getActiveLearnerByLesson(lessonId);
- }
+ /* *********** Service methods ********************************************** */
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.lesson.service.ILessonService#getActiveLessonLearners(java.lang.Long)
+ */
+ public List getActiveLessonLearners(Long lessonId) {
+ return lessonDAO.getActiveLearnerByLesson(lessonId);
+ }
- /* (non-Javadoc)
- * @see org.lamsfoundation.lams.lesson.service.ILessonService#getActiveLessonLearnersByGroup(java.lang.Long, java.lang.Long)
- */
- public List getActiveLessonLearnersByGroup(Long lessonId, Long groupId) {
- return lessonDAO.getActiveLearnerByLessonAndGroup(lessonId, groupId);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.lesson.service.ILessonService#getActiveLessonLearnersByGroup(java.lang.Long,
+ * java.lang.Long)
+ */
+ public List getActiveLessonLearnersByGroup(Long lessonId, Long groupId) {
+ return lessonDAO.getActiveLearnerByLessonAndGroup(lessonId, groupId);
+ }
- /* (non-Javadoc)
- * @see org.lamsfoundation.lams.lesson.service.ILessonService#getCountActiveLessonLearners(java.lang.Long)
- */
- public Integer getCountActiveLessonLearners(Long lessonId) {
- return lessonDAO.getCountActiveLearnerByLesson(lessonId);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.lesson.service.ILessonService#getCountActiveLessonLearners(java.lang.Long)
+ */
+ public Integer getCountActiveLessonLearners(Long lessonId) {
+ return lessonDAO.getCountActiveLearnerByLesson(lessonId);
+ }
- /* (non-Javadoc)
- * @see org.lamsfoundation.lams.lesson.service.ILessonService#getLessonDetails(java.lang.Long)
- */
- public LessonDetailsDTO getLessonDetails(Long lessonId) {
- Lesson lesson = lessonDAO.getLesson(lessonId);
- LessonDetailsDTO dto = null;
- if (lesson != null) {
- dto = lesson.getLessonDetails();
- Integer active = getCountActiveLessonLearners(lessonId);
- dto.setNumberStartedLearners(active != null ? active : new Integer(0));
- }
- return dto;
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.lesson.service.ILessonService#getLessonDetails(java.lang.Long)
+ */
+ public LessonDetailsDTO getLessonDetails(Long lessonId) {
+ Lesson lesson = lessonDAO.getLesson(lessonId);
+ LessonDetailsDTO dto = null;
+ if (lesson != null) {
+ dto = lesson.getLessonDetails();
+ Integer active = getCountActiveLessonLearners(lessonId);
+ dto.setNumberStartedLearners(active != null ? active : new Integer(0));
}
+ return dto;
+ }
- /* (non-Javadoc)
- * @see org.lamsfoundation.lams.lesson.service.ILessonService#getLessonData(java.lang.Long)
- */
- public LessonDTO getLessonData(Long lessonId) {
- Lesson lesson = lessonDAO.getLesson(lessonId);
- LessonDTO dto = null;
- if (lesson != null) {
- dto = lesson.getLessonData();
- }
- return dto;
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.lesson.service.ILessonService#getLessonData(java.lang.Long)
+ */
+ public LessonDTO getLessonData(Long lessonId) {
+ Lesson lesson = lessonDAO.getLesson(lessonId);
+ LessonDTO dto = null;
+ if (lesson != null) {
+ dto = lesson.getLessonData();
}
+ return dto;
+ }
- /** Get the lesson object.
- * @param lessonId
- * @return lesson details
- */
- public Lesson getLesson(Long lessonId) {
- return lessonDAO.getLesson(lessonId);
- }
+ /**
+ * Get the lesson object.
+ *
+ * @param lessonId
+ * @return lesson details
+ */
+ public Lesson getLesson(Long lessonId) {
+ return lessonDAO.getLesson(lessonId);
+ }
- /**
- * If the supplied learner is not already in a group, then perform grouping for
- * the learners who have started the lesson, based on the grouping activity.
- * The grouper decides who goes in which group.
- *
- * Can only be run on a Random Grouping
- *
- * @param lessonId lesson id (mandatory)
- * @param groupingActivity the activity that has create grouping. (mandatory)
- * @param learner the learner to be check before grouping. (mandatory)
- */
- public void performGrouping(Long lessonId, GroupingActivity groupingActivity, User learner) throws LessonServiceException {
- Grouping grouping = groupingActivity.getCreateGrouping();
- if (grouping != null && grouping.isRandomGrouping()) {
- // get the real objects, not the CGLIB version
- grouping = groupingDAO.getGroupingById(grouping.getGroupingId());
- Grouper grouper = grouping.getGrouper();
+ /**
+ * If the supplied learner is not already in a group, then perform grouping for the learners who have started the
+ * lesson, based on the grouping activity. The grouper decides who goes in which group.
+ *
+ * Can only be run on a Random Grouping
+ *
+ * @param lessonId
+ * lesson id (mandatory)
+ * @param groupingActivity
+ * the activity that has create grouping. (mandatory)
+ * @param learner
+ * the learner to be check before grouping. (mandatory)
+ */
+ public void performGrouping(Long lessonId, GroupingActivity groupingActivity, User learner)
+ throws LessonServiceException {
+ Grouping grouping = groupingActivity.getCreateGrouping();
+ if (grouping != null && grouping.isRandomGrouping()) {
+ // get the real objects, not the CGLIB version
+ grouping = groupingDAO.getGroupingById(grouping.getGroupingId());
+ Grouper grouper = grouping.getGrouper();
- if (grouper != null) {
- grouper.setCommonMessageService(messageService);
- try {
- if (grouping.getGroups().size() == 0) {
- // no grouping done yet - do everyone already in the lesson.
- List usersInLesson = getActiveLessonLearners(lessonId);
- grouper.doGrouping(grouping, (String) null, usersInLesson);
- }
- else if (!grouping.doesLearnerExist(learner)) {
- // done the others, just do the one user
- grouper.doGrouping(grouping, null, learner);
- }
- }
- catch (GroupingException e) {
- throw new LessonServiceException(e);
- }
- groupingDAO.update(grouping);
- }
-
+ if (grouper != null) {
+ grouper.setCommonMessageService(messageService);
+ try {
+ if (grouping.getGroups().size() == 0) {
+ // no grouping done yet - do everyone already in the lesson.
+ List usersInLesson = getActiveLessonLearners(lessonId);
+ grouper.doGrouping(grouping, (String) null, usersInLesson);
+ } else if (!grouping.doesLearnerExist(learner)) {
+ // done the others, just do the one user
+ grouper.doGrouping(grouping, null, learner);
+ }
+ } catch (GroupingException e) {
+ throw new LessonServiceException(e);
}
- else {
- String error = "The method performGrouping supports only grouping methods where the grouper decides the groups (currently only RandomGrouping). Called with a groupingActivity with the wrong grouper "
- + groupingActivity.getActivityId();
- LessonService.log.error(error);
- throw new LessonServiceException(error);
- }
+ groupingDAO.update(grouping);
+ }
+
+ } else {
+ String error = "The method performGrouping supports only grouping methods where the grouper decides the groups (currently only RandomGrouping). Called with a groupingActivity with the wrong grouper "
+ + groupingActivity.getActivityId();
+ LessonService.log.error(error);
+ throw new LessonServiceException(error);
}
+ }
- /**
- * Perform the grouping, setting the given list of learners as one group.
- * @param groupingActivity the activity that has create grouping. (mandatory)
- * @param groupName (optional)
- * @param learners to form one group (mandatory)
- */
- public void performGrouping(GroupingActivity groupingActivity, String groupName, List learners) throws LessonServiceException {
+ /**
+ * Perform the grouping, setting the given list of learners as one group.
+ *
+ * @param groupingActivity
+ * the activity that has create grouping. (mandatory)
+ * @param groupName
+ * (optional)
+ * @param learners
+ * to form one group (mandatory)
+ */
+ public void performGrouping(GroupingActivity groupingActivity, String groupName, List learners)
+ throws LessonServiceException {
- Grouping grouping = groupingActivity.getCreateGrouping();
- performGrouping(grouping, groupName, learners);
- }
+ Grouping grouping = groupingActivity.getCreateGrouping();
+ performGrouping(grouping, groupName, learners);
+ }
- /**
- * Perform the grouping, setting the given list of learners as one group. Used in situations
- * where there is a grouping but no grouping activity (e.g. in branching).
- * @param groupingActivity the activity that has create grouping. (mandatory)
- * @param groupName (optional)
- * @param learners to form one group (mandatory)
- */
- public void performGrouping(Grouping grouping, String groupName, List learners) throws LessonServiceException {
+ /**
+ * Perform the grouping, setting the given list of learners as one group. Used in situations where there is a
+ * grouping but no grouping activity (e.g. in branching).
+ *
+ * @param groupingActivity
+ * the activity that has create grouping. (mandatory)
+ * @param groupName
+ * (optional)
+ * @param learners
+ * to form one group (mandatory)
+ */
+ public void performGrouping(Grouping grouping, String groupName, List learners) throws LessonServiceException {
- if (grouping != null) {
- // Ensure we have a real grouping object, not just a CGLIB version (LDEV-1817)
- grouping = groupingDAO.getGroupingById(grouping.getGroupingId());
- Grouper grouper = grouping.getGrouper();
- if (grouper != null) {
- grouper.setCommonMessageService(messageService);
- try {
- grouper.doGrouping(grouping, groupName, learners);
- }
- catch (GroupingException e) {
- throw new LessonServiceException(e);
- }
- groupingDAO.update(grouping);
- }
+ if (grouping != null) {
+ // Ensure we have a real grouping object, not just a CGLIB version (LDEV-1817)
+ grouping = groupingDAO.getGroupingById(grouping.getGroupingId());
+ Grouper grouper = grouping.getGrouper();
+ if (grouper != null) {
+ grouper.setCommonMessageService(messageService);
+ try {
+ grouper.doGrouping(grouping, groupName, learners);
+ } catch (GroupingException e) {
+ throw new LessonServiceException(e);
}
+ groupingDAO.update(grouping);
+ }
}
+ }
- /**
- * Perform grouping for the given learner.
- *
- * @param grouping the object on which to perform the grouing. (mandatory)
- * @param groupId group id (mandatory)
- * @param learner learner to group (mandatory)
- * @throws LessonServiceException
- */
- public void performGrouping(Grouping grouping, Long groupId, User learner) throws LessonServiceException {
- if (grouping != null) {
- // Ensure we have a real grouping object, not just a CGLIB version (LDEV-1817)
- grouping = groupingDAO.getGroupingById(grouping.getGroupingId());
- Grouper grouper = grouping.getGrouper();
- if (grouper != null) {
- grouper.setCommonMessageService(messageService);
- try {
- List learners = new ArrayList(1);
- learners.add(learner);
- grouper.doGrouping(grouping, groupId, learners);
- }
- catch (GroupingException e) {
- throw new LessonServiceException(e);
- }
- groupingDAO.update(grouping);
- }
+ /**
+ * Perform grouping for the given learner.
+ *
+ * @param grouping
+ * the object on which to perform the grouing. (mandatory)
+ * @param groupId
+ * group id (mandatory)
+ * @param learner
+ * learner to group (mandatory)
+ * @throws LessonServiceException
+ */
+ public void performGrouping(Grouping grouping, Long groupId, User learner) throws LessonServiceException {
+ if (grouping != null) {
+ // Ensure we have a real grouping object, not just a CGLIB version (LDEV-1817)
+ grouping = groupingDAO.getGroupingById(grouping.getGroupingId());
+ Grouper grouper = grouping.getGrouper();
+ if (grouper != null) {
+ grouper.setCommonMessageService(messageService);
+ try {
+ List learners = new ArrayList(1);
+ learners.add(learner);
+ grouper.doGrouping(grouping, groupId, learners);
+ } catch (GroupingException e) {
+ throw new LessonServiceException(e);
}
+ groupingDAO.update(grouping);
+ }
}
+ }
- /**
- * Perform the grouping, setting the given list of learners as one group. Currently used for chosen grouping and
- * teacher chosen branching, and for group based branching in preview (when the user selects a branch that would
- * not be their normal branch).
- * @param grouping The grouping that needs to have the grouping performed.. (mandatory)
- * @param the id of the preferred group (optional)
- * @param learners to form one group (mandatory)
- */
- public void performGrouping(Grouping grouping, Long groupId, List learners) throws LessonServiceException {
- if (grouping != null) {
- Grouper grouper = grouping.getGrouper();
- if (grouper != null) {
- grouper.setCommonMessageService(messageService);
- try {
- grouper.doGrouping(grouping, groupId, learners);
- }
- catch (GroupingException e) {
- throw new LessonServiceException(e);
- }
- groupingDAO.update(grouping);
- }
+ /**
+ * Perform the grouping, setting the given list of learners as one group. Currently used for chosen grouping and
+ * teacher chosen branching, and for group based branching in preview (when the user selects a branch that would not
+ * be their normal branch).
+ *
+ * @param grouping
+ * The grouping that needs to have the grouping performed.. (mandatory)
+ * @param the
+ * id of the preferred group (optional)
+ * @param learners
+ * to form one group (mandatory)
+ */
+ public void performGrouping(Grouping grouping, Long groupId, List learners) throws LessonServiceException {
+ if (grouping != null) {
+ Grouper grouper = grouping.getGrouper();
+ if (grouper != null) {
+ grouper.setCommonMessageService(messageService);
+ try {
+ grouper.doGrouping(grouping, groupId, learners);
+ } catch (GroupingException e) {
+ throw new LessonServiceException(e);
}
- else {
- String error = "The method performChosenGrouping supports only grouping methods where the supplied list should be used as a single group (currently only ChosenGrouping). Called with a grouping with the wrong grouper "
- + grouping;
- LessonService.log.error(error);
- throw new LessonServiceException(error);
- }
+ groupingDAO.update(grouping);
+ }
+ } else {
+ String error = "The method performChosenGrouping supports only grouping methods where the supplied list should be used as a single group (currently only ChosenGrouping). Called with a grouping with the wrong grouper "
+ + grouping;
+ LessonService.log.error(error);
+ throw new LessonServiceException(error);
}
+ }
- /**
- * Remove learners from the given group.
- * @param grouping the grouping that contains the users to be removed (mandatory)
- * @param groupID if not null only remove user from this group, if null remove learner from any group.
- * @param learners the learners to be removed (mandatory)
- */
- public void removeLearnersFromGroup(Grouping grouping, Long groupID, List learners) throws LessonServiceException {
- if (grouping != null) {
- // get the real objects, not the CGLIB version
- grouping = groupingDAO.getGroupingById(grouping.getGroupingId());
- Grouper grouper = grouping.getGrouper();
- if (grouper != null) {
- try {
- grouper.removeLearnersFromGroup(grouping, groupID, learners);
- }
- catch (GroupingException e) {
- throw new LessonServiceException(e);
- }
- }
- groupingDAO.update(grouping);
+ /**
+ * Remove learners from the given group.
+ *
+ * @param grouping
+ * the grouping that contains the users to be removed (mandatory)
+ * @param groupID
+ * if not null only remove user from this group, if null remove learner from any group.
+ * @param learners
+ * the learners to be removed (mandatory)
+ */
+ public void removeLearnersFromGroup(Grouping grouping, Long groupID, List learners)
+ throws LessonServiceException {
+ if (grouping != null) {
+ // get the real objects, not the CGLIB version
+ grouping = groupingDAO.getGroupingById(grouping.getGroupingId());
+ Grouper grouper = grouping.getGrouper();
+ if (grouper != null) {
+ try {
+ grouper.removeLearnersFromGroup(grouping, groupID, learners);
+ } catch (GroupingException e) {
+ throw new LessonServiceException(e);
}
+ }
+ groupingDAO.update(grouping);
}
+ }
- /** Create an empty group for the given grouping. Create an empty group for the given grouping.
- * If the group name already exists then it will force the name to be unique.
- *
- * @param grouping the grouping. (mandatory)
- * @param groupName (mandatory)
- * @return the new group
- */
- public Group createGroup(Grouping grouping, String name) throws LessonServiceException {
- Group newGroup = null;
- if (grouping != null) {
- // get the real objects, not the CGLIB version
- grouping = groupingDAO.getGroupingById(grouping.getGroupingId());
- Grouper grouper = grouping.getGrouper();
- if (grouper != null) {
- try {
- newGroup = grouper.createGroup(grouping, name);
- }
- catch (GroupingException e) {
- throw new LessonServiceException(e);
- }
- }
- groupingDAO.update(grouping);
+ /**
+ * Create an empty group for the given grouping. Create an empty group for the given grouping. If the group name
+ * already exists then it will force the name to be unique.
+ *
+ * @param grouping
+ * the grouping. (mandatory)
+ * @param groupName
+ * (mandatory)
+ * @return the new group
+ */
+ public Group createGroup(Grouping grouping, String name) throws LessonServiceException {
+ Group newGroup = null;
+ if (grouping != null) {
+ // get the real objects, not the CGLIB version
+ grouping = groupingDAO.getGroupingById(grouping.getGroupingId());
+ Grouper grouper = grouping.getGrouper();
+ if (grouper != null) {
+ try {
+ newGroup = grouper.createGroup(grouping, name);
+ } catch (GroupingException e) {
+ throw new LessonServiceException(e);
}
- return newGroup;
+ }
+ groupingDAO.update(grouping);
}
+ return newGroup;
+ }
- /**
- * Remove a group for the given grouping. If the group is already used (e.g. a tool session exists)
- * then it throws a GroupingException.
- *
- * @param grouping the grouping that contains the group to be removed (mandatory)
- * @param groupID (mandatory)
- */
- public void removeGroup(Grouping grouping, Long groupID) throws LessonServiceException {
- if (grouping != null) {
- // get the real objects, not the CGLIB version
- grouping = groupingDAO.getGroupingById(grouping.getGroupingId());
- Grouper grouper = grouping.getGrouper();
- if (grouper != null) {
- try {
- grouper.removeGroup(grouping, groupID);
- }
- catch (GroupingException e) {
- throw new LessonServiceException(e);
- }
- }
- groupingDAO.update(grouping);
+ /**
+ * Remove a group for the given grouping. If the group is already used (e.g. a tool session exists) then it throws a
+ * GroupingException.
+ *
+ * @param grouping
+ * the grouping that contains the group to be removed (mandatory)
+ * @param groupID
+ * (mandatory)
+ */
+ public void removeGroup(Grouping grouping, Long groupID) throws LessonServiceException {
+ if (grouping != null) {
+ // get the real objects, not the CGLIB version
+ grouping = groupingDAO.getGroupingById(grouping.getGroupingId());
+ Grouper grouper = grouping.getGrouper();
+ if (grouper != null) {
+ try {
+ grouper.removeGroup(grouping, groupID);
+ } catch (GroupingException e) {
+ throw new LessonServiceException(e);
}
+ }
+ groupingDAO.update(grouping);
}
+ }
- /**
- * Add a learner to the lesson class. Checks for duplicates.
- * @param userId new learner id
- * @return true if added user, returns false if the user already a learner and hence not added.
- */
- public boolean addLearner(Long lessonId, Integer userId) throws LessonServiceException {
- Lesson lesson = lessonDAO.getLesson(lessonId);
- if (lesson == null) {
- throw new LessonServiceException("Lesson " + lessonId + " does not exist. Unable to add learner to lesson.");
- }
+ /**
+ * Add a learner to the lesson class. Checks for duplicates.
+ *
+ * @param userId
+ * new learner id
+ * @return true if added user, returns false if the user already a learner and hence not added.
+ */
+ public boolean addLearner(Long lessonId, Integer userId) throws LessonServiceException {
+ Lesson lesson = lessonDAO.getLesson(lessonId);
+ if (lesson == null) {
+ throw new LessonServiceException("Lesson " + lessonId + " does not exist. Unable to add learner to lesson.");
+ }
- LessonClass lessonClass = lesson.getLessonClass();
- if (lessonClass == null) {
- throw new LessonServiceException("Lesson class for " + lessonId + " does not exist. Unable to add learner to lesson.");
- }
+ LessonClass lessonClass = lesson.getLessonClass();
+ if (lessonClass == null) {
+ throw new LessonServiceException("Lesson class for " + lessonId
+ + " does not exist. Unable to add learner to lesson.");
+ }
- // initialise the lesson group, or we get a lazy loading error when logging in
- // from moodle. Should only be two groups - learner and staff
- // yes this is a bit of a hack!
- Group learnersGroup = lessonClass.getLearnersGroup();
- if (learnersGroup != null) {
- lessonDAO.initialize(learnersGroup);
- }
+ // initialise the lesson group, or we get a lazy loading error when logging in
+ // from moodle. Should only be two groups - learner and staff
+ // yes this is a bit of a hack!
+ Group learnersGroup = lessonClass.getLearnersGroup();
+ if (learnersGroup != null) {
+ lessonDAO.initialize(learnersGroup);
+ }
- User user = (User) baseDAO.find(User.class, userId);
- boolean ret = lessonClass.addLearner(user);
- if (ret) {
- lessonClassDAO.updateLessonClass(lessonClass);
- }
- return ret;
+ User user = (User) baseDAO.find(User.class, userId);
+ boolean ret = lessonClass.addLearner(user);
+ if (ret) {
+ lessonClassDAO.updateLessonClass(lessonClass);
}
+ return ret;
+ }
- /**
- * Add a set of learners to the lesson class.
- *
- * If version of the method is designed to be called from Moodle or some other external system,
- * and is less efficient in that it has to look up the user from the user id.
- * If we don't do this, then we may get a a session closed issue if this code is called from the
- * LoginRequestValve (as the users will be from a previous session)
- *
- * @param lessonId
- * @param userIds array of new learner ids
- */
- public void addLearners(Long lessonId, Integer[] userIds) throws LessonServiceException {
+ /**
+ * Add a set of learners to the lesson class.
+ *
+ * If version of the method is designed to be called from Moodle or some other external system, and is less
+ * efficient in that it has to look up the user from the user id. If we don't do this, then we may get a a session
+ * closed issue if this code is called from the LoginRequestValve (as the users will be from a previous session)
+ *
+ * @param lessonId
+ * @param userIds
+ * array of new learner ids
+ */
+ public void addLearners(Long lessonId, Integer[] userIds) throws LessonServiceException {
- Lesson lesson = lessonDAO.getLesson(lessonId);
- if (lesson == null) {
- throw new LessonServiceException("Lesson " + lessonId + " does not exist. Unable to add learner to lesson.");
- }
- LessonClass lessonClass = lesson.getLessonClass();
- if (lessonClass == null) {
- throw new LessonServiceException("Lesson class for " + lessonId + " does not exist. Unable to add learner to lesson.");
- }
+ Lesson lesson = lessonDAO.getLesson(lessonId);
+ if (lesson == null) {
+ throw new LessonServiceException("Lesson " + lessonId + " does not exist. Unable to add learner to lesson.");
+ }
+ LessonClass lessonClass = lesson.getLessonClass();
+ if (lessonClass == null) {
+ throw new LessonServiceException("Lesson class for " + lessonId
+ + " does not exist. Unable to add learner to lesson.");
+ }
- // initialise the lesson group, or we might get a lazy loading error in the future
- // when logging in from an external system. Should only be two groups - learner and staff
- // yes this is a bit of a hack!
- Group learnersGroup = lessonClass.getLearnersGroup();
- if (learnersGroup != null) {
- lessonDAO.initialize(learnersGroup);
- }
+ // initialise the lesson group, or we might get a lazy loading error in the future
+ // when logging in from an external system. Should only be two groups - learner and staff
+ // yes this is a bit of a hack!
+ Group learnersGroup = lessonClass.getLearnersGroup();
+ if (learnersGroup != null) {
+ lessonDAO.initialize(learnersGroup);
+ }
- Set users = new HashSet();
- for (Integer userId : userIds) {
- User user = (User) baseDAO.find(User.class, userId);
- users.add(user);
- }
- addLearners(lesson, users);
+ Set users = new HashSet();
+ for (Integer userId : userIds) {
+ User user = (User) baseDAO.find(User.class, userId);
+ users.add(user);
}
+ addLearners(lesson, users);
+ }
- /**
- * Add a set of learners to the lesson class. To be called within LAMS - see
- * addLearners(Long lessonId, Integer[] userIds) if calling from an external system.
- *
- * @param lesson lesson
- * @param users the users to add as learners
- */
- public void addLearners(Lesson lesson, Collection users) throws LessonServiceException {
+ /**
+ * Add a set of learners to the lesson class. To be called within LAMS - see addLearners(Long lessonId, Integer[]
+ * userIds) if calling from an external system.
+ *
+ * @param lesson
+ * lesson
+ * @param users
+ * the users to add as learners
+ */
+ public void addLearners(Lesson lesson, Collection users) throws LessonServiceException {
- LessonClass lessonClass = lesson.getLessonClass();
- int numAdded = lessonClass.addLearners(users);
- if (numAdded > 0) {
- lessonClassDAO.updateLessonClass(lessonClass);
- }
- if (LessonService.log.isDebugEnabled()) {
- LessonService.log.debug("Added " + numAdded + " learners to lessonClass " + lessonClass.getGroupingId());
- }
+ LessonClass lessonClass = lesson.getLessonClass();
+ int numAdded = lessonClass.addLearners(users);
+ if (numAdded > 0) {
+ lessonClassDAO.updateLessonClass(lessonClass);
}
+ if (LessonService.log.isDebugEnabled()) {
+ LessonService.log.debug("Added " + numAdded + " learners to lessonClass " + lessonClass.getGroupingId());
+ }
+ }
- /**
- * Add a new staff member to the lesson class. Checks for duplicates.
- * @param userId new learner id
- * @return true if added user, returns false if the user already a staff member and hence not added.
- */
- public boolean addStaffMember(Long lessonId, Integer userId) {
- Lesson lesson = lessonDAO.getLesson(lessonId);
- if (lesson == null) {
- throw new LessonServiceException("Lesson " + lessonId + " does not exist. Unable to add staff member to lesson.");
- }
+ /**
+ * Add a new staff member to the lesson class. Checks for duplicates.
+ *
+ * @param userId
+ * new learner id
+ * @return true if added user, returns false if the user already a staff member and hence not added.
+ */
+ public boolean addStaffMember(Long lessonId, Integer userId) {
+ Lesson lesson = lessonDAO.getLesson(lessonId);
+ if (lesson == null) {
+ throw new LessonServiceException("Lesson " + lessonId
+ + " does not exist. Unable to add staff member to lesson.");
+ }
- LessonClass lessonClass = lesson.getLessonClass();
+ LessonClass lessonClass = lesson.getLessonClass();
- if (lessonClass == null) {
- throw new LessonServiceException("Lesson class for " + lessonId
- + " does not exist. Unable to add staff member to lesson.");
- }
+ if (lessonClass == null) {
+ throw new LessonServiceException("Lesson class for " + lessonId
+ + " does not exist. Unable to add staff member to lesson.");
+ }
- lessonDAO.initialize(lessonClass.getStaffGroup());
- User user = (User) baseDAO.find(User.class, userId);
+ lessonDAO.initialize(lessonClass.getStaffGroup());
+ User user = (User) baseDAO.find(User.class, userId);
- boolean ret = lessonClass.addStaffMember(user);
- if (ret) {
- lessonClassDAO.updateLessonClass(lessonClass);
- }
- return ret;
+ boolean ret = lessonClass.addStaffMember(user);
+ if (ret) {
+ lessonClassDAO.updateLessonClass(lessonClass);
}
+ return ret;
+ }
- /**
- * Add a set of staff to the lesson class.
- *
- * If version of the method is designed to be called from Moodle or some other external system,
- * and is less efficient in that it has to look up the user from the user id.
- * If we don't do this, then we may get a a session closed issue if this code is called from the
- * LoginRequestValve (as the users will be from a previous session)
- *
- * @param lessonId
- * @param userIds array of new staff ids
- */
- public void addStaffMembers(Long lessonId, Integer[] userIds) throws LessonServiceException {
+ /**
+ * Add a set of staff to the lesson class.
+ *
+ * If version of the method is designed to be called from Moodle or some other external system, and is less
+ * efficient in that it has to look up the user from the user id. If we don't do this, then we may get a a session
+ * closed issue if this code is called from the LoginRequestValve (as the users will be from a previous session)
+ *
+ * @param lessonId
+ * @param userIds
+ * array of new staff ids
+ */
+ public void addStaffMembers(Long lessonId, Integer[] userIds) throws LessonServiceException {
- Lesson lesson = lessonDAO.getLesson(lessonId);
- if (lesson == null) {
- throw new LessonServiceException("Lesson " + lessonId + " does not exist. Unable to add learner to lesson.");
- }
- LessonClass lessonClass = lesson.getLessonClass();
- if (lessonClass == null) {
- throw new LessonServiceException("Lesson class for " + lessonId + " does not exist. Unable to add learner to lesson.");
- }
+ Lesson lesson = lessonDAO.getLesson(lessonId);
+ if (lesson == null) {
+ throw new LessonServiceException("Lesson " + lessonId + " does not exist. Unable to add learner to lesson.");
+ }
+ LessonClass lessonClass = lesson.getLessonClass();
+ if (lessonClass == null) {
+ throw new LessonServiceException("Lesson class for " + lessonId
+ + " does not exist. Unable to add learner to lesson.");
+ }
- // initialise the lesson group, or we might get a lazy loading error in the future
- // when logging in from an external system. Should only be two groups - learner and staff
- // yes this is a bit of a hack!
- lessonDAO.initialize(lessonClass.getStaffGroup());
+ // initialise the lesson group, or we might get a lazy loading error in the future
+ // when logging in from an external system. Should only be two groups - learner and staff
+ // yes this is a bit of a hack!
+ lessonDAO.initialize(lessonClass.getStaffGroup());
- Set users = new HashSet();
- for (Integer userId : userIds) {
- User user = (User) baseDAO.find(User.class, userId);
- users.add(user);
- }
- addStaffMembers(lesson, users);
+ Set users = new HashSet();
+ for (Integer userId : userIds) {
+ User user = (User) baseDAO.find(User.class, userId);
+ users.add(user);
}
+ addStaffMembers(lesson, users);
+ }
- /**
- * Add a set of staff members to the lesson class. To be called within LAMS - see
- * addLearners(Long lessonId, Integer[] userIds) if calling from an external system.
- *
- * @param lesson lesson
- * @param users the users to add as learners
- */
- public void addStaffMembers(Lesson lesson, Collection users) throws LessonServiceException {
+ /**
+ * Add a set of staff members to the lesson class. To be called within LAMS - see addLearners(Long lessonId,
+ * Integer[] userIds) if calling from an external system.
+ *
+ * @param lesson
+ * lesson
+ * @param users
+ * the users to add as learners
+ */
+ public void addStaffMembers(Lesson lesson, Collection users) throws LessonServiceException {
- LessonClass lessonClass = lesson.getLessonClass();
- int numAdded = lessonClass.addStaffMembers(users);
- if (numAdded > 0) {
- lessonClassDAO.updateLessonClass(lessonClass);
- }
- if (LessonService.log.isDebugEnabled()) {
- LessonService.log.debug("Added " + numAdded + " staff members to lessonClass " + lessonClass.getGroupingId());
- }
+ LessonClass lessonClass = lesson.getLessonClass();
+ int numAdded = lessonClass.addStaffMembers(users);
+ if (numAdded > 0) {
+ lessonClassDAO.updateLessonClass(lessonClass);
}
+ if (LessonService.log.isDebugEnabled()) {
+ LessonService.log.debug("Added " + numAdded + " staff members to lessonClass "
+ + lessonClass.getGroupingId());
+ }
+ }
- /**
- * Remove references to an activity from all learner progress entries.
- * Used by Live Edit, to remove any references to the system gates
- * @param activity The activity for which learner progress references should be removed.
- */
- public void removeProgressReferencesToActivity(Activity activity) throws LessonServiceException {
- if (activity != null) {
- LessonService.log.debug("Processing learner progress for activity " + activity.getActivityId());
+ /**
+ * Remove references to an activity from all learner progress entries. Used by Live Edit, to remove any references
+ * to the system gates
+ *
+ * @param activity
+ * The activity for which learner progress references should be removed.
+ */
+ public void removeProgressReferencesToActivity(Activity activity) throws LessonServiceException {
+ if (activity != null) {
+ LessonService.log.debug("Processing learner progress for activity " + activity.getActivityId());
- List progresses = learnerProgressDAO.getLearnerProgressReferringToActivity(activity);
- if (progresses != null && progresses.size() > 0) {
- Iterator iter = progresses.iterator();
- while (iter.hasNext()) {
- LearnerProgress progress = (LearnerProgress) iter.next();
- if (removeActivityReference(activity, progress)) {
- ;
- }
- learnerProgressDAO.updateLearnerProgress(progress);
- }
- }
+ List progresses = learnerProgressDAO.getLearnerProgressReferringToActivity(activity);
+ if (progresses != null && progresses.size() > 0) {
+ Iterator iter = progresses.iterator();
+ while (iter.hasNext()) {
+ LearnerProgress progress = (LearnerProgress) iter.next();
+ if (removeActivityReference(activity, progress)) {
+ ;
+ }
+ learnerProgressDAO.updateLearnerProgress(progress);
}
+ }
}
+ }
- private boolean removeActivityReference(Activity activity, LearnerProgress progress) {
+ private boolean removeActivityReference(Activity activity, LearnerProgress progress) {
- if (LessonService.log.isDebugEnabled()) {
- LessonService.log.debug("Processing learner progress learner " + progress.getUser().getUserId());
- }
+ if (LessonService.log.isDebugEnabled()) {
+ LessonService.log.debug("Processing learner progress learner " + progress.getUser().getUserId());
+ }
- boolean recordUpdated = false;
+ boolean recordUpdated = false;
- boolean removed = progress.getAttemptedActivities().remove(activity);
- if (removed) {
- recordUpdated = true;
- LessonService.log.debug("Removed activity from attempted activities");
- }
+ boolean removed = progress.getAttemptedActivities().remove(activity);
+ if (removed) {
+ recordUpdated = true;
+ LessonService.log.debug("Removed activity from attempted activities");
+ }
- removed = progress.getCompletedActivities().remove(activity);
- if (removed) {
- recordUpdated = true;
- LessonService.log.debug("Removed activity from completed activities");
- }
+ removed = progress.getCompletedActivities().remove(activity);
+ if (removed) {
+ recordUpdated = true;
+ LessonService.log.debug("Removed activity from completed activities");
+ }
- if (progress.getCurrentActivity() != null && progress.getCurrentActivity().equals(activity)) {
- progress.setCurrentActivity(null);
- recordUpdated = true;
- LessonService.log.debug("Removed activity as current activity");
- }
+ if (progress.getCurrentActivity() != null && progress.getCurrentActivity().equals(activity)) {
+ progress.setCurrentActivity(null);
+ recordUpdated = true;
+ LessonService.log.debug("Removed activity as current activity");
+ }
- if (progress.getNextActivity() != null && progress.getNextActivity().equals(activity)) {
- progress.setNextActivity(null);
- recordUpdated = true;
- LessonService.log.debug("Removed activity as next activity");
- }
+ if (progress.getNextActivity() != null && progress.getNextActivity().equals(activity)) {
+ progress.setNextActivity(null);
+ recordUpdated = true;
+ LessonService.log.debug("Removed activity as next activity");
+ }
- if (progress.getPreviousActivity() != null && progress.getPreviousActivity().equals(activity)) {
- progress.setPreviousActivity(null);
- recordUpdated = true;
- LessonService.log.debug("Removed activity as previous activity");
- }
-
- return recordUpdated;
+ if (progress.getPreviousActivity() != null && progress.getPreviousActivity().equals(activity)) {
+ progress.setPreviousActivity(null);
+ recordUpdated = true;
+ LessonService.log.debug("Removed activity as previous activity");
}
- /**
- * Mark any learner progresses for this lesson as not completed. Called when Live Edit
- * ends, to ensure that if there were any completed progress records, and the design
- * was extended, then they are no longer marked as completed.
- * @param lessonId The lesson for which learner progress entries should be updated.
- */
- public void performMarkLessonUncompleted(Long lessonId) throws LessonServiceException {
- int count = 0;
- if (lessonId != null) {
- LessonService.log.debug("Setting learner progress to uncompleted for lesson " + lessonId);
+ return recordUpdated;
+ }
- List progresses = learnerProgressDAO.getCompletedLearnerProgressForLesson(lessonId);
- if (progresses != null && progresses.size() > 0) {
- Iterator iter = progresses.iterator();
- while (iter.hasNext()) {
- LearnerProgress progress = (LearnerProgress) iter.next();
- if (progress.getLessonComplete() == LearnerProgress.LESSON_END_OF_DESIGN_COMPLETE) {
- progress.setLessonComplete(LearnerProgress.LESSON_NOT_COMPLETE);
- }
- count++;
- }
- }
+ /**
+ * Mark any learner progresses for this lesson as not completed. Called when Live Edit ends, to ensure that if there
+ * were any completed progress records, and the design was extended, then they are no longer marked as completed.
+ *
+ * @param lessonId
+ * The lesson for which learner progress entries should be updated.
+ */
+ public void performMarkLessonUncompleted(Long lessonId) throws LessonServiceException {
+ int count = 0;
+ if (lessonId != null) {
+ LessonService.log.debug("Setting learner progress to uncompleted for lesson " + lessonId);
+
+ List progresses = learnerProgressDAO.getCompletedLearnerProgressForLesson(lessonId);
+ if (progresses != null && progresses.size() > 0) {
+ Iterator iter = progresses.iterator();
+ while (iter.hasNext()) {
+ LearnerProgress progress = (LearnerProgress) iter.next();
+ if (progress.getLessonComplete() == LearnerProgress.LESSON_END_OF_DESIGN_COMPLETE) {
+ progress.setLessonComplete(LearnerProgress.LESSON_NOT_COMPLETE);
+ }
+ count++;
}
- if (LessonService.log.isDebugEnabled()) {
- LessonService.log.debug("Reset completed flag for " + count + " learners for lesson " + lessonId);
- }
+ }
}
-
- /**
- * Get the list of users who have attempted an activity. This is based on the progress engine records.
- * This will give the users in all tool sessions for an activity (if it is a tool activity) or
- * it will give all the users who have attempted an activity that doesn't have any tool sessions, i.e.
- * system activities such as branching.
- */
- public List getLearnersHaveAttemptedActivity(Activity activity) throws LessonServiceException {
- return learnerProgressDAO.getLearnersHaveAttemptedActivity(activity);
+ if (LessonService.log.isDebugEnabled()) {
+ LessonService.log.debug("Reset completed flag for " + count + " learners for lesson " + lessonId);
}
+ }
- /**
- * Get the list of users who have completed an activity. This is based on the progress engine records.
- * This will give the users in all tool sessions for an activity (if it is a tool activity) or
- * it will give all the users who have attempted an activity that doesn't have any tool sessions, i.e.
- * system activities such as branching.
- */
- public List getLearnersHaveCompletedActivity(Activity activity) throws LessonServiceException {
- return learnerProgressDAO.getLearnersHaveCompletedActivity(activity);
- }
+ /**
+ * Get the list of users who have attempted an activity. This is based on the progress engine records. This will
+ * give the users in all tool sessions for an activity (if it is a tool activity) or it will give all the users who
+ * have attempted an activity that doesn't have any tool sessions, i.e. system activities such as branching.
+ */
+ public List getLearnersHaveAttemptedActivity(Activity activity) throws LessonServiceException {
+ return learnerProgressDAO.getLearnersHaveAttemptedActivity(activity);
+ }
- /**
- * Gets the count of the users who have attempted an activity. This is based on the progress engine records.
- * This will work on all activities, including ones that don't have any tool sessions, i.e.
- * system activities such as branching.
- */
- public Integer getCountLearnersHaveAttemptedActivity(Activity activity) throws LessonServiceException {
- return learnerProgressDAO.getNumUsersAttemptedActivity(activity);
- }
+ /**
+ * Get the list of users who have completed an activity. This is based on the progress engine records. This will
+ * give the users in all tool sessions for an activity (if it is a tool activity) or it will give all the users who
+ * have attempted an activity that doesn't have any tool sessions, i.e. system activities such as branching.
+ */
+ public List getLearnersHaveCompletedActivity(Activity activity) throws LessonServiceException {
+ return learnerProgressDAO.getLearnersHaveCompletedActivity(activity);
+ }
- /**
- * Gets the count of the users who have completed an activity. This is based on the progress engine records.
- * This will work on all activities, including ones that don't have any tool sessions, i.e.
- * system activities such as branching.
- */
- public Integer getCountLearnersHaveCompletedActivity(Activity activity) throws LessonServiceException {
- return learnerProgressDAO.getNumUsersCompletedActivity(activity);
- }
+ /**
+ * Gets the count of the users who have attempted an activity. This is based on the progress engine records. This
+ * will work on all activities, including ones that don't have any tool sessions, i.e. system activities such as
+ * branching.
+ */
+ public Integer getCountLearnersHaveAttemptedActivity(Activity activity) throws LessonServiceException {
+ return learnerProgressDAO.getNumUsersAttemptedActivity(activity);
+ }
- public Map getLessonsByOrgAndUserWithCompletedFlag(Integer userId, Integer orgId, boolean isStaff) {
- TreeMap map = new TreeMap();
- List list = lessonDAO.getLessonsByOrgAndUserWithCompletedFlag(userId, orgId, isStaff);
- if (list != null) {
- Iterator iterator = list.iterator();
- while (iterator.hasNext()) {
- Object[] tuple = (Object[]) iterator.next();
- Long lessonId = (Long) tuple[0];
- String lessonName = (String) tuple[1];
- String lessonDescription = (String) tuple[2];
- Integer lessonState = (Integer) tuple[3];
- Boolean lessonCompleted = (Boolean) tuple[4];
- IndexLessonBean bean = new IndexLessonBean(lessonId, lessonName, lessonDescription, lessonState,
- (lessonCompleted == null ? false : lessonCompleted.booleanValue()));
- map.put(new Long(lessonId), bean);
- }
- }
- return map;
- }
+ /**
+ * Gets the count of the users who have completed an activity. This is based on the progress engine records. This
+ * will work on all activities, including ones that don't have any tool sessions, i.e. system activities such as
+ * branching.
+ */
+ public Integer getCountLearnersHaveCompletedActivity(Activity activity) throws LessonServiceException {
+ return learnerProgressDAO.getNumUsersCompletedActivity(activity);
+ }
- /**
- * Gets the learner's progress details for a particular lesson. Will return null if the user
- * has not started the lesson.
- *
- * @param learnerId user's id
- * @param lessonId lesson's id
- * @return learner's progress or null
- */
- public LearnerProgress getUserProgressForLesson(Integer learnerId, Long lessonId) {
- return learnerProgressDAO.getLearnerProgressByLearner(learnerId, lessonId);
+ public Map getLessonsByOrgAndUserWithCompletedFlag(Integer userId, Integer orgId,
+ boolean isStaff) {
+ TreeMap map = new TreeMap();
+ List list = lessonDAO.getLessonsByOrgAndUserWithCompletedFlag(userId, orgId, isStaff);
+ if (list != null) {
+ Iterator iterator = list.iterator();
+ while (iterator.hasNext()) {
+ Object[] tuple = (Object[]) iterator.next();
+ Long lessonId = (Long) tuple[0];
+ String lessonName = (String) tuple[1];
+ String lessonDescription = (String) tuple[2];
+ Integer lessonState = (Integer) tuple[3];
+ Boolean lessonCompleted = (Boolean) tuple[4];
+ IndexLessonBean bean = new IndexLessonBean(lessonId, lessonName, lessonDescription, lessonState,
+ (lessonCompleted == null ? false : lessonCompleted.booleanValue()));
+ map.put(new Long(lessonId), bean);
+ }
}
+ return map;
+ }
- /**
- * Gets list of lessons which are originally based on the given learning design id.
- */
- public List getLessonsByOriginalLearningDesign(Long ldId, Integer orgId) {
- return lessonDAO.getLessonsByOriginalLearningDesign(ldId, orgId);
- }
+ /**
+ * Gets the learner's progress details for a particular lesson. Will return null if the user has not started the
+ * lesson.
+ *
+ * @param learnerId
+ * user's id
+ * @param lessonId
+ * lesson's id
+ * @return learner's progress or null
+ */
+ public LearnerProgress getUserProgressForLesson(Integer learnerId, Long lessonId) {
+ return learnerProgressDAO.getLearnerProgressByLearner(learnerId, lessonId);
+ }
+
+ /**
+ * Gets list of lessons which are originally based on the given learning design id.
+ */
+ public List getLessonsByOriginalLearningDesign(Long ldId, Integer orgId) {
+ return lessonDAO.getLessonsByOriginalLearningDesign(ldId, orgId);
+ }
+
+ public List getMonitorsByToolSessionId(Long sessionId) {
+ return lessonDAO.getMonitorsByToolSessionId(sessionId);
+ }
}
Index: lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/rsrcApplicationContext.xml
===================================================================
diff -u -r05ab55ef4acdc0c374af7405c58fb0e0fe8eb6b7 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/rsrcApplicationContext.xml (.../rsrcApplicationContext.xml) (revision 05ab55ef4acdc0c374af7405c58fb0e0fe8eb6b7)
+++ lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/rsrcApplicationContext.xml (.../rsrcApplicationContext.xml) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -116,6 +116,9 @@
+
+
+
Index: lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/service/IResourceService.java
===================================================================
diff -u -r05ab55ef4acdc0c374af7405c58fb0e0fe8eb6b7 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/service/IResourceService.java (.../IResourceService.java) (revision 05ab55ef4acdc0c374af7405c58fb0e0fe8eb6b7)
+++ lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/service/IResourceService.java (.../IResourceService.java) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -39,6 +39,7 @@
import org.lamsfoundation.lams.tool.rsrc.model.ResourceItem;
import org.lamsfoundation.lams.tool.rsrc.model.ResourceSession;
import org.lamsfoundation.lams.tool.rsrc.model.ResourceUser;
+import org.lamsfoundation.lams.usermanagement.User;
/**
* @author Dapeng.Ni
@@ -47,227 +48,263 @@
*/
public interface IResourceService {
- /**
- * Get file IVersiondNode
by given package id and path.
- * @param packageId
- * @param relPathString
- * @return
- * @throws ResourceApplicationException
- */
- IVersionedNode getFileNode(Long packageId, String relPathString) throws ResourceApplicationException;
+ /**
+ * Get file IVersiondNode
by given package id and path.
+ *
+ * @param packageId
+ * @param relPathString
+ * @return
+ * @throws ResourceApplicationException
+ */
+ IVersionedNode getFileNode(Long packageId, String relPathString) throws ResourceApplicationException;
- /**
- * Get Resource
by toolContentID.
- * @param contentId
- * @return
- */
- Resource getResourceByContentId(Long contentId);
+ /**
+ * Get Resource
by toolContentID.
+ *
+ * @param contentId
+ * @return
+ */
+ Resource getResourceByContentId(Long contentId);
- /**
- * Get a cloned copy of tool default tool content (Resource) and assign the toolContentId of that copy as the
- * given contentId
- * @param contentId
- * @return
- * @throws ResourceApplicationException
- */
- Resource getDefaultContent(Long contentId) throws ResourceApplicationException;
+ /**
+ * Get a cloned copy of tool default tool content (Resource) and assign the toolContentId of that copy as the given
+ * contentId
+ *
+ * @param contentId
+ * @return
+ * @throws ResourceApplicationException
+ */
+ Resource getDefaultContent(Long contentId) throws ResourceApplicationException;
- /**
- * Get list of resource items by given resourceUid. These resource items must be created by author.
- * @param resourceUid
- * @return
- */
- List getAuthoredItems(Long resourceUid);
+ /**
+ * Get list of resource items by given resourceUid. These resource items must be created by author.
+ *
+ * @param resourceUid
+ * @return
+ */
+ List getAuthoredItems(Long resourceUid);
- /**
- * Upload instruciton file into repository.
- * @param file
- * @param type
- * @return
- * @throws UploadResourceFileException
- */
- ResourceAttachment uploadInstructionFile(FormFile file, String type) throws UploadResourceFileException;
+ /**
+ * Upload instruciton file into repository.
+ *
+ * @param file
+ * @param type
+ * @return
+ * @throws UploadResourceFileException
+ */
+ ResourceAttachment uploadInstructionFile(FormFile file, String type) throws UploadResourceFileException;
- /**
- * Upload resource item file to repository. i.e., single file, websize zip file, or learning object zip file.
- * @param item
- * @param file
- * @throws UploadResourceFileException
- */
- void uploadResourceItemFile(ResourceItem item, FormFile file) throws UploadResourceFileException;
+ /**
+ * Upload resource item file to repository. i.e., single file, websize zip file, or learning object zip file.
+ *
+ * @param item
+ * @param file
+ * @throws UploadResourceFileException
+ */
+ void uploadResourceItemFile(ResourceItem item, FormFile file) throws UploadResourceFileException;
- //********** for user methods *************
- /**
- * Create a new user in database.
- */
- void createUser(ResourceUser resourceUser);
+ // ********** for user methods *************
+ /**
+ * Create a new user in database.
+ */
+ void createUser(ResourceUser resourceUser);
- /**
- * Get user by given userID and toolContentID.
- * @param long1
- * @return
- */
- ResourceUser getUserByIDAndContent(Long userID, Long contentId);
+ /**
+ * Get user by given userID and toolContentID.
+ *
+ * @param long1
+ * @return
+ */
+ ResourceUser getUserByIDAndContent(Long userID, Long contentId);
- /**
- * Get user by sessionID and UserID
- * @param long1
- * @param sessionId
- * @return
- */
- ResourceUser getUserByIDAndSession(Long long1, Long sessionId);
+ /**
+ * Get user by sessionID and UserID
+ *
+ * @param long1
+ * @param sessionId
+ * @return
+ */
+ ResourceUser getUserByIDAndSession(Long long1, Long sessionId);
- //********** Repository methods ***********************
- /**
- * Delete file from repository.
- */
- void deleteFromRepository(Long fileUuid, Long fileVersionId) throws ResourceApplicationException;
+ // ********** Repository methods ***********************
+ /**
+ * Delete file from repository.
+ */
+ void deleteFromRepository(Long fileUuid, Long fileVersionId) throws ResourceApplicationException;
- /**
- * Save or update resource into database.
- * @param Resource
- */
- void saveOrUpdateResource(Resource Resource);
+ /**
+ * Save or update resource into database.
+ *
+ * @param Resource
+ */
+ void saveOrUpdateResource(Resource Resource);
- /**
- * Delete reource attachment(i.e., offline/online instruction file) from database. This method does not
- * delete the file from repository.
- *
- * @param attachmentUid
- */
- void deleteResourceAttachment(Long attachmentUid);
+ /**
+ * Delete reource attachment(i.e., offline/online instruction file) from database. This method does not delete the
+ * file from repository.
+ *
+ * @param attachmentUid
+ */
+ void deleteResourceAttachment(Long attachmentUid);
- /**
- * Delete resoruce item from database.
- * @param uid
- */
- void deleteResourceItem(Long uid);
+ /**
+ * Delete resoruce item from database.
+ *
+ * @param uid
+ */
+ void deleteResourceItem(Long uid);
- /**
- * Return all reource items within the given toolSessionID.
- * @param sessionId
- * @return
- */
- List getResourceItemsBySessionId(Long sessionId);
+ /**
+ * Return all reource items within the given toolSessionID.
+ *
+ * @param sessionId
+ * @return
+ */
+ List getResourceItemsBySessionId(Long sessionId);
- /**
- * Get resource which is relative with the special toolSession.
- * @param sessionId
- * @return
- */
- Resource getResourceBySessionId(Long sessionId);
+ /**
+ * Get resource which is relative with the special toolSession.
+ *
+ * @param sessionId
+ * @return
+ */
+ Resource getResourceBySessionId(Long sessionId);
- /**
- * Get resource toolSession by toolSessionId
- * @param sessionId
- * @return
- */
- ResourceSession getResourceSessionBySessionId(Long sessionId);
+ /**
+ * Get resource toolSession by toolSessionId
+ *
+ * @param sessionId
+ * @return
+ */
+ ResourceSession getResourceSessionBySessionId(Long sessionId);
- /**
- * Save or update resource session.
- * @param resSession
- */
- void saveOrUpdateResourceSession(ResourceSession resSession);
+ /**
+ * Save or update resource session.
+ *
+ * @param resSession
+ */
+ void saveOrUpdateResourceSession(ResourceSession resSession);
- void retrieveComplete(SortedSet resourceItemList, ResourceUser user);
+ void retrieveComplete(SortedSet resourceItemList, ResourceUser user);
- void setItemComplete(Long resourceItemUid, Long userId, Long sessionId);
+ void setItemComplete(Long resourceItemUid, Long userId, Long sessionId);
- void setItemAccess(Long resourceItemUid, Long userId, Long sessionId);
+ void setItemAccess(Long resourceItemUid, Long userId, Long sessionId);
- /**
- * the reqired number minus the count of view of the given user.
- * @param userUid
- * @return
- */
- int checkMiniView(Long toolSessionId, Long userId);
+ /**
+ * the reqired number minus the count of view of the given user.
+ *
+ * @param userUid
+ * @return
+ */
+ int checkMiniView(Long toolSessionId, Long userId);
- /**
- * If success return next activity's url, otherwise return null.
- * @param toolSessionId
- * @param userId
- * @return
- */
- String finishToolSession(Long toolSessionId, Long userId) throws ResourceApplicationException;
+ /**
+ * If success return next activity's url, otherwise return null.
+ *
+ * @param toolSessionId
+ * @param userId
+ * @return
+ */
+ String finishToolSession(Long toolSessionId, Long userId) throws ResourceApplicationException;
- ResourceItem getResourceItemByUid(Long itemUid);
+ ResourceItem getResourceItemByUid(Long itemUid);
- /**
- * Return monitoring summary list. The return value is list of resource summaries for each groups.
- * @param contentId
- * @return
- */
- List> getSummary(Long contentId);
+ /**
+ * Return monitoring summary list. The return value is list of resource summaries for each groups.
+ *
+ * @param contentId
+ * @return
+ */
+ List> getSummary(Long contentId);
- List getUserListBySessionItem(Long sessionId, Long itemUid);
+ List getUserListBySessionItem(Long sessionId, Long itemUid);
- /**
- * Set a resource item visible or not.
- * @param itemUid
- * @param visible true, item is visible. False, item is invisible.
- */
- void setItemVisible(Long itemUid, boolean visible);
+ /**
+ * Set a resource item visible or not.
+ *
+ * @param itemUid
+ * @param visible
+ * true, item is visible. False, item is invisible.
+ */
+ void setItemVisible(Long itemUid, boolean visible);
- /**
- * Get resource item Summary
list according to sessionId and skipHide flag.
- *
- * @param sessionId
- * @param skipHide true, don't get resource item if its isHide
flag is true.
- * Otherwise, get all resource item
- * @return
- */
- public List exportBySessionId(Long sessionId, boolean skipHide);
+ /**
+ * Get resource item Summary
list according to sessionId and skipHide flag.
+ *
+ * @param sessionId
+ * @param skipHide
+ * true, don't get resource item if its isHide
flag is true. Otherwise, get all
+ * resource item
+ * @return
+ */
+ public List exportBySessionId(Long sessionId, boolean skipHide);
- public List> exportByContentId(Long contentId);
+ public List> exportByContentId(Long contentId);
- /**
- * Create refection entry into notebook tool.
- * @param sessionId
- * @param notebook_tool
- * @param tool_signature
- * @param userId
- * @param entryText
- */
- public Long createNotebookEntry(Long sessionId, Integer notebookToolType, String toolSignature, Integer userId,
- String entryText);
+ /**
+ * Create refection entry into notebook tool.
+ *
+ * @param sessionId
+ * @param notebook_tool
+ * @param tool_signature
+ * @param userId
+ * @param entryText
+ */
+ public Long createNotebookEntry(Long sessionId, Integer notebookToolType, String toolSignature, Integer userId,
+ String entryText);
- /**
- * Get reflection entry from notebook tool.
- * @param sessionId
- * @param idType
- * @param signature
- * @param userID
- * @return
- */
- public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID);
+ /**
+ * Get reflection entry from notebook tool.
+ *
+ * @param sessionId
+ * @param idType
+ * @param signature
+ * @param userID
+ * @return
+ */
+ public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID);
- /**
- * @param notebookEntry
- */
- public void updateEntry(NotebookEntry notebookEntry);
+ /**
+ * @param notebookEntry
+ */
+ public void updateEntry(NotebookEntry notebookEntry);
- /**
- * Get Reflect DTO list grouped by sessionID.
- * @param contentId
- * @return
- */
- Map> getReflectList(Long contentId, boolean setEntry);
+ /**
+ * Get Reflect DTO list grouped by sessionID.
+ *
+ * @param contentId
+ * @return
+ */
+ Map> getReflectList(Long contentId, boolean setEntry);
- /**
- * Get user by UID
- * @param uid
- * @return
- */
- ResourceUser getUser(Long uid);
+ /**
+ * Get user by UID
+ *
+ * @param uid
+ * @return
+ */
+ ResourceUser getUser(Long uid);
- public IEventNotificationService getEventNotificationService();
+ public IEventNotificationService getEventNotificationService();
- /**
- * Gets a message from resource bundle. Same as
in JSP pages.
- * @param key key of the message
- * @param args arguments for the message
- * @return message content
- */
- String getLocalisedMessage(String key, Object[] args);
+ /**
+ * Gets a message from resource bundle. Same as
in JSP pages.
+ *
+ * @param key
+ * key of the message
+ * @param args
+ * arguments for the message
+ * @return message content
+ */
+ String getLocalisedMessage(String key, Object[] args);
+
+ /**
+ * Finds out which lesson the given tool content belongs to and returns its monitoring users.
+ *
+ * @param sessionId
+ * tool session ID
+ * @return list of teachers that monitor the lesson which contains the tool with given session ID
+ */
+ public List getMonitorsByToolSessionId(Long sessionId);
}
Index: lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/service/ResourceServiceImpl.java
===================================================================
diff -u -r05ab55ef4acdc0c374af7405c58fb0e0fe8eb6b7 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/service/ResourceServiceImpl.java (.../ResourceServiceImpl.java) (revision 05ab55ef4acdc0c374af7405c58fb0e0fe8eb6b7)
+++ lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/service/ResourceServiceImpl.java (.../ResourceServiceImpl.java) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -64,6 +64,7 @@
import org.lamsfoundation.lams.learningdesign.service.ExportToolContentException;
import org.lamsfoundation.lams.learningdesign.service.IExportToolContentService;
import org.lamsfoundation.lams.learningdesign.service.ImportToolContentException;
+import org.lamsfoundation.lams.lesson.service.ILessonService;
import org.lamsfoundation.lams.notebook.model.NotebookEntry;
import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants;
import org.lamsfoundation.lams.notebook.service.ICoreNotebookService;
@@ -112,1180 +113,1190 @@
/**
*
- * @author Dapeng.Ni
+ * @author Dapeng.Ni
*
*/
-public class ResourceServiceImpl implements IResourceService, ToolContentManager, ToolSessionManager, ToolContentImport102Manager
+public class ResourceServiceImpl implements IResourceService, ToolContentManager, ToolSessionManager,
+ ToolContentImport102Manager
{
- static Logger log = Logger.getLogger(ResourceServiceImpl.class.getName());
+ static Logger log = Logger.getLogger(ResourceServiceImpl.class.getName());
- private ResourceDAO resourceDao;
+ private ResourceDAO resourceDao;
- private ResourceItemDAO resourceItemDao;
+ private ResourceItemDAO resourceItemDao;
- private ResourceAttachmentDAO resourceAttachmentDao;
+ private ResourceAttachmentDAO resourceAttachmentDao;
- private ResourceUserDAO resourceUserDao;
+ private ResourceUserDAO resourceUserDao;
- private ResourceSessionDAO resourceSessionDao;
+ private ResourceSessionDAO resourceSessionDao;
- private ResourceItemVisitDAO resourceItemVisitDao;
+ private ResourceItemVisitDAO resourceItemVisitDao;
- //tool service
- private ResourceToolContentHandler resourceToolContentHandler;
+ // tool service
+ private ResourceToolContentHandler resourceToolContentHandler;
- private MessageService messageService;
+ private MessageService messageService;
- //system services
- private IRepositoryService repositoryService;
+ // system services
+ private IRepositoryService repositoryService;
- private ILamsToolService toolService;
+ private ILamsToolService toolService;
- private ILearnerService learnerService;
+ private ILearnerService learnerService;
- private IAuditService auditService;
+ private IAuditService auditService;
- private IUserManagementService userManagementService;
+ private IUserManagementService userManagementService;
- private IExportToolContentService exportContentService;
+ private IExportToolContentService exportContentService;
- private ICoreNotebookService coreNotebookService;
+ private ICoreNotebookService coreNotebookService;
- private IEventNotificationService eventNotificationService;
+ private IEventNotificationService eventNotificationService;
- public IVersionedNode getFileNode(Long itemUid, String relPathString) throws ResourceApplicationException {
- ResourceItem item = (ResourceItem) resourceItemDao.getObject(ResourceItem.class, itemUid);
- if (item == null) {
- throw new ResourceApplicationException("Reource item " + itemUid + " not found.");
- }
+ private ILessonService lessonService;
- return getFile(item.getFileUuid(), item.getFileVersionId(), relPathString);
+ public IVersionedNode getFileNode(Long itemUid, String relPathString) throws ResourceApplicationException {
+ ResourceItem item = (ResourceItem) resourceItemDao.getObject(ResourceItem.class, itemUid);
+ if (item == null) {
+ throw new ResourceApplicationException("Reource item " + itemUid + " not found.");
}
- //*******************************************************************************
- // Service method
- //*******************************************************************************
- /** Try to get the file. If forceLogin = false and an access denied exception occurs, call this method
- * again to get a new ticket and retry file lookup. If forceLogin = true and it then fails
- * then throw exception.
- * @param uuid
- * @param versionId
- * @param relativePath
- * @param attemptCount
- * @return file node
- * @throws ImscpApplicationException
- */
- private IVersionedNode getFile(Long uuid, Long versionId, String relativePath) throws ResourceApplicationException {
+ return getFile(item.getFileUuid(), item.getFileVersionId(), relPathString);
+ }
- ITicket tic = getRepositoryLoginTicket();
+ // *******************************************************************************
+ // Service method
+ // *******************************************************************************
+ /**
+ * Try to get the file. If forceLogin = false and an access denied exception occurs, call this method again to get a
+ * new ticket and retry file lookup. If forceLogin = true and it then fails then throw exception.
+ *
+ * @param uuid
+ * @param versionId
+ * @param relativePath
+ * @param attemptCount
+ * @return file node
+ * @throws ImscpApplicationException
+ */
+ private IVersionedNode getFile(Long uuid, Long versionId, String relativePath) throws ResourceApplicationException {
- try {
+ ITicket tic = getRepositoryLoginTicket();
- return repositoryService.getFileItem(tic, uuid, versionId, relativePath);
+ try {
- }
- catch (AccessDeniedException e) {
+ return repositoryService.getFileItem(tic, uuid, versionId, relativePath);
- String error = "Unable to access repository to get file uuid " + uuid + " version id " + versionId + " path "
- + relativePath + ".";
+ } catch (AccessDeniedException e) {
- error = error + "AccessDeniedException: " + e.getMessage() + " Unable to retry further.";
- ResourceServiceImpl.log.error(error);
- throw new ResourceApplicationException(error, e);
+ String error = "Unable to access repository to get file uuid " + uuid + " version id " + versionId
+ + " path " + relativePath + ".";
- }
- catch (Exception e) {
+ error = error + "AccessDeniedException: " + e.getMessage() + " Unable to retry further.";
+ ResourceServiceImpl.log.error(error);
+ throw new ResourceApplicationException(error, e);
- String error = "Unable to access repository to get file uuid " + uuid + " version id " + versionId + " path "
- + relativePath + "." + " Exception: " + e.getMessage();
- ResourceServiceImpl.log.error(error);
- throw new ResourceApplicationException(error, e);
+ } catch (Exception e) {
- }
- }
+ String error = "Unable to access repository to get file uuid " + uuid + " version id " + versionId
+ + " path " + relativePath + "." + " Exception: " + e.getMessage();
+ ResourceServiceImpl.log.error(error);
+ throw new ResourceApplicationException(error, e);
- /**
- * This method verifies the credentials of the Share Resource Tool and gives it
- * the Ticket
to login and access the Content Repository.
- *
- * A valid ticket is needed in order to access the content from the
- * repository. This method would be called evertime the tool needs to
- * upload/download files from the content repository.
- *
- * @return ITicket The ticket for repostory access
- * @throws ResourceApplicationException
- */
- private ITicket getRepositoryLoginTicket() throws ResourceApplicationException {
- ICredentials credentials = new SimpleCredentials(resourceToolContentHandler.getRepositoryUser(),
- resourceToolContentHandler.getRepositoryId());
- try {
- ITicket ticket = repositoryService.login(credentials, resourceToolContentHandler.getRepositoryWorkspaceName());
- return ticket;
- }
- catch (AccessDeniedException ae) {
- throw new ResourceApplicationException("Access Denied to repository." + ae.getMessage());
- }
- catch (WorkspaceNotFoundException we) {
- throw new ResourceApplicationException("Workspace not found." + we.getMessage());
- }
- catch (LoginException e) {
- throw new ResourceApplicationException("Login failed." + e.getMessage());
- }
}
+ }
- public Resource getResourceByContentId(Long contentId) {
- Resource rs = resourceDao.getByContentId(contentId);
- if (rs == null) {
- ResourceServiceImpl.log.error("Could not find the content by given ID:" + contentId);
- }
- return rs;
+ /**
+ * This method verifies the credentials of the Share Resource Tool and gives it the Ticket
to login
+ * and access the Content Repository.
+ *
+ * A valid ticket is needed in order to access the content from the repository. This method would be called evertime
+ * the tool needs to upload/download files from the content repository.
+ *
+ * @return ITicket The ticket for repostory access
+ * @throws ResourceApplicationException
+ */
+ private ITicket getRepositoryLoginTicket() throws ResourceApplicationException {
+ ICredentials credentials = new SimpleCredentials(resourceToolContentHandler.getRepositoryUser(),
+ resourceToolContentHandler.getRepositoryId());
+ try {
+ ITicket ticket = repositoryService.login(credentials, resourceToolContentHandler
+ .getRepositoryWorkspaceName());
+ return ticket;
+ } catch (AccessDeniedException ae) {
+ throw new ResourceApplicationException("Access Denied to repository." + ae.getMessage());
+ } catch (WorkspaceNotFoundException we) {
+ throw new ResourceApplicationException("Workspace not found." + we.getMessage());
+ } catch (LoginException e) {
+ throw new ResourceApplicationException("Login failed." + e.getMessage());
}
+ }
- public Resource getDefaultContent(Long contentId) throws ResourceApplicationException {
- if (contentId == null) {
- String error = messageService.getMessage("error.msg.default.content.not.find");
- ResourceServiceImpl.log.error(error);
- throw new ResourceApplicationException(error);
- }
-
- Resource defaultContent = getDefaultResource();
- //save default content by given ID.
- Resource content = new Resource();
- content = Resource.newInstance(defaultContent, contentId, resourceToolContentHandler);
- return content;
+ public Resource getResourceByContentId(Long contentId) {
+ Resource rs = resourceDao.getByContentId(contentId);
+ if (rs == null) {
+ ResourceServiceImpl.log.error("Could not find the content by given ID:" + contentId);
}
+ return rs;
+ }
- public List getAuthoredItems(Long resourceUid) {
- return resourceItemDao.getAuthoringItems(resourceUid);
+ public Resource getDefaultContent(Long contentId) throws ResourceApplicationException {
+ if (contentId == null) {
+ String error = messageService.getMessage("error.msg.default.content.not.find");
+ ResourceServiceImpl.log.error(error);
+ throw new ResourceApplicationException(error);
}
- public ResourceAttachment uploadInstructionFile(FormFile uploadFile, String fileType) throws UploadResourceFileException {
- if (uploadFile == null || StringUtils.isEmpty(uploadFile.getFileName())) {
- throw new UploadResourceFileException(messageService.getMessage("error.msg.upload.file.not.found",
- new Object[] { uploadFile }));
- }
+ Resource defaultContent = getDefaultResource();
+ // save default content by given ID.
+ Resource content = new Resource();
+ content = Resource.newInstance(defaultContent, contentId, resourceToolContentHandler);
+ return content;
+ }
- //upload file to repository
- NodeKey nodeKey = processFile(uploadFile, fileType);
+ public List getAuthoredItems(Long resourceUid) {
+ return resourceItemDao.getAuthoringItems(resourceUid);
+ }
- //create new attachement
- ResourceAttachment file = new ResourceAttachment();
- file.setFileType(fileType);
- file.setFileUuid(nodeKey.getUuid());
- file.setFileVersionId(nodeKey.getVersion());
- file.setFileName(uploadFile.getFileName());
- file.setCreated(new Date());
-
- return file;
+ public ResourceAttachment uploadInstructionFile(FormFile uploadFile, String fileType)
+ throws UploadResourceFileException {
+ if (uploadFile == null || StringUtils.isEmpty(uploadFile.getFileName())) {
+ throw new UploadResourceFileException(messageService.getMessage("error.msg.upload.file.not.found",
+ new Object[] { uploadFile }));
}
- public void createUser(ResourceUser resourceUser) {
- resourceUserDao.saveObject(resourceUser);
- }
+ // upload file to repository
+ NodeKey nodeKey = processFile(uploadFile, fileType);
- public ResourceUser getUserByIDAndContent(Long userId, Long contentId) {
+ // create new attachement
+ ResourceAttachment file = new ResourceAttachment();
+ file.setFileType(fileType);
+ file.setFileUuid(nodeKey.getUuid());
+ file.setFileVersionId(nodeKey.getVersion());
+ file.setFileName(uploadFile.getFileName());
+ file.setCreated(new Date());
- return resourceUserDao.getUserByUserIDAndContentID(userId, contentId);
+ return file;
+ }
- }
+ public void createUser(ResourceUser resourceUser) {
+ resourceUserDao.saveObject(resourceUser);
+ }
- public ResourceUser getUserByIDAndSession(Long userId, Long sessionId) {
+ public ResourceUser getUserByIDAndContent(Long userId, Long contentId) {
- return resourceUserDao.getUserByUserIDAndSessionID(userId, sessionId);
+ return resourceUserDao.getUserByUserIDAndContentID(userId, contentId);
- }
+ }
- public void deleteFromRepository(Long fileUuid, Long fileVersionId) throws ResourceApplicationException {
- ITicket ticket = getRepositoryLoginTicket();
- try {
- repositoryService.deleteVersion(ticket, fileUuid, fileVersionId);
- }
- catch (Exception e) {
- throw new ResourceApplicationException("Exception occured while deleting files from" + " the repository "
- + e.getMessage());
- }
- }
+ public ResourceUser getUserByIDAndSession(Long userId, Long sessionId) {
- public void saveOrUpdateResource(Resource resource) {
- resourceDao.saveObject(resource);
- }
+ return resourceUserDao.getUserByUserIDAndSessionID(userId, sessionId);
- public void deleteResourceAttachment(Long attachmentUid) {
- resourceAttachmentDao.removeObject(ResourceAttachment.class, attachmentUid);
+ }
+ public void deleteFromRepository(Long fileUuid, Long fileVersionId) throws ResourceApplicationException {
+ ITicket ticket = getRepositoryLoginTicket();
+ try {
+ repositoryService.deleteVersion(ticket, fileUuid, fileVersionId);
+ } catch (Exception e) {
+ throw new ResourceApplicationException("Exception occured while deleting files from" + " the repository "
+ + e.getMessage());
}
+ }
- public void saveOrUpdateResourceItem(ResourceItem item) {
- resourceItemDao.saveObject(item);
- }
+ public void saveOrUpdateResource(Resource resource) {
+ resourceDao.saveObject(resource);
+ }
- public void deleteResourceItem(Long uid) {
- resourceItemDao.removeObject(ResourceItem.class, uid);
- }
+ public void deleteResourceAttachment(Long attachmentUid) {
+ resourceAttachmentDao.removeObject(ResourceAttachment.class, attachmentUid);
- public List getResourceItemsBySessionId(Long sessionId) {
- ResourceSession session = resourceSessionDao.getSessionBySessionId(sessionId);
- if (session == null) {
- ResourceServiceImpl.log.error("Failed get ResourceSession by ID [" + sessionId + "]");
- return null;
- }
- //add resource items from Authoring
- Resource resource = session.getResource();
- List items = new ArrayList();
- items.addAll(resource.getResourceItems());
+ }
- //add resource items from ResourceSession
- items.addAll(session.getResourceItems());
+ public void saveOrUpdateResourceItem(ResourceItem item) {
+ resourceItemDao.saveObject(item);
+ }
- return items;
+ public void deleteResourceItem(Long uid) {
+ resourceItemDao.removeObject(ResourceItem.class, uid);
+ }
+
+ public List getResourceItemsBySessionId(Long sessionId) {
+ ResourceSession session = resourceSessionDao.getSessionBySessionId(sessionId);
+ if (session == null) {
+ ResourceServiceImpl.log.error("Failed get ResourceSession by ID [" + sessionId + "]");
+ return null;
}
+ // add resource items from Authoring
+ Resource resource = session.getResource();
+ List items = new ArrayList();
+ items.addAll(resource.getResourceItems());
- public List exportBySessionId(Long sessionId, boolean skipHide) {
- ResourceSession session = resourceSessionDao.getSessionBySessionId(sessionId);
- if (session == null) {
- ResourceServiceImpl.log.error("Failed get ResourceSession by ID [" + sessionId + "]");
- return null;
- }
- //initial resource items list
- List itemList = new ArrayList();
- Set resList = session.getResource().getResourceItems();
- for (ResourceItem item : resList) {
- if (skipHide && item.isHide()) {
- continue;
- }
- //if item is create by author
- if (item.isCreateByAuthor()) {
- Summary sum = new Summary(session.getSessionId(), session.getSessionName(), item, false);
- itemList.add(sum);
- }
- }
+ // add resource items from ResourceSession
+ items.addAll(session.getResourceItems());
- //get this session's all resource items
- Set sessList = session.getResourceItems();
- for (ResourceItem item : sessList) {
- if (skipHide && item.isHide()) {
- continue;
- }
+ return items;
+ }
- //to skip all item create by author
- if (!item.isCreateByAuthor()) {
- Summary sum = new Summary(session.getSessionId(), session.getSessionName(), item, false);
- itemList.add(sum);
- }
- }
-
- return itemList;
+ public List exportBySessionId(Long sessionId, boolean skipHide) {
+ ResourceSession session = resourceSessionDao.getSessionBySessionId(sessionId);
+ if (session == null) {
+ ResourceServiceImpl.log.error("Failed get ResourceSession by ID [" + sessionId + "]");
+ return null;
}
+ // initial resource items list
+ List itemList = new ArrayList();
+ Set resList = session.getResource().getResourceItems();
+ for (ResourceItem item : resList) {
+ if (skipHide && item.isHide()) {
+ continue;
+ }
+ // if item is create by author
+ if (item.isCreateByAuthor()) {
+ Summary sum = new Summary(session.getSessionId(), session.getSessionName(), item, false);
+ itemList.add(sum);
+ }
+ }
- public List> exportByContentId(Long contentId) {
- Resource resource = resourceDao.getByContentId(contentId);
- List> groupList = new ArrayList();
+ // get this session's all resource items
+ Set sessList = session.getResourceItems();
+ for (ResourceItem item : sessList) {
+ if (skipHide && item.isHide()) {
+ continue;
+ }
- //create init resource items list
- List initList = new ArrayList();
- groupList.add(initList);
- Set resList = resource.getResourceItems();
- for (ResourceItem item : resList) {
- if (item.isCreateByAuthor()) {
- Summary sum = new Summary(null, null, item, true);
- initList.add(sum);
- }
- }
-
- //session by session
- List sessionList = resourceSessionDao.getByContentId(contentId);
- for (ResourceSession session : sessionList) {
- List group = new ArrayList();
- //get this session's all resource items
- Set sessList = session.getResourceItems();
- for (ResourceItem item : sessList) {
- //to skip all item create by author
- if (!item.isCreateByAuthor()) {
- Summary sum = new Summary(session.getSessionId(), session.getSessionName(), item, false);
- group.add(sum);
- }
- }
- if (group.size() == 0) {
- group.add(new Summary(session.getSessionId(), session.getSessionName(), null, false));
- }
- groupList.add(group);
- }
-
- return groupList;
+ // to skip all item create by author
+ if (!item.isCreateByAuthor()) {
+ Summary sum = new Summary(session.getSessionId(), session.getSessionName(), item, false);
+ itemList.add(sum);
+ }
}
- public Resource getResourceBySessionId(Long sessionId) {
- ResourceSession session = resourceSessionDao.getSessionBySessionId(sessionId);
- //to skip CGLib problem
- Long contentId = session.getResource().getContentId();
- Resource res = resourceDao.getByContentId(contentId);
- int miniView = res.getMiniViewResourceNumber();
- //construct dto fields;
- res.setMiniViewNumberStr(messageService.getMessage("label.learning.minimum.review",
- new Object[] { new Integer(miniView) }));
- return res;
- }
+ return itemList;
+ }
- public ResourceSession getResourceSessionBySessionId(Long sessionId) {
- return resourceSessionDao.getSessionBySessionId(sessionId);
- }
+ public List> exportByContentId(Long contentId) {
+ Resource resource = resourceDao.getByContentId(contentId);
+ List> groupList = new ArrayList();
- public void saveOrUpdateResourceSession(ResourceSession resSession) {
- resourceSessionDao.saveObject(resSession);
+ // create init resource items list
+ List initList = new ArrayList();
+ groupList.add(initList);
+ Set resList = resource.getResourceItems();
+ for (ResourceItem item : resList) {
+ if (item.isCreateByAuthor()) {
+ Summary sum = new Summary(null, null, item, true);
+ initList.add(sum);
+ }
}
- public void retrieveComplete(SortedSet resourceItemList, ResourceUser user) {
- for (ResourceItem item : resourceItemList) {
- ResourceItemVisitLog log = resourceItemVisitDao.getResourceItemLog(item.getUid(), user.getUserId());
- if (log == null) {
- item.setComplete(false);
- }
- else {
- item.setComplete(log.isComplete());
- }
+ // session by session
+ List sessionList = resourceSessionDao.getByContentId(contentId);
+ for (ResourceSession session : sessionList) {
+ List group = new ArrayList();
+ // get this session's all resource items
+ Set sessList = session.getResourceItems();
+ for (ResourceItem item : sessList) {
+ // to skip all item create by author
+ if (!item.isCreateByAuthor()) {
+ Summary sum = new Summary(session.getSessionId(), session.getSessionName(), item, false);
+ group.add(sum);
}
+ }
+ if (group.size() == 0) {
+ group.add(new Summary(session.getSessionId(), session.getSessionName(), null, false));
+ }
+ groupList.add(group);
}
- public void setItemComplete(Long resourceItemUid, Long userId, Long sessionId) {
- ResourceItemVisitLog log = resourceItemVisitDao.getResourceItemLog(resourceItemUid, userId);
- if (log == null) {
- log = new ResourceItemVisitLog();
- ResourceItem item = resourceItemDao.getByUid(resourceItemUid);
- log.setResourceItem(item);
- ResourceUser user = resourceUserDao.getUserByUserIDAndSessionID(userId, sessionId);
- log.setUser(user);
- log.setSessionId(sessionId);
- log.setAccessDate(new Timestamp(new Date().getTime()));
- }
- log.setComplete(true);
- resourceItemVisitDao.saveObject(log);
- }
+ return groupList;
+ }
- public void setItemAccess(Long resourceItemUid, Long userId, Long sessionId) {
- ResourceItemVisitLog log = resourceItemVisitDao.getResourceItemLog(resourceItemUid, userId);
- if (log == null) {
- log = new ResourceItemVisitLog();
- ResourceItem item = resourceItemDao.getByUid(resourceItemUid);
- log.setResourceItem(item);
- ResourceUser user = resourceUserDao.getUserByUserIDAndSessionID(userId, sessionId);
- log.setUser(user);
- log.setComplete(false);
- log.setSessionId(sessionId);
- log.setAccessDate(new Timestamp(new Date().getTime()));
- resourceItemVisitDao.saveObject(log);
- }
- }
+ public Resource getResourceBySessionId(Long sessionId) {
+ ResourceSession session = resourceSessionDao.getSessionBySessionId(sessionId);
+ // to skip CGLib problem
+ Long contentId = session.getResource().getContentId();
+ Resource res = resourceDao.getByContentId(contentId);
+ int miniView = res.getMiniViewResourceNumber();
+ // construct dto fields;
+ res.setMiniViewNumberStr(messageService.getMessage("label.learning.minimum.review", new Object[] { new Integer(
+ miniView) }));
+ return res;
+ }
- public String finishToolSession(Long toolSessionId, Long userId) throws ResourceApplicationException {
- ResourceUser user = resourceUserDao.getUserByUserIDAndSessionID(userId, toolSessionId);
- user.setSessionFinished(true);
- resourceUserDao.saveObject(user);
+ public ResourceSession getResourceSessionBySessionId(Long sessionId) {
+ return resourceSessionDao.getSessionBySessionId(sessionId);
+ }
- // ResourceSession session = resourceSessionDao.getSessionBySessionId(toolSessionId);
- // session.setStatus(ResourceConstants.COMPLETED);
- // resourceSessionDao.saveObject(session);
+ public void saveOrUpdateResourceSession(ResourceSession resSession) {
+ resourceSessionDao.saveObject(resSession);
+ }
- String nextUrl = null;
- try {
- nextUrl = this.leaveToolSession(toolSessionId, userId);
- }
- catch (DataMissingException e) {
- throw new ResourceApplicationException(e);
- }
- catch (ToolException e) {
- throw new ResourceApplicationException(e);
- }
- return nextUrl;
+ public void retrieveComplete(SortedSet resourceItemList, ResourceUser user) {
+ for (ResourceItem item : resourceItemList) {
+ ResourceItemVisitLog log = resourceItemVisitDao.getResourceItemLog(item.getUid(), user.getUserId());
+ if (log == null) {
+ item.setComplete(false);
+ } else {
+ item.setComplete(log.isComplete());
+ }
}
+ }
- public int checkMiniView(Long toolSessionId, Long userUid) {
- int miniView = resourceItemVisitDao.getUserViewLogCount(toolSessionId, userUid);
- ResourceSession session = resourceSessionDao.getSessionBySessionId(toolSessionId);
- if (session == null) {
- ResourceServiceImpl.log.error("Failed get session by ID [" + toolSessionId + "]");
- return 0;
- }
- int reqView = session.getResource().getMiniViewResourceNumber();
-
- return reqView - miniView;
+ public void setItemComplete(Long resourceItemUid, Long userId, Long sessionId) {
+ ResourceItemVisitLog log = resourceItemVisitDao.getResourceItemLog(resourceItemUid, userId);
+ if (log == null) {
+ log = new ResourceItemVisitLog();
+ ResourceItem item = resourceItemDao.getByUid(resourceItemUid);
+ log.setResourceItem(item);
+ ResourceUser user = resourceUserDao.getUserByUserIDAndSessionID(userId, sessionId);
+ log.setUser(user);
+ log.setSessionId(sessionId);
+ log.setAccessDate(new Timestamp(new Date().getTime()));
}
+ log.setComplete(true);
+ resourceItemVisitDao.saveObject(log);
+ }
- public ResourceItem getResourceItemByUid(Long itemUid) {
- return resourceItemDao.getByUid(itemUid);
+ public void setItemAccess(Long resourceItemUid, Long userId, Long sessionId) {
+ ResourceItemVisitLog log = resourceItemVisitDao.getResourceItemLog(resourceItemUid, userId);
+ if (log == null) {
+ log = new ResourceItemVisitLog();
+ ResourceItem item = resourceItemDao.getByUid(resourceItemUid);
+ log.setResourceItem(item);
+ ResourceUser user = resourceUserDao.getUserByUserIDAndSessionID(userId, sessionId);
+ log.setUser(user);
+ log.setComplete(false);
+ log.setSessionId(sessionId);
+ log.setAccessDate(new Timestamp(new Date().getTime()));
+ resourceItemVisitDao.saveObject(log);
}
+ }
- public List> getSummary(Long contentId) {
- List> groupList = new ArrayList>();
- List group = new ArrayList();
+ public String finishToolSession(Long toolSessionId, Long userId) throws ResourceApplicationException {
+ ResourceUser user = resourceUserDao.getUserByUserIDAndSessionID(userId, toolSessionId);
+ user.setSessionFinished(true);
+ resourceUserDao.saveObject(user);
- //get all item which is accessed by user
- Map visitCountMap = resourceItemVisitDao.getSummary(contentId);
+ // ResourceSession session = resourceSessionDao.getSessionBySessionId(toolSessionId);
+ // session.setStatus(ResourceConstants.COMPLETED);
+ // resourceSessionDao.saveObject(session);
- Resource resource = resourceDao.getByContentId(contentId);
- Set resItemList = resource.getResourceItems();
+ String nextUrl = null;
+ try {
+ nextUrl = this.leaveToolSession(toolSessionId, userId);
+ } catch (DataMissingException e) {
+ throw new ResourceApplicationException(e);
+ } catch (ToolException e) {
+ throw new ResourceApplicationException(e);
+ }
+ return nextUrl;
+ }
- //get all sessions in a resource and retrieve all resource items under this session
- //plus initial resource items by author creating (resItemList)
- List sessionList = resourceSessionDao.getByContentId(contentId);
- for (ResourceSession session : sessionList) {
- //one new group for one session.
- group = new ArrayList();
- //firstly, put all initial resource item into this group.
- for (ResourceItem item : resItemList) {
- Summary sum = new Summary(session.getSessionId(), session.getSessionName(), item);
- //set viewNumber according visit log
- if (visitCountMap.containsKey(item.getUid())) {
- sum.setViewNumber(visitCountMap.get(item.getUid()).intValue());
- }
- group.add(sum);
- }
- //get this session's all resource items
- Set sessItemList = session.getResourceItems();
- for (ResourceItem item : sessItemList) {
- //to skip all item create by author
- if (!item.isCreateByAuthor()) {
- Summary sum = new Summary(session.getSessionId(), session.getSessionName(), item);
- //set viewNumber according visit log
- if (visitCountMap.containsKey(item.getUid())) {
- sum.setViewNumber(visitCountMap.get(item.getUid()).intValue());
- }
- group.add(sum);
- }
- }
- //so far no any item available, so just put session name info to Summary
- if (group.size() == 0) {
- group.add(new Summary(session.getSessionId(), session.getSessionName(), null));
- }
- groupList.add(group);
- }
-
- return groupList;
-
+ public int checkMiniView(Long toolSessionId, Long userUid) {
+ int miniView = resourceItemVisitDao.getUserViewLogCount(toolSessionId, userUid);
+ ResourceSession session = resourceSessionDao.getSessionBySessionId(toolSessionId);
+ if (session == null) {
+ ResourceServiceImpl.log.error("Failed get session by ID [" + toolSessionId + "]");
+ return 0;
}
+ int reqView = session.getResource().getMiniViewResourceNumber();
- public Map> getReflectList(Long contentId, boolean setEntry) {
- Map> map = new HashMap>();
+ return reqView - miniView;
+ }
- List sessionList = resourceSessionDao.getByContentId(contentId);
- for (ResourceSession session : sessionList) {
- Long sessionId = session.getSessionId();
- boolean hasRefection = session.getResource().isReflectOnActivity();
- Set list = new TreeSet(new ReflectDTOComparator());
- //get all users in this session
- List users = resourceUserDao.getBySessionID(sessionId);
- for (ResourceUser user : users) {
- ReflectDTO ref = new ReflectDTO(user);
+ public ResourceItem getResourceItemByUid(Long itemUid) {
+ return resourceItemDao.getByUid(itemUid);
+ }
- if (setEntry) {
- NotebookEntry entry = getEntry(sessionId, CoreNotebookConstants.NOTEBOOK_TOOL,
- ResourceConstants.TOOL_SIGNATURE, user.getUserId().intValue());
- if (entry != null) {
- ref.setReflect(entry.getEntry());
- }
- }
+ public List> getSummary(Long contentId) {
+ List> groupList = new ArrayList>();
+ List group = new ArrayList();
- ref.setHasRefection(hasRefection);
- list.add(ref);
- }
- map.put(sessionId, list);
- }
+ // get all item which is accessed by user
+ Map visitCountMap = resourceItemVisitDao.getSummary(contentId);
- return map;
- }
+ Resource resource = resourceDao.getByContentId(contentId);
+ Set resItemList = resource.getResourceItems();
- public List getUserListBySessionItem(Long sessionId, Long itemUid) {
- List logList = resourceItemVisitDao.getResourceItemLogBySession(sessionId, itemUid);
- List userList = new ArrayList(logList.size());
- for (ResourceItemVisitLog visit : logList) {
- ResourceUser user = visit.getUser();
- user.setAccessDate(visit.getAccessDate());
- userList.add(user);
+ // get all sessions in a resource and retrieve all resource items under this session
+ // plus initial resource items by author creating (resItemList)
+ List sessionList = resourceSessionDao.getByContentId(contentId);
+ for (ResourceSession session : sessionList) {
+ // one new group for one session.
+ group = new ArrayList();
+ // firstly, put all initial resource item into this group.
+ for (ResourceItem item : resItemList) {
+ Summary sum = new Summary(session.getSessionId(), session.getSessionName(), item);
+ // set viewNumber according visit log
+ if (visitCountMap.containsKey(item.getUid())) {
+ sum.setViewNumber(visitCountMap.get(item.getUid()).intValue());
}
- return userList;
- }
-
- public void setItemVisible(Long itemUid, boolean visible) {
- ResourceItem item = resourceItemDao.getByUid(itemUid);
- if (item != null) {
- //createBy should be null for system default value.
- Long userId = 0L;
- String loginName = "No user";
- if (item.getCreateBy() != null) {
- userId = item.getCreateBy().getUserId();
- loginName = item.getCreateBy().getLoginName();
- }
- if (visible) {
- auditService.logShowEntry(ResourceConstants.TOOL_SIGNATURE, userId, loginName, item.toString());
- }
- else {
- auditService.logHideEntry(ResourceConstants.TOOL_SIGNATURE, userId, loginName, item.toString());
- }
- item.setHide(!visible);
- resourceItemDao.saveObject(item);
+ group.add(sum);
+ }
+ // get this session's all resource items
+ Set sessItemList = session.getResourceItems();
+ for (ResourceItem item : sessItemList) {
+ // to skip all item create by author
+ if (!item.isCreateByAuthor()) {
+ Summary sum = new Summary(session.getSessionId(), session.getSessionName(), item);
+ // set viewNumber according visit log
+ if (visitCountMap.containsKey(item.getUid())) {
+ sum.setViewNumber(visitCountMap.get(item.getUid()).intValue());
+ }
+ group.add(sum);
}
+ }
+ // so far no any item available, so just put session name info to Summary
+ if (group.size() == 0) {
+ group.add(new Summary(session.getSessionId(), session.getSessionName(), null));
+ }
+ groupList.add(group);
}
- public Long createNotebookEntry(Long sessionId, Integer notebookToolType, String toolSignature, Integer userId,
- String entryText) {
- return coreNotebookService.createNotebookEntry(sessionId, notebookToolType, toolSignature, userId, "", entryText);
- }
+ return groupList;
- public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) {
- List list = coreNotebookService.getEntry(sessionId, idType, signature, userID);
- if (list == null || list.isEmpty()) {
- return null;
- }
- else {
- return list.get(0);
- }
- }
+ }
- /**
- * @param notebookEntry
- */
- public void updateEntry(NotebookEntry notebookEntry) {
- coreNotebookService.updateEntry(notebookEntry);
- }
+ public Map> getReflectList(Long contentId, boolean setEntry) {
+ Map> map = new HashMap>();
- public ResourceUser getUser(Long uid) {
- return (ResourceUser) resourceUserDao.getObject(ResourceUser.class, uid);
- }
+ List sessionList = resourceSessionDao.getByContentId(contentId);
+ for (ResourceSession session : sessionList) {
+ Long sessionId = session.getSessionId();
+ boolean hasRefection = session.getResource().isReflectOnActivity();
+ Set list = new TreeSet(new ReflectDTOComparator());
+ // get all users in this session
+ List users = resourceUserDao.getBySessionID(sessionId);
+ for (ResourceUser user : users) {
+ ReflectDTO ref = new ReflectDTO(user);
- //*****************************************************************************
- // private methods
- //*****************************************************************************
- private Resource getDefaultResource() throws ResourceApplicationException {
- Long defaultResourceId = getToolDefaultContentIdBySignature(ResourceConstants.TOOL_SIGNATURE);
- Resource defaultResource = getResourceByContentId(defaultResourceId);
- if (defaultResource == null) {
- String error = messageService.getMessage("error.msg.default.content.not.find");
- ResourceServiceImpl.log.error(error);
- throw new ResourceApplicationException(error);
+ if (setEntry) {
+ NotebookEntry entry = getEntry(sessionId, CoreNotebookConstants.NOTEBOOK_TOOL,
+ ResourceConstants.TOOL_SIGNATURE, user.getUserId().intValue());
+ if (entry != null) {
+ ref.setReflect(entry.getEntry());
+ }
}
- return defaultResource;
+ ref.setHasRefection(hasRefection);
+ list.add(ref);
+ }
+ map.put(sessionId, list);
}
- private Long getToolDefaultContentIdBySignature(String toolSignature) throws ResourceApplicationException {
- Long contentId = null;
- contentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature));
- if (contentId == null) {
- String error = messageService.getMessage("error.msg.default.content.not.find");
- ResourceServiceImpl.log.error(error);
- throw new ResourceApplicationException(error);
- }
- return contentId;
- }
+ return map;
+ }
- /**
- * Process an uploaded file.
- *
- * @throws ResourceApplicationException
- * @throws FileNotFoundException
- * @throws IOException
- * @throws RepositoryCheckedException
- * @throws InvalidParameterException
- */
- private NodeKey processFile(FormFile file, String fileType) throws UploadResourceFileException {
- NodeKey node = null;
- if (file != null && !StringUtils.isEmpty(file.getFileName())) {
- String fileName = file.getFileName();
- try {
- node = resourceToolContentHandler.uploadFile(file.getInputStream(), fileName, file.getContentType(), fileType);
- }
- catch (InvalidParameterException e) {
- throw new UploadResourceFileException(messageService.getMessage("error.msg.invaid.param.upload"));
- }
- catch (FileNotFoundException e) {
- throw new UploadResourceFileException(messageService.getMessage("error.msg.file.not.found"));
- }
- catch (RepositoryCheckedException e) {
- throw new UploadResourceFileException(messageService.getMessage("error.msg.repository"));
- }
- catch (IOException e) {
- throw new UploadResourceFileException(messageService.getMessage("error.msg.io.exception"));
- }
- }
- return node;
+ public List getUserListBySessionItem(Long sessionId, Long itemUid) {
+ List logList = resourceItemVisitDao.getResourceItemLogBySession(sessionId, itemUid);
+ List userList = new ArrayList(logList.size());
+ for (ResourceItemVisitLog visit : logList) {
+ ResourceUser user = visit.getUser();
+ user.setAccessDate(visit.getAccessDate());
+ userList.add(user);
}
+ return userList;
+ }
- private NodeKey processPackage(String packageDirectory, String initFile) throws UploadResourceFileException {
- NodeKey node = null;
- try {
- node = resourceToolContentHandler.uploadPackage(packageDirectory, initFile);
- }
- catch (InvalidParameterException e) {
- throw new UploadResourceFileException(messageService.getMessage("error.msg.invaid.param.upload"));
- }
- catch (RepositoryCheckedException e) {
- throw new UploadResourceFileException(messageService.getMessage("error.msg.repository"));
- }
- return node;
+ public void setItemVisible(Long itemUid, boolean visible) {
+ ResourceItem item = resourceItemDao.getByUid(itemUid);
+ if (item != null) {
+ // createBy should be null for system default value.
+ Long userId = 0L;
+ String loginName = "No user";
+ if (item.getCreateBy() != null) {
+ userId = item.getCreateBy().getUserId();
+ loginName = item.getCreateBy().getLoginName();
+ }
+ if (visible) {
+ auditService.logShowEntry(ResourceConstants.TOOL_SIGNATURE, userId, loginName, item.toString());
+ } else {
+ auditService.logHideEntry(ResourceConstants.TOOL_SIGNATURE, userId, loginName, item.toString());
+ }
+ item.setHide(!visible);
+ resourceItemDao.saveObject(item);
}
+ }
- public void uploadResourceItemFile(ResourceItem item, FormFile file) throws UploadResourceFileException {
- try {
- InputStream is = file.getInputStream();
- String fileName = file.getFileName();
- String fileType = file.getContentType();
- //For file only upload one sigle file
- if (item.getType() == ResourceConstants.RESOURCE_TYPE_FILE) {
- NodeKey nodeKey = processFile(file, IToolContentHandler.TYPE_ONLINE);
- item.setFileUuid(nodeKey.getUuid());
- item.setFileVersionId(nodeKey.getVersion());
- }
- //need unzip upload, and check the initial item :default.htm/html or index.htm/html
- if (item.getType() == ResourceConstants.RESOURCE_TYPE_WEBSITE) {
- String packageDirectory = ZipFileUtil.expandZip(is, fileName);
- String initFile = findWebsiteInitialItem(packageDirectory);
- if (initFile == null) {
- throw new UploadResourceFileException(messageService.getMessage("error.msg.website.no.initial.file"));
- }
- item.setInitialItem(initFile);
- //upload package
- NodeKey nodeKey = processPackage(packageDirectory, initFile);
- item.setFileUuid(nodeKey.getUuid());
- item.setFileVersionId(nodeKey.getVersion());
- }
- //need unzip upload, and parse learning object information from XML file.
- if (item.getType() == ResourceConstants.RESOURCE_TYPE_LEARNING_OBJECT) {
- String packageDirectory = ZipFileUtil.expandZip(is, fileName);
- IContentPackageConverter cpConverter = new SimpleContentPackageConverter(packageDirectory);
- String initFile = cpConverter.getDefaultItem();
- item.setInitialItem(initFile);
- item.setImsSchema(cpConverter.getSchema());
- item.setOrganizationXml(cpConverter.getOrganzationXML());
- // upload package
- NodeKey nodeKey = processPackage(packageDirectory, initFile);
- item.setFileUuid(nodeKey.getUuid());
- item.setFileVersionId(nodeKey.getVersion());
- }
- // create the package from the directory contents
- item.setFileType(fileType);
- item.setFileName(fileName);
- }
- catch (ZipFileUtilException e) {
- ResourceServiceImpl.log.error(messageService.getMessage("error.msg.zip.file.exception") + " : " + e.toString());
- throw new UploadResourceFileException(messageService.getMessage("error.msg.zip.file.exception"));
- }
- catch (FileNotFoundException e) {
- ResourceServiceImpl.log.error(messageService.getMessage("error.msg.file.not.found") + ":" + e.toString());
- throw new UploadResourceFileException(messageService.getMessage("error.msg.file.not.found"));
- }
- catch (IOException e) {
- ResourceServiceImpl.log.error(messageService.getMessage("error.msg.io.exception") + ":" + e.toString());
- throw new UploadResourceFileException(messageService.getMessage("error.msg.io.exception"));
- }
- catch (IMSManifestException e) {
- ResourceServiceImpl.log.error(messageService.getMessage("error.msg.ims.package") + ":" + e.toString());
- throw new UploadResourceFileException(messageService.getMessage("error.msg.ims.package"));
- }
- catch (ImscpApplicationException e) {
- ResourceServiceImpl.log.error(messageService.getMessage("error.msg.ims.application") + ":" + e.toString());
- throw new UploadResourceFileException(messageService.getMessage("error.msg.ims.application"));
- }
+ public Long createNotebookEntry(Long sessionId, Integer notebookToolType, String toolSignature, Integer userId,
+ String entryText) {
+ return coreNotebookService.createNotebookEntry(sessionId, notebookToolType, toolSignature, userId, "",
+ entryText);
+ }
+
+ public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) {
+ List list = coreNotebookService.getEntry(sessionId, idType, signature, userID);
+ if (list == null || list.isEmpty()) {
+ return null;
+ } else {
+ return list.get(0);
}
+ }
- /**
- * Find out default.htm/html or index.htm/html in the given directory folder
- * @param packageDirectory
- * @return
- */
- private String findWebsiteInitialItem(String packageDirectory) {
- File file = new File(packageDirectory);
- if (!file.isDirectory()) {
- return null;
- }
+ /**
+ * @param notebookEntry
+ */
+ public void updateEntry(NotebookEntry notebookEntry) {
+ coreNotebookService.updateEntry(notebookEntry);
+ }
- File[] initFiles = file.listFiles(new FileFilter() {
- public boolean accept(File pathname) {
- if (pathname == null || pathname.getName() == null) {
- return false;
- }
- String name = pathname.getName();
- if (name.endsWith("default.html") || name.endsWith("default.htm") || name.endsWith("index.html")
- || name.endsWith("index.htm")) {
- return true;
- }
- return false;
- }
- });
- if (initFiles != null && initFiles.length > 0) {
- return initFiles[0].getName();
- }
- else {
- return null;
- }
- }
+ public ResourceUser getUser(Long uid) {
+ return (ResourceUser) resourceUserDao.getObject(ResourceUser.class, uid);
+ }
- //*****************************************************************************
- // set methods for Spring Bean
- //*****************************************************************************
- public void setAuditService(IAuditService auditService) {
- this.auditService = auditService;
+ // *****************************************************************************
+ // private methods
+ // *****************************************************************************
+ private Resource getDefaultResource() throws ResourceApplicationException {
+ Long defaultResourceId = getToolDefaultContentIdBySignature(ResourceConstants.TOOL_SIGNATURE);
+ Resource defaultResource = getResourceByContentId(defaultResourceId);
+ if (defaultResource == null) {
+ String error = messageService.getMessage("error.msg.default.content.not.find");
+ ResourceServiceImpl.log.error(error);
+ throw new ResourceApplicationException(error);
}
- public void setLearnerService(ILearnerService learnerService) {
- this.learnerService = learnerService;
- }
+ return defaultResource;
+ }
- public void setMessageService(MessageService messageService) {
- this.messageService = messageService;
+ private Long getToolDefaultContentIdBySignature(String toolSignature) throws ResourceApplicationException {
+ Long contentId = null;
+ contentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature));
+ if (contentId == null) {
+ String error = messageService.getMessage("error.msg.default.content.not.find");
+ ResourceServiceImpl.log.error(error);
+ throw new ResourceApplicationException(error);
}
+ return contentId;
+ }
- public void setRepositoryService(IRepositoryService repositoryService) {
- this.repositoryService = repositoryService;
+ /**
+ * Process an uploaded file.
+ *
+ * @throws ResourceApplicationException
+ * @throws FileNotFoundException
+ * @throws IOException
+ * @throws RepositoryCheckedException
+ * @throws InvalidParameterException
+ */
+ private NodeKey processFile(FormFile file, String fileType) throws UploadResourceFileException {
+ NodeKey node = null;
+ if (file != null && !StringUtils.isEmpty(file.getFileName())) {
+ String fileName = file.getFileName();
+ try {
+ node = resourceToolContentHandler.uploadFile(file.getInputStream(), fileName, file.getContentType(),
+ fileType);
+ } catch (InvalidParameterException e) {
+ throw new UploadResourceFileException(messageService.getMessage("error.msg.invaid.param.upload"));
+ } catch (FileNotFoundException e) {
+ throw new UploadResourceFileException(messageService.getMessage("error.msg.file.not.found"));
+ } catch (RepositoryCheckedException e) {
+ throw new UploadResourceFileException(messageService.getMessage("error.msg.repository"));
+ } catch (IOException e) {
+ throw new UploadResourceFileException(messageService.getMessage("error.msg.io.exception"));
+ }
}
+ return node;
+ }
- public void setResourceAttachmentDao(ResourceAttachmentDAO resourceAttachmentDao) {
- this.resourceAttachmentDao = resourceAttachmentDao;
+ private NodeKey processPackage(String packageDirectory, String initFile) throws UploadResourceFileException {
+ NodeKey node = null;
+ try {
+ node = resourceToolContentHandler.uploadPackage(packageDirectory, initFile);
+ } catch (InvalidParameterException e) {
+ throw new UploadResourceFileException(messageService.getMessage("error.msg.invaid.param.upload"));
+ } catch (RepositoryCheckedException e) {
+ throw new UploadResourceFileException(messageService.getMessage("error.msg.repository"));
}
+ return node;
+ }
- public void setResourceDao(ResourceDAO resourceDao) {
- this.resourceDao = resourceDao;
+ public void uploadResourceItemFile(ResourceItem item, FormFile file) throws UploadResourceFileException {
+ try {
+ InputStream is = file.getInputStream();
+ String fileName = file.getFileName();
+ String fileType = file.getContentType();
+ // For file only upload one sigle file
+ if (item.getType() == ResourceConstants.RESOURCE_TYPE_FILE) {
+ NodeKey nodeKey = processFile(file, IToolContentHandler.TYPE_ONLINE);
+ item.setFileUuid(nodeKey.getUuid());
+ item.setFileVersionId(nodeKey.getVersion());
+ }
+ // need unzip upload, and check the initial item :default.htm/html or index.htm/html
+ if (item.getType() == ResourceConstants.RESOURCE_TYPE_WEBSITE) {
+ String packageDirectory = ZipFileUtil.expandZip(is, fileName);
+ String initFile = findWebsiteInitialItem(packageDirectory);
+ if (initFile == null) {
+ throw new UploadResourceFileException(messageService
+ .getMessage("error.msg.website.no.initial.file"));
+ }
+ item.setInitialItem(initFile);
+ // upload package
+ NodeKey nodeKey = processPackage(packageDirectory, initFile);
+ item.setFileUuid(nodeKey.getUuid());
+ item.setFileVersionId(nodeKey.getVersion());
+ }
+ // need unzip upload, and parse learning object information from XML file.
+ if (item.getType() == ResourceConstants.RESOURCE_TYPE_LEARNING_OBJECT) {
+ String packageDirectory = ZipFileUtil.expandZip(is, fileName);
+ IContentPackageConverter cpConverter = new SimpleContentPackageConverter(packageDirectory);
+ String initFile = cpConverter.getDefaultItem();
+ item.setInitialItem(initFile);
+ item.setImsSchema(cpConverter.getSchema());
+ item.setOrganizationXml(cpConverter.getOrganzationXML());
+ // upload package
+ NodeKey nodeKey = processPackage(packageDirectory, initFile);
+ item.setFileUuid(nodeKey.getUuid());
+ item.setFileVersionId(nodeKey.getVersion());
+ }
+ // create the package from the directory contents
+ item.setFileType(fileType);
+ item.setFileName(fileName);
+ } catch (ZipFileUtilException e) {
+ ResourceServiceImpl.log.error(messageService.getMessage("error.msg.zip.file.exception") + " : "
+ + e.toString());
+ throw new UploadResourceFileException(messageService.getMessage("error.msg.zip.file.exception"));
+ } catch (FileNotFoundException e) {
+ ResourceServiceImpl.log.error(messageService.getMessage("error.msg.file.not.found") + ":" + e.toString());
+ throw new UploadResourceFileException(messageService.getMessage("error.msg.file.not.found"));
+ } catch (IOException e) {
+ ResourceServiceImpl.log.error(messageService.getMessage("error.msg.io.exception") + ":" + e.toString());
+ throw new UploadResourceFileException(messageService.getMessage("error.msg.io.exception"));
+ } catch (IMSManifestException e) {
+ ResourceServiceImpl.log.error(messageService.getMessage("error.msg.ims.package") + ":" + e.toString());
+ throw new UploadResourceFileException(messageService.getMessage("error.msg.ims.package"));
+ } catch (ImscpApplicationException e) {
+ ResourceServiceImpl.log.error(messageService.getMessage("error.msg.ims.application") + ":" + e.toString());
+ throw new UploadResourceFileException(messageService.getMessage("error.msg.ims.application"));
}
+ }
- public void setResourceItemDao(ResourceItemDAO resourceItemDao) {
- this.resourceItemDao = resourceItemDao;
+ /**
+ * Find out default.htm/html or index.htm/html in the given directory folder
+ *
+ * @param packageDirectory
+ * @return
+ */
+ private String findWebsiteInitialItem(String packageDirectory) {
+ File file = new File(packageDirectory);
+ if (!file.isDirectory()) {
+ return null;
}
- public void setResourceSessionDao(ResourceSessionDAO resourceSessionDao) {
- this.resourceSessionDao = resourceSessionDao;
+ File[] initFiles = file.listFiles(new FileFilter() {
+ public boolean accept(File pathname) {
+ if (pathname == null || pathname.getName() == null) {
+ return false;
+ }
+ String name = pathname.getName();
+ if (name.endsWith("default.html") || name.endsWith("default.htm") || name.endsWith("index.html")
+ || name.endsWith("index.htm")) {
+ return true;
+ }
+ return false;
+ }
+ });
+ if (initFiles != null && initFiles.length > 0) {
+ return initFiles[0].getName();
+ } else {
+ return null;
}
+ }
- public void setResourceToolContentHandler(ResourceToolContentHandler resourceToolContentHandler) {
- this.resourceToolContentHandler = resourceToolContentHandler;
- }
+ // *****************************************************************************
+ // set methods for Spring Bean
+ // *****************************************************************************
+ public void setAuditService(IAuditService auditService) {
+ this.auditService = auditService;
+ }
- public void setResourceUserDao(ResourceUserDAO resourceUserDao) {
- this.resourceUserDao = resourceUserDao;
- }
+ public void setLearnerService(ILearnerService learnerService) {
+ this.learnerService = learnerService;
+ }
- public void setToolService(ILamsToolService toolService) {
- this.toolService = toolService;
- }
+ public void setMessageService(MessageService messageService) {
+ this.messageService = messageService;
+ }
- public ResourceItemVisitDAO getResourceItemVisitDao() {
- return resourceItemVisitDao;
- }
+ public void setRepositoryService(IRepositoryService repositoryService) {
+ this.repositoryService = repositoryService;
+ }
- public void setResourceItemVisitDao(ResourceItemVisitDAO resourceItemVisitDao) {
- this.resourceItemVisitDao = resourceItemVisitDao;
- }
+ public void setResourceAttachmentDao(ResourceAttachmentDAO resourceAttachmentDao) {
+ this.resourceAttachmentDao = resourceAttachmentDao;
+ }
- //*******************************************************************************
- //ToolContentManager, ToolSessionManager methods
- //*******************************************************************************
+ public void setResourceDao(ResourceDAO resourceDao) {
+ this.resourceDao = resourceDao;
+ }
- public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException {
- Resource toolContentObj = resourceDao.getByContentId(toolContentId);
- if (toolContentObj == null) {
- try {
- toolContentObj = getDefaultResource();
- }
- catch (ResourceApplicationException e) {
- throw new DataMissingException(e.getMessage());
- }
- }
- if (toolContentObj == null) {
- throw new DataMissingException("Unable to find default content for the share resources tool");
- }
+ public void setResourceItemDao(ResourceItemDAO resourceItemDao) {
+ this.resourceItemDao = resourceItemDao;
+ }
- //set ResourceToolContentHandler as null to avoid copy file node in repository again.
- toolContentObj = Resource.newInstance(toolContentObj, toolContentId, null);
- toolContentObj.setToolContentHandler(null);
- toolContentObj.setOfflineFileList(null);
- toolContentObj.setOnlineFileList(null);
- toolContentObj.setMiniViewNumberStr(null);
- try {
- exportContentService.registerFileClassForExport(ResourceAttachment.class.getName(), "fileUuid", "fileVersionId");
- exportContentService.registerFileClassForExport(ResourceItem.class.getName(), "fileUuid", "fileVersionId");
- exportContentService.exportToolContent(toolContentId, toolContentObj, resourceToolContentHandler, rootPath);
- }
- catch (ExportToolContentException e) {
- throw new ToolException(e);
- }
- }
+ public void setResourceSessionDao(ResourceSessionDAO resourceSessionDao) {
+ this.resourceSessionDao = resourceSessionDao;
+ }
- public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion,
- String toVersion) throws ToolException {
+ public void setResourceToolContentHandler(ResourceToolContentHandler resourceToolContentHandler) {
+ this.resourceToolContentHandler = resourceToolContentHandler;
+ }
- try {
- exportContentService.registerFileClassForImport(ResourceAttachment.class.getName(), "fileUuid", "fileVersionId",
- "fileName", "fileType", null, null);
- exportContentService.registerFileClassForImport(ResourceItem.class.getName(), "fileUuid", "fileVersionId",
- "fileName", "fileType", null, "initialItem");
+ public void setResourceUserDao(ResourceUserDAO resourceUserDao) {
+ this.resourceUserDao = resourceUserDao;
+ }
- Object toolPOJO = exportContentService.importToolContent(toolContentPath, resourceToolContentHandler, fromVersion,
- toVersion);
- if (!(toolPOJO instanceof Resource)) {
- throw new ImportToolContentException("Import Share resources tool content failed. Deserialized object is "
- + toolPOJO);
- }
- Resource toolContentObj = (Resource) toolPOJO;
+ public void setToolService(ILamsToolService toolService) {
+ this.toolService = toolService;
+ }
- // reset it to new toolContentId
- toolContentObj.setContentId(toolContentId);
- ResourceUser user = resourceUserDao.getUserByUserIDAndContentID(new Long(newUserUid.longValue()), toolContentId);
- if (user == null) {
- user = new ResourceUser();
- UserDTO sysUser = ((User) userManagementService.findById(User.class, newUserUid)).getUserDTO();
- user.setFirstName(sysUser.getFirstName());
- user.setLastName(sysUser.getLastName());
- user.setLoginName(sysUser.getLogin());
- user.setUserId(new Long(newUserUid.longValue()));
- user.setResource(toolContentObj);
- }
- toolContentObj.setCreatedBy(user);
+ public ResourceItemVisitDAO getResourceItemVisitDao() {
+ return resourceItemVisitDao;
+ }
- //reset all resourceItem createBy user
- Set items = toolContentObj.getResourceItems();
- for (ResourceItem item : items) {
- item.setCreateBy(user);
- }
- resourceDao.saveObject(toolContentObj);
- }
- catch (ImportToolContentException e) {
- throw new ToolException(e);
- }
+ public void setResourceItemVisitDao(ResourceItemVisitDAO resourceItemVisitDao) {
+ this.resourceItemVisitDao = resourceItemVisitDao;
+ }
+
+ // *******************************************************************************
+ // ToolContentManager, ToolSessionManager methods
+ // *******************************************************************************
+
+ public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException {
+ Resource toolContentObj = resourceDao.getByContentId(toolContentId);
+ if (toolContentObj == null) {
+ try {
+ toolContentObj = getDefaultResource();
+ } catch (ResourceApplicationException e) {
+ throw new DataMissingException(e.getMessage());
+ }
}
+ if (toolContentObj == null) {
+ throw new DataMissingException("Unable to find default content for the share resources tool");
+ }
- /** Get the definitions for possible output for an activity, based on the toolContentId. These may be definitions that are always
- * available for the tool (e.g. number of marks for Multiple Choice) or a custom definition created for a particular activity
- * such as the answer to the third question contains the word Koala and hence the need for the toolContentId
- * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition
- */
- public SortedMap getToolOutputDefinitions(Long toolContentId) throws ToolException {
- return new TreeMap();
+ // set ResourceToolContentHandler as null to avoid copy file node in repository again.
+ toolContentObj = Resource.newInstance(toolContentObj, toolContentId, null);
+ toolContentObj.setToolContentHandler(null);
+ toolContentObj.setOfflineFileList(null);
+ toolContentObj.setOnlineFileList(null);
+ toolContentObj.setMiniViewNumberStr(null);
+ try {
+ exportContentService.registerFileClassForExport(ResourceAttachment.class.getName(), "fileUuid",
+ "fileVersionId");
+ exportContentService.registerFileClassForExport(ResourceItem.class.getName(), "fileUuid", "fileVersionId");
+ exportContentService.exportToolContent(toolContentId, toolContentObj, resourceToolContentHandler, rootPath);
+ } catch (ExportToolContentException e) {
+ throw new ToolException(e);
}
+ }
- public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException {
- if (toContentId == null) {
- throw new ToolException("Failed to create the SharedResourceFiles tool seession");
- }
+ public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion,
+ String toVersion) throws ToolException {
- Resource resource = null;
- if (fromContentId != null) {
- resource = resourceDao.getByContentId(fromContentId);
- }
- if (resource == null) {
- try {
- resource = getDefaultResource();
- }
- catch (ResourceApplicationException e) {
- throw new ToolException(e);
- }
- }
+ try {
+ exportContentService.registerFileClassForImport(ResourceAttachment.class.getName(), "fileUuid",
+ "fileVersionId", "fileName", "fileType", null, null);
+ exportContentService.registerFileClassForImport(ResourceItem.class.getName(), "fileUuid", "fileVersionId",
+ "fileName", "fileType", null, "initialItem");
- Resource toContent = Resource.newInstance(resource, toContentId, resourceToolContentHandler);
- resourceDao.saveObject(toContent);
+ Object toolPOJO = exportContentService.importToolContent(toolContentPath, resourceToolContentHandler,
+ fromVersion, toVersion);
+ if (!(toolPOJO instanceof Resource)) {
+ throw new ImportToolContentException(
+ "Import Share resources tool content failed. Deserialized object is " + toolPOJO);
+ }
+ Resource toolContentObj = (Resource) toolPOJO;
- //save resource items as well
- Set items = toContent.getResourceItems();
- if (items != null) {
- Iterator iter = items.iterator();
- while (iter.hasNext()) {
- ResourceItem item = (ResourceItem) iter.next();
- // createRootTopic(toContent.getUid(),null,msg);
- }
- }
- }
+ // reset it to new toolContentId
+ toolContentObj.setContentId(toolContentId);
+ ResourceUser user = resourceUserDao.getUserByUserIDAndContentID(new Long(newUserUid.longValue()),
+ toolContentId);
+ if (user == null) {
+ user = new ResourceUser();
+ UserDTO sysUser = ((User) userManagementService.findById(User.class, newUserUid)).getUserDTO();
+ user.setFirstName(sysUser.getFirstName());
+ user.setLastName(sysUser.getLastName());
+ user.setLoginName(sysUser.getLogin());
+ user.setUserId(new Long(newUserUid.longValue()));
+ user.setResource(toolContentObj);
+ }
+ toolContentObj.setCreatedBy(user);
- public void setAsDefineLater(Long toolContentId, boolean value) throws DataMissingException, ToolException {
- Resource resource = resourceDao.getByContentId(toolContentId);
- if (resource == null) {
- throw new ToolException("No found tool content by given content ID:" + toolContentId);
- }
- resource.setDefineLater(value);
+ // reset all resourceItem createBy user
+ Set items = toolContentObj.getResourceItems();
+ for (ResourceItem item : items) {
+ item.setCreateBy(user);
+ }
+ resourceDao.saveObject(toolContentObj);
+ } catch (ImportToolContentException e) {
+ throw new ToolException(e);
}
+ }
- public void setAsRunOffline(Long toolContentId, boolean value) throws DataMissingException, ToolException {
- Resource resource = resourceDao.getByContentId(toolContentId);
- if (resource == null) {
- throw new ToolException("No found tool content by given content ID:" + toolContentId);
- }
- resource.setRunOffline(value);
- }
+ /**
+ * Get the definitions for possible output for an activity, based on the toolContentId. These may be definitions
+ * that are always available for the tool (e.g. number of marks for Multiple Choice) or a custom definition created
+ * for a particular activity such as the answer to the third question contains the word Koala and hence the need for
+ * the toolContentId
+ *
+ * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition
+ */
+ public SortedMap getToolOutputDefinitions(Long toolContentId) throws ToolException {
+ return new TreeMap();
+ }
- public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, ToolException {
- Resource resource = resourceDao.getByContentId(toolContentId);
- if (removeSessionData) {
- List list = resourceSessionDao.getByContentId(toolContentId);
- Iterator iter = list.iterator();
- while (iter.hasNext()) {
- ResourceSession session = (ResourceSession) iter.next();
- resourceSessionDao.delete(session);
- }
- }
- resourceDao.delete(resource);
+ public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException {
+ if (toContentId == null) {
+ throw new ToolException("Failed to create the SharedResourceFiles tool seession");
}
- public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException {
- ResourceSession session = new ResourceSession();
- session.setSessionId(toolSessionId);
- session.setSessionName(toolSessionName);
- Resource resource = resourceDao.getByContentId(toolContentId);
- session.setResource(resource);
- resourceSessionDao.saveObject(session);
+ Resource resource = null;
+ if (fromContentId != null) {
+ resource = resourceDao.getByContentId(fromContentId);
}
+ if (resource == null) {
+ try {
+ resource = getDefaultResource();
+ } catch (ResourceApplicationException e) {
+ throw new ToolException(e);
+ }
+ }
- public String leaveToolSession(Long toolSessionId, Long learnerId) throws DataMissingException, ToolException {
- if (toolSessionId == null) {
- ResourceServiceImpl.log.error("Fail to leave tool Session based on null tool session id.");
- throw new ToolException("Fail to remove tool Session based on null tool session id.");
- }
- if (learnerId == null) {
- ResourceServiceImpl.log.error("Fail to leave tool Session based on null learner.");
- throw new ToolException("Fail to remove tool Session based on null learner.");
- }
+ Resource toContent = Resource.newInstance(resource, toContentId, resourceToolContentHandler);
+ resourceDao.saveObject(toContent);
- ResourceSession session = resourceSessionDao.getSessionBySessionId(toolSessionId);
- if (session != null) {
- session.setStatus(ResourceConstants.COMPLETED);
- resourceSessionDao.saveObject(session);
- }
- else {
- ResourceServiceImpl.log.error("Fail to leave tool Session.Could not find shared resources "
- + "session by given session id: " + toolSessionId);
- throw new DataMissingException("Fail to leave tool Session."
- + "Could not find shared resource session by given session id: " + toolSessionId);
- }
- return learnerService.completeToolSession(toolSessionId, learnerId);
+ // save resource items as well
+ Set items = toContent.getResourceItems();
+ if (items != null) {
+ Iterator iter = items.iterator();
+ while (iter.hasNext()) {
+ ResourceItem item = (ResourceItem) iter.next();
+ // createRootTopic(toContent.getUid(),null,msg);
+ }
}
+ }
- public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException {
- return null;
+ public void setAsDefineLater(Long toolContentId, boolean value) throws DataMissingException, ToolException {
+ Resource resource = resourceDao.getByContentId(toolContentId);
+ if (resource == null) {
+ throw new ToolException("No found tool content by given content ID:" + toolContentId);
}
+ resource.setDefineLater(value);
+ }
- public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, ToolException {
- return null;
+ public void setAsRunOffline(Long toolContentId, boolean value) throws DataMissingException, ToolException {
+ Resource resource = resourceDao.getByContentId(toolContentId);
+ if (resource == null) {
+ throw new ToolException("No found tool content by given content ID:" + toolContentId);
}
+ resource.setRunOffline(value);
+ }
- public void removeToolSession(Long toolSessionId) throws DataMissingException, ToolException {
- resourceSessionDao.deleteBySessionId(toolSessionId);
+ public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException,
+ ToolException {
+ Resource resource = resourceDao.getByContentId(toolContentId);
+ if (removeSessionData) {
+ List list = resourceSessionDao.getByContentId(toolContentId);
+ Iterator iter = list.iterator();
+ while (iter.hasNext()) {
+ ResourceSession session = (ResourceSession) iter.next();
+ resourceSessionDao.delete(session);
+ }
}
+ resourceDao.delete(resource);
+ }
- /**
- * Get the tool output for the given tool output names.
- * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.util.List, java.lang.Long, java.lang.Long)
- */
- public SortedMap getToolOutput(List names, Long toolSessionId, Long learnerId) {
- return new TreeMap();
+ public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException {
+ ResourceSession session = new ResourceSession();
+ session.setSessionId(toolSessionId);
+ session.setSessionName(toolSessionName);
+ Resource resource = resourceDao.getByContentId(toolContentId);
+ session.setResource(resource);
+ resourceSessionDao.saveObject(session);
+ }
+
+ public String leaveToolSession(Long toolSessionId, Long learnerId) throws DataMissingException, ToolException {
+ if (toolSessionId == null) {
+ ResourceServiceImpl.log.error("Fail to leave tool Session based on null tool session id.");
+ throw new ToolException("Fail to remove tool Session based on null tool session id.");
}
+ if (learnerId == null) {
+ ResourceServiceImpl.log.error("Fail to leave tool Session based on null learner.");
+ throw new ToolException("Fail to remove tool Session based on null learner.");
+ }
- /**
- * Get the tool output for the given tool output name.
- * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.lang.String, java.lang.Long, java.lang.Long)
- */
- public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) {
- return null;
+ ResourceSession session = resourceSessionDao.getSessionBySessionId(toolSessionId);
+ if (session != null) {
+ session.setStatus(ResourceConstants.COMPLETED);
+ resourceSessionDao.saveObject(session);
+ } else {
+ ResourceServiceImpl.log.error("Fail to leave tool Session.Could not find shared resources "
+ + "session by given session id: " + toolSessionId);
+ throw new DataMissingException("Fail to leave tool Session."
+ + "Could not find shared resource session by given session id: " + toolSessionId);
}
+ return learnerService.completeToolSession(toolSessionId, learnerId);
+ }
- /* ===============Methods implemented from ToolContentImport102Manager =============== */
+ public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException {
+ return null;
+ }
- /**
- * Import the data for a 1.0.2 Noticeboard or HTMLNoticeboard
- */
- public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) {
- Date now = new Date();
- Resource toolContentObj = new Resource();
+ public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException,
+ ToolException {
+ return null;
+ }
- try {
- toolContentObj.setTitle((String) importValues.get(ToolContentImport102Manager.CONTENT_TITLE));
- toolContentObj.setContentId(toolContentId);
- toolContentObj.setContentInUse(Boolean.FALSE);
- toolContentObj.setCreated(now);
- toolContentObj.setDefineLater(Boolean.FALSE);
- toolContentObj.setInstructions(WebUtil.convertNewlines((String) importValues
- .get(ToolContentImport102Manager.CONTENT_BODY)));
- toolContentObj.setOfflineInstructions(null);
- toolContentObj.setOnlineInstructions(null);
- toolContentObj.setRunOffline(Boolean.FALSE);
- toolContentObj.setUpdated(now);
- toolContentObj.setReflectOnActivity(Boolean.FALSE);
- toolContentObj.setReflectInstructions(null);
+ public void removeToolSession(Long toolSessionId) throws DataMissingException, ToolException {
+ resourceSessionDao.deleteBySessionId(toolSessionId);
+ }
- toolContentObj.setRunAuto(Boolean.FALSE);
- Boolean bool = WDDXProcessor.convertToBoolean(importValues,
- ToolContentImport102Manager.CONTENT_URL_RUNTIME_LEARNER_SUBMIT_FILE);
- toolContentObj.setAllowAddFiles(bool != null ? bool : Boolean.TRUE);
- bool = WDDXProcessor.convertToBoolean(importValues,
- ToolContentImport102Manager.CONTENT_URL_RUNTIME_LEARNER_SUBMIT_URL);
- toolContentObj.setAllowAddUrls(bool != null ? bool : Boolean.TRUE);
- Integer minToComplete = WDDXProcessor.convertToInteger(importValues,
- ToolContentImport102Manager.CONTENT_URL_MIN_NUMBER_COMPLETE);
- toolContentObj.setMiniViewResourceNumber(minToComplete != null ? minToComplete.intValue() : 0);
- bool = WDDXProcessor.convertToBoolean(importValues,
- ToolContentImport102Manager.CONTENT_URL_RUNTIME_LEARNER_SUBMIT_URL);
- toolContentObj.setLockWhenFinished(Boolean.FALSE);
- toolContentObj.setRunAuto(Boolean.FALSE);
+ /**
+ * Get the tool output for the given tool output names.
+ *
+ * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.util.List, java.lang.Long,
+ * java.lang.Long)
+ */
+ public SortedMap getToolOutput(List names, Long toolSessionId, Long learnerId) {
+ return new TreeMap();
+ }
- // leave as empty, no need to set them to anything.
- //toolContentObj.setAttachments(attachments);
+ /**
+ * Get the tool output for the given tool output name.
+ *
+ * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.lang.String, java.lang.Long,
+ * java.lang.Long)
+ */
+ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) {
+ return null;
+ }
- /* unused entries from 1.0.2
- [directoryName=] no equivalent in 2.0
- [runtimeSubmissionStaffFile=true] no equivalent in 2.0
- [contentShowUser=false] no equivalent in 2.0
- [isHTML=false] no equivalent in 2.0
- [showbuttons=false] no equivalent in 2.0
- [isReusable=false] not used in 1.0.2 (would be lock when finished)
- */
- ResourceUser ruser = new ResourceUser();
- ruser.setUserId(new Long(user.getUserID().longValue()));
- ruser.setFirstName(user.getFirstName());
- ruser.setLastName(user.getLastName());
- ruser.setLoginName(user.getLogin());
- createUser(ruser);
- toolContentObj.setCreatedBy(ruser);
+ /* ===============Methods implemented from ToolContentImport102Manager =============== */
- // Resource Items. They are ordered on the screen by create date so they need to be saved in the right order.
- // So read them all in first, then go through and assign the dates in the correct order and then save.
- Vector urls = (Vector) importValues.get(ToolContentImport102Manager.CONTENT_URL_URLS);
- SortedMap items = new TreeMap();
- if (urls != null) {
- Iterator iter = urls.iterator();
- while (iter.hasNext()) {
- Hashtable urlMap = (Hashtable) iter.next();
- Integer itemOrder = WDDXProcessor.convertToInteger(urlMap,
- ToolContentImport102Manager.CONTENT_URL_URL_VIEW_ORDER);
- ResourceItem item = new ResourceItem();
- item.setTitle((String) urlMap.get(ToolContentImport102Manager.CONTENT_TITLE));
- item.setCreateBy(ruser);
- item.setCreateByAuthor(true);
- item.setHide(false);
+ /**
+ * Import the data for a 1.0.2 Noticeboard or HTMLNoticeboard
+ */
+ public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) {
+ Date now = new Date();
+ Resource toolContentObj = new Resource();
- Vector instructions = (Vector) urlMap.get(ToolContentImport102Manager.CONTENT_URL_URL_INSTRUCTION_ARRAY);
- if (instructions != null && instructions.size() > 0) {
- item.setItemInstructions(new HashSet());
- Iterator insIter = instructions.iterator();
- while (insIter.hasNext()) {
- item.getItemInstructions().add(createInstruction((Hashtable) insIter.next()));
- }
- }
+ try {
+ toolContentObj.setTitle((String) importValues.get(ToolContentImport102Manager.CONTENT_TITLE));
+ toolContentObj.setContentId(toolContentId);
+ toolContentObj.setContentInUse(Boolean.FALSE);
+ toolContentObj.setCreated(now);
+ toolContentObj.setDefineLater(Boolean.FALSE);
+ toolContentObj.setInstructions(WebUtil.convertNewlines((String) importValues
+ .get(ToolContentImport102Manager.CONTENT_BODY)));
+ toolContentObj.setOfflineInstructions(null);
+ toolContentObj.setOnlineInstructions(null);
+ toolContentObj.setRunOffline(Boolean.FALSE);
+ toolContentObj.setUpdated(now);
+ toolContentObj.setReflectOnActivity(Boolean.FALSE);
+ toolContentObj.setReflectInstructions(null);
- String resourceType = (String) urlMap.get(ToolContentImport102Manager.CONTENT_URL_URL_TYPE);
- if (ToolContentImport102Manager.URL_RESOURCE_TYPE_URL.equals(resourceType)) {
- item.setType(ResourceConstants.RESOURCE_TYPE_URL);
- item.setUrl((String) urlMap.get(ToolContentImport102Manager.CONTENT_URL_URL_URL));
- item.setOpenUrlNewWindow(false);
- }
- else if (ToolContentImport102Manager.URL_RESOURCE_TYPE_WEBSITE.equals(resourceType)) {
- item.setType(ResourceConstants.RESOURCE_TYPE_WEBSITE);
- }
- else if (ToolContentImport102Manager.URL_RESOURCE_TYPE_FILE.equals(resourceType)) {
- item.setType(ResourceConstants.RESOURCE_TYPE_FILE);
- }
- else {
- throw new ToolException("Invalid shared resources type. Type was " + resourceType);
- }
+ toolContentObj.setRunAuto(Boolean.FALSE);
+ Boolean bool = WDDXProcessor.convertToBoolean(importValues,
+ ToolContentImport102Manager.CONTENT_URL_RUNTIME_LEARNER_SUBMIT_FILE);
+ toolContentObj.setAllowAddFiles(bool != null ? bool : Boolean.TRUE);
+ bool = WDDXProcessor.convertToBoolean(importValues,
+ ToolContentImport102Manager.CONTENT_URL_RUNTIME_LEARNER_SUBMIT_URL);
+ toolContentObj.setAllowAddUrls(bool != null ? bool : Boolean.TRUE);
+ Integer minToComplete = WDDXProcessor.convertToInteger(importValues,
+ ToolContentImport102Manager.CONTENT_URL_MIN_NUMBER_COMPLETE);
+ toolContentObj.setMiniViewResourceNumber(minToComplete != null ? minToComplete.intValue() : 0);
+ bool = WDDXProcessor.convertToBoolean(importValues,
+ ToolContentImport102Manager.CONTENT_URL_RUNTIME_LEARNER_SUBMIT_URL);
+ toolContentObj.setLockWhenFinished(Boolean.FALSE);
+ toolContentObj.setRunAuto(Boolean.FALSE);
- items.put(itemOrder, item);
- }
- }
+ // leave as empty, no need to set them to anything.
+ // toolContentObj.setAttachments(attachments);
- Iterator iter = items.values().iterator();
- Date itemDate = null;
- while (iter.hasNext()) {
- if (itemDate != null) {
- try {
- Thread.sleep(1000);
- }
- catch (Exception e) {
- }
- }
- itemDate = new Date();
+ /*
+ * unused entries from 1.0.2 [directoryName=] no equivalent in 2.0 [runtimeSubmissionStaffFile=true] no
+ * equivalent in 2.0 [contentShowUser=false] no equivalent in 2.0 [isHTML=false] no equivalent in 2.0
+ * [showbuttons=false] no equivalent in 2.0 [isReusable=false] not used in 1.0.2 (would be lock when
+ * finished)
+ */
+ ResourceUser ruser = new ResourceUser();
+ ruser.setUserId(new Long(user.getUserID().longValue()));
+ ruser.setFirstName(user.getFirstName());
+ ruser.setLastName(user.getLastName());
+ ruser.setLoginName(user.getLogin());
+ createUser(ruser);
+ toolContentObj.setCreatedBy(ruser);
- ResourceItem item = (ResourceItem) iter.next();
- item.setCreateDate(itemDate);
- toolContentObj.getResourceItems().add(item);
+ // Resource Items. They are ordered on the screen by create date so they need to be saved in the right
+ // order.
+ // So read them all in first, then go through and assign the dates in the correct order and then save.
+ Vector urls = (Vector) importValues.get(ToolContentImport102Manager.CONTENT_URL_URLS);
+ SortedMap items = new TreeMap();
+ if (urls != null) {
+ Iterator iter = urls.iterator();
+ while (iter.hasNext()) {
+ Hashtable urlMap = (Hashtable) iter.next();
+ Integer itemOrder = WDDXProcessor.convertToInteger(urlMap,
+ ToolContentImport102Manager.CONTENT_URL_URL_VIEW_ORDER);
+ ResourceItem item = new ResourceItem();
+ item.setTitle((String) urlMap.get(ToolContentImport102Manager.CONTENT_TITLE));
+ item.setCreateBy(ruser);
+ item.setCreateByAuthor(true);
+ item.setHide(false);
+
+ Vector instructions = (Vector) urlMap
+ .get(ToolContentImport102Manager.CONTENT_URL_URL_INSTRUCTION_ARRAY);
+ if (instructions != null && instructions.size() > 0) {
+ item.setItemInstructions(new HashSet());
+ Iterator insIter = instructions.iterator();
+ while (insIter.hasNext()) {
+ item.getItemInstructions().add(createInstruction((Hashtable) insIter.next()));
}
+ }
+ String resourceType = (String) urlMap.get(ToolContentImport102Manager.CONTENT_URL_URL_TYPE);
+ if (ToolContentImport102Manager.URL_RESOURCE_TYPE_URL.equals(resourceType)) {
+ item.setType(ResourceConstants.RESOURCE_TYPE_URL);
+ item.setUrl((String) urlMap.get(ToolContentImport102Manager.CONTENT_URL_URL_URL));
+ item.setOpenUrlNewWindow(false);
+ } else if (ToolContentImport102Manager.URL_RESOURCE_TYPE_WEBSITE.equals(resourceType)) {
+ item.setType(ResourceConstants.RESOURCE_TYPE_WEBSITE);
+ } else if (ToolContentImport102Manager.URL_RESOURCE_TYPE_FILE.equals(resourceType)) {
+ item.setType(ResourceConstants.RESOURCE_TYPE_FILE);
+ } else {
+ throw new ToolException("Invalid shared resources type. Type was " + resourceType);
+ }
+
+ items.put(itemOrder, item);
}
- catch (WDDXProcessorConversionException e) {
- ResourceServiceImpl.log.error("Unable to content for activity " + toolContentObj.getTitle()
- + "properly due to a WDDXProcessorConversionException.", e);
- throw new ToolException("Invalid import data format for activity " + toolContentObj.getTitle()
- + "- WDDX caused an exception. Some data from the design will have been lost. See log for more details.");
+ }
+
+ Iterator iter = items.values().iterator();
+ Date itemDate = null;
+ while (iter.hasNext()) {
+ if (itemDate != null) {
+ try {
+ Thread.sleep(1000);
+ } catch (Exception e) {
+ }
}
+ itemDate = new Date();
- resourceDao.saveObject(toolContentObj);
+ ResourceItem item = (ResourceItem) iter.next();
+ item.setCreateDate(itemDate);
+ toolContentObj.getResourceItems().add(item);
+ }
+ } catch (WDDXProcessorConversionException e) {
+ ResourceServiceImpl.log.error("Unable to content for activity " + toolContentObj.getTitle()
+ + "properly due to a WDDXProcessorConversionException.", e);
+ throw new ToolException(
+ "Invalid import data format for activity "
+ + toolContentObj.getTitle()
+ + "- WDDX caused an exception. Some data from the design will have been lost. See log for more details.");
}
- private ResourceItemInstruction createInstruction(Hashtable instructionEntry) throws WDDXProcessorConversionException {
+ resourceDao.saveObject(toolContentObj);
- Integer instructionOrder = WDDXProcessor.convertToInteger(instructionEntry,
- ToolContentImport102Manager.CONTENT_URL_URL_VIEW_ORDER);
+ }
- // the description column in 1.0.2 was longer than 255 chars, so truncate.
- String instructionText = (String) instructionEntry.get(ToolContentImport102Manager.CONTENT_URL_INSTRUCTION);
- if (instructionText != null && instructionText.length() > 255) {
- if (ResourceServiceImpl.log.isDebugEnabled()) {
- ResourceServiceImpl.log.debug("1.0.2 Import truncating Item Instruction to 255 characters. Original text was\'"
- + instructionText + "\'");
- }
- instructionText = instructionText.substring(0, 255);
- }
+ private ResourceItemInstruction createInstruction(Hashtable instructionEntry)
+ throws WDDXProcessorConversionException {
- ResourceItemInstruction instruction = new ResourceItemInstruction();
- instruction.setDescription(instructionText);
- instruction.setSequenceId(instructionOrder);
+ Integer instructionOrder = WDDXProcessor.convertToInteger(instructionEntry,
+ ToolContentImport102Manager.CONTENT_URL_URL_VIEW_ORDER);
- return instruction;
+ // the description column in 1.0.2 was longer than 255 chars, so truncate.
+ String instructionText = (String) instructionEntry.get(ToolContentImport102Manager.CONTENT_URL_INSTRUCTION);
+ if (instructionText != null && instructionText.length() > 255) {
+ if (ResourceServiceImpl.log.isDebugEnabled()) {
+ ResourceServiceImpl.log
+ .debug("1.0.2 Import truncating Item Instruction to 255 characters. Original text was\'"
+ + instructionText + "\'");
+ }
+ instructionText = instructionText.substring(0, 255);
}
- /** Set the description, throws away the title value as this is not supported in 2.0 */
- public void setReflectiveData(Long toolContentId, String title, String description) throws ToolException,
- DataMissingException {
+ ResourceItemInstruction instruction = new ResourceItemInstruction();
+ instruction.setDescription(instructionText);
+ instruction.setSequenceId(instructionOrder);
- Resource toolContentObj = getResourceByContentId(toolContentId);
- if (toolContentObj == null) {
- throw new DataMissingException("Unable to set reflective data titled " + title + " on activity toolContentId "
- + toolContentId + " as the tool content does not exist.");
- }
+ return instruction;
+ }
- toolContentObj.setReflectOnActivity(Boolean.TRUE);
- toolContentObj.setReflectInstructions(description);
+ /** Set the description, throws away the title value as this is not supported in 2.0 */
+ public void setReflectiveData(Long toolContentId, String title, String description) throws ToolException,
+ DataMissingException {
+
+ Resource toolContentObj = getResourceByContentId(toolContentId);
+ if (toolContentObj == null) {
+ throw new DataMissingException("Unable to set reflective data titled " + title
+ + " on activity toolContentId " + toolContentId + " as the tool content does not exist.");
}
- /* =================================================================================== */
+ toolContentObj.setReflectOnActivity(Boolean.TRUE);
+ toolContentObj.setReflectInstructions(description);
+ }
- public IExportToolContentService getExportContentService() {
- return exportContentService;
- }
+ /* =================================================================================== */
- public void setExportContentService(IExportToolContentService exportContentService) {
- this.exportContentService = exportContentService;
- }
+ public IExportToolContentService getExportContentService() {
+ return exportContentService;
+ }
- public IUserManagementService getUserManagementService() {
- return userManagementService;
- }
+ public void setExportContentService(IExportToolContentService exportContentService) {
+ this.exportContentService = exportContentService;
+ }
- public void setUserManagementService(IUserManagementService userManagementService) {
- this.userManagementService = userManagementService;
- }
+ public IUserManagementService getUserManagementService() {
+ return userManagementService;
+ }
- public ICoreNotebookService getCoreNotebookService() {
- return coreNotebookService;
- }
+ public void setUserManagementService(IUserManagementService userManagementService) {
+ this.userManagementService = userManagementService;
+ }
- public void setCoreNotebookService(ICoreNotebookService coreNotebookService) {
- this.coreNotebookService = coreNotebookService;
- }
+ public ICoreNotebookService getCoreNotebookService() {
+ return coreNotebookService;
+ }
- public IEventNotificationService getEventNotificationService() {
- return eventNotificationService;
- }
+ public void setCoreNotebookService(ICoreNotebookService coreNotebookService) {
+ this.coreNotebookService = coreNotebookService;
+ }
- public void setEventNotificationService(IEventNotificationService eventNotificationService) {
- this.eventNotificationService = eventNotificationService;
- }
+ public IEventNotificationService getEventNotificationService() {
+ return eventNotificationService;
+ }
- public String getLocalisedMessage(String key, Object[] args) {
- return messageService.getMessage(key, args);
- }
+ public void setEventNotificationService(IEventNotificationService eventNotificationService) {
+ this.eventNotificationService = eventNotificationService;
+ }
+ public String getLocalisedMessage(String key, Object[] args) {
+ return messageService.getMessage(key, args);
+ }
+
+ public ILessonService getLessonService() {
+ return lessonService;
+ }
+
+ public void setLessonService(ILessonService lessonService) {
+ this.lessonService = lessonService;
+ }
+
+ /**
+ * Finds out which lesson the given tool content belongs to and returns its monitoring users.
+ *
+ * @param sessionId
+ * tool session ID
+ * @return list of teachers that monitor the lesson which contains the tool with given session ID
+ */
+ public List getMonitorsByToolSessionId(Long sessionId) {
+ return getLessonService().getMonitorsByToolSessionId(sessionId);
+ }
}
\ No newline at end of file
Index: lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/web/action/LearningAction.java
===================================================================
diff -u -r05ab55ef4acdc0c374af7405c58fb0e0fe8eb6b7 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/web/action/LearningAction.java (.../LearningAction.java) (revision 05ab55ef4acdc0c374af7405c58fb0e0fe8eb6b7)
+++ lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/web/action/LearningAction.java (.../LearningAction.java) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -48,6 +48,7 @@
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
+import org.lamsfoundation.lams.events.DeliveryMethodMail;
import org.lamsfoundation.lams.notebook.model.NotebookEntry;
import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants;
import org.lamsfoundation.lams.tool.ToolAccessMode;
@@ -62,6 +63,7 @@
import org.lamsfoundation.lams.tool.rsrc.util.ResourceItemComparator;
import org.lamsfoundation.lams.tool.rsrc.web.form.ReflectionForm;
import org.lamsfoundation.lams.tool.rsrc.web.form.ResourceItemForm;
+import org.lamsfoundation.lams.usermanagement.User;
import org.lamsfoundation.lams.usermanagement.dto.UserDTO;
import org.lamsfoundation.lams.util.FileUtil;
import org.lamsfoundation.lams.util.FileValidatorUtil;
@@ -80,609 +82,625 @@
*/
public class LearningAction extends Action {
- private static Logger log = Logger.getLogger(LearningAction.class);
+ private static Logger log = Logger.getLogger(LearningAction.class);
- @Override
- public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
- throws IOException, ServletException {
+ @Override
+ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) throws IOException, ServletException {
- String param = mapping.getParameter();
- //-----------------------Resource Learner function ---------------------------
- if (param.equals("start")) {
- return start(mapping, form, request, response);
- }
- if (param.equals("complete")) {
- return complete(mapping, form, request, response);
- }
+ String param = mapping.getParameter();
+ // -----------------------Resource Learner function ---------------------------
+ if (param.equals("start")) {
+ return start(mapping, form, request, response);
+ }
+ if (param.equals("complete")) {
+ return complete(mapping, form, request, response);
+ }
- if (param.equals("finish")) {
- return finish(mapping, form, request, response);
- }
- if (param.equals("addfile")) {
- return addItem(mapping, form, request, response);
- }
- if (param.equals("addurl")) {
- return addItem(mapping, form, request, response);
- }
- if (param.equals("saveOrUpdateItem")) {
- return saveOrUpdateItem(mapping, form, request, response);
- }
-
- //================ Reflection =======================
- if (param.equals("newReflection")) {
- return newReflection(mapping, form, request, response);
- }
- if (param.equals("submitReflection")) {
- return submitReflection(mapping, form, request, response);
- }
-
- return mapping.findForward(ResourceConstants.ERROR);
+ if (param.equals("finish")) {
+ return finish(mapping, form, request, response);
}
+ if (param.equals("addfile")) {
+ return addItem(mapping, form, request, response);
+ }
+ if (param.equals("addurl")) {
+ return addItem(mapping, form, request, response);
+ }
+ if (param.equals("saveOrUpdateItem")) {
+ return saveOrUpdateItem(mapping, form, request, response);
+ }
- /**
- * Initial page for add resource item (single file or URL).
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- private ActionForward addItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
- ResourceItemForm itemForm = (ResourceItemForm) form;
- itemForm.setMode(WebUtil.readStrParam(request, AttributeNames.ATTR_MODE));
- itemForm.setSessionMapID(WebUtil.readStrParam(request, ResourceConstants.ATTR_SESSION_MAP_ID));
- return mapping.findForward(ResourceConstants.SUCCESS);
+ // ================ Reflection =======================
+ if (param.equals("newReflection")) {
+ return newReflection(mapping, form, request, response);
}
+ if (param.equals("submitReflection")) {
+ return submitReflection(mapping, form, request, response);
+ }
- /**
- * Read resource data from database and put them into HttpSession. It will redirect to init.do directly after this
- * method run successfully.
- *
- * This method will avoid read database again and lost un-saved resouce item lost when user "refresh page",
- *
- */
- private ActionForward start(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
+ return mapping.findForward(ResourceConstants.ERROR);
+ }
- //initial Session Map
- SessionMap sessionMap = new SessionMap();
- request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap);
+ /**
+ * Initial page for add resource item (single file or URL).
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ private ActionForward addItem(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ ResourceItemForm itemForm = (ResourceItemForm) form;
+ itemForm.setMode(WebUtil.readStrParam(request, AttributeNames.ATTR_MODE));
+ itemForm.setSessionMapID(WebUtil.readStrParam(request, ResourceConstants.ATTR_SESSION_MAP_ID));
+ return mapping.findForward(ResourceConstants.SUCCESS);
+ }
- //save toolContentID into HTTPSession
- ToolAccessMode mode = WebUtil.readToolAccessModeParam(request, AttributeNames.PARAM_MODE, true);
+ /**
+ * Read resource data from database and put them into HttpSession. It will redirect to init.do directly after this
+ * method run successfully.
+ *
+ * This method will avoid read database again and lost un-saved resouce item lost when user "refresh page",
+ *
+ */
+ private ActionForward start(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
- Long sessionId = new Long(request.getParameter(ResourceConstants.PARAM_TOOL_SESSION_ID));
+ // initial Session Map
+ SessionMap sessionMap = new SessionMap();
+ request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap);
- request.setAttribute(ResourceConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID());
- request.setAttribute(AttributeNames.ATTR_MODE, mode);
- request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID, sessionId);
+ // save toolContentID into HTTPSession
+ ToolAccessMode mode = WebUtil.readToolAccessModeParam(request, AttributeNames.PARAM_MODE, true);
- // get back the resource and item list and display them on page
- IResourceService service = getResourceService();
- ResourceUser resourceUser = null;
- if (mode != null && mode.isTeacher()) {
- // monitoring mode - user is specified in URL
- // resourceUser may be null if the user was force completed.
- resourceUser = getSpecifiedUser(service, sessionId, WebUtil
- .readIntParam(request, AttributeNames.PARAM_USER_ID, false));
- }
- else {
- resourceUser = getCurrentUser(service, sessionId);
- }
+ Long sessionId = new Long(request.getParameter(ResourceConstants.PARAM_TOOL_SESSION_ID));
- List items = null;
- Resource resource;
- items = service.getResourceItemsBySessionId(sessionId);
- resource = service.getResourceBySessionId(sessionId);
+ request.setAttribute(ResourceConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID());
+ request.setAttribute(AttributeNames.ATTR_MODE, mode);
+ request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID, sessionId);
- //check whehter finish lock is on/off
- boolean lock = resource.getLockWhenFinished() && resourceUser != null && resourceUser.isSessionFinished();
+ // get back the resource and item list and display them on page
+ IResourceService service = getResourceService();
+ ResourceUser resourceUser = null;
+ if (mode != null && mode.isTeacher()) {
+ // monitoring mode - user is specified in URL
+ // resourceUser may be null if the user was force completed.
+ resourceUser = getSpecifiedUser(service, sessionId, WebUtil.readIntParam(request,
+ AttributeNames.PARAM_USER_ID, false));
+ } else {
+ resourceUser = getCurrentUser(service, sessionId);
+ }
- //check whether there is only one resource item and run auto flag is true or not.
- boolean runAuto = false;
- int itemsNumber = 0;
- if (resource.getResourceItems() != null) {
- itemsNumber = resource.getResourceItems().size();
- if (resource.isRunAuto() && itemsNumber == 1) {
- ResourceItem item = (ResourceItem) resource.getResourceItems().iterator().next();
- //only visible item can be run auto.
- if (!item.isHide()) {
- runAuto = true;
- request.setAttribute(ResourceConstants.ATTR_RESOURCE_ITEM_UID, item.getUid());
- }
- }
- }
+ List items = null;
+ Resource resource;
+ items = service.getResourceItemsBySessionId(sessionId);
+ resource = service.getResourceBySessionId(sessionId);
- // get notebook entry
- String entryText = new String();
- if (resourceUser != null) {
- NotebookEntry notebookEntry = service.getEntry(sessionId, CoreNotebookConstants.NOTEBOOK_TOOL,
- ResourceConstants.TOOL_SIGNATURE, resourceUser.getUserId().intValue());
- if (notebookEntry != null) {
- entryText = notebookEntry.getEntry();
- }
+ // check whehter finish lock is on/off
+ boolean lock = resource.getLockWhenFinished() && resourceUser != null && resourceUser.isSessionFinished();
+
+ // check whether there is only one resource item and run auto flag is true or not.
+ boolean runAuto = false;
+ int itemsNumber = 0;
+ if (resource.getResourceItems() != null) {
+ itemsNumber = resource.getResourceItems().size();
+ if (resource.isRunAuto() && itemsNumber == 1) {
+ ResourceItem item = (ResourceItem) resource.getResourceItems().iterator().next();
+ // only visible item can be run auto.
+ if (!item.isHide()) {
+ runAuto = true;
+ request.setAttribute(ResourceConstants.ATTR_RESOURCE_ITEM_UID, item.getUid());
}
+ }
+ }
- //basic information
- sessionMap.put(ResourceConstants.ATTR_TITLE, resource.getTitle());
- sessionMap.put(ResourceConstants.ATTR_RESOURCE_INSTRUCTION, resource.getInstructions());
- sessionMap.put(ResourceConstants.ATTR_FINISH_LOCK, lock);
- sessionMap.put(ResourceConstants.ATTR_LOCK_ON_FINISH, resource.getLockWhenFinished());
- sessionMap.put(ResourceConstants.ATTR_USER_FINISHED, resourceUser != null && resourceUser.isSessionFinished());
+ // get notebook entry
+ String entryText = new String();
+ if (resourceUser != null) {
+ NotebookEntry notebookEntry = service.getEntry(sessionId, CoreNotebookConstants.NOTEBOOK_TOOL,
+ ResourceConstants.TOOL_SIGNATURE, resourceUser.getUserId().intValue());
+ if (notebookEntry != null) {
+ entryText = notebookEntry.getEntry();
+ }
+ }
- sessionMap.put(AttributeNames.PARAM_TOOL_SESSION_ID, sessionId);
- sessionMap.put(AttributeNames.ATTR_MODE, mode);
- //reflection information
- sessionMap.put(ResourceConstants.ATTR_REFLECTION_ON, resource.isReflectOnActivity());
- sessionMap.put(ResourceConstants.ATTR_REFLECTION_INSTRUCTION, resource.getReflectInstructions());
- sessionMap.put(ResourceConstants.ATTR_REFLECTION_ENTRY, entryText);
- sessionMap.put(ResourceConstants.ATTR_RUN_AUTO, new Boolean(runAuto));
+ // basic information
+ sessionMap.put(ResourceConstants.ATTR_TITLE, resource.getTitle());
+ sessionMap.put(ResourceConstants.ATTR_RESOURCE_INSTRUCTION, resource.getInstructions());
+ sessionMap.put(ResourceConstants.ATTR_FINISH_LOCK, lock);
+ sessionMap.put(ResourceConstants.ATTR_LOCK_ON_FINISH, resource.getLockWhenFinished());
+ sessionMap.put(ResourceConstants.ATTR_USER_FINISHED, resourceUser != null && resourceUser.isSessionFinished());
- //add define later support
- if (resource.isDefineLater()) {
- return mapping.findForward("defineLater");
- }
+ sessionMap.put(AttributeNames.PARAM_TOOL_SESSION_ID, sessionId);
+ sessionMap.put(AttributeNames.ATTR_MODE, mode);
+ // reflection information
+ sessionMap.put(ResourceConstants.ATTR_REFLECTION_ON, resource.isReflectOnActivity());
+ sessionMap.put(ResourceConstants.ATTR_REFLECTION_INSTRUCTION, resource.getReflectInstructions());
+ sessionMap.put(ResourceConstants.ATTR_REFLECTION_ENTRY, entryText);
+ sessionMap.put(ResourceConstants.ATTR_RUN_AUTO, new Boolean(runAuto));
- //set contentInUse flag to true!
- resource.setContentInUse(true);
- resource.setDefineLater(false);
- service.saveOrUpdateResource(resource);
+ // add define later support
+ if (resource.isDefineLater()) {
+ return mapping.findForward("defineLater");
+ }
- //add run offline support
- if (resource.getRunOffline()) {
- sessionMap.put(ResourceConstants.PARAM_RUN_OFFLINE, true);
- return mapping.findForward("runOffline");
- }
- else {
- sessionMap.put(ResourceConstants.PARAM_RUN_OFFLINE, false);
- }
+ // set contentInUse flag to true!
+ resource.setContentInUse(true);
+ resource.setDefineLater(false);
+ service.saveOrUpdateResource(resource);
- //init resource item list
- SortedSet resourceItemList = getResourceItemList(sessionMap);
- resourceItemList.clear();
- if (items != null) {
- //remove hidden items.
- for (ResourceItem item : items) {
- //becuase in webpage will use this login name. Here is just
- //initial it to avoid session close error in proxy object.
- if (item.getCreateBy() != null) {
- item.getCreateBy().getLoginName();
- }
- if (!item.isHide()) {
- resourceItemList.add(item);
- }
- }
- }
+ // add run offline support
+ if (resource.getRunOffline()) {
+ sessionMap.put(ResourceConstants.PARAM_RUN_OFFLINE, true);
+ return mapping.findForward("runOffline");
+ } else {
+ sessionMap.put(ResourceConstants.PARAM_RUN_OFFLINE, false);
+ }
- //set complete flag for display purpose
- if (resourceUser != null) {
- service.retrieveComplete(resourceItemList, resourceUser);
+ // init resource item list
+ SortedSet resourceItemList = getResourceItemList(sessionMap);
+ resourceItemList.clear();
+ if (items != null) {
+ // remove hidden items.
+ for (ResourceItem item : items) {
+ // becuase in webpage will use this login name. Here is just
+ // initial it to avoid session close error in proxy object.
+ if (item.getCreateBy() != null) {
+ item.getCreateBy().getLoginName();
}
- sessionMap.put(ResourceConstants.ATTR_RESOURCE, resource);
+ if (!item.isHide()) {
+ resourceItemList.add(item);
+ }
+ }
+ }
- return mapping.findForward(ResourceConstants.SUCCESS);
+ // set complete flag for display purpose
+ if (resourceUser != null) {
+ service.retrieveComplete(resourceItemList, resourceUser);
}
+ sessionMap.put(ResourceConstants.ATTR_RESOURCE, resource);
- /**
- * Mark resource item as complete status.
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- private ActionForward complete(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
- String mode = request.getParameter(AttributeNames.ATTR_MODE);
- String sessionMapID = request.getParameter(ResourceConstants.ATTR_SESSION_MAP_ID);
+ return mapping.findForward(ResourceConstants.SUCCESS);
+ }
- doComplete(request);
+ /**
+ * Mark resource item as complete status.
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ private ActionForward complete(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ String mode = request.getParameter(AttributeNames.ATTR_MODE);
+ String sessionMapID = request.getParameter(ResourceConstants.ATTR_SESSION_MAP_ID);
- request.setAttribute(AttributeNames.ATTR_MODE, mode);
- request.setAttribute(ResourceConstants.ATTR_SESSION_MAP_ID, sessionMapID);
- return mapping.findForward(ResourceConstants.SUCCESS);
- }
+ doComplete(request);
- /**
- * Finish learning session.
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- private ActionForward finish(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
+ request.setAttribute(AttributeNames.ATTR_MODE, mode);
+ request.setAttribute(ResourceConstants.ATTR_SESSION_MAP_ID, sessionMapID);
+ return mapping.findForward(ResourceConstants.SUCCESS);
+ }
- //get back SessionMap
- String sessionMapID = request.getParameter(ResourceConstants.ATTR_SESSION_MAP_ID);
- SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
+ /**
+ * Finish learning session.
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ private ActionForward finish(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
- //get mode and ToolSessionID from sessionMAP
- ToolAccessMode mode = (ToolAccessMode) sessionMap.get(AttributeNames.ATTR_MODE);
- Long sessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
+ // get back SessionMap
+ String sessionMapID = request.getParameter(ResourceConstants.ATTR_SESSION_MAP_ID);
+ SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
- //auto run mode, when use finish the only one resource item, mark it as complete then finish this activity as well.
- String resourceItemUid = request.getParameter(ResourceConstants.PARAM_RESOURCE_ITEM_UID);
- if (resourceItemUid != null) {
- doComplete(request);
- //NOTE:So far this flag is useless(31/08/2006).
- //set flag, then finish page can know redir target is parent(AUTO_RUN) or self(normal)
- request.setAttribute(ResourceConstants.ATTR_RUN_AUTO, true);
- }
- else {
- request.setAttribute(ResourceConstants.ATTR_RUN_AUTO, false);
- }
+ // get mode and ToolSessionID from sessionMAP
+ ToolAccessMode mode = (ToolAccessMode) sessionMap.get(AttributeNames.ATTR_MODE);
+ Long sessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
- if (!validateBeforeFinish(request, sessionMapID)) {
- return mapping.getInputForward();
- }
+ // auto run mode, when use finish the only one resource item, mark it as complete then finish this activity as
+ // well.
+ String resourceItemUid = request.getParameter(ResourceConstants.PARAM_RESOURCE_ITEM_UID);
+ if (resourceItemUid != null) {
+ doComplete(request);
+ // NOTE:So far this flag is useless(31/08/2006).
+ // set flag, then finish page can know redir target is parent(AUTO_RUN) or self(normal)
+ request.setAttribute(ResourceConstants.ATTR_RUN_AUTO, true);
+ } else {
+ request.setAttribute(ResourceConstants.ATTR_RUN_AUTO, false);
+ }
- IResourceService service = getResourceService();
- // get sessionId from HttpServletRequest
- String nextActivityUrl = null;
- try {
- HttpSession ss = SessionManager.getSession();
- UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
- Long userID = new Long(user.getUserID().longValue());
+ if (!validateBeforeFinish(request, sessionMapID)) {
+ return mapping.getInputForward();
+ }
- nextActivityUrl = service.finishToolSession(sessionId, userID);
- request.setAttribute(ResourceConstants.ATTR_NEXT_ACTIVITY_URL, nextActivityUrl);
- }
- catch (ResourceApplicationException e) {
- LearningAction.log.error("Failed get next activity url:" + e.getMessage());
- }
+ IResourceService service = getResourceService();
+ // get sessionId from HttpServletRequest
+ String nextActivityUrl = null;
+ try {
+ HttpSession ss = SessionManager.getSession();
+ UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
+ Long userID = new Long(user.getUserID().longValue());
- return mapping.findForward(ResourceConstants.SUCCESS);
+ nextActivityUrl = service.finishToolSession(sessionId, userID);
+ request.setAttribute(ResourceConstants.ATTR_NEXT_ACTIVITY_URL, nextActivityUrl);
+ } catch (ResourceApplicationException e) {
+ LearningAction.log.error("Failed get next activity url:" + e.getMessage());
}
- /**
- * Save file or url resource item into database.
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- private ActionForward saveOrUpdateItem(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
- //get back SessionMap
- String sessionMapID = request.getParameter(ResourceConstants.ATTR_SESSION_MAP_ID);
- SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
- request.setAttribute(ResourceConstants.ATTR_SESSION_MAP_ID, sessionMapID);
+ return mapping.findForward(ResourceConstants.SUCCESS);
+ }
- Long sessionId = (Long) sessionMap.get(ResourceConstants.ATTR_TOOL_SESSION_ID);
+ /**
+ * Save file or url resource item into database.
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ private ActionForward saveOrUpdateItem(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ // get back SessionMap
+ String sessionMapID = request.getParameter(ResourceConstants.ATTR_SESSION_MAP_ID);
+ SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
+ request.setAttribute(ResourceConstants.ATTR_SESSION_MAP_ID, sessionMapID);
- String mode = request.getParameter(AttributeNames.ATTR_MODE);
- ResourceItemForm itemForm = (ResourceItemForm) form;
- ActionErrors errors = validateResourceItem(itemForm);
+ Long sessionId = (Long) sessionMap.get(ResourceConstants.ATTR_TOOL_SESSION_ID);
- if (!errors.isEmpty()) {
- this.addErrors(request, errors);
- return findForward(itemForm.getItemType(), mapping);
- }
- short type = itemForm.getItemType();
+ String mode = request.getParameter(AttributeNames.ATTR_MODE);
+ ResourceItemForm itemForm = (ResourceItemForm) form;
+ ActionErrors errors = validateResourceItem(itemForm);
- //create a new ResourceItem
- ResourceItem item = new ResourceItem();
- IResourceService service = getResourceService();
- ResourceUser resourceUser = getCurrentUser(service, sessionId);
- item.setType(type);
- item.setTitle(itemForm.getTitle());
- item.setDescription(itemForm.getDescription());
- item.setCreateDate(new Timestamp(new Date().getTime()));
- item.setCreateByAuthor(false);
- item.setCreateBy(resourceUser);
+ if (!errors.isEmpty()) {
+ this.addErrors(request, errors);
+ return findForward(itemForm.getItemType(), mapping);
+ }
+ short type = itemForm.getItemType();
- //special attribute for URL or FILE
- if (type == ResourceConstants.RESOURCE_TYPE_FILE) {
- try {
- service.uploadResourceItemFile(item, itemForm.getFile());
- }
- catch (UploadResourceFileException e) {
- LearningAction.log.error("Failed upload Resource File " + e.toString());
- return mapping.findForward(ResourceConstants.ERROR);
- }
- }
- else if (type == ResourceConstants.RESOURCE_TYPE_URL) {
- item.setUrl(itemForm.getUrl());
- item.setOpenUrlNewWindow(itemForm.isOpenUrlNewWindow());
- }
- //save and update session
+ // create a new ResourceItem
+ ResourceItem item = new ResourceItem();
+ IResourceService service = getResourceService();
+ ResourceUser resourceUser = getCurrentUser(service, sessionId);
+ item.setType(type);
+ item.setTitle(itemForm.getTitle());
+ item.setDescription(itemForm.getDescription());
+ item.setCreateDate(new Timestamp(new Date().getTime()));
+ item.setCreateByAuthor(false);
+ item.setCreateBy(resourceUser);
- ResourceSession resSession = service.getResourceSessionBySessionId(sessionId);
- if (resSession == null) {
- LearningAction.log.error("Failed update ResourceSession by ID[" + sessionId + "]");
- return mapping.findForward(ResourceConstants.ERROR);
- }
- Set items = resSession.getResourceItems();
- if (items == null) {
- items = new HashSet();
- resSession.setResourceItems(items);
- }
- items.add(item);
- service.saveOrUpdateResourceSession(resSession);
+ // special attribute for URL or FILE
+ if (type == ResourceConstants.RESOURCE_TYPE_FILE) {
+ try {
+ service.uploadResourceItemFile(item, itemForm.getFile());
+ } catch (UploadResourceFileException e) {
+ LearningAction.log.error("Failed upload Resource File " + e.toString());
+ return mapping.findForward(ResourceConstants.ERROR);
+ }
+ } else if (type == ResourceConstants.RESOURCE_TYPE_URL) {
+ item.setUrl(itemForm.getUrl());
+ item.setOpenUrlNewWindow(itemForm.isOpenUrlNewWindow());
+ }
+ // save and update session
- //update session value
- SortedSet resourceItemList = getResourceItemList(sessionMap);
- resourceItemList.add(item);
+ ResourceSession resSession = service.getResourceSessionBySessionId(sessionId);
+ if (resSession == null) {
+ LearningAction.log.error("Failed update ResourceSession by ID[" + sessionId + "]");
+ return mapping.findForward(ResourceConstants.ERROR);
+ }
+ Set items = resSession.getResourceItems();
+ if (items == null) {
+ items = new HashSet();
+ resSession.setResourceItems(items);
+ }
+ items.add(item);
+ service.saveOrUpdateResourceSession(resSession);
- //URL or file upload
- request.setAttribute(ResourceConstants.ATTR_ADD_RESOURCE_TYPE, new Short(type));
- request.setAttribute(AttributeNames.ATTR_MODE, mode);
+ // update session value
+ SortedSet resourceItemList = getResourceItemList(sessionMap);
+ resourceItemList.add(item);
- Resource resource = resSession.getResource();
- if (resource.isNotifyTeachersOnAssigmentSumbit()
- && service.getEventNotificationService().eventExists(ResourceConstants.TOOL_SIGNATURE,
- ResourceConstants.EVENT_NAME_NOTIFY_TEACHERS_ON_ASSIGMENT_SUBMIT, resource.getContentId())) {
- String fullName = resourceUser.getLastName() + " " + resourceUser.getFirstName();
- service.getEventNotificationService().trigger(ResourceConstants.TOOL_SIGNATURE,
- ResourceConstants.EVENT_NAME_NOTIFY_TEACHERS_ON_ASSIGMENT_SUBMIT, resource.getContentId(),
- new Object[] { fullName });
+ // URL or file upload
+ request.setAttribute(ResourceConstants.ATTR_ADD_RESOURCE_TYPE, new Short(type));
+ request.setAttribute(AttributeNames.ATTR_MODE, mode);
+
+ Resource resource = resSession.getResource();
+ if (resource.isNotifyTeachersOnAssigmentSumbit()) {
+ List monitoringUsers = service.getMonitorsByToolSessionId(sessionId);
+ if (monitoringUsers != null && !monitoringUsers.isEmpty()) {
+ Long[] monitoringUsersIds = new Long[monitoringUsers.size()];
+ for (int i = 0; i < monitoringUsersIds.length; i++) {
+ monitoringUsersIds[i] = monitoringUsers.get(i).getUserId().longValue();
}
- return mapping.findForward(ResourceConstants.SUCCESS);
+ String fullName = resourceUser.getLastName() + " " + resourceUser.getFirstName();
+ service.getEventNotificationService().sendMessage(monitoringUsersIds, DeliveryMethodMail.getInstance(),
+ service.getLocalisedMessage("event.assigment.submit.subject", null),
+ service.getLocalisedMessage("event.assigment.submit.body", new Object[] { fullName }));
+ }
}
+ return mapping.findForward(ResourceConstants.SUCCESS);
+ }
- /**
- * Display empty reflection form.
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- private ActionForward newReflection(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
+ /**
+ * Display empty reflection form.
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ private ActionForward newReflection(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
- //get session value
- String sessionMapID = WebUtil.readStrParam(request, ResourceConstants.ATTR_SESSION_MAP_ID);
- if (!validateBeforeFinish(request, sessionMapID)) {
- return mapping.getInputForward();
- }
+ // get session value
+ String sessionMapID = WebUtil.readStrParam(request, ResourceConstants.ATTR_SESSION_MAP_ID);
+ if (!validateBeforeFinish(request, sessionMapID)) {
+ return mapping.getInputForward();
+ }
- ReflectionForm refForm = (ReflectionForm) form;
- HttpSession ss = SessionManager.getSession();
- UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
+ ReflectionForm refForm = (ReflectionForm) form;
+ HttpSession ss = SessionManager.getSession();
+ UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
- refForm.setUserID(user.getUserID());
- refForm.setSessionMapID(sessionMapID);
+ refForm.setUserID(user.getUserID());
+ refForm.setSessionMapID(sessionMapID);
- // get the existing reflection entry
- IResourceService submitFilesService = getResourceService();
+ // get the existing reflection entry
+ IResourceService submitFilesService = getResourceService();
- SessionMap map = (SessionMap) request.getSession().getAttribute(sessionMapID);
- Long toolSessionID = (Long) map.get(AttributeNames.PARAM_TOOL_SESSION_ID);
- NotebookEntry entry = submitFilesService.getEntry(toolSessionID, CoreNotebookConstants.NOTEBOOK_TOOL,
- ResourceConstants.TOOL_SIGNATURE, user.getUserID());
+ SessionMap map = (SessionMap) request.getSession().getAttribute(sessionMapID);
+ Long toolSessionID = (Long) map.get(AttributeNames.PARAM_TOOL_SESSION_ID);
+ NotebookEntry entry = submitFilesService.getEntry(toolSessionID, CoreNotebookConstants.NOTEBOOK_TOOL,
+ ResourceConstants.TOOL_SIGNATURE, user.getUserID());
- if (entry != null) {
- refForm.setEntryText(entry.getEntry());
- }
-
- return mapping.findForward(ResourceConstants.SUCCESS);
+ if (entry != null) {
+ refForm.setEntryText(entry.getEntry());
}
- /**
- * Submit reflection form input database.
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- private ActionForward submitReflection(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
- ReflectionForm refForm = (ReflectionForm) form;
- Integer userId = refForm.getUserID();
+ return mapping.findForward(ResourceConstants.SUCCESS);
+ }
- String sessionMapID = WebUtil.readStrParam(request, ResourceConstants.ATTR_SESSION_MAP_ID);
- SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
- Long sessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
+ /**
+ * Submit reflection form input database.
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ private ActionForward submitReflection(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ ReflectionForm refForm = (ReflectionForm) form;
+ Integer userId = refForm.getUserID();
- IResourceService service = getResourceService();
+ String sessionMapID = WebUtil.readStrParam(request, ResourceConstants.ATTR_SESSION_MAP_ID);
+ SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
+ Long sessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
- // check for existing notebook entry
- NotebookEntry entry = service.getEntry(sessionId, CoreNotebookConstants.NOTEBOOK_TOOL, ResourceConstants.TOOL_SIGNATURE,
- userId);
+ IResourceService service = getResourceService();
- if (entry == null) {
- // create new entry
- service.createNotebookEntry(sessionId, CoreNotebookConstants.NOTEBOOK_TOOL, ResourceConstants.TOOL_SIGNATURE, userId,
- refForm.getEntryText());
- }
- else {
- // update existing entry
- entry.setEntry(refForm.getEntryText());
- entry.setLastModified(new Date());
- service.updateEntry(entry);
- }
+ // check for existing notebook entry
+ NotebookEntry entry = service.getEntry(sessionId, CoreNotebookConstants.NOTEBOOK_TOOL,
+ ResourceConstants.TOOL_SIGNATURE, userId);
- return finish(mapping, form, request, response);
+ if (entry == null) {
+ // create new entry
+ service.createNotebookEntry(sessionId, CoreNotebookConstants.NOTEBOOK_TOOL,
+ ResourceConstants.TOOL_SIGNATURE, userId, refForm.getEntryText());
+ } else {
+ // update existing entry
+ entry.setEntry(refForm.getEntryText());
+ entry.setLastModified(new Date());
+ service.updateEntry(entry);
}
- //*************************************************************************************
- // Private method
- //*************************************************************************************
- private boolean validateBeforeFinish(HttpServletRequest request, String sessionMapID) {
- SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
- Long sessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
+ return finish(mapping, form, request, response);
+ }
- HttpSession ss = SessionManager.getSession();
- UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
- Long userID = new Long(user.getUserID().longValue());
+ // *************************************************************************************
+ // Private method
+ // *************************************************************************************
+ private boolean validateBeforeFinish(HttpServletRequest request, String sessionMapID) {
+ SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
+ Long sessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
- IResourceService service = getResourceService();
- int miniViewFlag = service.checkMiniView(sessionId, userID);
- //if current user view less than reqired view count number, then just return error message.
- //if it is runOffline content, then need not check minimum view count
- Boolean runOffline = (Boolean) sessionMap.get(ResourceConstants.PARAM_RUN_OFFLINE);
- if (miniViewFlag > 0 && !runOffline) {
- ActionErrors errors = new ActionErrors();
- errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("lable.learning.minimum.view.number.less", miniViewFlag));
- this.addErrors(request, errors);
- return false;
- }
+ HttpSession ss = SessionManager.getSession();
+ UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
+ Long userID = new Long(user.getUserID().longValue());
- return true;
+ IResourceService service = getResourceService();
+ int miniViewFlag = service.checkMiniView(sessionId, userID);
+ // if current user view less than reqired view count number, then just return error message.
+ // if it is runOffline content, then need not check minimum view count
+ Boolean runOffline = (Boolean) sessionMap.get(ResourceConstants.PARAM_RUN_OFFLINE);
+ if (miniViewFlag > 0 && !runOffline) {
+ ActionErrors errors = new ActionErrors();
+ errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("lable.learning.minimum.view.number.less",
+ miniViewFlag));
+ this.addErrors(request, errors);
+ return false;
}
- private IResourceService getResourceService() {
- WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet().getServletContext());
- return (IResourceService) wac.getBean(ResourceConstants.RESOURCE_SERVICE);
- }
+ return true;
+ }
- /**
- * List save current resource items.
- * @param request
- * @return
- */
- private SortedSet getResourceItemList(SessionMap sessionMap) {
- SortedSet list = (SortedSet) sessionMap.get(ResourceConstants.ATTR_RESOURCE_ITEM_LIST);
- if (list == null) {
- list = new TreeSet(new ResourceItemComparator());
- sessionMap.put(ResourceConstants.ATTR_RESOURCE_ITEM_LIST, list);
- }
- return list;
+ private IResourceService getResourceService() {
+ WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet()
+ .getServletContext());
+ return (IResourceService) wac.getBean(ResourceConstants.RESOURCE_SERVICE);
+ }
+
+ /**
+ * List save current resource items.
+ *
+ * @param request
+ * @return
+ */
+ private SortedSet getResourceItemList(SessionMap sessionMap) {
+ SortedSet list = (SortedSet) sessionMap
+ .get(ResourceConstants.ATTR_RESOURCE_ITEM_LIST);
+ if (list == null) {
+ list = new TreeSet(new ResourceItemComparator());
+ sessionMap.put(ResourceConstants.ATTR_RESOURCE_ITEM_LIST, list);
}
+ return list;
+ }
- /**
- * Get java.util.List
from HttpSession by given name.
- *
- * @param request
- * @param name
- * @return
- */
- private List getListFromSession(SessionMap sessionMap, String name) {
- List list = (List) sessionMap.get(name);
- if (list == null) {
- list = new ArrayList();
- sessionMap.put(name, list);
- }
- return list;
+ /**
+ * Get java.util.List
from HttpSession by given name.
+ *
+ * @param request
+ * @param name
+ * @return
+ */
+ private List getListFromSession(SessionMap sessionMap, String name) {
+ List list = (List) sessionMap.get(name);
+ if (list == null) {
+ list = new ArrayList();
+ sessionMap.put(name, list);
}
+ return list;
+ }
- /**
- * Return ActionForward
according to resource item type.
- * @param type
- * @param mapping
- * @return
- */
- private ActionForward findForward(short type, ActionMapping mapping) {
- ActionForward forward;
- switch (type) {
- case ResourceConstants.RESOURCE_TYPE_URL:
- forward = mapping.findForward("url");
- break;
- case ResourceConstants.RESOURCE_TYPE_FILE:
- forward = mapping.findForward("file");
- break;
- case ResourceConstants.RESOURCE_TYPE_WEBSITE:
- forward = mapping.findForward("website");
- break;
- case ResourceConstants.RESOURCE_TYPE_LEARNING_OBJECT:
- forward = mapping.findForward("learningobject");
- break;
- default:
- forward = null;
- break;
- }
- return forward;
+ /**
+ * Return ActionForward
according to resource item type.
+ *
+ * @param type
+ * @param mapping
+ * @return
+ */
+ private ActionForward findForward(short type, ActionMapping mapping) {
+ ActionForward forward;
+ switch (type) {
+ case ResourceConstants.RESOURCE_TYPE_URL:
+ forward = mapping.findForward("url");
+ break;
+ case ResourceConstants.RESOURCE_TYPE_FILE:
+ forward = mapping.findForward("file");
+ break;
+ case ResourceConstants.RESOURCE_TYPE_WEBSITE:
+ forward = mapping.findForward("website");
+ break;
+ case ResourceConstants.RESOURCE_TYPE_LEARNING_OBJECT:
+ forward = mapping.findForward("learningobject");
+ break;
+ default:
+ forward = null;
+ break;
}
+ return forward;
+ }
- private ResourceUser getCurrentUser(IResourceService service, Long sessionId) {
- //try to get form system session
- HttpSession ss = SessionManager.getSession();
- //get back login user DTO
- UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
- ResourceUser resourceUser = service.getUserByIDAndSession(new Long(user.getUserID().intValue()), sessionId);
+ private ResourceUser getCurrentUser(IResourceService service, Long sessionId) {
+ // try to get form system session
+ HttpSession ss = SessionManager.getSession();
+ // get back login user DTO
+ UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
+ ResourceUser resourceUser = service.getUserByIDAndSession(new Long(user.getUserID().intValue()), sessionId);
- if (resourceUser == null) {
- ResourceSession session = service.getResourceSessionBySessionId(sessionId);
- resourceUser = new ResourceUser(user, session);
- service.createUser(resourceUser);
- }
- return resourceUser;
+ if (resourceUser == null) {
+ ResourceSession session = service.getResourceSessionBySessionId(sessionId);
+ resourceUser = new ResourceUser(user, session);
+ service.createUser(resourceUser);
}
+ return resourceUser;
+ }
- private ResourceUser getSpecifiedUser(IResourceService service, Long sessionId, Integer userId) {
- ResourceUser resourceUser = service.getUserByIDAndSession(new Long(userId.intValue()), sessionId);
- if (resourceUser == null) {
- LearningAction.log
- .error("Unable to find specified user for share resources activity. Screens are likely to fail. SessionId="
- + sessionId + " UserId=" + userId);
- }
- return resourceUser;
+ private ResourceUser getSpecifiedUser(IResourceService service, Long sessionId, Integer userId) {
+ ResourceUser resourceUser = service.getUserByIDAndSession(new Long(userId.intValue()), sessionId);
+ if (resourceUser == null) {
+ LearningAction.log
+ .error("Unable to find specified user for share resources activity. Screens are likely to fail. SessionId="
+ + sessionId + " UserId=" + userId);
}
+ return resourceUser;
+ }
- /**
- * @param itemForm
- * @return
- */
- private ActionErrors validateResourceItem(ResourceItemForm itemForm) {
- ActionErrors errors = new ActionErrors();
- if (StringUtils.isBlank(itemForm.getTitle())) {
- errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(ResourceConstants.ERROR_MSG_TITLE_BLANK));
- }
+ /**
+ * @param itemForm
+ * @return
+ */
+ private ActionErrors validateResourceItem(ResourceItemForm itemForm) {
+ ActionErrors errors = new ActionErrors();
+ if (StringUtils.isBlank(itemForm.getTitle())) {
+ errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(ResourceConstants.ERROR_MSG_TITLE_BLANK));
+ }
- if (itemForm.getItemType() == ResourceConstants.RESOURCE_TYPE_URL) {
- if (StringUtils.isBlank(itemForm.getUrl())) {
- errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(ResourceConstants.ERROR_MSG_URL_BLANK));
- //URL validation: Commom URL validate(1.3.0) work not very well: it can not support http://address:port format!!!
- // UrlValidator validator = new UrlValidator();
- // if(!validator.isValid(itemForm.getUrl()))
- // errors.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage(ResourceConstants.ERROR_MSG_INVALID_URL));
- }
- }
- // if(itemForm.getItemType() == ResourceConstants.RESOURCE_TYPE_WEBSITE
- // ||itemForm.getItemType() == ResourceConstants.RESOURCE_TYPE_LEARNING_OBJECT){
- // if(StringUtils.isBlank(itemForm.getDescription()))
- // errors.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage(ResourceConstants.ERROR_MSG_DESC_BLANK));
- // }
- if (itemForm.getItemType() == ResourceConstants.RESOURCE_TYPE_WEBSITE
- || itemForm.getItemType() == ResourceConstants.RESOURCE_TYPE_LEARNING_OBJECT
- || itemForm.getItemType() == ResourceConstants.RESOURCE_TYPE_FILE) {
+ if (itemForm.getItemType() == ResourceConstants.RESOURCE_TYPE_URL) {
+ if (StringUtils.isBlank(itemForm.getUrl())) {
+ errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(ResourceConstants.ERROR_MSG_URL_BLANK));
+ // URL validation: Commom URL validate(1.3.0) work not very well: it can not support http://address:port
+ // format!!!
+ // UrlValidator validator = new UrlValidator();
+ // if(!validator.isValid(itemForm.getUrl()))
+ // errors.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage(ResourceConstants.ERROR_MSG_INVALID_URL));
+ }
+ }
+ // if(itemForm.getItemType() == ResourceConstants.RESOURCE_TYPE_WEBSITE
+ // ||itemForm.getItemType() == ResourceConstants.RESOURCE_TYPE_LEARNING_OBJECT){
+ // if(StringUtils.isBlank(itemForm.getDescription()))
+ // errors.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage(ResourceConstants.ERROR_MSG_DESC_BLANK));
+ // }
+ if (itemForm.getItemType() == ResourceConstants.RESOURCE_TYPE_WEBSITE
+ || itemForm.getItemType() == ResourceConstants.RESOURCE_TYPE_LEARNING_OBJECT
+ || itemForm.getItemType() == ResourceConstants.RESOURCE_TYPE_FILE) {
- if (itemForm.getFile() != null && FileUtil.isExecutableFile(itemForm.getFile().getFileName())) {
- ActionMessage msg = new ActionMessage("error.attachment.executable");
- errors.add(ActionMessages.GLOBAL_MESSAGE, msg);
- }
+ if (itemForm.getFile() != null && FileUtil.isExecutableFile(itemForm.getFile().getFileName())) {
+ ActionMessage msg = new ActionMessage("error.attachment.executable");
+ errors.add(ActionMessages.GLOBAL_MESSAGE, msg);
+ }
- // validate item size
- FileValidatorUtil.validateFileSize(itemForm.getFile(), false, errors);
+ // validate item size
+ FileValidatorUtil.validateFileSize(itemForm.getFile(), false, errors);
- //for edit validate: file already exist
- if (!itemForm.isHasFile() && (itemForm.getFile() == null || StringUtils.isEmpty(itemForm.getFile().getFileName()))) {
- errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(ResourceConstants.ERROR_MSG_FILE_BLANK));
- }
- }
- return errors;
+ // for edit validate: file already exist
+ if (!itemForm.isHasFile()
+ && (itemForm.getFile() == null || StringUtils.isEmpty(itemForm.getFile().getFileName()))) {
+ errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(ResourceConstants.ERROR_MSG_FILE_BLANK));
+ }
}
+ return errors;
+ }
- /**
- * Set complete flag for given resource item.
- * @param request
- * @param sessionId
- */
- private void doComplete(HttpServletRequest request) {
- //get back sessionMap
- String sessionMapID = request.getParameter(ResourceConstants.ATTR_SESSION_MAP_ID);
- SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
+ /**
+ * Set complete flag for given resource item.
+ *
+ * @param request
+ * @param sessionId
+ */
+ private void doComplete(HttpServletRequest request) {
+ // get back sessionMap
+ String sessionMapID = request.getParameter(ResourceConstants.ATTR_SESSION_MAP_ID);
+ SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
- Long resourceItemUid = new Long(request.getParameter(ResourceConstants.PARAM_RESOURCE_ITEM_UID));
- IResourceService service = getResourceService();
- HttpSession ss = SessionManager.getSession();
- //get back login user DTO
- UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
+ Long resourceItemUid = new Long(request.getParameter(ResourceConstants.PARAM_RESOURCE_ITEM_UID));
+ IResourceService service = getResourceService();
+ HttpSession ss = SessionManager.getSession();
+ // get back login user DTO
+ UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
- Long sessionId = (Long) sessionMap.get(ResourceConstants.ATTR_TOOL_SESSION_ID);
- service.setItemComplete(resourceItemUid, new Long(user.getUserID().intValue()), sessionId);
+ Long sessionId = (Long) sessionMap.get(ResourceConstants.ATTR_TOOL_SESSION_ID);
+ service.setItemComplete(resourceItemUid, new Long(user.getUserID().intValue()), sessionId);
- //set resource item complete tag
- SortedSet resourceItemList = getResourceItemList(sessionMap);
- for (ResourceItem item : resourceItemList) {
- if (item.getUid().equals(resourceItemUid)) {
- item.setComplete(true);
- break;
- }
- }
+ // set resource item complete tag
+ SortedSet resourceItemList = getResourceItemList(sessionMap);
+ for (ResourceItem item : resourceItemList) {
+ if (item.getUid().equals(resourceItemUid)) {
+ item.setComplete(true);
+ break;
+ }
}
+ }
}
Index: lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/web/action/MonitoringAction.java
===================================================================
diff -u -r05ab55ef4acdc0c374af7405c58fb0e0fe8eb6b7 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/web/action/MonitoringAction.java (.../MonitoringAction.java) (revision 05ab55ef4acdc0c374af7405c58fb0e0fe8eb6b7)
+++ lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/web/action/MonitoringAction.java (.../MonitoringAction.java) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -32,14 +32,12 @@
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
-import org.lamsfoundation.lams.events.IEventNotificationService;
import org.lamsfoundation.lams.notebook.model.NotebookEntry;
import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants;
import org.lamsfoundation.lams.tool.rsrc.ResourceConstants;
@@ -49,186 +47,171 @@
import org.lamsfoundation.lams.tool.rsrc.model.ResourceSession;
import org.lamsfoundation.lams.tool.rsrc.model.ResourceUser;
import org.lamsfoundation.lams.tool.rsrc.service.IResourceService;
-import org.lamsfoundation.lams.usermanagement.dto.UserDTO;
import org.lamsfoundation.lams.util.WebUtil;
-import org.lamsfoundation.lams.web.session.SessionManager;
import org.lamsfoundation.lams.web.util.AttributeNames;
import org.lamsfoundation.lams.web.util.SessionMap;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class MonitoringAction extends Action {
- public static Logger log = Logger.getLogger(MonitoringAction.class);
+ public static Logger log = Logger.getLogger(MonitoringAction.class);
- @Override
- public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
- throws IOException, ServletException {
- String param = mapping.getParameter();
+ @Override
+ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) throws IOException, ServletException {
+ String param = mapping.getParameter();
- request.setAttribute("initialTabId", WebUtil.readLongParam(request, AttributeNames.PARAM_CURRENT_TAB, true));
+ request.setAttribute("initialTabId", WebUtil.readLongParam(request, AttributeNames.PARAM_CURRENT_TAB, true));
- if (param.equals("summary")) {
- return summary(mapping, form, request, response);
- }
+ if (param.equals("summary")) {
+ return summary(mapping, form, request, response);
+ }
- if (param.equals("listuser")) {
- return listuser(mapping, form, request, response);
- }
- if (param.equals("showitem")) {
- return showitem(mapping, form, request, response);
- }
- if (param.equals("hideitem")) {
- return hideitem(mapping, form, request, response);
- }
- if (param.equals("viewReflection")) {
- return viewReflection(mapping, form, request, response);
- }
-
- return mapping.findForward(ResourceConstants.ERROR);
+ if (param.equals("listuser")) {
+ return listuser(mapping, form, request, response);
}
+ if (param.equals("showitem")) {
+ return showitem(mapping, form, request, response);
+ }
+ if (param.equals("hideitem")) {
+ return hideitem(mapping, form, request, response);
+ }
+ if (param.equals("viewReflection")) {
+ return viewReflection(mapping, form, request, response);
+ }
- private ActionForward hideitem(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
+ return mapping.findForward(ResourceConstants.ERROR);
+ }
- Long itemUid = WebUtil.readLongParam(request, ResourceConstants.PARAM_RESOURCE_ITEM_UID);
- IResourceService service = getResourceService();
- service.setItemVisible(itemUid, false);
+ private ActionForward hideitem(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
- //get back SessionMap
- String sessionMapID = request.getParameter(ResourceConstants.ATTR_SESSION_MAP_ID);
- SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
- request.setAttribute(ResourceConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID());
+ Long itemUid = WebUtil.readLongParam(request, ResourceConstants.PARAM_RESOURCE_ITEM_UID);
+ IResourceService service = getResourceService();
+ service.setItemVisible(itemUid, false);
- //update session value
- List groupList = (List) sessionMap.get(ResourceConstants.ATTR_SUMMARY_LIST);
- if (groupList != null) {
- for (List group : groupList) {
- for (Summary sum : group) {
- if (itemUid.equals(sum.getItemUid())) {
- sum.setItemHide(true);
- break;
- }
- }
- }
- }
+ // get back SessionMap
+ String sessionMapID = request.getParameter(ResourceConstants.ATTR_SESSION_MAP_ID);
+ SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
+ request.setAttribute(ResourceConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID());
- return mapping.findForward(ResourceConstants.SUCCESS);
+ // update session value
+ List groupList = (List) sessionMap.get(ResourceConstants.ATTR_SUMMARY_LIST);
+ if (groupList != null) {
+ for (List group : groupList) {
+ for (Summary sum : group) {
+ if (itemUid.equals(sum.getItemUid())) {
+ sum.setItemHide(true);
+ break;
+ }
+ }
+ }
}
- private ActionForward showitem(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
- Long itemUid = WebUtil.readLongParam(request, ResourceConstants.PARAM_RESOURCE_ITEM_UID);
- IResourceService service = getResourceService();
- service.setItemVisible(itemUid, true);
+ return mapping.findForward(ResourceConstants.SUCCESS);
+ }
- //get back SessionMap
- String sessionMapID = request.getParameter(ResourceConstants.ATTR_SESSION_MAP_ID);
- SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
- request.setAttribute(ResourceConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID());
+ private ActionForward showitem(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ Long itemUid = WebUtil.readLongParam(request, ResourceConstants.PARAM_RESOURCE_ITEM_UID);
+ IResourceService service = getResourceService();
+ service.setItemVisible(itemUid, true);
- //update session value
- List groupList = (List) sessionMap.get(ResourceConstants.ATTR_SUMMARY_LIST);
- if (groupList != null) {
- for (List group : groupList) {
- for (Summary sum : group) {
- if (itemUid.equals(sum.getItemUid())) {
- sum.setItemHide(false);
- break;
- }
- }
- }
+ // get back SessionMap
+ String sessionMapID = request.getParameter(ResourceConstants.ATTR_SESSION_MAP_ID);
+ SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
+ request.setAttribute(ResourceConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID());
+
+ // update session value
+ List groupList = (List) sessionMap.get(ResourceConstants.ATTR_SUMMARY_LIST);
+ if (groupList != null) {
+ for (List group : groupList) {
+ for (Summary sum : group) {
+ if (itemUid.equals(sum.getItemUid())) {
+ sum.setItemHide(false);
+ break;
+ }
}
- return mapping.findForward(ResourceConstants.SUCCESS);
+ }
}
+ return mapping.findForward(ResourceConstants.SUCCESS);
+ }
- private ActionForward summary(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
- //initial Session Map
- SessionMap sessionMap = new SessionMap();
- request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap);
- request.setAttribute(ResourceConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID());
- // save contentFolderID into session
- sessionMap.put(AttributeNames.PARAM_CONTENT_FOLDER_ID, WebUtil.readStrParam(request,
- AttributeNames.PARAM_CONTENT_FOLDER_ID));
+ private ActionForward summary(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ // initial Session Map
+ SessionMap sessionMap = new SessionMap();
+ request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap);
+ request.setAttribute(ResourceConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID());
+ // save contentFolderID into session
+ sessionMap.put(AttributeNames.PARAM_CONTENT_FOLDER_ID, WebUtil.readStrParam(request,
+ AttributeNames.PARAM_CONTENT_FOLDER_ID));
- Long contentId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID);
- IResourceService service = getResourceService();
- List> groupList = service.getSummary(contentId);
+ Long contentId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID);
+ IResourceService service = getResourceService();
+ List> groupList = service.getSummary(contentId);
- Resource resource = service.getResourceByContentId(contentId);
- resource.toDTO();
+ Resource resource = service.getResourceByContentId(contentId);
+ resource.toDTO();
- Map> relectList = service.getReflectList(contentId, false);
+ Map> relectList = service.getReflectList(contentId, false);
- //cache into sessionMap
- sessionMap.put(ResourceConstants.ATTR_SUMMARY_LIST, groupList);
- sessionMap.put(ResourceConstants.PAGE_EDITABLE, resource.isContentInUse());
- sessionMap.put(ResourceConstants.ATTR_RESOURCE, resource);
- sessionMap.put(ResourceConstants.ATTR_TOOL_CONTENT_ID, contentId);
- sessionMap.put(ResourceConstants.ATTR_REFLECT_LIST, relectList);
- if (resource.isNotifyTeachersOnAssigmentSumbit()) {
- //Since we don't know if the event exists, we just try to create it.
- service.getEventNotificationService().createEvent(ResourceConstants.TOOL_SIGNATURE,
- ResourceConstants.EVENT_NAME_NOTIFY_TEACHERS_ON_ASSIGMENT_SUBMIT, contentId,
- service.getLocalisedMessage("event.assigment.submit.subject", null),
- service.getLocalisedMessage("event.assigment.submit.body", null));
+ // cache into sessionMap
+ sessionMap.put(ResourceConstants.ATTR_SUMMARY_LIST, groupList);
+ sessionMap.put(ResourceConstants.PAGE_EDITABLE, resource.isContentInUse());
+ sessionMap.put(ResourceConstants.ATTR_RESOURCE, resource);
+ sessionMap.put(ResourceConstants.ATTR_TOOL_CONTENT_ID, contentId);
+ sessionMap.put(ResourceConstants.ATTR_REFLECT_LIST, relectList);
+ return mapping.findForward(ResourceConstants.SUCCESS);
+ }
- HttpSession ss = SessionManager.getSession();
- UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
- //Now we subscribe the teacher
- service.getEventNotificationService().subscribe(ResourceConstants.TOOL_SIGNATURE,
- ResourceConstants.EVENT_NAME_NOTIFY_TEACHERS_ON_ASSIGMENT_SUBMIT, contentId, user.getUserID().longValue(),
- IEventNotificationService.DELIVERY_METHOD_MAIL, IEventNotificationService.PERIODICITY_SINGLE);
- }
- return mapping.findForward(ResourceConstants.SUCCESS);
- }
+ private ActionForward listuser(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ Long sessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID);
+ Long itemUid = WebUtil.readLongParam(request, ResourceConstants.PARAM_RESOURCE_ITEM_UID);
- private ActionForward listuser(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
- Long sessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID);
- Long itemUid = WebUtil.readLongParam(request, ResourceConstants.PARAM_RESOURCE_ITEM_UID);
+ // get user list by given item uid
+ IResourceService service = getResourceService();
+ List list = service.getUserListBySessionItem(sessionId, itemUid);
- //get user list by given item uid
- IResourceService service = getResourceService();
- List list = service.getUserListBySessionItem(sessionId, itemUid);
+ // set to request
+ request.setAttribute(ResourceConstants.ATTR_USER_LIST, list);
+ return mapping.findForward(ResourceConstants.SUCCESS);
+ }
- //set to request
- request.setAttribute(ResourceConstants.ATTR_USER_LIST, list);
- return mapping.findForward(ResourceConstants.SUCCESS);
- }
+ private ActionForward viewReflection(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
- private ActionForward viewReflection(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
+ Long uid = WebUtil.readLongParam(request, ResourceConstants.ATTR_USER_UID);
+ Long sessionID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID);
- Long uid = WebUtil.readLongParam(request, ResourceConstants.ATTR_USER_UID);
- Long sessionID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID);
+ IResourceService service = getResourceService();
+ ResourceUser user = service.getUser(uid);
+ NotebookEntry notebookEntry = service.getEntry(sessionID, CoreNotebookConstants.NOTEBOOK_TOOL,
+ ResourceConstants.TOOL_SIGNATURE, user.getUserId().intValue());
- IResourceService service = getResourceService();
- ResourceUser user = service.getUser(uid);
- NotebookEntry notebookEntry = service.getEntry(sessionID, CoreNotebookConstants.NOTEBOOK_TOOL,
- ResourceConstants.TOOL_SIGNATURE, user.getUserId().intValue());
+ ResourceSession session = service.getResourceSessionBySessionId(sessionID);
- ResourceSession session = service.getResourceSessionBySessionId(sessionID);
-
- ReflectDTO refDTO = new ReflectDTO(user);
- if (notebookEntry == null) {
- refDTO.setFinishReflection(false);
- refDTO.setReflect(null);
- }
- else {
- refDTO.setFinishReflection(true);
- refDTO.setReflect(notebookEntry.getEntry());
- }
- refDTO.setReflectInstrctions(session.getResource().getReflectInstructions());
-
- request.setAttribute("userDTO", refDTO);
- return mapping.findForward("success");
+ ReflectDTO refDTO = new ReflectDTO(user);
+ if (notebookEntry == null) {
+ refDTO.setFinishReflection(false);
+ refDTO.setReflect(null);
+ } else {
+ refDTO.setFinishReflection(true);
+ refDTO.setReflect(notebookEntry.getEntry());
}
+ refDTO.setReflectInstrctions(session.getResource().getReflectInstructions());
- // *************************************************************************************
- // Private method
- // *************************************************************************************
- private IResourceService getResourceService() {
- WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet().getServletContext());
- return (IResourceService) wac.getBean(ResourceConstants.RESOURCE_SERVICE);
- }
+ request.setAttribute("userDTO", refDTO);
+ return mapping.findForward("success");
+ }
+
+ // *************************************************************************************
+ // Private method
+ // *************************************************************************************
+ private IResourceService getResourceService() {
+ WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet()
+ .getServletContext());
+ return (IResourceService) wac.getBean(ResourceConstants.RESOURCE_SERVICE);
+ }
}
Index: lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/ISubmitFilesService.java
===================================================================
diff -u -ra01292ae06e058ffcc16aaeec6d61959a7b69273 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/ISubmitFilesService.java (.../ISubmitFilesService.java) (revision a01292ae06e058ffcc16aaeec6d61959a7b69273)
+++ lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/ISubmitFilesService.java (.../ISubmitFilesService.java) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -40,230 +40,253 @@
import org.lamsfoundation.lams.tool.sbmt.SubmitUser;
import org.lamsfoundation.lams.tool.sbmt.dto.FileDetailsDTO;
import org.lamsfoundation.lams.tool.sbmt.exception.SubmitFilesException;
+import org.lamsfoundation.lams.usermanagement.User;
import org.lamsfoundation.lams.usermanagement.dto.UserDTO;
/**
* @author Manpreet Minhas
*/
public interface ISubmitFilesService {
- /**
- * Returns the SubmitFilesContent
object corresponding to the
- * given contentID
. If could not find out corresponding
- * SubmitFilesContent
by given contentID
, return a not-null
- * but emtpy SubmitFilesContent
instance.
- *
- * @param contentID
- * The content_id
of the object to be looked up
- * @return SubmitFilesContent The required populated object
- */
- public SubmitFilesContent getSubmitFilesContent(Long contentID);
+ /**
+ * Returns the SubmitFilesContent
object corresponding to the given contentID
. If
+ * could not find out corresponding SubmitFilesContent
by given contentID
, return a
+ * not-null but emtpy SubmitFilesContent
instance.
+ *
+ * @param contentID
+ * The content_id
of the object to be looked up
+ * @return SubmitFilesContent The required populated object
+ */
+ public SubmitFilesContent getSubmitFilesContent(Long contentID);
- /**
- *
- * Returns the SubmitFilesReport
object corresponding to the
- * given reportID
- *
- * @param reportID
- * @return SubmitFilesReport The required populated object
- */
- public SubmitFilesReport getSubmitFilesReport(Long reportID);
+ /**
+ *
+ * Returns the SubmitFilesReport
object corresponding to the given reportID
+ *
+ * @param reportID
+ * @return SubmitFilesReport The required populated object
+ */
+ public SubmitFilesReport getSubmitFilesReport(Long reportID);
- /**
- * This method uploads a file with the given name and description. It's a
- * two step process
- *
- * - It first uploads the file to the content repository
- * - And then it updates the database
- *
- * @param fileDescription
- * The description of the file being uploaded.
- * @param userID
- * The User
who has uploaded the file.
- * @param contentID
- * The content_id of the record to be updated in the database
- * @param uploadedFile
- * The STRUTS org.apache.struts.upload.FormFile type
- *
- * @throws SubmitFilesException
- */
- public void uploadFileToSession(Long sessionID, FormFile uploadFile, String fileDescription, Integer userID)
- throws SubmitFilesException;
+ /**
+ * This method uploads a file with the given name and description. It's a two step process
+ *
+ * - It first uploads the file to the content repository
+ * - And then it updates the database
+ *
+ *
+ * @param fileDescription
+ * The description of the file being uploaded.
+ * @param userID
+ * The User
who has uploaded the file.
+ * @param contentID
+ * The content_id of the record to be updated in the database
+ * @param uploadedFile
+ * The STRUTS org.apache.struts.upload.FormFile type
+ *
+ * @throws SubmitFilesException
+ */
+ public void uploadFileToSession(Long sessionID, FormFile uploadFile, String fileDescription, Integer userID)
+ throws SubmitFilesException;
- /**
- * Upload file to repository and persist relative attributes into database.
- *
- * @param contentID
- * @param uploadFile
- * @param fileType
- * @return If successs, return an instance of InstructionFile
. Otherwise, return null.
- * @throws SubmitFilesException
- */
- public InstructionFiles uploadFileToContent(Long contentID, FormFile uploadFile, String fileType) throws SubmitFilesException;
+ /**
+ * Upload file to repository and persist relative attributes into database.
+ *
+ * @param contentID
+ * @param uploadFile
+ * @param fileType
+ * @return If successs, return an instance of InstructionFile
. Otherwise, return null.
+ * @throws SubmitFilesException
+ */
+ public InstructionFiles uploadFileToContent(Long contentID, FormFile uploadFile, String fileType)
+ throws SubmitFilesException;
- /**
- * This method returns a list of files that were uploaded by the
- * given User for given contentID
.
- *
- * This method is used in the learning enviornment for displaying
- * the files being uploaded by the given user, as the user
- * uploads them one by one.
- *
- * @param userID The user_id
of the User
- * @param sessionID The session_id
to be looked up
- * @return List The list of required objects.
- */
- public List getFilesUploadedByUser(Integer userID, Long sessionID, Locale currentLocale);
+ /**
+ * This method returns a list of files that were uploaded by the given
+ * User for given contentID
.
+ *
+ * This method is used in the learning enviornment for displaying
+ * the files being uploaded by the given user, as the user
+ * uploads them one by one.
+ *
+ * @param userID The user_id
of the User
+ * @param sessionID The session_id
to be looked up
+ * @return List The list of required objects.
+ */
+ public List getFilesUploadedByUser(Integer userID, Long sessionID, Locale currentLocale);
- /**
- * This method returns a SortedMap of all files that were submitted users within a
- * given sessionID
.
- *
- * @param sessionID The session_id
to be looked up
- * @return SortedMap, the key is UserDTO, the value is a List of FileDetailsDTO objects
- */
- public SortedMap getFilesUploadedBySession(Long sessionID, Locale currentLocale);
+ /**
+ * This method returns a SortedMap of all files that were submitted users within a given sessionID
.
+ *
+ * @param sessionID
+ * The session_id
to be looked up
+ * @return SortedMap, the key is UserDTO, the value is a List of FileDetailsDTO objects
+ */
+ public SortedMap getFilesUploadedBySession(Long sessionID, Locale currentLocale);
- public void updateMarks(Long reportID, Float marks, String comments);
+ public void updateMarks(Long reportID, Float marks, String comments);
- public FileDetailsDTO getFileDetails(Long detailID, Locale currentLocale);
+ public FileDetailsDTO getFileDetails(Long detailID, Locale currentLocale);
- /**
- * Get SubmitFilesSession instance according to the given session id.
- * @param sessionID
- * @return
- */
- public SubmitFilesSession getSessionById(Long sessionID);
+ /**
+ * Get SubmitFilesSession instance according to the given session id.
+ *
+ * @param sessionID
+ * @return
+ */
+ public SubmitFilesSession getSessionById(Long sessionID);
- public IVersionedNode downloadFile(Long uuid, Long versionID);
+ public IVersionedNode downloadFile(Long uuid, Long versionID);
- /**
- * Release marks and comments information to learners, for a special session.
- * @param sessionID
- * @return success return true, otherwise return false.
- */
- public boolean releaseMarksForSession(Long sessionID);
+ /**
+ * Release marks and comments information to learners, for a special session.
+ *
+ * @param sessionID
+ * @return success return true, otherwise return false.
+ */
+ public boolean releaseMarksForSession(Long sessionID);
- public void deleteFromRepository(Long uuid, Long versionID);
+ public void deleteFromRepository(Long uuid, Long versionID);
- /**
- * When learner finish submission, it invokes this function and will remark the finished
field.
- *
- * @param sessionID
- * @param userID
- */
- public void finishSubmission(Long sessionID, Integer userID);
+ /**
+ * When learner finish submission, it invokes this function and will remark the finished
field.
+ *
+ * @param sessionID
+ * @param userID
+ */
+ public void finishSubmission(Long sessionID, Integer userID);
- /**
- * Create the default content for the given contentID. These default data will copy from default record in
- * Tool Content database table.
- *
- * @return
- * The SubmitFilesContent with default content and given contentID
- */
- public SubmitFilesContent createDefaultContent(Long contentID);
+ /**
+ * Create the default content for the given contentID. These default data will copy from default record in Tool
+ * Content database table.
+ *
+ * @return The SubmitFilesContent with default content and given contentID
+ */
+ public SubmitFilesContent createDefaultContent(Long contentID);
- /**
- * This method retrieves the default content id.
- * @param toolSignature The tool signature which is defined in lams_tool table.
- * @return the default content id
- */
- public Long getToolDefaultContentIdBySignature(String toolSignature);
+ /**
+ * This method retrieves the default content id.
+ *
+ * @param toolSignature
+ * The tool signature which is defined in lams_tool table.
+ * @return the default content id
+ */
+ public Long getToolDefaultContentIdBySignature(String toolSignature);
- /**
- * This method retrieves a list of SubmitFileSession from the contentID.
- * @param contentID
- * @return a list of SubmitFileSession
- */
- //public List getSubmitFilesSessionsByContentID(Long contentID);
- public List getSubmitFilesSessionByContentID(Long contentID);
+ /**
+ * This method retrieves a list of SubmitFileSession from the contentID.
+ *
+ * @param contentID
+ * @return a list of SubmitFileSession
+ */
+ // public List getSubmitFilesSessionsByContentID(Long contentID);
+ public List getSubmitFilesSessionByContentID(Long contentID);
- /**
- * Save or update tool content into database.
- * @param persistContent
- * The SubmitFilesContent
to be updated
- */
- public void saveOrUpdateContent(SubmitFilesContent persistContent);
+ /**
+ * Save or update tool content into database.
+ *
+ * @param persistContent
+ * The SubmitFilesContent
to be updated
+ */
+ public void saveOrUpdateContent(SubmitFilesContent persistContent);
- /**
- * Create refection entry into notebook tool.
- * @param sessionId
- * @param notebook_tool
- * @param tool_signature
- * @param userId
- * @param entryText
- */
- public Long createNotebookEntry(Long sessionId, Integer notebookToolType, String toolSignature, Integer userId,
- String entryText);
+ /**
+ * Create refection entry into notebook tool.
+ *
+ * @param sessionId
+ * @param notebook_tool
+ * @param tool_signature
+ * @param userId
+ * @param entryText
+ */
+ public Long createNotebookEntry(Long sessionId, Integer notebookToolType, String toolSignature, Integer userId,
+ String entryText);
- /**
- * Get reflection entry from notebook tool.
- * @param sessionId
- * @param idType
- * @param signature
- * @param userID
- * @return
- */
- public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID);
+ /**
+ * Get reflection entry from notebook tool.
+ *
+ * @param sessionId
+ * @param idType
+ * @param signature
+ * @param userID
+ * @return
+ */
+ public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID);
- /**
- * @param notebookEntry
- */
- public void updateEntry(NotebookEntry notebookEntry);
+ /**
+ * @param notebookEntry
+ */
+ public void updateEntry(NotebookEntry notebookEntry);
- /**
- * Delete instruction file by UID
- * @param uid
- */
- public void deleteInstructionFile(Long uid);
+ /**
+ * Delete instruction file by UID
+ *
+ * @param uid
+ */
+ public void deleteInstructionFile(Long uid);
- public List getSessionsByContentID(Long toolContentID);
+ public List getSessionsByContentID(Long toolContentID);
- //*************************************************************
- // get SubmitUser methods
- //*************************************************************
+ // *************************************************************
+ // get SubmitUser methods
+ // *************************************************************
- /**
- * Get learner by given toolSessionID
and userID
.
- *
- * @param sessionID
- * @param userID
- * @return
- */
- public SubmitUser getSessionUser(Long sessionID, Integer userID);
+ /**
+ * Get learner by given toolSessionID
and userID
.
+ *
+ * @param sessionID
+ * @param userID
+ * @return
+ */
+ public SubmitUser getSessionUser(Long sessionID, Integer userID);
- public SubmitUser getContentUser(Long contentId, Integer userID);
+ public SubmitUser getContentUser(Long contentId, Integer userID);
- /**
- * Create new user
- * @param userDto
- * @param sessionID
- * @return
- */
- public SubmitUser createSessionUser(UserDTO userDto, Long sessionID);
+ /**
+ * Create new user
+ *
+ * @param userDto
+ * @param sessionID
+ * @return
+ */
+ public SubmitUser createSessionUser(UserDTO userDto, Long sessionID);
- public SubmitUser createContentUser(UserDTO user, Long contentId);
+ public SubmitUser createContentUser(UserDTO user, Long contentId);
- /**
- * Get information of all users who have submitted file.
- * @return The user information list
- */
- public List getUsersBySession(Long sessionID);
+ /**
+ * Get information of all users who have submitted file.
+ *
+ * @return The user information list
+ */
+ public List getUsersBySession(Long sessionID);
- /**
- * get user by UID
- * @param uid
- * @return
- */
- public SubmitUser getUserByUid(Long uid);
+ /**
+ * get user by UID
+ *
+ * @param uid
+ * @return
+ */
+ public SubmitUser getUserByUid(Long uid);
- public IEventNotificationService getEventNotificationService();
+ public IEventNotificationService getEventNotificationService();
- /**
- * Gets a message from resource bundle. Same as
in JSP pages.
- * @param key key of the message
- * @param args arguments for the message
- * @return message content
- */
- String getLocalisedMessage(String key, Object[] args);
+ /**
+ * Gets a message from resource bundle. Same as
in JSP pages.
+ *
+ * @param key
+ * key of the message
+ * @param args
+ * arguments for the message
+ * @return message content
+ */
+ String getLocalisedMessage(String key, Object[] args);
+
+ /**
+ * Finds out which lesson the given tool content belongs to and returns its monitoring users.
+ *
+ * @param sessionId
+ * tool session ID
+ * @return list of teachers that monitor the lesson which contains the tool with given session ID
+ */
+ List getMonitorsByToolSessionId(Long sessionId);
}
Index: lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/SubmitFilesService.java
===================================================================
diff -u -ra01292ae06e058ffcc16aaeec6d61959a7b69273 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/SubmitFilesService.java (.../SubmitFilesService.java) (revision a01292ae06e058ffcc16aaeec6d61959a7b69273)
+++ lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/SubmitFilesService.java (.../SubmitFilesService.java) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -65,6 +65,7 @@
import org.lamsfoundation.lams.learningdesign.service.ExportToolContentException;
import org.lamsfoundation.lams.learningdesign.service.IExportToolContentService;
import org.lamsfoundation.lams.learningdesign.service.ImportToolContentException;
+import org.lamsfoundation.lams.lesson.service.ILessonService;
import org.lamsfoundation.lams.notebook.model.NotebookEntry;
import org.lamsfoundation.lams.notebook.service.ICoreNotebookService;
import org.lamsfoundation.lams.tool.ToolContentImport102Manager;
@@ -106,1002 +107,1024 @@
* @author Manpreet Minhas
*/
public class SubmitFilesService implements ToolContentManager, ToolSessionManager, ISubmitFilesService,
- ToolContentImport102Manager {
+ ToolContentImport102Manager {
- private static Logger log = Logger.getLogger(SubmitFilesService.class);
+ private static Logger log = Logger.getLogger(SubmitFilesService.class);
- private ISubmitFilesContentDAO submitFilesContentDAO;
+ private ISubmitFilesContentDAO submitFilesContentDAO;
- private ISubmitFilesReportDAO submitFilesReportDAO;
+ private ISubmitFilesReportDAO submitFilesReportDAO;
- private ISubmitFilesSessionDAO submitFilesSessionDAO;
+ private ISubmitFilesSessionDAO submitFilesSessionDAO;
- private ISubmissionDetailsDAO submissionDetailsDAO;
+ private ISubmissionDetailsDAO submissionDetailsDAO;
- private ISubmitUserDAO submitUserDAO;
+ private ISubmitUserDAO submitUserDAO;
- private IAttachmentDAO attachmentDAO;
+ private IAttachmentDAO attachmentDAO;
- private IToolContentHandler sbmtToolContentHandler;
+ private IToolContentHandler sbmtToolContentHandler;
- private ILamsToolService toolService;
+ private ILamsToolService toolService;
- private ILearnerService learnerService;
+ private ILearnerService learnerService;
- private IRepositoryService repositoryService;
+ private IRepositoryService repositoryService;
- private IExportToolContentService exportContentService;
+ private IExportToolContentService exportContentService;
- private ICoreNotebookService coreNotebookService;
+ private ICoreNotebookService coreNotebookService;
- private IUserManagementService userManagementService;
+ private IUserManagementService userManagementService;
- private IEventNotificationService eventNotificationService;
+ private IEventNotificationService eventNotificationService;
- private MessageService messageService;
+ private MessageService messageService;
- private class FileDtoComparator implements Comparator {
+ private ILessonService lessonService;
- public int compare(FileDetailsDTO o1, FileDetailsDTO o2) {
- if (o1 != null && o2 != null && o1.getDateOfSubmission() != null && o2.getDateOfSubmission() != null) {
- //don't use Date.comparaTo() directly, because the date could be Timestamp or Date (depeneds the object is persist or not)
- return o1.getDateOfSubmission().getTime() - o2.getDateOfSubmission().getTime() > 0 ? 1 : -1;
- }
- else if (o1 != null) {
- return 1;
- }
- else {
- return -1;
- }
- }
+ private class FileDtoComparator implements Comparator {
+ public int compare(FileDetailsDTO o1, FileDetailsDTO o2) {
+ if (o1 != null && o2 != null && o1.getDateOfSubmission() != null && o2.getDateOfSubmission() != null) {
+ // don't use Date.comparaTo() directly, because the date could be Timestamp or Date (depeneds the object
+ // is persist or not)
+ return o1.getDateOfSubmission().getTime() - o2.getDateOfSubmission().getTime() > 0 ? 1 : -1;
+ } else if (o1 != null) {
+ return 1;
+ } else {
+ return -1;
+ }
}
- public Long createNotebookEntry(Long sessionId, Integer notebookToolType, String toolSignature, Integer userId,
- String entryText) {
- return coreNotebookService.createNotebookEntry(sessionId, notebookToolType, toolSignature, userId, "", entryText);
- }
+ }
- public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) {
- List list = coreNotebookService.getEntry(sessionId, idType, signature, userID);
- if (list == null || list.isEmpty()) {
- return null;
- }
- else {
- return list.get(0);
- }
- }
+ public Long createNotebookEntry(Long sessionId, Integer notebookToolType, String toolSignature, Integer userId,
+ String entryText) {
+ return coreNotebookService.createNotebookEntry(sessionId, notebookToolType, toolSignature, userId, "",
+ entryText);
+ }
- public void updateEntry(NotebookEntry notebookEntry) {
- coreNotebookService.updateEntry(notebookEntry);
+ public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) {
+ List list = coreNotebookService.getEntry(sessionId, idType, signature, userID);
+ if (list == null || list.isEmpty()) {
+ return null;
+ } else {
+ return list.get(0);
}
+ }
- /**
- * (non-Javadoc)
- *
- * @see org.lamsfoundation.lams.tool.ToolContentManager#copyToolContent(java.lang.Long,
- * java.lang.Long)
- */
- public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException {
- if (toContentId == null) {
- throw new ToolException("Failed to create the SubmitFiles tool seession");
- }
+ public void updateEntry(NotebookEntry notebookEntry) {
+ coreNotebookService.updateEntry(notebookEntry);
+ }
- SubmitFilesContent fromContent = null;
- if (fromContentId != null) {
- fromContent = submitFilesContentDAO.getContentByID(fromContentId);
- }
- if (fromContent == null) {
- fromContent = getDefaultSubmit();
- }
- SubmitFilesContent toContent = SubmitFilesContent.newInstance(fromContent, toContentId, sbmtToolContentHandler);
-
- submitFilesContentDAO.saveOrUpdate(toContent);
+ /**
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.ToolContentManager#copyToolContent(java.lang.Long, java.lang.Long)
+ */
+ public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException {
+ if (toContentId == null) {
+ throw new ToolException("Failed to create the SubmitFiles tool seession");
}
- /**
- * @see org.lamsfoundation.lams.tool.ToolContentManager#setAsRunOffline(java.lang.Long)
- */
- public void setAsRunOffline(Long toolContentId, boolean value) {
- //pre-condition validation
- if (toolContentId == null) {
- throw new SubmitFilesException("Fail to set tool content to run offline - " + " based on null toolContentId");
- }
- try {
- SubmitFilesContent content = getSubmitFilesContent(toolContentId);
- if (content == null || !toolContentId.equals(content.getContentID())) {
- content = duplicateDefaultToolContent(toolContentId);
- }
- content.setRunOffline(value);
- submitFilesContentDAO.saveOrUpdate(content);
- }
- catch (DataAccessException e) {
- throw new SubmitFilesException("Exception occured when LAMS is setting content to run offline" + e.getMessage(), e);
- }
+ SubmitFilesContent fromContent = null;
+ if (fromContentId != null) {
+ fromContent = submitFilesContentDAO.getContentByID(fromContentId);
}
+ if (fromContent == null) {
+ fromContent = getDefaultSubmit();
+ }
+ SubmitFilesContent toContent = SubmitFilesContent.newInstance(fromContent, toContentId, sbmtToolContentHandler);
- /**
- * If the toolContentID does not exist, then get default tool content id from tool core and
- * initialize a emtpy SubmitFilesContent
return.
- *
- * @param toolContentId
- * @return
- */
- private SubmitFilesContent duplicateDefaultToolContent(Long toolContentId) {
- long contentId = 0;
- contentId = toolService.getToolDefaultContentIdBySignature(SbmtConstants.TOOL_SIGNATURE);
- SubmitFilesContent content = new SubmitFilesContent();
- content.setContentID(new Long(contentId));
- return content;
+ submitFilesContentDAO.saveOrUpdate(toContent);
+ }
+
+ /**
+ * @see org.lamsfoundation.lams.tool.ToolContentManager#setAsRunOffline(java.lang.Long)
+ */
+ public void setAsRunOffline(Long toolContentId, boolean value) {
+ // pre-condition validation
+ if (toolContentId == null) {
+ throw new SubmitFilesException("Fail to set tool content to run offline - "
+ + " based on null toolContentId");
}
+ try {
+ SubmitFilesContent content = getSubmitFilesContent(toolContentId);
+ if (content == null || !toolContentId.equals(content.getContentID())) {
+ content = duplicateDefaultToolContent(toolContentId);
+ }
+ content.setRunOffline(value);
+ submitFilesContentDAO.saveOrUpdate(content);
+ } catch (DataAccessException e) {
+ throw new SubmitFilesException("Exception occured when LAMS is setting content to run offline"
+ + e.getMessage(), e);
+ }
+ }
- /**
- * @see org.lamsfoundation.lams.tool.ToolContentManager#setAsDefineLater(java.lang.Long)
- */
- public void setAsDefineLater(Long toolContentId, boolean value) {
- //pre-condition validation
- if (toolContentId == null) {
- throw new SubmitFilesException("Fail to set tool content to define later - " + " based on null toolContentId");
- }
- try {
- SubmitFilesContent content = getSubmitFilesContent(toolContentId);
- if (content == null || !toolContentId.equals(content.getContentID())) {
- content = duplicateDefaultToolContent(toolContentId);
- }
- content.setDefineLater(value);
- submitFilesContentDAO.saveOrUpdate(content);
- }
- catch (DataAccessException e) {
- throw new SubmitFilesException("Exception occured when LAMS is setting content to run define later" + e.getMessage(),
- e);
- }
+ /**
+ * If the toolContentID does not exist, then get default tool content id from tool core and initialize a emtpy
+ * SubmitFilesContent
return.
+ *
+ * @param toolContentId
+ * @return
+ */
+ private SubmitFilesContent duplicateDefaultToolContent(Long toolContentId) {
+ long contentId = 0;
+ contentId = toolService.getToolDefaultContentIdBySignature(SbmtConstants.TOOL_SIGNATURE);
+ SubmitFilesContent content = new SubmitFilesContent();
+ content.setContentID(new Long(contentId));
+ return content;
+ }
+ /**
+ * @see org.lamsfoundation.lams.tool.ToolContentManager#setAsDefineLater(java.lang.Long)
+ */
+ public void setAsDefineLater(Long toolContentId, boolean value) {
+ // pre-condition validation
+ if (toolContentId == null) {
+ throw new SubmitFilesException("Fail to set tool content to define later - "
+ + " based on null toolContentId");
}
+ try {
+ SubmitFilesContent content = getSubmitFilesContent(toolContentId);
+ if (content == null || !toolContentId.equals(content.getContentID())) {
+ content = duplicateDefaultToolContent(toolContentId);
+ }
+ content.setDefineLater(value);
+ submitFilesContentDAO.saveOrUpdate(content);
+ } catch (DataAccessException e) {
+ throw new SubmitFilesException("Exception occured when LAMS is setting content to run define later"
+ + e.getMessage(), e);
+ }
- /**
- * @throws SessionDataExistsException
- *
- * @see org.lamsfoundation.lams.tool.ToolContentManager#removeToolContent(java.lang.Long)
- */
- public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException {
- SubmitFilesContent submitFilesContent = submitFilesContentDAO.getContentByID(toolContentId);
- if (submitFilesContent != null) {
- //if session data exist and removeSessionData=false, throw an exception
- List submissionData = submitFilesSessionDAO.getSubmitFilesSessionByContentID(toolContentId);
- if (!(submissionData == null || submissionData.isEmpty()) && !removeSessionData) {
- throw new SessionDataExistsException("Delete failed: There is session data that belongs to this tool content id");
- }
- else if (submissionData != null) {
- Iterator iter = submissionData.iterator();
- while (iter.hasNext()) {
- SubmitFilesSession element = (SubmitFilesSession) iter.next();
- removeToolSession(element);
- }
- }
- submitFilesContentDAO.delete(submitFilesContent);
+ }
+
+ /**
+ * @throws SessionDataExistsException
+ *
+ * @see org.lamsfoundation.lams.tool.ToolContentManager#removeToolContent(java.lang.Long)
+ */
+ public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException {
+ SubmitFilesContent submitFilesContent = submitFilesContentDAO.getContentByID(toolContentId);
+ if (submitFilesContent != null) {
+ // if session data exist and removeSessionData=false, throw an exception
+ List submissionData = submitFilesSessionDAO.getSubmitFilesSessionByContentID(toolContentId);
+ if (!(submissionData == null || submissionData.isEmpty()) && !removeSessionData) {
+ throw new SessionDataExistsException(
+ "Delete failed: There is session data that belongs to this tool content id");
+ } else if (submissionData != null) {
+ Iterator iter = submissionData.iterator();
+ while (iter.hasNext()) {
+ SubmitFilesSession element = (SubmitFilesSession) iter.next();
+ removeToolSession(element);
}
+ }
+ submitFilesContentDAO.delete(submitFilesContent);
}
+ }
- public List getSessionsByContentID(Long toolContentID) {
- return submitFilesSessionDAO.getSubmitFilesSessionByContentID(toolContentID);
+ public List getSessionsByContentID(Long toolContentID) {
+ return submitFilesSessionDAO.getSubmitFilesSessionByContentID(toolContentID);
+ }
+
+ /**
+ * Export the XML fragment for the tool's content, along with any files needed for the content.
+ *
+ * @throws ExportToolContentException
+ */
+ public void exportToolContent(Long toolContentId, String toPath) throws ToolException, DataMissingException {
+ exportContentService.registerFileClassForExport(InstructionFiles.class.getName(), "uuID", "versionID");
+ SubmitFilesContent toolContentObj = submitFilesContentDAO.getContentByID(toolContentId);
+ if (toolContentObj == null) {
+ toolContentObj = getDefaultSubmit();
}
+ if (toolContentObj == null) {
+ throw new DataMissingException("Unable to find default content for the submit files tool");
+ }
- /**
- * Export the XML fragment for the tool's content, along with any files needed
- * for the content.
- * @throws ExportToolContentException
- */
- public void exportToolContent(Long toolContentId, String toPath) throws ToolException, DataMissingException {
- exportContentService.registerFileClassForExport(InstructionFiles.class.getName(), "uuID", "versionID");
- SubmitFilesContent toolContentObj = submitFilesContentDAO.getContentByID(toolContentId);
- if (toolContentObj == null) {
- toolContentObj = getDefaultSubmit();
- }
- if (toolContentObj == null) {
- throw new DataMissingException("Unable to find default content for the submit files tool");
- }
-
- //set toolContentHandler as null to avoid duplicate file node in repository.
- toolContentObj = SubmitFilesContent.newInstance(toolContentObj, toolContentId, null);
- toolContentObj.setToolContentHandler(null);
- try {
- exportContentService.exportToolContent(toolContentId, toolContentObj, sbmtToolContentHandler, toPath);
- }
- catch (ExportToolContentException e) {
- throw new ToolException(e);
- }
+ // set toolContentHandler as null to avoid duplicate file node in repository.
+ toolContentObj = SubmitFilesContent.newInstance(toolContentObj, toolContentId, null);
+ toolContentObj.setToolContentHandler(null);
+ try {
+ exportContentService.exportToolContent(toolContentId, toolContentObj, sbmtToolContentHandler, toPath);
+ } catch (ExportToolContentException e) {
+ throw new ToolException(e);
}
+ }
- public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion,
- String toVersion) throws ToolException {
+ public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion,
+ String toVersion) throws ToolException {
- try {
- exportContentService.registerFileClassForImport(InstructionFiles.class.getName(), "uuID", "versionID", "name",
- "type", null, null);
+ try {
+ exportContentService.registerFileClassForImport(InstructionFiles.class.getName(), "uuID", "versionID",
+ "name", "type", null, null);
- Object toolPOJO = exportContentService.importToolContent(toolContentPath, sbmtToolContentHandler, fromVersion,
- toVersion);
- if (!(toolPOJO instanceof SubmitFilesContent)) {
- throw new ImportToolContentException("Import Submit tool content failed. Deserialized object is " + toolPOJO);
- }
- SubmitFilesContent toolContentObj = (SubmitFilesContent) toolPOJO;
+ Object toolPOJO = exportContentService.importToolContent(toolContentPath, sbmtToolContentHandler,
+ fromVersion, toVersion);
+ if (!(toolPOJO instanceof SubmitFilesContent)) {
+ throw new ImportToolContentException("Import Submit tool content failed. Deserialized object is "
+ + toolPOJO);
+ }
+ SubmitFilesContent toolContentObj = (SubmitFilesContent) toolPOJO;
- //reset it to new toolContentId
- toolContentObj.setContentID(toolContentId);
+ // reset it to new toolContentId
+ toolContentObj.setContentID(toolContentId);
- SubmitUser user = submitUserDAO.getContentUser(toolContentId, newUserUid);
- if (user == null) {
- user = new SubmitUser();
- UserDTO sysUser = ((User) userManagementService.findById(User.class, newUserUid)).getUserDTO();
- user.setFirstName(sysUser.getFirstName());
- user.setLastName(sysUser.getLastName());
- user.setLogin(sysUser.getLogin());
- user.setUserID(newUserUid);
- user.setContentID(toolContentId);
- submitUserDAO.saveOrUpdateUser(user);
- }
+ SubmitUser user = submitUserDAO.getContentUser(toolContentId, newUserUid);
+ if (user == null) {
+ user = new SubmitUser();
+ UserDTO sysUser = ((User) userManagementService.findById(User.class, newUserUid)).getUserDTO();
+ user.setFirstName(sysUser.getFirstName());
+ user.setLastName(sysUser.getLastName());
+ user.setLogin(sysUser.getLogin());
+ user.setUserID(newUserUid);
+ user.setContentID(toolContentId);
+ submitUserDAO.saveOrUpdateUser(user);
+ }
- toolContentObj.setCreatedBy(user);
- toolContentObj.setCreated(new Date());
- toolContentObj.setUpdated(new Date());
+ toolContentObj.setCreatedBy(user);
+ toolContentObj.setCreated(new Date());
+ toolContentObj.setUpdated(new Date());
- submitFilesContentDAO.saveOrUpdate(toolContentObj);
- }
- catch (ImportToolContentException e) {
- throw new ToolException(e);
- }
+ submitFilesContentDAO.saveOrUpdate(toolContentObj);
+ } catch (ImportToolContentException e) {
+ throw new ToolException(e);
}
+ }
- /** Get the definitions for possible output for an activity, based on the toolContentId. These may be definitions that are always
- * available for the tool (e.g. number of marks for Multiple Choice) or a custom definition created for a particular activity
- * such as the answer to the third question contains the word Koala and hence the need for the toolContentId
- * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition
- */
- public SortedMap getToolOutputDefinitions(Long toolContentId) throws ToolException {
- return new TreeMap();
- }
+ /**
+ * Get the definitions for possible output for an activity, based on the toolContentId. These may be definitions
+ * that are always available for the tool (e.g. number of marks for Multiple Choice) or a custom definition created
+ * for a particular activity such as the answer to the third question contains the word Koala and hence the need for
+ * the toolContentId
+ *
+ * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition
+ */
+ public SortedMap getToolOutputDefinitions(Long toolContentId) throws ToolException {
+ return new TreeMap();
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#updateSubmitFilesContent(org.lamsfoundation.lams.tool.sbmt.SubmitFilesContent)
- */
- public void saveOrUpdateContent(SubmitFilesContent submitFilesContent) {
- submitFilesContent.setUpdated(new Date());
- submitFilesContentDAO.saveOrUpdate(submitFilesContent);
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#updateSubmitFilesContent(org.lamsfoundation.lams.tool.sbmt.SubmitFilesContent)
+ */
+ public void saveOrUpdateContent(SubmitFilesContent submitFilesContent) {
+ submitFilesContent.setUpdated(new Date());
+ submitFilesContentDAO.saveOrUpdate(submitFilesContent);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#getSubmitFilesContent(java.lang.Long)
+ */
+ public SubmitFilesContent getSubmitFilesContent(Long contentID) {
+ SubmitFilesContent content = null;
+ try {
+ content = submitFilesContentDAO.getContentByID(contentID);
+ } catch (Exception e) {
+ SubmitFilesService.log.error("Could not find the content by given ID:" + contentID + ". Excpetion is " + e);
}
+ if (content == null) {
+ SubmitFilesService.log.error("Could not find the content by given ID:" + contentID);
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#getSubmitFilesContent(java.lang.Long)
- */
- public SubmitFilesContent getSubmitFilesContent(Long contentID) {
- SubmitFilesContent content = null;
- try {
- content = submitFilesContentDAO.getContentByID(contentID);
- }
- catch (Exception e) {
- SubmitFilesService.log.error("Could not find the content by given ID:" + contentID + ". Excpetion is " + e);
- }
- if (content == null) {
- SubmitFilesService.log.error("Could not find the content by given ID:" + contentID);
- }
+ return content;
+ }
- return content;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#getSubmitFilesReport(java.lang.Long)
+ */
+ public SubmitFilesReport getSubmitFilesReport(Long reportID) {
+ return submitFilesReportDAO.getReportByID(reportID);
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#getSubmitFilesReport(java.lang.Long)
- */
- public SubmitFilesReport getSubmitFilesReport(Long reportID) {
- return submitFilesReportDAO.getReportByID(reportID);
+ /**
+ * This method verifies the credentials of the SubmitFiles Tool and gives it the Ticket
to login and
+ * access the Content Repository.
+ *
+ * A valid ticket is needed in order to access the content from the repository. This method would be called evertime
+ * the tool needs to upload/download files from the content repository.
+ *
+ * @return ITicket The ticket for repostory access
+ * @throws SubmitFilesException
+ */
+ private ITicket getRepositoryLoginTicket() throws SubmitFilesException {
+ repositoryService = RepositoryProxy.getRepositoryService();
+ ICredentials credentials = new SimpleCredentials(SbmtToolContentHandler.repositoryUser,
+ SbmtToolContentHandler.repositoryId);
+ try {
+ ITicket ticket = repositoryService.login(credentials, SbmtToolContentHandler.repositoryWorkspaceName);
+ return ticket;
+ } catch (AccessDeniedException ae) {
+ throw new SubmitFilesException("Access Denied to repository." + ae.getMessage());
+ } catch (WorkspaceNotFoundException we) {
+ throw new SubmitFilesException("Workspace not found." + we.getMessage());
+ } catch (LoginException e) {
+ throw new SubmitFilesException("Login failed." + e.getMessage());
}
+ }
- /**
- * This method verifies the credentials of the SubmitFiles Tool and gives it
- * the Ticket
to login and access the Content Repository.
- *
- * A valid ticket is needed in order to access the content from the
- * repository. This method would be called evertime the tool needs to
- * upload/download files from the content repository.
- *
- * @return ITicket The ticket for repostory access
- * @throws SubmitFilesException
- */
- private ITicket getRepositoryLoginTicket() throws SubmitFilesException {
- repositoryService = RepositoryProxy.getRepositoryService();
- ICredentials credentials = new SimpleCredentials(SbmtToolContentHandler.repositoryUser,
- SbmtToolContentHandler.repositoryId);
- try {
- ITicket ticket = repositoryService.login(credentials, SbmtToolContentHandler.repositoryWorkspaceName);
- return ticket;
- }
- catch (AccessDeniedException ae) {
- throw new SubmitFilesException("Access Denied to repository." + ae.getMessage());
- }
- catch (WorkspaceNotFoundException we) {
- throw new SubmitFilesException("Workspace not found." + we.getMessage());
- }
- catch (LoginException e) {
- throw new SubmitFilesException("Login failed." + e.getMessage());
- }
+ /**
+ * This method deletes the content with the given uuid
and versionID
from the content
+ * repository
+ *
+ * @param uuid
+ * The uuid
of the node to be deleted
+ * @param versionID
+ * The version_id
of the node to be deleted.
+ * @throws SubmitFilesException
+ */
+ public void deleteFromRepository(Long uuid, Long versionID) throws SubmitFilesException {
+ ITicket ticket = getRepositoryLoginTicket();
+ try {
+ repositoryService.deleteVersion(ticket, uuid, versionID);
+ } catch (Exception e) {
+ throw new SubmitFilesException("Exception occured while deleting files from" + " the repository "
+ + e.getMessage());
}
+ }
- /**
- * This method deletes the content with the given uuid
and
- * versionID
from the content repository
- *
- * @param uuid
- * The uuid
of the node to be deleted
- * @param versionID
- * The version_id
of the node to be deleted.
- * @throws SubmitFilesException
- */
- public void deleteFromRepository(Long uuid, Long versionID) throws SubmitFilesException {
- ITicket ticket = getRepositoryLoginTicket();
- try {
- repositoryService.deleteVersion(ticket, uuid, versionID);
- }
- catch (Exception e) {
- throw new SubmitFilesException("Exception occured while deleting files from" + " the repository " + e.getMessage());
- }
- }
+ public void deleteInstructionFile(Long uid) {
+ attachmentDAO.deleteById(InstructionFiles.class, uid);
+ }
- public void deleteInstructionFile(Long uid) {
- attachmentDAO.deleteById(InstructionFiles.class, uid);
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.ToolSessionManager#createToolSession(java.lang.Long,java.lang.String,
+ * java.lang.Long)
+ */
+ public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) {
+ // pre-condition validation
+ if (toolSessionId == null || toolContentId == null) {
+ throw new SubmitFilesException("Fail to create a submission session"
+ + " based on null toolSessionId or toolContentId");
}
- /*
- * (non-Javadoc)
- *
- * @see org.lamsfoundation.lams.tool.ToolSessionManager#createToolSession(java.lang.Long,java.lang.String,
- * java.lang.Long)
- */
- public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) {
- //pre-condition validation
- if (toolSessionId == null || toolContentId == null) {
- throw new SubmitFilesException("Fail to create a submission session"
- + " based on null toolSessionId or toolContentId");
- }
+ SubmitFilesService.log.debug("Start to create submission session based on toolSessionId["
+ + toolSessionId.longValue() + "] and toolContentId[" + toolContentId.longValue() + "]");
+ try {
+ SubmitFilesContent submitContent = getSubmitFilesContent(toolContentId);
+ if (submitContent == null || !toolContentId.equals(submitContent.getContentID())) {
+ submitContent = new SubmitFilesContent();
+ submitContent.setContentID(toolContentId);
+ }
+ SubmitFilesSession submitSession = new SubmitFilesSession();
- SubmitFilesService.log.debug("Start to create submission session based on toolSessionId[" + toolSessionId.longValue()
- + "] and toolContentId[" + toolContentId.longValue() + "]");
- try {
- SubmitFilesContent submitContent = getSubmitFilesContent(toolContentId);
- if (submitContent == null || !toolContentId.equals(submitContent.getContentID())) {
- submitContent = new SubmitFilesContent();
- submitContent.setContentID(toolContentId);
- }
- SubmitFilesSession submitSession = new SubmitFilesSession();
-
- submitSession.setSessionID(toolSessionId);
- submitSession.setSessionName(toolSessionName);
- submitSession.setStatus(new Integer(SubmitFilesSession.INCOMPLETE));
- submitSession.setContent(submitContent);
- submitFilesSessionDAO.createSession(submitSession);
- SubmitFilesService.log.debug("Submit File session created");
- }
- catch (DataAccessException e) {
- throw new SubmitFilesException(
- "Exception occured when lams is creating" + " a submission Session: " + e.getMessage(), e);
- }
-
+ submitSession.setSessionID(toolSessionId);
+ submitSession.setSessionName(toolSessionName);
+ submitSession.setStatus(new Integer(SubmitFilesSession.INCOMPLETE));
+ submitSession.setContent(submitContent);
+ submitFilesSessionDAO.createSession(submitSession);
+ SubmitFilesService.log.debug("Submit File session created");
+ } catch (DataAccessException e) {
+ throw new SubmitFilesException("Exception occured when lams is creating" + " a submission Session: "
+ + e.getMessage(), e);
}
- /*
- * (non-Javadoc)
- *
- * @see org.lamsfoundation.lams.tool.ToolSessionManager#leaveToolSession(java.lang.Long,
- * org.lamsfoundation.lams.usermanagement.User)
- */
- public String leaveToolSession(Long toolSessionId, Long learnerId) throws DataMissingException, ToolException {
- if (toolSessionId == null) {
- SubmitFilesService.log.error("Fail to leave tool Session based on null tool session id.");
- throw new ToolException("Fail to remove tool Session based on null tool session id.");
- }
- if (learnerId == null) {
- SubmitFilesService.log.error("Fail to leave tool Session based on null learner.");
- throw new ToolException("Fail to remove tool Session based on null learner.");
- }
+ }
- SubmitFilesSession session = submitFilesSessionDAO.getSessionByID(toolSessionId);
- if (session != null) {
- session.setStatus(new Integer(SubmitFilesSession.COMPLETED));
- submitFilesSessionDAO.update(session);
- }
- else {
- SubmitFilesService.log.error("Fail to leave tool Session.Could not find submit file "
- + "session by given session id: " + toolSessionId);
- throw new DataMissingException("Fail to leave tool Session."
- + "Could not find submit file session by given session id: " + toolSessionId);
- }
- return learnerService.completeToolSession(toolSessionId, learnerId);
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.ToolSessionManager#leaveToolSession(java.lang.Long,
+ * org.lamsfoundation.lams.usermanagement.User)
+ */
+ public String leaveToolSession(Long toolSessionId, Long learnerId) throws DataMissingException, ToolException {
+ if (toolSessionId == null) {
+ SubmitFilesService.log.error("Fail to leave tool Session based on null tool session id.");
+ throw new ToolException("Fail to remove tool Session based on null tool session id.");
}
-
- /**
- * (non-Javadoc)
- *
- * @see org.lamsfoundation.lams.tool.ToolSessionManager#exportToolSession(java.lang.Long)
- */
- public ToolSessionExportOutputData exportToolSession(Long toolSessionId) {
- // TODO Auto-generated method stub
- return null;
+ if (learnerId == null) {
+ SubmitFilesService.log.error("Fail to leave tool Session based on null learner.");
+ throw new ToolException("Fail to remove tool Session based on null learner.");
}
- /**
- * (non-Javadoc)
- *
- * @see org.lamsfoundation.lams.tool.ToolSessionManager#exportToolSession(java.util.List)
- */
- public ToolSessionExportOutputData exportToolSession(List toolSessionIds) {
- // TODO Auto-generated method stub
- return null;
+ SubmitFilesSession session = submitFilesSessionDAO.getSessionByID(toolSessionId);
+ if (session != null) {
+ session.setStatus(new Integer(SubmitFilesSession.COMPLETED));
+ submitFilesSessionDAO.update(session);
+ } else {
+ SubmitFilesService.log.error("Fail to leave tool Session.Could not find submit file "
+ + "session by given session id: " + toolSessionId);
+ throw new DataMissingException("Fail to leave tool Session."
+ + "Could not find submit file session by given session id: " + toolSessionId);
}
+ return learnerService.completeToolSession(toolSessionId, learnerId);
+ }
- /**
- * (non-Javadoc)
- *
- * @see org.lamsfoundation.lams.tool.ToolSessionManager#removeToolSession(java.lang.Long)
- */
- public void removeToolSession(Long toolSessionId) throws DataMissingException, ToolException {
- if (toolSessionId == null) {
- SubmitFilesService.log.error("Fail to remove tool Session based on null tool session id.");
- throw new ToolException("Fail to remove tool Session based on null tool session id.");
- }
+ /**
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.ToolSessionManager#exportToolSession(java.lang.Long)
+ */
+ public ToolSessionExportOutputData exportToolSession(Long toolSessionId) {
+ // TODO Auto-generated method stub
+ return null;
+ }
- SubmitFilesSession session = submitFilesSessionDAO.getSessionByID(toolSessionId);
- if (session != null) {
- removeToolSession(session);
- }
- else {
- SubmitFilesService.log.error("Could not find submit file session by given session id: " + toolSessionId);
- throw new DataMissingException("Could not find submit file session by given session id: " + toolSessionId);
- }
+ /**
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.ToolSessionManager#exportToolSession(java.util.List)
+ */
+ public ToolSessionExportOutputData exportToolSession(List toolSessionIds) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ /**
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.ToolSessionManager#removeToolSession(java.lang.Long)
+ */
+ public void removeToolSession(Long toolSessionId) throws DataMissingException, ToolException {
+ if (toolSessionId == null) {
+ SubmitFilesService.log.error("Fail to remove tool Session based on null tool session id.");
+ throw new ToolException("Fail to remove tool Session based on null tool session id.");
}
- /** Remove a tool session. The session parameter must not be null. */
- private void removeToolSession(SubmitFilesSession session) {
- Set filesUploaded = session.getSubmissionDetails();
- if (filesUploaded != null) {
- Iterator fileIterator = filesUploaded.iterator();
- while (fileIterator.hasNext()) {
- SubmissionDetails details = (SubmissionDetails) fileIterator.next();
- deleteFromRepository(details.getUuid(), details.getVersionID());
- submissionDetailsDAO.delete(details);
- }
- }
- submitFilesSessionDAO.delete(session);
+ SubmitFilesSession session = submitFilesSessionDAO.getSessionByID(toolSessionId);
+ if (session != null) {
+ removeToolSession(session);
+ } else {
+ SubmitFilesService.log.error("Could not find submit file session by given session id: " + toolSessionId);
+ throw new DataMissingException("Could not find submit file session by given session id: " + toolSessionId);
}
+ }
- /**
- * Get the tool output for the given tool output names.
- * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.util.List, java.lang.Long, java.lang.Long)
- */
- public SortedMap getToolOutput(List names, Long toolSessionId, Long learnerId) {
- return new TreeMap();
+ /** Remove a tool session. The session parameter must not be null. */
+ private void removeToolSession(SubmitFilesSession session) {
+ Set filesUploaded = session.getSubmissionDetails();
+ if (filesUploaded != null) {
+ Iterator fileIterator = filesUploaded.iterator();
+ while (fileIterator.hasNext()) {
+ SubmissionDetails details = (SubmissionDetails) fileIterator.next();
+ deleteFromRepository(details.getUuid(), details.getVersionID());
+ submissionDetailsDAO.delete(details);
+ }
}
+ submitFilesSessionDAO.delete(session);
+ }
- /**
- * Get the tool output for the given tool output name.
- * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.lang.String, java.lang.Long, java.lang.Long)
- */
- public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) {
- return null;
+ /**
+ * Get the tool output for the given tool output names.
+ *
+ * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.util.List, java.lang.Long,
+ * java.lang.Long)
+ */
+ public SortedMap getToolOutput(List names, Long toolSessionId, Long learnerId) {
+ return new TreeMap();
+ }
+
+ /**
+ * Get the tool output for the given tool output name.
+ *
+ * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.lang.String, java.lang.Long,
+ * java.lang.Long)
+ */
+ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) {
+ return null;
+ }
+
+ /**
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.ToolSessionManager# uploadFileToContent(Long,FormFile )
+ */
+ public InstructionFiles uploadFileToContent(Long contentID, FormFile uploadFile, String fileType)
+ throws SubmitFilesException {
+ if (uploadFile == null || StringUtils.isEmpty(uploadFile.getFileName())) {
+ throw new SubmitFilesException("Could not find upload file: " + uploadFile);
}
- /**
- * (non-Javadoc)
- *
- * @see org.lamsfoundation.lams.tool.ToolSessionManager# uploadFileToContent(Long,FormFile )
- */
- public InstructionFiles uploadFileToContent(Long contentID, FormFile uploadFile, String fileType) throws SubmitFilesException {
- if (uploadFile == null || StringUtils.isEmpty(uploadFile.getFileName())) {
- throw new SubmitFilesException("Could not find upload file: " + uploadFile);
- }
+ NodeKey nodeKey = processFile(uploadFile, fileType);
- NodeKey nodeKey = processFile(uploadFile, fileType);
+ InstructionFiles file = new InstructionFiles();
+ file.setType(fileType);
+ file.setUuID(nodeKey.getUuid());
+ file.setVersionID(nodeKey.getVersion());
+ file.setName(uploadFile.getFileName());
- InstructionFiles file = new InstructionFiles();
- file.setType(fileType);
- file.setUuID(nodeKey.getUuid());
- file.setVersionID(nodeKey.getVersion());
- file.setName(uploadFile.getFileName());
+ return file;
+ }
- return file;
+ /**
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.ToolSessionManager# uploadFileToSession(Long,FormFile,String,Long )
+ */
+ public void uploadFileToSession(Long sessionID, FormFile uploadFile, String fileDescription, Integer userID)
+ throws SubmitFilesException {
+
+ if (uploadFile == null || StringUtils.isEmpty(uploadFile.getFileName())) {
+ throw new SubmitFilesException("Could not find upload file: " + uploadFile);
}
- /**
- * (non-Javadoc)
- *
- * @see org.lamsfoundation.lams.tool.ToolSessionManager# uploadFileToSession(Long,FormFile,String,Long )
- */
- public void uploadFileToSession(Long sessionID, FormFile uploadFile, String fileDescription, Integer userID)
- throws SubmitFilesException {
+ SubmitFilesSession session = submitFilesSessionDAO.getSessionByID(sessionID);
+ if (session == null) {
+ throw new SubmitFilesException("No such session with a sessionID of: " + sessionID + " found.");
+ }
- if (uploadFile == null || StringUtils.isEmpty(uploadFile.getFileName())) {
- throw new SubmitFilesException("Could not find upload file: " + uploadFile);
- }
+ NodeKey nodeKey = processFile(uploadFile, IToolContentHandler.TYPE_ONLINE);
- SubmitFilesSession session = submitFilesSessionDAO.getSessionByID(sessionID);
- if (session == null) {
- throw new SubmitFilesException("No such session with a sessionID of: " + sessionID + " found.");
- }
+ SubmissionDetails details = new SubmissionDetails();
+ details.setFileDescription(fileDescription);
+ details.setFilePath(uploadFile.getFileName());
+ details.setDateOfSubmission(new Date());
- NodeKey nodeKey = processFile(uploadFile, IToolContentHandler.TYPE_ONLINE);
+ SubmitUser learner = submitUserDAO.getLearner(sessionID, userID);
+ details.setLearner(learner);
+ details.setUuid(nodeKey.getUuid());
+ details.setVersionID(nodeKey.getVersion());
+ SubmitFilesReport report = new SubmitFilesReport();
+ details.setReport(report);
+ details.setSubmitFileSession(session);
- SubmissionDetails details = new SubmissionDetails();
- details.setFileDescription(fileDescription);
- details.setFilePath(uploadFile.getFileName());
- details.setDateOfSubmission(new Date());
+ // update session, then insert the detail too.
+ Set detailSet = session.getSubmissionDetails();
+ detailSet.add(details);
+ session.setSubmissionDetails(detailSet);
+ submissionDetailsDAO.saveOrUpdate(session);
- SubmitUser learner = submitUserDAO.getLearner(sessionID, userID);
- details.setLearner(learner);
- details.setUuid(nodeKey.getUuid());
- details.setVersionID(nodeKey.getVersion());
- SubmitFilesReport report = new SubmitFilesReport();
- details.setReport(report);
- details.setSubmitFileSession(session);
+ }
- //update session, then insert the detail too.
- Set detailSet = session.getSubmissionDetails();
- detailSet.add(details);
- session.setSubmissionDetails(detailSet);
- submissionDetailsDAO.saveOrUpdate(session);
+ /**
+ * Process an uploaded file.
+ *
+ * @param forumForm
+ * @throws FileNotFoundException
+ * @throws IOException
+ * @throws RepositoryCheckedException
+ * @throws InvalidParameterException
+ */
+ private NodeKey processFile(FormFile file, String fileType) {
+ NodeKey node = null;
+ if (file != null && !StringUtils.isEmpty(file.getFileName())) {
+ String fileName = file.getFileName();
+ try {
+ node = getSbmtToolContentHandler().uploadFile(file.getInputStream(), fileName, file.getContentType(),
+ fileType);
+ } catch (InvalidParameterException e) {
+ throw new SubmitFilesException("FileNotFoundException occured while trying to upload File"
+ + e.getMessage());
+ } catch (FileNotFoundException e) {
+ throw new SubmitFilesException("FileNotFoundException occured while trying to upload File"
+ + e.getMessage());
+ } catch (RepositoryCheckedException e) {
+ throw new SubmitFilesException("FileNotFoundException occured while trying to upload File"
+ + e.getMessage());
+ } catch (IOException e) {
+ throw new SubmitFilesException("FileNotFoundException occured while trying to upload File"
+ + e.getMessage());
+ }
+ }
+ return node;
+ }
+ /**
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#getFilesUploadedByUserForContent(java.lang.Long,
+ * java.lang.Long)
+ */
+ public List getFilesUploadedByUser(Integer userID, Long sessionID, Locale currentLocale) {
+ List list = submissionDetailsDAO.getBySessionAndLearner(sessionID, userID);
+ SortedSet details = new TreeSet(this.new FileDtoComparator());
+ if (list == null) {
+ return new ArrayList(details);
}
- /**
- * Process an uploaded file.
- *
- * @param forumForm
- * @throws FileNotFoundException
- * @throws IOException
- * @throws RepositoryCheckedException
- * @throws InvalidParameterException
- */
- private NodeKey processFile(FormFile file, String fileType) {
- NodeKey node = null;
- if (file != null && !StringUtils.isEmpty(file.getFileName())) {
- String fileName = file.getFileName();
- try {
- node = getSbmtToolContentHandler().uploadFile(file.getInputStream(), fileName, file.getContentType(), fileType);
- }
- catch (InvalidParameterException e) {
- throw new SubmitFilesException("FileNotFoundException occured while trying to upload File" + e.getMessage());
- }
- catch (FileNotFoundException e) {
- throw new SubmitFilesException("FileNotFoundException occured while trying to upload File" + e.getMessage());
- }
- catch (RepositoryCheckedException e) {
- throw new SubmitFilesException("FileNotFoundException occured while trying to upload File" + e.getMessage());
- }
- catch (IOException e) {
- throw new SubmitFilesException("FileNotFoundException occured while trying to upload File" + e.getMessage());
- }
- }
- return node;
+ NumberFormat numberFormat = currentLocale != null ? NumberFormat.getInstance(currentLocale) : null;
+ for (SubmissionDetails submissionDetails : list) {
+ FileDetailsDTO detailDto = new FileDetailsDTO(submissionDetails, numberFormat);
+ details.add(detailDto);
}
+ return new ArrayList(details);
+ }
- /**
- * (non-Javadoc)
- * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#getFilesUploadedByUserForContent(java.lang.Long, java.lang.Long)
- */
- public List getFilesUploadedByUser(Integer userID, Long sessionID, Locale currentLocale) {
- List list = submissionDetailsDAO.getBySessionAndLearner(sessionID, userID);
- SortedSet details = new TreeSet(this.new FileDtoComparator());
- if (list == null) {
- return new ArrayList(details);
+ /**
+ * This method save SubmissionDetails list into a map container: key is user id, value is a list container, which
+ * contains all FileDetailsDTO
object belong to this user.
+ */
+ public SortedMap getFilesUploadedBySession(Long sessionID, Locale currentLocale) {
+ List list = submissionDetailsDAO.getSubmissionDetailsBySession(sessionID);
+ if (list != null) {
+ SortedMap map = new TreeMap(new LastNameAlphabeticComparator());
+ Iterator iterator = list.iterator();
+ List userFileList;
+ NumberFormat numberFormat = currentLocale != null ? NumberFormat.getInstance(currentLocale) : null;
+ while (iterator.hasNext()) {
+ SubmissionDetails submissionDetails = (SubmissionDetails) iterator.next();
+ SubmitUser learner = submissionDetails.getLearner();
+ if (learner == null) {
+ SubmitFilesService.log.error("Could not find learer for special submission item:"
+ + submissionDetails);
+ return null;
}
+ SubmitUserDTO submitUserDTO = new SubmitUserDTO(learner);
- NumberFormat numberFormat = currentLocale != null ? NumberFormat.getInstance(currentLocale) : null;
- for (SubmissionDetails submissionDetails : list) {
- FileDetailsDTO detailDto = new FileDetailsDTO(submissionDetails, numberFormat);
- details.add(detailDto);
+ FileDetailsDTO detailDto = new FileDetailsDTO(submissionDetails, numberFormat);
+ userFileList = (List) map.get(submitUserDTO);
+ // if it is first time to this user, creating a new ArrayList for this user.
+ if (userFileList == null) {
+ userFileList = new ArrayList();
}
- return new ArrayList(details);
+ userFileList.add(detailDto);
+ map.put(submitUserDTO, userFileList);
+ }
+ return map;
+ } else {
+ return null;
}
+ }
- /**
- * This method save SubmissionDetails list into a map container: key is user id,
- * value is a list container, which contains all FileDetailsDTO
object belong to
- * this user.
- */
- public SortedMap getFilesUploadedBySession(Long sessionID, Locale currentLocale) {
- List list = submissionDetailsDAO.getSubmissionDetailsBySession(sessionID);
- if (list != null) {
- SortedMap map = new TreeMap(new LastNameAlphabeticComparator());
- Iterator iterator = list.iterator();
- List userFileList;
- NumberFormat numberFormat = currentLocale != null ? NumberFormat.getInstance(currentLocale) : null;
- while (iterator.hasNext()) {
- SubmissionDetails submissionDetails = (SubmissionDetails) iterator.next();
- SubmitUser learner = submissionDetails.getLearner();
- if (learner == null) {
- SubmitFilesService.log.error("Could not find learer for special submission item:" + submissionDetails);
- return null;
- }
- SubmitUserDTO submitUserDTO = new SubmitUserDTO(learner);
+ public FileDetailsDTO getFileDetails(Long detailID, Locale currentLocale) {
+ SubmissionDetails details = submissionDetailsDAO.getSubmissionDetailsByID(detailID);
+ return new FileDetailsDTO(details, currentLocale != null ? NumberFormat.getInstance(currentLocale) : null);
+ }
- FileDetailsDTO detailDto = new FileDetailsDTO(submissionDetails, numberFormat);
- userFileList = (List) map.get(submitUserDTO);
- //if it is first time to this user, creating a new ArrayList for this user.
- if (userFileList == null) {
- userFileList = new ArrayList();
- }
- userFileList.add(detailDto);
- map.put(submitUserDTO, userFileList);
- }
- return map;
- }
- else {
- return null;
- }
- }
+ /**
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#getUsersBySession(java.lang.Long)
+ */
+ public List getUsersBySession(Long sessionID) {
+ return submitUserDAO.getUsersBySession(sessionID);
+ }
- public FileDetailsDTO getFileDetails(Long detailID, Locale currentLocale) {
- SubmissionDetails details = submissionDetailsDAO.getSubmissionDetailsByID(detailID);
- return new FileDetailsDTO(details, currentLocale != null ? NumberFormat.getInstance(currentLocale) : null);
+ public void updateMarks(Long reportID, Float marks, String comments) {
+ SubmitFilesReport report = submitFilesReportDAO.getReportByID(reportID);
+ if (report != null) {
+ report.setComments(comments);
+ report.setMarks(marks);
+ submitFilesReportDAO.update(report);
}
+ }
- /**
- * (non-Javadoc)
- * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#getUsersBySession(java.lang.Long)
- */
- public List getUsersBySession(Long sessionID) {
- return submitUserDAO.getUsersBySession(sessionID);
+ public IVersionedNode downloadFile(Long uuid, Long versionID) throws SubmitFilesException {
+ ITicket ticket = getRepositoryLoginTicket();
+ try {
+ IVersionedNode node = repositoryService.getFileItem(ticket, uuid, null);
+ return node;
+ } catch (AccessDeniedException ae) {
+ throw new SubmitFilesException("AccessDeniedException occured while trying to download file "
+ + ae.getMessage());
+ } catch (FileException fe) {
+ throw new SubmitFilesException("FileException occured while trying to download file " + fe.getMessage());
+ } catch (ItemNotFoundException ie) {
+ throw new SubmitFilesException("ItemNotFoundException occured while trying to download file "
+ + ie.getMessage());
}
+ }
- public void updateMarks(Long reportID, Float marks, String comments) {
- SubmitFilesReport report = submitFilesReportDAO.getReportByID(reportID);
- if (report != null) {
- report.setComments(comments);
- report.setMarks(marks);
- submitFilesReportDAO.update(report);
- }
- }
+ public SubmitFilesSession getSessionById(Long sessionID) {
+ return submitFilesSessionDAO.getSessionByID(sessionID);
+ }
- public IVersionedNode downloadFile(Long uuid, Long versionID) throws SubmitFilesException {
- ITicket ticket = getRepositoryLoginTicket();
- try {
- IVersionedNode node = repositoryService.getFileItem(ticket, uuid, null);
- return node;
+ public boolean releaseMarksForSession(Long sessionID) {
+ List list = submissionDetailsDAO.getSubmissionDetailsBySession(sessionID);
+ Iterator iter = list.iterator();
+ SubmissionDetails details;
+ SubmitFilesReport report;
+ SubmitFilesSession session = getSessionById(sessionID);
+
+ SubmitFilesContent content = session.getContent();
+ boolean notifyLearnersOnMarkRelease = getEventNotificationService().eventExists(SbmtConstants.TOOL_SIGNATURE,
+ SbmtConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, content.getContentID());
+ Map notificationMessages = null;
+ Object[] notificationMessageParameters = null;
+ if (notifyLearnersOnMarkRelease) {
+ notificationMessages = new TreeMap();
+ notificationMessageParameters = new Object[3];
+ }
+ while (iter.hasNext()) {
+ details = (SubmissionDetails) iter.next();
+ report = details.getReport();
+ report.setDateMarksReleased(new Date());
+ if (notifyLearnersOnMarkRelease) {
+ SubmitUser user = details.getLearner();
+ StringBuilder notificationMessage = notificationMessages.get(user.getUserID().longValue());
+ if (notificationMessage == null) {
+ notificationMessage = new StringBuilder();
}
- catch (AccessDeniedException ae) {
- throw new SubmitFilesException("AccessDeniedException occured while trying to download file " + ae.getMessage());
- }
- catch (FileException fe) {
- throw new SubmitFilesException("FileException occured while trying to download file " + fe.getMessage());
- }
- catch (ItemNotFoundException ie) {
- throw new SubmitFilesException("ItemNotFoundException occured while trying to download file " + ie.getMessage());
- }
+ notificationMessageParameters[0] = details.getFilePath();
+ notificationMessageParameters[1] = details.getDateOfSubmission();
+ notificationMessageParameters[2] = report.getMarks();
+ notificationMessage
+ .append(getLocalisedMessage("event.mark.release.mark", notificationMessageParameters));
+ notificationMessages.put(user.getUserID().longValue(), notificationMessage);
+ }
+ submitFilesReportDAO.updateReport(report);
}
-
- public SubmitFilesSession getSessionById(Long sessionID) {
- return submitFilesSessionDAO.getSessionByID(sessionID);
+ // current there is no false return
+ if (notifyLearnersOnMarkRelease) {
+ notificationMessageParameters = new Object[1];
+ for (Long userID : notificationMessages.keySet()) {
+ notificationMessageParameters[0] = notificationMessages.get(userID).toString();
+ getEventNotificationService().triggerForSingleUser(SbmtConstants.TOOL_SIGNATURE,
+ SbmtConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, content.getContentID(), userID,
+ notificationMessageParameters);
+ }
}
+ return true;
+ }
- public boolean releaseMarksForSession(Long sessionID) {
- List list = submissionDetailsDAO.getSubmissionDetailsBySession(sessionID);
- Iterator iter = list.iterator();
- SubmissionDetails details;
- SubmitFilesReport report;
- SubmitFilesSession session = getSessionById(sessionID);
+ public void finishSubmission(Long sessionID, Integer userID) {
+ SubmitUser learner = submitUserDAO.getLearner(sessionID, userID);
+ learner.setFinished(true);
+ submitUserDAO.saveOrUpdateUser(learner);
+ }
- SubmitFilesContent content = session.getContent();
- boolean notifyLearnersOnMarkRelease = getEventNotificationService().eventExists(SbmtConstants.TOOL_SIGNATURE,
- SbmtConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, content.getContentID());
- Map notificationMessages = null;
- Object[] notificationMessageParameters = null;
- if (notifyLearnersOnMarkRelease) {
- notificationMessages = new TreeMap();
- notificationMessageParameters = new Object[3];
- }
- while (iter.hasNext()) {
- details = (SubmissionDetails) iter.next();
- report = details.getReport();
- report.setDateMarksReleased(new Date());
- if (notifyLearnersOnMarkRelease) {
- SubmitUser user = details.getLearner();
- StringBuilder notificationMessage = notificationMessages.get(user.getUserID().longValue());
- if (notificationMessage == null) {
- notificationMessage = new StringBuilder();
- }
- notificationMessageParameters[0] = details.getFilePath();
- notificationMessageParameters[1] = details.getDateOfSubmission();
- notificationMessageParameters[2] = report.getMarks();
- notificationMessage.append(getLocalisedMessage("event.mark.release.mark", notificationMessageParameters));
- notificationMessages.put(user.getUserID().longValue(), notificationMessage);
- }
- submitFilesReportDAO.updateReport(report);
- }
- //current there is no false return
- if (notifyLearnersOnMarkRelease) {
- notificationMessageParameters = new Object[1];
- for (Long userID : notificationMessages.keySet()) {
- notificationMessageParameters[0] = notificationMessages.get(userID).toString();
- getEventNotificationService().triggerForSingleUser(SbmtConstants.TOOL_SIGNATURE,
- SbmtConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, content.getContentID(), userID,
- notificationMessageParameters);
- }
- }
- return true;
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#getToolDefaultContentIdBySignature(java.lang.Long)
+ */
+ public Long getToolDefaultContentIdBySignature(String toolSignature) {
+ Long contentId = null;
+ contentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature));
+ if (contentId == null) {
+ String error = "Could not retrieve default content id for this tool";
+ SubmitFilesService.log.error(error);
+ throw new SubmitFilesException(error);
}
+ return contentId;
+ }
- public void finishSubmission(Long sessionID, Integer userID) {
- SubmitUser learner = submitUserDAO.getLearner(sessionID, userID);
- learner.setFinished(true);
- submitUserDAO.saveOrUpdateUser(learner);
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#createDefaultContent(java.lang.Long)
+ */
+ public SubmitFilesContent createDefaultContent(Long contentID) {
+ if (contentID == null) {
+ String error = "Could not retrieve default content id for this tool";
+ SubmitFilesService.log.error(error);
+ throw new SubmitFilesException(error);
}
+ SubmitFilesContent defaultContent = getDefaultSubmit();
- /* (non-Javadoc)
- * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#getToolDefaultContentIdBySignature(java.lang.Long)
- */
- public Long getToolDefaultContentIdBySignature(String toolSignature) {
- Long contentId = null;
- contentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature));
- if (contentId == null) {
- String error = "Could not retrieve default content id for this tool";
- SubmitFilesService.log.error(error);
- throw new SubmitFilesException(error);
- }
- return contentId;
- }
+ // save default content by given ID.
+ SubmitFilesContent content = new SubmitFilesContent();
+ content = SubmitFilesContent.newInstance(defaultContent, contentID, sbmtToolContentHandler);
+ content.setContentID(contentID);
- /* (non-Javadoc)
- * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#createDefaultContent(java.lang.Long)
- */
- public SubmitFilesContent createDefaultContent(Long contentID) {
- if (contentID == null) {
- String error = "Could not retrieve default content id for this tool";
- SubmitFilesService.log.error(error);
- throw new SubmitFilesException(error);
- }
- SubmitFilesContent defaultContent = getDefaultSubmit();
+ return content;
+ }
- //save default content by given ID.
- SubmitFilesContent content = new SubmitFilesContent();
- content = SubmitFilesContent.newInstance(defaultContent, contentID, sbmtToolContentHandler);
- content.setContentID(contentID);
-
- return content;
+ private SubmitFilesContent getDefaultSubmit() {
+ Long defaultToolContentId = getToolDefaultContentIdBySignature(SbmtConstants.TOOL_SIGNATURE);
+ SubmitFilesContent defaultContent = getSubmitFilesContent(defaultToolContentId);
+ if (defaultContent == null) {
+ String error = "Could not retrieve default content record for this tool";
+ SubmitFilesService.log.error(error);
+ throw new SubmitFilesException(error);
}
+ return defaultContent;
+ }
- private SubmitFilesContent getDefaultSubmit() {
- Long defaultToolContentId = getToolDefaultContentIdBySignature(SbmtConstants.TOOL_SIGNATURE);
- SubmitFilesContent defaultContent = getSubmitFilesContent(defaultToolContentId);
- if (defaultContent == null) {
- String error = "Could not retrieve default content record for this tool";
- SubmitFilesService.log.error(error);
- throw new SubmitFilesException(error);
- }
- return defaultContent;
+ public List getSubmitFilesSessionByContentID(Long contentID) {
+ List learners = submitFilesSessionDAO.getSubmitFilesSessionByContentID(contentID);
+ if (learners == null) {
+ learners = new ArrayList(); // return sized 0 list rather than null value
}
+ return learners;
+ }
- public List getSubmitFilesSessionByContentID(Long contentID) {
- List learners = submitFilesSessionDAO.getSubmitFilesSessionByContentID(contentID);
- if (learners == null) {
- learners = new ArrayList(); //return sized 0 list rather than null value
- }
- return learners;
- }
+ /* ===============Methods implemented from ToolContentImport102Manager =============== */
- /* ===============Methods implemented from ToolContentImport102Manager =============== */
+ /**
+ * Import the data for a 1.0.2 Noticeboard or HTMLNoticeboard
+ */
+ public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) {
+ Date now = new Date();
+ SubmitFilesContent toolContentObj = new SubmitFilesContent();
- /**
- * Import the data for a 1.0.2 Noticeboard or HTMLNoticeboard
- */
- public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) {
- Date now = new Date();
- SubmitFilesContent toolContentObj = new SubmitFilesContent();
+ toolContentObj.setTitle((String) importValues.get(ToolContentImport102Manager.CONTENT_TITLE));
+ toolContentObj.setContentID(toolContentId);
+ toolContentObj.setContentInUse(Boolean.FALSE);
+ toolContentObj.setCreated(now);
+ toolContentObj.setDefineLater(Boolean.FALSE);
+ toolContentObj.setInstruction(WebUtil.convertNewlines((String) importValues
+ .get(ToolContentImport102Manager.CONTENT_BODY)));
+ toolContentObj.setOfflineInstruction(null);
+ toolContentObj.setOnlineInstruction(null);
+ toolContentObj.setRunOffline(Boolean.FALSE);
+ toolContentObj.setUpdated(now);
+ // 1.0.2 doesn't allow users to go back after completion, which is the equivalent of lock on finish.
+ toolContentObj.setLockOnFinished(Boolean.TRUE);
+ toolContentObj.setReflectOnActivity(Boolean.FALSE);
+ toolContentObj.setReflectInstructions(null);
- toolContentObj.setTitle((String) importValues.get(ToolContentImport102Manager.CONTENT_TITLE));
- toolContentObj.setContentID(toolContentId);
- toolContentObj.setContentInUse(Boolean.FALSE);
- toolContentObj.setCreated(now);
- toolContentObj.setDefineLater(Boolean.FALSE);
- toolContentObj.setInstruction(WebUtil
- .convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY)));
- toolContentObj.setOfflineInstruction(null);
- toolContentObj.setOnlineInstruction(null);
- toolContentObj.setRunOffline(Boolean.FALSE);
- toolContentObj.setUpdated(now);
- // 1.0.2 doesn't allow users to go back after completion, which is the equivalent of lock on finish.
- toolContentObj.setLockOnFinished(Boolean.TRUE);
- toolContentObj.setReflectOnActivity(Boolean.FALSE);
- toolContentObj.setReflectInstructions(null);
+ SubmitUser suser = createContentUser(user, toolContentId);
+ toolContentObj.setCreatedBy(suser);
- SubmitUser suser = createContentUser(user, toolContentId);
- toolContentObj.setCreatedBy(suser);
+ // leave as empty, no need to set them to anything.
+ // toolContentObj.setInstructionFiles(attachments);
- // leave as empty, no need to set them to anything.
- //toolContentObj.setInstructionFiles(attachments);
+ submitFilesContentDAO.saveOrUpdate(toolContentObj);
+ }
- submitFilesContentDAO.saveOrUpdate(toolContentObj);
+ /** Set the description, throws away the title value as this is not supported in 2.0 */
+ public void setReflectiveData(Long toolContentId, String title, String description) throws ToolException,
+ DataMissingException {
+
+ SubmitFilesContent toolContentObj = getSubmitFilesContent(toolContentId);
+ if (toolContentObj == null) {
+ throw new DataMissingException("Unable to set reflective data titled " + title
+ + " on activity toolContentId " + toolContentId + " as the tool content does not exist.");
}
- /** Set the description, throws away the title value as this is not supported in 2.0 */
- public void setReflectiveData(Long toolContentId, String title, String description) throws ToolException,
- DataMissingException {
+ toolContentObj.setReflectOnActivity(Boolean.TRUE);
+ toolContentObj.setReflectInstructions(description);
+ }
- SubmitFilesContent toolContentObj = getSubmitFilesContent(toolContentId);
- if (toolContentObj == null) {
- throw new DataMissingException("Unable to set reflective data titled " + title + " on activity toolContentId "
- + toolContentId + " as the tool content does not exist.");
- }
+ public SubmitUser getUserByUid(Long learnerID) {
+ return (SubmitUser) submitUserDAO.find(SubmitUser.class, learnerID);
- toolContentObj.setReflectOnActivity(Boolean.TRUE);
- toolContentObj.setReflectInstructions(description);
- }
+ }
- public SubmitUser getUserByUid(Long learnerID) {
- return (SubmitUser) submitUserDAO.find(SubmitUser.class, learnerID);
-
+ public SubmitUser createSessionUser(UserDTO userDto, Long sessionID) {
+ SubmitUser learner = submitUserDAO.getLearner(sessionID, userDto.getUserID());
+ if (learner != null) {
+ return learner;
}
+ learner = new SubmitUser();
+ learner.setUserID(userDto.getUserID());
+ learner.setFirstName(userDto.getFirstName());
+ learner.setLastName(userDto.getLastName());
+ learner.setLogin(userDto.getLogin());
+ learner.setSessionID(sessionID);
+ learner.setFinished(false);
- public SubmitUser createSessionUser(UserDTO userDto, Long sessionID) {
- SubmitUser learner = submitUserDAO.getLearner(sessionID, userDto.getUserID());
- if (learner != null) {
- return learner;
- }
- learner = new SubmitUser();
- learner.setUserID(userDto.getUserID());
- learner.setFirstName(userDto.getFirstName());
- learner.setLastName(userDto.getLastName());
- learner.setLogin(userDto.getLogin());
- learner.setSessionID(sessionID);
- learner.setFinished(false);
+ submitUserDAO.saveOrUpdateUser(learner);
- submitUserDAO.saveOrUpdateUser(learner);
+ return learner;
+ }
- return learner;
- }
+ public SubmitUser getSessionUser(Long sessionID, Integer userID) {
+ return submitUserDAO.getLearner(sessionID, userID);
+ }
- public SubmitUser getSessionUser(Long sessionID, Integer userID) {
- return submitUserDAO.getLearner(sessionID, userID);
+ public SubmitUser createContentUser(UserDTO userDto, Long contentId) {
+ SubmitUser learner = submitUserDAO.getContentUser(contentId, userDto.getUserID());
+ if (learner != null) {
+ return learner;
}
+ learner = new SubmitUser();
+ learner.setUserID(userDto.getUserID());
+ learner.setFirstName(userDto.getFirstName());
+ learner.setLastName(userDto.getLastName());
+ learner.setLogin(userDto.getLogin());
+ learner.setContentID(contentId);
+ learner.setFinished(false);
- public SubmitUser createContentUser(UserDTO userDto, Long contentId) {
- SubmitUser learner = submitUserDAO.getContentUser(contentId, userDto.getUserID());
- if (learner != null) {
- return learner;
- }
- learner = new SubmitUser();
- learner.setUserID(userDto.getUserID());
- learner.setFirstName(userDto.getFirstName());
- learner.setLastName(userDto.getLastName());
- learner.setLogin(userDto.getLogin());
- learner.setContentID(contentId);
- learner.setFinished(false);
+ submitUserDAO.saveOrUpdateUser(learner);
+ return learner;
- submitUserDAO.saveOrUpdateUser(learner);
- return learner;
+ }
- }
+ public SubmitUser getContentUser(Long contentId, Integer userID) {
+ return submitUserDAO.getContentUser(contentId, userID);
+ }
- public SubmitUser getContentUser(Long contentId, Integer userID) {
- return submitUserDAO.getContentUser(contentId, userID);
- }
+ /*******************************************************************************************************************
+ * Property Injection Methods
+ ******************************************************************************************************************/
- /***************************************************************************
- * Property Injection Methods
- **************************************************************************/
+ /**
+ * @param submitFilesContentDAO
+ * The submitFilesContentDAO to set.
+ */
+ public void setSubmitFilesContentDAO(ISubmitFilesContentDAO submitFilesContentDAO) {
+ this.submitFilesContentDAO = submitFilesContentDAO;
+ }
- /**
- * @param submitFilesContentDAO
- * The submitFilesContentDAO to set.
- */
- public void setSubmitFilesContentDAO(ISubmitFilesContentDAO submitFilesContentDAO) {
- this.submitFilesContentDAO = submitFilesContentDAO;
- }
+ /**
+ * @param submitFilesReportDAO
+ * The submitFilesReportDAO to set.
+ */
+ public void setSubmitFilesReportDAO(ISubmitFilesReportDAO submitFilesReportDAO) {
+ this.submitFilesReportDAO = submitFilesReportDAO;
+ }
- /**
- * @param submitFilesReportDAO
- * The submitFilesReportDAO to set.
- */
- public void setSubmitFilesReportDAO(ISubmitFilesReportDAO submitFilesReportDAO) {
- this.submitFilesReportDAO = submitFilesReportDAO;
- }
+ /**
+ * @param submitFilesSessionDAO
+ * The submitFilesSessionDAO to set.
+ */
+ public void setSubmitFilesSessionDAO(ISubmitFilesSessionDAO submitFilesSessionDAO) {
+ this.submitFilesSessionDAO = submitFilesSessionDAO;
+ }
- /**
- * @param submitFilesSessionDAO
- * The submitFilesSessionDAO to set.
- */
- public void setSubmitFilesSessionDAO(ISubmitFilesSessionDAO submitFilesSessionDAO) {
- this.submitFilesSessionDAO = submitFilesSessionDAO;
- }
+ /**
+ * @param submissionDetailsDAO
+ * The submissionDetailsDAO to set.
+ */
+ public void setSubmissionDetailsDAO(ISubmissionDetailsDAO submissionDetailsDAO) {
+ this.submissionDetailsDAO = submissionDetailsDAO;
+ }
- /**
- * @param submissionDetailsDAO The submissionDetailsDAO to set.
- */
- public void setSubmissionDetailsDAO(ISubmissionDetailsDAO submissionDetailsDAO) {
- this.submissionDetailsDAO = submissionDetailsDAO;
- }
+ /**
+ * @return Returns the sbmtToolContentHandler.
+ */
+ public IToolContentHandler getSbmtToolContentHandler() {
+ return sbmtToolContentHandler;
+ }
- /**
- * @return Returns the sbmtToolContentHandler.
- */
- public IToolContentHandler getSbmtToolContentHandler() {
- return sbmtToolContentHandler;
- }
+ /**
+ * @param sbmtToolContentHandler
+ * The sbmtToolContentHandler to set.
+ */
+ public void setSbmtToolContentHandler(IToolContentHandler sbmtToolContentHandler) {
+ this.sbmtToolContentHandler = sbmtToolContentHandler;
+ }
- /**
- * @param sbmtToolContentHandler The sbmtToolContentHandler to set.
- */
- public void setSbmtToolContentHandler(IToolContentHandler sbmtToolContentHandler) {
- this.sbmtToolContentHandler = sbmtToolContentHandler;
- }
+ /**
+ * @return Returns the learnerDAO.
+ */
+ public ISubmitUserDAO getSubmitUserDAO() {
+ return submitUserDAO;
+ }
- /**
- * @return Returns the learnerDAO.
- */
- public ISubmitUserDAO getSubmitUserDAO() {
- return submitUserDAO;
- }
+ /**
+ * @param learnerDAO
+ * The learnerDAO to set.
+ */
+ public void setSubmitUserDAO(ISubmitUserDAO learnerDAO) {
+ submitUserDAO = learnerDAO;
+ }
- /**
- * @param learnerDAO The learnerDAO to set.
- */
- public void setSubmitUserDAO(ISubmitUserDAO learnerDAO) {
- submitUserDAO = learnerDAO;
- }
+ public ILearnerService getLearnerService() {
+ return learnerService;
+ }
- public ILearnerService getLearnerService() {
- return learnerService;
- }
+ public void setLearnerService(ILearnerService learnerService) {
+ this.learnerService = learnerService;
+ }
- public void setLearnerService(ILearnerService learnerService) {
- this.learnerService = learnerService;
- }
+ public ILamsToolService getToolService() {
+ return toolService;
+ }
- public ILamsToolService getToolService() {
- return toolService;
- }
+ public void setToolService(ILamsToolService toolService) {
+ this.toolService = toolService;
+ }
- public void setToolService(ILamsToolService toolService) {
- this.toolService = toolService;
- }
+ public IExportToolContentService getExportContentService() {
+ return exportContentService;
+ }
- public IExportToolContentService getExportContentService() {
- return exportContentService;
- }
+ public void setExportContentService(IExportToolContentService exportContentService) {
+ this.exportContentService = exportContentService;
+ }
- public void setExportContentService(IExportToolContentService exportContentService) {
- this.exportContentService = exportContentService;
- }
+ public ICoreNotebookService getCoreNotebookService() {
+ return coreNotebookService;
+ }
- public ICoreNotebookService getCoreNotebookService() {
- return coreNotebookService;
- }
+ public void setCoreNotebookService(ICoreNotebookService coreNotebookService) {
+ this.coreNotebookService = coreNotebookService;
+ }
- public void setCoreNotebookService(ICoreNotebookService coreNotebookService) {
- this.coreNotebookService = coreNotebookService;
- }
+ public void setAttachmentDAO(IAttachmentDAO attachmentDAO) {
+ this.attachmentDAO = attachmentDAO;
+ }
- public void setAttachmentDAO(IAttachmentDAO attachmentDAO) {
- this.attachmentDAO = attachmentDAO;
- }
+ public void setUserManagementService(IUserManagementService userManagementService) {
+ this.userManagementService = userManagementService;
+ }
- public void setUserManagementService(IUserManagementService userManagementService) {
- this.userManagementService = userManagementService;
- }
+ public IEventNotificationService getEventNotificationService() {
+ return eventNotificationService;
+ }
- public IEventNotificationService getEventNotificationService() {
- return eventNotificationService;
- }
+ public void setEventNotificationService(IEventNotificationService eventNotificationService) {
+ this.eventNotificationService = eventNotificationService;
+ }
- public void setEventNotificationService(IEventNotificationService eventNotificationService) {
- this.eventNotificationService = eventNotificationService;
- }
+ public String getLocalisedMessage(String key, Object[] args) {
+ return messageService.getMessage(key, args);
+ }
- public String getLocalisedMessage(String key, Object[] args) {
- return messageService.getMessage(key, args);
- }
+ public void setMessageService(MessageService messageService) {
+ this.messageService = messageService;
+ }
- public void setMessageService(MessageService messageService) {
- this.messageService = messageService;
- }
+ public List getMonitorsByToolSessionId(Long sessionId) {
+ return getLessonService().getMonitorsByToolSessionId(sessionId);
+ }
+
+ public ILessonService getLessonService() {
+ return lessonService;
+ }
+
+ public void setLessonService(ILessonService lessonService) {
+ this.lessonService = lessonService;
+ }
}
\ No newline at end of file
Index: lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/submitFilesApplicationContext.xml
===================================================================
diff -u -ra01292ae06e058ffcc16aaeec6d61959a7b69273 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/submitFilesApplicationContext.xml (.../submitFilesApplicationContext.xml) (revision a01292ae06e058ffcc16aaeec6d61959a7b69273)
+++ lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/submitFilesApplicationContext.xml (.../submitFilesApplicationContext.xml) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -70,6 +70,7 @@
+
Index: lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/web/LearnerAction.java
===================================================================
diff -u -r05ab55ef4acdc0c374af7405c58fb0e0fe8eb6b7 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/web/LearnerAction.java (.../LearnerAction.java) (revision 05ab55ef4acdc0c374af7405c58fb0e0fe8eb6b7)
+++ lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/web/LearnerAction.java (.../LearnerAction.java) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -43,6 +43,7 @@
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;
+import org.lamsfoundation.lams.events.DeliveryMethodMail;
import org.lamsfoundation.lams.events.IEventNotificationService;
import org.lamsfoundation.lams.notebook.model.NotebookEntry;
import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants;
@@ -60,6 +61,7 @@
import org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService;
import org.lamsfoundation.lams.tool.sbmt.service.SubmitFilesServiceProxy;
import org.lamsfoundation.lams.tool.sbmt.util.SbmtConstants;
+import org.lamsfoundation.lams.usermanagement.User;
import org.lamsfoundation.lams.usermanagement.dto.UserDTO;
import org.lamsfoundation.lams.util.FileUtil;
import org.lamsfoundation.lams.util.FileValidatorUtil;
@@ -72,359 +74,360 @@
/**
* @author Manpreet Minhas
* @author Steve.Ni
- * @struts.action
- * path="/learner"
- * parameter="method"
- * name="learnerForm"
- * input="/learner/sbmtlearner.jsp"
- * scope="request"
- * validate="false"
+ * @struts.action path="/learner" parameter="method" name="learnerForm" input="/learner/sbmtlearner.jsp" scope="request"
+ * validate="false"
*
* @struts.action-forward name="success" path="/learner/sbmtlearner.jsp"
* @struts.action-forward name="defineLater" path="/learner/definelater.jsp"
* @struts.action-forward name="runOffline" path="/learner/runoffline.jsp"
-
*
+ *
*/
public class LearnerAction extends DispatchAction {
- private static final boolean MODE_OPTIONAL = false;
+ private static final boolean MODE_OPTIONAL = false;
- public static Logger logger = Logger.getLogger(LearnerAction.class);
+ public static Logger logger = Logger.getLogger(LearnerAction.class);
- /**
- * The initial page of learner in Submission tool. This page will list all uploaded files and learn
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- @Override
- public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
- //initial session Map
- SessionMap sessionMap = new SessionMap();
- request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap);
- request.setAttribute(SbmtConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID());
- ((LearnerForm) form).setSessionMapID(sessionMap.getSessionID());
+ /**
+ * The initial page of learner in Submission tool. This page will list all uploaded files and learn
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ @Override
+ public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ // initial session Map
+ SessionMap sessionMap = new SessionMap();
+ request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap);
+ request.setAttribute(SbmtConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID());
+ ((LearnerForm) form).setSessionMapID(sessionMap.getSessionID());
- //get parameters from Request
- ToolAccessMode mode = null;
- try {
- mode = WebUtil.readToolAccessModeParam(request, AttributeNames.PARAM_MODE, LearnerAction.MODE_OPTIONAL);
- }
- catch (Exception e) {
- }
- if (mode == null) {
- mode = ToolAccessMode.LEARNER;
- }
+ // get parameters from Request
+ ToolAccessMode mode = null;
+ try {
+ mode = WebUtil.readToolAccessModeParam(request, AttributeNames.PARAM_MODE, LearnerAction.MODE_OPTIONAL);
+ } catch (Exception e) {
+ }
+ if (mode == null) {
+ mode = ToolAccessMode.LEARNER;
+ }
- Long sessionID = new Long(request.getParameter(AttributeNames.PARAM_TOOL_SESSION_ID));
+ Long sessionID = new Long(request.getParameter(AttributeNames.PARAM_TOOL_SESSION_ID));
- //get session from shared session.
- HttpSession ss = SessionManager.getSession();
+ // get session from shared session.
+ HttpSession ss = SessionManager.getSession();
- Integer userID = null;
- if (mode != null && mode.isTeacher()) {
- //monitoring mode - user is specified in URL
- userID = WebUtil.readIntParam(request, AttributeNames.PARAM_USER_ID, false);
- }
- else {
- UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
- userID = user.getUserID();
- }
+ Integer userID = null;
+ if (mode != null && mode.isTeacher()) {
+ // monitoring mode - user is specified in URL
+ userID = WebUtil.readIntParam(request, AttributeNames.PARAM_USER_ID, false);
+ } else {
+ UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
+ userID = user.getUserID();
+ }
- ISubmitFilesService submitFilesService = getService();
- SubmitFilesSession session = submitFilesService.getSessionById(sessionID);
- SubmitFilesContent content = session.getContent();
+ ISubmitFilesService submitFilesService = getService();
+ SubmitFilesSession session = submitFilesService.getSessionById(sessionID);
+ SubmitFilesContent content = session.getContent();
- //this must before getFileUploadByUser() method becuase getCurrentLearner()
- // will create session user if it does not exist.
- SubmitUser learner = getCurrentLearner(sessionID, submitFilesService);
- List filesUploaded = submitFilesService.getFilesUploadedByUser(userID, sessionID, request.getLocale());
+ // this must before getFileUploadByUser() method becuase getCurrentLearner()
+ // will create session user if it does not exist.
+ SubmitUser learner = getCurrentLearner(sessionID, submitFilesService);
+ List filesUploaded = submitFilesService.getFilesUploadedByUser(userID, sessionID, request.getLocale());
- // check whehter finish lock is on/off
- boolean lock = content.isLockOnFinished() && learner.isFinished();
+ // check whehter finish lock is on/off
+ boolean lock = content.isLockOnFinished() && learner.isFinished();
- sessionMap.put(AttributeNames.PARAM_MODE, mode);
- sessionMap.put(AttributeNames.PARAM_TOOL_SESSION_ID, sessionID);
- sessionMap.put(SbmtConstants.ATTR_FINISH_LOCK, lock);
- sessionMap.put(SbmtConstants.ATTR_LOCK_ON_FINISH, content.isLockOnFinished());
- sessionMap.put(SbmtConstants.ATTR_REFLECTION_ON, content.isReflectOnActivity());
- sessionMap.put(SbmtConstants.ATTR_REFLECTION_INSTRUCTION, content.getReflectInstructions());
- sessionMap.put(SbmtConstants.ATTR_TITLE, content.getTitle());
- sessionMap.put(SbmtConstants.ATTR_INSTRUCTION, content.getInstruction());
- sessionMap.put(SbmtConstants.ATTR_LIMIT_UPLOAD, content.isLimitUpload());
- sessionMap.put(SbmtConstants.ATTR_LIMIT_UPLOAD_NUMBER, content.getLimitUploadNumber());
- sessionMap.put(SbmtConstants.ATTR_USER_FINISHED, learner.isFinished());
+ sessionMap.put(AttributeNames.PARAM_MODE, mode);
+ sessionMap.put(AttributeNames.PARAM_TOOL_SESSION_ID, sessionID);
+ sessionMap.put(SbmtConstants.ATTR_FINISH_LOCK, lock);
+ sessionMap.put(SbmtConstants.ATTR_LOCK_ON_FINISH, content.isLockOnFinished());
+ sessionMap.put(SbmtConstants.ATTR_REFLECTION_ON, content.isReflectOnActivity());
+ sessionMap.put(SbmtConstants.ATTR_REFLECTION_INSTRUCTION, content.getReflectInstructions());
+ sessionMap.put(SbmtConstants.ATTR_TITLE, content.getTitle());
+ sessionMap.put(SbmtConstants.ATTR_INSTRUCTION, content.getInstruction());
+ sessionMap.put(SbmtConstants.ATTR_LIMIT_UPLOAD, content.isLimitUpload());
+ sessionMap.put(SbmtConstants.ATTR_LIMIT_UPLOAD_NUMBER, content.getLimitUploadNumber());
+ sessionMap.put(SbmtConstants.ATTR_USER_FINISHED, learner.isFinished());
- setLearnerDTO(request, sessionMap, learner, filesUploaded, mode);
+ setLearnerDTO(request, sessionMap, learner, filesUploaded, mode);
- //if content in use, return special page.
- if (content.isDefineLater()) {
- return mapping.findForward("defineLater");
- }
+ // if content in use, return special page.
+ if (content.isDefineLater()) {
+ return mapping.findForward("defineLater");
+ }
- //set contentInUse flag to true!
- content.setContentInUse(true);
- content.setDefineLater(false);
- submitFilesService.saveOrUpdateContent(content);
+ // set contentInUse flag to true!
+ content.setContentInUse(true);
+ content.setDefineLater(false);
+ submitFilesService.saveOrUpdateContent(content);
- //add run offline support
- if (content.isRunOffline()) {
- return mapping.findForward("runOffline");
- }
+ // add run offline support
+ if (content.isRunOffline()) {
+ return mapping.findForward("runOffline");
+ }
- if (content.isNotifyLearnersOnMarkRelease()) {
- submitFilesService.getEventNotificationService().createEvent(SbmtConstants.TOOL_SIGNATURE,
- SbmtConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, content.getContentID(),
- submitFilesService.getLocalisedMessage("event.mark.release.subject", null),
- submitFilesService.getLocalisedMessage("event.mark.release.body", null));
+ if (content.isNotifyLearnersOnMarkRelease()) {
+ submitFilesService.getEventNotificationService().createEvent(SbmtConstants.TOOL_SIGNATURE,
+ SbmtConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, content.getContentID(),
+ submitFilesService.getLocalisedMessage("event.mark.release.subject", null),
+ submitFilesService.getLocalisedMessage("event.mark.release.body", null));
- submitFilesService.getEventNotificationService().subscribe(SbmtConstants.TOOL_SIGNATURE,
- SbmtConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, content.getContentID(),
- learner.getUserID().longValue(), IEventNotificationService.DELIVERY_METHOD_MAIL,
- IEventNotificationService.PERIODICITY_SINGLE);
- }
-
- return mapping.findForward(SbmtConstants.SUCCESS);
+ submitFilesService.getEventNotificationService().subscribe(SbmtConstants.TOOL_SIGNATURE,
+ SbmtConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, content.getContentID(),
+ learner.getUserID().longValue(), IEventNotificationService.DELIVERY_METHOD_MAIL,
+ IEventNotificationService.PERIODICITY_SINGLE);
}
- /**
- * Implements learner upload submission function. This function also display the page again for learner uploading
- * more submission use.
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- public ActionForward uploadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
+ return mapping.findForward(SbmtConstants.SUCCESS);
+ }
- LearnerForm learnerForm = (LearnerForm) form;
- String sessionMapID = learnerForm.getSessionMapID();
- SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
- request.setAttribute(SbmtConstants.ATTR_SESSION_MAP_ID, sessionMapID);
+ /**
+ * Implements learner upload submission function. This function also display the page again for learner uploading
+ * more submission use.
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ public ActionForward uploadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
- //set the mode into http session
- Long sessionID = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
+ LearnerForm learnerForm = (LearnerForm) form;
+ String sessionMapID = learnerForm.getSessionMapID();
+ SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
+ request.setAttribute(SbmtConstants.ATTR_SESSION_MAP_ID, sessionMapID);
- if (validateUploadForm(learnerForm, request)) {
- //get session from shared session.
- HttpSession ss = SessionManager.getSession();
- //get back login user DTO
- UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
- Integer userID = user.getUserID();
+ // set the mode into http session
+ Long sessionID = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
- ISubmitFilesService submitFilesService = getService();
- List filesUploaded = submitFilesService.getFilesUploadedByUser(userID, sessionID, request.getLocale());
+ if (validateUploadForm(learnerForm, request)) {
+ // get session from shared session.
+ HttpSession ss = SessionManager.getSession();
+ // get back login user DTO
+ UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
+ Integer userID = user.getUserID();
- SubmitUser learner = getCurrentLearner(sessionID, submitFilesService);
- ToolAccessMode mode = (ToolAccessMode) sessionMap.get(AttributeNames.ATTR_MODE);
- setLearnerDTO(request, sessionMap, learner, filesUploaded, mode);
+ ISubmitFilesService submitFilesService = getService();
+ List filesUploaded = submitFilesService.getFilesUploadedByUser(userID, sessionID, request.getLocale());
- return mapping.getInputForward();
- }
+ SubmitUser learner = getCurrentLearner(sessionID, submitFilesService);
+ ToolAccessMode mode = (ToolAccessMode) sessionMap.get(AttributeNames.ATTR_MODE);
+ setLearnerDTO(request, sessionMap, learner, filesUploaded, mode);
- //get session from shared session.
- HttpSession ss = SessionManager.getSession();
- //get back login user DTO
- UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
- Integer userID = user.getUserID();
+ return mapping.getInputForward();
+ }
- FormFile uploadedFile = learnerForm.getFile();
- String fileDescription = learnerForm.getDescription();
- //reset fields and display a new form for next new file upload
- learnerForm.setDescription("");
+ // get session from shared session.
+ HttpSession ss = SessionManager.getSession();
+ // get back login user DTO
+ UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
+ Integer userID = user.getUserID();
- ISubmitFilesService submitFilesService = getService();
+ FormFile uploadedFile = learnerForm.getFile();
+ String fileDescription = learnerForm.getDescription();
+ // reset fields and display a new form for next new file upload
+ learnerForm.setDescription("");
- submitFilesService.uploadFileToSession(sessionID, uploadedFile, fileDescription, userID);
- List filesUploaded = submitFilesService.getFilesUploadedByUser(userID, sessionID, request.getLocale());
- SubmitUser learner = getCurrentLearner(sessionID, submitFilesService);
- ToolAccessMode mode = (ToolAccessMode) sessionMap.get(AttributeNames.ATTR_MODE);
- setLearnerDTO(request, sessionMap, learner, filesUploaded, mode);
+ ISubmitFilesService submitFilesService = getService();
- SubmitFilesContent content = submitFilesService.getSessionById(sessionID).getContent();
- if (content.isNotifyTeachersOnFileSubmit()
- && submitFilesService.getEventNotificationService().eventExists(SbmtConstants.TOOL_SIGNATURE,
- SbmtConstants.EVENT_NAME_NOTIFY_TEACHERS_ON_FILE_SUBMIT, content.getContentID())) {
- String fullName = learner.getLastName() + " " + learner.getFirstName();
- submitFilesService.getEventNotificationService().trigger(SbmtConstants.TOOL_SIGNATURE,
- SbmtConstants.EVENT_NAME_NOTIFY_TEACHERS_ON_FILE_SUBMIT, content.getContentID(), new Object[] { fullName });
+ submitFilesService.uploadFileToSession(sessionID, uploadedFile, fileDescription, userID);
+ List filesUploaded = submitFilesService.getFilesUploadedByUser(userID, sessionID, request.getLocale());
+ SubmitUser learner = getCurrentLearner(sessionID, submitFilesService);
+ ToolAccessMode mode = (ToolAccessMode) sessionMap.get(AttributeNames.ATTR_MODE);
+ setLearnerDTO(request, sessionMap, learner, filesUploaded, mode);
+
+ SubmitFilesContent content = submitFilesService.getSessionById(sessionID).getContent();
+ if (content.isNotifyTeachersOnFileSubmit()) {
+ List monitoringUsers = submitFilesService.getMonitorsByToolSessionId(sessionID);
+ if (monitoringUsers != null && !monitoringUsers.isEmpty()) {
+ Long[] monitoringUsersIds = new Long[monitoringUsers.size()];
+ for (int i = 0; i < monitoringUsersIds.length; i++) {
+ monitoringUsersIds[i] = monitoringUsers.get(i).getUserId().longValue();
}
- return mapping.getInputForward();
+ String fullName = learner.getLastName() + " " + learner.getFirstName();
+ submitFilesService.getEventNotificationService().sendMessage(monitoringUsersIds,
+ DeliveryMethodMail.getInstance(),
+ submitFilesService.getLocalisedMessage("event.file.submit.subject", null),
+ submitFilesService.getLocalisedMessage("event.file.submit.body", new Object[] { fullName }));
+ }
}
+ return mapping.getInputForward();
+ }
- /**
- * Learner choose finish upload button, will invoke this function. This function will mark the finished
- * field by special toolSessionID and userID.
- *
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- public ActionForward finish(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
+ /**
+ * Learner choose finish upload button, will invoke this function. This function will mark the finished
+ * field by special toolSessionID and userID.
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ public ActionForward finish(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
- String sessionMapID = WebUtil.readStrParam(request, SbmtConstants.ATTR_SESSION_MAP_ID);
- SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
- request.setAttribute(SbmtConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID());
+ String sessionMapID = WebUtil.readStrParam(request, SbmtConstants.ATTR_SESSION_MAP_ID);
+ SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);
+ request.setAttribute(SbmtConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID());
- ToolAccessMode mode = (ToolAccessMode) sessionMap.get(AttributeNames.ATTR_MODE);
- Long sessionID = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
+ ToolAccessMode mode = (ToolAccessMode) sessionMap.get(AttributeNames.ATTR_MODE);
+ Long sessionID = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
- if (mode == ToolAccessMode.LEARNER || mode.equals(ToolAccessMode.AUTHOR)) {
- ToolSessionManager sessionMgrService = SubmitFilesServiceProxy
- .getToolSessionManager(getServlet().getServletContext());
- ISubmitFilesService submitFilesService = getService();
+ if (mode == ToolAccessMode.LEARNER || mode.equals(ToolAccessMode.AUTHOR)) {
+ ToolSessionManager sessionMgrService = SubmitFilesServiceProxy.getToolSessionManager(getServlet()
+ .getServletContext());
+ ISubmitFilesService submitFilesService = getService();
- //get back login user DTO
- //get session from shared session.
- HttpSession ss = SessionManager.getSession();
- UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
- Integer userID = user.getUserID();
- submitFilesService.finishSubmission(sessionID, userID);
+ // get back login user DTO
+ // get session from shared session.
+ HttpSession ss = SessionManager.getSession();
+ UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
+ Integer userID = user.getUserID();
+ submitFilesService.finishSubmission(sessionID, userID);
- String nextActivityUrl;
- try {
- nextActivityUrl = sessionMgrService.leaveToolSession(sessionID, new Long(userID.intValue()));
- response.sendRedirect(nextActivityUrl);
- }
- catch (DataMissingException e) {
- throw new SubmitFilesException(e);
- }
- catch (ToolException e) {
- throw new SubmitFilesException(e);
- }
- catch (IOException e) {
- throw new SubmitFilesException(e);
- }
- }
- return null;
-
+ String nextActivityUrl;
+ try {
+ nextActivityUrl = sessionMgrService.leaveToolSession(sessionID, new Long(userID.intValue()));
+ response.sendRedirect(nextActivityUrl);
+ } catch (DataMissingException e) {
+ throw new SubmitFilesException(e);
+ } catch (ToolException e) {
+ throw new SubmitFilesException(e);
+ } catch (IOException e) {
+ throw new SubmitFilesException(e);
+ }
}
+ return null;
- //**********************************************************************************************
- // Private mehtods
- //**********************************************************************************************
- private ISubmitFilesService getService() {
- ISubmitFilesService submitFilesService = SubmitFilesServiceProxy.getSubmitFilesService(this.getServlet()
- .getServletContext());
- return submitFilesService;
- }
+ }
- //validate uploaded form
- private boolean validateUploadForm(LearnerForm learnerForm, HttpServletRequest request) {
- ActionMessages errors = new ActionMessages();
- Locale preferredLocale = (Locale) request.getSession().getAttribute(LocaleFilter.PREFERRED_LOCALE_KEY);
- if (learnerForm.getFile() == null || StringUtils.isBlank(learnerForm.getFile().getFileName())) {
- errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.required", this.getResources(request).getMessage(
- preferredLocale, "learner.form.filepath.displayname")));
- }
- if (StringUtils.isBlank(learnerForm.getDescription())) {
- errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.required", this.getResources(request).getMessage(
- preferredLocale, "label.learner.fileDescription")));
- }
- else if (learnerForm.getDescription().length() > LearnerForm.DESCRIPTION_LENGTH) {
- errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.maxdescsize", LearnerForm.DESCRIPTION_LENGTH));
- }
+ // **********************************************************************************************
+ // Private mehtods
+ // **********************************************************************************************
+ private ISubmitFilesService getService() {
+ ISubmitFilesService submitFilesService = SubmitFilesServiceProxy.getSubmitFilesService(this.getServlet()
+ .getServletContext());
+ return submitFilesService;
+ }
- FileValidatorUtil.validateFileSize(learnerForm.getFile(), false, errors);
+ // validate uploaded form
+ private boolean validateUploadForm(LearnerForm learnerForm, HttpServletRequest request) {
+ ActionMessages errors = new ActionMessages();
+ Locale preferredLocale = (Locale) request.getSession().getAttribute(LocaleFilter.PREFERRED_LOCALE_KEY);
+ if (learnerForm.getFile() == null || StringUtils.isBlank(learnerForm.getFile().getFileName())) {
+ errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.required", this.getResources(request)
+ .getMessage(preferredLocale, "learner.form.filepath.displayname")));
+ }
+ if (StringUtils.isBlank(learnerForm.getDescription())) {
+ errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.required", this.getResources(request)
+ .getMessage(preferredLocale, "label.learner.fileDescription")));
+ } else if (learnerForm.getDescription().length() > LearnerForm.DESCRIPTION_LENGTH) {
+ errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.maxdescsize",
+ LearnerForm.DESCRIPTION_LENGTH));
+ }
- if (learnerForm.getFile() != null) {
- DispatchAction.log.debug("Learner submit file : " + learnerForm.getFile().getFileName());
- }
+ FileValidatorUtil.validateFileSize(learnerForm.getFile(), false, errors);
- if (learnerForm.getFile() != null && FileUtil.isExecutableFile(learnerForm.getFile().getFileName())) {
- DispatchAction.log.debug("File is executatable : " + learnerForm.getFile().getFileName());
- ActionMessage msg = new ActionMessage("error.attachment.executable");
- errors.add(ActionMessages.GLOBAL_MESSAGE, msg);
- }
+ if (learnerForm.getFile() != null) {
+ DispatchAction.log.debug("Learner submit file : " + learnerForm.getFile().getFileName());
+ }
- if (!errors.isEmpty()) {
- this.addErrors(request, errors);
- return true;
- }
- return false;
+ if (learnerForm.getFile() != null && FileUtil.isExecutableFile(learnerForm.getFile().getFileName())) {
+ DispatchAction.log.debug("File is executatable : " + learnerForm.getFile().getFileName());
+ ActionMessage msg = new ActionMessage("error.attachment.executable");
+ errors.add(ActionMessages.GLOBAL_MESSAGE, msg);
}
- /**
- *
- * Set information into learner DTO object for page display.
- * Fill file list uploaded by the special user into web form. Remove the unauthorized mark and comments.
- * @param request
- * @param sessionMap
- * @param sessionID
- * @param userID
- * @param content
- * @param filesUploaded
- */
- private void setLearnerDTO(HttpServletRequest request, SessionMap sessionMap, SubmitUser currUser, List filesUploaded,
- ToolAccessMode mode) {
+ if (!errors.isEmpty()) {
+ this.addErrors(request, errors);
+ return true;
+ }
+ return false;
+ }
- SubmitUserDTO dto = new SubmitUserDTO(currUser);
- if (currUser != null) {
- //if Monitoring does not release marks, then skip this mark and comment content.
- if (filesUploaded != null) {
- Iterator iter = filesUploaded.iterator();
- while (iter.hasNext()) {
- FileDetailsDTO filedto = (FileDetailsDTO) iter.next();
- if (mode.isTeacher() || currUser.getUid().equals(filedto.getOwner().getUserUid())) {
- filedto.setCurrentLearner(true);
- }
- else {
- filedto.setCurrentLearner(false);
- }
- if (filedto.getDateMarksReleased() == null) {
- filedto.setComments(null);
- filedto.setMarks(null);
- }
- }
- }
- dto.setFilesUploaded(filesUploaded);
- }
+ /**
+ *
+ * Set information into learner DTO object for page display. Fill file list uploaded by the special user into web
+ * form. Remove the unauthorized mark and comments.
+ *
+ * @param request
+ * @param sessionMap
+ * @param sessionID
+ * @param userID
+ * @param content
+ * @param filesUploaded
+ */
+ private void setLearnerDTO(HttpServletRequest request, SessionMap sessionMap, SubmitUser currUser,
+ List filesUploaded, ToolAccessMode mode) {
- //preset
- boolean limitUpload = (Boolean) sessionMap.get(SbmtConstants.ATTR_LIMIT_UPLOAD);
- if (limitUpload && filesUploaded != null) {
- int limit = (Integer) sessionMap.get(SbmtConstants.ATTR_LIMIT_UPLOAD_NUMBER);
- if (limit == filesUploaded.size()) {
- sessionMap.put(SbmtConstants.ATTR_ARRIVE_LIMIT, true);
- }
- int limitUploadLeft = limit - filesUploaded.size();
- dto.setLimitUploadLeft(limitUploadLeft);
+ SubmitUserDTO dto = new SubmitUserDTO(currUser);
+ if (currUser != null) {
+ // if Monitoring does not release marks, then skip this mark and comment content.
+ if (filesUploaded != null) {
+ Iterator iter = filesUploaded.iterator();
+ while (iter.hasNext()) {
+ FileDetailsDTO filedto = (FileDetailsDTO) iter.next();
+ if (mode.isTeacher() || currUser.getUid().equals(filedto.getOwner().getUserUid())) {
+ filedto.setCurrentLearner(true);
+ } else {
+ filedto.setCurrentLearner(false);
+ }
+ if (filedto.getDateMarksReleased() == null) {
+ filedto.setComments(null);
+ filedto.setMarks(null);
+ }
}
+ }
+ dto.setFilesUploaded(filesUploaded);
+ }
- // retreive notebook reflection entry.
- ISubmitFilesService submitFilesService = getService();
+ // preset
+ boolean limitUpload = (Boolean) sessionMap.get(SbmtConstants.ATTR_LIMIT_UPLOAD);
+ if (limitUpload && filesUploaded != null) {
+ int limit = (Integer) sessionMap.get(SbmtConstants.ATTR_LIMIT_UPLOAD_NUMBER);
+ if (limit == filesUploaded.size()) {
+ sessionMap.put(SbmtConstants.ATTR_ARRIVE_LIMIT, true);
+ }
+ int limitUploadLeft = limit - filesUploaded.size();
+ dto.setLimitUploadLeft(limitUploadLeft);
+ }
- NotebookEntry notebookEntry = submitFilesService.getEntry((Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID),
- CoreNotebookConstants.NOTEBOOK_TOOL, SbmtConstants.TOOL_SIGNATURE, currUser.getUserID());
+ // retreive notebook reflection entry.
+ ISubmitFilesService submitFilesService = getService();
- if (notebookEntry != null) {
- dto.setReflect(notebookEntry.getEntry());
- }
+ NotebookEntry notebookEntry = submitFilesService.getEntry((Long) sessionMap
+ .get(AttributeNames.PARAM_TOOL_SESSION_ID), CoreNotebookConstants.NOTEBOOK_TOOL,
+ SbmtConstants.TOOL_SIGNATURE, currUser.getUserID());
- request.setAttribute("learner", dto);
+ if (notebookEntry != null) {
+ dto.setReflect(notebookEntry.getEntry());
}
- private SubmitUser getCurrentLearner(Long sessionID, ISubmitFilesService submitFilesService) {
- //get session from shared session.
- HttpSession ss = SessionManager.getSession();
- //get back login user DTO
- UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
- Integer userID = user.getUserID();
+ request.setAttribute("learner", dto);
+ }
- SubmitUser learner = submitFilesService.getSessionUser(sessionID, userID);
- if (learner == null) {
- learner = submitFilesService.createSessionUser(user, sessionID);
- }
+ private SubmitUser getCurrentLearner(Long sessionID, ISubmitFilesService submitFilesService) {
+ // get session from shared session.
+ HttpSession ss = SessionManager.getSession();
+ // get back login user DTO
+ UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
+ Integer userID = user.getUserID();
- return learner;
+ SubmitUser learner = submitFilesService.getSessionUser(sessionID, userID);
+ if (learner == null) {
+ learner = submitFilesService.createSessionUser(user, sessionID);
}
+ return learner;
+ }
+
}
Index: lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/web/MonitoringAction.java
===================================================================
diff -u -rb4f39fe54478833bd6b677d5e7adf357a398c9f6 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/web/MonitoringAction.java (.../MonitoringAction.java) (revision b4f39fe54478833bd6b677d5e7adf357a398c9f6)
+++ lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/web/MonitoringAction.java (.../MonitoringAction.java) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -37,7 +37,6 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
@@ -50,7 +49,6 @@
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
-import org.lamsfoundation.lams.events.IEventNotificationService;
import org.lamsfoundation.lams.notebook.model.NotebookEntry;
import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants;
import org.lamsfoundation.lams.tool.sbmt.SubmitFilesContent;
@@ -64,24 +62,17 @@
import org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService;
import org.lamsfoundation.lams.tool.sbmt.service.SubmitFilesServiceProxy;
import org.lamsfoundation.lams.tool.sbmt.util.SbmtConstants;
-import org.lamsfoundation.lams.usermanagement.dto.UserDTO;
import org.lamsfoundation.lams.util.MessageService;
import org.lamsfoundation.lams.util.NumberUtil;
import org.lamsfoundation.lams.util.WebUtil;
import org.lamsfoundation.lams.web.action.LamsDispatchAction;
-import org.lamsfoundation.lams.web.session.SessionManager;
import org.lamsfoundation.lams.web.util.AttributeNames;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
* @author Manpreet Minhas
- * @struts.action
- * path="/monitoring"
- * parameter="method"
- * scope="request"
- * validate="false"
- * name="SbmtMonitoringForm"
+ * @struts.action path="/monitoring" parameter="method" scope="request" validate="false" name="SbmtMonitoringForm"
*
* @struts.action-forward name="listMark" path="/monitoring/mark/mark.jsp"
* @struts.action-forward name="updateMark" path="/monitoring/mark/updatemark.jsp"
@@ -95,525 +86,516 @@
*/
public class MonitoringAction extends LamsDispatchAction {
- public ISubmitFilesService submitFilesService;
+ public ISubmitFilesService submitFilesService;
- private class SessionComparator implements Comparator {
- public int compare(SessionDTO o1, SessionDTO o2) {
- if (o1 != null && o2 != null) {
- return o1.getSessionName().compareTo(o2.getSessionName());
- }
- else if (o1 != null) {
- return 1;
- }
- else {
- return -1;
- }
- }
+ private class SessionComparator implements Comparator {
+ public int compare(SessionDTO o1, SessionDTO o2) {
+ if (o1 != null && o2 != null) {
+ return o1.getSessionName().compareTo(o2.getSessionName());
+ } else if (o1 != null) {
+ return 1;
+ } else {
+ return -1;
+ }
}
+ }
- /**
- * Default ActionForward for Monitor
- */
- @Override
- public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
- String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID);
- Long contentID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID));
- submitFilesService = getSubmitFilesService();
+ /**
+ * Default ActionForward for Monitor
+ */
+ @Override
+ public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID);
+ Long contentID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID));
+ submitFilesService = getSubmitFilesService();
- request.setAttribute(AttributeNames.PARAM_CONTENT_FOLDER_ID, contentFolderID);
+ request.setAttribute(AttributeNames.PARAM_CONTENT_FOLDER_ID, contentFolderID);
- // List userList = submitFilesService.getUsers(sessionID);
- List submitFilesSessionList = submitFilesService.getSubmitFilesSessionByContentID(contentID);
- summary(request, submitFilesSessionList);
- statistic(request, submitFilesSessionList);
+ // List userList = submitFilesService.getUsers(sessionID);
+ List submitFilesSessionList = submitFilesService.getSubmitFilesSessionByContentID(contentID);
+ summary(request, submitFilesSessionList);
+ statistic(request, submitFilesSessionList);
- //instruction
- SubmitFilesContent persistContent = submitFilesService.getSubmitFilesContent(contentID);
- //if this content does not exist, then reset the contentID to current value to keep it on HTML page.
- persistContent.setContentID(contentID);
+ // instruction
+ SubmitFilesContent persistContent = submitFilesService.getSubmitFilesContent(contentID);
+ // if this content does not exist, then reset the contentID to current value to keep it on HTML page.
+ persistContent.setContentID(contentID);
- AuthoringDTO authorDto = new AuthoringDTO(persistContent);
- request.setAttribute(SbmtConstants.AUTHORING_DTO, authorDto);
- request.setAttribute(SbmtConstants.PAGE_EDITABLE, persistContent.isContentInUse());
+ AuthoringDTO authorDto = new AuthoringDTO(persistContent);
+ request.setAttribute(SbmtConstants.AUTHORING_DTO, authorDto);
+ request.setAttribute(SbmtConstants.PAGE_EDITABLE, persistContent.isContentInUse());
- DynaActionForm smbtMonitoringForm = (DynaActionForm) form;
- // smbtMonitoringForm.set("currentTab", WebUtil.readStrParam(request, AttributeNames.PARAM_CURRENT_TAB,true));
+ DynaActionForm smbtMonitoringForm = (DynaActionForm) form;
+ // smbtMonitoringForm.set("currentTab", WebUtil.readStrParam(request, AttributeNames.PARAM_CURRENT_TAB,true));
- if (persistContent.isNotifyTeachersOnFileSubmit()) {
- //Since we don't know if the event exists, we just try to create it.
- submitFilesService.getEventNotificationService().createEvent(SbmtConstants.TOOL_SIGNATURE,
- SbmtConstants.EVENT_NAME_NOTIFY_TEACHERS_ON_FILE_SUBMIT, contentID,
- submitFilesService.getLocalisedMessage("event.file.submit.subject", null),
- submitFilesService.getLocalisedMessage("event.file.submit.body", null));
+ return mapping.findForward("success");
+ }
- HttpSession ss = SessionManager.getSession();
- UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
- //Now we subscribe the teacher
- submitFilesService.getEventNotificationService().subscribe(SbmtConstants.TOOL_SIGNATURE,
- SbmtConstants.EVENT_NAME_NOTIFY_TEACHERS_ON_FILE_SUBMIT, contentID, user.getUserID().longValue(),
- IEventNotificationService.DELIVERY_METHOD_MAIL, IEventNotificationService.PERIODICITY_SINGLE);
- }
- return mapping.findForward("success");
- }
+ /**
+ * AJAX call to refresh statistic page.
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ public ActionForward doStatistic(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ Long contentID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID));
+ submitFilesService = getSubmitFilesService();
- /**
- * AJAX call to refresh statistic page.
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- public ActionForward doStatistic(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
- Long contentID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID));
- submitFilesService = getSubmitFilesService();
+ // List userList = submitFilesService.getUsers(sessionID);
+ List submitFilesSessionList = submitFilesService.getSubmitFilesSessionByContentID(contentID);
+ statistic(request, submitFilesSessionList);
- // List userList = submitFilesService.getUsers(sessionID);
- List submitFilesSessionList = submitFilesService.getSubmitFilesSessionByContentID(contentID);
- statistic(request, submitFilesSessionList);
+ return mapping.findForward("statistic");
- return mapping.findForward("statistic");
+ }
- }
+ /**
+ * Release mark
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ public ActionForward releaseMarks(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
- /**
- * Release mark
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- public ActionForward releaseMarks(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
+ // get service then update report table
+ submitFilesService = getSubmitFilesService();
+ Long sessionID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID));
+ submitFilesService.releaseMarksForSession(sessionID);
- //get service then update report table
- submitFilesService = getSubmitFilesService();
- Long sessionID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID));
- submitFilesService.releaseMarksForSession(sessionID);
-
- try {
- response.setContentType("text/html;charset=utf-8");
- PrintWriter out = response.getWriter();
- SubmitFilesSession session = submitFilesService.getSessionById(sessionID);
- String sessionName = "";
- if (session != null) {
- sessionName = session.getSessionName();
- }
- out.write(getMessageService().getMessage("msg.mark.released", new String[] { sessionName }));
- out.flush();
- }
- catch (IOException e) {
- }
- return null;
+ try {
+ response.setContentType("text/html;charset=utf-8");
+ PrintWriter out = response.getWriter();
+ SubmitFilesSession session = submitFilesService.getSessionById(sessionID);
+ String sessionName = "";
+ if (session != null) {
+ sessionName = session.getSessionName();
+ }
+ out.write(getMessageService().getMessage("msg.mark.released", new String[] { sessionName }));
+ out.flush();
+ } catch (IOException e) {
}
+ return null;
+ }
- /**
- * Download submit file marks by MS Excel file format.
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- public ActionForward downloadMarks(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
+ /**
+ * Download submit file marks by MS Excel file format.
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ public ActionForward downloadMarks(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
- Long sessionID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID));
- submitFilesService = getSubmitFilesService();
- //return FileDetailsDTO list according to the given sessionID
- Map userFilesMap = submitFilesService.getFilesUploadedBySession(sessionID, request.getLocale());
- //construct Excel file format and download
- String errors = null;
- try {
- //create an empty excel file
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet("Marks");
- sheet.setColumnWidth((short) 0, (short) 5000);
- HSSFRow row;
- HSSFCell cell;
+ Long sessionID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID));
+ submitFilesService = getSubmitFilesService();
+ // return FileDetailsDTO list according to the given sessionID
+ Map userFilesMap = submitFilesService.getFilesUploadedBySession(sessionID, request.getLocale());
+ // construct Excel file format and download
+ String errors = null;
+ try {
+ // create an empty excel file
+ HSSFWorkbook wb = new HSSFWorkbook();
+ HSSFSheet sheet = wb.createSheet("Marks");
+ sheet.setColumnWidth((short) 0, (short) 5000);
+ HSSFRow row;
+ HSSFCell cell;
- Iterator iter = userFilesMap.values().iterator();
- Iterator dtoIter;
+ Iterator iter = userFilesMap.values().iterator();
+ Iterator dtoIter;
- short idx = (short) 0;
+ short idx = (short) 0;
- row = sheet.createRow(idx++);
- cell = row.createCell((short) 2);
- cell.setEncoding(HSSFCell.ENCODING_UTF_16);
- cell.setCellValue(getMessageService().getMessage("label.learner.fileName"));
+ row = sheet.createRow(idx++);
+ cell = row.createCell((short) 2);
+ cell.setEncoding(HSSFCell.ENCODING_UTF_16);
+ cell.setCellValue(getMessageService().getMessage("label.learner.fileName"));
- cell = row.createCell((short) 3);
- cell.setEncoding(HSSFCell.ENCODING_UTF_16);
- cell.setCellValue(getMessageService().getMessage("label.learner.fileDescription"));
+ cell = row.createCell((short) 3);
+ cell.setEncoding(HSSFCell.ENCODING_UTF_16);
+ cell.setCellValue(getMessageService().getMessage("label.learner.fileDescription"));
- cell = row.createCell((short) 4);
- cell.setEncoding(HSSFCell.ENCODING_UTF_16);
- cell.setCellValue(getMessageService().getMessage("label.learner.marks"));
+ cell = row.createCell((short) 4);
+ cell.setEncoding(HSSFCell.ENCODING_UTF_16);
+ cell.setCellValue(getMessageService().getMessage("label.learner.marks"));
- cell = row.createCell((short) 5);
- cell.setEncoding(HSSFCell.ENCODING_UTF_16);
- cell.setCellValue(getMessageService().getMessage("label.learner.comments"));
+ cell = row.createCell((short) 5);
+ cell.setEncoding(HSSFCell.ENCODING_UTF_16);
+ cell.setCellValue(getMessageService().getMessage("label.learner.comments"));
- while (iter.hasNext()) {
- List list = (List) iter.next();
- dtoIter = list.iterator();
+ while (iter.hasNext()) {
+ List list = (List) iter.next();
+ dtoIter = list.iterator();
- while (dtoIter.hasNext()) {
- FileDetailsDTO dto = (FileDetailsDTO) dtoIter.next();
- row = sheet.createRow(idx++);
+ while (dtoIter.hasNext()) {
+ FileDetailsDTO dto = (FileDetailsDTO) dtoIter.next();
+ row = sheet.createRow(idx++);
- short count = 0;
+ short count = 0;
- cell = row.createCell(count++);
- cell.setEncoding(HSSFCell.ENCODING_UTF_16);
- cell.setCellValue(dto.getOwner().getFirstName() + " " + dto.getOwner().getLastName());
+ cell = row.createCell(count++);
+ cell.setEncoding(HSSFCell.ENCODING_UTF_16);
+ cell.setCellValue(dto.getOwner().getFirstName() + " " + dto.getOwner().getLastName());
- ++count;
+ ++count;
- sheet.setColumnWidth(count, (short) 8000);
+ sheet.setColumnWidth(count, (short) 8000);
- cell = row.createCell(count++);
- cell.setEncoding(HSSFCell.ENCODING_UTF_16);
- cell.setCellValue(dto.getFilePath());
+ cell = row.createCell(count++);
+ cell.setEncoding(HSSFCell.ENCODING_UTF_16);
+ cell.setCellValue(dto.getFilePath());
- cell = row.createCell(count++);
- cell.setEncoding(HSSFCell.ENCODING_UTF_16);
- cell.setCellValue(dto.getFileDescription());
+ cell = row.createCell(count++);
+ cell.setEncoding(HSSFCell.ENCODING_UTF_16);
+ cell.setCellValue(dto.getFileDescription());
- cell = row.createCell(count++);
+ cell = row.createCell(count++);
- String marks = dto.getMarks();
- cell.setCellValue(marks != null ? marks : "");
+ String marks = dto.getMarks();
+ cell.setCellValue(marks != null ? marks : "");
- cell = row.createCell(count++);
- cell.setEncoding(HSSFCell.ENCODING_UTF_16);
- cell.setCellValue(dto.getComments());
- }
- }
+ cell = row.createCell(count++);
+ cell.setEncoding(HSSFCell.ENCODING_UTF_16);
+ cell.setCellValue(dto.getComments());
+ }
+ }
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- wb.write(bos);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ wb.write(bos);
- //construct download file response header
- String fileName = "marks" + sessionID + ".xls";
- String mineType = "application/vnd.ms-excel";
- String header = "attachment; filename=\"" + fileName + "\";";
- response.setContentType(mineType);
- response.setHeader("Content-Disposition", header);
+ // construct download file response header
+ String fileName = "marks" + sessionID + ".xls";
+ String mineType = "application/vnd.ms-excel";
+ String header = "attachment; filename=\"" + fileName + "\";";
+ response.setContentType(mineType);
+ response.setHeader("Content-Disposition", header);
- byte[] data = bos.toByteArray();
- response.getOutputStream().write(data, 0, data.length);
- response.getOutputStream().flush();
- }
- catch (Exception e) {
- LamsDispatchAction.log.error(e);
- errors = new ActionMessage("monitoring.download.error", e.toString()).toString();
- }
+ byte[] data = bos.toByteArray();
+ response.getOutputStream().write(data, 0, data.length);
+ response.getOutputStream().flush();
+ } catch (Exception e) {
+ LamsDispatchAction.log.error(e);
+ errors = new ActionMessage("monitoring.download.error", e.toString()).toString();
+ }
- if (errors != null) {
- try {
- PrintWriter out = response.getWriter();
- out.write(errors);
- out.flush();
- }
- catch (IOException e) {
- }
- }
-
- return null;
+ if (errors != null) {
+ try {
+ PrintWriter out = response.getWriter();
+ out.write(errors);
+ out.flush();
+ } catch (IOException e) {
+ }
}
- //**********************************************************
- // Mark udpate/view methods
- //**********************************************************
- /**
- * Display special user's marks information.
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- public ActionForward listMark(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
- Long sessionID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID));
- Integer userID = WebUtil.readIntParam(request, "userID");
+ return null;
+ }
- submitFilesService = getSubmitFilesService();
- //return FileDetailsDTO list according to the given userID and sessionID
- List files = submitFilesService.getFilesUploadedByUser(userID, sessionID, request.getLocale());
+ // **********************************************************
+ // Mark udpate/view methods
+ // **********************************************************
+ /**
+ * Display special user's marks information.
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ public ActionForward listMark(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ Long sessionID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID));
+ Integer userID = WebUtil.readIntParam(request, "userID");
- request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID, sessionID);
- request.setAttribute("report", files);
- return mapping.findForward("listMark");
- }
+ submitFilesService = getSubmitFilesService();
+ // return FileDetailsDTO list according to the given userID and sessionID
+ List files = submitFilesService.getFilesUploadedByUser(userID, sessionID, request.getLocale());
- /**
- * Display update mark initial page.
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- public ActionForward newMark(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
+ request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID, sessionID);
+ request.setAttribute("report", files);
+ return mapping.findForward("listMark");
+ }
- Long sessionID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID));
- Long detailID = new Long(WebUtil.readLongParam(request, "detailID"));
- String updateMode = request.getParameter("updateMode");
+ /**
+ * Display update mark initial page.
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ public ActionForward newMark(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
- submitFilesService = getSubmitFilesService();
+ Long sessionID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID));
+ Long detailID = new Long(WebUtil.readLongParam(request, "detailID"));
+ String updateMode = request.getParameter("updateMode");
- List report = new ArrayList();
- report.add(submitFilesService.getFileDetails(detailID, request.getLocale()));
+ submitFilesService = getSubmitFilesService();
- request.setAttribute("report", report);
- request.setAttribute("updateMode", updateMode);
- request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID, sessionID);
+ List report = new ArrayList();
+ report.add(submitFilesService.getFileDetails(detailID, request.getLocale()));
- return mapping.findForward("updateMark");
- }
+ request.setAttribute("report", report);
+ request.setAttribute("updateMode", updateMode);
+ request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID, sessionID);
- /**
- * Update mark.
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- public ActionForward updateMark(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
- Long sessionID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID));
- Integer userID = WebUtil.readIntParam(request, "userID");
- Long detailID = new Long(WebUtil.readLongParam(request, "detailID"));
- String updateMode = request.getParameter("updateMode");
- Long reportID = new Long(WebUtil.readLongParam(request, "reportID"));
+ return mapping.findForward("updateMark");
+ }
- ActionMessages errors = new ActionMessages();
- // Check whether the mark is valid.
- Float marks = null;
- String markStr = request.getParameter("marks");
- try {
- marks = NumberUtil.getLocalisedFloat(markStr, request.getLocale());
- }
- catch (Exception e) {
- errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.mark.invalid.number"));
- }
+ /**
+ * Update mark.
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ public ActionForward updateMark(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ Long sessionID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID));
+ Integer userID = WebUtil.readIntParam(request, "userID");
+ Long detailID = new Long(WebUtil.readLongParam(request, "detailID"));
+ String updateMode = request.getParameter("updateMode");
+ Long reportID = new Long(WebUtil.readLongParam(request, "reportID"));
- String comments = WebUtil.readStrParam(request, "comments", true);
- if (!errors.isEmpty()) {
- submitFilesService = getSubmitFilesService();
- List report = new ArrayList();
- FileDetailsDTO fileDetail = submitFilesService.getFileDetails(detailID, request.getLocale());
- //echo back the input, even they are wrong.
- fileDetail.setComments(comments);
- fileDetail.setMarks(markStr);
- report.add(fileDetail);
+ ActionMessages errors = new ActionMessages();
+ // Check whether the mark is valid.
+ Float marks = null;
+ String markStr = request.getParameter("marks");
+ try {
+ marks = NumberUtil.getLocalisedFloat(markStr, request.getLocale());
+ } catch (Exception e) {
+ errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.mark.invalid.number"));
+ }
- request.setAttribute("report", report);
- request.setAttribute("updateMode", updateMode);
- request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID, sessionID);
+ String comments = WebUtil.readStrParam(request, "comments", true);
+ if (!errors.isEmpty()) {
+ submitFilesService = getSubmitFilesService();
+ List report = new ArrayList();
+ FileDetailsDTO fileDetail = submitFilesService.getFileDetails(detailID, request.getLocale());
+ // echo back the input, even they are wrong.
+ fileDetail.setComments(comments);
+ fileDetail.setMarks(markStr);
+ report.add(fileDetail);
- saveErrors(request, errors);
- return mapping.findForward("updateMark");
- }
+ request.setAttribute("report", report);
+ request.setAttribute("updateMode", updateMode);
+ request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID, sessionID);
- //get service then update report table
- submitFilesService = getSubmitFilesService();
+ saveErrors(request, errors);
+ return mapping.findForward("updateMark");
+ }
- submitFilesService.updateMarks(reportID, marks, comments);
+ // get service then update report table
+ submitFilesService = getSubmitFilesService();
- request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID, sessionID);
- if (StringUtils.equals(updateMode, "listMark")) {
- List report = submitFilesService.getFilesUploadedByUser(userID, sessionID, request.getLocale());
- request.setAttribute("report", report);
- return mapping.findForward("listMark");
- }
- else {
- Map report = submitFilesService.getFilesUploadedBySession(sessionID, request.getLocale());
- request.setAttribute("reports", report);
- return mapping.findForward("listAllMarks");
- }
+ submitFilesService.updateMarks(reportID, marks, comments);
+
+ request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID, sessionID);
+ if (StringUtils.equals(updateMode, "listMark")) {
+ List report = submitFilesService.getFilesUploadedByUser(userID, sessionID, request.getLocale());
+ request.setAttribute("report", report);
+ return mapping.findForward("listMark");
+ } else {
+ Map report = submitFilesService.getFilesUploadedBySession(sessionID, request.getLocale());
+ request.setAttribute("reports", report);
+ return mapping.findForward("listAllMarks");
}
+ }
- /**
- * View mark of all learner from same tool content ID.
- * @param mapping
- * @param form
- * @param request
- * @param response
- * @return
- */
- public ActionForward listAllMarks(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
+ /**
+ * View mark of all learner from same tool content ID.
+ *
+ * @param mapping
+ * @param form
+ * @param request
+ * @param response
+ * @return
+ */
+ public ActionForward listAllMarks(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
- Long sessionID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID));
- submitFilesService = getSubmitFilesService();
- //return FileDetailsDTO list according to the given sessionID
- Map userFilesMap = submitFilesService.getFilesUploadedBySession(sessionID, request.getLocale());
- request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID, sessionID);
- // request.setAttribute("user",submitFilesService.getUserDetails(userID));
- request.setAttribute("reports", userFilesMap);
+ Long sessionID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID));
+ submitFilesService = getSubmitFilesService();
+ // return FileDetailsDTO list according to the given sessionID
+ Map userFilesMap = submitFilesService.getFilesUploadedBySession(sessionID, request.getLocale());
+ request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID, sessionID);
+ // request.setAttribute("user",submitFilesService.getUserDetails(userID));
+ request.setAttribute("reports", userFilesMap);
- return mapping.findForward("listAllMarks");
+ return mapping.findForward("listAllMarks");
- }
+ }
- //**********************************************************
- // Private methods
- //**********************************************************
+ // **********************************************************
+ // Private methods
+ // **********************************************************
- private ISubmitFilesService getSubmitFilesService() {
- return SubmitFilesServiceProxy.getSubmitFilesService(this.getServlet().getServletContext());
- }
+ private ISubmitFilesService getSubmitFilesService() {
+ return SubmitFilesServiceProxy.getSubmitFilesService(this.getServlet().getServletContext());
+ }
- /**
- * Return ResourceService bean.
- */
- private MessageService getMessageService() {
- WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet().getServletContext());
- return (MessageService) wac.getBean("sbmtMessageService");
- }
+ /**
+ * Return ResourceService bean.
+ */
+ private MessageService getMessageService() {
+ WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet()
+ .getServletContext());
+ return (MessageService) wac.getBean("sbmtMessageService");
+ }
- /**
- * Save file mark information into HttpRequest
- * @param request
- * @param sessionID
- * @param userID
- * @param detailID
- * @param updateMode
- */
- private void setMarkPage(HttpServletRequest request, Long sessionID, Long userID, Long detailID, String updateMode) {
+ /**
+ * Save file mark information into HttpRequest
+ *
+ * @param request
+ * @param sessionID
+ * @param userID
+ * @param detailID
+ * @param updateMode
+ */
+ private void setMarkPage(HttpServletRequest request, Long sessionID, Long userID, Long detailID, String updateMode) {
- }
+ }
- /**
- * Save statistic information into request
- * @param request
- * @param submitFilesSessionList
- */
- private void statistic(HttpServletRequest request, List submitFilesSessionList) {
- Iterator it;
- Map sessionStatisticMap = new TreeMap(this.new SessionComparator());
+ /**
+ * Save statistic information into request
+ *
+ * @param request
+ * @param submitFilesSessionList
+ */
+ private void statistic(HttpServletRequest request, List submitFilesSessionList) {
+ Iterator it;
+ Map sessionStatisticMap = new TreeMap(
+ this.new SessionComparator());
- // build a map with all users in the submitFilesSessionList
- it = submitFilesSessionList.iterator();
- while (it.hasNext()) {
+ // build a map with all users in the submitFilesSessionList
+ it = submitFilesSessionList.iterator();
+ while (it.hasNext()) {
- SubmitFilesSession sfs = (SubmitFilesSession) it.next();
- Long sessionID = sfs.getSessionID();
- String sessionName = sfs.getSessionName();
+ SubmitFilesSession sfs = (SubmitFilesSession) it.next();
+ Long sessionID = sfs.getSessionID();
+ String sessionName = sfs.getSessionName();
- //return FileDetailsDTO list according to the given sessionID
- Map userFilesMap = submitFilesService.getFilesUploadedBySession(sessionID, request.getLocale());
- Iterator iter = userFilesMap.values().iterator();
- Iterator dtoIter;
- int notMarkedCount = 0;
- int markedCount = 0;
- while (iter.hasNext()) {
- List list = (List) iter.next();
- dtoIter = list.iterator();
- while (dtoIter.hasNext()) {
- FileDetailsDTO dto = (FileDetailsDTO) dtoIter.next();
- if (dto.getMarks() == null) {
- notMarkedCount++;
- }
- else {
- markedCount++;
- }
- }
- }
- StatisticDTO statisticDto = new StatisticDTO();
- SessionDTO sessionDto = new SessionDTO();
- statisticDto.setMarkedCount(markedCount);
- statisticDto.setNotMarkedCount(notMarkedCount);
- statisticDto.setTotalUploadedFiles(markedCount + notMarkedCount);
- sessionDto.setSessionID(sessionID);
- sessionDto.setSessionName(sessionName);
- sessionStatisticMap.put(sessionDto, statisticDto);
+ // return FileDetailsDTO list according to the given sessionID
+ Map userFilesMap = submitFilesService.getFilesUploadedBySession(sessionID, request.getLocale());
+ Iterator iter = userFilesMap.values().iterator();
+ Iterator dtoIter;
+ int notMarkedCount = 0;
+ int markedCount = 0;
+ while (iter.hasNext()) {
+ List list = (List) iter.next();
+ dtoIter = list.iterator();
+ while (dtoIter.hasNext()) {
+ FileDetailsDTO dto = (FileDetailsDTO) dtoIter.next();
+ if (dto.getMarks() == null) {
+ notMarkedCount++;
+ } else {
+ markedCount++;
+ }
}
-
- request.setAttribute("statisticList", sessionStatisticMap);
+ }
+ StatisticDTO statisticDto = new StatisticDTO();
+ SessionDTO sessionDto = new SessionDTO();
+ statisticDto.setMarkedCount(markedCount);
+ statisticDto.setNotMarkedCount(notMarkedCount);
+ statisticDto.setTotalUploadedFiles(markedCount + notMarkedCount);
+ sessionDto.setSessionID(sessionID);
+ sessionDto.setSessionName(sessionName);
+ sessionStatisticMap.put(sessionDto, statisticDto);
}
- /**
- * Save Summary information into HttpRequest.
- * @param request
- * @param submitFilesSessionList
- */
- private void summary(HttpServletRequest request, List submitFilesSessionList) {
- Map sessionUserMap = new TreeMap(this.new SessionComparator());
+ request.setAttribute("statisticList", sessionStatisticMap);
+ }
- //build a map with all users in the submitFilesSessionList
- Iterator it = submitFilesSessionList.iterator();
- while (it.hasNext()) {
- SessionDTO sessionDto = new SessionDTO();
- SubmitFilesSession sfs = (SubmitFilesSession) it.next();
+ /**
+ * Save Summary information into HttpRequest.
+ *
+ * @param request
+ * @param submitFilesSessionList
+ */
+ private void summary(HttpServletRequest request, List submitFilesSessionList) {
+ Map sessionUserMap = new TreeMap(this.new SessionComparator());
- Long sessionID = sfs.getSessionID();
- sessionDto.setSessionID(sessionID);
- sessionDto.setSessionName(sfs.getSessionName());
+ // build a map with all users in the submitFilesSessionList
+ Iterator it = submitFilesSessionList.iterator();
+ while (it.hasNext()) {
+ SessionDTO sessionDto = new SessionDTO();
+ SubmitFilesSession sfs = (SubmitFilesSession) it.next();
- boolean hasReflect = sfs.getContent().isReflectOnActivity();
- Map userFilesMap = submitFilesService.getFilesUploadedBySession(sessionID, request
- .getLocale());
+ Long sessionID = sfs.getSessionID();
+ sessionDto.setSessionID(sessionID);
+ sessionDto.setSessionName(sfs.getSessionName());
- //construct LearnerDTO list
- List userList = submitFilesService.getUsersBySession(sessionID);
- List learnerList = new ArrayList();
- for (SubmitUser user : userList) {
- SubmitUserDTO learnerDto = new SubmitUserDTO(user);
- learnerDto.setHasRefection(hasReflect);
+ boolean hasReflect = sfs.getContent().isReflectOnActivity();
+ Map userFilesMap = submitFilesService.getFilesUploadedBySession(sessionID,
+ request.getLocale());
- learnerDto.setAnyFilesMarked(false);
- List files = (List) userFilesMap.get(user);
- if (files != null && files.size() > 0) {
- for (FileDetailsDTO file : files) {
- if (file.getMarks() != null && file.getMarks().trim().length() > 0) {
- learnerDto.setAnyFilesMarked(true);
- break;
- }
- }
- }
+ // construct LearnerDTO list
+ List userList = submitFilesService.getUsersBySession(sessionID);
+ List learnerList = new ArrayList();
+ for (SubmitUser user : userList) {
+ SubmitUserDTO learnerDto = new SubmitUserDTO(user);
+ learnerDto.setHasRefection(hasReflect);
- learnerList.add(learnerDto);
+ learnerDto.setAnyFilesMarked(false);
+ List files = (List) userFilesMap.get(user);
+ if (files != null && files.size() > 0) {
+ for (FileDetailsDTO file : files) {
+ if (file.getMarks() != null && file.getMarks().trim().length() > 0) {
+ learnerDto.setAnyFilesMarked(true);
+ break;
}
- sessionUserMap.put(sessionDto, learnerList);
+ }
}
- //request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID,sessionID);
- request.setAttribute("sessionUserMap", sessionUserMap);
+ learnerList.add(learnerDto);
+ }
+ sessionUserMap.put(sessionDto, learnerList);
}
- public ActionForward viewReflection(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) {
- Long userUid = WebUtil.readLongParam(request, SbmtConstants.ATTR_USER_UID);
- Long sessionID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID);
+ // request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID,sessionID);
+ request.setAttribute("sessionUserMap", sessionUserMap);
+ }
- submitFilesService = getSubmitFilesService();
- SubmitUser userDto = submitFilesService.getUserByUid(userUid);
+ public ActionForward viewReflection(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ Long userUid = WebUtil.readLongParam(request, SbmtConstants.ATTR_USER_UID);
+ Long sessionID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID);
- submitFilesService = getSubmitFilesService();
- NotebookEntry notebookEntry = submitFilesService.getEntry(sessionID, CoreNotebookConstants.NOTEBOOK_TOOL,
- SbmtConstants.TOOL_SIGNATURE, userDto.getUserID());
+ submitFilesService = getSubmitFilesService();
+ SubmitUser userDto = submitFilesService.getUserByUid(userUid);
- SubmitFilesSession session = submitFilesService.getSessionById(sessionID);
+ submitFilesService = getSubmitFilesService();
+ NotebookEntry notebookEntry = submitFilesService.getEntry(sessionID, CoreNotebookConstants.NOTEBOOK_TOOL,
+ SbmtConstants.TOOL_SIGNATURE, userDto.getUserID());
- SubmitUserDTO userDTO = new SubmitUserDTO(userDto);
- if (notebookEntry == null) {
- userDTO.setFinishReflection(false);
- userDTO.setReflect(null);
- }
- else {
- userDTO.setFinishReflection(true);
- userDTO.setReflect(notebookEntry.getEntry());
- }
- userDTO.setReflectInstrctions(session.getContent().getReflectInstructions());
+ SubmitFilesSession session = submitFilesService.getSessionById(sessionID);
- request.setAttribute("userDTO", userDTO);
- return mapping.findForward("viewReflect");
+ SubmitUserDTO userDTO = new SubmitUserDTO(userDto);
+ if (notebookEntry == null) {
+ userDTO.setFinishReflection(false);
+ userDTO.setReflect(null);
+ } else {
+ userDTO.setFinishReflection(true);
+ userDTO.setReflect(notebookEntry.getEntry());
}
+ userDTO.setReflectInstrctions(session.getContent().getReflectInstructions());
+
+ request.setAttribute("userDTO", userDTO);
+ return mapping.findForward("viewReflect");
+ }
}
Index: lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/service/ISurveyService.java
===================================================================
diff -u -r05ab55ef4acdc0c374af7405c58fb0e0fe8eb6b7 -ref2417616a93e7d6f1eaee601fd78455a90564d6
--- lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/service/ISurveyService.java (.../ISurveyService.java) (revision 05ab55ef4acdc0c374af7405c58fb0e0fe8eb6b7)
+++ lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/service/ISurveyService.java (.../ISurveyService.java) (revision ef2417616a93e7d6f1eaee601fd78455a90564d6)
@@ -39,6 +39,7 @@
import org.lamsfoundation.lams.tool.survey.model.SurveyQuestion;
import org.lamsfoundation.lams.tool.survey.model.SurveySession;
import org.lamsfoundation.lams.tool.survey.model.SurveyUser;
+import org.lamsfoundation.lams.usermanagement.User;
/**
* @author Dapeng.Ni
@@ -47,233 +48,264 @@
*/
public interface ISurveyService {
- //******************************************************************************************
- // Content methods
- //******************************************************************************************
- /**
- * Get