Index: lams_build/lib/lams/lams.jar =================================================================== diff -u -r3b02878f07a0d07bf85a0c4126155b7b77d126a8 -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 Binary files differ Index: lams_common/src/java/org/lamsfoundation/lams/dao/IBaseDAO.java =================================================================== diff -u -r2dd947ef3812e8d41a9e4be552f54e71ecd1558a -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_common/src/java/org/lamsfoundation/lams/dao/IBaseDAO.java (.../IBaseDAO.java) (revision 2dd947ef3812e8d41a9e4be552f54e71ecd1558a) +++ lams_common/src/java/org/lamsfoundation/lams/dao/IBaseDAO.java (.../IBaseDAO.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -31,294 +31,327 @@ /** * @version * - *

- * View Source - *

+ *

+ * View Source + *

* * @author Fei Yang * - * Created at 22:50:25 on 16/06/2006 + * Created at 22:50:25 on 16/06/2006 */ public interface IBaseDAO { - - /** - * Insert an object into the database. Should only be used if the object has not - * been persisted previously. - * - * @param object The object to be inserted - */ - public void insert(Object object); - /** - * Update a previously inserted object into the database. - * @param object The object to be updated - */ - public void update(Object object); - /** - * Insert or update an object into the database. It is up to the persistence - * engine to decide whether to insert or update. - * @param object The object to be inserted/updated - */ - public void insertOrUpdate(Object object); - - /** - * @param objects - * @return void - */ - public void insertOrUpdateAll(Collection objects); - - /** - * Just a wrapper of the method in HibernateTemplate - * shouldn't be used unless a complicated query needed - * @param queryString - * @return void - */ - public void update(String queryString); - - /** - * Just a wrapper of the method in HibernateTemplate - * shouldn't be used unless a complicated query needed - * @param queryString - * @param value - * @return void - */ - public void update(String queryString, Object value); - - /** - * Just a wrapper of the method in HibernateTemplate - * shouldn't be used unless a complicated query needed - * @param queryString - * @param values - * @return void - */ - public void update(String queryString, Object[] values); - - /** - * @param clazz - * @param propertyToChange - * @param newValue - * @param conditionProperty - * @param conditionValue - * @return void - */ - public void update(Class clazz, String propertyToChange, Object newValue, String conditionProperty, Object conditionValue); - - /** - * @param clazz - * @param propertyToChange - * @param newValue - * @param conditions in a map - * @return void - */ - public void update(Class clazz, String propertyToChange, Object newValue, Map conditions); - - /** - * @param clazz - * @param newValues in a map - * @param conditionProperty - * @param conditionValue - * @return void - */ - public void update(Class clazz, Map newValues, String conditionProperty, Object conditionValue); - - /** - * @param clazz - * @param newValues in a map - * @param conditions in a map - * @return void - */ - public void update(Class clazz, Map newValues, Map conditions); - - /** - * These 2 objects have to be instances of the Class - * @param clazz - * @param newValues in a object - * @param conditions in a object - * @return void - */ - public void updateAnythingLike(Class clazz, Object newValues, Object conditions); - - /** - * Remove an object from the database. - * @param object The object to be deleted - */ - public void delete(Object object); - - - /** - * Be careful to use this method. It will clean up the whole table for the Class - * @param clazz - * @return void - */ - public void deleteAll(Class clazz); - - /** - * @param objects to delete - * @return void - */ - public void deleteAll(Collection objects); - - /** - * @param clazz java Class - * @param id identifier - * @return void - */ - public void deleteById(Class clazz, Serializable id); - - /** - * @param clazz - * @param name - * @param value - * @return void - */ - public void deleteByProperty(Class clazz, String name, Object value); - - /** - * @param properties a map of property names and values - * @return void - */ - public void deleteByProperties(Class clazz, Map properties); - - /** - * Delete any object which has the same non-null property values as the object - * @param object - * @return void - */ - public void deleteAnythingLike(Object object); - - /** - * Find an object. If the object is not found - * then it will return null - * @param clazz - * @param id - */ - public Object find(Class clazz, Serializable id); - - /** - * @param clazz - * @return all of rows in the table for the Class as objects - */ - public List findAll(Class clazz); - - /** - * @param clazz - * @param name - * @param value - * @return a list of objects which have the same propery value - */ - public List findByProperty(Class clazz, String name, Object value); - - /** - * @param properties a map of property names and values - * @return a list of objects which have the same property values - */ - public List findByProperties(Class clazz, Map properties); - - /** - * Find any object which has the same non-null property values as the object - * @param object - * @return a list of objects which has the same non-null property values as the object - */ - public List findAnythingLike(Object object); - - /** - * Just a wrapper of the method in HibernateTemplate - * shouldn't be used unless a complicated query needed - * @param queryString - * @return void - */ - public List find(String queryString); - - /** - * Just a wrapper of the method in HibernateTemplate - * shouldn't be used unless a complicated query needed - * @param queryString - * @param value - * @return void - */ - public List find(String queryString, Object value); - - /** - * Just a wrapper of the method in HibernateTemplate - * shouldn't be used unless a complicated query needed - * @param queryString - * @param values - * @return void - */ - public List find(String queryString, Object[] values); - - /** - * Just a wrapper of the method in HibernateTemplate - * shouldn't be used unless a complicated query needed - * @param queryName - * @return void - */ - public List findByNamedQuery(String queryName); - - /** - * Just a wrapper of the method in HibernateTemplate - * shouldn't be used unless a complicated query needed - * @param queryName - * @param value - * @return void - */ - public List findByNamedQuery(String queryName, Object value); - - /** - * Just a wrapper of the method in HibernateTemplate - * shouldn't be used unless a complicated query needed - * @param queryName - * @param values - * @return void - */ - public List findByNamedQuery(String queryName, Object[] values); - - - /** - * @param clazz - * @param name of the property - * @param pattern to match - * @return a list of objects - */ - public List searchByStringProperty(Class clazz, String name, String pattern); - - /** - * @param clazz - * @param name of the property - * @param pattern to match - * @return a list of objects - */ - public List searchByStringProperties(Class clazz, Map properties); - - /** - * @param clazz - * @param name of the property - * @param min - * @param minIncluded - * @param max - * @param maxIncluded - * @return a list of objects - */ - public List searchByNumberSpan(Class clazz, String name, Integer min, Boolean minIncluded, Integer max, Boolean maxIncluded); - - - /** - * Force initialization of a Hibernate proxy or persistent collection - * @param proxy of persistent object or a collection - */ - public void initialize(Object proxy); - - /** - * Count all rows in a table for a hibernate-mapped class - * @param clazz - * @return - */ - public long countAll(Class clazz); - - /** - * Create a query based on the properties, and count the result - * - * @param properties a map of property names and values - * @return a list of objects which have the same property values - */ - public long countByProperties(Class clazz, Map properties); + + public void flush(); + + /** + * Insert an object into the database. Should only be used if the object has not been persisted previously. + * + * @param object + * The object to be inserted + */ + public void insert(Object object); + + /** + * Update a previously inserted object into the database. + * + * @param object + * The object to be updated + */ + public void update(Object object); + + /** + * Insert or update an object into the database. It is up to the persistence engine to decide whether to insert or + * update. + * + * @param object + * The object to be inserted/updated + */ + public void insertOrUpdate(Object object); + + /** + * @param objects + * @return void + */ + public void insertOrUpdateAll(Collection objects); + + /** + * Just a wrapper of the method in HibernateTemplate shouldn't be used unless a complicated query needed + * + * @param queryString + * @return void + */ + public void update(String queryString); + + /** + * Just a wrapper of the method in HibernateTemplate shouldn't be used unless a complicated query needed + * + * @param queryString + * @param value + * @return void + */ + public void update(String queryString, Object value); + + /** + * Just a wrapper of the method in HibernateTemplate shouldn't be used unless a complicated query needed + * + * @param queryString + * @param values + * @return void + */ + public void update(String queryString, Object[] values); + + /** + * @param clazz + * @param propertyToChange + * @param newValue + * @param conditionProperty + * @param conditionValue + * @return void + */ + public void update(Class clazz, String propertyToChange, Object newValue, String conditionProperty, + Object conditionValue); + + /** + * @param clazz + * @param propertyToChange + * @param newValue + * @param conditions + * in a map + * @return void + */ + public void update(Class clazz, String propertyToChange, Object newValue, Map conditions); + + /** + * @param clazz + * @param newValues + * in a map + * @param conditionProperty + * @param conditionValue + * @return void + */ + public void update(Class clazz, Map newValues, String conditionProperty, Object conditionValue); + + /** + * @param clazz + * @param newValues + * in a map + * @param conditions + * in a map + * @return void + */ + public void update(Class clazz, Map newValues, Map conditions); + + /** + * These 2 objects have to be instances of the Class + * + * @param clazz + * @param newValues + * in a object + * @param conditions + * in a object + * @return void + */ + public void updateAnythingLike(Class clazz, Object newValues, Object conditions); + + /** + * Remove an object from the database. + * + * @param object + * The object to be deleted + */ + public void delete(Object object); + + /** + * Be careful to use this method. It will clean up the whole table for the Class + * + * @param clazz + * @return void + */ + public void deleteAll(Class clazz); + + /** + * @param objects + * to delete + * @return void + */ + public void deleteAll(Collection objects); + + /** + * @param clazz + * java Class + * @param id + * identifier + * @return void + */ + public void deleteById(Class clazz, Serializable id); + + /** + * @param clazz + * @param name + * @param value + * @return void + */ + public void deleteByProperty(Class clazz, String name, Object value); + + /** + * @param properties + * a map of property names and values + * @return void + */ + public void deleteByProperties(Class clazz, Map properties); + + /** + * Delete any object which has the same non-null property values as the object + * + * @param object + * @return void + */ + public void deleteAnythingLike(Object object); + + /** + * Find an object. If the object is not found then it will return null + * + * @param clazz + * @param id + */ + public Object find(Class clazz, Serializable id); + + /** + * @param clazz + * @return all of rows in the table for the Class as objects + */ + public List findAll(Class clazz); + + /** + * @param clazz + * @param name + * @param value + * @return a list of objects which have the same propery value + */ + public List findByProperty(Class clazz, String name, Object value); + + /** + * @param properties + * a map of property names and values + * @return a list of objects which have the same property values + */ + public List findByProperties(Class clazz, Map properties); + + /** + * Find any object which has the same non-null property values as the object + * + * @param object + * @return a list of objects which has the same non-null property values as the object + */ + public List findAnythingLike(Object object); + + /** + * Just a wrapper of the method in HibernateTemplate shouldn't be used unless a complicated query needed + * + * @param queryString + * @return void + */ + public List find(String queryString); + + /** + * Just a wrapper of the method in HibernateTemplate shouldn't be used unless a complicated query needed + * + * @param queryString + * @param value + * @return void + */ + public List find(String queryString, Object value); + + /** + * Just a wrapper of the method in HibernateTemplate shouldn't be used unless a complicated query needed + * + * @param queryString + * @param values + * @return void + */ + public List find(String queryString, Object[] values); + + /** + * Just a wrapper of the method in HibernateTemplate shouldn't be used unless a complicated query needed + * + * @param queryName + * @return void + */ + public List findByNamedQuery(String queryName); + + /** + * Just a wrapper of the method in HibernateTemplate shouldn't be used unless a complicated query needed + * + * @param queryName + * @param value + * @return void + */ + public List findByNamedQuery(String queryName, Object value); + + /** + * Just a wrapper of the method in HibernateTemplate shouldn't be used unless a complicated query needed + * + * @param queryName + * @param values + * @return void + */ + public List findByNamedQuery(String queryName, Object[] values); + + /** + * @param clazz + * @param name + * of the property + * @param pattern + * to match + * @return a list of objects + */ + public List searchByStringProperty(Class clazz, String name, String pattern); + + /** + * @param clazz + * @param name + * of the property + * @param pattern + * to match + * @return a list of objects + */ + public List searchByStringProperties(Class clazz, Map properties); + + /** + * @param clazz + * @param name + * of the property + * @param min + * @param minIncluded + * @param max + * @param maxIncluded + * @return a list of objects + */ + public List searchByNumberSpan(Class clazz, String name, Integer min, Boolean minIncluded, Integer max, + Boolean maxIncluded); + + /** + * Force initialization of a Hibernate proxy or persistent collection + * + * @param proxy + * of persistent object or a collection + */ + public void initialize(Object proxy); + + /** + * Count all rows in a table for a hibernate-mapped class + * + * @param clazz + * @return + */ + public long countAll(Class clazz); + + /** + * Create a query based on the properties, and count the result + * + * @param properties + * a map of property names and values + * @return a list of objects which have the same property values + */ + public long countByProperties(Class clazz, Map properties); } Index: lams_common/src/java/org/lamsfoundation/lams/dao/hibernate/BaseDAO.java =================================================================== diff -u -r2dd947ef3812e8d41a9e4be552f54e71ecd1558a -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_common/src/java/org/lamsfoundation/lams/dao/hibernate/BaseDAO.java (.../BaseDAO.java) (revision 2dd947ef3812e8d41a9e4be552f54e71ecd1558a) +++ lams_common/src/java/org/lamsfoundation/lams/dao/hibernate/BaseDAO.java (.../BaseDAO.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -38,344 +38,387 @@ /** * @version * - * Wrapper of HibernteTemplate() with some more OO methods + * Wrapper of HibernteTemplate() with some more OO methods * - *

- * View Source - *

+ *

+ * View Source + *

* * @author Fei Yang * - * Created at 23:13:41 on 16/06/2006 + * Created at 23:13:41 on 16/06/2006 */ public class BaseDAO extends HibernateDaoSupport implements IBaseDAO { - - private static class Qv { - - String queryString; - Object[] values; - - Qv(String queryString, Object[] values) { - super(); - - this.queryString = queryString; - this.values = values; - } - } - private static final String SELECT = "from "; - private static final String UPDATE = "update "; - private static final String DELETE = "delete "; - private static final String WHERE = " where "; - private static final String AND = " and "; - private static final String SPACE = " "; - private static final String SPOT = "."; - private static final String EQUAL_TO_WHAT = "=?"; - private static final String LIKE_WHAT = " like ?"; - - private static Logger log = Logger.getLogger(BaseDAO.class); - + private static class Qv { - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#insert(java.lang.Object) - */ - public void insert(Object object) { - getHibernateTemplate().save(object); - } + String queryString; + Object[] values; - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#update(java.lang.Object) - */ - public void update(Object object) { - getHibernateTemplate().update(object); - } + Qv(String queryString, Object[] values) { + super(); - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#insertOrUpdate(java.lang.Object) - */ - public void insertOrUpdate(Object object) { - getHibernateTemplate().saveOrUpdate(object); + this.queryString = queryString; + this.values = values; } + } - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#insertOrUpdateAll(java.util.Collection) - */ - public void insertOrUpdateAll(Collection objects) { - getHibernateTemplate().saveOrUpdateAll(objects); - } + private static final String SELECT = "from "; + private static final String UPDATE = "update "; + private static final String DELETE = "delete "; + private static final String WHERE = " where "; + private static final String AND = " and "; + private static final String SPACE = " "; + private static final String SPOT = "."; + private static final String EQUAL_TO_WHAT = "=?"; + private static final String LIKE_WHAT = " like ?"; - public void update(String queryString) { - getHibernateTemplate().bulkUpdate(queryString); - } + private static Logger log = Logger.getLogger(BaseDAO.class); - public void update(String queryString, Object value) { - getHibernateTemplate().bulkUpdate(queryString, value); - } + @Override + public void flush() { + getHibernateTemplate().flush(); + } - public void update(String queryString, Object[] values) { - getHibernateTemplate().bulkUpdate(queryString, values); - } + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#insert(java.lang.Object) + */ + @Override + public void insert(Object object) { + getHibernateTemplate().save(object); + } - public void update(Class clazz, String propertyToChange, Object newValue, String conditionProperty, Object conditionValue) { - //TODO implement me - } + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#update(java.lang.Object) + */ + @Override + public void update(Object object) { + getHibernateTemplate().update(object); + } - public void update(Class clazz, String propertyToChange, Object newValue, Map conditions) { - //TODO implement me - } + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#insertOrUpdate(java.lang.Object) + */ + @Override + public void insertOrUpdate(Object object) { + getHibernateTemplate().saveOrUpdate(object); + } - public void update(Class clazz, Map newValues, String conditionProperty, Object conditionValue) { - //TODO implement me - } + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#insertOrUpdateAll(java.util.Collection) + */ + @Override + public void insertOrUpdateAll(Collection objects) { + getHibernateTemplate().saveOrUpdateAll(objects); + } - public void update(Class clazz, Map newValues, Map conditions) { - //TODO implement me - } + @Override + public void update(String queryString) { + getHibernateTemplate().bulkUpdate(queryString); + } - public void updateAnythingLike(Class clazz, Object newValues, Object conditions) { - //TODO implement me - } + @Override + public void update(String queryString, Object value) { + getHibernateTemplate().bulkUpdate(queryString, value); + } - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#delete(java.lang.Object) - */ - public void delete(Object object) { - getHibernateTemplate().delete(object); - } + @Override + public void update(String queryString, Object[] values) { + getHibernateTemplate().bulkUpdate(queryString, values); + } - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#deleteAll(java.lang.Class) - */ - public void deleteAll(Class clazz) { - String queryString = buildQueryString(clazz,DELETE); - getHibernateTemplate().bulkUpdate(queryString); - } + @Override + public void update(Class clazz, String propertyToChange, Object newValue, String conditionProperty, + Object conditionValue) { + // TODO implement me + } - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#deleteAll(java.util.Collection) - */ - public void deleteAll(Collection objects) { - getHibernateTemplate().deleteAll(objects); - } + @Override + public void update(Class clazz, String propertyToChange, Object newValue, Map conditions) { + // TODO implement me + } - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#deleteById(java.lang.Class, java.io.Serializable) - */ - public void deleteById(Class clazz, Serializable id) { - delete(find(clazz,id)); - } + @Override + public void update(Class clazz, Map newValues, String conditionProperty, Object conditionValue) { + // TODO implement me + } - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#deleteByProperty(java.lang.Class, java.lang.String, java.lang.Object) - */ - public void deleteByProperty(Class clazz, String name, Object value) { - String queryString = buildQueryString(clazz,name,DELETE); - getHibernateTemplate().bulkUpdate(queryString,value); - } + @Override + public void update(Class clazz, Map newValues, Map conditions) { + // TODO implement me + } - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#deleteByProperties(java.lang.Class, java.util.Map) - */ - public void deleteByProperties(Class clazz, Map properties) { - Qv qv = buildQueryString(clazz,properties,DELETE,EQUAL_TO_WHAT); - getHibernateTemplate().bulkUpdate(qv.queryString,qv.values); - } + @Override + public void updateAnythingLike(Class clazz, Object newValues, Object conditions) { + // TODO implement me + } - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#deleteAnythingLike(java.lang.Object) - */ - public void deleteAnythingLike(Object object) { - try{ - Qv qv = buildQueryString(object,DELETE); - getHibernateTemplate().bulkUpdate(qv.queryString,qv.values); - }catch(Exception e){ - log.debug(e); - } - } + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#delete(java.lang.Object) + */ + @Override + public void delete(Object object) { + getHibernateTemplate().delete(object); + } - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#find(java.lang.Class, java.io.Serializable) - */ - public Object find(Class clazz, Serializable id) { - return getHibernateTemplate().get(clazz,id); - } + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#deleteAll(java.lang.Class) + */ + @Override + public void deleteAll(Class clazz) { + String queryString = buildQueryString(clazz, BaseDAO.DELETE); + getHibernateTemplate().bulkUpdate(queryString); + } - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#findAll(java.lang.Class) - */ - public List findAll(Class clazz) { - return getHibernateTemplate().loadAll(clazz); - } + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#deleteAll(java.util.Collection) + */ + @Override + public void deleteAll(Collection objects) { + getHibernateTemplate().deleteAll(objects); + } - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#findByProperty(java.lang.Class, java.lang.String, java.lang.Object) - */ - public List findByProperty(Class clazz, String name, Object value) { - String queryString = buildQueryString(clazz,name,SELECT); - return getHibernateTemplate().find(queryString,value); - } + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#deleteById(java.lang.Class, java.io.Serializable) + */ + @Override + public void deleteById(Class clazz, Serializable id) { + delete(find(clazz, id)); + } - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#findByProperties(java.lang.Class, java.util.Map) - */ - public List findByProperties(Class clazz, Map properties) { - Qv qv = buildQueryString(clazz,properties,SELECT,EQUAL_TO_WHAT); - return getHibernateTemplate().find(qv.queryString,qv.values); - } + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#deleteByProperty(java.lang.Class, java.lang.String, java.lang.Object) + */ + @Override + public void deleteByProperty(Class clazz, String name, Object value) { + String queryString = buildQueryString(clazz, name, BaseDAO.DELETE); + getHibernateTemplate().bulkUpdate(queryString, value); + } - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#findAnythingLike(java.lang.Object) - */ - public List findAnythingLike(Object object) { - return getHibernateTemplate().findByExample(object); - } - - private String buildQueryString(Class clazz,String operation){ - StringBuffer queryString = new StringBuffer(operation).append(clazz.getSimpleName()); - //log.debug(queryString); - return queryString.toString(); - } - - private String buildQueryString(Class clazz,String name, String operation){ - String clazzName = clazz.getSimpleName(); - String objName = createObjectName(clazzName); - StringBuffer queryString = new StringBuffer(operation).append(clazzName).append(SPACE) - .append(objName).append(WHERE).append(objName).append(SPOT) - .append(name).append(EQUAL_TO_WHAT); - //log.debug(queryString); - return queryString.toString(); - } - - public List find(String queryString) { - return getHibernateTemplate().find(queryString); - } + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#deleteByProperties(java.lang.Class, java.util.Map) + */ + @Override + public void deleteByProperties(Class clazz, Map properties) { + Qv qv = buildQueryString(clazz, properties, BaseDAO.DELETE, BaseDAO.EQUAL_TO_WHAT); + getHibernateTemplate().bulkUpdate(qv.queryString, qv.values); + } - public List find(String queryString, Object value) { - return getHibernateTemplate().find(queryString,value); + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#deleteAnythingLike(java.lang.Object) + */ + @Override + public void deleteAnythingLike(Object object) { + try { + Qv qv = buildQueryString(object, BaseDAO.DELETE); + getHibernateTemplate().bulkUpdate(qv.queryString, qv.values); + } catch (Exception e) { + BaseDAO.log.debug(e); } + } - public List find(String queryString, Object[] values) { - return getHibernateTemplate().find(queryString, values); - } + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#find(java.lang.Class, java.io.Serializable) + */ + @Override + public Object find(Class clazz, Serializable id) { + return getHibernateTemplate().get(clazz, id); + } - public List findByNamedQuery(String queryName) { - return getHibernateTemplate().findByNamedQuery(queryName); - } + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#findAll(java.lang.Class) + */ + @Override + public List findAll(Class clazz) { + return getHibernateTemplate().loadAll(clazz); + } - public List findByNamedQuery(String queryName, Object value) { - return getHibernateTemplate().findByNamedQuery(queryName, value); - } + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#findByProperty(java.lang.Class, java.lang.String, java.lang.Object) + */ + @Override + public List findByProperty(Class clazz, String name, Object value) { + String queryString = buildQueryString(clazz, name, BaseDAO.SELECT); + return getHibernateTemplate().find(queryString, value); + } - public List findByNamedQuery(String queryName, Object[] values) { - return getHibernateTemplate().findByNamedQuery(queryName, values); + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#findByProperties(java.lang.Class, java.util.Map) + */ + @Override + public List findByProperties(Class clazz, Map properties) { + Qv qv = buildQueryString(clazz, properties, BaseDAO.SELECT, BaseDAO.EQUAL_TO_WHAT); + return getHibernateTemplate().find(qv.queryString, qv.values); + } + + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#findAnythingLike(java.lang.Object) + */ + @Override + public List findAnythingLike(Object object) { + return getHibernateTemplate().findByExample(object); + } + + private String buildQueryString(Class clazz, String operation) { + StringBuffer queryString = new StringBuffer(operation).append(clazz.getSimpleName()); + // log.debug(queryString); + return queryString.toString(); + } + + private String buildQueryString(Class clazz, String name, String operation) { + String clazzName = clazz.getSimpleName(); + String objName = createObjectName(clazzName); + StringBuffer queryString = new StringBuffer(operation).append(clazzName).append(BaseDAO.SPACE).append(objName) + .append(BaseDAO.WHERE).append(objName).append(BaseDAO.SPOT).append(name).append(BaseDAO.EQUAL_TO_WHAT); + // log.debug(queryString); + return queryString.toString(); + } + + @Override + public List find(String queryString) { + return getHibernateTemplate().find(queryString); + } + + @Override + public List find(String queryString, Object value) { + return getHibernateTemplate().find(queryString, value); + } + + @Override + public List find(String queryString, Object[] values) { + return getHibernateTemplate().find(queryString, values); + } + + @Override + public List findByNamedQuery(String queryName) { + return getHibernateTemplate().findByNamedQuery(queryName); + } + + @Override + public List findByNamedQuery(String queryName, Object value) { + return getHibernateTemplate().findByNamedQuery(queryName, value); + } + + @Override + public List findByNamedQuery(String queryName, Object[] values) { + return getHibernateTemplate().findByNamedQuery(queryName, values); + } + + @Override + public List searchByStringProperty(Class clazz, String name, String pattern) { + // TODO implement me + return null; + } + + @Override + public List searchByStringProperties(Class clazz, Map properties) { + Map p = new HashMap(); + for (Map.Entry entry : properties.entrySet()) { + p.put(entry.getKey(), entry.getValue()); } + Qv qv = buildQueryString(clazz, p, BaseDAO.SELECT, BaseDAO.LIKE_WHAT); + return getHibernateTemplate().find(qv.queryString, qv.values); + } - public List searchByStringProperty(Class clazz, String name, String pattern) { - //TODO implement me - return null; + @Override + public List searchByNumberSpan(Class clazz, String name, Integer min, Boolean minIncluded, Integer max, + Boolean maxIncluded) { + // TODO implement me + return null; + } + + private Qv buildQueryString(Class clazz, Map properties, String operation, String condition) { + String clazzName = clazz.getSimpleName(); + String objName = createObjectName(clazzName); + StringBuffer queryString = new StringBuffer(operation).append(clazzName).append(BaseDAO.SPACE).append(objName) + .append(BaseDAO.WHERE); + Object[] values = new Object[properties.size()]; + int i = 0; + for (Map.Entry entry : properties.entrySet()) { + queryString.append(objName).append(BaseDAO.SPOT).append(entry.getKey()).append(condition); + if (i != (properties.size() - 1)) { + queryString.append(BaseDAO.AND); + } + values[i] = entry.getValue(); + i++; } + // log.debug(queryString); + return new Qv(queryString.toString(), values); + } - public List searchByStringProperties(Class clazz, Map properties) { - Map p = new HashMap(); - for(Map.Entry entry : properties.entrySet()){ - p.put(entry.getKey(), (Object)entry.getValue()); + private Qv buildQueryString(Object obj, String operation) throws Exception { + String clazzName = obj.getClass().getSimpleName(); + String objName = createObjectName(clazzName); + StringBuffer queryString = new StringBuffer(operation).append(clazzName).append(BaseDAO.SPACE).append(objName) + .append(BaseDAO.WHERE); + Field[] fields = obj.getClass().getDeclaredFields(); + List values = new ArrayList(); + for (int i = 0; i < fields.length; i++) { + String name = fields[i].getName(); + Method readMethod = getReadMethod(fields[i], name, obj.getClass()); + Object value = readMethod.invoke(obj); + if (value != null) { + queryString.append(objName).append(BaseDAO.SPOT).append(name).append(BaseDAO.EQUAL_TO_WHAT); + if (i != (fields.length - 1)) { + queryString.append(BaseDAO.AND); } - Qv qv = buildQueryString(clazz,p,SELECT,LIKE_WHAT); - return getHibernateTemplate().find(qv.queryString,qv.values); + values.add(value); + } } + // log.debug(queryString); + return new Qv(queryString.toString(), values.toArray()); + } - public List searchByNumberSpan(Class clazz, String name, Integer min, Boolean minIncluded, Integer max, Boolean maxIncluded) { - //TODO implement me - return null; + private Method getReadMethod(Field field, String fieldName, Class clazz) throws Exception { + String convertedName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); + if (field.getType().getSimpleName().equals("Boolean")) { + return clazz.getDeclaredMethod("is" + convertedName); + } else { + return clazz.getDeclaredMethod("get" + convertedName); } - - private Qv buildQueryString(Class clazz, Map properties, String operation, String condition){ - String clazzName = clazz.getSimpleName(); - String objName = createObjectName(clazzName); - StringBuffer queryString = new StringBuffer(operation).append(clazzName).append(SPACE).append(objName).append(WHERE); - Object[] values = new Object[properties.size()]; - int i=0; - for(Map.Entry entry : properties.entrySet()){ - queryString.append(objName).append(SPOT).append(entry.getKey()).append(condition); - if(i!=properties.size()-1){ - queryString.append(AND); - } - values[i] = entry.getValue(); - i++; - } - //log.debug(queryString); - return new Qv(queryString.toString(),values); + + } + + private String createObjectName(String clazzName) { + return clazzName.substring(0, 1).toLowerCase(); + } + + @Override + public void initialize(Object proxy) { + getHibernateTemplate().initialize(proxy); + } + + /* (non-Javadoc) + * @see org.lamsfoundation.lams.dao.IBaseDAO#countAll(java.lang.Class) + */ + @Override + public long countAll(Class clazz) { + String query = "select count(*) from " + clazz.getSimpleName(); + + List list = getHibernateTemplate().find(query); + + if ((list != null) && (list.size() > 0)) { + return (Long) list.get(0); + } else { + return 0; } - - private Qv buildQueryString(Object obj, String operation) throws Exception{ - String clazzName = obj.getClass().getSimpleName(); - String objName = createObjectName(clazzName); - StringBuffer queryString = new StringBuffer(operation).append(clazzName).append(SPACE).append(objName).append(WHERE); - Field[] fields = obj.getClass().getDeclaredFields(); - List values = new ArrayList(); - for(int i=0; i properties) { + Qv qv = buildQueryString(clazz, properties, BaseDAO.SELECT, BaseDAO.EQUAL_TO_WHAT); + String query = "select count(*) " + qv.queryString; + + List list = getHibernateTemplate().find(query, qv.values); + + if ((list != null) && (list.size() > 0)) { + return (Long) list.get(0); + } else { + return 0; } - - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#countAll(java.lang.Class) - */ - public long countAll(Class clazz) { - String query = "select count(*) from " + clazz.getSimpleName(); - - List list = getHibernateTemplate().find(query); - - if (list != null && list.size() > 0) { - return (Long)list.get(0); - } else { - return 0; - } - } - - /* (non-Javadoc) - * @see org.lamsfoundation.lams.dao.IBaseDAO#countByProperties(java.lang.Class, java.util.Map) - */ - public long countByProperties(Class clazz, Map properties) { - Qv qv = buildQueryString(clazz,properties,SELECT,EQUAL_TO_WHAT); - String query = "select count(*) " + qv.queryString; - - List list = getHibernateTemplate().find(query,qv.values); - - if (list != null && list.size() > 0) { - return (Long)list.get(0); - } else { - return 0; - } - } + } } Index: lams_common/src/java/org/lamsfoundation/lams/notebook/dao/INotebookEntryDAO.java =================================================================== diff -u -r38a6c414e30497d03559a85b5c33155e4a2fc22e -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_common/src/java/org/lamsfoundation/lams/notebook/dao/INotebookEntryDAO.java (.../INotebookEntryDAO.java) (revision 38a6c414e30497d03559a85b5c33155e4a2fc22e) +++ lams_common/src/java/org/lamsfoundation/lams/notebook/dao/INotebookEntryDAO.java (.../INotebookEntryDAO.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -31,21 +31,21 @@ public interface INotebookEntryDAO { - void saveOrUpdate(NotebookEntry nb); + void saveOrUpdate(NotebookEntry nb); - NotebookEntry get(Long uid); + NotebookEntry get(Long uid); - List get(Integer userID); + List get(Integer userID); - List get(Integer userID, Integer idType); - - List get(Integer userID, Long lessonID); + List get(Integer userID, Integer idType); - List get(Long id, Integer idType, Integer userID); - - List get(Long id, Integer idType, String signature, - Integer userID); - - List get(Long id, Integer idType, String signature); + List get(Integer userID, Long lessonID); -} + List get(Long id, Integer idType, Integer userID); + + List get(Long id, Integer idType, String signature, Integer userID); + + List get(Long id, Integer idType, String signature); + + void delete(NotebookEntry notebookEntry); +} \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/notebook/dao/hibernate/NotebookEntryDAO.java =================================================================== diff -u -r38a6c414e30497d03559a85b5c33155e4a2fc22e -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_common/src/java/org/lamsfoundation/lams/notebook/dao/hibernate/NotebookEntryDAO.java (.../NotebookEntryDAO.java) (revision 38a6c414e30497d03559a85b5c33155e4a2fc22e) +++ lams_common/src/java/org/lamsfoundation/lams/notebook/dao/hibernate/NotebookEntryDAO.java (.../NotebookEntryDAO.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -32,59 +32,73 @@ import org.lamsfoundation.lams.notebook.model.NotebookEntry; public class NotebookEntryDAO extends BaseDAO implements INotebookEntryDAO { - - private static final String SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID_SIG = "from " + NotebookEntry.class.getName() - + " where external_id=? and external_id_type=? and external_signature=? and user_id=?" - + " order by create_date desc"; - private static final String SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID_SIG_ALL = "from " + NotebookEntry.class.getName() - + " where external_id=? and external_id_type=? and external_signature=?" - + " order by user_id asc, create_date desc"; - private static final String SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID = "from " + NotebookEntry.class.getName() - + " where external_id=? and external_id_type=? and user_id=?" - + " order by create_date desc"; - private static final String SQL_QUERY_FIND_ENTRY_BY_USER_ID = "from " + NotebookEntry.class.getName() - + " where user_id=?"; - private static final String SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID_TYPE = "from " + NotebookEntry.class.getName() - + " where user_id=? and external_id_type=?" - + " order by external_signature desc, create_date desc"; - - - public void saveOrUpdate(NotebookEntry notebookEntry) { - this.getHibernateTemplate().saveOrUpdate(notebookEntry); - this.getHibernateTemplate().flush(); - } - public List get(Long id, Integer idType, String signature, Integer userID) { - return (List)(getHibernateTemplate().find(SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID_SIG, new Object[]{id, idType, signature, userID})); - } - - public List get(Long id, Integer idType, String signature) { - return (List)(getHibernateTemplate().find(SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID_SIG_ALL, new Object[]{id, idType, signature})); - } - - public List get(Long id, Integer idType, Integer userID) { - return (List)(getHibernateTemplate().find(SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID, new Object[]{id, idType, userID})); - } + private static final String SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID_SIG = "from " + NotebookEntry.class.getName() + + " where external_id=? and external_id_type=? and external_signature=? and user_id=?" + + " order by create_date desc"; + private static final String SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID_SIG_ALL = "from " + NotebookEntry.class.getName() + + " where external_id=? and external_id_type=? and external_signature=?" + + " order by user_id asc, create_date desc"; + private static final String SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID = "from " + NotebookEntry.class.getName() + + " where external_id=? and external_id_type=? and user_id=?" + " order by create_date desc"; + private static final String SQL_QUERY_FIND_ENTRY_BY_USER_ID = "from " + NotebookEntry.class.getName() + + " where user_id=?"; + private static final String SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID_TYPE = "from " + NotebookEntry.class.getName() + + " where user_id=? and external_id_type=?" + " order by external_signature desc, create_date desc"; - public NotebookEntry get(Long uid) { - if (uid != null) { - Object o = getHibernateTemplate().get(NotebookEntry.class, uid); - return (NotebookEntry)o; - } else { - return null; - } - } + @Override + public void saveOrUpdate(NotebookEntry notebookEntry) { + this.getHibernateTemplate().saveOrUpdate(notebookEntry); + this.getHibernateTemplate().flush(); + } - public List get(Integer userID) { - return (List)(getHibernateTemplate().find(SQL_QUERY_FIND_ENTRY_BY_USER_ID, userID)); - } + @Override + public List get(Long id, Integer idType, String signature, Integer userID) { + return (getHibernateTemplate().find(NotebookEntryDAO.SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID_SIG, + new Object[] { id, idType, signature, userID })); + } - public List get(Integer userID, Integer idType) { - return (List)(getHibernateTemplate().find(SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID_TYPE, new Object[]{userID, idType})); + @Override + public List get(Long id, Integer idType, String signature) { + return (getHibernateTemplate().find(NotebookEntryDAO.SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID_SIG_ALL, + new Object[] { id, idType, signature })); + } + + @Override + public List get(Long id, Integer idType, Integer userID) { + return (getHibernateTemplate().find(NotebookEntryDAO.SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID, + new Object[] { id, idType, userID })); + } + + @Override + public NotebookEntry get(Long uid) { + if (uid != null) { + Object o = getHibernateTemplate().get(NotebookEntry.class, uid); + return (NotebookEntry) o; + } else { + return null; } - - public List get(Integer userID, Long lessonID) { - // TODO need to write hql query for lessionID and userID - return null; - } -} + } + + @Override + public List get(Integer userID) { + return (getHibernateTemplate().find(NotebookEntryDAO.SQL_QUERY_FIND_ENTRY_BY_USER_ID, userID)); + } + + @Override + public List get(Integer userID, Integer idType) { + return (getHibernateTemplate().find(NotebookEntryDAO.SQL_QUERY_FIND_ENTRY_BY_EXTERNAL_ID_TYPE, + new Object[] { userID, idType })); + } + + @Override + public List get(Integer userID, Long lessonID) { + // TODO need to write hql query for lessionID and userID + return null; + } + + @Override + public void delete(NotebookEntry notebookEntry) { + this.getHibernateTemplate().delete(notebookEntry); + } +} \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/notebook/service/CoreNotebookService.java =================================================================== diff -u -r11e6de9b3e4fe89c16cc8545ca8f1b99a990d210 -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_common/src/java/org/lamsfoundation/lams/notebook/service/CoreNotebookService.java (.../CoreNotebookService.java) (revision 11e6de9b3e4fe89c16cc8545ca8f1b99a990d210) +++ lams_common/src/java/org/lamsfoundation/lams/notebook/service/CoreNotebookService.java (.../CoreNotebookService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -25,199 +25,208 @@ package org.lamsfoundation.lams.notebook.service; +import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.ArrayList; import java.util.TreeMap; import org.apache.log4j.Logger; import org.lamsfoundation.lams.dao.IBaseDAO; import org.lamsfoundation.lams.lesson.Lesson; import org.lamsfoundation.lams.notebook.dao.INotebookEntryDAO; import org.lamsfoundation.lams.notebook.model.NotebookEntry; +import org.lamsfoundation.lams.usermanagement.User; import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; import org.lamsfoundation.lams.util.MessageService; -import org.lamsfoundation.lams.usermanagement.User; -import org.lamsfoundation.lams.usermanagement.Role; +public class CoreNotebookService implements ICoreNotebookService { + private static Logger log = Logger.getLogger(CoreNotebookService.class); -public class CoreNotebookService implements ICoreNotebookService, IExtendedCoreNotebookService{ + private INotebookEntryDAO notebookEntryDAO; - private static Logger log = Logger.getLogger(CoreNotebookService.class); - - private INotebookEntryDAO notebookEntryDAO; - private IBaseDAO baseDAO; - protected IUserManagementService userManagementService; - - protected MessageService messageService; - - public Long createNotebookEntry(Long id, Integer idType, String signature, - Integer userID, String title, String entry) { - User user = (User)getUserManagementService().findById(User.class, userID); - NotebookEntry notebookEntry = new NotebookEntry(id, idType, signature, - user, title, entry, new Date()); - saveOrUpdateNotebookEntry(notebookEntry); - return notebookEntry.getUid(); - } - - public TreeMap> getEntryByLesson(Integer userID, Integer idType) { - TreeMap> entryMap = new TreeMap>(); - List list = getEntry(userID, idType); - - for (NotebookEntry entry : list) { - if(entryMap.containsKey(entry.getExternalID())) { - String lessonName = (String) entryMap.get(entry.getExternalID()).get(0).getLessonName(); - entry.setLessonName(lessonName); - entryMap.get(entry.getExternalID()).add(entry); - } else { - Lesson lesson = (Lesson) baseDAO.find(Lesson.class, entry.getExternalID()); - List newEntryList = new ArrayList(); - - entry.setLessonName(lesson.getLessonName()); - newEntryList.add(entry); - - entryMap.put(entry.getExternalID(), newEntryList); - } - } - - return entryMap; - } + protected IUserManagementService userManagementService; - public List getEntry(Long id, Integer idType, String signature, Integer userID) { - return notebookEntryDAO.get(id, idType, signature, userID); - } - - /** - * Add the SQL needed to look up entries for a given tool. Expects a valid string buffer to be supplied. - * This allows a tool to get the single matching entry (assuming the tool has only created one notebook entry - * for each learner in each session) for the teacher to view. This is an efficient way to get the - * entries at the same time as retrieving the tool data, rather than making a separate lookup. - * Note - if there is more than on row for each tool/session/learner, then the tool will end up with a - * cross product against the learner record and you will get one row in the learner + notebook result for each - * notebook entry. - * - * May only be used for entries where the external_id_type = CoreNotebookConstants.NOTEBOOK_TOOL - * - * The parameters are strings, and the SQL is built up rather than using parameters as either sessionIdString or - * userIdString may be the name of a field you are joining on. Typically the sessionId will be a number as the tool - * would be requesting the entries for only one session but the user field will need to be a reference to a column - * in the user table so that it can get entries for more than one user. If you wanted multiple users across - * multiple sessions, then the sessionId would need to refer to the column in the user/session table. - * - * If you only want an entry for one user, use getEntry(id, idIdType, signature, userID); - * - * The return values are the entry for the select clause (will always have a leading but no trailing comma and - * an alias of notebookEntry) and the sql join clause, which should go with any other join clauses. - * - * To make sure it always returns the same number of objects add the select clause like this: - * queryText.append(notebookEntryStrings != null ? notebookEntryStrings[0] : ", NULL notebookEntry"); - * - * Then if there is isn't a notebookEntry to return, it still returns a notebookEntry column, which translates - * to null. So you can return a collection like List irrespective of whether - * or not the notebook entries (the Strings) are needed. - * - * Finally, as it will be returning the notebook entry as a separate field in select clause, set up the sql -> java - * object translation using ".addScalar("notebookEntry", Hibernate.STRING)". - * - * @param sessionIdString Session identifier, usually the toolSessionId - * @param toolSignature Tool's string signature (without any quotes) e.g. lantbk11 - * @param userIdString User identifier field string e.g. - * @return String[] { partial select string, join clause } - * - */ - public String[] getNotebookEntrySQLStrings(String sessionIdString, String toolSignature, String userIdString) { - StringBuilder buf = new StringBuilder(" LEFT JOIN lams_notebook_entry entry ON entry.external_id="); - buf.append(sessionIdString); - buf.append(" AND entry.external_id_type="); - buf.append(CoreNotebookConstants.NOTEBOOK_TOOL); - buf.append(" AND entry.external_signature=\""); - buf.append(toolSignature); - buf.append("\" AND entry.user_id="); - buf.append(userIdString); - return new String[] { ", entry.entry notebookEntry ", buf.toString() }; - } + protected MessageService messageService; - public List getEntry(Long id, Integer idType, String signature) { - return notebookEntryDAO.get(id, idType, signature); - } - - public List getEntry(Long id, Integer idType, Integer userID) { - return notebookEntryDAO.get(id, idType, userID); - } + @Override + public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String title, + String entry) { + User user = (User) getUserManagementService().findById(User.class, userID); + NotebookEntry notebookEntry = new NotebookEntry(id, idType, signature, user, title, entry, new Date()); + saveOrUpdateNotebookEntry(notebookEntry); + return notebookEntry.getUid(); + } - public List getEntry(Integer userID) { - return notebookEntryDAO.get(userID); - } - - public List getEntry(Integer userID, Integer idType) { - return notebookEntryDAO.get(userID, idType); - } + @Override + public TreeMap> getEntryByLesson(Integer userID, Integer idType) { + TreeMap> entryMap = new TreeMap>(); + List list = getEntry(userID, idType); - public List getEntry(Integer userID, Long lessonID) { - return notebookEntryDAO.get(userID, lessonID); - } - - public NotebookEntry getEntry(Long uid) { - return notebookEntryDAO.get(uid); - } + for (NotebookEntry entry : list) { + if (entryMap.containsKey(entry.getExternalID())) { + String lessonName = entryMap.get(entry.getExternalID()).get(0).getLessonName(); + entry.setLessonName(lessonName); + entryMap.get(entry.getExternalID()).add(entry); + } else { + Lesson lesson = (Lesson) baseDAO.find(Lesson.class, entry.getExternalID()); + List newEntryList = new ArrayList(); - public void updateEntry(Long uid, String title, String entry) { - NotebookEntry ne = getEntry(uid); - if (ne != null) { - ne.setTitle(title); - ne.setEntry(entry); - ne.setLastModified(new Date()); - saveOrUpdateNotebookEntry(ne); - } else { - log.debug("updateEntry: uid " + uid + "does not exist"); - } - } + entry.setLessonName(lesson.getLessonName()); + newEntryList.add(entry); - public void updateEntry(NotebookEntry notebookEntry) { - notebookEntry.setLastModified(new Date()); - saveOrUpdateNotebookEntry(notebookEntry); + entryMap.put(entry.getExternalID(), newEntryList); + } } - public void saveOrUpdateNotebookEntry(NotebookEntry notebookEntry) { - notebookEntryDAO.saveOrUpdate(notebookEntry); - } + return entryMap; + } - /* ********** Used by Spring to "inject" the linked objects ************* */ + @Override + public List getEntry(Long id, Integer idType, String signature, Integer userID) { + return notebookEntryDAO.get(id, idType, signature, userID); + } - public void setNotebookEntryDAO(INotebookEntryDAO notebookEntryDAO) { - this.notebookEntryDAO = notebookEntryDAO; - } - - public void setBaseDAO(IBaseDAO baseDAO) { - this.baseDAO = baseDAO; - } - - /** + /** + * Add the SQL needed to look up entries for a given tool. Expects a valid string buffer to be supplied. This allows + * a tool to get the single matching entry (assuming the tool has only created one notebook entry for each learner + * in each session) for the teacher to view. This is an efficient way to get the entries at the same time as + * retrieving the tool data, rather than making a separate lookup. Note - if there is more than on row for each + * tool/session/learner, then the tool will end up with a cross product against the learner record and you will get + * one row in the learner + notebook result for each notebook entry. * - * @param IUserManagementService The userManagementService to set. + * May only be used for entries where the external_id_type = CoreNotebookConstants.NOTEBOOK_TOOL + * + * The parameters are strings, and the SQL is built up rather than using parameters as either sessionIdString or + * userIdString may be the name of a field you are joining on. Typically the sessionId will be a number as the tool + * would be requesting the entries for only one session but the user field will need to be a reference to a column + * in the user table so that it can get entries for more than one user. If you wanted multiple users across multiple + * sessions, then the sessionId would need to refer to the column in the user/session table. + * + * If you only want an entry for one user, use getEntry(id, idIdType, signature, userID); + * + * The return values are the entry for the select clause (will always have a leading but no trailing comma and an + * alias of notebookEntry) and the sql join clause, which should go with any other join clauses. + * + * To make sure it always returns the same number of objects add the select clause like this: + * queryText.append(notebookEntryStrings != null ? notebookEntryStrings[0] : ", NULL notebookEntry"); + * + * Then if there is isn't a notebookEntry to return, it still returns a notebookEntry column, which translates to + * null. So you can return a collection like List irrespective of whether or not the + * notebook entries (the Strings) are needed. + * + * Finally, as it will be returning the notebook entry as a separate field in select clause, set up the sql -> java + * object translation using ".addScalar("notebookEntry", Hibernate.STRING)". + * + * @param sessionIdString + * Session identifier, usually the toolSessionId + * @param toolSignature + * Tool's string signature (without any quotes) e.g. lantbk11 + * @param userIdString + * User identifier field string e.g. + * @return String[] { partial select string, join clause } + * */ - public void setUserManagementService(IUserManagementService userManagementService) { - this.userManagementService = userManagementService; + @Override + public String[] getNotebookEntrySQLStrings(String sessionIdString, String toolSignature, String userIdString) { + StringBuilder buf = new StringBuilder(" LEFT JOIN lams_notebook_entry entry ON entry.external_id="); + buf.append(sessionIdString); + buf.append(" AND entry.external_id_type="); + buf.append(CoreNotebookConstants.NOTEBOOK_TOOL); + buf.append(" AND entry.external_signature=\""); + buf.append(toolSignature); + buf.append("\" AND entry.user_id="); + buf.append(userIdString); + return new String[] { ", entry.entry notebookEntry ", buf.toString() }; + } + + @Override + public List getEntry(Long id, Integer idType, String signature) { + return notebookEntryDAO.get(id, idType, signature); + } + + @Override + public List getEntry(Long id, Integer idType, Integer userID) { + return notebookEntryDAO.get(id, idType, userID); + } + + @Override + public List getEntry(Integer userID, Integer idType) { + return notebookEntryDAO.get(userID, idType); + } + + @Override + public NotebookEntry getEntry(Long uid) { + return notebookEntryDAO.get(uid); + } + + @Override + public void updateEntry(Long uid, String title, String entry) { + NotebookEntry ne = getEntry(uid); + if (ne != null) { + ne.setTitle(title); + ne.setEntry(entry); + ne.setLastModified(new Date()); + saveOrUpdateNotebookEntry(ne); + } else { + CoreNotebookService.log.debug("updateEntry: uid " + uid + "does not exist"); } - - public IUserManagementService getUserManagementService() { - return userManagementService; - } - - /** - * Set i18n MessageService - */ - public void setMessageService(MessageService messageService) { - this.messageService = messageService; - } - - /** - * Get i18n MessageService - */ - public MessageService getMessageService() { - return this.messageService; - } + } + + @Override + public void updateEntry(NotebookEntry notebookEntry) { + notebookEntry.setLastModified(new Date()); + saveOrUpdateNotebookEntry(notebookEntry); + } + + @Override + public void saveOrUpdateNotebookEntry(NotebookEntry notebookEntry) { + notebookEntryDAO.saveOrUpdate(notebookEntry); + } + + @Override + public void deleteEntry(NotebookEntry notebookEntry) { + notebookEntryDAO.delete(notebookEntry); + } + + /* ********** Used by Spring to "inject" the linked objects ************* */ + + public void setNotebookEntryDAO(INotebookEntryDAO notebookEntryDAO) { + this.notebookEntryDAO = notebookEntryDAO; + } + + public void setBaseDAO(IBaseDAO baseDAO) { + this.baseDAO = baseDAO; + } + + /** + * + * @param IUserManagementService + * The userManagementService to set. + */ + public void setUserManagementService(IUserManagementService userManagementService) { + this.userManagementService = userManagementService; + } + + @Override + public IUserManagementService getUserManagementService() { + return userManagementService; + } + + /** + * Set i18n MessageService + */ + public void setMessageService(MessageService messageService) { + this.messageService = messageService; + } + + /** + * Get i18n MessageService + */ + @Override + public MessageService getMessageService() { + return this.messageService; + } } Index: lams_common/src/java/org/lamsfoundation/lams/notebook/service/ICoreNotebookService.java =================================================================== diff -u -r11e6de9b3e4fe89c16cc8545ca8f1b99a990d210 -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_common/src/java/org/lamsfoundation/lams/notebook/service/ICoreNotebookService.java (.../ICoreNotebookService.java) (revision 11e6de9b3e4fe89c16cc8545ca8f1b99a990d210) +++ lams_common/src/java/org/lamsfoundation/lams/notebook/service/ICoreNotebookService.java (.../ICoreNotebookService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -28,35 +28,37 @@ import java.util.List; import java.util.TreeMap; -import org.lamsfoundation.lams.usermanagement.User; import org.lamsfoundation.lams.notebook.model.NotebookEntry; import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; import org.lamsfoundation.lams.util.MessageService; public interface ICoreNotebookService { - Long createNotebookEntry(Long id, Integer idType, String signature, - Integer userID, String title, String entry); + Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String title, String entry); - TreeMap> getEntryByLesson(Integer userID, Integer idType); - - List getEntry(Long id, Integer idType, String signature, Integer userID); - - String[] getNotebookEntrySQLStrings(String sessionIdString, String toolSignature, String userIdString); - - List getEntry(Long id, Integer idType, String signature); - - List getEntry(Long id, Integer idType, Integer userID); - - NotebookEntry getEntry(Long uid); - - void updateEntry(Long uid, String title, String entry); - - void updateEntry(NotebookEntry notebookEntry); - - void saveOrUpdateNotebookEntry(NotebookEntry notebookEntry); - - IUserManagementService getUserManagementService(); - - MessageService getMessageService(); -} + TreeMap> getEntryByLesson(Integer userID, Integer idType); + + List getEntry(Long id, Integer idType, String signature, Integer userID); + + String[] getNotebookEntrySQLStrings(String sessionIdString, String toolSignature, String userIdString); + + List getEntry(Long id, Integer idType, String signature); + + List getEntry(Long id, Integer idType, Integer userID); + + List getEntry(Integer userID, Integer idType); + + NotebookEntry getEntry(Long uid); + + void updateEntry(Long uid, String title, String entry); + + void updateEntry(NotebookEntry notebookEntry); + + void saveOrUpdateNotebookEntry(NotebookEntry notebookEntry); + + IUserManagementService getUserManagementService(); + + MessageService getMessageService(); + + void deleteEntry(NotebookEntry entry); +} \ No newline at end of file Fisheye: Tag 9aad33f52b06632e7a8ed3705a7708338bcc00f8 refers to a dead (removed) revision in file `lams_common/src/java/org/lamsfoundation/lams/notebook/service/IExtendedCoreNotebookService.java'. Fisheye: No comparison available. Pass `N' to diff? Index: lams_common/src/java/org/lamsfoundation/lams/tool/ToolContentManager.java =================================================================== diff -u -r40eb54374e84591563d8b6a679ac719dbc85c8f7 -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_common/src/java/org/lamsfoundation/lams/tool/ToolContentManager.java (.../ToolContentManager.java) (revision 40eb54374e84591563d8b6a679ac719dbc85c8f7) +++ lams_common/src/java/org/lamsfoundation/lams/tool/ToolContentManager.java (.../ToolContentManager.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -26,7 +26,6 @@ import java.util.SortedMap; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; /** @@ -44,11 +43,11 @@ * the default content id. * * @param fromContentId - * the original tool content id. + * the original tool content id. * @param toContentId - * the destination tool content id. + * the destination tool content id. * @throws ToolException - * if an error occurs e.g. defaultContent is missing + * if an error occurs e.g. defaultContent is missing */ public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException; @@ -67,30 +66,18 @@ public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException; /** - * Remove tool's content according specified the content id. It will be needed by lams to modify the learning - * design. + * Remove tool's content according specified the content id. * - * If the tool content includes files in the content repository then the - * files should be removed from the repository. + * If the tool content includes files in the content repository then the files should be removed from the + * repository. If no matching data exists, the tool should return without throwing an exception. * - * If session data for this toolContentId exists and removeSessionData = true, then the tool should delete the - * session data as well as the content data. - * - * If session data for this toolContentId exists and removeSessionData = false, then the tool should throw - * SessionDataExists. - * - * If no matching data exists, the tool should return without throwing an exception. - * * @param toolContentId - * the requested tool content id. - * @param removeSessionData - * should it remove any related session data? + * the requested tool content id. * @throws ToolException - * if any other error occurs + * if any other error occurs */ - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException; - + public void removeToolContent(Long toolContentId) throws ToolException; + /** * Removes content previously added by the given user. */ @@ -100,17 +87,17 @@ * Export the XML fragment for the tool's content, along with any files needed for the content. * * @throws DataMissingException - * if no tool content matches the toolSessionId + * if no tool content matches the toolSessionId * @throws ToolException - * if any other error occurs + * if any other error occurs */ public void exportToolContent(Long toolContentId, String toPath) throws DataMissingException, ToolException; /** * Import the XML fragment for the tool's content, along with any files needed for the content. * * @throws ToolException - * if any other error occurs + * if any other error occurs */ public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion, String toVersion) throws ToolException; @@ -123,18 +110,18 @@ * * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition. * - * Added in LAMS 2.1 + * Added in LAMS 2.1 */ public SortedMap getToolOutputDefinitions(Long toolContentId, int definitionType) throws ToolException; public Class[] getSupportedToolOutputDefinitionClasses(int definitionType); - + /** * Finds title entered in the tool content. */ public String getToolContentTitle(Long toolContentId); - + /** * Is an activity being edited by Monitor? */ Index: lams_common/src/java/org/lamsfoundation/lams/tool/service/LamsCoreToolService.java =================================================================== diff -u -ra207bdecc16a704428826dbf402a97de2e35458b -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_common/src/java/org/lamsfoundation/lams/tool/service/LamsCoreToolService.java (.../LamsCoreToolService.java) (revision a207bdecc16a704428826dbf402a97de2e35458b) +++ lams_common/src/java/org/lamsfoundation/lams/tool/service/LamsCoreToolService.java (.../LamsCoreToolService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -92,7 +92,7 @@ /** * @param toolSessionDAO - * The toolSessionDAO to set. + * The toolSessionDAO to set. */ public void setToolSessionDAO(IToolSessionDAO toolSessionDAO) { this.toolSessionDAO = toolSessionDAO; @@ -108,16 +108,16 @@ /** * @param contentIDGenerator - * The contentIDGenerator to set. + * The contentIDGenerator to set. */ public void setContentIDGenerator(ToolContentIDGenerator contentIDGenerator) { this.contentIDGenerator = contentIDGenerator; } - + public void setToolContentDAO(IToolContentDAO toolContentDAO) { this.toolContentDAO = toolContentDAO; } - + /** * Set i18n MessageService */ @@ -177,8 +177,8 @@ try { ToolSessionManager sessionManager = (ToolSessionManager) findToolService(activity.getTool()); - sessionManager.createToolSession(toolSession.getToolSessionId(), toolSession.getToolSessionName(), activity - .getToolContentId()); + sessionManager.createToolSession(toolSession.getToolSessionId(), toolSession.getToolSessionName(), + activity.getToolContentId()); } catch (NoSuchBeanDefinitionException e) { String message = "A tool which is defined in the database appears to missing from the classpath. Unable to create tool session. ToolActivity " + activity; @@ -188,8 +188,8 @@ } @Override - public Long notifyToolToCopyContent(ToolActivity toolActivity, String customCSV) throws DataMissingException, - ToolException { + public Long notifyToolToCopyContent(ToolActivity toolActivity, String customCSV) + throws DataMissingException, ToolException { Long toolcontentID = toolActivity.getToolContentId(); try { ToolContentManager contentManager = (ToolContentManager) findToolService(toolActivity.getTool()); @@ -215,8 +215,8 @@ } @Override - public Long notifyToolToCopyContent(Long toolContentId, String customCSV) throws DataMissingException, - ToolException { + public Long notifyToolToCopyContent(Long toolContentId, String customCSV) + throws DataMissingException, ToolException { ToolContent toolContent = (ToolContent) toolContentDAO.find(ToolContent.class, toolContentId); if (toolContent == null) { String error = "The toolContentID " + toolContentId @@ -255,15 +255,15 @@ public void notifyToolToDeleteContent(ToolActivity toolActivity) throws ToolException { try { ToolContentManager contentManager = (ToolContentManager) findToolService(toolActivity.getTool()); - contentManager.removeToolContent(toolActivity.getToolContentId(), true); + contentManager.removeToolContent(toolActivity.getToolContentId()); } catch (NoSuchBeanDefinitionException e) { String message = "A tool which is defined in the database appears to missing from the classpath. Unable to delete the tool content. ToolActivity " + toolActivity; LamsCoreToolService.log.error(message, e); throw new ToolException(message, e); } } - + @Override public void notifyToolToDeleteLearnerContent(ToolActivity toolActivity, Integer userId) throws ToolException { try { @@ -305,8 +305,7 @@ LamsCoreToolService.log.error(message, e); throw new ToolException(message, e); } catch (java.lang.AbstractMethodError e) { - String message = "Tool " - + tool.getToolDisplayName() + String message = "Tool " + tool.getToolDisplayName() + " doesn't support the getToolOutputDefinitions(toolContentId) method so no output definitions can be accessed."; LamsCoreToolService.log.error(message, e); throw new ToolException(message, e); @@ -369,8 +368,7 @@ LamsCoreToolService.log.error(message, e); throw new ToolException(message, e); } catch (java.lang.AbstractMethodError e) { - String message = "Tool " - + tool.getToolDisplayName() + String message = "Tool " + tool.getToolDisplayName() + " doesn't support the getSupportedToolOutputDefinitionClasses(definitionType) method so no output definitions can be accessed."; LamsCoreToolService.log.error(message, e); throw new ToolException(message, e); @@ -414,8 +412,7 @@ LamsCoreToolService.log.error(message, e); throw new ToolException(message, e); } catch (java.lang.AbstractMethodError e) { - String message = "Tool " - + tool.getToolDisplayName() + String message = "Tool " + tool.getToolDisplayName() + " doesn't support the getToolOutput(name, toolSessionId, learnerId) method so no output definitions can be accessed."; LamsCoreToolService.log.error(message, e); throw new ToolException(message, e); @@ -447,8 +444,7 @@ LamsCoreToolService.log.error(message, e); throw new ToolException(message, e); } catch (java.lang.AbstractMethodError e) { - String message = "Tool " - + tool.getToolDisplayName() + String message = "Tool " + tool.getToolDisplayName() + " doesn't support the forceCompleteUser(ToolSession toolSession, User learner) method so can't force complete learner."; LamsCoreToolService.log.error(message, e); throw new ToolException(message, e); @@ -489,14 +485,13 @@ LamsCoreToolService.log.error(message, e); throw new ToolException(message, e); } catch (java.lang.AbstractMethodError e) { - String message = "Tool " - + tool.getToolDisplayName() + String message = "Tool " + tool.getToolDisplayName() + " doesn't support the getToolOutput(name, toolSessionId, learnerId) method so no output definitions can be accessed."; LamsCoreToolService.log.error(message, e); throw new ToolException(message, e); } } - + @Override public Long getActivityMaxPossibleMark(ToolActivity activity) { SortedMap map = getOutputDefinitionsFromTool(activity.getToolContentId(), @@ -552,8 +547,8 @@ } // call the tool to remove the session details - ToolSessionManager sessionManager = (ToolSessionManager) findToolService(toolSession.getToolActivity() - .getTool()); + ToolSessionManager sessionManager = (ToolSessionManager) findToolService( + toolSession.getToolActivity().getTool()); try { sessionManager.removeToolSession(toolSession.getToolSessionId()); @@ -612,8 +607,8 @@ } else if (activity.isSystemToolActivity()) { SystemTool sysTool = systemToolDAO.getSystemToolByActivityTypeId(activity.getActivityTypeId()); if (sysTool != null) { - return setupURLWithActivityLessonUserID(activity, lessonID, learner.getUserId(), sysTool - .getLearnerProgressUrl()); + return setupURLWithActivityLessonUserID(activity, lessonID, learner.getUserId(), + sysTool.getLearnerProgressUrl()); } } return null; @@ -651,13 +646,13 @@ @Override public String getToolAuthorURL(Long lessonID, ToolActivity activity, ToolAccessMode mode) { String url = activity.getTool().getAuthorUrl(); - url = WebUtil.appendParameterToURL(url, AttributeNames.PARAM_TOOL_CONTENT_ID, activity.getToolContentId() - .toString()); + url = WebUtil.appendParameterToURL(url, AttributeNames.PARAM_TOOL_CONTENT_ID, + activity.getToolContentId().toString()); // should have used LessonService, but reusing existing tools is just easier Lesson lesson = (Lesson) toolContentDAO.find(Lesson.class, lessonID); - url = WebUtil.appendParameterToURL(url, AttributeNames.PARAM_CONTENT_FOLDER_ID, lesson.getLearningDesign() - .getContentFolderID()); - + url = WebUtil.appendParameterToURL(url, AttributeNames.PARAM_CONTENT_FOLDER_ID, + lesson.getLearningDesign().getContentFolderID()); + url = WebUtil.appendParameterToURL(url, AttributeNames.PARAM_MODE, mode.toString()); return url; } @@ -682,11 +677,12 @@ throw new LamsToolServiceException(error); } - return WebUtil.appendParameterToURL(toolURL, AttributeNames.PARAM_TOOL_SESSION_ID, toolSession - .getToolSessionId().toString()); + return WebUtil.appendParameterToURL(toolURL, AttributeNames.PARAM_TOOL_SESSION_ID, + toolSession.getToolSessionId().toString()); } - private String setupURLWithActivityLessonUserID(Activity activity, Long lessonID, Integer userID, String learnerURL) { + private String setupURLWithActivityLessonUserID(Activity activity, Long lessonID, Integer userID, + String learnerURL) { String url = setupURLWithActivityLessonID(activity, lessonID, learnerURL); if (url != null && userID != null) { url = WebUtil.appendParameterToURL(url, AttributeNames.PARAM_USER_ID, userID.toString()); @@ -697,8 +693,8 @@ private String setupURLWithActivityLessonID(Activity activity, Long lessonID, String learnerURL) { String url = learnerURL; if (url != null && activity != null) { - url = WebUtil.appendParameterToURL(url, AttributeNames.PARAM_ACTIVITY_ID, activity.getActivityId() - .toString()); + url = WebUtil.appendParameterToURL(url, AttributeNames.PARAM_ACTIVITY_ID, + activity.getActivityId().toString()); } if (url != null && lessonID != null) { url = WebUtil.appendParameterToURL(url, AttributeNames.PARAM_LESSON_ID, lessonID.toString()); @@ -708,8 +704,8 @@ @Override public String setupToolURLWithToolContent(ToolActivity activity, String toolURL) { - return WebUtil.appendParameterToURL(toolURL, AttributeNames.PARAM_TOOL_CONTENT_ID, activity.getToolContentId() - .toString()); + return WebUtil.appendParameterToURL(toolURL, AttributeNames.PARAM_TOOL_CONTENT_ID, + activity.getToolContentId().toString()); } @Override Index: lams_common/src/java/org/lamsfoundation/lams/web/filter/TransactionRetryInterceptor.java =================================================================== diff -u -rf5fca2d435f9f8765a3ddb1c2ce162a36ba09a9e -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_common/src/java/org/lamsfoundation/lams/web/filter/TransactionRetryInterceptor.java (.../TransactionRetryInterceptor.java) (revision f5fca2d435f9f8765a3ddb1c2ce162a36ba09a9e) +++ lams_common/src/java/org/lamsfoundation/lams/web/filter/TransactionRetryInterceptor.java (.../TransactionRetryInterceptor.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -66,9 +66,13 @@ } } catch (DataIntegrityViolationException e) { exception = e; + if (exception.getCause() instanceof ConstraintViolationException) { + TransactionRetryInterceptor.log.error("Schema error", exception); + } processException(e, invocation, attempt); } catch (ConstraintViolationException e) { exception = e; + TransactionRetryInterceptor.log.error("Schema error", exception); processException(e, invocation, attempt); } catch (CannotAcquireLockException e) { exception = e; @@ -107,6 +111,6 @@ } public void setSessionFactory(SessionFactory sessionFactory) { - this.sessionFactory = sessionFactory; + this.sessionFactory = sessionFactory; } } \ No newline at end of file Index: lams_learning/src/java/org/lamsfoundation/lams/learning/web/action/NotebookAction.java =================================================================== diff -u -rd578eb0e78e1723052d35e825b00b5c735fe2f7a -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_learning/src/java/org/lamsfoundation/lams/learning/web/action/NotebookAction.java (.../NotebookAction.java) (revision d578eb0e78e1723052d35e825b00b5c735fe2f7a) +++ lams_learning/src/java/org/lamsfoundation/lams/learning/web/action/NotebookAction.java (.../NotebookAction.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -21,291 +21,260 @@ * **************************************************************** */ -/* $$Id$$ */ +/* $$Id$$ */ package org.lamsfoundation.lams.learning.web.action; +import java.io.IOException; import java.util.List; import java.util.TreeMap; -import java.lang.Integer; -import java.io.IOException; -import java.io.PrintWriter; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; -import org.apache.struts.action.DynaActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; - -import org.lamsfoundation.lams.web.action.LamsDispatchAction; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; - -import org.lamsfoundation.lams.learning.web.util.ActivityMapping; -import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; -import org.lamsfoundation.lams.notebook.service.ICoreNotebookService; -import org.lamsfoundation.lams.notebook.service.IExtendedCoreNotebookService; -import org.lamsfoundation.lams.notebook.model.NotebookEntry; - +import org.apache.struts.action.DynaActionForm; import org.lamsfoundation.lams.learning.service.ICoreLearnerService; import org.lamsfoundation.lams.learning.service.LearnerServiceProxy; - -import org.lamsfoundation.lams.usermanagement.User; -import org.lamsfoundation.lams.usermanagement.exception.UserAccessDeniedException; -import org.lamsfoundation.lams.web.util.AttributeNames; import org.lamsfoundation.lams.learning.web.util.LearningWebUtil; import org.lamsfoundation.lams.lesson.Lesson; +import org.lamsfoundation.lams.notebook.model.NotebookEntry; +import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; +import org.lamsfoundation.lams.notebook.service.ICoreNotebookService; +import org.lamsfoundation.lams.usermanagement.User; +import org.lamsfoundation.lams.usermanagement.exception.UserAccessDeniedException; import org.lamsfoundation.lams.util.WebUtil; - import org.lamsfoundation.lams.util.audit.IAuditService; +import org.lamsfoundation.lams.web.action.LamsDispatchAction; +import org.lamsfoundation.lams.web.util.AttributeNames; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.WebApplicationContextUtils; - -/** +/** * * @author M Seaton * - * ----------------XDoclet Tags-------------------- + * ----------------XDoclet Tags-------------------- * - * @struts:action name="NotebookForm" path="/notebook" - * parameter="method" - * validate="false" - * + * @struts:action name="NotebookForm" path="/notebook" parameter="method" validate="false" + * * @struts.action-forward name = "viewAll" path = ".notebookViewAll" * @struts.action-forward name= "viewSingle" path = ".notebookViewSingle" * @struts.action-forward name= "viewJournals" path = ".notebookViewJournals" * @struts.action-forward name = "addNew" path = ".notebookAddNew" - * @struts.action-forward name = "saveSuccess" path = ".notebookSaveSuccess" - * ----------------XDoclet Tags-------------------- + * @struts.action-forward name = "saveSuccess" path = ".notebookSaveSuccess" ----------------XDoclet + * Tags-------------------- * */ -public class NotebookAction extends LamsDispatchAction -{ - //--------------------------------------------------------------------- +public class NotebookAction extends LamsDispatchAction { + // --------------------------------------------------------------------- // Instance variables - //--------------------------------------------------------------------- - private static Logger log = Logger.getLogger(NotebookAction.class); + // --------------------------------------------------------------------- + private static Logger log = Logger.getLogger(NotebookAction.class); - private static IAuditService auditService; - - private static final String VIEW_ALL = "viewAll"; - private static final String VIEW_SINGLE = "viewSingle"; - private static final String VIEW_JOURNALS = "viewJournals"; - private static final String ADD_NEW = "addNew"; - private static final String SAVE_SUCCESS = "saveSuccess"; + private static IAuditService auditService; - public ICoreNotebookService getNotebookService(){ - WebApplicationContext webContext = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServlet().getServletContext()); - return (IExtendedCoreNotebookService) webContext.getBean(CoreNotebookConstants.NOTEBOOK_SERVICE_BEAN_NAME); + private static final String VIEW_ALL = "viewAll"; + private static final String VIEW_SINGLE = "viewSingle"; + private static final String VIEW_JOURNALS = "viewJournals"; + private static final String ADD_NEW = "addNew"; + private static final String SAVE_SUCCESS = "saveSuccess"; + + public ICoreNotebookService getNotebookService() { + WebApplicationContext webContext = WebApplicationContextUtils + .getRequiredWebApplicationContext(this.getServlet().getServletContext()); + return (ICoreNotebookService) webContext.getBean(CoreNotebookConstants.NOTEBOOK_SERVICE_BEAN_NAME); + } + + /** + * View all notebook entries + */ + public ActionForward viewAll(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, + HttpServletResponse response) throws IOException, ServletException { + + // initialize service object + ICoreNotebookService notebookService = getNotebookService(); + + DynaActionForm notebookForm = (DynaActionForm) actionForm; + + // getting requested object according to coming parameters + Integer learnerID = LearningWebUtil.getUserId(); + + // lessonID + Long lessonID = (Long) notebookForm.get(AttributeNames.PARAM_LESSON_ID); + + // get all notebook entries for the learner + + TreeMap> entries = notebookService.getEntryByLesson(learnerID, + CoreNotebookConstants.SCRATCH_PAD); + + request.getSession().setAttribute("entries", entries.values()); + request.setAttribute("lessonID", lessonID); + + return mapping.findForward(NotebookAction.VIEW_ALL); + + } + + /** + * View all journals entries from a lesson call + */ + public ActionForward viewAllJournals(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, + HttpServletResponse response) throws IOException, ServletException { + + // List of Journal entries + List journals = null; + + DynaActionForm notebookForm = (DynaActionForm) actionForm; + + // lesson service + ICoreLearnerService learnerService = LearnerServiceProxy.getLearnerService(getServlet().getServletContext()); + + // getting requested object according to coming parameters + Integer userID = LearningWebUtil.getUserId(); + + // lessonID + Long lessonID = (Long) notebookForm.get(AttributeNames.PARAM_LESSON_ID); + Lesson lesson = learnerService.getLesson(lessonID); + + // check user has permission + User user = (User) LearnerServiceProxy.getUserManagementService(getServlet().getServletContext()) + .findById(User.class, userID); + + if ((lesson.getUser() != null) && lesson.getUser().getUserId().equals(userID)) { + journals = getJournals(lesson.getLessonId()); } - - /** - * View all notebook entries - */ - public ActionForward viewAll( - ActionMapping mapping, - ActionForm actionForm, - HttpServletRequest request, - HttpServletResponse response) - throws IOException, ServletException { - // initialize service object - IExtendedCoreNotebookService notebookService = (IExtendedCoreNotebookService) getNotebookService(); - - DynaActionForm notebookForm = (DynaActionForm)actionForm; - - // getting requested object according to coming parameters - Integer learnerID = LearningWebUtil.getUserId(); - - // lessonID - Long lessonID = (Long) notebookForm.get(AttributeNames.PARAM_LESSON_ID); - - // get all notebook entries for the learner - - - TreeMap> entries = notebookService.getEntryByLesson(learnerID, CoreNotebookConstants.SCRATCH_PAD); - - request.getSession().setAttribute("entries", entries.values()); - request.setAttribute("lessonID", lessonID); - - return mapping.findForward(VIEW_ALL); - + if ((lesson == null) || (lesson.getLessonClass() == null) || !lesson.getLessonClass().isStaffMember(user)) { + throw new UserAccessDeniedException( + "User " + userID + " may not retrieve journal entries for lesson " + lesson.getLessonId()); + } else if (journals == null) { + journals = getJournals(lesson.getLessonId()); } - - - /** - * View all journals entries from a lesson call - */ - public ActionForward viewAllJournals( - ActionMapping mapping, - ActionForm actionForm, - HttpServletRequest request, - HttpServletResponse response) - throws IOException, ServletException { - - // List of Journal entries - List journals = null; - - DynaActionForm notebookForm = (DynaActionForm)actionForm; - - // lesson service - ICoreLearnerService learnerService = LearnerServiceProxy.getLearnerService(getServlet().getServletContext()); - // getting requested object according to coming parameters - Integer userID = LearningWebUtil.getUserId(); - - // lessonID - Long lessonID = (Long) notebookForm.get(AttributeNames.PARAM_LESSON_ID); - Lesson lesson = learnerService.getLesson(lessonID); - - // check user has permission - User user = (User)LearnerServiceProxy.getUserManagementService(getServlet().getServletContext()).findById(User.class,userID); - - if ( lesson.getUser() != null && lesson.getUser().getUserId().equals(userID) ) { - journals = getJournals(lesson.getLessonId()); - } - - if ( lesson == null || lesson.getLessonClass()==null || !lesson.getLessonClass().isStaffMember(user) ) { - throw new UserAccessDeniedException("User "+userID+" may not retrieve journal entries for lesson "+lesson.getLessonId()); - } else if(journals == null){ - journals = getJournals(lesson.getLessonId()); - } - - request.getSession().setAttribute("journals", journals); - request.setAttribute("lessonID", lessonID); - - return mapping.findForward(VIEW_JOURNALS); + request.getSession().setAttribute("journals", journals); + request.setAttribute("lessonID", lessonID); + + return mapping.findForward(NotebookAction.VIEW_JOURNALS); + } + + /** + * + * @param lessonID + * Lesson to get the journals from. + * @return List of Journal entries + */ + private List getJournals(Long lessonID) { + // initialize service object + ICoreNotebookService notebookService = getNotebookService(); + + if (lessonID == null) { + return null; } - - /** - * - * @param lessonID Lesson to get the journals from. - * @return List of Journal entries - */ - private List getJournals(Long lessonID) { - // initialize service object - ICoreNotebookService notebookService = (ICoreNotebookService) getNotebookService(); - - if(lessonID == null) - return null; - - return notebookService.getEntry(lessonID, CoreNotebookConstants.SCRATCH_PAD, CoreNotebookConstants.JOURNAL_SIG); - + + return notebookService.getEntry(lessonID, CoreNotebookConstants.SCRATCH_PAD, CoreNotebookConstants.JOURNAL_SIG); + + } + + /** + * View single notebook entry + */ + public ActionForward viewEntry(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, + HttpServletResponse response) throws IOException, ServletException { + + // initialize service object + ICoreNotebookService notebookService = getNotebookService(); + + DynaActionForm notebookForm = (DynaActionForm) actionForm; + Long uid = (Long) notebookForm.get("uid"); + String mode = WebUtil.readStrParam(request, "mode", true); + + NotebookEntry entry = notebookService.getEntry(uid); + + if (mode != null) { + request.setAttribute("mode", mode); } - - /** - * View single notebook entry - */ - public ActionForward viewEntry( - ActionMapping mapping, - ActionForm actionForm, - HttpServletRequest request, - HttpServletResponse response) - throws IOException, ServletException { - // initialize service object - IExtendedCoreNotebookService notebookService = (IExtendedCoreNotebookService) getNotebookService(); - - DynaActionForm notebookForm = (DynaActionForm)actionForm; - Long uid = (Long) notebookForm.get("uid"); - String mode = WebUtil.readStrParam(request, "mode", true); - - - NotebookEntry entry = notebookService.getEntry(uid); - - if(mode != null) - request.setAttribute("mode", mode); - - if(entry != null) - request.setAttribute("entry", entry); - - return mapping.findForward(VIEW_SINGLE); + if (entry != null) { + request.setAttribute("entry", entry); } - - - - /** - * - */ - public ActionForward processNewEntry( - ActionMapping mapping, - ActionForm actionForm, - HttpServletRequest request, - HttpServletResponse response) - throws IOException, ServletException { - - // initialize service object - ICoreNotebookService notebookService = (ICoreNotebookService) getNotebookService(); - - DynaActionForm notebookForm = (DynaActionForm)actionForm; - Long id = (Long) notebookForm.get(AttributeNames.PARAM_LESSON_ID); - String title = (String) notebookForm.get("title"); - String entry = (String) notebookForm.get("entry"); - String signature = (String) notebookForm.get("signature"); - Integer userID = LearningWebUtil.getUserId(); - - notebookService.createNotebookEntry(id, CoreNotebookConstants.SCRATCH_PAD, signature, - userID, title, entry); - - boolean skipViewAll = WebUtil.readBooleanParam(request, "skipViewAll", false); - return skipViewAll ? null : viewAll(mapping, actionForm, request, response); + + return mapping.findForward(NotebookAction.VIEW_SINGLE); + } + + /** + * + */ + public ActionForward processNewEntry(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, + HttpServletResponse response) throws IOException, ServletException { + + // initialize service object + ICoreNotebookService notebookService = getNotebookService(); + + DynaActionForm notebookForm = (DynaActionForm) actionForm; + Long id = (Long) notebookForm.get(AttributeNames.PARAM_LESSON_ID); + String title = (String) notebookForm.get("title"); + String entry = (String) notebookForm.get("entry"); + String signature = (String) notebookForm.get("signature"); + Integer userID = LearningWebUtil.getUserId(); + + notebookService.createNotebookEntry(id, CoreNotebookConstants.SCRATCH_PAD, signature, userID, title, entry); + + boolean skipViewAll = WebUtil.readBooleanParam(request, "skipViewAll", false); + return skipViewAll ? null : viewAll(mapping, actionForm, request, response); + } + + /** + * + */ + public ActionForward updateEntry(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, + HttpServletResponse response) throws IOException, ServletException { + + // initialize service object + ICoreNotebookService notebookService = getNotebookService(); + + // get form data + DynaActionForm notebookForm = (DynaActionForm) actionForm; + Long uid = (Long) notebookForm.get("uid"); + Long id = (Long) notebookForm.get(AttributeNames.PARAM_LESSON_ID); + String title = (String) notebookForm.get("title"); + String entry = (String) notebookForm.get("entry"); + String signature = (String) notebookForm.get("signature"); + + // get existing entry to edit + NotebookEntry entryObj = notebookService.getEntry(uid); + + // check entry is being edited by it's owner + Integer userID = LearningWebUtil.getUserId(); + if (userID != entryObj.getUser().getUserId()) { + // throw exception } - - /** - * - */ - public ActionForward updateEntry( - ActionMapping mapping, - ActionForm actionForm, - HttpServletRequest request, - HttpServletResponse response) - throws IOException, ServletException { - - // initialize service object - ICoreNotebookService notebookService = (ICoreNotebookService) getNotebookService(); - - // get form data - DynaActionForm notebookForm = (DynaActionForm)actionForm; - Long uid = (Long) notebookForm.get("uid"); - Long id = (Long) notebookForm.get(AttributeNames.PARAM_LESSON_ID); - String title = (String) notebookForm.get("title"); - String entry = (String) notebookForm.get("entry"); - String signature = (String) notebookForm.get("signature"); - - - // get existing entry to edit - NotebookEntry entryObj = notebookService.getEntry(uid); - - // check entry is being edited by it's owner - Integer userID = LearningWebUtil.getUserId(); - if(userID != entryObj.getUser().getUserId()) { - // throw exception - } - - //update entry - entryObj.setTitle(title); - entryObj.setEntry(entry); - entryObj.setExternalSignature(signature); - - notebookService.updateEntry(entryObj); - - return viewAll(mapping, actionForm, request, response); - + + // update entry + entryObj.setTitle(title); + entryObj.setEntry(entry); + entryObj.setExternalSignature(signature); + + notebookService.updateEntry(entryObj); + + return viewAll(mapping, actionForm, request, response); + + } + + /** + * Get AuditService bean. + * + * @return + */ + private IAuditService getAuditService() { + if (NotebookAction.auditService == null) { + WebApplicationContext ctx = WebApplicationContextUtils + .getRequiredWebApplicationContext(getServlet().getServletContext()); + NotebookAction.auditService = (IAuditService) ctx.getBean("auditService"); } - - /** - * Get AuditService bean. - * @return - */ - private IAuditService getAuditService(){ - if(auditService==null){ - WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet().getServletContext()); - auditService = (IAuditService) ctx.getBean("auditService"); - } - return auditService; - } - + return NotebookAction.auditService; + } + } \ No newline at end of file Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/IMonitoringService.java =================================================================== diff -u -r1b3256ab2070e6b8b91c1c5df04b5ad0e52635a2 -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/IMonitoringService.java (.../IMonitoringService.java) (revision 1b3256ab2070e6b8b91c1c5df04b5ad0e52635a2) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/IMonitoringService.java (.../IMonitoringService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -342,9 +342,14 @@ * @param userId * checks that the user is a staff member for this lesson */ - void removeLesson(long lessonId, Integer userId) throws UserAccessDeniedException; + void removeLesson(long lessonId, Integer userId) throws SecurityException; /** + * Removes the lesson and all referenced resources (learning design, tool content etc.) from the database. + */ + void removeLessonPermanently(long lessonId, Integer userId) throws SecurityException; + + /** * Set the gate to open to let all the learners through. This learning service is triggerred by the system * scheduler. Will return true GateActivity (or subclass) object, rather than a hibernate proxy. This is needed so * that the class can be returned to the web layer for proper handling. @@ -669,13 +674,13 @@ * Activity id of the branchingActivity */ SortedSet getGroupsNotAssignedToBranch(Long branchingActivityID) throws LessonServiceException; - + /** * Get all the users records where the user has attempted the given activity, but has not completed it yet. Uses the * progress records to determine the users. */ List getLearnersAttemptedActivity(Activity activity); - + /** * 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. Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/MonitoringService.java =================================================================== diff -u -r2c9f5c4fd2a8e8e664d53cf362b85eaa8dc387ed -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/MonitoringService.java (.../MonitoringService.java) (revision 2c9f5c4fd2a8e8e664d53cf362b85eaa8dc387ed) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/MonitoringService.java (.../MonitoringService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -53,6 +53,8 @@ import org.lamsfoundation.lams.learning.service.ICoreLearnerService; import org.lamsfoundation.lams.learning.web.bean.GateActivityDTO; import org.lamsfoundation.lams.learningdesign.Activity; +import org.lamsfoundation.lams.learningdesign.BranchActivityEntry; +import org.lamsfoundation.lams.learningdesign.BranchCondition; import org.lamsfoundation.lams.learningdesign.BranchingActivity; import org.lamsfoundation.lams.learningdesign.ChosenGrouping; import org.lamsfoundation.lams.learningdesign.ComplexActivity; @@ -83,7 +85,10 @@ import org.lamsfoundation.lams.logevent.service.ILogEventService; import org.lamsfoundation.lams.monitoring.MonitoringConstants; import org.lamsfoundation.lams.monitoring.dto.ContributeActivityDTO; +import org.lamsfoundation.lams.notebook.model.NotebookEntry; +import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; import org.lamsfoundation.lams.security.ISecurityService; +import org.lamsfoundation.lams.tool.ToolContent; import org.lamsfoundation.lams.tool.ToolSession; import org.lamsfoundation.lams.tool.exception.LamsToolServiceException; import org.lamsfoundation.lams.tool.service.ILamsCoreToolService; @@ -932,7 +937,68 @@ setLessonState(requestedLesson, Lesson.REMOVED_STATE); } + @SuppressWarnings("unchecked") @Override + public void removeLessonPermanently(long lessonId, Integer userId) { + securityService.isLessonMonitor(lessonId, userId, "remove lesson permanently", true); + + Lesson lesson = lessonDAO.getLesson(lessonId); + LearningDesign learningDesign = lesson.getLearningDesign(); + + // remove lesson resources + lessonDAO.deleteByProperty(LogEvent.class, "lessonId", lessonId); + lessonDAO.deleteByProperty(ToolSession.class, "lesson.lessonId", lessonId); + Map notebookProperties = new TreeMap(); + notebookProperties.put("externalID", lessonId); + notebookProperties.put("externalSignature", CoreNotebookConstants.SCRATCH_PAD_SIG); + lessonDAO.deleteByProperties(NotebookEntry.class, notebookProperties); + lessonDAO.deleteLesson(lesson); + + // remove each Tool activity content + // It has to be done before removing BranchEntries as fetching Tool content + // in its own transaction would re-add connected BranchEntries (Hibernate error) + Set systemActivities = new HashSet(); + for (Activity activity : (Set) learningDesign.getActivities()) { + // get the real object, not the proxy + activity = activityDAO.getActivityByActivityId(activity.getActivityId()); + if (activity.isToolActivity()) { + ToolActivity toolActivity = (ToolActivity) activity; + // delete content of each tool + lamsCoreToolService.notifyToolToDeleteContent(toolActivity); + // possible nonthreadsafe access to session!!! + lessonDAO.flush(); + Long toolContentId = toolActivity.getToolContentId(); + lessonDAO.deleteById(ToolContent.class, toolContentId); + } else { + systemActivities.add(activity); + } + } + + // remove branching and grouping resources + for (Activity activity : systemActivities) { + if (activity.isBranchingActivity()) { + BranchingActivity branchingActivity = (BranchingActivity) activity; + Grouping grouping = branchingActivity.getGrouping(); + groupingDAO.delete(grouping); + + for (BranchActivityEntry entry : branchingActivity.getBranchActivityEntries()) { + BranchCondition condition = entry.getCondition(); + if (condition != null) { + lessonDAO.deleteById(BranchCondition.class, condition.getConditionId()); + } + } + } else if (activity.isGroupingActivity()) { + GroupingActivity groupingActivity = (GroupingActivity) activity; + Grouping grouping = groupingActivity.getCreateGrouping(); + groupingDAO.delete(grouping); + } + } + + // finally remove the learning design + lessonDAO.delete(learningDesign); + } + + @Override public Boolean setLearnerPortfolioAvailable(long lessonId, Integer userId, Boolean isLearnerExportAvailable) { securityService.isLessonMonitor(lessonId, userId, "set learner portfolio available", true); @@ -2350,10 +2416,10 @@ } @Override - public List getLearnersAttemptedActivity(Activity activity){ + public List getLearnersAttemptedActivity(Activity activity) { return learnerProgressDAO.getLearnersAttemptedActivity(activity); } - + @Override public List getLearnersAttemptedOrCompletedActivity(Activity activity) throws LessonServiceException { return lessonService.getLearnersAttemptedOrCompletedActivity(activity); @@ -2370,7 +2436,8 @@ } @Override - public List getLearnersByActivities(Long[] activityIds, Integer limit, Integer offset, boolean orderAscending) { + public List getLearnersByActivities(Long[] activityIds, Integer limit, Integer offset, + boolean orderAscending) { return learnerProgressDAO.getLearnersByActivities(activityIds, limit, offset, orderAscending); } @@ -2414,12 +2481,11 @@ @Override public int cloneLessons(String[] lessonIds, Boolean addAllStaff, Boolean addAllLearners, String[] staffIds, String[] learnerIds, Organisation group) throws MonitoringServiceException { - int result = 0; - HttpSession ss = SessionManager.getSession(); - if (ss != null) { - UserDTO userDto = (UserDTO) ss.getAttribute(AttributeNames.USER); - if (userDto != null) { + HttpSession ss = SessionManager.getSession(); + if (ss != null) { + UserDTO userDto = (UserDTO) ss.getAttribute(AttributeNames.USER); + if (userDto != null) { Integer creatorId = userDto.getUserID(); for (String lessonIdStr : lessonIds) { @@ -2446,44 +2512,44 @@ Lesson lesson = lessonService.getLesson(lessonId); if (lesson != null) { - if ((!addAllStaff && (staffIds.length > 0)) || addAllStaff) { - // create staff LessonClass - String staffGroupName = group.getName() + " Staff"; - List staffUsers = createStaffGroup(group.getOrganisationId(), addAllStaff, staffIds); + if ((!addAllStaff && (staffIds.length > 0)) || addAllStaff) { + // create staff LessonClass + String staffGroupName = group.getName() + " Staff"; + List staffUsers = createStaffGroup(group.getOrganisationId(), addAllStaff, staffIds); - if ((!addAllLearners && (learnerIds.length > 0)) || addAllLearners) { - // create learner LessonClass for lesson - String learnerGroupName = group.getName() + " Learners"; + if ((!addAllLearners && (learnerIds.length > 0)) || addAllLearners) { + // create learner LessonClass for lesson + String learnerGroupName = group.getName() + " Learners"; List learnerUsers = createLearnerGroup(group.getOrganisationId(), addAllLearners, learnerIds); - // init Lesson with user as creator + // init Lesson with user as creator newLesson = this.initializeLesson(lesson.getLessonName(), lesson.getLessonDescription(), lesson .getLearningDesign().getLearningDesignId(), group.getOrganisationId(), creatorId, null, lesson.isEnableLessonIntro(), lesson.isDisplayDesignImage(), lesson .getLearnerExportAvailable(), lesson.getLearnerPresenceAvailable(), lesson .getLearnerImAvailable(), lesson.getLiveEditEnabled(), lesson .getEnableLessonNotifications(), lesson.getLearnerRestart(), null, null); - // save LessonClasses + // save LessonClasses newLesson = this.createLessonClassForLesson(newLesson.getLessonId(), group, learnerGroupName, learnerUsers, staffGroupName, staffUsers, creatorId); - // start Lessons - // TODO user-specified creator; must be someone in staff group - this.startLesson(newLesson.getLessonId(), staffUsers.get(0).getUserId()); + // start Lessons + // TODO user-specified creator; must be someone in staff group + this.startLesson(newLesson.getLessonId(), staffUsers.get(0).getUserId()); - } else { + } else { throw new MonitoringServiceException("No learners specified, can't create any Lessons."); - } - } else { - throw new MonitoringServiceException("No staff specified, can't create any Lessons."); - } - } else { + } + } else { + throw new MonitoringServiceException("No staff specified, can't create any Lessons."); + } + } else { throw new MonitoringServiceException("Couldn't find Lesson based on id=" + lessonId); - } + } return newLesson.getLessonId(); - } + } /* * Used in cloneLessons. Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/MonitoringAction.java =================================================================== diff -u -r3dcdc86bb42ea2451ca470c75a959eff48d0c931 -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/MonitoringAction.java (.../MonitoringAction.java) (revision 3dcdc86bb42ea2451ca470c75a959eff48d0c931) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/MonitoringAction.java (.../MonitoringAction.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -579,15 +579,22 @@ */ public ActionForward removeLesson(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException, ServletException { - long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); - JSONObject jsonObject = new JSONObject(); + Integer userId = getUserId(); + boolean permanently = WebUtil.readBooleanParam(request, "permanently", false); + if (permanently) { + getMonitoringService().removeLessonPermanently(lessonId, userId); + response.setContentType("text/plain;charset=utf-8"); + response.getWriter().print("OK"); + return null; + } + + JSONObject jsonObject = new JSONObject(); try { // if this method throws an Exception, there will be no removeLesson=true in the JSON reply - getMonitoringService().removeLesson(lessonId, getUserId()); + getMonitoringService().removeLesson(lessonId, userId); jsonObject.put("removeLesson", true); - } catch (Exception e) { String[] msg = new String[1]; msg[0] = e.getMessage(); Index: lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java =================================================================== diff -u -rdb4bd53f341896f8d1087dda549c89b3ab785ede -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java (.../AssessmentServiceImpl.java) (revision db4bd53f341896f8d1087dda549c89b3ab785ede) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java (.../AssessmentServiceImpl.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -42,7 +42,6 @@ import java.util.regex.Pattern; import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.tomcat.util.json.JSONArray; @@ -100,7 +99,6 @@ import org.lamsfoundation.lams.tool.assessment.util.AssessmentToolContentHandler; import org.lamsfoundation.lams.tool.assessment.util.SequencableComparator; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.usermanagement.Organisation; @@ -295,18 +293,18 @@ public List getUsersBySession(Long toolSessionID) { return assessmentUserDao.getBySessionID(toolSessionID); } - + @Override - public List getPagedUsersBySession(Long sessionId, int page, int size, String sortBy, String sortOrder, - String searchString) { + public List getPagedUsersBySession(Long sessionId, int page, int size, String sortBy, + String sortOrder, String searchString) { return assessmentUserDao.getPagedUsersBySession(sessionId, page, size, sortBy, sortOrder, searchString); } - + @Override public int getCountUsersBySession(Long sessionId, String searchString) { return assessmentUserDao.getCountUsersBySession(sessionId, searchString); } - + @Override public List getPagedUsersBySessionAndQuestion(Long sessionId, Long questionUid, int page, int size, String sortBy, String sortOrder, String searchString) { @@ -407,12 +405,12 @@ public void setAttemptStarted(Assessment assessment, AssessmentUser assessmentUser, Long toolSessionId) { AssessmentResult lastResult = getLastAssessmentResult(assessment.getUid(), assessmentUser.getUserId()); if (lastResult != null) { - + // don't instantiate new attempt if the previous one wasn't finished and thus continue working with it if (lastResult.getFinishDate() == null) { return; - - // mark previous attempt as not the latest anymore + + // mark previous attempt as not the latest anymore } else { lastResult.setLatest(false); assessmentResultDao.saveObject(lastResult); @@ -752,7 +750,7 @@ public int getAssessmentResultCount(Long assessmentUid, Long userId) { return assessmentResultDao.getAssessmentResultCount(assessmentUid, userId); } - + @Override public AssessmentQuestionResult getAssessmentQuestionResultByUid(Long questionResultUid) { return assessmentQuestionResultDao.getAssessmentQuestionResultByUid(questionResultUid); @@ -833,7 +831,7 @@ } return nextUrl; } - + @Override public List getSessionDtos(Long contentId) { List sessionDtos = new ArrayList(); @@ -842,18 +840,18 @@ for (AssessmentSession session : sessionList) { Long sessionId = session.getSessionId(); SessionDTO sessionDto = new SessionDTO(sessionId, session.getSessionName()); - - //for statistics tab + + // for statistics tab int countUsers = assessmentUserDao.getCountUsersBySession(sessionId, ""); sessionDto.setNumberLearners(countUsers); - + sessionDtos.add(sessionDto); } - + return sessionDtos; } - //remove method once we remove export portfolio + // remove method once we remove export portfolio @Override @Deprecated public List getSessionDataForExport(Long contentId) { @@ -966,34 +964,34 @@ return userSummary; } - + @Override public QuestionSummary getQuestionSummary(Long contentId, Long questionUid) { QuestionSummary questionSummary = new QuestionSummary(); AssessmentQuestion question = assessmentQuestionDao.getByUid(questionUid); questionSummary.setQuestion(question); - + return questionSummary; } @Override public Map getQuestionSummaryForExport(Assessment assessment) { Map questionSummaries = new HashMap(); - + if (assessment.getQuestions() == null) { return questionSummaries; } - + SortedSet sessions = new TreeSet(new AssessmentSessionComparator()); sessions.addAll(assessmentSessionDao.getByContentId(assessment.getContentId())); - - List assessmentResults = assessmentResultDao.getLastFinishedAssessmentResults(assessment - .getContentId()); + + List assessmentResults = assessmentResultDao + .getLastFinishedAssessmentResults(assessment.getContentId()); Map userUidToResultMap = new HashMap(); for (AssessmentResult assessmentResult : assessmentResults) { userUidToResultMap.put(assessmentResult.getUser().getUid(), assessmentResult); } - + Map> sessionIdToUsersMap = new HashMap>(); for (AssessmentSession session : sessions) { @@ -1012,7 +1010,7 @@ sessionIdToUsersMap.put(sessionId, users); } - + for (AssessmentQuestion question : (Set) assessment.getQuestions()) { Long questionUid = question.getUid(); QuestionSummary questionSummary = new QuestionSummary(); @@ -1070,9 +1068,10 @@ return questionSummaries; } - + @Override - public LinkedHashMap exportSummary(Assessment assessment, List sessionDtos, boolean showUserNames) { + public LinkedHashMap exportSummary(Assessment assessment, List sessionDtos, + boolean showUserNames) { LinkedHashMap dataToExport = new LinkedHashMap(); final ExcelCell[] EMPTY_ROW = new ExcelCell[0]; @@ -1134,10 +1133,10 @@ dataToExport.put(getMessage("label.export.summary"), summaryTab.toArray(new ExcelCell[][] {})); } - + // ------------------------------------------------------------------ // -------------- Second tab: Question Summary ---------------------- - + ArrayList questionSummaryTab = new ArrayList(); // Create the question summary @@ -1148,15 +1147,16 @@ Map questionSummaries = getQuestionSummaryForExport(assessment); if (assessment.getQuestions() != null) { - Set questions = (Set) assessment.getQuestions(); - + Set questions = assessment.getQuestions(); + // question row title int count = 0; ExcelCell[] summaryRowTitle = showUserNames ? new ExcelCell[10] : new ExcelCell[9]; summaryRowTitle[count++] = new ExcelCell(getMessage("label.monitoring.question.summary.question"), true); summaryRowTitle[count++] = new ExcelCell(getMessage("label.authoring.basic.list.header.type"), true); summaryRowTitle[count++] = new ExcelCell(getMessage("label.authoring.basic.penalty.factor"), true); - summaryRowTitle[count++] = new ExcelCell(getMessage("label.monitoring.question.summary.default.mark"), true); + summaryRowTitle[count++] = new ExcelCell(getMessage("label.monitoring.question.summary.default.mark"), + true); summaryRowTitle[count++] = new ExcelCell(getMessage("label.export.user.id"), true); if (showUserNames) { summaryRowTitle[count++] = new ExcelCell(getMessage("label.monitoring.user.summary.user.name"), true); @@ -1184,12 +1184,13 @@ if (showUserNames) { ExcelCell[] userResultRow = new ExcelCell[10]; userResultRow[0] = new ExcelCell(questionResult.getAssessmentQuestion().getTitle(), false); - userResultRow[1] = new ExcelCell(getQuestionTypeLanguageLabel(questionResult - .getAssessmentQuestion().getType()), false); - userResultRow[2] = new ExcelCell(new Float(questionResult.getAssessmentQuestion() - .getPenaltyFactor()), false); - Float maxMark = (questionResult.getMaxMark() == null) ? 0 : new Float( - questionResult.getMaxMark()); + userResultRow[1] = new ExcelCell( + getQuestionTypeLanguageLabel(questionResult.getAssessmentQuestion().getType()), + false); + userResultRow[2] = new ExcelCell( + new Float(questionResult.getAssessmentQuestion().getPenaltyFactor()), false); + Float maxMark = (questionResult.getMaxMark() == null) ? 0 + : new Float(questionResult.getMaxMark()); userResultRow[3] = new ExcelCell(maxMark, false); userResultRow[4] = new ExcelCell(questionResult.getUser().getUserId(), false); userResultRow[5] = new ExcelCell(questionResult.getUser().getFullName(), false); @@ -1199,7 +1200,7 @@ AssessmentResult assessmentResult = questionResult.getAssessmentResult(); Date finishDate = questionResult.getFinishDate(); - if (assessmentResult != null && finishDate != null) { + if ((assessmentResult != null) && (finishDate != null)) { Date startDate = assessmentResult.getStartDate(); if (startDate != null) { Long seconds = (finishDate.getTime() - startDate.getTime()) / 1000; @@ -1220,12 +1221,13 @@ } else { ExcelCell[] userResultRow = new ExcelCell[9]; userResultRow[0] = new ExcelCell(questionResult.getAssessmentQuestion().getTitle(), false); - userResultRow[1] = new ExcelCell(getQuestionTypeLanguageLabel(questionResult - .getAssessmentQuestion().getType()), false); - userResultRow[2] = new ExcelCell(new Float(questionResult.getAssessmentQuestion() - .getPenaltyFactor()), false); - Float maxMark = (questionResult.getMaxMark() == null) ? 0 : new Float( - questionResult.getMaxMark()); + userResultRow[1] = new ExcelCell( + getQuestionTypeLanguageLabel(questionResult.getAssessmentQuestion().getType()), + false); + userResultRow[2] = new ExcelCell( + new Float(questionResult.getAssessmentQuestion().getPenaltyFactor()), false); + Float maxMark = (questionResult.getMaxMark() == null) ? 0 + : new Float(questionResult.getMaxMark()); userResultRow[3] = new ExcelCell(maxMark, false); userResultRow[4] = new ExcelCell(questionResult.getUser().getUserId(), false); userResultRow[5] = new ExcelCell(questionResult.getFinishDate(), false); @@ -1235,7 +1237,7 @@ if (questionResult.getAssessmentResult() != null) { Date startDate = questionResult.getAssessmentResult().getStartDate(); Date finishDate = questionResult.getFinishDate(); - if (startDate != null && finishDate != null) { + if ((startDate != null) && (finishDate != null)) { Long seconds = (finishDate.getTime() - startDate.getTime()) / 1000; userResultRow[7] = new ExcelCell(seconds, false); timeTakenCount++; @@ -1295,10 +1297,10 @@ } dataToExport.put(getMessage("lable.export.summary.by.question"), questionSummaryTab.toArray(new ExcelCell[][] {})); - + // ------------------------------------------------------------------ // -------------- Third tab: User Summary --------------------------- - + ArrayList userSummaryTab = new ArrayList(); // Create the question summary @@ -1370,13 +1372,13 @@ } if (sessionDtos != null) { - List assessmentResults = assessmentResultDao.getLastFinishedAssessmentResults(assessment - .getContentId()); + List assessmentResults = assessmentResultDao + .getLastFinishedAssessmentResults(assessment.getContentId()); Map userUidToResultMap = new HashMap(); for (AssessmentResult assessmentResult : assessmentResults) { userUidToResultMap.put(assessmentResult.getUser().getUid(), assessmentResult); } - + for (SessionDTO sessionDTO : sessionDtos) { userSummaryTab.add(EMPTY_ROW); @@ -1396,23 +1398,21 @@ if (showUserNames) { ExcelCell[] userTitleRow = new ExcelCell[6]; userTitleRow[0] = new ExcelCell(getMessage("label.export.user.id"), true); - userTitleRow[1] = new ExcelCell( - getMessage("label.monitoring.user.summary.user.name"), true); + userTitleRow[1] = new ExcelCell(getMessage("label.monitoring.user.summary.user.name"), + true); userTitleRow[2] = new ExcelCell(getMessage("label.export.date.attempted"), true); - userTitleRow[3] = new ExcelCell( - getMessage("label.monitoring.question.summary.question"), true); - userTitleRow[4] = new ExcelCell(getMessage("label.authoring.basic.option.answer"), + userTitleRow[3] = new ExcelCell(getMessage("label.monitoring.question.summary.question"), true); + userTitleRow[4] = new ExcelCell(getMessage("label.authoring.basic.option.answer"), true); userTitleRow[5] = new ExcelCell(getMessage("label.export.mark"), true); userSummaryTab.add(userTitleRow); } else { ExcelCell[] userTitleRow = new ExcelCell[5]; userTitleRow[0] = new ExcelCell(getMessage("label.export.user.id"), true); userTitleRow[1] = new ExcelCell(getMessage("label.export.date.attempted"), true); - userTitleRow[2] = new ExcelCell( - getMessage("label.monitoring.question.summary.question"), true); - userTitleRow[3] = new ExcelCell(getMessage("label.authoring.basic.option.answer"), + userTitleRow[2] = new ExcelCell(getMessage("label.monitoring.question.summary.question"), true); + userTitleRow[3] = new ExcelCell(getMessage("label.authoring.basic.option.answer"), true); userTitleRow[4] = new ExcelCell(getMessage("label.export.mark"), true); userSummaryTab.add(userTitleRow); } @@ -1431,8 +1431,8 @@ userResultRow[0] = new ExcelCell(assessmentUser.getUserId(), false); userResultRow[1] = new ExcelCell(assessmentUser.getFullName(), false); userResultRow[2] = new ExcelCell(assessmentResult.getStartDate(), false); - userResultRow[3] = new ExcelCell(questionResult.getAssessmentQuestion() - .getTitle(), false); + userResultRow[3] = new ExcelCell( + questionResult.getAssessmentQuestion().getTitle(), false); userResultRow[4] = new ExcelCell( AssessmentEscapeUtils.printResponsesForExcelExport(questionResult), false); @@ -1442,8 +1442,8 @@ ExcelCell[] userResultRow = new ExcelCell[5]; userResultRow[0] = new ExcelCell(assessmentUser.getUserId(), false); userResultRow[1] = new ExcelCell(assessmentResult.getStartDate(), false); - userResultRow[2] = new ExcelCell(questionResult.getAssessmentQuestion() - .getTitle(), false); + userResultRow[2] = new ExcelCell( + questionResult.getAssessmentQuestion().getTitle(), false); userResultRow[3] = new ExcelCell( AssessmentEscapeUtils.printResponsesForExcelExport(questionResult), false); @@ -1456,13 +1456,11 @@ ExcelCell[] userTotalRow; if (showUserNames) { userTotalRow = new ExcelCell[6]; - userTotalRow[4] = new ExcelCell(getMessage("label.monitoring.summary.total"), - true); + userTotalRow[4] = new ExcelCell(getMessage("label.monitoring.summary.total"), true); userTotalRow[5] = new ExcelCell(assessmentResult.getGrade(), false); } else { userTotalRow = new ExcelCell[5]; - userTotalRow[3] = new ExcelCell(getMessage("label.monitoring.summary.total"), - true); + userTotalRow[3] = new ExcelCell(getMessage("label.monitoring.summary.total"), true); userTotalRow[4] = new ExcelCell(assessmentResult.getGrade(), false); } @@ -1474,10 +1472,10 @@ } } dataToExport.put(getMessage("label.export.summary.by.user"), userSummaryTab.toArray(new ExcelCell[][] {})); - + return dataToExport; } - + /** * Used only for excell export (for getUserSummaryData() method). */ @@ -1498,7 +1496,7 @@ case AssessmentConstants.QUESTION_TYPE_TRUE_FALSE: return "True/False"; case AssessmentConstants.QUESTION_TYPE_MARK_HEDGING: - return "Mark Hedging"; + return "Mark Hedging"; default: return null; } @@ -2127,17 +2125,22 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) - throws SessionDataExistsException, ToolException { + public void removeToolContent(Long toolContentId) throws ToolException { Assessment assessment = assessmentDao.getByContentId(toolContentId); - if (removeSessionData) { - List list = assessmentSessionDao.getByContentId(toolContentId); - Iterator iter = list.iterator(); - while (iter.hasNext()) { - AssessmentSession session = (AssessmentSession) iter.next(); - assessmentSessionDao.delete(session); + if (assessment == null) { + AssessmentServiceImpl.log + .warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (AssessmentSession session : assessmentSessionDao.getByContentId(toolContentId)) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, AssessmentConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); } } + assessmentDao.delete(assessment); } @@ -2167,7 +2170,7 @@ assessmentDao.removeObject(NotebookEntry.class, entry.getUid()); } - if (session.getGroupLeader() != null && session.getGroupLeader().getUid().equals(user.getUid())) { + if ((session.getGroupLeader() != null) && session.getGroupLeader().getUid().equals(user.getUid())) { session.setGroupLeader(null); } @@ -2434,7 +2437,8 @@ assessment.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); assessment.setShuffled(JsonUtil.opt(toolContentJSON, "shuffled", Boolean.FALSE)); assessment.setTimeLimit(JsonUtil.opt(toolContentJSON, "timeLimit", 0)); - assessment.setUseSelectLeaderToolOuput(JsonUtil.opt(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE)); + assessment.setUseSelectLeaderToolOuput( + JsonUtil.opt(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE)); // submission deadline set in monitoring if (toolContentJSON.has("overallFeedback")) { @@ -2557,9 +2561,11 @@ // TODO Implement REST support for all types and then remove checkType method void checkType(short type) throws JSONException { - if (type != AssessmentConstants.QUESTION_TYPE_ESSAY && type != AssessmentConstants.QUESTION_TYPE_MULTIPLE_CHOICE) { + if ((type != AssessmentConstants.QUESTION_TYPE_ESSAY) + && (type != AssessmentConstants.QUESTION_TYPE_MULTIPLE_CHOICE)) { throw new JSONException( - "Assessment Tool does not support REST Authoring for anything but Essay Type and Multiple Choice. Found type " + type); + "Assessment Tool does not support REST Authoring for anything but Essay Type and Multiple Choice. Found type " + + type); } // public static final short QUESTION_TYPE_MATCHING_PAIRS = 2; // public static final short QUESTION_TYPE_SHORT_ANSWER = 3; Index: lams_tool_bbb/src/java/org/lamsfoundation/lams/tool/bbb/service/BbbService.java =================================================================== diff -u -ra207bdecc16a704428826dbf402a97de2e35458b -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_bbb/src/java/org/lamsfoundation/lams/tool/bbb/service/BbbService.java (.../BbbService.java) (revision a207bdecc16a704428826dbf402a97de2e35458b) +++ lams_tool_bbb/src/java/org/lamsfoundation/lams/tool/bbb/service/BbbService.java (.../BbbService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -44,6 +44,7 @@ import org.lamsfoundation.lams.learningdesign.service.IExportToolContentService; import org.lamsfoundation.lams.learningdesign.service.ImportToolContentException; import org.lamsfoundation.lams.notebook.model.NotebookEntry; +import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; import org.lamsfoundation.lams.notebook.service.ICoreNotebookService; import org.lamsfoundation.lams.tool.ToolContentManager; import org.lamsfoundation.lams.tool.ToolOutput; @@ -62,7 +63,6 @@ import org.lamsfoundation.lams.tool.bbb.util.BbbUtil; import org.lamsfoundation.lams.tool.bbb.util.Constants; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.usermanagement.User; @@ -102,9 +102,10 @@ } /* Methods from ToolSessionManager */ + @Override public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("entering method createToolSession:" + " toolSessionId = " + toolSessionId + if (BbbService.logger.isDebugEnabled()) { + BbbService.logger.debug("entering method createToolSession:" + " toolSessionId = " + toolSessionId + " toolSessionName = " + toolSessionName + " toolContentId = " + toolContentId); } @@ -117,17 +118,21 @@ bbbSessionDAO.insertOrUpdate(session); } + @Override public String leaveToolSession(Long toolSessionId, Long learnerId) throws DataMissingException, ToolException { return learnerService.completeToolSession(toolSessionId, learnerId); } - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + @Override + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } + @Override @SuppressWarnings("unchecked") - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -146,19 +151,20 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return null; } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /* Methods from ToolContentManager */ + @Override public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("entering method copyToolContent:" + " fromContentId=" + fromContentId + " toContentId=" - + toContentId); + if (BbbService.logger.isDebugEnabled()) { + BbbService.logger.debug("entering method copyToolContent:" + " fromContentId=" + fromContentId + + " toContentId=" + toContentId); } if (toContentId == null) { @@ -177,7 +183,7 @@ Bbb toContent = Bbb.newInstance(fromContent, toContentId, bbbToolContentHandler); saveOrUpdateBbb(toContent); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Bbb bbb = getBbbByContentId(toolContentId); @@ -189,20 +195,35 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { - // TODO Auto-generated method stub + public void removeToolContent(Long toolContentId) throws ToolException { + Bbb bbb = getBbbByContentId(toolContentId); + if (bbb == null) { + BbbService.logger.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (BbbSession session : bbb.getBbbSessions()) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, Constants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); + } + } + + bbbDAO.delete(bbb); } - + + @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("Resetting Web Conference completion flag for user ID " + userId + " and toolContentId " - + toolContentId); + if (BbbService.logger.isDebugEnabled()) { + BbbService.logger.debug("Resetting Web Conference completion flag for user ID " + userId + + " and toolContentId " + toolContentId); } Bbb bbb = getBbbByContentId(toolContentId); if (bbb == null) { - logger.warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); + BbbService.logger + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } @@ -230,13 +251,15 @@ * if any other error occurs */ + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { Bbb bbb = getBbbByContentId(toolContentId); if (bbb == null) { bbb = getDefaultContent(); } - if (bbb == null) + if (bbb == null) { throw new DataMissingException("Unable to find default content for the bbb tool"); + } // set ResourceToolContentHandler as null to avoid copy file node in // repository again. @@ -256,17 +279,19 @@ * @throws ToolException * if any other error occurs */ + @Override public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion, String toVersion) throws ToolException { try { // register version filter class exportContentService.registerImportVersionFilterClass(BbbImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, bbbToolContentHandler, fromVersion, toVersion); - if (!(toolPOJO instanceof Bbb)) - throw new ImportToolContentException("Import Bbb tool content failed. Deserialized object is " - + toolPOJO); + if (!(toolPOJO instanceof Bbb)) { + throw new ImportToolContentException( + "Import Bbb tool content failed. Deserialized object is " + toolPOJO); + } Bbb bbb = (Bbb) toolPOJO; // reset it to new toolContentId @@ -279,10 +304,11 @@ } } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return null; } - + /** * 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 @@ -291,74 +317,84 @@ * * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition */ + @Override public SortedMap getToolOutputDefinitions(Long toolContentId, int definitionType) throws ToolException { return new TreeMap(); } + @Override public String getToolContentTitle(Long toolContentId) { return getBbbByContentId(toolContentId).getTitle(); } - + + @Override public boolean isContentEdited(Long toolContentId) { return getBbbByContentId(toolContentId).isDefineLater(); } - + /* IBbbService Methods */ + @Override public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry) { return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); } public NotebookEntry getEntry(Long id, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(id, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); } } + @Override public NotebookEntry getNotebookEntry(Long uid) { return coreNotebookService.getEntry(uid); } + @Override public void updateNotebookEntry(Long uid, String entry) { coreNotebookService.updateEntry(uid, "", entry); } + @Override public void updateNotebookEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } + @Override public Long getDefaultContentIdBySignature(String toolSignature) { Long toolContentId = null; toolContentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature)); if (toolContentId == null) { String error = "Could not retrieve default content id for this tool"; - logger.error(error); + BbbService.logger.error(error); throw new BbbException(error); } return toolContentId; } + @Override public Bbb getDefaultContent() { Long defaultContentID = getDefaultContentIdBySignature(Constants.TOOL_SIGNATURE); Bbb defaultContent = getBbbByContentId(defaultContentID); if (defaultContent == null) { String error = "Could not retrieve default content record for this tool"; - logger.error(error); + BbbService.logger.error(error); throw new BbbException(error); } return defaultContent; } + @Override public Bbb copyDefaultContent(Long newContentID) { if (newContentID == null) { String error = "Cannot copy the Bbb tools default content: + " + "newContentID is null"; - logger.error(error); + BbbService.logger.error(error); throw new BbbException(error); } @@ -370,6 +406,7 @@ return newContent; } + @Override @SuppressWarnings("unchecked") public Bbb getBbbByContentId(Long toolContentID) { List list = bbbDAO.findByProperty(Bbb.class, "toolContentId", toolContentID); @@ -380,6 +417,7 @@ } } + @Override @SuppressWarnings("unchecked") public BbbSession getSessionBySessionId(Long toolSessionId) { List list = bbbSessionDAO.findByProperty(BbbSession.class, "sessionId", toolSessionId); @@ -390,6 +428,7 @@ } } + @Override @SuppressWarnings("unchecked") public BbbUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { Map map = new HashMap(); @@ -403,6 +442,7 @@ } } + @Override @SuppressWarnings("unchecked") public BbbUser getUserByUID(Long uid) { List list = bbbUserDAO.findByProperty(BbbUser.class, "uid", uid); @@ -413,159 +453,151 @@ } } + @Override public String getJoinMeetingURL(UserDTO userDTO, String meetingKey, String password) throws Exception { // Get Bbb details String serverURL = getConfigValue(Constants.CFG_SERVER_URL); - String securitySalt = getConfigValue(Constants.CFG_SECURITYSALT); + String securitySalt = getConfigValue(Constants.CFG_SECURITYSALT); // Get Join parameter String joinParam = Constants.BBB_JOIN_PARAM; - + if (serverURL == null) { - logger.error("Config item : '" + Constants.CFG_SERVER_URL + "' not defined"); + BbbService.logger.error("Config item : '" + Constants.CFG_SERVER_URL + "' not defined"); throw new BbbException("Server url not defined"); } - String queryString = "fullName=" - + URLEncoder.encode(userDTO.getFirstName() + " " + userDTO.getLastName(), "UTF8") - + "&meetingID=" - + URLEncoder.encode(meetingKey, "UTF8") - + "&password=" - + URLEncoder.encode(password, "UTF8"); - - String checkSum = DigestUtils.shaHex("join" + queryString + securitySalt); - + String queryString = "fullName=" + + URLEncoder.encode(userDTO.getFirstName() + " " + userDTO.getLastName(), "UTF8") + "&meetingID=" + + URLEncoder.encode(meetingKey, "UTF8") + "&password=" + URLEncoder.encode(password, "UTF8"); + + String checkSum = DigestUtils.shaHex("join" + queryString + securitySalt); + String url = serverURL + joinParam + queryString + "&checksum=" + checkSum; return url; - } - - public Boolean isMeetingRunning(String meetingKey) throws Exception { - String serverURL = getConfigValue(Constants.CFG_SERVER_URL); - String securitySalt = getConfigValue(Constants.CFG_SECURITYSALT); - String meetingRunning = Constants.BBB_MEETING_RUNNING_PARAM; - - String queryString = "meetingID=" - + URLEncoder.encode(meetingKey, "UTF8"); - - String checkSum = DigestUtils.shaHex("isMeetingRunning" + queryString + securitySalt); - - URL url; - url = new URL(serverURL - + meetingRunning - + queryString - + "&checksum=" - + URLEncoder.encode(checkSum, "UTF8")); + } - logger.debug("isMeetingRunningURL=" + url); - - String response; - response = sendRequest(url); - - if (response.contains("true")) { - return true; - } else { - return false; - } - + @Override + public Boolean isMeetingRunning(String meetingKey) throws Exception { + String serverURL = getConfigValue(Constants.CFG_SERVER_URL); + String securitySalt = getConfigValue(Constants.CFG_SECURITYSALT); + String meetingRunning = Constants.BBB_MEETING_RUNNING_PARAM; + + String queryString = "meetingID=" + URLEncoder.encode(meetingKey, "UTF8"); + + String checkSum = DigestUtils.shaHex("isMeetingRunning" + queryString + securitySalt); + + URL url; + url = new URL(serverURL + meetingRunning + queryString + "&checksum=" + URLEncoder.encode(checkSum, "UTF8")); + + BbbService.logger.debug("isMeetingRunningURL=" + url); + + String response; + response = sendRequest(url); + + if (response.contains("true")) { + return true; + } else { + return false; + } + } - - - public String startConference(String meetingKey, String atendeePassword, - String moderatorPassword, String returnURL, - String welcomeMessage) - throws Exception { + @Override + public String startConference(String meetingKey, String atendeePassword, String moderatorPassword, String returnURL, + String welcomeMessage) throws Exception { + String serverURL = getConfigValue(Constants.CFG_SERVER_URL); String securitySalt = getConfigValue(Constants.CFG_SECURITYSALT); String createParam = Constants.BBB_CREATE_PARAM; - + if (serverURL == null) { - logger.error("Config item : '" + Constants.CFG_SERVER_URL + "' not defined"); + BbbService.logger.error("Config item : '" + Constants.CFG_SERVER_URL + "' not defined"); throw new BbbException("Standard server url not defined"); } - - String queryString = "name=" - + URLEncoder.encode(meetingKey, "UTF8") + "&meetingID=" - + URLEncoder.encode(meetingKey, "UTF8") + "&attendeePW=" - + URLEncoder.encode(atendeePassword, "UTF8") + "&moderatorPW=" - + URLEncoder.encode(moderatorPassword, "UTF8") + "&logoutURL=" - + URLEncoder.encode(returnURL, "UTF8") + "&welcome=" - + URLEncoder.encode(welcomeMessage, "UTF8"); - logger.debug("queryString = " + queryString); - + String queryString = "name=" + URLEncoder.encode(meetingKey, "UTF8") + "&meetingID=" + + URLEncoder.encode(meetingKey, "UTF8") + "&attendeePW=" + URLEncoder.encode(atendeePassword, "UTF8") + + "&moderatorPW=" + URLEncoder.encode(moderatorPassword, "UTF8") + "&logoutURL=" + + URLEncoder.encode(returnURL, "UTF8") + "&welcome=" + URLEncoder.encode(welcomeMessage, "UTF8"); + + BbbService.logger.debug("queryString = " + queryString); + String checkSum = DigestUtils.shaHex("create" + queryString + securitySalt); - logger.debug("checksum = " + checkSum); - + BbbService.logger.debug("checksum = " + checkSum); + URL url; - url = new URL(serverURL - + createParam - + queryString - + "&checksum=" - + URLEncoder.encode(checkSum, "UTF8")); + url = new URL(serverURL + createParam + queryString + "&checksum=" + URLEncoder.encode(checkSum, "UTF8")); - logger.info("url = " + url); - + BbbService.logger.info("url = " + url); + String response; response = sendRequest(url); - + if (BbbUtil.getResponse(response) == Constants.RESPONSE_SUCCESS) { - return Constants.RESPONSE_SUCCESS; + return Constants.RESPONSE_SUCCESS; } else { - logger.error("BBB returns fail when creating a meeting room"); + BbbService.logger.error("BBB returns fail when creating a meeting room"); throw new BbbException("Standard server url not defined"); } } - + + @Override public void saveOrUpdateBbb(Bbb bbb) { bbbDAO.insertOrUpdate(bbb); } + @Override public void saveOrUpdateBbbSession(BbbSession bbbSession) { bbbSessionDAO.insertOrUpdate(bbbSession); } + @Override public void saveOrUpdateBbbUser(BbbUser bbbUser) { bbbUserDAO.insertOrUpdate(bbbUser); } + @Override public BbbUser createBbbUser(UserDTO user, BbbSession bbbSession) { BbbUser bbbUser = new BbbUser(user, bbbSession); saveOrUpdateBbbUser(bbbUser); return bbbUser; } + @Override @SuppressWarnings("unchecked") public BbbConfig getConfig(String key) { - List list = (List) bbbConfigDAO.findByProperty(BbbConfig.class, "key", key); + List list = bbbConfigDAO.findByProperty(BbbConfig.class, "key", key); if (list.isEmpty()) { return null; } else { return list.get(0); } } + @Override @SuppressWarnings("unchecked") public String getConfigValue(String key) { - List list = (List) bbbConfigDAO.findByProperty(BbbConfig.class, "key", key); + List list = bbbConfigDAO.findByProperty(BbbConfig.class, "key", key); if (list.isEmpty()) { return null; } else { return list.get(0).getValue(); } } + @Override public void saveOrUpdateConfigEntry(BbbConfig bbbConfig) { bbbConfigDAO.insertOrUpdate(bbbConfig); } private String sendRequest(URL url) throws IOException { - if (logger.isDebugEnabled()) { - logger.debug("request = " + url); + if (BbbService.logger.isDebugEnabled()) { + BbbService.logger.debug("request = " + url); } URLConnection connection = url.openConnection(); @@ -574,12 +606,13 @@ String response = ""; String line = ""; - while ((line = in.readLine()) != null) + while ((line = in.readLine()) != null) { response += line; + } in.close(); - if (logger.isDebugEnabled()) { - logger.debug("response = " + response); + if (BbbService.logger.isDebugEnabled()) { + BbbService.logger.debug("response = " + response); } return response; @@ -588,11 +621,11 @@ /** * 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 { + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { - logger - .warn("Setting the reflective field on a bbb. This doesn't make sense as the bbb is for reflection and we don't reflect on reflection!"); + BbbService.logger.warn( + "Setting the reflective field on a bbb. This doesn't make sense as the bbb is for reflection and we don't reflect on reflection!"); Bbb bbb = getBbbByContentId(toolContentId); if (bbb == null) { throw new DataMissingException("Unable to set reflective data titled " + title Index: lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/ChatService.java =================================================================== diff -u -ra207bdecc16a704428826dbf402a97de2e35458b -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/ChatService.java (.../ChatService.java) (revision a207bdecc16a704428826dbf402a97de2e35458b) +++ lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/ChatService.java (.../ChatService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -68,7 +68,6 @@ import org.lamsfoundation.lams.tool.chat.util.ChatException; import org.lamsfoundation.lams.tool.chat.util.ChatMessageFilter; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.usermanagement.User; @@ -85,7 +84,8 @@ * As a requirement, all LAMS tool's service bean must implement ToolContentManager and ToolSessionManager. */ -public class ChatService implements ToolSessionManager, ToolContentManager, ToolContentImport102Manager, IChatService, ToolRestManager { +public class ChatService + implements ToolSessionManager, ToolContentManager, ToolContentImport102Manager, IChatService, ToolRestManager { private static Logger logger = Logger.getLogger(ChatService.class.getName()); @@ -114,6 +114,7 @@ private Random generator = new Random(); /* Methods from ToolSessionManager */ + @Override public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException { if (ChatService.logger.isDebugEnabled()) { ChatService.logger.debug("entering method createToolSession:" + " toolSessionId = " + toolSessionId @@ -170,14 +171,15 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { // TODO Auto-generated method stub return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { // TODO Auto-generated method stub return null; } @@ -197,10 +199,10 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return getChatOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /* Methods from ToolContentManager */ @@ -229,7 +231,7 @@ Chat toContent = Chat.newInstance(fromContent, toContentId); chatDAO.saveOrUpdate(toContent); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Chat chat = chatDAO.getByContentId(toolContentId); @@ -240,19 +242,37 @@ chatDAO.saveOrUpdate(chat); } - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { - // TODO Auto-generated method stub + @SuppressWarnings("unchecked") + @Override + public void removeToolContent(Long toolContentId) throws ToolException { + Chat chat = chatDAO.getByContentId(toolContentId); + if (chat == null) { + ChatService.logger.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (ChatSession session : (Set) chat.getChatSessions()) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, ChatConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); + } + } + + chatDAO.delete(chat); } + @Override @SuppressWarnings("unchecked") public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("Removing Chat messages for user ID " + userId + " and toolContentId " + toolContentId); + if (ChatService.logger.isDebugEnabled()) { + ChatService.logger + .debug("Removing Chat messages for user ID " + userId + " and toolContentId " + toolContentId); } Chat chat = chatDAO.getByContentId(toolContentId); if (chat == null) { - logger.warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); + ChatService.logger + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } @@ -280,7 +300,7 @@ } } - + /** * Export the XML fragment for the tool's content, along with any files needed for the content. * @@ -290,6 +310,7 @@ * if any other error occurs */ + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { Chat chat = chatDAO.getByContentId(toolContentId); if (chat == null) { @@ -316,17 +337,18 @@ * @throws ToolException * if any other error occurs */ + @Override public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion, String toVersion) throws ToolException { try { // register version filter class exportContentService.registerImportVersionFilterClass(ChatImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, chatToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof Chat)) { - throw new ImportToolContentException("Import Chat tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import Chat tool content failed. Deserialized object is " + toolPOJO); } Chat chat = (Chat) toolPOJO; @@ -348,6 +370,7 @@ * * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition */ + @Override public SortedMap getToolOutputDefinitions(Long toolContentId, int definitionType) throws ToolException { Chat chat = getChatDAO().getByContentId(toolContentId); @@ -359,15 +382,18 @@ return getChatOutputFactory().getToolOutputDefinitions(chat, definitionType); } + @Override public String getToolContentTitle(Long toolContentId) { return getChatByContentId(toolContentId).getTitle(); } - + + @Override public boolean isContentEdited(Long toolContentId) { return getChatByContentId(toolContentId).isDefineLater(); } /* IChatService Methods */ + @Override public Long getDefaultContentIdBySignature(String toolSignature) { Long toolContentId = null; toolContentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature)); @@ -379,6 +405,7 @@ return toolContentId; } + @Override public Chat getDefaultContent() { Long defaultContentID = getDefaultContentIdBySignature(ChatConstants.TOOL_SIGNATURE); Chat defaultContent = getChatByContentId(defaultContentID); @@ -388,12 +415,13 @@ throw new ChatException(error); } if (defaultContent.getConditions().isEmpty()) { - defaultContent.getConditions().add( - getChatOutputFactory().createDefaultUserMessagesCondition(defaultContent)); + defaultContent.getConditions() + .add(getChatOutputFactory().createDefaultUserMessagesCondition(defaultContent)); } return defaultContent; } + @Override public Chat copyDefaultContent(Long newContentID) { if (newContentID == null) { @@ -410,6 +438,7 @@ return newContent; } + @Override public Chat getChatByContentId(Long toolContentID) { Chat chat = chatDAO.getByContentId(toolContentID); if (chat == null) { @@ -418,6 +447,7 @@ return chat; } + @Override public ChatSession getSessionBySessionId(Long toolSessionId) { ChatSession chatSession = chatSessionDAO.getBySessionId(toolSessionId); if (chatSession == null) { @@ -426,30 +456,36 @@ return chatSession; } + @Override public List getUsersActiveBySessionId(Long toolSessionId) { Date oldestLastPresence = new Date(System.currentTimeMillis() - ChatConstants.PRESENCE_IDLE_TIMEOUT); return chatUserDAO.getBySessionIdAndLastPresence(toolSessionId, oldestLastPresence); } + @Override public ChatUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { return chatUserDAO.getByUserIdAndSessionId(userId, toolSessionId); } + @Override public ChatUser getUserByLoginNameAndSessionId(String loginName, Long toolSessionId) { return chatUserDAO.getByLoginNameAndSessionId(loginName, toolSessionId); } + @Override public ChatUser getUserByUID(Long uid) { return chatUserDAO.getByUID(uid); } + @Override public ChatUser getUserByNicknameAndSessionID(String nickname, Long sessionID) { return chatUserDAO.getByNicknameAndSessionID(nickname, sessionID); } /** * Stores information when users with given UIDs were last seen in their Chat session. */ + @Override public void updateUserPresence(Map presence) { for (Long userUid : presence.keySet()) { ChatUser chatUser = chatUserDAO.getByUID(userUid); @@ -458,34 +494,41 @@ } } + @Override public List getMessagesForUser(ChatUser chatUser) { return chatMessageDAO.getForUser(chatUser); } /** * {@inheritDoc} */ + @Override public List getMessagesSentByUser(Long userUid) { return chatMessageDAO.getSentByUser(userUid); } + @Override public void saveOrUpdateChat(Chat chat) { updateMessageFilters(chat); chatDAO.saveOrUpdate(chat); } + @Override public void saveOrUpdateChatSession(ChatSession chatSession) { chatSessionDAO.saveOrUpdate(chatSession); } + @Override public void saveOrUpdateChatUser(ChatUser chatUser) { chatUserDAO.saveOrUpdate(chatUser); } + @Override public void saveOrUpdateChatMessage(ChatMessage chatMessage) { chatMessageDAO.saveOrUpdate(chatMessage); } + @Override public synchronized ChatUser createChatUser(UserDTO user, ChatSession chatSession) { ChatUser chatUser = new ChatUser(user, chatSession); @@ -515,6 +558,7 @@ return nickname; } + @Override public String filterMessage(String message, Chat chat) { Pattern pattern = getFilterPattern(chat); @@ -549,16 +593,19 @@ return pattern; } + @Override public ChatMessageFilter updateMessageFilters(Chat chat) { ChatMessageFilter filter = new ChatMessageFilter(chat); messageFilters.put(chat.getToolContentId(), filter); return filter; } + @Override public ChatMessage getMessageByUID(Long messageUID) { return chatMessageDAO.getByUID(messageUID); } + @Override public List getLastestMessages(ChatSession chatSession, int max) { return chatMessageDAO.getLatest(chatSession, max); } @@ -571,21 +618,24 @@ this.auditService = auditService; } + @Override public void auditEditMessage(ChatMessage chatMessage, String messageBody) { - auditService.logChange(ChatConstants.TOOL_SIGNATURE, chatMessage.getFromUser().getUserId(), chatMessage - .getFromUser().getLoginName(), chatMessage.getBody(), messageBody); + auditService.logChange(ChatConstants.TOOL_SIGNATURE, chatMessage.getFromUser().getUserId(), + chatMessage.getFromUser().getLoginName(), chatMessage.getBody(), messageBody); } + @Override public void auditHideShowMessage(ChatMessage chatMessage, boolean messageHidden) { if (messageHidden) { - auditService.logHideEntry(ChatConstants.TOOL_SIGNATURE, chatMessage.getFromUser().getUserId(), chatMessage - .getFromUser().getLoginName(), chatMessage.toString()); + auditService.logHideEntry(ChatConstants.TOOL_SIGNATURE, chatMessage.getFromUser().getUserId(), + chatMessage.getFromUser().getLoginName(), chatMessage.toString()); } else { - auditService.logShowEntry(ChatConstants.TOOL_SIGNATURE, chatMessage.getFromUser().getUserId(), chatMessage - .getFromUser().getLoginName(), chatMessage.toString()); + auditService.logShowEntry(ChatConstants.TOOL_SIGNATURE, chatMessage.getFromUser().getUserId(), + chatMessage.getFromUser().getLoginName(), chatMessage.toString()); } } + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } @@ -657,10 +707,12 @@ this.exportContentService = exportContentService; } + @Override public Map getMessageCountBySession(Long chatUID) { return chatMessageDAO.getCountBySession(chatUID); } + @Override public Map getMessageCountByFromUser(Long sessionUID) { return chatMessageDAO.getCountByFromUser(sessionUID); } @@ -673,10 +725,12 @@ this.coreNotebookService = coreNotebookService; } + @Override public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry) { return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); } + @Override public NotebookEntry getEntry(Long id, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(id, idType, signature, userID); @@ -690,6 +744,7 @@ /** * @param notebookEntry */ + @Override public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } @@ -701,6 +756,7 @@ /** * Import the data for a 1.0.2 Chat */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { Date now = new Date(); Chat chat = new Chat(); @@ -710,8 +766,8 @@ chat.setDefineLater(Boolean.FALSE); chat.setFilterKeywords(null); chat.setFilteringEnabled(Boolean.FALSE); - chat.setInstructions(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); + chat.setInstructions( + WebUtil.convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY))); chat.setLockOnFinished(Boolean.FALSE); chat.setReflectInstructions(null); chat.setReflectOnActivity(Boolean.FALSE); @@ -726,10 +782,8 @@ } catch (WDDXProcessorConversionException e) { ChatService.logger.error("Unable to content for activity " + chat.getTitle() + "properly due to a WDDXProcessorConversionException.", e); - throw new ToolException( - "Invalid import data format for activity " - + chat.getTitle() - + "- WDDX caused an exception. Some data from the design will have been lost. See log for more details."); + throw new ToolException("Invalid import data format for activity " + chat.getTitle() + + "- WDDX caused an exception. Some data from the design will have been lost. See log for more details."); } chatDAO.saveOrUpdate(chat); @@ -738,8 +792,9 @@ /** * 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { Chat chat = getChatByContentId(toolContentId); if (chat == null) { @@ -759,6 +814,7 @@ chatOutputFactory = notebookOutputFactory; } + @Override public String createConditionName(Collection existingConditions) { String uniqueNumber = null; do { @@ -773,12 +829,14 @@ return getChatOutputFactory().buildUserMessagesConditionName(uniqueNumber); } + @Override public void deleteCondition(ChatCondition condition) { if ((condition != null) && (condition.getConditionId() != null)) { chatDAO.delete(condition); } } + @Override public void releaseConditionsFromCache(Chat chat) { if (chat.getConditions() != null) { for (ChatCondition condition : chat.getConditions()) { @@ -787,19 +845,21 @@ } } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getChatOutputFactory().getSupportedDefinitionClasses(definitionType); } // ========================================================================================= - + // ****************** REST methods ************************* - /** Used by the Rest calls to create content. - * Mandatory fields in toolContentJSON: title, instructions - * Optional fields reflectInstructions, lockWhenFinished, filterKeywords + /** + * Used by the Rest calls to create content. Mandatory fields in toolContentJSON: title, instructions Optional + * fields reflectInstructions, lockWhenFinished, filterKeywords */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) + throws JSONException { Chat content = new Chat(); Date updateDate = new Date(); @@ -809,15 +869,15 @@ content.setTitle(toolContentJSON.getString(RestTags.TITLE)); content.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); content.setCreateBy(userID.longValue()); - + content.setContentInUse(false); content.setDefineLater(false); content.setReflectInstructions((String) JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null)); content.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); content.setLockOnFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); - + String filterKeywords = JsonUtil.opt(toolContentJSON, "filterKeywords", null); - content.setFilteringEnabled(filterKeywords != null && filterKeywords.length()>0); + content.setFilteringEnabled((filterKeywords != null) && (filterKeywords.length() > 0)); content.setFilterKeywords(filterKeywords); // submissionDeadline is set in monitoring Index: lams_tool_daco/src/java/org/lamsfoundation/lams/tool/daco/service/DacoServiceImpl.java =================================================================== diff -u -ra789c1395e0f8c1f0ded10147c464574c979b69c -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_daco/src/java/org/lamsfoundation/lams/tool/daco/service/DacoServiceImpl.java (.../DacoServiceImpl.java) (revision a789c1395e0f8c1f0ded10147c464574c979b69c) +++ lams_tool_daco/src/java/org/lamsfoundation/lams/tool/daco/service/DacoServiceImpl.java (.../DacoServiceImpl.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -77,7 +77,6 @@ import org.lamsfoundation.lams.tool.daco.model.DacoUser; import org.lamsfoundation.lams.tool.daco.util.DacoToolContentHandler; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.usermanagement.User; @@ -190,8 +189,8 @@ try { repositoryService.deleteVersion(ticket, fileUuid, fileVersionId); } catch (Exception e) { - throw new DacoApplicationException("Exception occured while deleting files from" + " the repository " - + e.getMessage()); + throw new DacoApplicationException( + "Exception occured while deleting files from" + " the repository " + e.getMessage()); } } @@ -220,13 +219,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @@ -252,7 +252,7 @@ DacoUser user = getUser(userUid); Set answers = user.getAnswers(); List> result = new LinkedList>(); - if (answers != null && answers.size() > 0) { + if ((answers != null) && (answers.size() > 0)) { int recordId = 1; @@ -320,7 +320,7 @@ @Override public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(sessionId, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -339,8 +339,8 @@ String fileName = file.getFileName(); String fileType = file.getContentType(); // For file only upload one sigle file - if (answer.getQuestion().getType() == DacoConstants.QUESTION_TYPE_FILE - || answer.getQuestion().getType() == DacoConstants.QUESTION_TYPE_IMAGE) { + if ((answer.getQuestion().getType() == DacoConstants.QUESTION_TYPE_FILE) + || (answer.getQuestion().getType() == DacoConstants.QUESTION_TYPE_IMAGE)) { NodeKey nodeKey = processFile(file); answer.setFileUuid(nodeKey.getUuid()); answer.setFileVersionId(nodeKey.getVersion()); @@ -408,13 +408,13 @@ return getFile(answer.getFileUuid(), answer.getFileVersionId(), relPathString); } - + @Override public Integer getGroupRecordCount(Long sessionId) { List users = dacoUserDao.getBySessionId(sessionId); - + Integer groupRecordCount = 0; - for (DacoUser user: users) { + for (DacoUser user : users) { groupRecordCount += dacoAnswerDao.getUserRecordCount(user.getUserId(), sessionId); } return groupRecordCount; @@ -449,15 +449,16 @@ List users = dacoUserDao.getBySessionId(session.getSessionId()); List monitoringUsers = new ArrayList(users.size()); for (DacoUser user : users) { - MonitoringSummaryUserDTO monitoringUser = new MonitoringSummaryUserDTO(user.getUid(), user.getUserId() - .intValue(), user.getLastName() + " " + user.getFirstName(), user.getLoginName()); + MonitoringSummaryUserDTO monitoringUser = new MonitoringSummaryUserDTO(user.getUid(), + user.getUserId().intValue(), user.getLastName() + " " + user.getFirstName(), + user.getLoginName()); List> records = getDacoAnswersByUserUid(user.getUid()); /* * If the user provided as "userUid" matches current user UID, the summary is filled with additional * data. NULL matches all users. UID < 0 matches no users, so only the brief description of users is * filled in. */ - if (userUid == null || userUid.equals(user.getUid())) { + if ((userUid == null) || userUid.equals(user.getUid())) { monitoringUser.setRecords(records); NotebookEntry entry = getEntry(session.getSessionId(), CoreNotebookConstants.NOTEBOOK_TOOL, DacoConstants.TOOL_SIGNATURE, user.getUserId().intValue()); @@ -503,8 +504,8 @@ QuestionSummaryDTO summary = new QuestionSummaryDTO(); summary.setQuestionUid(question.getUid()); for (int answerOption = 0; answerOption < answerOptionCount; answerOption++) { - QuestionSummarySingleAnswerDTO singleAnswer = new QuestionSummarySingleAnswerDTO(String - .valueOf(answerOption + 1), null, "0%", "0"); + QuestionSummarySingleAnswerDTO singleAnswer = new QuestionSummarySingleAnswerDTO( + String.valueOf(answerOption + 1), null, "0%", "0"); summary.addUserSummarySingleAnswer(answerOption, singleAnswer); singleAnswer = (QuestionSummarySingleAnswerDTO) singleAnswer.clone(); summary.addGroupSummarySingleAnswer(answerOption, singleAnswer); @@ -521,14 +522,14 @@ } return result; } - + @Override public void notifyTeachersOnLearnerEntry(Long sessionId, DacoUser dacoUser) { String userName = dacoUser.getLastName() + " " + dacoUser.getFirstName(); String message = getLocalisedMessage("event.learnerentry.body", new Object[] { userName }); eventNotificationService.notifyLessonMonitors(sessionId, message, false); } - + @Override public void notifyTeachersOnRecordSumbit(Long sessionId, DacoUser dacoUser) { String userName = dacoUser.getLastName() + " " + dacoUser.getFirstName(); @@ -586,10 +587,10 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return dacoOutputFactory.getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } @Override @@ -610,12 +611,12 @@ public String getToolContentTitle(Long toolContentId) { return getDacoByContentId(toolContentId).getTitle(); } - + @Override public boolean isContentEdited(Long toolContentId) { return getDacoByContentId(toolContentId).isDefineLater(); } - + @Override public DacoUser getUser(Long uid) { return (DacoUser) dacoUserDao.getObject(DacoUser.class, uid); @@ -634,18 +635,19 @@ /* * ===============Methods implemented from ToolContentImport102Manager =============== */ + @Override public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion, String toVersion) throws ToolException { try { // register version filter class exportContentService.registerImportVersionFilterClass(DacoImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, dacoToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof Daco)) { - throw new ImportToolContentException("Import Share daco tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import Share daco tool content failed. Deserialized object is " + toolPOJO); } Daco toolContentObj = (Daco) toolPOJO; @@ -674,6 +676,7 @@ } } + @Override public String leaveToolSession(Long toolSessionId, Long learnerId) throws DataMissingException, ToolException { if (toolSessionId == null) { DacoServiceImpl.log.error("Fail to leave tool Session based on null tool session id."); @@ -696,7 +699,8 @@ } return learnerService.completeToolSession(toolSessionId, learnerId); } - + + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } @@ -716,7 +720,7 @@ */ private NodeKey processFile(FormFile file) throws UploadDacoFileException { NodeKey node = null; - if (file != null && !StringUtils.isEmpty(file.getFileName())) { + if ((file != null) && !StringUtils.isEmpty(file.getFileName())) { String fileName = file.getFileName(); try { node = dacoToolContentHandler.uploadFile(file.getInputStream(), fileName, file.getContentType()); @@ -745,34 +749,45 @@ return node; } + @Override public void releaseAnswersFromCache(Collection answers) { for (DacoAnswer answer : answers) { dacoAnswerDao.releaseFromCache(answer); } } + @Override public void releaseDacoFromCache(Daco daco) { dacoDao.releaseFromCache(daco); for (DacoQuestion question : daco.getDacoQuestions()) { dacoQuestionDao.releaseFromCache(question); } } - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + @Override + public void removeToolContent(Long toolContentId) throws ToolException { Daco daco = dacoDao.getByContentId(toolContentId); - if (removeSessionData) { - List list = dacoSessionDao.getByContentId(toolContentId); - for (DacoSession session : list) { - dacoSessionDao.deleteBySessionId(session.getSessionId()); + if (daco == null) { + DacoServiceImpl.log.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (DacoSession session : dacoSessionDao.getByContentId(toolContentId)) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, DacoConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); } } + dacoDao.removeObject(Daco.class, daco.getUid()); } + @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (log.isDebugEnabled()) { - log.debug("Removing Daco data for user ID " + userId + " and toolContentId " + toolContentId); + if (DacoServiceImpl.log.isDebugEnabled()) { + DacoServiceImpl.log + .debug("Removing Daco data for user ID " + userId + " and toolContentId " + toolContentId); } List sessions = dacoSessionDao.getByContentId(toolContentId); for (DacoSession session : sessions) { @@ -799,15 +814,18 @@ } } } - + + @Override public void removeToolSession(Long toolSessionId) throws DataMissingException, ToolException { dacoSessionDao.deleteBySessionId(toolSessionId); } + @Override public void saveOrUpdateAnswer(DacoAnswer answer) { dacoAnswerDao.saveObject(answer); } + @Override public void saveOrUpdateDaco(Daco daco) { dacoDao.saveObject(daco); } @@ -816,6 +834,7 @@ dacoQuestionDao.saveObject(question); } + @Override public void saveOrUpdateDacoSession(DacoSession resSession) { dacoSessionDao.saveObject(resSession); } @@ -836,11 +855,11 @@ public ICoreNotebookService getCoreNotebookService() { return coreNotebookService; } - + public IUserManagementService getUserManagementService() { return userManagementService; } - + public void setCoreNotebookService(ICoreNotebookService coreNotebookService) { this.coreNotebookService = coreNotebookService; } @@ -905,6 +924,7 @@ this.eventNotificationService = eventNotificationService; } + @Override public int getRecordNum(Long userID, Long sessionId) { return dacoAnswerDao.getUserRecordCount(userID, sessionId); } @@ -917,6 +937,7 @@ this.dacoOutputFactory = dacoOutputFactory; } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getDacoOutputFactory().getSupportedDefinitionClasses(definitionType); } Index: lams_tool_eadventure/src/java/org/eucm/lams/tool/eadventure/service/EadventureServiceImpl.java =================================================================== diff -u -ra789c1395e0f8c1f0ded10147c464574c979b69c -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_eadventure/src/java/org/eucm/lams/tool/eadventure/service/EadventureServiceImpl.java (.../EadventureServiceImpl.java) (revision a789c1395e0f8c1f0ded10147c464574c979b69c) +++ lams_tool_eadventure/src/java/org/eucm/lams/tool/eadventure/service/EadventureServiceImpl.java (.../EadventureServiceImpl.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -41,7 +41,6 @@ import java.util.SortedMap; import java.util.TreeSet; -import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.struts.upload.FormFile; import org.eucm.lams.tool.eadventure.EadventureConstants; @@ -98,7 +97,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.usermanagement.User; @@ -117,24 +115,24 @@ * @author Dapeng.Ni * */ -public class EadventureServiceImpl implements IEadventureService, ToolContentManager, ToolSessionManager, - ToolContentImport102Manager { +public class EadventureServiceImpl + implements IEadventureService, ToolContentManager, ToolSessionManager, ToolContentImport102Manager { static Logger log = Logger.getLogger(EadventureServiceImpl.class.getName()); private EadventureDAO eadventureDao; private EadventureUserDAO eadventureUserDao; private EadventureSessionDAO eadventureSessionDao; - + private EadventureItemVisitDAO eadventureItemVisitDao; - + private EadventureVarsDAO eadventureVarsDao; - + private EadventureParamDAO eadventureParamDao; - + private EadventureConditionDAO eadventureConditionDao; - + private EadventureExpressionDAO eadventureExpressionDao; // tool service @@ -160,14 +158,12 @@ private IEventNotificationService eventNotificationService; private ILessonService lessonService; - + private IGradebookService gradebookService; private EadventureOutputFactory eadventureOutputFactory; - - - + @Override public IVersionedNode getFileNode(Long itemUid, String relPathString) throws EadventureApplicationException { Eadventure ead = (Eadventure) eadventureDao.getObject(Eadventure.class, itemUid); if (ead == null) { @@ -191,7 +187,8 @@ * @return file node * @throws ImscpApplicationException */ - private IVersionedNode getFile(Long uuid, Long versionId, String relativePath) throws EadventureApplicationException { + private IVersionedNode getFile(Long uuid, Long versionId, String relativePath) + throws EadventureApplicationException { ITicket tic = getRepositoryLoginTicket(); @@ -219,8 +216,8 @@ } /** - * This method verifies the credentials of the Eadventure Tool and gives it the Ticket to login - * and access the Content Repository. + * This method verifies the credentials of the Eadventure 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. @@ -232,8 +229,8 @@ ICredentials credentials = new SimpleCredentials(eadventureToolContentHandler.getRepositoryUser(), eadventureToolContentHandler.getRepositoryId()); try { - ITicket ticket = repositoryService.login(credentials, eadventureToolContentHandler - .getRepositoryWorkspaceName()); + ITicket ticket = repositoryService.login(credentials, + eadventureToolContentHandler.getRepositoryWorkspaceName()); return ticket; } catch (AccessDeniedException ae) { throw new EadventureApplicationException("Access Denied to repository." + ae.getMessage()); @@ -244,11 +241,13 @@ } } + @Override public Eadventure getEadventureByContentId(Long contentId) { Eadventure rs = eadventureDao.getByContentId(contentId); return rs; } + @Override public Eadventure getDefaultContent(Long contentId) throws EadventureApplicationException { if (contentId == null) { String error = messageService.getMessage("error.msg.default.content.not.find"); @@ -263,82 +262,93 @@ return content; } - //TODO revisar - /* public List getAuthoredItems(Long eadventureUid) { - return eadventureItemDao.getAuthoringItems(eadventureUid); + // TODO revisar + /* public List getAuthoredItems(Long eadventureUid) { + return eadventureItemDao.getAuthoringItems(eadventureUid); }*/ + @Override public void createUser(EadventureUser eadventureUser) { eadventureUserDao.saveObject(eadventureUser); } + @Override public EadventureUser getUserByIDAndContent(Long userId, Long contentId) { return eadventureUserDao.getUserByUserIDAndContentID(userId, contentId); } + @Override public EadventureUser getUserByIDAndSession(Long userId, Long sessionId) { return eadventureUserDao.getUserByUserIDAndSessionID(userId, sessionId); } + @Override public void deleteFromRepository(Long fileUuid, Long fileVersionId) throws EadventureApplicationException { ITicket ticket = getRepositoryLoginTicket(); try { repositoryService.deleteVersion(ticket, fileUuid, fileVersionId); } catch (Exception e) { - throw new EadventureApplicationException("Exception occured while deleting files from" + " the repository " - + e.getMessage()); + throw new EadventureApplicationException( + "Exception occured while deleting files from" + " the repository " + e.getMessage()); } } + @Override public void saveOrUpdateEadventure(Eadventure eadventure) { eadventureDao.saveObject(eadventure); } - - + + @Override public void saveOrUpdateEadventureExpressions(Set eadExpressions, Long condUID) { - Iterator it = eadExpressions.iterator(); - while (it.hasNext()){ - EadventureExpression expression = it.next(); - // expression.setCondition_uid(condUID); - eadventureExpressionDao.saveObject(expression); - } + Iterator it = eadExpressions.iterator(); + while (it.hasNext()) { + EadventureExpression expression = it.next(); + // expression.setCondition_uid(condUID); + eadventureExpressionDao.saveObject(expression); + } } - + + @Override public void saveOrUpdateEadventureExpression(EadventureExpression eadExpression) { eadventureExpressionDao.saveObject(eadExpression); } - + + @Override public void saveOrUpdateEadventureCondition(EadventureCondition eadCondition) { eadventureConditionDao.saveObject(eadCondition); } - + + @Override public void saveOrUpdateEadventureConditions(Set eadConditions) { Iterator it = eadConditions.iterator(); - while (it.hasNext()){ + while (it.hasNext()) { EadventureCondition cond = it.next(); - // Set expList = cond.getEadListExpression(); - // cond.setEadListExpression(null); + // Set expList = cond.getEadListExpression(); + // cond.setEadListExpression(null); eadventureConditionDao.saveObject(cond); - // saveOrUpdateEadventureExpressions(expList, cond.getUid()); - // cond.setEadListExpression(expList); + // saveOrUpdateEadventureExpressions(expList, cond.getUid()); + // cond.setEadListExpression(expList); } -} - + } + + @Override public void deleteEadventureCondition(Long conditionUid) { eadventureConditionDao.removeObject(EadventureCondition.class, conditionUid); } - + + @Override public void deleteEadventureExpression(Long expressionUid) { eadventureExpressionDao.removeObject(EadventureExpression.class, expressionUid); } - - //TODO revisar!!!!!! Monitoring + + // TODO revisar!!!!!! Monitoring + @Override public List exportBySessionId(Long sessionId, Long userId) { EadventureSession session = eadventureSessionDao.getSessionBySessionId(sessionId); if (session == null) { @@ -350,87 +360,85 @@ Eadventure ead = session.getEadventure(); Summary sum = new Summary(session.getSessionId(), session.getSessionName(), ead, false); - - - //List userList = getUserListBySessionItem(session.getSessionId(), ead.getUid()); + // List userList = getUserListBySessionItem(session.getSessionId(), ead.getUid()); boolean[] existList = new boolean[1]; String[] reportList = new String[1]; - - EadventureUser eadUser = eadventureUserDao.getUserByUserIDAndSessionID(userId,sessionId); - //TODO doble acceso a vistit log... (aqui y en getUserListBySessionItem) + + EadventureUser eadUser = eadventureUserDao.getUserByUserIDAndSessionID(userId, sessionId); + // TODO doble acceso a vistit log... (aqui y en getUserListBySessionItem) EadventureItemVisitLog log = getEadventureItemLog(ead.getUid(), userId); eadUser.setAccessDate(log.getAccessDate()); EadventureVars var = getEadventureVars(log.getUid(), EadventureConstants.VAR_NAME_REPORT); - - if (var!=null){ - existList[0]=true; - reportList[0]=var.getValue(); - }else{ - existList[0]=false; - reportList[0]=null; + if (var != null) { + existList[0] = true; + reportList[0] = var.getValue(); + } else { + existList[0] = false; + reportList[0] = null; } - ArrayList userList = new ArrayList(); userList.add(eadUser); sum.setUsers(userList); sum.setExistList(existList); sum.setReportList(reportList); - - - //TODO ver si tiene sentido que sea una lista + + // TODO ver si tiene sentido que sea una lista ArrayList list = new ArrayList(); list.add(sum); - + return list; } - //TODO revisar!!!!!! Monitoring + + // TODO revisar!!!!!! Monitoring + @Override public List exportByContentId(Long contentId) { Eadventure eadventure = eadventureDao.getByContentId(contentId); List groupList = new ArrayList(); // session by session List sessionList = eadventureSessionDao.getByContentId(contentId); for (EadventureSession session : sessionList) { - + Summary sum = new Summary(session.getSessionId(), session.getSessionName(), session.getEadventure(), false); - + List userList = getUserListBySessionItem(session.getSessionId(), eadventure.getUid()); - boolean[] existList = new boolean[userList.size()]; - String[] reportList = new String[userList.size()]; - int numberOfFinishedLearners = 0; - int i=0; - for (EadventureUser eadUser : userList){ - //TODO doble acceso a vistit log... (aqui y en getUserListBySessionItem) + boolean[] existList = new boolean[userList.size()]; + String[] reportList = new String[userList.size()]; + int numberOfFinishedLearners = 0; + int i = 0; + for (EadventureUser eadUser : userList) { + // TODO doble acceso a vistit log... (aqui y en getUserListBySessionItem) EadventureItemVisitLog log = getEadventureItemLog(eadventure.getUid(), eadUser.getUserId()); - + EadventureVars var = getEadventureVars(log.getUid(), EadventureConstants.VAR_NAME_REPORT); - - if (log.isComplete()) + + if (log.isComplete()) { numberOfFinishedLearners++; + } - if (var!=null){ - existList[i]=true; - reportList[i]=var.getValue(); - }else{ - existList[i]=false; - reportList[i]=null; + if (var != null) { + existList[i] = true; + reportList[i] = var.getValue(); + } else { + existList[i] = false; + reportList[i] = null; } i++; - - } - sum.setUsers(userList); - sum.setExistList(existList); - sum.setReportList(reportList); - - + + } + sum.setUsers(userList); + sum.setExistList(existList); + sum.setReportList(reportList); + groupList.add(sum); } return groupList; } + @Override public Eadventure getEadventureBySessionId(Long sessionId) { EadventureSession session = eadventureSessionDao.getSessionBySessionId(sessionId); // to skip CGLib problem @@ -439,26 +447,28 @@ return res; } + @Override public EadventureSession getEadventureSessionBySessionId(Long sessionId) { return eadventureSessionDao.getSessionBySessionId(sessionId); } + @Override public void saveOrUpdateEadventureSession(EadventureSession resSession) { eadventureSessionDao.saveObject(resSession); } - /* public void retrieveComplete(SortedSet eadventureItemList, EadventureUser user) { - for (EadventureItem item : eadventureItemList) { - EadventureItemVisitLog log = eadventureItemVisitDao.getEadventureItemLog(item.getUid(), user.getUserId()); - if (log == null) { - item.setComplete(false); - } else { - item.setComplete(log.isComplete()); - } - } + /* public void retrieveComplete(SortedSet eadventureItemList, EadventureUser user) { + for (EadventureItem item : eadventureItemList) { + EadventureItemVisitLog log = eadventureItemVisitDao.getEadventureItemLog(item.getUid(), user.getUserId()); + if (log == null) { + item.setComplete(false); + } else { + item.setComplete(log.isComplete()); + } + } }*/ - + @Override public void setItemComplete(Long eadventureItemUid, Long userId, Long sessionId) { EadventureItemVisitLog log = eadventureItemVisitDao.getEadventureItemLog(eadventureItemUid, userId); if (log == null) { @@ -474,29 +484,33 @@ eadventureItemVisitDao.saveObject(log); } + @Override public void setItemAccess(Long eadventureItemUid, Long userId, Long sessionId) { EadventureItemVisitLog log = eadventureItemVisitDao.getEadventureItemLog(eadventureItemUid, userId); EadventureServiceImpl.log.error("Set item acces!!!!!"); - + if (log == null) { log = new EadventureItemVisitLog(); Eadventure item = eadventureDao.getByUid(eadventureItemUid); log.setEadventure(item); EadventureServiceImpl.log.error("El id de usuario es " + userId); - EadventureServiceImpl.log.error("USER ID "+userId); - EadventureServiceImpl.log.error("SESSION ID "+sessionId); + EadventureServiceImpl.log.error("USER ID " + userId); + EadventureServiceImpl.log.error("SESSION ID " + sessionId); EadventureUser user = eadventureUserDao.getUserByUserIDAndSessionID(userId, sessionId); - if (user==null) + if (user == null) { EadventureServiceImpl.log.error("NOS DA NULL!!!!!!!"); + } log.setUser(user); log.setComplete(false); log.setSessionId(sessionId); log.setAccessDate(new Timestamp(new Date().getTime())); eadventureItemVisitDao.saveObject(log); - } else + } else { EadventureServiceImpl.log.error("NO ES NULL!!!"); + } } + @Override public String finishToolSession(Long toolSessionId, Long userId) throws EadventureApplicationException { EadventureUser user = eadventureUserDao.getUserByUserIDAndSessionID(userId, toolSessionId); user.setSessionFinished(true); @@ -516,8 +530,9 @@ } return nextUrl; } - - //TODO revisar!!!! monitoring + + // TODO revisar!!!! monitoring + @Override public List getSummary(Long contentId) { List groupList = new ArrayList(); @@ -529,45 +544,48 @@ List sessionList = eadventureSessionDao.getByContentId(contentId); for (EadventureSession session : sessionList) { // one new group for one session. - // so far no any ead available, so just put session name info to Summary + // so far no any ead available, so just put session name info to Summary Summary sum = new Summary(session.getSessionId(), session.getSessionName(), session.getEadventure()); // set viewNumber according visit log - if (visitCountMap.containsKey(eadventure.getUid())) { - sum.setViewNumber(visitCountMap.get(eadventure.getUid()).intValue()); - } - List userList = getUserListBySessionItem(session.getSessionId(), eadventure.getUid()); - boolean[] existList = new boolean[userList.size()]; - int numberOfFinishedLearners = 0; - int i=0; - for (EadventureUser eadUser : userList){ - //TODO doble acceso a vistit log... (aqui y en getUserListBySessionItem) + if (visitCountMap.containsKey(eadventure.getUid())) { + sum.setViewNumber(visitCountMap.get(eadventure.getUid()).intValue()); + } + List userList = getUserListBySessionItem(session.getSessionId(), eadventure.getUid()); + boolean[] existList = new boolean[userList.size()]; + int numberOfFinishedLearners = 0; + int i = 0; + for (EadventureUser eadUser : userList) { + // TODO doble acceso a vistit log... (aqui y en getUserListBySessionItem) EadventureItemVisitLog log = getEadventureItemLog(eadventure.getUid(), eadUser.getUserId()); - + EadventureVars var = getEadventureVars(log.getUid(), EadventureConstants.VAR_NAME_REPORT); - - if (log.isComplete()) + + if (log.isComplete()) { numberOfFinishedLearners++; + } - if (var!=null) - existList[i]=true; - else - existList[i]=false; - - i++; - + if (var != null) { + existList[i] = true; + } else { + existList[i] = false; } - sum.setUsers(userList); - sum.setExistList(existList); - sum.setNumberOfLearners(userList.size()); - sum.setNumberOfFinishedLearners(numberOfFinishedLearners); - - groupList.add(sum); + + i++; + + } + sum.setUsers(userList); + sum.setExistList(existList); + sum.setNumberOfLearners(userList.size()); + sum.setNumberOfFinishedLearners(numberOfFinishedLearners); + + groupList.add(sum); } - + return groupList; } + @Override public Map> getReflectList(Long contentId, boolean setEntry) { Map> map = new HashMap>(); @@ -598,6 +616,7 @@ return map; } + @Override public List getUserListBySessionItem(Long sessionId, Long itemUid) { List logList = eadventureItemVisitDao.getEadventureItemLogBySession(sessionId, itemUid); List userList = new ArrayList(logList.size()); @@ -606,11 +625,12 @@ user.setAccessDate(visit.getAccessDate()); userList.add(user); } - //List userList = null; + // List userList = null; return userList; } - //TODO revisar Monitoring!!! + // TODO revisar Monitoring!!! + @Override public void setItemVisible(Long itemUid, boolean visible) { /*EadventureItem item = eadventureItemDao.getByUid(itemUid); if (item != null) { @@ -631,15 +651,17 @@ }*/ } + @Override public Long createNotebookEntry(Long sessionId, Integer notebookToolType, String toolSignature, Integer userId, String entryText) { return coreNotebookService.createNotebookEntry(sessionId, notebookToolType, toolSignature, userId, "", entryText); } + @Override public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(sessionId, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -649,10 +671,12 @@ /** * @param notebookEntry */ + @Override public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } + @Override public EadventureUser getUser(Long uid) { return (EadventureUser) eadventureUserDao.getObject(EadventureUser.class, uid); } @@ -694,74 +718,78 @@ } return node; } - - public void saveOrUpdateEadventureParams(Set eadParams){ + + @Override + public void saveOrUpdateEadventureParams(Set eadParams) { Iterator it = eadParams.iterator(); - while (it.hasNext()){ + while (it.hasNext()) { EadventureParam param = it.next(); eadventureParamDao.saveObject(param); } } - - public void removeParam(EadventureParam eadParams){ - eadventureParamDao.delete(eadParams); + + @Override + public void removeParam(EadventureParam eadParams) { + eadventureParamDao.delete(eadParams); } - + @Override public void uploadEadventureFile(Eadventure ead, FormFile file) throws UploadEadventureFileException { try { InputStream is = file.getInputStream(); String fileName = file.getFileName(); String fileType = file.getContentType(); - + // need unzip upload, and parse learning object information from XML file. - - String packageDirectory = ZipFileUtil.expandZip(is, fileName); - log.error("Direcci�n del zip: "+packageDirectory); - IContentPackageConverter cpConverter = new SimpleContentPackageConverter(packageDirectory); - String initFile = cpConverter.getDefaultItem(); - ead.setImsSchema(cpConverter.getSchema()); - ead.setOrganizationXml(cpConverter.getOrganzationXML()); - ead.setInitialItem(initFile); - // upload package - NodeKey nodeKey = processPackage(packageDirectory, initFile); - ead.setFileUuid(nodeKey.getUuid()); - ead.setFileVersionId(nodeKey.getVersion()); - + + String packageDirectory = ZipFileUtil.expandZip(is, fileName); + EadventureServiceImpl.log.error("Direcci�n del zip: " + packageDirectory); + IContentPackageConverter cpConverter = new SimpleContentPackageConverter(packageDirectory); + String initFile = cpConverter.getDefaultItem(); + ead.setImsSchema(cpConverter.getSchema()); + ead.setOrganizationXml(cpConverter.getOrganzationXML()); + ead.setInitialItem(initFile); + // upload package + NodeKey nodeKey = processPackage(packageDirectory, initFile); + ead.setFileUuid(nodeKey.getUuid()); + ead.setFileVersionId(nodeKey.getVersion()); + // create the package from the directory contents - ead.setFileType(fileType); - ead.setFileName(fileName); - + ead.setFileType(fileType); + ead.setFileName(fileName); + // parse parameters.xml file, and create the eadParams - //TODO reportar bien el error cuando no se produce xk no es un e-Ad file - HashMap params = InputOutputReader.getOutputParameterList(packageDirectory+"//"+EadventureConstants.PARAMETERS_FILE_NAME); - // chek if its a real e-adventure package - - if (! new File(packageDirectory+"//"+EadventureConstants.PARAMETERS_FILE_NAME).exists()){ - EadventureServiceImpl.log.error(messageService.getMessage("error.msg.ims.package") + " : " - + "No eAdventure game!! "); - throw new UploadEadventureFileException(messageService.getMessage("error.msg.ims.package")); - } - Iterator it = params.keySet().iterator(); - Set eadParam = new HashSet(); - while (it.hasNext()){ - EadventureParam param = new EadventureParam(); - String key = it.next(); - param.setInput(false); - param.setName(key); - param.setType(params.get(key)); - // eadventureParamDao.saveObject(param); - eadParam.add(param); - log.error(key+" ha sido subido con exito!!!!!!"); - - } - //add default params (this are not included in the params file at eAd LAMS export due to they always have to appear) - eadParam.addAll(getDefaultParams()); - ead.setParams(eadParam); - + // TODO reportar bien el error cuando no se produce xk no es un e-Ad file + HashMap params = InputOutputReader + .getOutputParameterList(packageDirectory + "//" + EadventureConstants.PARAMETERS_FILE_NAME); + // chek if its a real e-adventure package + + if (!new File(packageDirectory + "//" + EadventureConstants.PARAMETERS_FILE_NAME).exists()) { + EadventureServiceImpl.log + .error(messageService.getMessage("error.msg.ims.package") + " : " + "No eAdventure game!! "); + throw new UploadEadventureFileException(messageService.getMessage("error.msg.ims.package")); + } + Iterator it = params.keySet().iterator(); + Set eadParam = new HashSet(); + while (it.hasNext()) { + EadventureParam param = new EadventureParam(); + String key = it.next(); + param.setInput(false); + param.setName(key); + param.setType(params.get(key)); + // eadventureParamDao.saveObject(param); + eadParam.add(param); + EadventureServiceImpl.log.error(key + " ha sido subido con exito!!!!!!"); + + } + // add default params (this are not included in the params file at eAd LAMS export due to they always have + // to appear) + eadParam.addAll(getDefaultParams()); + ead.setParams(eadParam); + } catch (ZipFileUtilException e) { - EadventureServiceImpl.log.error(messageService.getMessage("error.msg.zip.file.exception") + " : " - + e.toString()); + EadventureServiceImpl.log + .error(messageService.getMessage("error.msg.zip.file.exception") + " : " + e.toString()); throw new UploadEadventureFileException(messageService.getMessage("error.msg.zip.file.exception")); } catch (FileNotFoundException e) { EadventureServiceImpl.log.error(messageService.getMessage("error.msg.file.not.found") + ":" + e.toString()); @@ -773,16 +801,17 @@ EadventureServiceImpl.log.error(messageService.getMessage("error.msg.ims.package") + ":" + e.toString()); throw new UploadEadventureFileException(messageService.getMessage("error.msg.ims.package")); } catch (ImscpApplicationException e) { - EadventureServiceImpl.log.error(messageService.getMessage("error.msg.ims.application") + ":" + e.toString()); + EadventureServiceImpl.log + .error(messageService.getMessage("error.msg.ims.application") + ":" + e.toString()); throw new UploadEadventureFileException(messageService.getMessage("error.msg.ims.application")); } } - - private List getDefaultParams(){ + + private List getDefaultParams() { List defaultParams = new ArrayList(); - defaultParams.add(new EadventureParam("score","integer",false)); - defaultParams.add(new EadventureParam("game-completed","boolean",false)); - defaultParams.add(new EadventureParam("total-time","integer",false)); + defaultParams.add(new EadventureParam("score", "integer", false)); + defaultParams.add(new EadventureParam("game-completed", "boolean", false)); + defaultParams.add(new EadventureParam("total-time", "integer", false)); return defaultParams; } @@ -792,17 +821,18 @@ * @param packageDirectory * @return */ - - //TODO creo que vga a sobrar + + // TODO creo que vga a sobrar private String findWebsiteInitialItem(String packageDirectory) { File file = new File(packageDirectory); if (!file.isDirectory()) { return null; } File[] initFiles = file.listFiles(new FileFilter() { + @Override public boolean accept(File pathname) { - if (pathname == null || pathname.getName() == null) { + if ((pathname == null) || (pathname.getName() == null)) { return false; } String name = pathname.getName(); @@ -813,7 +843,7 @@ return false; } }); - if (initFiles != null && initFiles.length > 0) { + if ((initFiles != null) && (initFiles.length > 0)) { return initFiles[0].getName(); } else { return null; @@ -842,8 +872,9 @@ public void setEadventureDao(EadventureDAO eadventureDao) { this.eadventureDao = eadventureDao; } - - public List getEadventureParamByContentId(Long contentId){ + + @Override + public List getEadventureParamByContentId(Long contentId) { return eadventureParamDao.getEadventureParamByEadContentId(contentId); } @@ -860,26 +891,26 @@ } public void setEadventureItemVisitDao(EadventureItemVisitDAO eadventureItemVisitDao) { - this.eadventureItemVisitDao = eadventureItemVisitDao; + this.eadventureItemVisitDao = eadventureItemVisitDao; } public EadventureItemVisitDAO getEadventureItemVisitDao() { - return eadventureItemVisitDao; + return eadventureItemVisitDao; } public void setEadventureVarsDao(EadventureVarsDAO eadventureVarsDao) { - this.eadventureVarsDao = eadventureVarsDao; + this.eadventureVarsDao = eadventureVarsDao; } public void setToolService(ILamsToolService toolService) { this.toolService = toolService; } - // ******************************************************************************* // ToolContentManager, ToolSessionManager methods // ******************************************************************************* + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { Eadventure toolContentObj = eadventureDao.getByContentId(toolContentId); if (toolContentObj == null) { @@ -896,22 +927,24 @@ // set EadventureToolContentHandler as null to avoid copy file node in repository again. toolContentObj = Eadventure.newInstance(toolContentObj, toolContentId); try { - //TODO revisar!! + // TODO revisar!! exportContentService.registerFileClassForExport(Eadventure.class.getName(), "fileUuid", "fileVersionId"); - exportContentService.exportToolContent(toolContentId, toolContentObj, eadventureToolContentHandler, rootPath); + exportContentService.exportToolContent(toolContentId, toolContentObj, eadventureToolContentHandler, + rootPath); } catch (ExportToolContentException e) { throw new ToolException(e); } } + @Override public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion, String toVersion) throws ToolException { try { // register version filter class exportContentService.registerImportVersionFilterClass(EadventureImportContentVersionFilter.class); - - //TODO revisar + + // TODO revisar exportContentService.registerFileClassForImport(Eadventure.class.getName(), "fileUuid", "fileVersionId", "fileName", "fileType", null, "initialItem"); @@ -937,31 +970,28 @@ user.setEadventure(toolContentObj); } toolContentObj.setCreatedBy(user); - //TODO revisar!! que no falte nada al objeto de EAD + // TODO revisar!! que no falte nada al objeto de EAD // reset all eadventureItem createBy user /*Set items = toolContentObj.getEadventureItems(); for (EadventureItem item : items) { - item.setCreateBy(user); + item.setCreateBy(user); }*/ - //TODO ver si esto es correcto: + // TODO ver si esto es correcto: Set par = toolContentObj.getParams(); List listPar = new ArrayList(par); - for (Object o:listPar){ - ((EadventureParam)o).setEadventure_uid(null); - this.eadventureParamDao.saveObject(o); + for (Object o : listPar) { + ((EadventureParam) o).setEadventure_uid(null); + this.eadventureParamDao.saveObject(o); } Set con = toolContentObj.getConditions(); List listCon = new ArrayList(con); - for (Object o:listCon){ - ((EadventureCondition)o).setEadventure_uid(null); - this.eadventureConditionDao.saveObject(o); + for (Object o : listCon) { + ((EadventureCondition) o).setEadventure_uid(null); + this.eadventureConditionDao.saveObject(o); } - - + eadventureDao.saveObject(toolContentObj); - - - + } catch (ImportToolContentException e) { throw new ToolException(e); } @@ -976,8 +1006,9 @@ * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition * @throws EadventureApplicationException */ - + // @Override + @Override public SortedMap getToolOutputDefinitions(Long toolContentId, int definitionType) throws ToolException { Eadventure content = getEadventureByContentId(toolContentId); @@ -996,6 +1027,7 @@ return prueba; } + @Override public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { if (toContentId == null) { throw new ToolException("Failed to create the EadventureFiles tool seession"); @@ -1016,7 +1048,7 @@ Eadventure toContent = Eadventure.newInstance(eadventure, toContentId); eadventureDao.saveObject(toContent); - //TODO no hace nada... pero comprobar que no de problema + // TODO no hace nada... pero comprobar que no de problema // save eadventure items as well /*Set items = toContent.getEadventureItems(); if (items != null) { @@ -1028,10 +1060,11 @@ }*/ } + @Override public String getToolContentTitle(Long toolContentId) { return getEadventureByContentId(toolContentId).getTitle(); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Eadventure eadventure = eadventureDao.getByContentId(toolContentId); @@ -1041,32 +1074,41 @@ eadventure.setDefineLater(false); } + @Override public boolean isContentEdited(Long toolContentId) { return getEadventureByContentId(toolContentId).isDefineLater(); } - - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + + @Override + public void removeToolContent(Long toolContentId) throws ToolException { Eadventure eadventure = eadventureDao.getByContentId(toolContentId); - if (removeSessionData) { - List list = eadventureSessionDao.getByContentId(toolContentId); - Iterator iter = list.iterator(); - while (iter.hasNext()) { - EadventureSession session = (EadventureSession) iter.next(); - eadventureSessionDao.delete(session); + if (eadventure == null) { + EadventureServiceImpl.log + .warn("Can not remove the tool content as it does not exist. ID: " + toolContentId); + } + + for (EadventureSession session : eadventureSessionDao.getByContentId(toolContentId)) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, EadventureConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); } } + eadventureDao.delete(eadventure); } + @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (log.isDebugEnabled()) { - log.debug("Removing Eadventure content for user ID " + userId + " and toolContentId " + toolContentId); + if (EadventureServiceImpl.log.isDebugEnabled()) { + EadventureServiceImpl.log + .debug("Removing Eadventure content for user ID " + userId + " and toolContentId " + toolContentId); } Eadventure eadventure = eadventureDao.getByContentId(toolContentId); if (eadventure == null) { - log.warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); + EadventureServiceImpl.log + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } EadventureItemVisitLog visitLog = eadventureItemVisitDao.getEadventureItemLog(eadventure.getUid(), @@ -1093,6 +1135,7 @@ } } + @Override public void removeParams(Long toolContentId) { List params = getEadventureParamByContentId(toolContentId); if (params != null) { @@ -1137,13 +1180,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -1161,17 +1205,18 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return getEadventureOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /* ===============Methods implemented from ToolContentImport102Manager =============== */ /** * Import the data for a 1.0.2 Noticeboard or HTMLNoticeboard */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { Date now = new Date(); Eadventure toolContentObj = new Eadventure(); @@ -1182,8 +1227,8 @@ toolContentObj.setContentInUse(Boolean.FALSE); toolContentObj.setCreated(now); toolContentObj.setDefineLater(Boolean.FALSE); - toolContentObj.setInstructions(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); + toolContentObj.setInstructions( + WebUtil.convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY))); toolContentObj.setUpdated(now); toolContentObj.setReflectOnActivity(Boolean.FALSE); toolContentObj.setReflectInstructions(null); @@ -1213,71 +1258,69 @@ // Eadventure 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. - //TODO nos cargamos la parte de los items.... comprobar que se pase todo bien y no de ning�n problema + // TODO nos cargamos la parte de los items.... comprobar que se pase todo bien y no de ning�n problema /* 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); - EadventureItem item = new EadventureItem(); - 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 eadventureType = (String) urlMap.get(ToolContentImport102Manager.CONTENT_URL_URL_TYPE); - if (ToolContentImport102Manager.URL_RESOURCE_TYPE_URL.equals(eadventureType)) { - item.setType(EadventureConstants.RESOURCE_TYPE_URL); - item.setUrl((String) urlMap.get(ToolContentImport102Manager.CONTENT_URL_URL_URL)); - item.setOpenUrlNewWindow(false); - } else if (ToolContentImport102Manager.URL_RESOURCE_TYPE_WEBSITE.equals(eadventureType)) { - item.setType(EadventureConstants.RESOURCE_TYPE_WEBSITE); - } else if (ToolContentImport102Manager.URL_RESOURCE_TYPE_FILE.equals(eadventureType)) { - item.setType(EadventureConstants.RESOURCE_TYPE_FILE); - } else { - throw new ToolException("Invalid eadventure type. Type was " + eadventureType); - } - - items.put(itemOrder, item); - } + Iterator iter = urls.iterator(); + while (iter.hasNext()) { + Hashtable urlMap = (Hashtable) iter.next(); + Integer itemOrder = WDDXProcessor.convertToInteger(urlMap, + ToolContentImport102Manager.CONTENT_URL_URL_VIEW_ORDER); + EadventureItem item = new EadventureItem(); + 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 eadventureType = (String) urlMap.get(ToolContentImport102Manager.CONTENT_URL_URL_TYPE); + if (ToolContentImport102Manager.URL_RESOURCE_TYPE_URL.equals(eadventureType)) { + item.setType(EadventureConstants.RESOURCE_TYPE_URL); + item.setUrl((String) urlMap.get(ToolContentImport102Manager.CONTENT_URL_URL_URL)); + item.setOpenUrlNewWindow(false); + } else if (ToolContentImport102Manager.URL_RESOURCE_TYPE_WEBSITE.equals(eadventureType)) { + item.setType(EadventureConstants.RESOURCE_TYPE_WEBSITE); + } else if (ToolContentImport102Manager.URL_RESOURCE_TYPE_FILE.equals(eadventureType)) { + item.setType(EadventureConstants.RESOURCE_TYPE_FILE); + } else { + throw new ToolException("Invalid eadventure type. Type was " + eadventureType); + } + + items.put(itemOrder, item); } - + } + Iterator iter = items.values().iterator(); Date itemDate = null; while (iter.hasNext()) { - if (itemDate != null) { - try { - Thread.sleep(1000); - } catch (Exception e) { - } - } - itemDate = new Date(); - - EadventureItem item = (EadventureItem) iter.next(); - item.setCreateDate(itemDate); - toolContentObj.getEadventureItems().add(item); + if (itemDate != null) { + try { + Thread.sleep(1000); + } catch (Exception e) { + } + } + itemDate = new Date(); + + EadventureItem item = (EadventureItem) iter.next(); + item.setCreateDate(itemDate); + toolContentObj.getEadventureItems().add(item); }*/ } catch (WDDXProcessorConversionException e) { EadventureServiceImpl.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."); + 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."); } eadventureDao.saveObject(toolContentObj); @@ -1286,32 +1329,33 @@ // TODO comprobar que no hay problema por quitar esto /*private EadventureItemInstruction createInstruction(Hashtable instructionEntry) - throws WDDXProcessorConversionException { - - 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 (EadventureServiceImpl.log.isDebugEnabled()) { - EadventureServiceImpl.log - .debug("1.0.2 Import truncating Item Instruction to 255 characters. Original text was\'" - + instructionText + "\'"); - } - instructionText = instructionText.substring(0, 255); - } - - EadventureItemInstruction instruction = new EadventureItemInstruction(); - instruction.setDescription(instructionText); - instruction.setSequenceId(instructionOrder); - - return instruction; + throws WDDXProcessorConversionException { + + 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 (EadventureServiceImpl.log.isDebugEnabled()) { + EadventureServiceImpl.log + .debug("1.0.2 Import truncating Item Instruction to 255 characters. Original text was\'" + + instructionText + "\'"); + } + instructionText = instructionText.substring(0, 255); + } + + EadventureItemInstruction instruction = new EadventureItemInstruction(); + instruction.setDescription(instructionText); + instruction.setSequenceId(instructionOrder); + + return instruction; }*/ /** 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { Eadventure toolContentObj = getEadventureByContentId(toolContentId); if (toolContentObj == null) { @@ -1349,6 +1393,7 @@ this.coreNotebookService = coreNotebookService; } + @Override public IEventNotificationService getEventNotificationService() { return eventNotificationService; } @@ -1357,6 +1402,7 @@ this.eventNotificationService = eventNotificationService; } + @Override public String getLocalisedMessage(String key, Object[] args) { return messageService.getMessage(key, args); } @@ -1373,17 +1419,18 @@ * Finds out which lesson the given tool content belongs to and returns its monitoring users. * * @param sessionId - * tool session ID + * tool session ID * @return list of teachers that monitor the lesson which contains the tool with given session ID */ + @Override public List getMonitorsByToolSessionId(Long sessionId) { return getLessonService().getMonitorsByToolSessionId(sessionId); } - //TODO Resultado de la actualizaci�n a la brach de release 2.3.5, ver si afecta!!! - + // TODO Resultado de la actualizaci�n a la brach de release 2.3.5, ver si afecta!!! + /*public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { - return getEadventureOutputFactory().getSupportedDefinitionClasses(definitionType); + return getEadventureOutputFactory().getSupportedDefinitionClasses(definitionType); }*/ public EadventureOutputFactory getEadventureOutputFactory() { @@ -1393,211 +1440,223 @@ public void setEadventureOutputFactory(EadventureOutputFactory eadventureOutputFactory) { this.eadventureOutputFactory = eadventureOutputFactory; } - + public void setGradebookService(IGradebookService gradebookService) { - this.gradebookService = gradebookService; - } - + this.gradebookService = gradebookService; + } + public IGradebookService getGradebookService() { - return gradebookService; - } - - - /** - * {@inheritDoc} - */ - public boolean checkCondition(String conditionName, Long toolSessionId, Long userUid) { - EadventureUser user = eadventureUserDao.getUserByUserIDAndSessionID(userUid, toolSessionId); - Eadventure eadventure = eadventureSessionDao.getSessionBySessionId(toolSessionId).getEadventure(); - Set conditions = eadventure.getConditions(); - EadventureCondition condition = null; - for (EadventureCondition cond:conditions) { - if (cond.getName().equals(conditionName)) { - condition = cond; - break; - } - } + return gradebookService; + } - boolean result = true; - if (condition != null) { - EadventureItemVisitLog visitLog = eadventureItemVisitDao.getEadventureItemLog(eadventure.getUid(), userUid); - Set eadV = visitLog.getEadventureVars(); - if (!eadV.isEmpty()){ - List eadventureVars = new ArrayList( eadV); - //TODO comprobar si no lo tengo que meter con comparator para que salga en orden - Iterator it = condition.getEadListExpression().iterator(); - String previousOp = null; - while(it.hasNext()) { - Boolean andExpression= null; - boolean iniNewAnd=false; - EadventureExpression expr = it.next(); - String nextOp = expr.getNextOp(); - if (visitLog != null) { - boolean partialResult = checkExpression(expr, eadventureVars); - // first expr - if (expr.getSequenceId()==0||iniNewAnd) - result = partialResult; - else if (previousOp==null||previousOp.equals("and")) - result &= partialResult; - else if (previousOp!=null&&previousOp.equals("or")||!it.hasNext()){ - if (andExpression==null){ - andExpression = new Boolean(result); - iniNewAnd = true; - }else { - result = partialResult||andExpression; - iniNewAnd=false; - andExpression=null; - } - } - - previousOp = nextOp; - - } else { - - result = false; - break; - } + /** + * {@inheritDoc} + */ + @Override + public boolean checkCondition(String conditionName, Long toolSessionId, Long userUid) { + EadventureUser user = eadventureUserDao.getUserByUserIDAndSessionID(userUid, toolSessionId); + Eadventure eadventure = eadventureSessionDao.getSessionBySessionId(toolSessionId).getEadventure(); + Set conditions = eadventure.getConditions(); + EadventureCondition condition = null; + for (EadventureCondition cond : conditions) { + if (cond.getName().equals(conditionName)) { + condition = cond; + break; + } + } + + boolean result = true; + if (condition != null) { + EadventureItemVisitLog visitLog = eadventureItemVisitDao.getEadventureItemLog(eadventure.getUid(), userUid); + Set eadV = visitLog.getEadventureVars(); + if (!eadV.isEmpty()) { + List eadventureVars = new ArrayList(eadV); + // TODO comprobar si no lo tengo que meter con comparator para que salga en orden + Iterator it = condition.getEadListExpression().iterator(); + String previousOp = null; + while (it.hasNext()) { + Boolean andExpression = null; + boolean iniNewAnd = false; + EadventureExpression expr = it.next(); + String nextOp = expr.getNextOp(); + if (visitLog != null) { + boolean partialResult = checkExpression(expr, eadventureVars); + // first expr + if ((expr.getSequenceId() == 0) || iniNewAnd) { + result = partialResult; + } else if ((previousOp == null) || previousOp.equals("and")) { + result &= partialResult; + } else if (((previousOp != null) && previousOp.equals("or")) || !it.hasNext()) { + if (andExpression == null) { + andExpression = new Boolean(result); + iniNewAnd = true; + } else { + result = partialResult || andExpression; + iniNewAnd = false; + andExpression = null; + } } - }else { - //There aren't vars set for this user and session - result=false; - } - } else { - //there is no such a condition + + previousOp = nextOp; + + } else { + result = false; + break; + } } - - return result; + } else { + // There aren't vars set for this user and session + result = false; + } + } else { + // there is no such a condition + result = false; } - - private boolean checkExpression(EadventureExpression expr, List eadventureVars){ - EadventureVars firstVar = getVarByName(expr.getFirstOp().getName(),eadventureVars); -// firstVar.setType(expr.getFirstOp().getType()); - EadventureVars secVar = null; - String operator = expr.getExpresionOp(); - String value = expr.getValueIntroduced(); - if (expr.getVarIntroduced()!=null){ - secVar = getVarByName(expr.getVarIntroduced().getName(),eadventureVars); - secVar.setType(expr.getVarIntroduced().getType()); + + return result; + } + + private boolean checkExpression(EadventureExpression expr, List eadventureVars) { + EadventureVars firstVar = getVarByName(expr.getFirstOp().getName(), eadventureVars); + // firstVar.setType(expr.getFirstOp().getType()); + EadventureVars secVar = null; + String operator = expr.getExpresionOp(); + String value = expr.getValueIntroduced(); + if (expr.getVarIntroduced() != null) { + secVar = getVarByName(expr.getVarIntroduced().getName(), eadventureVars); + secVar.setType(expr.getVarIntroduced().getType()); + } + // when tries to check a var that has not been send by the game + if (firstVar != null) { + if (secVar == null) { + return evalExpr(new String(firstVar.getType()), new String(firstVar.getValue()), value, operator); + } else { + return evalExpr(firstVar.getType(), firstVar.getValue(), secVar.getValue(), operator); } - // when tries to check a var that has not been send by the game - if (firstVar!=null){ - if (secVar==null) - return evalExpr(new String(firstVar.getType()), new String(firstVar.getValue()), value, operator); - else - return evalExpr(firstVar.getType(), firstVar.getValue(), secVar.getValue(), operator); - } else - return false; + } else { + return false; } - - private boolean evalExpr(String type, String firstValue, String secondValue, String op){ - if (type.equals("string")){ - if (op.equals("==")) - return firstValue.equals(secondValue); - else - return !firstValue.equals(secondValue); - } else if (type.equals("boolean")){ + } + + private boolean evalExpr(String type, String firstValue, String secondValue, String op) { + if (type.equals("string")) { + if (op.equals("==")) { return firstValue.equals(secondValue); - }else if (type.equals("integer")){ - if (op.equals("==")) - return Integer.parseInt(firstValue) == Integer.parseInt(secondValue); - else if (op.equals("!=")) - return Integer.parseInt(firstValue) != Integer.parseInt(secondValue); - else if (op.equals(">")) - return Integer.parseInt(firstValue) > Integer.parseInt(secondValue); - else if (op.equals("<")) - return Integer.parseInt(firstValue) < Integer.parseInt(secondValue); - else if (op.equals(">=")) - return Integer.parseInt(firstValue) >= Integer.parseInt(secondValue); - else if (op.equals("<=")) - return Integer.parseInt(firstValue) <= Integer.parseInt(secondValue); - - + } else { + return !firstValue.equals(secondValue); } - - return false; + } else if (type.equals("boolean")) { + return firstValue.equals(secondValue); + } else if (type.equals("integer")) { + if (op.equals("==")) { + return Integer.parseInt(firstValue) == Integer.parseInt(secondValue); + } else if (op.equals("!=")) { + return Integer.parseInt(firstValue) != Integer.parseInt(secondValue); + } else if (op.equals(">")) { + return Integer.parseInt(firstValue) > Integer.parseInt(secondValue); + } else if (op.equals("<")) { + return Integer.parseInt(firstValue) < Integer.parseInt(secondValue); + } else if (op.equals(">=")) { + return Integer.parseInt(firstValue) >= Integer.parseInt(secondValue); + } else if (op.equals("<=")) { + return Integer.parseInt(firstValue) <= Integer.parseInt(secondValue); + } + } - - private EadventureVars getVarByName(String name, List eadventureVars){ - for (EadventureVars var: eadventureVars) { - if (var.getName().equals(name)) { - return var; - - } + + return false; + } + + private EadventureVars getVarByName(String name, List eadventureVars) { + for (EadventureVars var : eadventureVars) { + if (var.getName().equals(name)) { + return var; + + } } - return null; - - } - + return null; - - //TODO IMPORRRRRRRRRRRRRRRTANTE!!!!!!!!!!!!!!! el par�metro toolContentID que estamos pasando es realmente toolSessionID!!!! - //@Override + } + + // TODO IMPORRRRRRRRRRRRRRRTANTE!!!!!!!!!!!!!!! el par�metro toolContentID que estamos pasando es realmente + // toolSessionID!!!! + // @Override + @Override public boolean setAppletInput(String name, String value, String userId, String toolContentID) { - //TODO restart when + // TODO restart when EadventureServiceImpl.log.error("EEEEEEEEEEEEEEEEEE " + name); EadventureServiceImpl.log.error("EEEEEEEEEEEEEEEEEE " + value); - //EadventureServiceImpl.log.error("USER ID "+ userId); - EadventureServiceImpl.log.error("TOOL SESION ID "+ toolContentID); + // EadventureServiceImpl.log.error("USER ID "+ userId); + EadventureServiceImpl.log.error("TOOL SESION ID " + toolContentID); EadventureServiceImpl.log.error("OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOEEEEEEEEEEEEEEEE"); - - - //TODO Ahora recuperamos la session para sacar el EAD!!! pero a�adir el toolContentId para que sea mas sencillo!!! - //TODO user va a sobrar!! con el userID que ya se nos pasa por par�metro vamos sobraos!! - //EadventureUser user = eadventureUserDao.getUserByUserIDAndContentID(Long.parseLong(userId), Long.parseLong(toolContentID)); - //EadventureUser user = eadventureUserDao.getUserByUserIDAndSessionID(Long.parseLong(userId), Long.parseLong(toolContentID)); - //eadventureUserDao.getUserByUserIDAndSessionID(Long.parseLong(userId), Long.parseLong(toolSessionID)); - EadventureServiceImpl.log.error("USER ID "+ userId); - EadventureSession eadSession = eadventureSessionDao.getSessionBySessionId( Long.parseLong(toolContentID)); - //Eadventure ead = eadventureDao.getByContentId(Long.parseLong(toolContentID)); - EadventureItemVisitLog log = eadventureItemVisitDao.getEadventureItemLog(eadSession.getEadventure().getUid(), Long.parseLong(userId)); + + // TODO Ahora recuperamos la session para sacar el EAD!!! pero a�adir el toolContentId para que sea mas + // sencillo!!! + // TODO user va a sobrar!! con el userID que ya se nos pasa por par�metro vamos sobraos!! + // EadventureUser user = eadventureUserDao.getUserByUserIDAndContentID(Long.parseLong(userId), + // Long.parseLong(toolContentID)); + // EadventureUser user = eadventureUserDao.getUserByUserIDAndSessionID(Long.parseLong(userId), + // Long.parseLong(toolContentID)); + // eadventureUserDao.getUserByUserIDAndSessionID(Long.parseLong(userId), Long.parseLong(toolSessionID)); + EadventureServiceImpl.log.error("USER ID " + userId); + EadventureSession eadSession = eadventureSessionDao.getSessionBySessionId(Long.parseLong(toolContentID)); + // Eadventure ead = eadventureDao.getByContentId(Long.parseLong(toolContentID)); + EadventureItemVisitLog log = eadventureItemVisitDao.getEadventureItemLog(eadSession.getEadventure().getUid(), + Long.parseLong(userId)); EadventureVars var = eadventureVarsDao.getEadventureVars(log.getUid(), name); - if (var==null){ + if (var == null) { var = new EadventureVars(); var.setName(name); var.setVisitLog(log); - //Get the type from the params list - var.setType(eadventureParamDao.getEadventureParamTypeByNameAndEadContentID(name, eadSession.getEadventure().getUid())); + // Get the type from the params list + var.setType(eadventureParamDao.getEadventureParamTypeByNameAndEadContentID(name, + eadSession.getEadventure().getUid())); } var.setValue(value); this.eadventureVarsDao.saveObject(var); - boolean changeButton = eadSession.getEadventure().isDefineComplete()&!log.isComplete(); - if (name.equals(EadventureConstants.VAR_NAME_COMPLETED)&&value.equals("true")&&changeButton) + boolean changeButton = eadSession.getEadventure().isDefineComplete() & !log.isComplete(); + if (name.equals(EadventureConstants.VAR_NAME_COMPLETED) && value.equals("true") && changeButton) { setItemComplete(eadSession.getEadventure().getUid(), Long.parseLong(userId), eadSession.getSessionId()); - - return changeButton; + } + + return changeButton; } - //@Override + // @Override + @Override public void setReportInput(String name, String value, String userId, String toolSessionID) { // TODO Auto-generated method stub - + } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return null; } - - //@Override + + // @Override + @Override public EadventureItemVisitLog getEadventureItemLog(Long itemUid, Long userId) { - + return eadventureItemVisitDao.getEadventureItemLog(itemUid, userId); } - // @Override + // @Override + @Override public EadventureVars getEadventureVars(Long itemVisitLogID, String name) { return eadventureVarsDao.getEadventureVars(itemVisitLogID, name); } public void setEadventureParamDao(EadventureParamDAO eadventureParamDao) { - this.eadventureParamDao = eadventureParamDao; + this.eadventureParamDao = eadventureParamDao; } public void setEadventureConditionDao(EadventureConditionDAO eadventureConditionDao) { - this.eadventureConditionDao = eadventureConditionDao; + this.eadventureConditionDao = eadventureConditionDao; } public void setEadventureExpressionDao(EadventureExpressionDAO eadventureExpressionDao) { - this.eadventureExpressionDao = eadventureExpressionDao; + this.eadventureExpressionDao = eadventureExpressionDao; } } \ No newline at end of file Index: lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/service/ForumService.java =================================================================== diff -u -rfb1a57de810877a03bfeecc4005929f5516c52b6 -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/service/ForumService.java (.../ForumService.java) (revision fb1a57de810877a03bfeecc4005929f5516c52b6) +++ lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/service/ForumService.java (.../ForumService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -80,7 +80,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.forum.dto.AverageRatingDTO; import org.lamsfoundation.lams.tool.forum.dto.MessageDTO; @@ -126,7 +125,8 @@ * * @version $Revision$ */ -public class ForumService implements IForumService, ToolContentManager, ToolSessionManager, ToolContentImport102Manager, ToolRestManager { +public class ForumService + implements IForumService, ToolContentManager, ToolSessionManager, ToolContentImport102Manager, ToolRestManager { private static final Logger log = Logger.getLogger(ForumService.class); // DAO variables @@ -139,7 +139,7 @@ private TimestampDao timestampDao; private MessageSeqDao messageSeqDao; - + private MessageRatingDAO messageRatingDao; private ForumUserDao forumUserDao; @@ -184,6 +184,7 @@ this.auditService = auditService; } + @Override public IAuditService getAuditService() { return auditService; } @@ -200,15 +201,18 @@ this.forumOutputFactory = forumOutputFactory; } + @Override public Forum updateForum(Forum forum) throws PersistenceException { forumDao.saveOrUpdate(forum); return forum; } + @Override public Forum getForum(Long forumUid) throws PersistenceException { return forumDao.getById(forumUid); } + @Override public Forum getForumByContentId(Long contentID) throws PersistenceException { return forumDao.getByContentId(contentID); } @@ -218,11 +222,13 @@ attachmentDao.delete(attachment); } + @Override public Message createRootTopic(Long forumId, Long sessionId, Message message) throws PersistenceException { return createRootTopic(forumId, getSessionBySessionId(sessionId), message); } - public Message createRootTopic(Long forumId, ForumToolSession session, Message message) throws PersistenceException { + public Message createRootTopic(Long forumId, ForumToolSession session, Message message) + throws PersistenceException { // get Forum and ForumToolSesion if (message.getForum() == null) { Forum forum = forumDao.getById(forumId); @@ -262,6 +268,7 @@ return message; } + @Override public Message updateTopic(Message message) throws PersistenceException { // update message @@ -277,7 +284,7 @@ return message; } - + @Override public List getMessageAsDTO(Long messageUid) throws PersistenceException { MessageSeq msgSeq = messageSeqDao.getByMessageId(messageUid); @@ -286,10 +293,12 @@ return msgDtoList; } + @Override public void updateContainedReport(Message message) { messageDao.saveOrUpdate(message); } + @Override public Message updateMessageHideFlag(Long messageId, boolean hideFlag) { Message message = getMessage(messageId); @@ -314,10 +323,12 @@ return message; } + @Override public Message getMessage(Long messageUid) throws PersistenceException { return messageDao.getById(messageUid); } + @Override public void deleteTopic(Long topicUid) throws PersistenceException { Message topic = messageDao.getById(topicUid); @@ -360,26 +371,26 @@ // get root topic and create record in MessageSeq table MessageSeq parentSeq = messageSeqDao.getByTopicId(parent.getUid()); if (parentSeq == null) { - ForumService.log.error("Message Sequence table is broken becuase topic " + parent - + " can not get Sequence Record"); + ForumService.log + .error("Message Sequence table is broken becuase topic " + parent + " can not get Sequence Record"); } Message root = parentSeq.getRootMessage(); MessageSeq msgSeq = new MessageSeq(); msgSeq.setMessage(replyMessage); msgSeq.setMessageLevel((short) (parentSeq.getMessageLevel() + 1)); msgSeq.setRootMessage(root); - + // look back up through the parents to find the thread top - will be level 1 - if ( msgSeq.getMessageLevel() == 1 ) { + if (msgSeq.getMessageLevel() == 1) { msgSeq.setThreadMessage(replyMessage); } else { MessageSeq threadSeq = parentSeq; - while ( threadSeq.getMessageLevel() > 1 ) { + while (threadSeq.getMessageLevel() > 1) { threadSeq = messageSeqDao.getByTopicId(threadSeq.getMessage().getParent().getUid()); } msgSeq.setThreadMessage(threadSeq.getMessage()); } - + messageSeqDao.save(msgSeq); // update last reply date for root message @@ -393,7 +404,7 @@ @Override public Attachment uploadAttachment(FormFile uploadFile) throws PersistenceException { - if (uploadFile == null || StringUtils.isEmpty(uploadFile.getFileName())) { + if ((uploadFile == null) || StringUtils.isEmpty(uploadFile.getFileName())) { throw new ForumException("Could not find upload file: " + uploadFile); } @@ -419,67 +430,67 @@ return getSortedMessageDTO(map); } - + @Override - public List getTopicThread(Long rootTopicId, Long afterSequenceId, Long pagingSize ) { + public List getTopicThread(Long rootTopicId, Long afterSequenceId, Long pagingSize) { long lastThreadMessageUid = afterSequenceId != null ? afterSequenceId.longValue() : 0L; long usePagingSize = pagingSize != null ? pagingSize.longValue() : ForumConstants.DEFAULT_PAGE_SIZE; - + SortedMap map = new TreeMap(new TopicComparator()); // first time through we need to include the top topic message (level 0) - if ( lastThreadMessageUid == 0 ) { + if (lastThreadMessageUid == 0) { MessageSeq msgSeq = messageSeqDao.getByTopicId(rootTopicId); map.put(msgSeq, msgSeq.getMessage()); } long count = 0; - boolean foundEnough = false; - - do { - - List msgSeqs = messageSeqDao.getNextThreadByThreadId(rootTopicId, lastThreadMessageUid); - if ( msgSeqs.size() == 0 ) { + boolean foundEnough = false; + + do { + + List msgSeqs = messageSeqDao.getNextThreadByThreadId(rootTopicId, lastThreadMessageUid); + if (msgSeqs.size() == 0) { // no more to come from db foundEnough = true; } else { - + Iterator iter = msgSeqs.iterator(); - while ( iter.hasNext() ) { - MessageSeq msgSeq = ( MessageSeq) iter.next(); - if ( msgSeq.getMessageLevel() == 1 ) { - lastThreadMessageUid = msgSeq.getMessage().getUid().longValue(); - } - map.put(msgSeq, msgSeq.getMessage()); - count++; - } - if ( usePagingSize >= 0 && count >= usePagingSize ) { - foundEnough = true; - } - } - } while ( ! foundEnough); - + while (iter.hasNext()) { + MessageSeq msgSeq = (MessageSeq) iter.next(); + if (msgSeq.getMessageLevel() == 1) { + lastThreadMessageUid = msgSeq.getMessage().getUid().longValue(); + } + map.put(msgSeq, msgSeq.getMessage()); + count++; + } + if ((usePagingSize >= 0) && (count >= usePagingSize)) { + foundEnough = true; + } + } + } while (!foundEnough); + return getSortedMessageDTO(map); } @Override - public List getThread( Long threadId ) { - List msgSeqs = messageSeqDao.getThreadByThreadId(threadId); + public List getThread(Long threadId) { + List msgSeqs = messageSeqDao.getThreadByThreadId(threadId); SortedMap map = new TreeMap(new TopicComparator()); Iterator iter = msgSeqs.iterator(); - while ( iter.hasNext() ) { - MessageSeq msgSeq = ( MessageSeq) iter.next(); - map.put(msgSeq, msgSeq.getMessage()); - }; + while (iter.hasNext()) { + MessageSeq msgSeq = (MessageSeq) iter.next(); + map.put(msgSeq, msgSeq.getMessage()); + } + ; return getSortedMessageDTO(map); } - @Override public List getRootTopics(Long sessionId) { ForumToolSession session = getSessionBySessionId(sessionId); - if (session == null || session.getForum() == null) { + if ((session == null) || (session.getForum() == null)) { ForumService.log.error("Failed on getting session by given sessionID:" + sessionId); throw new ForumException("Failed on getting session by given sessionID:" + sessionId); } @@ -515,13 +526,14 @@ public ForumUser getUserByUserAndSession(Long userId, Long sessionId) { return forumUserDao.getByUserIdAndSessionId(userId, sessionId); } - + @Override - public List getUsersForTablesorter(final Long sessionId, int page, int size, int sorting, String searchString, - boolean getNotebookEntries) { - return forumUserDao.getUsersForTablesorter(sessionId, page, size, sorting, searchString, getNotebookEntries, coreNotebookService); + public List getUsersForTablesorter(final Long sessionId, int page, int size, int sorting, + String searchString, boolean getNotebookEntries) { + return forumUserDao.getUsersForTablesorter(sessionId, page, size, sorting, searchString, getNotebookEntries, + coreNotebookService); } - + @Override public int getCountUsersBySession(Long sessionId, String searchString) { return forumUserDao.getCountUsersBySession(sessionId, searchString); @@ -540,7 +552,7 @@ @Override public Long getRootTopicId(Long topicId) { MessageSeq seq = messageSeqDao.getByTopicId(topicId); - if (seq == null || seq.getRootMessage() == null) { + if ((seq == null) || (seq.getRootMessage() == null)) { ForumService.log.error("A sequence information can not be found for topic ID:" + topicId); return null; } @@ -615,8 +627,8 @@ notificationMessageParameters[0] = msg.getSubject(); notificationMessageParameters[1] = msg.getUpdated(); notificationMessageParameters[2] = report.getMark(); - notificationMessage.append(getLocalisedMessage("event.mark.release.mark", - notificationMessageParameters)); + notificationMessage + .append(getLocalisedMessage("event.mark.release.mark", notificationMessageParameters)); notificationMessages.put(user.getUserId().intValue(), notificationMessage); } } @@ -653,31 +665,31 @@ currentUser.setSessionFinished(true); forumUserDao.save(currentUser); } - + @Override public AverageRatingDTO rateMessage(Long messageId, Long userId, Long toolSessionID, float rating) { ForumUser imageGalleryUser = getUserByUserAndSession(userId, toolSessionID); MessageRating messageRating = messageRatingDao.getRatingByMessageAndUser(messageId, userId); - Message message = messageDao.getById(messageId); + Message message = messageDao.getById(messageId); - //persist MessageRating changes in DB + // persist MessageRating changes in DB if (messageRating == null) { // add messageRating = new MessageRating(); messageRating.setUser(imageGalleryUser); messageRating.setMessage(message); } messageRating.setRating(rating); messageRatingDao.saveObject(messageRating); - - //to make available new changes be visible in jsp page + + // to make available new changes be visible in jsp page return messageRatingDao.getAverageRatingDTOByMessage(messageId); } - + @Override public AverageRatingDTO getAverageRatingDTOByMessage(Long messageId) { return messageRatingDao.getAverageRatingDTOByMessage(messageId); } - + @Override public int getNumOfRatingsByUserAndForum(Long userUid, Long forumUid) { return messageRatingDao.getNumOfRatingsByUserAndForum(userUid, forumUid); @@ -708,17 +720,16 @@ private MessageDTO makeDTOSetRating(MessageSeq msgSeq, Message message) { MessageDTO dto = MessageDTO.getMessageDTO(message); dto.setLevel(msgSeq.getMessageLevel()); - - //set averageRating + + // set averageRating if (message.getForum().isAllowRateMessages()) { - AverageRatingDTO averageRating = getAverageRatingDTOByMessage(message.getUid()); - dto.setAverageRating(averageRating.getRating()); - dto.setNumberOfVotes(averageRating.getNumberOfVotes()); + AverageRatingDTO averageRating = getAverageRatingDTOByMessage(message.getUid()); + dto.setAverageRating(averageRating.getRating()); + dto.setNumberOfVotes(averageRating.getNumberOfVotes()); } return dto; } - /** * Process an uploaded file. * @@ -730,7 +741,7 @@ */ private NodeKey processFile(FormFile file) { NodeKey node = null; - if (file != null && !StringUtils.isEmpty(file.getFileName())) { + if ((file != null) && !StringUtils.isEmpty(file.getFileName())) { String fileName = file.getFileName(); try { node = getForumToolContentHandler().uploadFile(file.getInputStream(), fileName, file.getContentType()); @@ -779,7 +790,7 @@ ForumService.log.error(error); throw new ForumException(error); } - + Forum defaultForum = getForumByContentId(defaultForumId); if (defaultForum == null) { String error = "Could not retrieve default content record for this tool"; @@ -801,7 +812,7 @@ @Override public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(sessionId, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -812,12 +823,12 @@ public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } - + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public String getLearnerContentFolder(Long toolSessionId, Long userId) { return toolService.getLearnerContentFolder(toolSessionId, userId); @@ -826,6 +837,7 @@ // *************************************************************************************************************** // ToolContentManager and ToolSessionManager methods // *************************************************************************************************************** + @Override public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { if (toContentId == null) { throw new ToolException("Failed to create the ForumFiles tool seession"); @@ -848,7 +860,7 @@ while (iter.hasNext()) { Message msg = (Message) iter.next(); // set this message forum Uid as toContent - if (!msg.getIsAuthored() || msg.getToolSession() != null) { + if (!msg.getIsAuthored() || (msg.getToolSession() != null)) { iter.remove(); continue; } @@ -861,7 +873,7 @@ createRootTopic(toContent.getUid(), (ForumToolSession) null, msg); } } - + forumDao.saveOrUpdate(toContent); } @@ -875,25 +887,31 @@ forum.setDefineLater(false); forum.setContentInUse(false); } - - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + + @Override + public void removeToolContent(Long toolContentId) throws ToolException { Forum forum = forumDao.getByContentId(toolContentId); - if (removeSessionData) { - List list = forumToolSessionDao.getByContentId(toolContentId); - Iterator iter = list.iterator(); - while (iter.hasNext()) { - ForumToolSession session = (ForumToolSession) iter.next(); - forumToolSessionDao.delete(session); + if (forum == null) { + ForumService.log.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (ForumToolSession session : forumToolSessionDao.getByContentId(toolContentId)) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, ForumConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); } } + forumDao.delete(forum); } - @SuppressWarnings("unchecked") + @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (log.isDebugEnabled()) { - log.debug("Hiding or removing Forum messages for user ID " + userId + " and toolContentId " + toolContentId); + if (ForumService.log.isDebugEnabled()) { + ForumService.log.debug( + "Hiding or removing Forum messages for user ID " + userId + " and toolContentId " + toolContentId); } List sessionList = forumToolSessionDao.getByContentId(toolContentId); @@ -966,7 +984,7 @@ Set items = toolContentObj.getMessages(); Set authorItems = new HashSet(); for (Message item : items) { - if (item.getIsAuthored() && item.getToolSession() == null) { + if (item.getIsAuthored() && (item.getToolSession() == null)) { authorItems.add(item); item.setCreatedBy(null); item.setModifiedBy(null); @@ -993,15 +1011,15 @@ try { // register version filter class exportContentService.registerImportVersionFilterClass(ForumImportContentVersionFilter.class); - + exportContentService.registerFileClassForImport(Attachment.class.getName(), "fileUuid", "fileVersionId", "fileName", "fileType", null, null); Object toolPOJO = exportContentService.importToolContent(toolContentPath, forumToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof Forum)) { - throw new ImportToolContentException("Import Forum tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import Forum tool content failed. Deserialized object is " + toolPOJO); } Forum toolContentObj = (Forum) toolPOJO; @@ -1055,12 +1073,12 @@ public String getToolContentTitle(Long toolContentId) { return getForumByContentId(toolContentId).getTitle(); } - + @Override public boolean isContentEdited(Long toolContentId) { return getForumByContentId(toolContentId).isDefineLater(); } - + @Override public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException { ForumToolSession session = new ForumToolSession(); @@ -1072,14 +1090,14 @@ // also clone author created topic from this forum tool content!!! // this can avoid topic record information conflict when multiple sessions are against same tool content // for example, the reply number maybe various for different sessions. - if ( log.isDebugEnabled() ) { - log.debug("Clone tool content [" + forum.getContentId() + "] topics for session [" - + session.getSessionId() + "]"); + if (ForumService.log.isDebugEnabled()) { + ForumService.log.debug("Clone tool content [" + forum.getContentId() + "] topics for session [" + + session.getSessionId() + "]"); } Set contentTopics = forum.getMessages(); - if (contentTopics != null && contentTopics.size() > 0) { + if ((contentTopics != null) && (contentTopics.size() > 0)) { for (Message msg : contentTopics) { - if (msg.getIsAuthored() && msg.getToolSession() == null) { + if (msg.getIsAuthored() && (msg.getToolSession() == null)) { Message newMsg = Message.newInstance(msg); msg.getSessionClones().add(newMsg); createRootTopic(forum.getContentId(), session, newMsg); @@ -1089,7 +1107,7 @@ session.setStatus(ForumConstants.STATUS_CONTENT_COPYED); forumToolSessionDao.saveOrUpdate(session); - if ( log.isDebugEnabled() ) { + if (ForumService.log.isDebugEnabled()) { ForumService.log.debug("tool session [" + session.getSessionId() + "] created."); } } @@ -1118,13 +1136,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -1144,10 +1163,10 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return forumOutputFactory.getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } @Override @@ -1160,7 +1179,8 @@ Forum defaultContent = getDefaultForum(); if (defaultContent.getConditions().isEmpty()) { - ForumCondition defaultCondition = getForumOutputFactory().createDefaultTopicDateToAnswersCondition(defaultContent); + ForumCondition defaultCondition = getForumOutputFactory() + .createDefaultTopicDateToAnswersCondition(defaultContent); if (defaultCondition != null) { defaultContent.getConditions().add(defaultCondition); } @@ -1181,6 +1201,7 @@ /** * Import the data for a 1.0.2 Forum */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { Date now = new Date(); Forum toolContentObj = new Forum(); @@ -1199,8 +1220,8 @@ toolContentObj.setContentInUse(Boolean.FALSE); toolContentObj.setCreated(now); toolContentObj.setDefineLater(Boolean.FALSE); - toolContentObj.setInstructions(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); + toolContentObj.setInstructions( + WebUtil.convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY))); toolContentObj.setMaxCharacters(5000); // this is the default value toolContentObj.setReflectOnActivity(Boolean.FALSE); toolContentObj.setReflectInstructions(null); @@ -1269,8 +1290,8 @@ message.setUpdated(msgDate); message.setLastReplyDate(msgDate); message.setSubject((String) messageMap.get(ToolContentImport102Manager.CONTENT_TITLE)); - message.setBody(WebUtil.convertNewlines((String) messageMap - .get(ToolContentImport102Manager.CONTENT_MB_TOPIC_MESSAGE))); + message.setBody(WebUtil.convertNewlines( + (String) messageMap.get(ToolContentImport102Manager.CONTENT_MB_TOPIC_MESSAGE))); // ignore the old subject field - it wasn't updated by the old interface. message.setHideFlag(Boolean.FALSE); message.setIsAnonymous(Boolean.FALSE); @@ -1283,19 +1304,18 @@ } catch (WDDXProcessorConversionException e) { ForumService.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."); + 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."); } } /** * 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { Forum toolContentObj = getForumByContentId(toolContentId); if (toolContentObj == null) { @@ -1384,7 +1404,7 @@ public void setMessageSeqDao(MessageSeqDao messageSeqDao) { this.messageSeqDao = messageSeqDao; } - + public MessageRatingDAO getMessageRatingDao() { return messageRatingDao; } @@ -1457,6 +1477,7 @@ this.coreNotebookService = coreNotebookService; } + @Override public IEventNotificationService getEventNotificationService() { return eventNotificationService; } @@ -1465,6 +1486,7 @@ this.eventNotificationService = eventNotificationService; } + @Override public String getLocalisedMessage(String key, Object[] args) { return messageService.getMessage(key, args); } @@ -1476,14 +1498,15 @@ public void setLessonService(ILessonService lessonService) { this.lessonService = lessonService; } - + public void setActivityDAO(IActivityDAO activityDAO) { this.activityDAO = activityDAO; } /** * {@inheritDoc} */ + @Override public String createTextSearchConditionName(Collection existingConditions) { String uniqueNumber = null; do { @@ -1505,8 +1528,9 @@ * @param userId * @return */ + @Override public int getNewMessagesNum(Message message, Long userId) { - + Timestamp timestamp = timestampDao.getTimestamp(message.getUid(), userId); if (timestamp == null) { // if first time - show all postings as new, including root message @@ -1516,6 +1540,7 @@ } } + @Override public void saveTimestamp(Long rootTopicId, ForumUser forumUser) { Timestamp timestamp = timestampDao.getTimestamp(rootTopicId, forumUser.getUid()); if (timestamp != null) { @@ -1529,6 +1554,7 @@ timestampDao.saveOrUpdate(timestamp); } + @Override public void sendNotificationsOnNewPosting(Long forumId, Long sessionId, Message message) { Forum forum = getForum(forumId); ForumUser postAuthor = message.getCreatedBy(); @@ -1540,7 +1566,7 @@ if (forum.isNotifyLearnersOnForumPosting()) { List learners = lessonService.getLearnersAttemptedOrCompletedActivity(activity); - if (learners != null && !learners.isEmpty()) { + if ((learners != null) && !learners.isEmpty()) { ArrayList learnerIds = new ArrayList(); for (User learner : learners) { learnerIds.add(learner.getUserId()); @@ -1561,19 +1587,21 @@ } } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getForumOutputFactory().getSupportedDefinitionClasses(definitionType); } - + // ****************** REST methods ************************* - /** Used by the Rest calls to create content. - * Mandatory fields in toolContentJSON: title, instructions, topics. + /** + * Used by the Rest calls to create content. Mandatory fields in toolContentJSON: title, instructions, topics. * Topics must contain a JSONArray of JSONObject objects, which have the following mandatory fields: subject, body * There will usually be at least one topic object in the Topics array but the array may be of zero length. */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) + throws JSONException { Forum forum = new Forum(); Date updateDate = new Date(); @@ -1583,10 +1611,12 @@ forum.setContentId(toolContentID); forum.setTitle(toolContentJSON.getString(RestTags.TITLE)); forum.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); - + forum.setAllowAnonym(JsonUtil.opt(toolContentJSON, "allowAnonym", Boolean.FALSE)); - forum.setAllowEdit(JsonUtil.opt(toolContentJSON, "allowEdit", Boolean.TRUE)); // defaults to true in the default entry in the db - forum.setAllowNewTopic(JsonUtil.opt(toolContentJSON, "allowNewTopic", Boolean.TRUE)); // defaults to true in the default entry in the db + forum.setAllowEdit(JsonUtil.opt(toolContentJSON, "allowEdit", Boolean.TRUE)); // defaults to true in the default + // entry in the db + forum.setAllowNewTopic(JsonUtil.opt(toolContentJSON, "allowNewTopic", Boolean.TRUE)); // defaults to true in the + // default entry in the db forum.setAllowRateMessages(JsonUtil.opt(toolContentJSON, "allowRateMessages", Boolean.FALSE)); forum.setAllowRichEditor(JsonUtil.opt(toolContentJSON, RestTags.ALLOW_RICH_TEXT_EDITOR, Boolean.FALSE)); forum.setAllowUpload(JsonUtil.opt(toolContentJSON, "allowUpload", Boolean.FALSE)); @@ -1595,67 +1625,72 @@ forum.setLimitedMaxCharacters(JsonUtil.opt(toolContentJSON, "limitedMaxCharacters", Boolean.TRUE)); forum.setLimitedMinCharacters(JsonUtil.opt(toolContentJSON, "limitedMinCharacters", Boolean.FALSE)); forum.setLockWhenFinished(JsonUtil.opt(toolContentJSON, "lockWhenFinished", Boolean.FALSE)); - forum.setMaxCharacters(JsonUtil.opt(toolContentJSON, "maxCharacters", 5000)); // defaults to 5000 chars in the default entry in the db. + forum.setMaxCharacters(JsonUtil.opt(toolContentJSON, "maxCharacters", 5000)); // defaults to 5000 chars in the + // default entry in the db. forum.setMaximumRate(JsonUtil.opt(toolContentJSON, "maximumRate", 0)); forum.setMaximumReply(JsonUtil.opt(toolContentJSON, "maximumReply", 0)); forum.setMinCharacters(JsonUtil.opt(toolContentJSON, "minCharacters", 0)); forum.setMinimumRate(JsonUtil.opt(toolContentJSON, "minimumRate", 0)); forum.setMinimumReply(JsonUtil.opt(toolContentJSON, "minimumReply", 0)); - forum.setNotifyLearnersOnForumPosting(JsonUtil.opt(toolContentJSON, "notifyLearnersOnForumPosting", Boolean.FALSE)); - forum.setNotifyLearnersOnMarkRelease(JsonUtil.opt(toolContentJSON, "notifyLearnersOnMarkRelease", Boolean.FALSE)); - forum.setNotifyTeachersOnForumPosting(JsonUtil.opt(toolContentJSON, "notifyTeachersOnForumPosting", Boolean.FALSE)); + forum.setNotifyLearnersOnForumPosting( + JsonUtil.opt(toolContentJSON, "notifyLearnersOnForumPosting", Boolean.FALSE)); + forum.setNotifyLearnersOnMarkRelease( + JsonUtil.opt(toolContentJSON, "notifyLearnersOnMarkRelease", Boolean.FALSE)); + forum.setNotifyTeachersOnForumPosting( + JsonUtil.opt(toolContentJSON, "notifyTeachersOnForumPosting", Boolean.FALSE)); forum.setReflectInstructions((String) JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null)); forum.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); // submissionDeadline is set in monitoring - + // *******************************Handle user******************* - // Code taken from AuthoringAction TODO -// String contentFolderID = (String) sessionMap.get(AttributeNames.PARAM_CONTENT_FOLDER_ID); + // Code taken from AuthoringAction TODO + // String contentFolderID = (String) sessionMap.get(AttributeNames.PARAM_CONTENT_FOLDER_ID); // check whether it is sysadmin:LDEV-906 -// if (!StringUtils.equals(contentFolderID, "-1")) { - // try to get form system session -// HttpSession ss = SessionManager.getSession(); - // get back login user DTO -// UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); + // if (!StringUtils.equals(contentFolderID, "-1")) { + // try to get form system session + // HttpSession ss = SessionManager.getSession(); + // get back login user DTO + // UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); ForumUser forumUser = getUserByID(userID.longValue()); if (forumUser == null) { - forumUser = new ForumUser(userID.longValue(), toolContentJSON.getString("firstName"), toolContentJSON.getString("lastName"),toolContentJSON.getString("loginName")); - getForumUserDao().save(forumUser); + forumUser = new ForumUser(userID.longValue(), toolContentJSON.getString("firstName"), + toolContentJSON.getString("lastName"), toolContentJSON.getString("loginName")); + getForumUserDao().save(forumUser); } forum.setCreatedBy(forumUser); - - updateForum(forum); + updateForum(forum); + // **************************** Handle topic ********************* JSONArray topics = toolContentJSON.getJSONArray("topics"); - for (int i=0; i markers = gmap.getGmapMarkers(); - if (markers != null && markers.size() > 0) { + if ((markers != null) && (markers.size() > 0)) { for (GmapMarker marker : markers) { - if (marker.isAuthored() && marker.getGmapSession() == null) { + if (marker.isAuthored() && (marker.getGmapSession() == null)) { GmapMarker newMarker = (GmapMarker) marker.clone(); newMarker.setGmapSession(session); saveOrUpdateGmapMarker(newMarker); @@ -148,13 +147,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -173,14 +173,15 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return null; } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /* ************ Methods from ToolContentManager ************************* */ + @Override public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { if (GmapService.logger.isDebugEnabled()) { @@ -214,19 +215,36 @@ gmap.setDefineLater(false); gmapDAO.saveOrUpdate(gmap); } - - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { - // TODO Auto-generated method stub + + @Override + public void removeToolContent(Long toolContentId) throws ToolException { + Gmap gmap = gmapDAO.getByContentId(toolContentId); + if (gmap == null) { + GmapService.logger.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (GmapSession session : gmap.getGmapSessions()) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, GmapConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); + } + } + + gmapDAO.delete(gmap); } + @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("Removing Gmap markers for user ID " + userId + " and toolContentId " + toolContentId); + if (GmapService.logger.isDebugEnabled()) { + GmapService.logger + .debug("Removing Gmap markers for user ID " + userId + " and toolContentId " + toolContentId); } Gmap gmap = gmapDAO.getByContentId(toolContentId); if (gmap == null) { - logger.warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); + GmapService.logger + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } @@ -253,16 +271,17 @@ } } } - + /** * Export the XML fragment for the tool's content, along with any files needed for the content. * * @throws DataMissingException - * if no tool content matches the toolSessionId + * if no tool content matches the toolSessionId * @throws ToolException - * if any other error occurs + * if any other error occurs */ + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { Gmap gmap = gmapDAO.getByContentId(toolContentId); if (gmap == null) { @@ -303,19 +322,20 @@ * Import the XML fragment for the tool's content, along with any files needed for the content. * * @throws ToolException - * if any other error occurs + * if any other error occurs */ + @Override public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion, String toVersion) throws ToolException { try { // register version filter class exportContentService.registerImportVersionFilterClass(GmapImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, gmapToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof Gmap)) { - throw new ImportToolContentException("Import Gmap tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import Gmap tool content failed. Deserialized object is " + toolPOJO); } Gmap gmap = (Gmap) toolPOJO; @@ -354,21 +374,25 @@ * * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition */ + @Override public SortedMap getToolOutputDefinitions(Long toolContentId, int definitionType) throws ToolException { return new TreeMap(); } + @Override public String getToolContentTitle(Long toolContentId) { return getGmapByContentId(toolContentId).getTitle(); } - + + @Override public boolean isContentEdited(Long toolContentId) { return getGmapByContentId(toolContentId).isDefineLater(); } - + /* ********** IGmapService Methods ********************************* */ + @Override public Long getDefaultContentIdBySignature(String toolSignature) { Long toolContentId = null; toolContentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature)); @@ -380,6 +404,7 @@ return toolContentId; } + @Override public Gmap getDefaultContent() { Long defaultContentID = getDefaultContentIdBySignature(GmapConstants.TOOL_SIGNATURE); Gmap defaultContent = getGmapByContentId(defaultContentID); @@ -391,6 +416,7 @@ return defaultContent; } + @Override public Gmap copyDefaultContent(Long newContentID) { if (newContentID == null) { @@ -407,6 +433,7 @@ return newContent; } + @Override public Gmap getGmapByContentId(Long toolContentID) { Gmap gmap = gmapDAO.getByContentId(toolContentID); if (gmap == null) { @@ -415,6 +442,7 @@ return gmap; } + @Override public GmapSession getSessionBySessionId(Long toolSessionId) { GmapSession gmapSession = gmapSessionDAO.getBySessionId(toolSessionId); if (gmapSession == null) { @@ -423,6 +451,7 @@ return gmapSession; } + @Override public GmapUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { return gmapUserDAO.getByUserIdAndSessionId(userId, toolSessionId); } @@ -431,40 +460,49 @@ return gmapUserDAO.getByLoginNameAndSessionId(loginName, toolSessionId); } + @Override public GmapUser getUserByUID(Long uid) { return gmapUserDAO.getByUID(uid); } + @Override public void saveOrUpdateGmap(Gmap gmap) { gmapDAO.saveOrUpdate(gmap); } + @Override public void saveOrUpdateGmapMarker(GmapMarker gmapMarker) { gmapMarkerDAO.saveOrUpdate(gmapMarker); } + @Override public List getGmapMarkersBySessionId(Long sessionId) { return gmapMarkerDAO.getByToolSessionId(sessionId); } + @Override public void saveOrUpdateGmapSession(GmapSession gmapSession) { gmapSessionDAO.saveOrUpdate(gmapSession); } + @Override public void saveOrUpdateGmapUser(GmapUser gmapUser) { gmapUserDAO.saveOrUpdate(gmapUser); } + @Override public GmapUser createGmapUser(UserDTO user, GmapSession gmapSession) { GmapUser gmapUser = new GmapUser(user, gmapSession); saveOrUpdateGmapUser(gmapUser); return gmapUser; } + @Override public GmapConfigItem getConfigItem(String key) { return gmapConfigItemDAO.getConfigItemByKey(key); } + @Override public void saveOrUpdateGmapConfigItem(GmapConfigItem item) { gmapConfigItemDAO.saveOrUpdate(item); } @@ -476,10 +514,11 @@ * org.lamsfoundation.lams.tool.gmap.model.Gmap, org.lamsfoundation.lams.tool.gmap.model.GmapUser, boolean, * org.lamsfoundation.lams.tool.gmap.model.GmapSession) */ + @Override public void updateMarkerListFromXML(String markerXML, Gmap gmap, GmapUser guser, boolean isAuthored, GmapSession session) { - if (markerXML != null && !markerXML.equals("")) { + if ((markerXML != null) && !markerXML.equals("")) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); @@ -531,7 +570,8 @@ GmapService.logger.debug("MarkerXML string was empty"); } } - + + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } @@ -541,6 +581,7 @@ /** * Import the data for a 1.0.2 Gmap */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { Date now = new Date(); Gmap gmap = new Gmap(); @@ -556,11 +597,12 @@ } /** 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { - GmapService.logger - .warn("Setting the reflective field on a gmap. This doesn't make sense as the gmap is for reflection and we don't reflect on reflection!"); + GmapService.logger.warn( + "Setting the reflective field on a gmap. This doesn't make sense as the gmap is for reflection and we don't reflect on reflection!"); Gmap gmap = getGmapByContentId(toolContentId); if (gmap == null) { throw new DataMissingException("Unable to set reflective data titled " + title @@ -653,13 +695,15 @@ this.gmapConfigItemDAO = gmapConfigItemDAO; } + @Override public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry) { return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); } + @Override public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(sessionId, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -669,10 +713,12 @@ /** * @param notebookEntry */ + @Override public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return null; } Index: lams_tool_images/src/java/org/lamsfoundation/lams/tool/imageGallery/service/ImageGalleryServiceImpl.java =================================================================== diff -u -r7530a8f92ba05991702ccc1bd0d388ea6827cba3 -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_images/src/java/org/lamsfoundation/lams/tool/imageGallery/service/ImageGalleryServiceImpl.java (.../ImageGalleryServiceImpl.java) (revision 7530a8f92ba05991702ccc1bd0d388ea6827cba3) +++ lams_tool_images/src/java/org/lamsfoundation/lams/tool/imageGallery/service/ImageGalleryServiceImpl.java (.../ImageGalleryServiceImpl.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -68,7 +68,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.imageGallery.ImageGalleryConstants; import org.lamsfoundation.lams.tool.imageGallery.dao.ImageGalleryConfigItemDAO; @@ -103,8 +102,8 @@ /** * @author Andrey Balan */ -public class ImageGalleryServiceImpl implements IImageGalleryService, ToolContentManager, ToolSessionManager, - ToolContentImport102Manager { +public class ImageGalleryServiceImpl + implements IImageGalleryService, ToolContentManager, ToolSessionManager, ToolContentImport102Manager { private final static String MEDIUM_FILENAME_PREFIX = "medium_"; @@ -146,7 +145,7 @@ private IExportToolContentService exportContentService; private ICoreNotebookService coreNotebookService; - + private IRatingService ratingService; private IEventNotificationService eventNotificationService; @@ -211,18 +210,19 @@ public void saveOrUpdateImageGalleryItem(ImageGalleryItem image) { imageGalleryItemDao.saveObject(image); } - + @Override public void deleteImage(Long toolSessionId, Long imageUid) { ImageGallery imageGallery = getImageGalleryBySessionId(toolSessionId); ImageGalleryItem image = getImageGalleryItemByUid(imageUid); - + Set imageList = imageGallery.getImageGalleryItems(); imageList.remove(image); imageGallery.setImageGalleryItems(imageList); saveOrUpdateImageGallery(imageGallery); } + @Override public ImageVote getImageVoteByImageAndUser(Long imageUid, Long userId) { return imageVoteDao.getImageVoteByImageAndUser(imageUid, userId); } @@ -334,7 +334,7 @@ @Override public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(sessionId, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -345,7 +345,7 @@ public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } - + @Override public ItemRatingDTO getRatingCriteriaDtos(Long contentId, Long imageUid, Long userId) { @@ -355,29 +355,30 @@ return ratingCriteria; } - + @Override public List getRatingCriteriaDtos(Long contentId, Collection itemIds, boolean isCommentsByOtherUsersRequired, Long userId) { return ratingService.getRatingCriteriaDtos(contentId, itemIds, isCommentsByOtherUsersRequired, userId); } - + @Override public int getCountItemsRatedByUser(Long toolContentId, Integer userId) { return ratingService.getCountItemsRatedByUser(toolContentId, userId); } - + @Override public List getRatingCriterias(Long toolContentId) { List ratingCriterias = ratingService.getCriteriasByToolContentId(toolContentId); return ratingCriterias; } - + @Override - public void saveRatingCriterias(HttpServletRequest request, Collection oldCriterias, Long toolContentId) { + public void saveRatingCriterias(HttpServletRequest request, Collection oldCriterias, + Long toolContentId) { ratingService.saveRatingCriterias(request, oldCriterias, toolContentId); } - + @Override public boolean isCommentsEnabled(Long toolContentId) { return ratingService.isCommentsEnabled(toolContentId); @@ -401,7 +402,7 @@ // one new group for one session. group = new ArrayList(); Set groupImages = getImagesForGroup(imageGallery, session.getSessionId()); - + List itemRatingDtos = null; if (imageGallery.isAllowRank()) { // create itemIds list @@ -411,9 +412,10 @@ } final Long USER_ID = -1L; final boolean IS_COMMENTS_BY_OTHER_USERS_REQUIRED = true; - // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!TODO calculate average ratings based on one session data - itemRatingDtos = getRatingCriteriaDtos(contentId, itemIds, - IS_COMMENTS_BY_OTHER_USERS_REQUIRED, USER_ID); + // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!TODO calculate average ratings based on one + // session data + itemRatingDtos = getRatingCriteriaDtos(contentId, itemIds, IS_COMMENTS_BY_OTHER_USERS_REQUIRED, + USER_ID); } for (ImageGalleryItem image : groupImages) { @@ -466,22 +468,23 @@ for (ImageGallerySession session : sessionList) { // one new group for one session. group = new ArrayList(); -// Object[] ratingForGroup = getRatingForGroup(image.getUid(), session.getSessionId()); + // Object[] ratingForGroup = getRatingForGroup(image.getUid(), session.getSessionId()); List users = imageGalleryUserDao.getBySessionID(session.getSessionId()); for (ImageGalleryUser user : users) { - - //create UserContribution - UserImageContributionDTO userContribution = new UserImageContributionDTO(session.getSessionName(), user); - + + // create UserContribution + UserImageContributionDTO userContribution = new UserImageContributionDTO(session.getSessionName(), + user); + if (imageGallery.isAllowVote()) { int numberOfVotesForImage = imageVoteDao.getNumImageVotesByImageUid(image.getUid(), session.getSessionId()); userContribution.setNumberOfVotesForImage(numberOfVotesForImage); boolean isVotedForThisImage = false; ImageVote imageVote = imageVoteDao.getImageVoteByImageAndUser(image.getUid(), user.getUserId()); - if (imageVote != null && imageVote.isVoted()) { + if ((imageVote != null) && imageVote.isVoted()) { isVotedForThisImage = true; } userContribution.setVotedForThisImage(isVotedForThisImage); @@ -491,12 +494,13 @@ // userContribution.setNumberRatings(((Long) ratingForGroup[0]).intValue()); // userContribution.setAverageRating(((Float) ratingForGroup[1]).floatValue()); -// ImageRating rating = imageRatingDao.getImageRatingByImageAndUser(image.getUid(), user.getUserId()); -// if (rating != null) { -// userContribution.setRating(rating.getRating()); -// } + // ImageRating rating = imageRatingDao.getImageRatingByImageAndUser(image.getUid(), + // user.getUserId()); + // if (rating != null) { + // userContribution.setRating(rating.getRating()); + // } } - + group.add(userContribution); } @@ -562,10 +566,10 @@ List userContributionList = new ArrayList(); -// Object[] ratingForGroup = getRatingForGroup(image.getUid(), session.getSessionId()); -// UserImageContributionDTO userContribution = createUserContribution(image, user, session, ratingForGroup); -// userContribution.setImage(image); -// userContributionList.add(userContribution); + // Object[] ratingForGroup = getRatingForGroup(image.getUid(), session.getSessionId()); + // UserImageContributionDTO userContribution = createUserContribution(image, user, session, ratingForGroup); + // userContribution.setImage(image); + // userContributionList.add(userContribution); imageList.add(userContributionList); } @@ -585,16 +589,16 @@ dbImages.addAll(imageGallery.getImageGalleryItems()); for (ImageGalleryItem image : dbImages) { List userContributionList = new ArrayList(); -// Object[] ratingForGroup = getRatingForGroup(image.getUid(), imageSession.getSessionId()); + // Object[] ratingForGroup = getRatingForGroup(image.getUid(), imageSession.getSessionId()); -// List userList = imageGalleryUserDao.getBySessionID(imageSession.getSessionId()); -// for (ImageGalleryUser user : userList) { -// UserImageContributionDTO userContribution = createUserContribution(image, user, imageSession, -// ratingForGroup); -// userContribution.setImage(image); -// userContributionList.add(userContribution); -// } -// imageList.add(userContributionList); + // List userList = imageGalleryUserDao.getBySessionID(imageSession.getSessionId()); + // for (ImageGalleryUser user : userList) { + // UserImageContributionDTO userContribution = createUserContribution(image, user, imageSession, + // ratingForGroup); + // userContribution.setImage(image); + // userContributionList.add(userContribution); + // } + // imageList.add(userContributionList); } @@ -617,7 +621,8 @@ String fileName = file.getFileName(); - ImageGalleryConfigItem mediumImageDimensionsKey = getConfigItem(ImageGalleryConfigItem.KEY_MEDIUM_IMAGE_DIMENSIONS); + ImageGalleryConfigItem mediumImageDimensionsKey = getConfigItem( + ImageGalleryConfigItem.KEY_MEDIUM_IMAGE_DIMENSIONS); int mediumImageDimensions = Integer.parseInt(mediumImageDimensionsKey.getConfigValue()); // Read the original image from the repository @@ -632,7 +637,8 @@ file.getContentType()); image.setMediumFileUuid(mediumNodeKey.getUuid()); - ImageGalleryConfigItem thumbnailImageDimensionsKey = getConfigItem(ImageGalleryConfigItem.KEY_THUMBNAIL_IMAGE_DIMENSIONS); + ImageGalleryConfigItem thumbnailImageDimensionsKey = getConfigItem( + ImageGalleryConfigItem.KEY_THUMBNAIL_IMAGE_DIMENSIONS); int thumbnailImageDimensions = Integer.parseInt(thumbnailImageDimensionsKey.getConfigValue()); // Read the original image from the repository @@ -648,17 +654,17 @@ image.setThumbnailFileUuid(thumbnailNodeKey.getUuid()); } catch (RepositoryCheckedException e) { - ImageGalleryServiceImpl.log.error(messageService.getMessage("error.msg.repository.checked.exception") + ":" - + e.toString()); - throw new UploadImageGalleryFileException(messageService - .getMessage("error.msg.repository.checked.exception")); + ImageGalleryServiceImpl.log + .error(messageService.getMessage("error.msg.repository.checked.exception") + ":" + e.toString()); + throw new UploadImageGalleryFileException( + messageService.getMessage("error.msg.repository.checked.exception")); } catch (NumberFormatException e) { - ImageGalleryServiceImpl.log.error(messageService.getMessage("error.msg.number.format.exception") + ":" - + e.toString()); + ImageGalleryServiceImpl.log + .error(messageService.getMessage("error.msg.number.format.exception") + ":" + e.toString()); throw new UploadImageGalleryFileException(messageService.getMessage("error.msg.number.format.exception")); } catch (IOException e) { - ImageGalleryServiceImpl.log.error(messageService.getMessage("error.msg.io.exception.resizing") + ":" - + e.toString()); + ImageGalleryServiceImpl.log + .error(messageService.getMessage("error.msg.io.exception.resizing") + ":" + e.toString()); throw new ImageGalleryException(messageService.getMessage("error.msg.io.exception.resizing")); } } @@ -673,9 +679,9 @@ * @throws InvalidParameterException */ private NodeKey uploadFormFile(FormFile file) throws UploadImageGalleryFileException { - if (file == null || StringUtils.isEmpty(file.getFileName())) { - throw new UploadImageGalleryFileException(messageService.getMessage("error.msg.upload.file.not.found", - new Object[] { file })); + if ((file == null) || StringUtils.isEmpty(file.getFileName())) { + throw new UploadImageGalleryFileException( + messageService.getMessage("error.msg.upload.file.not.found", new Object[] { file })); } NodeKey node = null; @@ -693,12 +699,12 @@ } return node; } - + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public void notifyTeachersOnImageSumbit(Long sessionId, ImageGalleryUser imageGalleryUser) { String userName = imageGalleryUser.getLastName() + " " + imageGalleryUser.getFirstName(); @@ -720,7 +726,7 @@ public void setMessageService(MessageService messageService) { this.messageService = messageService; } - + public void setImageGalleryDao(ImageGalleryDAO imageGalleryDao) { this.imageGalleryDao = imageGalleryDao; } @@ -787,8 +793,8 @@ toolContentObj = ImageGallery.newInstance(toolContentObj, toolContentId); Set images = toolContentObj.getImageGalleryItems(); for (ImageGalleryItem image : images) { - - //convert file extension to lower case + + // convert file extension to lower case String fileName = image.getFileName(); String[] fileNameParts = fileName.split("\\."); String fileExtension = fileNameParts[fileNameParts.length - 1]; @@ -831,15 +837,15 @@ try { // register version filter class exportContentService.registerImportVersionFilterClass(ImageGalleryImportContentVersionFilter.class); - + exportContentService.registerFileClassForImport(ImageGalleryAttachment.class.getName(), "fileUuid", "fileVersionId", "fileName", "fileType", null, null); Object toolPOJO = exportContentService.importToolContent(toolContentPath, imageGalleryToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof ImageGallery)) { - throw new ImportToolContentException("Import ImageGallery tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import ImageGallery tool content failed. Deserialized object is " + toolPOJO); } ImageGallery toolContentObj = (ImageGallery) toolPOJO; @@ -920,15 +926,15 @@ } } } - + imageGalleryDao.saveObject(toContent); } @Override public String getToolContentTitle(Long toolContentId) { return getImageGalleryByContentId(toolContentId).getTitle(); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { ImageGallery imageGallery = imageGalleryDao.getByContentId(toolContentId); @@ -942,34 +948,41 @@ public boolean isContentEdited(Long toolContentId) { return getImageGalleryByContentId(toolContentId).isDefineLater(); } - + @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId) throws ToolException { ImageGallery imageGallery = imageGalleryDao.getByContentId(toolContentId); - if (removeSessionData) { - List list = imageGallerySessionDao.getByContentId(toolContentId); - Iterator iter = list.iterator(); - while (iter.hasNext()) { - ImageGallerySession session = (ImageGallerySession) iter.next(); - imageGallerySessionDao.delete(session); + if (imageGallery == null) { + ImageGalleryServiceImpl.log + .warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (ImageGallerySession session : imageGallerySessionDao.getByContentId(toolContentId)) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, ImageGalleryConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); } } + imageGalleryDao.delete(imageGallery); } @Override @SuppressWarnings("unchecked") public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (log.isDebugEnabled()) { - log.debug("Removing Image Gallery content for user ID " + userId + " and toolContentId " + toolContentId); + if (ImageGalleryServiceImpl.log.isDebugEnabled()) { + ImageGalleryServiceImpl.log.debug( + "Removing Image Gallery content for user ID " + userId + " and toolContentId " + toolContentId); } ImageGallery gallery = imageGalleryDao.getByContentId(toolContentId); if (gallery == null) { - log.warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); + ImageGalleryServiceImpl.log + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } - + Iterator itemIterator = gallery.getImageGalleryItems().iterator(); while (itemIterator.hasNext()) { ImageGalleryItem item = itemIterator.next(); @@ -1011,7 +1024,7 @@ } } - + @Override public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException { ImageGallerySession session = new ImageGallerySession(); @@ -1047,13 +1060,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -1071,23 +1085,25 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return imageGalleryOutputFactory.getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /* ===============Methods implemented from ToolContentImport102Manager =============== */ /** * Import the data for a 1.0.2 Noticeboard or HTMLNoticeboard */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { } /** 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { ImageGallery toolContentObj = getImageGalleryByContentId(toolContentId); if (toolContentObj == null) { @@ -1124,7 +1140,7 @@ public void setCoreNotebookService(ICoreNotebookService coreNotebookService) { this.coreNotebookService = coreNotebookService; } - + public void setRatingService(IRatingService ratingService) { this.ratingService = ratingService; } @@ -1133,6 +1149,7 @@ this.eventNotificationService = eventNotificationService; } + @Override public String getLocalisedMessage(String key, Object[] args) { return messageService.getMessage(key, args); } @@ -1145,14 +1162,17 @@ this.imageGalleryOutputFactory = imageGalleryOutputFactory; } + @Override public ImageGalleryConfigItem getConfigItem(String key) { return imageGalleryConfigItemDAO.getConfigItemByKey(key); } + @Override public void saveOrUpdateImageGalleryConfigItem(ImageGalleryConfigItem item) { imageGalleryConfigItemDAO.saveOrUpdate(item); } + @Override public Set getImagesForGroup(ImageGallery imageGallery, Long sessionId) { TreeSet images = new TreeSet(new ImageGalleryItemComparator()); @@ -1196,6 +1216,7 @@ return contentId; } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getImageGalleryOutputFactory().getSupportedDefinitionClasses(definitionType); } Index: lams_tool_imscc/src/java/org/lamsfoundation/lams/tool/commonCartridge/service/CommonCartridgeServiceImpl.java =================================================================== diff -u -r6295cf4835d8f435273ea815741a057d030d3508 -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_imscc/src/java/org/lamsfoundation/lams/tool/commonCartridge/service/CommonCartridgeServiceImpl.java (.../CommonCartridgeServiceImpl.java) (revision 6295cf4835d8f435273ea815741a057d030d3508) +++ lams_tool_imscc/src/java/org/lamsfoundation/lams/tool/commonCartridge/service/CommonCartridgeServiceImpl.java (.../CommonCartridgeServiceImpl.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -40,17 +40,13 @@ import java.util.TreeMap; import java.util.TreeSet; -import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.struts.upload.FormFile; import org.lamsfoundation.lams.contentrepository.AccessDeniedException; import org.lamsfoundation.lams.contentrepository.ICredentials; import org.lamsfoundation.lams.contentrepository.ITicket; import org.lamsfoundation.lams.contentrepository.IVersionedNode; -import org.lamsfoundation.lams.contentrepository.InvalidParameterException; import org.lamsfoundation.lams.contentrepository.LoginException; -import org.lamsfoundation.lams.contentrepository.NodeKey; -import org.lamsfoundation.lams.contentrepository.RepositoryCheckedException; import org.lamsfoundation.lams.contentrepository.WorkspaceNotFoundException; import org.lamsfoundation.lams.contentrepository.service.IRepositoryService; import org.lamsfoundation.lams.contentrepository.service.SimpleCredentials; @@ -91,7 +87,6 @@ import org.lamsfoundation.lams.tool.commonCartridge.util.CommonCartridgeToolContentHandler; import org.lamsfoundation.lams.tool.commonCartridge.util.ReflectDTOComparator; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.usermanagement.User; @@ -109,8 +104,8 @@ * @author Andrey Balan * */ -public class CommonCartridgeServiceImpl implements ICommonCartridgeService, ToolContentManager, ToolSessionManager, - ToolContentImport102Manager { +public class CommonCartridgeServiceImpl + implements ICommonCartridgeService, ToolContentManager, ToolSessionManager, ToolContentImport102Manager { static Logger log = Logger.getLogger(CommonCartridgeServiceImpl.class.getName()); private CommonCartridgeDAO commonCartridgeDao; @@ -136,7 +131,7 @@ private ILamsToolService toolService; private ILearnerService learnerService; - + private IAuditService auditService; private IUserManagementService userManagementService; @@ -149,6 +144,7 @@ private ILessonService lessonService; + @Override public IVersionedNode getFileNode(Long itemUid, String relPathString) throws CommonCartridgeApplicationException { CommonCartridgeItem item = (CommonCartridgeItem) commonCartridgeItemDao.getObject(CommonCartridgeItem.class, itemUid); @@ -227,11 +223,13 @@ } } + @Override public CommonCartridge getCommonCartridgeByContentId(Long contentId) { CommonCartridge rs = commonCartridgeDao.getByContentId(contentId); return rs; } + @Override public CommonCartridge getDefaultContent(Long contentId) throws CommonCartridgeApplicationException { if (contentId == null) { String error = messageService.getMessage("error.msg.default.content.not.find"); @@ -246,36 +244,42 @@ return content; } + @Override public List getAuthoredItems(Long commonCartridgeUid) { return commonCartridgeItemDao.getAuthoringItems(commonCartridgeUid); } + @Override public void createUser(CommonCartridgeUser commonCartridgeUser) { commonCartridgeUserDao.saveObject(commonCartridgeUser); } + @Override public CommonCartridgeUser getUserByIDAndContent(Long userId, Long contentId) { return commonCartridgeUserDao.getUserByUserIDAndContentID(userId, contentId); } + @Override public CommonCartridgeUser getUserByIDAndSession(Long userId, Long sessionId) { return commonCartridgeUserDao.getUserByUserIDAndSessionID(userId, sessionId); } + @Override public void deleteFromRepository(Long fileUuid, Long fileVersionId) throws CommonCartridgeApplicationException { ITicket ticket = getRepositoryLoginTicket(); try { repositoryService.deleteVersion(ticket, fileUuid, fileVersionId); } catch (Exception e) { - throw new CommonCartridgeApplicationException("Exception occured while deleting files from" - + " the repository " + e.getMessage()); + throw new CommonCartridgeApplicationException( + "Exception occured while deleting files from" + " the repository " + e.getMessage()); } } + @Override public void saveOrUpdateCommonCartridge(CommonCartridge commonCartridge) { commonCartridgeDao.saveObject(commonCartridge); } @@ -284,10 +288,12 @@ commonCartridgeItemDao.saveObject(item); } + @Override public void deleteCommonCartridgeItem(Long uid) { commonCartridgeItemDao.removeObject(CommonCartridgeItem.class, uid); } + @Override public List getCommonCartridgeItemsBySessionId(Long sessionId) { CommonCartridgeSession session = commonCartridgeSessionDao.getSessionBySessionId(sessionId); if (session == null) { @@ -305,6 +311,7 @@ return items; } + @Override public List exportBySessionId(Long sessionId, boolean skipHide) { CommonCartridgeSession session = commonCartridgeSessionDao.getSessionBySessionId(sessionId); if (session == null) { @@ -342,6 +349,7 @@ return itemList; } + @Override public List> exportByContentId(Long contentId) { CommonCartridge commonCartridge = commonCartridgeDao.getByContentId(contentId); List> groupList = new ArrayList(); @@ -379,26 +387,30 @@ return groupList; } + @Override public CommonCartridge getCommonCartridgeBySessionId(Long sessionId) { CommonCartridgeSession session = commonCartridgeSessionDao.getSessionBySessionId(sessionId); // to skip CGLib problem Long contentId = session.getCommonCartridge().getContentId(); CommonCartridge res = commonCartridgeDao.getByContentId(contentId); int miniView = res.getMiniViewCommonCartridgeNumber(); // construct dto fields; - res.setMiniViewNumberStr(messageService.getMessage("label.learning.minimum.review", new Object[] { new Integer( - miniView) })); + res.setMiniViewNumberStr( + messageService.getMessage("label.learning.minimum.review", new Object[] { new Integer(miniView) })); return res; } + @Override public CommonCartridgeSession getCommonCartridgeSessionBySessionId(Long sessionId) { return commonCartridgeSessionDao.getSessionBySessionId(sessionId); } + @Override public void saveOrUpdateCommonCartridgeSession(CommonCartridgeSession resSession) { commonCartridgeSessionDao.saveObject(resSession); } + @Override public void retrieveComplete(SortedSet commonCartridgeItemList, CommonCartridgeUser user) { for (CommonCartridgeItem item : commonCartridgeItemList) { CommonCartridgeItemVisitLog log = commonCartridgeItemVisitDao.getCommonCartridgeItemLog(item.getUid(), @@ -411,6 +423,7 @@ } } + @Override public void setItemComplete(Long commonCartridgeItemUid, Long userId, Long sessionId) { CommonCartridgeItemVisitLog log = commonCartridgeItemVisitDao.getCommonCartridgeItemLog(commonCartridgeItemUid, userId); @@ -427,6 +440,7 @@ commonCartridgeItemVisitDao.saveObject(log); } + @Override public void setItemAccess(Long commonCartridgeItemUid, Long userId, Long sessionId) { CommonCartridgeItemVisitLog log = commonCartridgeItemVisitDao.getCommonCartridgeItemLog(commonCartridgeItemUid, userId); @@ -443,6 +457,7 @@ } } + @Override public String finishToolSession(Long toolSessionId, Long userId) throws CommonCartridgeApplicationException { CommonCartridgeUser user = commonCartridgeUserDao.getUserByUserIDAndSessionID(userId, toolSessionId); user.setSessionFinished(true); @@ -463,6 +478,7 @@ return nextUrl; } + @Override public int checkMiniView(Long toolSessionId, Long userUid) { int miniView = commonCartridgeItemVisitDao.getUserViewLogCount(toolSessionId, userUid); CommonCartridgeSession session = commonCartridgeSessionDao.getSessionBySessionId(toolSessionId); @@ -475,10 +491,12 @@ return reqView - miniView; } + @Override public CommonCartridgeItem getCommonCartridgeItemByUid(Long itemUid) { return commonCartridgeItemDao.getByUid(itemUid); } + @Override public List> getSummary(Long contentId) { List> groupList = new ArrayList>(); List group = new ArrayList(); @@ -528,6 +546,7 @@ } + @Override public Map> getReflectList(Long contentId, boolean setEntry) { Map> map = new HashMap>(); @@ -558,9 +577,10 @@ return map; } + @Override public List getUserListBySessionItem(Long sessionId, Long itemUid) { - List logList = commonCartridgeItemVisitDao.getCommonCartridgeItemLogBySession( - sessionId, itemUid); + List logList = commonCartridgeItemVisitDao + .getCommonCartridgeItemLogBySession(sessionId, itemUid); List userList = new ArrayList(logList.size()); for (CommonCartridgeItemVisitLog visit : logList) { CommonCartridgeUser user = visit.getUser(); @@ -570,6 +590,7 @@ return userList; } + @Override public void setItemVisible(Long itemUid, boolean visible) { CommonCartridgeItem item = commonCartridgeItemDao.getByUid(itemUid); if (item != null) { @@ -590,15 +611,17 @@ } } + @Override public Long createNotebookEntry(Long sessionId, Integer notebookToolType, String toolSignature, Integer userId, String entryText) { return coreNotebookService.createNotebookEntry(sessionId, notebookToolType, toolSignature, userId, "", entryText); } + @Override public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(sessionId, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -608,10 +631,12 @@ /** * @param notebookEntry */ + @Override public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } + @Override public CommonCartridgeUser getUser(Long uid) { return (CommonCartridgeUser) commonCartridgeUserDao.getObject(CommonCartridgeUser.class, uid); } @@ -642,6 +667,7 @@ return contentId; } + @Override public List uploadCommonCartridgeFile(CommonCartridgeItem item, FormFile file) throws UploadCommonCartridgeFileException { try { @@ -655,43 +681,45 @@ 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()); -// item.setFileType(fileType); -// item.setFileName(fileName); + // // upload package + // NodeKey nodeKey = processPackage(packageDirectory, initFile); + // item.setFileUuid(nodeKey.getUuid()); + // item.setFileVersionId(nodeKey.getVersion()); + // item.setFileType(fileType); + // item.setFileName(fileName); List items = cpConverter.getBasicLTIItems(); return items; } catch (ZipFileUtilException e) { - CommonCartridgeServiceImpl.log.error(messageService.getMessage("error.msg.zip.file.exception") + " : " - + e.toString()); + CommonCartridgeServiceImpl.log + .error(messageService.getMessage("error.msg.zip.file.exception") + " : " + e.toString()); throw new UploadCommonCartridgeFileException(messageService.getMessage("error.msg.zip.file.exception")); } catch (FileNotFoundException e) { - CommonCartridgeServiceImpl.log.error(messageService.getMessage("error.msg.file.not.found") + ":" - + e.toString()); + CommonCartridgeServiceImpl.log + .error(messageService.getMessage("error.msg.file.not.found") + ":" + e.toString()); throw new UploadCommonCartridgeFileException(messageService.getMessage("error.msg.file.not.found")); } catch (IOException e) { - CommonCartridgeServiceImpl.log.error(messageService.getMessage("error.msg.io.exception") + ":" - + e.toString()); + CommonCartridgeServiceImpl.log + .error(messageService.getMessage("error.msg.io.exception") + ":" + e.toString()); throw new UploadCommonCartridgeFileException(messageService.getMessage("error.msg.io.exception")); } catch (IMSManifestException e) { - CommonCartridgeServiceImpl.log.error(messageService.getMessage("error.msg.ims.package") + ":" - + e.toString()); + CommonCartridgeServiceImpl.log + .error(messageService.getMessage("error.msg.ims.package") + ":" + e.toString()); throw new UploadCommonCartridgeFileException(messageService.getMessage("error.msg.ims.package")); } catch (ImscpApplicationException e) { - CommonCartridgeServiceImpl.log.error(messageService.getMessage("error.msg.ims.application") + ":" - + e.toString()); + CommonCartridgeServiceImpl.log + .error(messageService.getMessage("error.msg.ims.application") + ":" + e.toString()); throw new UploadCommonCartridgeFileException(messageService.getMessage("error.msg.ims.application")); } } + @Override public CommonCartridgeConfigItem getConfigItem(String key) { return commonCartridgeConfigItemDao.getConfigItemByKey(key); } + @Override public void saveOrUpdateConfigItem(CommonCartridgeConfigItem item) { commonCartridgeConfigItemDao.saveOrUpdate(item); } @@ -727,7 +755,8 @@ this.commonCartridgeSessionDao = commonCartridgeSessionDao; } - public void setCommonCartridgeToolContentHandler(CommonCartridgeToolContentHandler commonCartridgeToolContentHandler) { + public void setCommonCartridgeToolContentHandler( + CommonCartridgeToolContentHandler commonCartridgeToolContentHandler) { this.commonCartridgeToolContentHandler = commonCartridgeToolContentHandler; } @@ -759,6 +788,7 @@ // ToolContentManager, ToolSessionManager methods // ******************************************************************************* + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { CommonCartridge toolContentObj = commonCartridgeDao.getByContentId(toolContentId); if (toolContentObj == null) { @@ -785,18 +815,19 @@ } } + @Override public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion, String toVersion) throws ToolException { try { // register version filter class exportContentService.registerImportVersionFilterClass(CommonCartridgeImportContentVersionFilter.class); - + exportContentService.registerFileClassForImport(CommonCartridgeItem.class.getName(), "fileUuid", "fileVersionId", "fileName", "fileType", null, "initialItem"); - Object toolPOJO = exportContentService.importToolContent(toolContentPath, - commonCartridgeToolContentHandler, fromVersion, toVersion); + Object toolPOJO = exportContentService.importToolContent(toolContentPath, commonCartridgeToolContentHandler, + fromVersion, toVersion); if (!(toolPOJO instanceof CommonCartridge)) { throw new ImportToolContentException( "Import Share commonCartridge tool content failed. Deserialized object is " + toolPOJO); @@ -805,8 +836,8 @@ // reset it to new toolContentId toolContentObj.setContentId(toolContentId); - CommonCartridgeUser user = commonCartridgeUserDao.getUserByUserIDAndContentID( - new Long(newUserUid.longValue()), toolContentId); + CommonCartridgeUser user = commonCartridgeUserDao + .getUserByUserIDAndContentID(new Long(newUserUid.longValue()), toolContentId); if (user == null) { user = new CommonCartridgeUser(); UserDTO sysUser = ((User) userManagementService.findById(User.class, newUserUid)).getUserDTO(); @@ -829,10 +860,11 @@ } } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return null; } - + /** * 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 @@ -841,11 +873,13 @@ * * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition */ + @Override public SortedMap getToolOutputDefinitions(Long toolContentId, int definitionType) throws ToolException { return new TreeMap(); } + @Override public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { if (toContentId == null) { throw new ToolException("Failed to create the SharedCommonCartridgeFiles tool seession"); @@ -877,10 +911,11 @@ } } + @Override public String getToolContentTitle(Long toolContentId) { return getCommonCartridgeByContentId(toolContentId).getTitle(); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { CommonCartridge commonCartridge = commonCartridgeDao.getByContentId(toolContentId); @@ -889,37 +924,44 @@ } commonCartridge.setDefineLater(false); } - + @Override public boolean isContentEdited(Long toolContentId) { return getCommonCartridgeByContentId(toolContentId).isDefineLater(); } - + @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId) throws ToolException { CommonCartridge commonCartridge = commonCartridgeDao.getByContentId(toolContentId); - if (removeSessionData) { - List list = commonCartridgeSessionDao.getByContentId(toolContentId); - Iterator iter = list.iterator(); - while (iter.hasNext()) { - CommonCartridgeSession session = (CommonCartridgeSession) iter.next(); - commonCartridgeSessionDao.delete(session); + if (commonCartridge == null) { + CommonCartridgeServiceImpl.log + .warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (CommonCartridgeSession session : commonCartridgeSessionDao.getByContentId(toolContentId)) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, CommonCartridgeConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); } } + commonCartridgeDao.delete(commonCartridge); } - + @Override @SuppressWarnings("unchecked") public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (log.isDebugEnabled()) { - log.debug("Removing Common Cartridge content for user ID " + userId + " and toolContentId " + toolContentId); + if (CommonCartridgeServiceImpl.log.isDebugEnabled()) { + CommonCartridgeServiceImpl.log.debug( + "Removing Common Cartridge content for user ID " + userId + " and toolContentId " + toolContentId); } CommonCartridge cartridge = commonCartridgeDao.getByContentId(toolContentId); if (cartridge == null) { - log.warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); + CommonCartridgeServiceImpl.log + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } @@ -937,8 +979,8 @@ try { commonCartridgeToolContentHandler.deleteFile(item.getFileUuid()); } catch (Exception e) { - throw new ToolException( - "Error while removing Common Cartridge file UUID " + item.getFileUuid(), e); + throw new ToolException("Error while removing Common Cartridge file UUID " + item.getFileUuid(), + e); } } commonCartridgeItemDao.removeObject(CommonCartridgeItem.class, item.getUid()); @@ -998,13 +1040,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -1022,17 +1065,18 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return null; } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /* ===============Methods implemented from ToolContentImport102Manager =============== */ /** * Import the data for a 1.0.2 Noticeboard or HTMLNoticeboard */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { } @@ -1044,7 +1088,7 @@ // 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 ((instructionText != null) && (instructionText.length() > 255)) { if (CommonCartridgeServiceImpl.log.isDebugEnabled()) { CommonCartridgeServiceImpl.log .debug("1.0.2 Import truncating Item Instruction to 255 characters. Original text was\'" @@ -1061,8 +1105,9 @@ } /** 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { CommonCartridge toolContentObj = getCommonCartridgeByContentId(toolContentId); if (toolContentObj == null) { @@ -1100,6 +1145,7 @@ this.coreNotebookService = coreNotebookService; } + @Override public IEventNotificationService getEventNotificationService() { return eventNotificationService; } @@ -1108,6 +1154,7 @@ this.eventNotificationService = eventNotificationService; } + @Override public String getLocalisedMessage(String key, Object[] args) { return messageService.getMessage(key, args); } @@ -1127,6 +1174,7 @@ * tool session ID * @return list of teachers that monitor the lesson which contains the tool with given session ID */ + @Override public List getMonitorsByToolSessionId(Long sessionId) { return getLessonService().getMonitorsByToolSessionId(sessionId); } Index: lams_tool_kaltura/src/java/org/lamsfoundation/lams/tool/kaltura/service/KalturaService.java =================================================================== diff -u -ra207bdecc16a704428826dbf402a97de2e35458b -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_kaltura/src/java/org/lamsfoundation/lams/tool/kaltura/service/KalturaService.java (.../KalturaService.java) (revision a207bdecc16a704428826dbf402a97de2e35458b) +++ lams_tool_kaltura/src/java/org/lamsfoundation/lams/tool/kaltura/service/KalturaService.java (.../KalturaService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -50,7 +50,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.kaltura.dao.IKalturaCommentDAO; import org.lamsfoundation.lams.tool.kaltura.dao.IKalturaDAO; @@ -85,19 +84,19 @@ * As a requirement, all LAMS tool's service bean must implement ToolContentManager and ToolSessionManager. */ -public class KalturaService implements ToolSessionManager, ToolContentManager, IKalturaService, - ToolContentImport102Manager { +public class KalturaService + implements ToolSessionManager, ToolContentManager, IKalturaService, ToolContentImport102Manager { private static Logger logger = Logger.getLogger(KalturaService.class.getName()); private IKalturaDAO kalturaDao = null; - + private IKalturaItemDAO kalturaItemDao = null; - + private IKalturaItemVisitDAO kalturaItemVisitDao = null; - + private IKalturaCommentDAO kalturaCommentDao = null; - + private IKalturaRatingDAO kalturaRatingDao = null; private IKalturaSessionDAO kalturaSessionDao = null; @@ -107,9 +106,9 @@ private ILearnerService learnerService; private ILamsToolService toolService; - + private IUserManagementService userManagementService; - + private MessageService messageService; private IToolContentHandler kalturaToolContentHandler = null; @@ -129,8 +128,8 @@ /* ************ Methods from ToolSessionManager ************* */ @Override public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("entering method createToolSession:" + " toolSessionId = " + toolSessionId + if (KalturaService.logger.isDebugEnabled()) { + KalturaService.logger.debug("entering method createToolSession:" + " toolSessionId = " + toolSessionId + " toolSessionName = " + toolSessionName + " toolContentId = " + toolContentId); } @@ -149,13 +148,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -173,19 +173,19 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return getKalturaOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /* ************ Methods from ToolContentManager ************************* */ @Override public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("entering method copyToolContent:" + " fromContentId=" + fromContentId + if (KalturaService.logger.isDebugEnabled()) { + KalturaService.logger.debug("entering method copyToolContent:" + " fromContentId=" + fromContentId + " toContentId=" + toContentId); } @@ -214,14 +214,14 @@ } } } - + kalturaDao.saveOrUpdate(toContent); - for (KalturaItem item : (Set)items) { + for (KalturaItem item : (Set) items) { kalturaUserDao.saveOrUpdate(item.getCreatedBy()); kalturaItemDao.insert(item); } } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Kaltura kaltura = kalturaDao.getByContentId(toolContentId); @@ -232,17 +232,33 @@ kalturaDao.saveOrUpdate(kaltura); } + @SuppressWarnings("unchecked") @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId) throws ToolException { + Kaltura kaltura = kalturaDao.getByContentId(toolContentId); + if (kaltura == null) { + KalturaService.logger.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (KalturaSession session : (Set) kaltura.getKalturaSessions()) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, KalturaConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); + } + } + + kalturaDao.delete(kaltura); } - + + @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("This tool does not support learner content removing yet."); + if (KalturaService.logger.isDebugEnabled()) { + KalturaService.logger.debug("This tool does not support learner content removing yet."); } } - + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { Kaltura kaltura = kalturaDao.getByContentId(toolContentId); @@ -274,19 +290,18 @@ try { // register version filter class exportContentService.registerImportVersionFilterClass(KalturaImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, kalturaToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof Kaltura)) { - throw new ImportToolContentException("Import Kaltura tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import Kaltura tool content failed. Deserialized object is " + toolPOJO); } Kaltura kaltura = (Kaltura) toolPOJO; // reset it to new toolContentId kaltura.setToolContentId(toolContentId); - KalturaUser user = kalturaUserDao.getByUserIdAndContentId(new Long(newUserUid.longValue()), - toolContentId); + KalturaUser user = kalturaUserDao.getByUserIdAndContentId(new Long(newUserUid.longValue()), toolContentId); if (user == null) { user = new KalturaUser(); UserDTO sysUser = ((User) userManagementService.findById(User.class, newUserUid)).getUserDTO(); @@ -320,14 +335,16 @@ return getKalturaOutputFactory().getToolOutputDefinitions(kaltura, definitionType); } + @Override public String getToolContentTitle(Long toolContentId) { return getKalturaByContentId(toolContentId).getTitle(); } - + + @Override public boolean isContentEdited(Long toolContentId) { return getKalturaByContentId(toolContentId).isDefineLater(); } - + /* ********** IKalturaService Methods ********************************* */ @Override public Long createNotebookEntry(Long sessionId, Integer notebookToolType, String toolSignature, Integer userId, @@ -340,7 +357,7 @@ public NotebookEntry getEntry(Long sessionId, Integer userId) { List list = coreNotebookService.getEntry(sessionId, CoreNotebookConstants.NOTEBOOK_TOOL, KalturaConstants.TOOL_SIGNATURE, userId); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -351,7 +368,7 @@ public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } - + @Override public List getReflectList(Kaltura kaltura) { List reflectList = new LinkedList(); @@ -367,18 +384,18 @@ if (entry != null) { NotebookEntryDTO notebookEntryDTO = new NotebookEntryDTO(entry); notebookEntryDTO.setFullName(user.getFirstName() + " " + user.getLastName()); - Date postedDate = (entry.getLastModified() != null) ? entry.getLastModified() : entry - .getCreateDate(); + Date postedDate = (entry.getLastModified() != null) ? entry.getLastModified() + : entry.getCreateDate(); notebookEntryDTO.setLastModified(postedDate); reflectList.add(notebookEntryDTO); } - + } } return reflectList; } - + @Override public String finishToolSession(Long toolSessionId, Long userId) throws KalturaException { KalturaUser user = kalturaUserDao.getByUserIdAndSessionId(userId, toolSessionId); @@ -395,46 +412,46 @@ } return nextUrl; } - + @Override public AverageRatingDTO rateMessage(Long itemUid, Long userId, Long toolSessionId, float rating) { KalturaUser user = getUserByUserIdAndSessionId(userId, toolSessionId); KalturaRating itemRating = kalturaRatingDao.getKalturaRatingByItemAndUser(itemUid, userId); - KalturaItem item = getKalturaItem(itemUid); + KalturaItem item = getKalturaItem(itemUid); - //persist KalturaRating changes in DB + // persist KalturaRating changes in DB if (itemRating == null) { // add itemRating = new KalturaRating(); itemRating.setCreateBy(user); itemRating.setKalturaItem(item); } itemRating.setRating(rating); kalturaRatingDao.insertOrUpdate(itemRating); - - //to make available new changes be visible in jsp page + + // to make available new changes be visible in jsp page return kalturaRatingDao.getAverageRatingDtoByItem(itemUid, toolSessionId); } - + @Override public AverageRatingDTO getAverageRatingDto(Long itemUid, Long sessionId) { return kalturaRatingDao.getAverageRatingDtoByItem(itemUid, sessionId); } - + @Override public void deleteKalturaItem(Long uid) { kalturaItemDao.deleteById(KalturaItem.class, uid); } - + @Override public KalturaItem getKalturaItem(Long itemUid) { return kalturaItemDao.getByUid(itemUid); } - + @Override public void saveKalturaItem(KalturaItem item) { kalturaItemDao.insertOrUpdate(item); } - + @Override public Set getGroupItems(Long toolContentId, Long toolSessionId, Long useId, boolean isMonitoring) { TreeSet groupItems = new TreeSet(new KalturaItemComparator()); @@ -443,25 +460,26 @@ Set allItems = kaltura.getKalturaItems(); for (KalturaItem item : allItems) { - //hide hidden items from learner and ignore this parameter for teacher - boolean isHidden = isMonitoring || !isMonitoring && !item.isHidden(); - - //remove hidden - if (isHidden && - //show authored items - (item.isCreateByAuthor() - //user should see his own items - || item.getCreatedBy().getUserId().equals(useId) - //filter items from other groups - || item.getCreatedBy().getSession().getSessionId().equals(toolSessionId) && (kaltura.isAllowSeeingOtherUsersRecordings() || isMonitoring) )) { - + // hide hidden items from learner and ignore this parameter for teacher + boolean isHidden = isMonitoring || (!isMonitoring && !item.isHidden()); + + // remove hidden + if (isHidden && + // show authored items + (item.isCreateByAuthor() + // user should see his own items + || item.getCreatedBy().getUserId().equals(useId) + // filter items from other groups + || (item.getCreatedBy().getSession().getSessionId().equals(toolSessionId) + && (kaltura.isAllowSeeingOtherUsersRecordings() || isMonitoring)))) { + groupItems.add(item); } } return groupItems; } - + @Override public void logItemWatched(Long itemUid, Long userId, Long toolSessionId) { KalturaItemVisitLog log = kalturaItemVisitDao.getKalturaItemLog(itemUid, userId); @@ -477,14 +495,14 @@ kalturaItemVisitDao.insert(log); } } - + @Override public void markItem(Long itemUid, Long mark) { KalturaItem item = kalturaItemDao.getByUid(itemUid); item.setMark(mark); kalturaItemDao.update(item); } - + @Override public void hideItem(Long itemUid, boolean isHiding) { KalturaItem item = kalturaItemDao.getByUid(itemUid); @@ -493,7 +511,7 @@ kalturaItemDao.update(item); } } - + @Override public void hideComment(Long commentUid, boolean isHiding) { KalturaComment comment = kalturaCommentDao.getCommentByUid(commentUid); @@ -502,12 +520,12 @@ kalturaCommentDao.update(comment); } } - + @Override public int getNumberViewedVideos(Long toolSessionId, Long userId) { return kalturaItemVisitDao.getUserViewLogCount(toolSessionId, userId); } - + @Override public int getNumberUploadedVideos(Long toolSessionId, Long userId) { return kalturaItemDao.getItemsCountByUser(toolSessionId, userId); @@ -519,7 +537,7 @@ toolContentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature)); if (toolContentId == null) { String error = "Could not retrieve default content id for this tool"; - logger.error(error); + KalturaService.logger.error(error); throw new KalturaException(error); } return toolContentId; @@ -531,7 +549,7 @@ Kaltura defaultContent = getKalturaByContentId(defaultContentID); if (defaultContent == null) { String error = "Could not retrieve default content record for this tool"; - logger.error(error); + KalturaService.logger.error(error); throw new KalturaException(error); } return defaultContent; @@ -542,7 +560,7 @@ if (newContentID == null) { String error = "Cannot copy the Kaltura tools default content: + " + "newContentID is null"; - logger.error(error); + KalturaService.logger.error(error); throw new KalturaException(error); } @@ -558,7 +576,7 @@ public Kaltura getKalturaByContentId(Long toolContentID) { Kaltura kaltura = kalturaDao.getByContentId(toolContentID); if (kaltura == null) { - logger.debug("Could not find the content with toolContentID:" + toolContentID); + KalturaService.logger.debug("Could not find the content with toolContentID:" + toolContentID); } return kaltura; } @@ -567,7 +585,7 @@ public KalturaSession getSessionBySessionId(Long toolSessionId) { KalturaSession kalturaSession = kalturaSessionDao.getBySessionId(toolSessionId); if (kalturaSession == null) { - logger.debug("Could not find the kaltura session with toolSessionID:" + toolSessionId); + KalturaService.logger.debug("Could not find the kaltura session with toolSessionID:" + toolSessionId); } return kalturaSession; } @@ -581,7 +599,7 @@ public KalturaUser getUserByUid(Long uid) { return kalturaUserDao.getByUid(uid); } - + @Override public KalturaUser getUserByUserIdAndContentId(Long userId, Long contentId) { return kalturaUserDao.getByUserIdAndContentId(userId, contentId); @@ -616,7 +634,7 @@ public void setAuditService(IAuditService auditService) { this.auditService = auditService; } - + @Override public String getLocalisedMessage(String key, Object[] args) { return messageService.getMessage(key, args); @@ -627,14 +645,16 @@ /** * Import the data for a 1.0.2 Kaltura */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { } @Override - public void setReflectiveData(Long toolContentId, String title, String description) throws ToolException, - DataMissingException { + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { - logger.warn("Setting the reflective field on a kaltura. This doesn't make sense as the kaltura is for reflection and we don't reflect on reflection!"); + KalturaService.logger.warn( + "Setting the reflective field on a kaltura. This doesn't make sense as the kaltura is for reflection and we don't reflect on reflection!"); Kaltura kaltura = getKalturaByContentId(toolContentId); if (kaltura == null) { throw new DataMissingException("Unable to set reflective data titled " + title @@ -650,19 +670,19 @@ public void setKalturaDao(IKalturaDAO kalturaDAO) { this.kalturaDao = kalturaDAO; } - + public void setKalturaItemDao(IKalturaItemDAO kalturaItemDAO) { this.kalturaItemDao = kalturaItemDAO; } - + public void setKalturaItemVisitDao(IKalturaItemVisitDAO kalturaItemVisitDAO) { this.kalturaItemVisitDao = kalturaItemVisitDAO; } - + public void setKalturaCommentDao(IKalturaCommentDAO kalturaCommentDAO) { this.kalturaCommentDao = kalturaCommentDAO; } - + public void setKalturaRatingDao(IKalturaRatingDAO kalturaRatingDAO) { this.kalturaRatingDao = kalturaRatingDAO; } @@ -694,7 +714,7 @@ public void setExportContentService(IExportToolContentService exportContentService) { this.exportContentService = exportContentService; } - + public void setUserManagementService(IUserManagementService userManagementService) { this.userManagementService = userManagementService; } @@ -710,15 +730,17 @@ public void setKalturaOutputFactory(KalturaOutputFactory kalturaOutputFactory) { this.kalturaOutputFactory = kalturaOutputFactory; } - + public void setMessageService(MessageService messageService) { this.messageService = messageService; } + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getKalturaOutputFactory().getSupportedDefinitionClasses(definitionType); } Index: lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/IMcService.java =================================================================== diff -u -r4d139bddc3cdd41d32d9f3033f2100c711d8c0c5 -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/IMcService.java (.../IMcService.java) (revision 4d139bddc3cdd41d32d9f3033f2100c711d8c0c5) +++ lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/IMcService.java (.../IMcService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -128,9 +128,6 @@ void copyToolContent(Long fromContentId, Long toContentId) throws ToolException; - void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException; - boolean existsSession(Long toolSessionId); void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException; Index: lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/McServicePOJO.java =================================================================== diff -u -re08b873af178aec14f4a58df17f0f34a47931069 -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/McServicePOJO.java (.../McServicePOJO.java) (revision e08b873af178aec14f4a58df17f0f34a47931069) +++ lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/McServicePOJO.java (.../McServicePOJO.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -74,7 +74,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.mc.McAppConstants; import org.lamsfoundation.lams.tool.mc.McApplicationException; @@ -120,8 +119,8 @@ * * @author Ozgur Demirtas */ -public class McServicePOJO implements IMcService, ToolContentManager, ToolSessionManager, ToolContentImport102Manager, ToolRestManager, - McAppConstants { +public class McServicePOJO implements IMcService, ToolContentManager, ToolSessionManager, ToolContentImport102Manager, + ToolRestManager, McAppConstants { private static Logger logger = Logger.getLogger(McServicePOJO.class.getName()); private IMcContentDAO mcContentDAO; @@ -146,10 +145,10 @@ public McServicePOJO() { } - + @Override public McQueUsr checkLeaderSelectToolForSessionLeader(McQueUsr user, Long toolSessionId) { - if (user == null || toolSessionId == null) { + if ((user == null) || (toolSessionId == null)) { return null; } @@ -161,12 +160,12 @@ Long leaderUserId = toolService.getLeaderUserId(toolSessionId, user.getQueUsrId().intValue()); if (leaderUserId != null) { - + leader = getMcUserBySession(leaderUserId, mcSession.getUid()); // create new user in a DB if (leader == null) { - logger.debug("creating new user with userId: " + leaderUserId); + McServicePOJO.logger.debug("creating new user with userId: " + leaderUserId); User leaderDto = (User) getUserManagementService().findById(User.class, leaderUserId.intValue()); String userName = leaderDto.getLogin(); String fullName = leaderDto.getFirstName() + " " + leaderDto.getLastName(); @@ -182,7 +181,7 @@ return leader; } - + @Override public void copyAnswersFromLeader(McQueUsr user, McQueUsr leader) { @@ -192,7 +191,7 @@ List leaderAttempts = this.getFinalizedUserAttempts(leader); for (McUsrAttempt leaderAttempt : leaderAttempts) { - + McQueContent question = leaderAttempt.getMcQueContent(); McUsrAttempt userAttempt = mcUsrAttemptDAO.getUserAttemptByQuestion(user.getUid(), question.getUid()); @@ -203,7 +202,7 @@ leaderAttempt.isAttemptCorrect()); mcUsrAttemptDAO.saveMcUsrAttempt(userAttempt); - // if it's been changed by the leader + // if it's been changed by the leader } else if (leaderAttempt.getAttemptTime().compareTo(userAttempt.getAttemptTime()) != 0) { userAttempt.setMcOptionsContent(leaderAttempt.getMcOptionsContent()); userAttempt.setAttemptTime(leaderAttempt.getAttemptTime()); @@ -221,7 +220,8 @@ try { mcContentDAO.saveMcContent(mcContent); } catch (DataAccessException e) { - throw new McApplicationException("Exception occured when lams is creating mc content: " + e.getMessage(), e); + throw new McApplicationException("Exception occured when lams is creating mc content: " + e.getMessage(), + e); } } @@ -233,7 +233,7 @@ throw new McApplicationException("Exception occured when lams is loading mc content: " + e.getMessage(), e); } } - + @Override public void setDefineLater(String strToolContentID, boolean value) { @@ -249,8 +249,8 @@ try { mcQueContentDAO.updateMcQueContent(mcQueContent); } catch (DataAccessException e) { - throw new McApplicationException("Exception occured when lams is updating mc que content: " - + e.getMessage(), e); + throw new McApplicationException( + "Exception occured when lams is updating mc que content: " + e.getMessage(), e); } } @@ -261,8 +261,8 @@ try { return mcQueContentDAO.getQuestionContentByDisplayOrder(displayOrder, mcContentUid); } catch (DataAccessException e) { - throw new McApplicationException("Exception occured when lams is getting mc que content by display order: " - + e.getMessage(), e); + throw new McApplicationException( + "Exception occured when lams is getting mc que content by display order: " + e.getMessage(), e); } } @@ -271,8 +271,8 @@ try { return mcQueContentDAO.getAllQuestionEntriesSorted(mcContentId); } catch (DataAccessException e) { - throw new McApplicationException("Exception occured when lams is getting all question entries: " - + e.getMessage(), e); + throw new McApplicationException( + "Exception occured when lams is getting all question entries: " + e.getMessage(), e); } } @@ -281,11 +281,11 @@ try { mcQueContentDAO.saveOrUpdateMcQueContent(mcQueContent); } catch (DataAccessException e) { - throw new McApplicationException("Exception occured when lams is updating mc que content: " - + e.getMessage(), e); + throw new McApplicationException( + "Exception occured when lams is updating mc que content: " + e.getMessage(), e); } } - + @Override public McContent createQuestions(List questionDTOs, McContent content) { @@ -336,15 +336,15 @@ Long optionUid = optionDTO.getUid(); String optionText = optionDTO.getCandidateAnswer(); boolean isCorrectOption = "Correct".equals(optionDTO.getCorrect()); - - //find persisted option if it exists + + // find persisted option if it exists McOptsContent option = new McOptsContent(); - for (McOptsContent oldOption: oldOptions) { + for (McOptsContent oldOption : oldOptions) { if (oldOption.getUid().equals(optionUid)) { option = oldOption; } } - + option.setDisplayOrder(displayOrderOption); option.setCorrectOption(isCorrectOption); option.setMcQueOptionText(optionText); @@ -353,7 +353,7 @@ newOptions.add(option); displayOrderOption++; } - + question.setMcOptionsContents(newOptions); // updating the existing question content @@ -362,14 +362,14 @@ } return content; } - + @Override public void releaseQuestionsFromCache(McContent content) { - for (McQueContent question : (Set)content.getMcQueContents()) { + for (McQueContent question : (Set) content.getMcQueContents()) { mcQueContentDAO.releaseQuestionFromCache(question); } } - + @Override public McQueUsr createMcUser(Long toolSessionID) throws McApplicationException { try { @@ -382,7 +382,7 @@ McQueUsr user = new McQueUsr(userId, userName, fullName, mcSession, new TreeSet()); mcUserDAO.saveMcUser(user); - + return user; } catch (DataAccessException e) { throw new McApplicationException("Exception occured when lams is creating mc QueUsr: " + e.getMessage(), e); @@ -412,8 +412,8 @@ try { return mcUserDAO.getMcUserByUID(uid); } catch (DataAccessException e) { - throw new McApplicationException("Exception occured when lams is getting the mc QueUsr by uid." - + e.getMessage(), e); + throw new McApplicationException( + "Exception occured when lams is getting the mc QueUsr by uid." + e.getMessage(), e); } } @@ -427,12 +427,13 @@ Long questionUid = mcLearnerAnswersDTO.getQuestionUid(); McQueContent question = this.getQuestionByUid(questionUid); if (question == null) { - throw new McApplicationException("Can't find question with specified question uid: " + mcLearnerAnswersDTO.getQuestionUid()); + throw new McApplicationException( + "Can't find question with specified question uid: " + mcLearnerAnswersDTO.getQuestionUid()); } McOptsContent answerOption = mcLearnerAnswersDTO.getAnswerOption(); if (answerOption != null) { - + Integer mark = mcLearnerAnswersDTO.getMark(); boolean passed = user.isMarkPassed(mark); boolean isAttemptCorrect = new Boolean(mcLearnerAnswersDTO.getAttemptCorrect()); @@ -457,7 +458,8 @@ } else { // create new userAttempt - userAttempt = new McUsrAttempt(attemptTime, question, user, answerOption, mark, passed, isAttemptCorrect); + userAttempt = new McUsrAttempt(attemptTime, question, user, answerOption, mark, passed, + isAttemptCorrect); } @@ -472,11 +474,11 @@ try { mcUsrAttemptDAO.updateMcUsrAttempt(mcUsrAttempt); } catch (DataAccessException e) { - throw new McApplicationException( - "Exception occured when lams is updating mc UsrAttempt: " + e.getMessage(), e); + throw new McApplicationException("Exception occured when lams is updating mc UsrAttempt: " + e.getMessage(), + e); } } - + @Override public List buildLearnerAnswersDTOList(McContent mcContent, McQueUsr user) { List learnerAnswersDTOList = new LinkedList(); @@ -486,7 +488,7 @@ McLearnerAnswersDTO learnerAnswersDTO = new McLearnerAnswersDTO(); Set optionSet = question.getMcOptionsContents(); List optionList = new LinkedList(optionSet); - + boolean randomize = mcContent.isRandomize(); if (randomize) { ArrayList shuffledList = new ArrayList(optionList); @@ -503,18 +505,18 @@ learnerAnswersDTOList.add(learnerAnswersDTO); } - - //populate answers + + // populate answers if (user != null) { for (McLearnerAnswersDTO learnerAnswersDTO : learnerAnswersDTOList) { Long questionUid = learnerAnswersDTO.getQuestionUid(); - + McUsrAttempt dbAttempt = this.getUserAttemptByQuestion(user.getUid(), questionUid); if (dbAttempt != null) { Long selectedOptionUid = dbAttempt.getMcOptionsContent().getUid(); - - //mark selected option as selected + + // mark selected option as selected for (McOptsContent option : learnerAnswersDTO.getOptions()) { if (selectedOptionUid.equals(option.getUid())) { option.setSelected(true); @@ -526,7 +528,7 @@ return learnerAnswersDTOList; } - + @Override public List buildGroupsMarkData(McContent mcContent, boolean isFullAttemptDetailsRequired) { List listMonitoredMarksContainerDTO = new LinkedList(); @@ -543,7 +545,8 @@ Set sessionUsers = session.getMcQueUsers(); Iterator usersIterator = sessionUsers.iterator(); - Map mapSessionUsersData = new TreeMap(new McStringComparator()); + Map mapSessionUsersData = new TreeMap( + new McStringComparator()); Long mapIndex = new Long(1); while (usersIterator.hasNext()) { @@ -575,8 +578,8 @@ long totalMark = 0; for (McUsrAttempt attempt : finalizedUserAttempts) { Integer displayOrder = attempt.getMcQueContent().getDisplayOrder(); - int arrayIndex = displayOrder != null && displayOrder.intValue() > 0 ? displayOrder.intValue() - 1 - : 1; + int arrayIndex = (displayOrder != null) && (displayOrder.intValue() > 0) + ? displayOrder.intValue() - 1 : 1; if (userMarks[arrayIndex] == null) { // We get the mark for the attempt if the answer is correct and we don't allow @@ -593,7 +596,7 @@ for (McOptsContent option : (Set) attempt.getMcQueContent() .getMcOptionsContents()) { if (attempt.getMcOptionsContent().getUid().equals(option.getUid())) { - answeredOptionLetter = String.valueOf((char) (optionCount + 'A' - 1)); + answeredOptionLetter = String.valueOf((char) ((optionCount + 'A') - 1)); break; } optionCount++; @@ -633,19 +636,20 @@ } catch (DataAccessException e) { throw new McApplicationException( "Exception occured when lams is getting the learner's attempts by user id and que content id and attempt order: " - + e.getMessage(), e); + + e.getMessage(), + e); } } @Override - public McUsrAttempt getUserAttemptByQuestion(Long queUsrUid, Long mcQueContentId) - throws McApplicationException { + public McUsrAttempt getUserAttemptByQuestion(Long queUsrUid, Long mcQueContentId) throws McApplicationException { try { return mcUsrAttemptDAO.getUserAttemptByQuestion(queUsrUid, mcQueContentId); } catch (DataAccessException e) { throw new McApplicationException( "Exception occured when lams is getting the learner's attempts by user id and que content id and attempt order: " - + e.getMessage(), e); + + e.getMessage(), + e); } } @@ -654,8 +658,8 @@ try { return mcQueContentDAO.getQuestionsByContentUid(contentUid.longValue()); } catch (DataAccessException e) { - throw new McApplicationException("Exception occured when lams is getting by uid mc question content: " - + e.getMessage(), e); + throw new McApplicationException( + "Exception occured when lams is getting by uid mc question content: " + e.getMessage(), e); } } @@ -664,8 +668,8 @@ try { return mcQueContentDAO.refreshQuestionContent(mcContentId); } catch (DataAccessException e) { - throw new McApplicationException("Exception occured when lams is refreshing mc question content: " - + e.getMessage(), e); + throw new McApplicationException( + "Exception occured when lams is refreshing mc question content: " + e.getMessage(), e); } } @@ -675,8 +679,8 @@ try { mcQueContentDAO.removeMcQueContent(mcQueContent); } catch (DataAccessException e) { - throw new McApplicationException("Exception occured when lams is removing mc question content: " - + e.getMessage(), e); + throw new McApplicationException( + "Exception occured when lams is removing mc question content: " + e.getMessage(), e); } } @@ -685,8 +689,8 @@ try { return mcOptionsContentDAO.getOptionDtos(mcQueContentId); } catch (DataAccessException e) { - throw new McApplicationException("Exception occured when lams is populating candidate answers dto" - + e.getMessage(), e); + throw new McApplicationException( + "Exception occured when lams is populating candidate answers dto" + e.getMessage(), e); } } @@ -695,8 +699,8 @@ try { return mcSessionDAO.getMcSessionById(mcSessionId); } catch (DataAccessException e) { - throw new McApplicationException("Exception occured when lams is retrieving by id mc session : " - + e.getMessage(), e); + throw new McApplicationException( + "Exception occured when lams is retrieving by id mc session : " + e.getMessage(), e); } } @@ -705,8 +709,8 @@ try { mcContentDAO.updateMcContent(mc); } catch (DataAccessException e) { - throw new McApplicationException("Exception occured when lams is updating" + " the mc content: " - + e.getMessage(), e); + throw new McApplicationException( + "Exception occured when lams is updating" + " the mc content: " + e.getMessage(), e); } } @@ -720,8 +724,8 @@ try { return mcOptionsContentDAO.findMcOptionsContentByQueId(mcQueContentId); } catch (DataAccessException e) { - throw new McApplicationException("Exception occured when lams is finding by que id" + " the mc options: " - + e.getMessage(), e); + throw new McApplicationException( + "Exception occured when lams is finding by que id" + " the mc options: " + e.getMessage(), e); } } @@ -730,7 +734,7 @@ if (uid == null) { return null; } - + return mcQueContentDAO.findMcQuestionContentByUid(uid); } @@ -739,63 +743,63 @@ try { mcOptionsContentDAO.updateMcOptionsContent(mcOptsContent); } catch (DataAccessException e) { - throw new McApplicationException("Exception occured when lams is updating" + " the mc options content: " - + e.getMessage(), e); + throw new McApplicationException( + "Exception occured when lams is updating" + " the mc options content: " + e.getMessage(), e); } } - + @Override public void changeUserAttemptMark(Long userAttemptUid, Integer newMark) { if (newMark == null) { return; } - + McUsrAttempt userAttempt = mcUsrAttemptDAO.getUserAttemptByUid(userAttemptUid); Integer userId = userAttempt.getMcQueUsr().getQueUsrId().intValue(); Long userUid = userAttempt.getMcQueUsr().getUid(); - Long toolSessionId = userAttempt.getMcQueUsr().getMcSession().getMcSessionId(); + Long toolSessionId = userAttempt.getMcQueUsr().getMcSession().getMcSessionId(); Integer oldMark = userAttempt.getMark(); int oldTotalMark = mcUsrAttemptDAO.getUserTotalMark(userUid); - + userAttempt.setMark(newMark); mcUsrAttemptDAO.saveMcUsrAttempt(userAttempt); // propagade changes to Gradebook - int totalMark = (oldMark == null) ? oldTotalMark + newMark : oldTotalMark - oldMark + newMark; + int totalMark = (oldMark == null) ? oldTotalMark + newMark : (oldTotalMark - oldMark) + newMark; gradebookService.updateActivityMark(new Double(totalMark), null, userId, toolSessionId, false); - - //record mark change with audit service - auditService.logMarkChange(McAppConstants.MY_SIGNATURE, userAttempt.getMcQueUsr().getQueUsrId(), userAttempt - .getMcQueUsr().getUsername(), "" + oldMark, "" + totalMark); + // record mark change with audit service + auditService.logMarkChange(McAppConstants.MY_SIGNATURE, userAttempt.getMcQueUsr().getQueUsrId(), + userAttempt.getMcQueUsr().getUsername(), "" + oldMark, "" + totalMark); + } - + @Override public void recalculateUserAnswers(McContent content, Set oldQuestions, List questionDTOs, List deletedQuestions) { - //create list of modified questions + // create list of modified questions List modifiedQuestions = new ArrayList(); - //create list of modified question marks - List modifiedQuestionsMarksOnly= new ArrayList(); + // create list of modified question marks + List modifiedQuestionsMarksOnly = new ArrayList(); for (McQueContent oldQuestion : oldQuestions) { for (McQuestionDTO questionDTO : questionDTOs) { if (oldQuestion.getUid().equals(questionDTO.getUid())) { - + boolean isQuestionModified = false; boolean isQuestionMarkModified = false; - //question is different + // question is different if (!oldQuestion.getQuestion().equals(questionDTO.getQuestion())) { isQuestionModified = true; } - - //mark is different + + // mark is different if (oldQuestion.getMark().intValue() != (new Integer(questionDTO.getMark())).intValue()) { isQuestionMarkModified = true; } - - //options are different + + // options are different Set oldOptions = oldQuestion.getMcOptionsContents(); List optionDTOs = questionDTO.getListCandidateAnswersDTO(); for (McOptsContent oldOption : oldOptions) { @@ -809,28 +813,28 @@ } } } - + if (isQuestionModified) { modifiedQuestions.add(questionDTO); - + } else if (isQuestionMarkModified) { modifiedQuestionsMarksOnly.add(questionDTO); } } - } + } } - + Set sessionList = content.getMcSessions(); for (McSession session : sessionList) { Long toolSessionId = session.getMcSessionId(); Set sessionUsers = session.getMcQueUsers(); - + for (McQueUsr user : sessionUsers) { - + final int oldTotalMark = mcUsrAttemptDAO.getUserTotalMark(user.getUid()); int newTotalMark = oldTotalMark; - - //get all finished user results + + // get all finished user results List userAttempts = getFinalizedUserAttempts(user); Iterator iter = userAttempts.iterator(); while (iter.hasNext()) { @@ -839,20 +843,20 @@ McQueContent question = userAttempt.getMcQueContent(); boolean isRemoveQuestionResult = false; - + // [+] if the question mark is modified for (McQuestionDTO modifiedQuestion : modifiedQuestionsMarksOnly) { if (question.getUid().equals(modifiedQuestion.getUid())) { Integer newQuestionMark = new Integer(modifiedQuestion.getMark()); Integer oldQuestionMark = question.getMark(); - Integer newActualMark = userAttempt.getMark() * newQuestionMark / oldQuestionMark; + Integer newActualMark = (userAttempt.getMark() * newQuestionMark) / oldQuestionMark; newTotalMark += newActualMark - userAttempt.getMark(); - + // update question answer's mark userAttempt.setMark(newActualMark); mcUsrAttemptDAO.saveMcUsrAttempt(userAttempt); - + break; } @@ -875,7 +879,7 @@ } if (isRemoveQuestionResult) { - + Integer oldMark = userAttempt.getMark(); if (oldMark != null) { newTotalMark -= oldMark; @@ -887,7 +891,6 @@ // [+] doing nothing if the new question was added - } // propagade new total mark to Gradebook if it was changed @@ -898,28 +901,27 @@ } } - } - + @Override public byte[] prepareSessionDataSpreadsheet(McContent mcContent) throws IOException { - + Set questions = mcContent.getMcQueContents(); int maxOptionsInQuestion = 0; for (McQueContent question : questions) { if (question.getMcOptionsContents().size() > maxOptionsInQuestion) { maxOptionsInQuestion = question.getMcOptionsContents().size(); } } - + int totalNumberOfUsers = 0; for (McSession session : (Set) mcContent.getMcSessions()) { totalNumberOfUsers += session.getMcQueUsers().size(); } - + List sessionMarkDTOs = this.buildGroupsMarkData(mcContent, true); - + // create an empty excel file HSSFWorkbook wb = new HSSFWorkbook(); HSSFCellStyle greenColor = wb.createCellStyle(); @@ -929,27 +931,27 @@ whiteFont.setColor(IndexedColors.WHITE.getIndex()); whiteFont.setFontName(ExcelUtil.DEFAULT_FONT_NAME); greenColor.setFont(whiteFont); - + // ======================================================= Report by question IRA page // ======================================= - + HSSFSheet sheet = wb.createSheet(messageService.getMessage("label.report.by.question")); HSSFRow row; HSSFCell cell; int rowCount = 0; - + row = sheet.createRow(rowCount++); int count = 0; cell = row.createCell(count++); cell.setCellValue(messageService.getMessage("label.question")); for (int optionCount = 0; optionCount < maxOptionsInQuestion; optionCount++) { cell = row.createCell(count++); - cell.setCellValue(String.valueOf((char)(optionCount + 'A'))); + cell.setCellValue(String.valueOf((char) (optionCount + 'A'))); } cell = row.createCell(count++); cell.setCellValue(messageService.getMessage("label.not.available")); - + for (McQueContent question : questions) { row = sheet.createRow(rowCount); @@ -963,17 +965,17 @@ for (McOptsContent option : (Set) question.getMcOptionsContents()) { int optionAttemptCount = mcUsrAttemptDAO.getAttemptsCountPerOption(option.getUid()); cell = row.createCell(count++); - int percentage = optionAttemptCount * 100 / totalNumberOfUsers; + int percentage = (optionAttemptCount * 100) / totalNumberOfUsers; cell.setCellValue(percentage + "%"); totalPercentage += percentage; if (option.isCorrectOption()) { cell.setCellStyle(greenColor); } } cell = row.createCell(maxOptionsInQuestion + 1); - cell.setCellValue(100 - totalPercentage + "%"); + cell.setCellValue((100 - totalPercentage) + "%"); } - + rowCount++; row = sheet.createRow(rowCount++); cell = row.createCell(0); @@ -986,13 +988,13 @@ cell.setCellStyle(greenColor); cell = row.createCell(2); cell.setCellStyle(greenColor); - + // ======================================================= Report by student IRA page // ======================================= - + sheet = wb.createSheet(messageService.getMessage("label.report.by.student")); rowCount = 0; - + row = sheet.createRow(rowCount++); count = 2; for (int questionCount = 1; questionCount <= questions.size(); questionCount++) { @@ -1016,7 +1018,7 @@ int answerCount = 1; for (McOptsContent option : (Set) question.getMcOptionsContents()) { if (option.isCorrectOption()) { - correctAnswerLetter = String.valueOf((char) (answerCount + 'A' - 1)); + correctAnswerLetter = String.valueOf((char) ((answerCount + 'A') - 1)); break; } answerCount++; @@ -1025,14 +1027,14 @@ cell.setCellValue(correctAnswerLetter); correctAnswers.add(correctAnswerLetter); } - + row = sheet.createRow(rowCount++); count = 0; cell = row.createCell(count++); cell.setCellValue(messageService.getMessage("group.label")); cell = row.createCell(count++); cell.setCellValue(messageService.getMessage("label.learner")); - + ArrayList totalPercentList = new ArrayList(); int[] numberOfCorrectAnswersPerQuestion = new int[questions.size()]; for (McSessionMarkDTO sessionMarkDTO : sessionMarkDTOs) { @@ -1043,10 +1045,10 @@ count = 0; cell = row.createCell(count++); cell.setCellValue(sessionMarkDTO.getSessionName()); - + cell = row.createCell(count++); cell.setCellValue(userMark.getFullName()); - + String[] answeredOptions = userMark.getAnsweredOptions(); int numberOfCorrectlyAnsweredByUser = 0; for (int i = 0; i < answeredOptions.length; i++) { @@ -1056,33 +1058,33 @@ if (StringUtils.equals(answeredOption, correctAnswers.get(i))) { cell.setCellStyle(greenColor); numberOfCorrectlyAnsweredByUser++; - numberOfCorrectAnswersPerQuestion[count-3]++; + numberOfCorrectAnswersPerQuestion[count - 3]++; } } - + cell = row.createCell(count++); cell.setCellValue(new Long(userMark.getTotalMark())); - int totalPercents = numberOfCorrectlyAnsweredByUser * 100 / questions.size(); + int totalPercents = (numberOfCorrectlyAnsweredByUser * 100) / questions.size(); totalPercentList.add(totalPercents); cell = row.createCell(count++); cell.setCellValue(totalPercents + "%"); } - + rowCount++; } - - //ave + + // ave row = sheet.createRow(rowCount++); count = 1; cell = row.createCell(count++); cell.setCellValue(messageService.getMessage("label.ave")); for (int numberOfCorrectAnswers : numberOfCorrectAnswersPerQuestion) { cell = row.createCell(count++); - cell.setCellValue(numberOfCorrectAnswers * 100 / totalPercentList.size() + "%"); + cell.setCellValue(((numberOfCorrectAnswers * 100) / totalPercentList.size()) + "%"); } - //class mean + // class mean Integer[] totalPercents = totalPercentList.toArray(new Integer[0]); Arrays.sort(totalPercents); int sum = 0; @@ -1097,15 +1099,15 @@ cell = row.createCell(questions.size() + 3); cell.setCellValue(classMean + "%"); } - + // median row = sheet.createRow(rowCount++); cell = row.createCell(1); cell.setCellValue(messageService.getMessage("label.median")); if (totalPercents.length != 0) { int median; int middle = totalPercents.length / 2; - if (totalPercents.length % 2 == 1) { + if ((totalPercents.length % 2) == 1) { median = totalPercents[middle]; } else { median = (int) ((totalPercents[middle - 1] + totalPercents[middle]) / 2.0); @@ -1126,22 +1128,22 @@ cell.setCellStyle(greenColor); cell = row.createCell(2); cell.setCellStyle(greenColor); - + // ======================================================= Marks page // ======================================= - + sheet = wb.createSheet("Marks"); rowCount = 0; count = 0; - + row = sheet.createRow(rowCount++); for (McQueContent question : questions) { cell = row.createCell(2 + count++); cell.setCellValue(messageService.getMessage("label.monitoring.downloadMarks.question.mark", new Object[] { count, question.getMark() })); } - + for (McSessionMarkDTO sessionMarkDTO : sessionMarkDTOs) { Map usersMarksMap = sessionMarkDTO.getUserMarks(); @@ -1234,40 +1236,26 @@ } } + @SuppressWarnings("unchecked") @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { - - if (toolContentId == null) { - McServicePOJO.logger.error("toolContentId is null"); - throw new ToolException("toolContentId is missing"); + public void removeToolContent(Long toolContentId) throws ToolException { + McContent mcContent = mcContentDAO.findMcContentById(toolContentId); + if (mcContent == null) { + McServicePOJO.logger.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; } - McContent mcContent = mcContentDAO.findMcContentById(toolContentId); - - if (mcContent != null) { - Iterator sessionIterator = mcContent.getMcSessions().iterator(); - while (sessionIterator.hasNext()) { - if (removeSessionData == false) { - throw new SessionDataExistsException(); - } - - McSession mcSession = (McSession) sessionIterator.next(); - - Iterator sessionUsersIterator = mcSession.getMcQueUsers().iterator(); - while (sessionUsersIterator.hasNext()) { - McQueUsr mcQueUsr = (McQueUsr) sessionUsersIterator.next(); - - mcUsrAttemptDAO.removeAllUserAttempts(mcQueUsr.getUid()); - } + for (McSession session : (Set) mcContent.getMcSessions()) { + List entries = coreNotebookService.getEntry(session.getMcSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, McAppConstants.MY_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); } - mcContentDAO.removeMcById(toolContentId); - } else { - McServicePOJO.logger.error("Warning!!!, We should have not come here. mcContent is null."); - throw new ToolException("toolContentId is missing"); } + + mcContentDAO.delete(mcContent); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { McContent mcContent = getMcContent(toolContentId); @@ -1276,14 +1264,14 @@ } mcContent.setDefineLater(false); mcContentDAO.saveMcContent(mcContent); - } + } @Override @SuppressWarnings("unchecked") public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("Removing Multiple Choice attempts for user ID " + userId + " and toolContentId " - + toolContentId); + if (McServicePOJO.logger.isDebugEnabled()) { + McServicePOJO.logger.debug( + "Removing Multiple Choice attempts for user ID " + userId + " and toolContentId " + toolContentId); } McContent content = mcContentDAO.findMcContentById(toolContentId); @@ -1299,7 +1287,7 @@ mcContentDAO.delete(entry); } - if (session.getGroupLeader() != null && session.getGroupLeader().getUid().equals(user.getUid())) { + if ((session.getGroupLeader() != null) && session.getGroupLeader().getUid().equals(user.getUid())) { session.setGroupLeader(null); } @@ -1310,7 +1298,7 @@ } } } - + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { McContent toolContentObj = mcContentDAO.findMcContentById(toolContentId); @@ -1339,11 +1327,11 @@ // register version filter class exportContentService.registerImportVersionFilterClass(McImportContentVersionFilter.class); - Object toolPOJO = exportContentService.importToolContent(toolContentPath, mcToolContentHandler, - fromVersion, toVersion); + Object toolPOJO = exportContentService.importToolContent(toolContentPath, mcToolContentHandler, fromVersion, + toVersion); if (!(toolPOJO instanceof McContent)) { - throw new ImportToolContentException("Import MC tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import MC tool content failed. Deserialized object is " + toolPOJO); } McContent toolContentObj = (McContent) toolPOJO; @@ -1369,21 +1357,22 @@ @Override public String getToolContentTitle(Long toolContentId) { - return mcContentDAO.findMcContentById(toolContentId).getTitle(); + return mcContentDAO.findMcContentById(toolContentId).getTitle(); } - + @Override public boolean isContentEdited(Long toolContentId) { - return mcContentDAO.findMcContentById(toolContentId).isDefineLater(); + return mcContentDAO.findMcContentById(toolContentId).isDefineLater(); } - + /** * it is possible that the tool session id already exists in the tool sessions table as the users from the same * session are involved. existsSession(long toolSessionId) * * @param toolSessionId * @return boolean */ + @Override public boolean existsSession(Long toolSessionId) { McSession mcSession = getMcSessionById(toolSessionId); return mcSession != null; @@ -1399,7 +1388,7 @@ McContent mcContent = mcContentDAO.findMcContentById(toolContentId); - //create a new a new tool session if it does not already exist in the tool session table + // create a new a new tool session if it does not already exist in the tool session table if (!existsSession(toolSessionId)) { try { McSession mcSession = new McSession(toolSessionId, new Date(System.currentTimeMillis()), @@ -1480,13 +1469,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { throw new ToolException("not yet implemented"); } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { throw new ToolException("not yet implemented"); } @@ -1500,7 +1490,7 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return mcOutputFactory.getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { Long userId = user.getUserId().longValue(); @@ -1527,7 +1517,7 @@ McQueUsr groupLeader = session.getGroupLeader(); // check if leader has submitted answers - if (groupLeader != null && groupLeader.isResponseFinalised()) { + if ((groupLeader != null) && groupLeader.isResponseFinalised()) { // we need to make sure specified user has the same scratches as a leader copyAnswersFromLeader(mcUser, groupLeader); @@ -1537,17 +1527,20 @@ } + @Override public IToolVO getToolBySignature(String toolSignature) throws McApplicationException { IToolVO tool = toolService.getToolBySignature(toolSignature); return tool; } + @Override public long getToolDefaultContentIdBySignature(String toolSignature) { long contentId = 0; contentId = toolService.getToolDefaultContentIdBySignature(toolSignature); return contentId; } + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } @@ -1701,7 +1694,7 @@ public void setExportContentService(IExportToolContentService exportContentService) { this.exportContentService = exportContentService; } - + public void setGradebookService(IGradebookService gradebookService) { this.gradebookService = gradebookService; } @@ -1719,14 +1712,15 @@ /** * Import the data for a 1.0.2 Chat */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { Date now = new Date(); McContent toolContentObj = new McContent(); toolContentObj.setCreatedBy(user.getUserID().longValue()); toolContentObj.setCreationDate(now); toolContentObj.setDefineLater(false); - toolContentObj.setInstructions(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); + toolContentObj.setInstructions( + WebUtil.convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY))); toolContentObj.setReflect(false); toolContentObj.setReflectionSubject(null); toolContentObj.setTitle((String) importValues.get(ToolContentImport102Manager.CONTENT_TITLE)); @@ -1776,10 +1770,8 @@ } catch (WDDXProcessorConversionException e) { McServicePOJO.logger.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."); + 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."); } mcContentDAO.saveMcContent(toolContentObj); @@ -1788,12 +1780,12 @@ private void create102Question(Hashtable questionMap, McContent toolContentObj) throws WDDXProcessorConversionException { McQueContent question = new McQueContent(); - question.setDisplayOrder(WDDXProcessor.convertToInteger(questionMap, - ToolContentImport102Manager.CONTENT_Q_ORDER)); + question.setDisplayOrder( + WDDXProcessor.convertToInteger(questionMap, ToolContentImport102Manager.CONTENT_Q_ORDER)); question.setFeedback((String) questionMap.get(ToolContentImport102Manager.CONTENT_Q_FEEDBACK)); - question.setQuestion(WebUtil.convertNewlines((String) questionMap - .get(ToolContentImport102Manager.CONTENT_Q_QUESTION))); + question.setQuestion( + WebUtil.convertNewlines((String) questionMap.get(ToolContentImport102Manager.CONTENT_Q_QUESTION))); // In 1.0.2 all questions are implicitly assumed to be 1 and be of equal weight question.setMark(new Integer(1)); @@ -1806,10 +1798,10 @@ while (candIterator.hasNext()) { Hashtable candidate = (Hashtable) candIterator.next(); String optionText = (String) candidate.get(ToolContentImport102Manager.CONTENT_Q_ANSWER); - if (optionText != null && optionText.length() > 0) { + if ((optionText != null) && (optionText.length() > 0)) { // 1.0.2 has a display order but 2.0 doesn't ToolContentImport102Manager.CONTENT_Q_ORDER McOptsContent options = new McOptsContent(); - options.setCorrectOption(correctAnswer != null && correctAnswer.equals(optionText)); + options.setCorrectOption((correctAnswer != null) && correctAnswer.equals(optionText)); options.setMcQueOptionText(optionText); options.setMcQueContent(question); question.getMcOptionsContents().add(options); @@ -1821,19 +1813,19 @@ question.setMcContent(toolContentObj); question.setMcContentId(toolContentObj.getUid()); } - + @Override public List getReflectionList(McContent mcContent, Long userID) { List reflectionsContainerDTO = new LinkedList(); if (userID == null) { // all users mode - for (McSession mcSession : (Set)mcContent.getMcSessions()) { + for (McSession mcSession : (Set) mcContent.getMcSessions()) { - for (McQueUsr user : (Set)mcSession.getMcQueUsers()) { + for (McQueUsr user : (Set) mcSession.getMcQueUsers()) { NotebookEntry notebookEntry = this.getEntry(mcSession.getMcSessionId(), - CoreNotebookConstants.NOTEBOOK_TOOL, MY_SIGNATURE, new Integer(user.getQueUsrId() - .toString())); + CoreNotebookConstants.NOTEBOOK_TOOL, McAppConstants.MY_SIGNATURE, + new Integer(user.getQueUsrId().toString())); if (notebookEntry != null) { ReflectionDTO reflectionDTO = new ReflectionDTO(); @@ -1855,8 +1847,8 @@ McQueUsr user = (McQueUsr) userIter.next(); if (user.getQueUsrId().equals(userID)) { NotebookEntry notebookEntry = this.getEntry(mcSession.getMcSessionId(), - CoreNotebookConstants.NOTEBOOK_TOOL, MY_SIGNATURE, new Integer(user.getQueUsrId() - .toString())); + CoreNotebookConstants.NOTEBOOK_TOOL, McAppConstants.MY_SIGNATURE, + new Integer(user.getQueUsrId().toString())); if (notebookEntry != null) { ReflectionDTO reflectionDTO = new ReflectionDTO(); @@ -1877,8 +1869,9 @@ } /** 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { McContent toolContentObj = null; if (toolContentId != null) { @@ -1893,20 +1886,23 @@ toolContentObj.setReflectionSubject(description); } + @Override public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry) { return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); } + @Override public NotebookEntry getEntry(Long id, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(id, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); } } + @Override public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } @@ -1956,21 +1952,25 @@ this.messageService = messageService; } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getMcOutputFactory().getSupportedDefinitionClasses(definitionType); } // ****************** REST methods ************************* - /** Rest call to create a new Multiple Choice content. Required fields in toolContentJSON: "title", "instructions", "questions". - * The questions entry should be JSONArray containing JSON objects, which in turn must contain "questionText", "displayOrder" (Integer) and a JSONArray "answers". - * The answers entry should be JSONArray containing JSON objects, which in turn must contain "answerText", "displayOrder" (Integer), "correct" (Boolean). + /** + * Rest call to create a new Multiple Choice content. Required fields in toolContentJSON: "title", "instructions", + * "questions". The questions entry should be JSONArray containing JSON objects, which in turn must contain + * "questionText", "displayOrder" (Integer) and a JSONArray "answers". The answers entry should be JSONArray + * containing JSON objects, which in turn must contain "answerText", "displayOrder" (Integer), "correct" (Boolean). * * Retries are controlled by lockWhenFinished, which defaults to true (no retries). */ @SuppressWarnings("unchecked") @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) + throws JSONException { McContent mcq = new McContent(); Date updateDate = new Date(); @@ -1983,11 +1983,12 @@ mcq.setMcContentId(toolContentID); mcq.setTitle(toolContentJSON.getString(RestTags.TITLE)); mcq.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); - + mcq.setRetries(JsonUtil.opt(toolContentJSON, "allowRetries", Boolean.FALSE)); - mcq.setUseSelectLeaderToolOuput(JsonUtil.opt(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE)); + mcq.setUseSelectLeaderToolOuput( + JsonUtil.opt(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE)); mcq.setReflect(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - mcq.setReflectionSubject(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS,"")); + mcq.setReflectionSubject(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, "")); mcq.setQuestionsSequenced(JsonUtil.opt(toolContentJSON, "questionsSequenced", Boolean.FALSE)); mcq.setRandomize(JsonUtil.opt(toolContentJSON, "randomize", Boolean.FALSE)); mcq.setShowReport(JsonUtil.opt(toolContentJSON, "showReport", Boolean.FALSE)); @@ -1996,28 +1997,26 @@ mcq.setPrefixAnswersWithLetters(JsonUtil.opt(toolContentJSON, "prefixAnswersWithLetters", Boolean.TRUE)); mcq.setPassMark(JsonUtil.opt(toolContentJSON, "passMark", 0)); // submissionDeadline is set in monitoring - + createMc(mcq); - + // Questions JSONArray questions = toolContentJSON.getJSONArray(RestTags.QUESTIONS); - for (int i=0; i()); + McQueContent question = new McQueContent(questionData.getString(RestTags.QUESTION_TEXT), + questionData.getInt(RestTags.DISPLAY_ORDER), 1, "", mcq, null, new HashSet()); - JSONArray optionsData = (JSONArray) questionData.getJSONArray(RestTags.ANSWERS); - for (int j=0; j getResponsesForTablesorter(final Long toolContentId, final Long qaSessionId, final Long questionId, - final Long excludeUserId, int page, int size, int sorting, String searchString) { - return qaUsrRespDAO.getResponsesForTablesorter(toolContentId, qaSessionId, questionId, excludeUserId, page, size, sorting, searchString); + public List getResponsesForTablesorter(final Long toolContentId, final Long qaSessionId, + final Long questionId, final Long excludeUserId, int page, int size, int sorting, String searchString) { + return qaUsrRespDAO.getResponsesForTablesorter(toolContentId, qaSessionId, questionId, excludeUserId, page, + size, sorting, searchString); } @Override @@ -530,7 +531,7 @@ fromContent = qaDAO.getQaByContentId(fromContentId.longValue()); } - if (fromContentId.equals(defaultContentId) && fromContent != null && fromContent.getConditions().isEmpty()) { + if (fromContentId.equals(defaultContentId) && (fromContent != null) && fromContent.getConditions().isEmpty()) { fromContent.getConditions().add(getQaOutputFactory().createDefaultComplexUserAnswersCondition(fromContent)); } QaContent toContent = QaContent.newInstance(fromContent, toContentId); @@ -548,49 +549,32 @@ } + @SuppressWarnings("unchecked") @Override - public void removeToolContent(Long toolContentID, boolean removeSessionData) - throws SessionDataExistsException, ToolException { - if (toolContentID == null) { - throw new ToolException("toolContentID is missing"); + public void removeToolContent(Long toolContentId) throws ToolException { + QaContent qaContent = qaDAO.getQaByContentId(toolContentId.longValue()); + if (qaContent == null) { + QaServicePOJO.logger.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; } - QaContent qaContent = qaDAO.getQaByContentId(toolContentID.longValue()); - - if (qaContent != null) { - Iterator sessionIterator = qaContent.getQaSessions().iterator(); - while (sessionIterator.hasNext()) { - if (removeSessionData == false) { - QaServicePOJO.logger.error("removeSessionData is false, throwing SessionDataExistsException."); - throw new SessionDataExistsException(); - } - - QaSession qaSession = (QaSession) sessionIterator.next(); - - Iterator sessionUsersIterator = qaSession.getQaQueUsers().iterator(); - while (sessionUsersIterator.hasNext()) { - QaQueUsr qaQueUsr = (QaQueUsr) sessionUsersIterator.next(); - - Iterator sessionUsersResponsesIterator = qaQueUsr.getQaUsrResps().iterator(); - while (sessionUsersResponsesIterator.hasNext()) { - QaUsrResp qaUsrResp = (QaUsrResp) sessionUsersResponsesIterator.next(); - removeUserResponse(qaUsrResp); - } - } + for (QaSession session : (Set) qaContent.getQaSessions()) { + List entries = coreNotebookService.getEntry(session.getQaSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, QaAppConstants.MY_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); } - - // removed all existing responses of toolContent with toolContentID - qaDAO.removeQa(toolContentID); - } else { - QaServicePOJO.logger.error("Warning!!!, We should have not come here. qaContent is null."); - throw new ToolException("toolContentID is missing"); } + + qaDAO.removeQa(toolContentId); } + @Override @SuppressWarnings("unchecked") public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("Removing Q&A answers for user ID " + userId + " and toolContentId " + toolContentId); + if (QaServicePOJO.logger.isDebugEnabled()) { + QaServicePOJO.logger + .debug("Removing Q&A answers for user ID " + userId + " and toolContentId " + toolContentId); } QaContent content = qaDAO.getQaByContentId(toolContentId); @@ -602,7 +586,7 @@ qaUsrRespDAO.removeUserResponse(response); } - if (session.getGroupLeader() != null && session.getGroupLeader().getUid().equals(user.getUid())) { + if ((session.getGroupLeader() != null) && session.getGroupLeader().getUid().equals(user.getUid())) { session.setGroupLeader(null); } @@ -881,7 +865,7 @@ if (toolContentObj == null) { long defaultToolContentId = toolService.getToolDefaultContentIdBySignature(QaAppConstants.MY_SIGNATURE); toolContentObj = getQaContent(defaultToolContentId); - if (toolContentObj != null && toolContentObj.getConditions().isEmpty()) { + if ((toolContentObj != null) && toolContentObj.getConditions().isEmpty()) { toolContentObj.getConditions() .add(getQaOutputFactory().createDefaultComplexUserAnswersCondition(toolContentObj)); } @@ -945,17 +929,19 @@ if (qaContent == null) { long defaultToolContentId = toolService.getToolDefaultContentIdBySignature(QaAppConstants.MY_SIGNATURE); qaContent = getQaContent(defaultToolContentId); - if (qaContent != null && qaContent.getConditions().isEmpty()) { + if ((qaContent != null) && qaContent.getConditions().isEmpty()) { qaContent.getConditions().add(getQaOutputFactory().createDefaultComplexUserAnswersCondition(qaContent)); } } return getQaOutputFactory().getToolOutputDefinitions(qaContent, definitionType); } + @Override public String getToolContentTitle(Long toolContentId) { return qaDAO.getQaByContentId(toolContentId).getTitle(); } + @Override public boolean isContentEdited(Long toolContentId) { return qaDAO.getQaByContentId(toolContentId).isDefineLater(); } @@ -1071,6 +1057,7 @@ /** * ToolSessionManager CONTRACT */ + @Override public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { throw new ToolException("not yet implemented"); @@ -1079,6 +1066,7 @@ /** * ToolSessionManager CONTRACT */ + @Override public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, ToolException { throw new ToolException("not yet implemented"); @@ -1120,7 +1108,7 @@ QaQueUsr groupLeader = session.getGroupLeader(); // check if leader has submitted answers - if (groupLeader != null && groupLeader.isResponseFinalized()) { + if ((groupLeader != null) && groupLeader.isResponseFinalized()) { // we need to make sure specified user has the same scratches as a leader copyAnswersFromLeader(qaUser, groupLeader); @@ -1130,11 +1118,13 @@ } + @Override public IToolVO getToolBySignature(String toolSignature) { IToolVO tool = toolService.getToolBySignature(toolSignature); return tool; } + @Override public long getToolDefaultContentIdBySignature(String toolSignature) { long contentId = 0; contentId = toolService.getToolDefaultContentIdBySignature(toolSignature); @@ -1150,7 +1140,7 @@ public NotebookEntry getEntry(Long id, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(id, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -1221,6 +1211,7 @@ this.qaToolContentHandler = qaToolContentHandler; } + @Override public IAuditService getAuditService() { return auditService; } @@ -1244,6 +1235,7 @@ /** * Import the data for a 1.0.2 Chat */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { Date now = new Date(); QaContent toolContentObj = new QaContent(); @@ -1339,6 +1331,7 @@ this.messageService = messageService; } + @Override public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } @@ -1393,7 +1386,7 @@ @Override public void deleteCondition(QaCondition condition) { - if (condition != null && condition.getConditionId() != null) { + if ((condition != null) && (condition.getConditionId() != null)) { qaDAO.deleteCondition(condition); } } Index: lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/service/ResourceServiceImpl.java =================================================================== diff -u -r6d6d46936b5e8db2ed485ad5b4276d0891e8b87f -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/service/ResourceServiceImpl.java (.../ResourceServiceImpl.java) (revision 6d6d46936b5e8db2ed485ad5b4276d0891e8b87f) +++ lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/service/ResourceServiceImpl.java (.../ResourceServiceImpl.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -79,17 +79,16 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.rsrc.ResourceConstants; import org.lamsfoundation.lams.tool.rsrc.dao.ResourceDAO; import org.lamsfoundation.lams.tool.rsrc.dao.ResourceItemDAO; import org.lamsfoundation.lams.tool.rsrc.dao.ResourceItemVisitDAO; import org.lamsfoundation.lams.tool.rsrc.dao.ResourceSessionDAO; import org.lamsfoundation.lams.tool.rsrc.dao.ResourceUserDAO; -import org.lamsfoundation.lams.tool.rsrc.dto.SessionDTO; -import org.lamsfoundation.lams.tool.rsrc.dto.ResourceItemDTO; import org.lamsfoundation.lams.tool.rsrc.dto.ReflectDTO; +import org.lamsfoundation.lams.tool.rsrc.dto.ResourceItemDTO; +import org.lamsfoundation.lams.tool.rsrc.dto.SessionDTO; import org.lamsfoundation.lams.tool.rsrc.dto.VisitLogDTO; import org.lamsfoundation.lams.tool.rsrc.ims.IContentPackageConverter; import org.lamsfoundation.lams.tool.rsrc.ims.IMSManifestException; @@ -209,8 +208,8 @@ } /** - * This method verifies the credentials of the Share Resource Tool and gives it the Ticket to login - * and access the Content Repository. + * 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. @@ -222,8 +221,8 @@ ICredentials credentials = new SimpleCredentials(resourceToolContentHandler.getRepositoryUser(), resourceToolContentHandler.getRepositoryId()); try { - ITicket ticket = repositoryService.login(credentials, resourceToolContentHandler - .getRepositoryWorkspaceName()); + ITicket ticket = repositoryService.login(credentials, + resourceToolContentHandler.getRepositoryWorkspaceName()); return ticket; } catch (AccessDeniedException ae) { throw new ResourceApplicationException("Access Denied to repository." + ae.getMessage()); @@ -285,8 +284,8 @@ try { repositoryService.deleteVersion(ticket, fileUuid, fileVersionId); } catch (Exception e) { - throw new ResourceApplicationException("Exception occured while deleting files from" + " the repository " - + e.getMessage()); + throw new ResourceApplicationException( + "Exception occured while deleting files from" + " the repository " + e.getMessage()); } } @@ -402,8 +401,8 @@ 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) })); + res.setMiniViewNumberStr( + messageService.getMessage("label.learning.minimum.review", new Object[] { new Integer(miniView) })); return res; } @@ -512,7 +511,7 @@ // 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. SessionDTO group = new SessionDTO(); @@ -524,7 +523,7 @@ items.addAll(resource.getResourceItems()); // add this session's resource items items.addAll(session.getResourceItems()); - + for (ResourceItem item : items) { ResourceItemDTO resourceItemDTO = new ResourceItemDTO(item); // set viewNumber according visit log @@ -533,7 +532,7 @@ } group.getItems().add(resourceItemDTO); } - + groupList.add(group); } @@ -556,14 +555,14 @@ if (entry != null) { ReflectDTO ref = new ReflectDTO(user); ref.setReflect(entry.getEntry()); - Date postedDate = (entry.getLastModified() != null) ? entry.getLastModified() : entry - .getCreateDate(); + Date postedDate = (entry.getLastModified() != null) ? entry.getLastModified() + : entry.getCreateDate(); ref.setDate(postedDate); reflections.add(ref); } } - + } return reflections; @@ -577,21 +576,21 @@ ResourceUser user = visit.getUser(); user.setAccessDate(visit.getAccessDate()); user.setCompleteDate(visit.getCompleteDate()); - Date timeTaken = (visit.getCompleteDate() != null && visit.getAccessDate() != null) ? - new Date(visit.getCompleteDate().getTime() - visit.getAccessDate().getTime()) : null; + Date timeTaken = ((visit.getCompleteDate() != null) && (visit.getAccessDate() != null)) + ? new Date(visit.getCompleteDate().getTime() - visit.getAccessDate().getTime()) : null; user.setTimeTaken(timeTaken); userList.add(user); } return userList; } - + @Override public List getPagedVisitLogsBySessionAndItem(Long sessionId, Long itemUid, int page, int size, String sortBy, String sortOrder, String searchString) { - return resourceItemVisitDao.getPagedVisitLogsBySessionAndItem(sessionId, itemUid, page, size, sortBy, - sortOrder, searchString); + return resourceItemVisitDao.getPagedVisitLogsBySessionAndItem(sessionId, itemUid, page, size, sortBy, sortOrder, + searchString); } - + @Override public int getCountVisitLogsBySessionAndItem(Long sessionId, Long itemUid, String searchString) { return resourceItemVisitDao.getCountVisitLogsBySessionAndItem(sessionId, itemUid, searchString); @@ -628,7 +627,7 @@ @Override public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(sessionId, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -644,7 +643,7 @@ public ResourceUser getUser(Long uid) { return (ResourceUser) resourceUserDao.getObject(ResourceUser.class, uid); } - + @Override public void notifyTeachersOnAssigmentSumbit(Long sessionId, ResourceUser resourceUser) { String userName = resourceUser.getLastName() + " " + resourceUser.getFirstName(); @@ -689,7 +688,7 @@ */ private NodeKey processFile(FormFile file) throws UploadResourceFileException { NodeKey node = null; - if (file != null && !StringUtils.isEmpty(file.getFileName())) { + if ((file != null) && !StringUtils.isEmpty(file.getFileName())) { String fileName = file.getFileName(); try { node = resourceToolContentHandler.uploadFile(file.getInputStream(), fileName, file.getContentType()); @@ -735,8 +734,8 @@ String packageDirectory = ZipFileUtil.expandZip(is, fileName); String initFile = findWebsiteInitialItem(packageDirectory); if (initFile == null) { - throw new UploadResourceFileException(messageService - .getMessage("error.msg.website.no.initial.file")); + throw new UploadResourceFileException( + messageService.getMessage("error.msg.website.no.initial.file")); } item.setInitialItem(initFile); // upload package @@ -761,8 +760,8 @@ item.setFileType(fileType); item.setFileName(fileName); } catch (ZipFileUtilException e) { - ResourceServiceImpl.log.error(messageService.getMessage("error.msg.zip.file.exception") + " : " - + e.toString()); + 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()); @@ -778,7 +777,7 @@ throw new UploadResourceFileException(messageService.getMessage("error.msg.ims.application")); } } - + /** * Find out default.htm/html or index.htm/html in the given directory folder * @@ -792,8 +791,9 @@ } File[] initFiles = file.listFiles(new FileFilter() { + @Override public boolean accept(File pathname) { - if (pathname == null || pathname.getName() == null) { + if ((pathname == null) || (pathname.getName() == null)) { return false; } String name = pathname.getName(); @@ -804,7 +804,7 @@ return false; } }); - if (initFiles != null && initFiles.length > 0) { + if ((initFiles != null) && (initFiles.length > 0)) { return initFiles[0].getName(); } else { return null; @@ -815,20 +815,20 @@ * Gets a message from resource bundle. Same as in JSP pages. * * @param key - * key of the message + * key of the message * @param args - * arguments for the message + * arguments for the message * @return message content */ private String getLocalisedMessage(String key, Object[] args) { return messageService.getMessage(key, args); } - + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + // ******************************************************************************* // ToolContentManager, ToolSessionManager methods // ******************************************************************************* @@ -865,7 +865,7 @@ try { // register version filter class exportContentService.registerImportVersionFilterClass(ResourceImportContentVersionFilter.class); - + exportContentService.registerFileClassForImport(ResourceItem.class.getName(), "fileUuid", "fileVersionId", "fileName", "fileType", null, "initialItem"); @@ -948,12 +948,12 @@ } } } - + @Override public String getToolContentTitle(Long toolContentId) { return getResourceByContentId(toolContentId).getTitle(); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Resource resource = resourceDao.getByContentId(toolContentId); @@ -967,32 +967,38 @@ public boolean isContentEdited(Long toolContentId) { return getResourceByContentId(toolContentId).isDefineLater(); } - + @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId) throws 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); + if (resource == null) { + ResourceServiceImpl.log.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (ResourceSession session : resourceSessionDao.getByContentId(toolContentId)) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, ResourceConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); } } + resourceDao.delete(resource); } @Override @SuppressWarnings("unchecked") public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (log.isDebugEnabled()) { - log.debug("Removing Share Resources content for user ID " + userId + " and toolContentId " + toolContentId); + if (ResourceServiceImpl.log.isDebugEnabled()) { + ResourceServiceImpl.log.debug( + "Removing Share Resources content for user ID " + userId + " and toolContentId " + toolContentId); } Resource resource = resourceDao.getByContentId(toolContentId); if (resource == null) { - log.warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); + ResourceServiceImpl.log + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } @@ -1027,7 +1033,7 @@ if (entry != null) { resourceDao.removeObject(NotebookEntry.class, entry.getUid()); } - + resourceUserDao.removeObject(ResourceUser.class, user.getUid()); } } @@ -1068,13 +1074,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -1092,10 +1099,10 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return getResourceOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /* ===============Methods implemented from ToolContentImport102Manager =============== */ @@ -1111,8 +1118,8 @@ toolContentObj.setContentInUse(Boolean.FALSE); toolContentObj.setCreated(now); toolContentObj.setDefineLater(Boolean.FALSE); - toolContentObj.setInstructions(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); + toolContentObj.setInstructions( + WebUtil.convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY))); toolContentObj.setUpdated(now); toolContentObj.setReflectOnActivity(Boolean.FALSE); toolContentObj.setReflectInstructions(null); @@ -1168,7 +1175,7 @@ Vector instructions = (Vector) urlMap .get(ToolContentImport102Manager.CONTENT_URL_URL_INSTRUCTION_ARRAY); - if (instructions != null && instructions.size() > 0) { + if ((instructions != null) && (instructions.size() > 0)) { item.setItemInstructions(new HashSet()); Iterator insIter = instructions.iterator(); while (insIter.hasNext()) { @@ -1213,10 +1220,8 @@ } 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."); + 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."); } resourceDao.saveObject(toolContentObj); @@ -1231,7 +1236,7 @@ // 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 ((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\'" @@ -1248,8 +1253,9 @@ } /** 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { Resource toolContentObj = getResourceByContentId(toolContentId); if (toolContentObj == null) { @@ -1261,10 +1267,11 @@ toolContentObj.setReflectInstructions(description); } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getResourceOutputFactory().getSupportedDefinitionClasses(definitionType); } - + // ***************************************************************************** // set methods for Spring Bean // ***************************************************************************** @@ -1355,17 +1362,18 @@ public void setResourceOutputFactory(ResourceOutputFactory resourceOutputFactory) { this.resourceOutputFactory = resourceOutputFactory; } - + // ****************** REST methods ************************* - /** Used by the Rest calls to create content. - * Mandatory fields in toolContentJSON: title, instructions, resources, user fields firstName, lastName and loginName - * Resources must contain a JSONArray of JSONObject objects, which have the following mandatory fields: title, description, type. - * If there are instructions for a resource, the instructions are a JSONArray of Strings. - * There should be at least one resource object in the resources array. + /** + * Used by the Rest calls to create content. Mandatory fields in toolContentJSON: title, instructions, resources, + * user fields firstName, lastName and loginName Resources must contain a JSONArray of JSONObject objects, which + * have the following mandatory fields: title, description, type. If there are instructions for a resource, the + * instructions are a JSONArray of Strings. There should be at least one resource object in the resources array. */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) + throws JSONException { Date updateDate = new Date(); @@ -1379,9 +1387,10 @@ resource.setAllowAddUrls(JsonUtil.opt(toolContentJSON, "allowAddUrls", Boolean.FALSE)); resource.setLockWhenFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); resource.setMiniViewResourceNumber(JsonUtil.opt(toolContentJSON, "minViewResourceNumber", 0)); - resource.setNotifyTeachersOnAssigmentSumbit(JsonUtil.opt(toolContentJSON, "notifyTeachersOnAssigmentSubmit", Boolean.FALSE)); + resource.setNotifyTeachersOnAssigmentSumbit( + JsonUtil.opt(toolContentJSON, "notifyTeachersOnAssigmentSubmit", Boolean.FALSE)); resource.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - resource.setReflectInstructions(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, (String)null)); + resource.setReflectInstructions(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, (String) null)); resource.setRunAuto(JsonUtil.opt(toolContentJSON, "runAuto", Boolean.FALSE)); resource.setContentInUse(false); @@ -1393,41 +1402,40 @@ resourceUser.setFirstName(toolContentJSON.getString("firstName")); resourceUser.setLastName(toolContentJSON.getString("lastName")); resourceUser.setLoginName(toolContentJSON.getString("loginName")); - // resourceUser.setResource(content); + // resourceUser.setResource(content); } resource.setCreatedBy(resourceUser); - // **************************** Handle topic ********************* JSONArray resources = toolContentJSON.getJSONArray("resources"); Set itemList = new LinkedHashSet(); - for (int i=0; i 0) { + if ((instructionStrings != null) && (instructionStrings.length() > 0)) { Set instructions = new LinkedHashSet(); - for ( int j=0; j) content.getLeaderselectionSessions()) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, LeaderselectionConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); + } + } + + leaderselectionDAO.delete(content); } - + + @Override @SuppressWarnings("unchecked") public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("Removing Leader Selection state for user ID " + userId + " and toolContentId " - + toolContentId); + if (LeaderselectionService.logger.isDebugEnabled()) { + LeaderselectionService.logger.debug( + "Removing Leader Selection state for user ID " + userId + " and toolContentId " + toolContentId); } Leaderselection selection = leaderselectionDAO.getByContentId(toolContentId); @@ -217,8 +234,8 @@ for (LeaderselectionSession session : (Set) selection.getLeaderselectionSessions()) { /* if (session.getGroupLeader() != null && session.getGroupLeader().getUserId().equals(userId.longValue())) { - session.setGroupLeader(null); - leaderselectionSessionDAO.update(session); + session.setGroupLeader(null); + leaderselectionSessionDAO.update(session); } */ @@ -259,8 +276,8 @@ // register version filter class exportContentService.registerImportVersionFilterClass(LeaderselectionImportContentVersionFilter.class); - Object toolPOJO = exportContentService.importToolContent(toolContentPath, - leaderselectionToolContentHandler, fromVersion, toVersion); + Object toolPOJO = exportContentService.importToolContent(toolContentPath, leaderselectionToolContentHandler, + fromVersion, toVersion); if (!(toolPOJO instanceof Leaderselection)) { throw new ImportToolContentException( "Import Leaderselection tool content failed. Deserialized object is " + toolPOJO); @@ -287,26 +304,29 @@ return getLeaderselectionOutputFactory().getToolOutputDefinitions(content, definitionType); } + @Override public String getToolContentTitle(Long toolContentId) { return getContentByContentId(toolContentId).getTitle(); } - + + @Override public boolean isContentEdited(Long toolContentId) { return getContentByContentId(toolContentId).isDefineLater(); } - + /* ********** ILeaderselectionService Methods ********************************* */ @Override public void setGroupLeader(Long userUid, Long toolSessionId) { - if (userUid == null || toolSessionId == null) { + if ((userUid == null) || (toolSessionId == null)) { return; } LeaderselectionSession session = getSessionBySessionId(toolSessionId); LeaderselectionUser newLeader = getUserByUID(userUid); - if (session == null || newLeader == null) { - logger.error("Wrong parameters supplied. SessionId=" + toolSessionId + " UserId=" + userUid); + if ((session == null) || (newLeader == null)) { + LeaderselectionService.logger + .error("Wrong parameters supplied. SessionId=" + toolSessionId + " UserId=" + userUid); return; } @@ -316,7 +336,7 @@ @Override public boolean isUserLeader(Long userId, Long toolSessionId) { - if (userId == null || toolSessionId == null) { + if ((userId == null) || (toolSessionId == null)) { throw new LeaderselectionException("Wrong parameters supplied: userId or toolSessionId is null. SessionId=" + toolSessionId + " UserId=" + userId); } @@ -353,7 +373,7 @@ toolContentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature)); if (toolContentId == null) { String error = "Could not retrieve default content id for this tool"; - logger.error(error); + LeaderselectionService.logger.error(error); throw new LeaderselectionException(error); } return toolContentId; @@ -365,7 +385,7 @@ Leaderselection defaultContent = getContentByContentId(defaultContentID); if (defaultContent == null) { String error = "Could not retrieve default content record for this tool"; - logger.error(error); + LeaderselectionService.logger.error(error); throw new LeaderselectionException(error); } return defaultContent; @@ -376,7 +396,7 @@ if (newContentID == null) { String error = "Cannot copy the Leaderselection tools default content: + " + "newContentID is null"; - logger.error(error); + LeaderselectionService.logger.error(error); throw new LeaderselectionException(error); } @@ -392,7 +412,7 @@ public Leaderselection getContentByContentId(Long toolContentID) { Leaderselection leaderselection = leaderselectionDAO.getByContentId(toolContentID); if (leaderselection == null) { - logger.debug("Could not find the content with toolContentID:" + toolContentID); + LeaderselectionService.logger.debug("Could not find the content with toolContentID:" + toolContentID); } return leaderselection; } @@ -401,7 +421,8 @@ public LeaderselectionSession getSessionBySessionId(Long toolSessionId) { LeaderselectionSession leaderselectionSession = leaderselectionSessionDAO.getBySessionId(toolSessionId); if (leaderselectionSession == null) { - logger.debug("Could not find the leaderselection session with toolSessionID:" + toolSessionId); + LeaderselectionService.logger + .debug("Could not find the leaderselection session with toolSessionID:" + toolSessionId); } return leaderselectionSession; } @@ -471,8 +492,8 @@ } @Override - public void setReflectiveData(Long toolContentId, String title, String description) throws ToolException, - DataMissingException { + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { Leaderselection leaderselection = getContentByContentId(toolContentId); if (leaderselection == null) { @@ -566,20 +587,24 @@ this.leaderselectionOutputFactory = leaderselectionOutputFactory; } + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getLeaderselectionOutputFactory().getSupportedDefinitionClasses(definitionType); } - + // ****************** REST methods ************************* - /** Rest call to create a new Learner Selection content. Required fields in toolContentJSON: "title", "instructions". + /** + * Rest call to create a new Learner Selection content. Required fields in toolContentJSON: "title", "instructions". */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) + throws JSONException { Date updateDate = new Date(); Leaderselection leaderselection = new Leaderselection(); @@ -593,5 +618,5 @@ leaderselection.setDefineLater(false); saveOrUpdateLeaderselection(leaderselection); } - + } Index: lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/service/MindmapService.java =================================================================== diff -u -ra207bdecc16a704428826dbf402a97de2e35458b -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/service/MindmapService.java (.../MindmapService.java) (revision a207bdecc16a704428826dbf402a97de2e35458b) +++ lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/service/MindmapService.java (.../MindmapService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -42,6 +42,7 @@ import org.lamsfoundation.lams.learningdesign.service.IExportToolContentService; import org.lamsfoundation.lams.learningdesign.service.ImportToolContentException; import org.lamsfoundation.lams.notebook.model.NotebookEntry; +import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; import org.lamsfoundation.lams.notebook.service.ICoreNotebookService; import org.lamsfoundation.lams.rest.RestTags; import org.lamsfoundation.lams.rest.ToolRestManager; @@ -130,13 +131,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -155,10 +157,10 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return getMindmapOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /** @@ -168,6 +170,7 @@ * @param toolSessionId * @return */ + @Override public int getNumNodes(Long learnerId, Long toolSessionId) { MindmapUser mindmapUser = getUserByUserIdAndSessionId(learnerId, toolSessionId); // MindmapSession mindmapSession = getSessionBySessionId(toolSessionId); @@ -178,6 +181,7 @@ /* * Methods from ToolContentManager Called on adding lesson. */ + @Override public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { if (MindmapService.logger.isDebugEnabled()) { @@ -237,8 +241,8 @@ * @param toContent * @return */ - public void cloneMindmapNodesForRuntime(MindmapNode fromMindmapNode, MindmapNode toMindmapNode, - Mindmap fromContent, Mindmap toContent) { + public void cloneMindmapNodesForRuntime(MindmapNode fromMindmapNode, MindmapNode toMindmapNode, Mindmap fromContent, + Mindmap toContent) { toMindmapNode = saveMindmapNode(null, toMindmapNode, fromMindmapNode.getUniqueId(), fromMindmapNode.getText(), fromMindmapNode.getColor(), fromMindmapNode.getUser(), toContent, null); @@ -264,6 +268,7 @@ * @param mindmap * @return null */ + @Override public MindmapNode saveMindmapNode(MindmapNode currentMindmapNode, MindmapNode parentMindmapNode, Long uniqueId, String text, String color, MindmapUser mindmapUser, Mindmap mindmap, MindmapSession session) { if (currentMindmapNode == null) { @@ -290,6 +295,7 @@ * @param mindmapUser * @return rootNodeModel */ + @Override public NodeModel getMindmapXMLFromDatabase(Long rootNodeId, Long mindmapId, NodeModel rootNodeModel, MindmapUser mindmapUser) { List mindmapNodes = getMindmapNodeByParentId(rootNodeId, mindmapId); @@ -329,6 +335,7 @@ return rootNodeModel; } + @Override public void getChildMindmapNodes(List branches, MindmapNode rootMindmapNode, MindmapUser mindmapUser, Mindmap mindmap, MindmapSession mindmapSession) { for (Iterator iterator = branches.iterator(); iterator.hasNext();) { @@ -359,6 +366,7 @@ } } + @Override public String getLanguageXML() { ArrayList languageCollection = new ArrayList(); languageCollection.add(new String("local.title")); @@ -378,7 +386,7 @@ return languageOutput; } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Mindmap mindmap = mindmapDAO.getByContentId(toolContentId); @@ -389,22 +397,38 @@ mindmapDAO.saveOrUpdate(mindmap); } - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { - // TODO Auto-generated method stub + @SuppressWarnings("unchecked") + @Override + public void removeToolContent(Long toolContentId) throws SessionDataExistsException, ToolException { + Mindmap mindmap = mindmapDAO.getByContentId(toolContentId); + if (mindmap == null) { + MindmapService.logger.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (MindmapSession session : (Set) mindmap.getMindmapSessions()) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, MindmapConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); + } + } + + mindmapDAO.delete(mindmap); } + @Override @SuppressWarnings("unchecked") public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { if (MindmapService.logger.isDebugEnabled()) { - MindmapService.logger.debug("Removing Mindmap content for user ID " + userId + " and toolContentId " - + toolContentId); + MindmapService.logger + .debug("Removing Mindmap content for user ID " + userId + " and toolContentId " + toolContentId); } Mindmap mindmap = mindmapDAO.getByContentId(toolContentId); if (mindmap == null) { - MindmapService.logger.warn("Did not find activity with toolContentId: " + toolContentId - + " to remove learner content"); + MindmapService.logger + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } @@ -446,8 +470,8 @@ @SuppressWarnings("unchecked") private boolean userOwnsChildrenNodes(MindmapNode node, Long userId, List descendants) { - List children = mindmapNodeDAO.getMindmapNodeByParentIdMindmapIdSessionId(node.getNodeId(), node - .getMindmap().getUid(), node.getSession().getSessionId()); + List children = mindmapNodeDAO.getMindmapNodeByParentIdMindmapIdSessionId(node.getNodeId(), + node.getMindmap().getUid(), node.getSession().getSessionId()); for (MindmapNode child : children) { boolean userOwnsChild = (child.getUser() != null) && child.getUser().getUserId().equals(userId) && userOwnsChildrenNodes(child, userId, descendants); @@ -467,6 +491,7 @@ * @throws ToolException * if any other error occurs */ + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { Mindmap mindmap = mindmapDAO.getByContentId(toolContentId); if (mindmap == null) { @@ -512,6 +537,7 @@ * @throws ToolException * if any other error occurs */ + @Override public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion, String toVersion) throws ToolException { try { @@ -521,8 +547,8 @@ Object toolPOJO = exportContentService.importToolContent(toolContentPath, mindmapToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof Mindmap)) { - throw new ImportToolContentException("Import Mindmap tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import Mindmap tool content failed. Deserialized object is " + toolPOJO); } Mindmap mindmap = (Mindmap) toolPOJO; @@ -566,6 +592,7 @@ * * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition */ + @Override public SortedMap getToolOutputDefinitions(Long toolContentId, int definitionType) throws ToolException { Mindmap mindmap = getMindmapDAO().getByContentId(toolContentId); @@ -575,32 +602,39 @@ return getMindmapOutputFactory().getToolOutputDefinitions(mindmap, definitionType); } + @Override public String getToolContentTitle(Long toolContentId) { return getMindmapByContentId(toolContentId).getTitle(); } - + + @Override public boolean isContentEdited(Long toolContentId) { return getMindmapByContentId(toolContentId).isDefineLater(); } /* IMindmapService Methods */ + @Override public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry) { return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); } + @Override public NotebookEntry getEntry(Long uid) { return coreNotebookService.getEntry(uid); } + @Override public void updateEntry(Long uid, String entry) { coreNotebookService.updateEntry(uid, "", entry); } + @Override public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } + @Override public Long getDefaultContentIdBySignature(String toolSignature) { Long toolContentId = null; toolContentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature)); @@ -612,6 +646,7 @@ return toolContentId; } + @Override public Mindmap getDefaultContent() { Long defaultContentID = getDefaultContentIdBySignature(MindmapConstants.TOOL_SIGNATURE); Mindmap defaultContent = getMindmapByContentId(defaultContentID); @@ -624,6 +659,7 @@ return defaultContent; } + @Override public Mindmap copyDefaultContent(Long newContentID) { if (newContentID == null) { @@ -640,6 +676,7 @@ return newContent; } + @Override public Mindmap getMindmapByContentId(Long toolContentID) { Mindmap mindmap = mindmapDAO.getByContentId(toolContentID); if (mindmap == null) { @@ -648,6 +685,7 @@ return mindmap; } + @Override public Mindmap getMindmapByUid(Long Uid) { Mindmap mindmap = mindmapDAO.getMindmapByUid(Uid); if (mindmap == null) { @@ -656,6 +694,7 @@ return mindmap; } + @Override public MindmapSession getSessionBySessionId(Long toolSessionId) { MindmapSession mindmapSession = mindmapSessionDAO.getBySessionId(toolSessionId); if (mindmapSession == null) { @@ -664,6 +703,7 @@ return mindmapSession; } + @Override public MindmapUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { return mindmapUserDAO.getByUserIdAndSessionId(userId, toolSessionId); } @@ -672,26 +712,32 @@ return mindmapUserDAO.getByLoginNameAndSessionId(loginName, toolSessionId); } + @Override public MindmapUser getUserByUID(Long uid) { return mindmapUserDAO.getByUID(uid); } + @Override public void saveOrUpdateMindmap(Mindmap mindmap) { mindmapDAO.saveOrUpdate(mindmap); } + @Override public void saveOrUpdateMindmapRequest(MindmapRequest mindmapRequest) { mindmapRequestDAO.saveOrUpdate(mindmapRequest); } + @Override public void saveOrUpdateMindmapSession(MindmapSession mindmapSession) { mindmapSessionDAO.saveOrUpdate(mindmapSession); } + @Override public void saveOrUpdateMindmapUser(MindmapUser mindmapUser) { mindmapUserDAO.saveOrUpdate(mindmapUser); } + @Override public MindmapUser createMindmapUser(UserDTO user, MindmapSession mindmapSession) { MindmapUser mindmapUser = new MindmapUser(user, mindmapSession); saveOrUpdateMindmapUser(mindmapUser); @@ -711,15 +757,16 @@ /** * Import the data for a 1.0.2 Mindmap */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { Date now = new Date(); Mindmap mindmap = new Mindmap(); mindmap.setContentInUse(Boolean.FALSE); mindmap.setCreateBy(new Long(user.getUserID().longValue())); mindmap.setCreateDate(now); mindmap.setDefineLater(Boolean.FALSE); - mindmap.setInstructions(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); + mindmap.setInstructions( + WebUtil.convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY))); mindmap.setLockOnFinished(Boolean.TRUE); mindmap.setTitle((String) importValues.get(ToolContentImport102Manager.CONTENT_TITLE)); mindmap.setToolContentId(toolContentId); @@ -731,11 +778,12 @@ } /** 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { - MindmapService.logger - .warn("Setting the reflective field on a mindmap. This doesn't make sense as the mindmap is for reflection and we don't reflect on reflection!"); + MindmapService.logger.warn( + "Setting the reflective field on a mindmap. This doesn't make sense as the mindmap is for reflection and we don't reflect on reflection!"); Mindmap mindmap = getMindmapByContentId(toolContentId); if (mindmap == null) { throw new DataMissingException("Unable to set reflective data titled " + title @@ -820,6 +868,7 @@ this.mindmapOutputFactory = mindmapOutputFactory; } + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } @@ -832,62 +881,77 @@ return mindmapNodeDAO; } + @Override public void saveOrUpdateMindmapNode(MindmapNode mindmapNode) { mindmapNodeDAO.saveOrUpdate(mindmapNode); } + @Override public List getAuthorRootNodeByMindmapId(Long mindmapId) { return mindmapNodeDAO.getAuthorRootNodeByMindmapId(mindmapId); } + @Override public List getAuthorRootNodeBySessionId(Long sessionId) { return mindmapNodeDAO.getAuthorRootNodeBySessionId(sessionId); } + @Override public List getAuthorRootNodeByMindmapSession(Long mindmapId, Long toolSessionId) { return mindmapNodeDAO.getAuthorRootNodeByMindmapSession(mindmapId, toolSessionId); } + @Override public List getRootNodeByMindmapIdAndUserId(Long mindmapId, Long userId) { return mindmapNodeDAO.getRootNodeByMindmapIdAndUserId(mindmapId, userId); } + @Override public List getRootNodeByMindmapIdAndSessionId(Long mindmapId, Long sessionId) { return mindmapNodeDAO.getRootNodeByMindmapIdAndUserId(mindmapId, sessionId); } + @Override public List getMindmapNodeByParentId(Long parentId, Long mindmapId) { return mindmapNodeDAO.getMindmapNodeByParentId(parentId, mindmapId); } + @Override public List getMindmapNodeByParentIdMindmapIdSessionId(Long parentId, Long mindmapId, Long sessionId) { return mindmapNodeDAO.getMindmapNodeByParentIdMindmapIdSessionId(parentId, mindmapId, sessionId); } + @Override public List getMindmapNodeByUniqueId(Long uniqueId, Long mindmapId) { return mindmapNodeDAO.getMindmapNodeByUniqueId(uniqueId, mindmapId); } + @Override public List getMindmapNodeByUniqueIdSessionId(Long uniqueId, Long mindmapId, Long sessionId) { return mindmapNodeDAO.getMindmapNodeByUniqueIdSessionId(uniqueId, mindmapId, sessionId); } + @Override public List getMindmapNodeByUniqueIdMindmapIdUserId(Long uniqueId, Long mindmapId, Long userId) { return mindmapNodeDAO.getMindmapNodeByUniqueIdMindmapIdUserId(uniqueId, mindmapId, userId); } + @Override public void deleteNodeByUniqueMindmapUser(Long uniqueId, Long mindmapId, Long userId, Long sessionId) { mindmapNodeDAO.deleteNodeByUniqueMindmapUser(uniqueId, mindmapId, userId, sessionId); } + @Override public void deleteNodes(String nodesToDeleteCondition) { mindmapNodeDAO.deleteNodes(nodesToDeleteCondition); } + @Override public String getNodesToDeleteCondition() { return nodesToDeleteCondition; } + @Override public void setNodesToDeleteCondition(String nodesToDeleteCondition) { this.nodesToDeleteCondition = nodesToDeleteCondition; } @@ -900,42 +964,51 @@ return mindmapRequestDAO; } + @Override public List getLastRequestsAfterGlobalId(Long globalId, Long mindmapId, Long userId, Long sessionId) { return mindmapRequestDAO.getLastRequestsAfterGlobalId(globalId, mindmapId, userId, sessionId); } + @Override public MindmapRequest getRequestByUniqueId(Long uniqueId, Long userId, Long mindmapId, Long globalId) { return mindmapRequestDAO.getRequestByUniqueId(uniqueId, userId, mindmapId, globalId); } + @Override public Long getLastGlobalIdByMindmapId(Long mindmapId, Long sessionId) { return mindmapRequestDAO.getLastGlobalIdByMindmapId(mindmapId, sessionId); } + @Override public Long getNodeLastUniqueIdByMindmapUidSessionId(Long mindmapUid, Long sessionId) { return mindmapNodeDAO.getNodeLastUniqueIdByMindmapUidSessionId(mindmapUid, sessionId); } + @Override public void setMindmapMessageService(MessageService mindmapMessageService) { this.mindmapMessageService = mindmapMessageService; } + @Override public MessageService getMindmapMessageService() { return mindmapMessageService; } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getMindmapOutputFactory().getSupportedDefinitionClasses(definitionType); } - + // ****************** REST methods ************************* - /** Used by the Rest calls to create content. Creates default nodes as seen when first opening authoring. - * Mandatory fields in toolContentJSON: title, instructions - * Optional fields: multiUserMode (default false), lockWhenFinished (default false), reflectOnActivity (default false), reflectInstructions + /** + * Used by the Rest calls to create content. Creates default nodes as seen when first opening authoring. Mandatory + * fields in toolContentJSON: title, instructions Optional fields: multiUserMode (default false), lockWhenFinished + * (default false), reflectOnActivity (default false), reflectInstructions */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) + throws JSONException { Mindmap content = new Mindmap(); Date updateDate = new Date(); @@ -962,7 +1035,7 @@ String rootNodeName = getMindmapMessageService().getMessage("node.root.defaultName"); String childNodeName1 = getMindmapMessageService().getMessage("node.child1.defaultName"); String childNodeName2 = getMindmapMessageService().getMessage("node.child2.defaultName"); - + MindmapNode rootMindmapNode = saveMindmapNode(null, null, 1l, rootNodeName, "ffffff", null, content, null); saveOrUpdateMindmapNode(rootMindmapNode); saveMindmapNode(null, rootMindmapNode, 2l, childNodeName1, "ffffff", null, content, null); Index: lams_tool_nb/src/java/org/lamsfoundation/lams/tool/noticeboard/service/NoticeboardServicePOJO.java =================================================================== diff -u -ra207bdecc16a704428826dbf402a97de2e35458b -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_nb/src/java/org/lamsfoundation/lams/tool/noticeboard/service/NoticeboardServicePOJO.java (.../NoticeboardServicePOJO.java) (revision a207bdecc16a704428826dbf402a97de2e35458b) +++ lams_tool_nb/src/java/org/lamsfoundation/lams/tool/noticeboard/service/NoticeboardServicePOJO.java (.../NoticeboardServicePOJO.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -53,7 +53,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.noticeboard.NbApplicationException; import org.lamsfoundation.lams.tool.noticeboard.NoticeboardConstants; @@ -306,7 +305,8 @@ // default content { // use default content id to grab contents - NoticeboardContent defaultContent = retrieveNoticeboard(getToolDefaultContentIdBySignature(NoticeboardConstants.TOOL_SIGNATURE)); + NoticeboardContent defaultContent = retrieveNoticeboard( + getToolDefaultContentIdBySignature(NoticeboardConstants.TOOL_SIGNATURE)); if (defaultContent != null) { NoticeboardContent newContent = NoticeboardContent.newInstance(defaultContent, toContentId); @@ -335,29 +335,36 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { - NoticeboardContent nbContent = getAndCheckIDandObject(toolContentId); - // if session data exist and removeSessionData=false, throw an exception - if (!nbContent.getNbSessions().isEmpty() && !removeSessionData) { - throw new SessionDataExistsException( - "Delete failed: There is session data that belongs to this tool content id"); + public void removeToolContent(Long toolContentId) throws ToolException { + NoticeboardContent nbContent = retrieveNoticeboard(toolContentId); + if (nbContent == null) { + NoticeboardServicePOJO.log + .warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; } + for (NoticeboardSession session : nbContent.getNbSessions()) { + List entries = coreNotebookService.getEntry(session.getNbSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, NoticeboardConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); + } + } + removeNoticeboard(toolContentId); } @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { if (NoticeboardServicePOJO.log.isDebugEnabled()) { - NoticeboardServicePOJO.log.debug("Removing Noticeboard user for user ID " + userId + " and toolContentId " - + toolContentId); + NoticeboardServicePOJO.log + .debug("Removing Noticeboard user for user ID " + userId + " and toolContentId " + toolContentId); } NoticeboardContent nbContent = nbContentDAO.findNbContentById(toolContentId); if (nbContent == null) { - NoticeboardServicePOJO.log.warn("Did not find activity with toolContentId: " + toolContentId - + " to remove learner content"); + NoticeboardServicePOJO.log + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } @@ -388,8 +395,8 @@ return nbContent; } - private NoticeboardSession getAndCheckSessionIDandObject(Long toolSessionId) throws ToolException, - DataMissingException { + private NoticeboardSession getAndCheckSessionIDandObject(Long toolSessionId) + throws ToolException, DataMissingException { if (toolSessionId == null) { throw new ToolException("Tool session ID is missing."); } @@ -434,8 +441,8 @@ // register version filter class exportContentService.registerImportVersionFilterClass(NoticeboardImportContentVersionFilter.class); - Object toolPOJO = exportContentService.importToolContent(toolContentPath, nbToolContentHandler, - fromVersion, toVersion); + Object toolPOJO = exportContentService.importToolContent(toolContentPath, nbToolContentHandler, fromVersion, + toVersion); if (!(toolPOJO instanceof NoticeboardContent)) { throw new ImportToolContentException( "Import Noteice board tool content failed. Deserialized object is " + toolPOJO); @@ -474,8 +481,8 @@ } NoticeboardContent nbContent = retrieveNoticeboard(toolContentId); - NoticeboardSession nbSession = new NoticeboardSession(toolSessionId, toolSessionName, nbContent, new Date( - System.currentTimeMillis()), NoticeboardSession.NOT_ATTEMPTED); + NoticeboardSession nbSession = new NoticeboardSession(toolSessionId, toolSessionName, nbContent, + new Date(System.currentTimeMillis()), NoticeboardSession.NOT_ATTEMPTED); nbContent.getNbSessions().add(nbSession); saveNoticeboard(nbContent); @@ -489,15 +496,16 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws ToolException, DataMissingException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws ToolException, DataMissingException { getAndCheckSessionIDandObject(toolSessionId); throw new UnsupportedOperationException("not yet implemented"); } @SuppressWarnings("unchecked") @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws ToolException, - DataMissingException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws ToolException, DataMissingException { Iterator i = toolSessionIds.iterator(); if (i.hasNext()) { Long id = i.next(); @@ -522,10 +530,10 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return null; } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } @Override @@ -546,8 +554,8 @@ } @Override - public void setReflectiveData(Long toolContentId, String title, String description) throws ToolException, - DataMissingException { + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { NoticeboardContent toolContentObj = retrieveNoticeboard(toolContentId); if (toolContentObj == null) { @@ -638,15 +646,16 @@ // ****************** REST methods ************************* @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) + throws JSONException { Date updateDate = new Date(); NoticeboardContent noticeboard = new NoticeboardContent(); noticeboard.setNbContentId(toolContentID); noticeboard.setTitle(toolContentJSON.getString(RestTags.TITLE)); noticeboard.setContent(toolContentJSON.getString("content")); noticeboard.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - noticeboard.setReflectInstructions((String)JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null)); + noticeboard.setReflectInstructions((String) JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null)); noticeboard.setCreatorUserId(userID.longValue()); noticeboard.setDateCreated(updateDate); Index: lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/NotebookService.java =================================================================== diff -u -ra207bdecc16a704428826dbf402a97de2e35458b -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/NotebookService.java (.../NotebookService.java) (revision a207bdecc16a704428826dbf402a97de2e35458b) +++ lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/NotebookService.java (.../NotebookService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -42,6 +42,7 @@ import org.lamsfoundation.lams.learningdesign.service.IExportToolContentService; import org.lamsfoundation.lams.learningdesign.service.ImportToolContentException; import org.lamsfoundation.lams.notebook.model.NotebookEntry; +import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; import org.lamsfoundation.lams.notebook.service.ICoreNotebookService; import org.lamsfoundation.lams.rest.RestTags; import org.lamsfoundation.lams.rest.ToolRestManager; @@ -52,7 +53,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.notebook.dao.INotebookDAO; import org.lamsfoundation.lams.tool.notebook.dao.INotebookSessionDAO; @@ -99,9 +99,9 @@ private IExportToolContentService exportContentService; private ICoreNotebookService coreNotebookService; - + private IEventNotificationService eventNotificationService; - + private MessageService messageService; private NotebookOutputFactory notebookOutputFactory; @@ -136,13 +136,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -161,10 +162,10 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return getNotebookOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /* ************ Methods from ToolContentManager ************************* */ @@ -192,7 +193,7 @@ Notebook toContent = Notebook.newInstance(fromContent, toContentId); notebookDAO.saveOrUpdate(toContent); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Notebook notebook = notebookDAO.getByContentId(toolContentId); @@ -204,22 +205,39 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId) throws ToolException { + Notebook notebook = notebookDAO.getByContentId(toolContentId); + if (notebook == null) { + NotebookService.logger.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (NotebookSession session : (Set) notebook.getNotebookSessions()) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, NotebookConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); + } + } + + notebookDAO.delete(notebook); } - + + @Override @SuppressWarnings("unchecked") public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("Removing Notebook entries for user ID " + userId + " and toolContentId " + toolContentId); + if (NotebookService.logger.isDebugEnabled()) { + NotebookService.logger + .debug("Removing Notebook entries for user ID " + userId + " and toolContentId " + toolContentId); } Notebook notebook = notebookDAO.getByContentId(toolContentId); if (notebook == null) { - logger.warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); + NotebookService.logger + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } - + for (NotebookSession session : (Set) notebook.getNotebookSessions()) { NotebookUser user = notebookUserDAO.getByUserIdAndSessionId(userId.longValue(), session.getSessionId()); if (user != null) { @@ -237,11 +255,12 @@ * Export the XML fragment for the tool's content, along with any files needed for the content. * * @throws DataMissingException - * if no tool content matches the toolSessionId + * if no tool content matches the toolSessionId * @throws ToolException - * if any other error occurs + * if any other error occurs */ + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { Notebook notebook = notebookDAO.getByContentId(toolContentId); if (notebook == null) { @@ -266,19 +285,20 @@ * Import the XML fragment for the tool's content, along with any files needed for the content. * * @throws ToolException - * if any other error occurs + * if any other error occurs */ + @Override public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion, String toVersion) throws ToolException { try { // register version filter class exportContentService.registerImportVersionFilterClass(NotebookImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, notebookToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof Notebook)) { - throw new ImportToolContentException("Import Notebook tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import Notebook tool content failed. Deserialized object is " + toolPOJO); } Notebook notebook = (Notebook) toolPOJO; @@ -300,6 +320,7 @@ * * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition */ + @Override public SortedMap getToolOutputDefinitions(Long toolContentId, int definitionType) throws ToolException { Notebook notebook = getNotebookDAO().getByContentId(toolContentId); @@ -308,29 +329,35 @@ } return getNotebookOutputFactory().getToolOutputDefinitions(notebook, definitionType); } - + + @Override public String getToolContentTitle(Long toolContentId) { return getNotebookByContentId(toolContentId).getTitle(); } - + + @Override public boolean isContentEdited(Long toolContentId) { return getNotebookByContentId(toolContentId).isDefineLater(); } - + /* ********** INotebookService Methods ********************************* */ + @Override public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry) { return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); } + @Override public NotebookEntry getEntry(Long uid) { return coreNotebookService.getEntry(uid); } + @Override public void updateEntry(Long uid, String entry) { coreNotebookService.updateEntry(uid, "", entry); } + @Override public Long getDefaultContentIdBySignature(String toolSignature) { Long toolContentId = null; toolContentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature)); @@ -342,6 +369,7 @@ return toolContentId; } + @Override public Notebook getDefaultContent() { Long defaultContentID = getDefaultContentIdBySignature(NotebookConstants.TOOL_SIGNATURE); Notebook defaultContent = getNotebookByContentId(defaultContentID); @@ -357,6 +385,7 @@ return defaultContent; } + @Override public Notebook copyDefaultContent(Long newContentID) { if (newContentID == null) { @@ -373,6 +402,7 @@ return newContent; } + @Override public Notebook getNotebookByContentId(Long toolContentID) { Notebook notebook = notebookDAO.getByContentId(toolContentID); if (notebook == null) { @@ -381,6 +411,7 @@ return notebook; } + @Override public NotebookSession getSessionBySessionId(Long toolSessionId) { NotebookSession notebookSession = notebookSessionDAO.getBySessionId(toolSessionId); if (notebookSession == null) { @@ -389,6 +420,7 @@ return notebookSession; } + @Override public NotebookUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { return notebookUserDAO.getByUserIdAndSessionId(userId, toolSessionId); } @@ -397,28 +429,33 @@ return notebookUserDAO.getByLoginNameAndSessionId(loginName, toolSessionId); } + @Override public NotebookUser getUserByUID(Long uid) { return notebookUserDAO.getByUID(uid); } + @Override public void saveOrUpdateNotebook(Notebook notebook) { notebookDAO.saveOrUpdate(notebook); } + @Override public void saveOrUpdateNotebookSession(NotebookSession notebookSession) { notebookSessionDAO.saveOrUpdate(notebookSession); } + @Override public void saveOrUpdateNotebookUser(NotebookUser notebookUser) { notebookUserDAO.saveOrUpdate(notebookUser); } + @Override public NotebookUser createNotebookUser(UserDTO user, NotebookSession notebookSession) { NotebookUser notebookUser = new NotebookUser(user, notebookSession); saveOrUpdateNotebookUser(notebookUser); return notebookUser; } - + @Override public boolean notifyUser(Integer userId, String comment) { boolean isHtmlFormat = false; @@ -437,15 +474,16 @@ /** * Import the data for a 1.0.2 Notebook */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { Date now = new Date(); Notebook notebook = new Notebook(); notebook.setContentInUse(Boolean.FALSE); notebook.setCreateBy(new Long(user.getUserID().longValue())); notebook.setCreateDate(now); notebook.setDefineLater(Boolean.FALSE); - notebook.setInstructions(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); + notebook.setInstructions( + WebUtil.convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY))); notebook.setLockOnFinished(Boolean.TRUE); notebook.setTitle((String) importValues.get(ToolContentImport102Manager.CONTENT_TITLE)); notebook.setToolContentId(toolContentId); @@ -457,11 +495,12 @@ } /** 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { - NotebookService.logger - .warn("Setting the reflective field on a notebook. This doesn't make sense as the notebook is for reflection and we don't reflect on reflection!"); + NotebookService.logger.warn( + "Setting the reflective field on a notebook. This doesn't make sense as the notebook is for reflection and we don't reflect on reflection!"); Notebook notebook = getNotebookByContentId(toolContentId); if (notebook == null) { throw new DataMissingException("Unable to set reflective data titled " + title @@ -545,11 +584,11 @@ public void setCoreNotebookService(ICoreNotebookService coreNotebookService) { this.coreNotebookService = coreNotebookService; } - + public void setEventNotificationService(IEventNotificationService eventNotificationService) { this.eventNotificationService = eventNotificationService; } - + public void setMessageService(MessageService messageService) { this.messageService = messageService; } @@ -565,6 +604,7 @@ /** * {@inheritDoc} */ + @Override public String createConditionName(Collection existingConditions) { String uniqueNumber = null; do { @@ -579,6 +619,7 @@ return getNotebookOutputFactory().buildUserEntryConditionName(uniqueNumber); } + @Override public void releaseConditionsFromCache(Notebook notebook) { if (notebook.getConditions() != null) { for (NotebookCondition condition : notebook.getConditions()) { @@ -587,8 +628,9 @@ } } + @Override public void deleteCondition(NotebookCondition condition) { - if (condition != null && condition.getConditionId() != null) { + if ((condition != null) && (condition.getConditionId() != null)) { notebookDAO.delete(condition); } } @@ -597,22 +639,25 @@ public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public String getLearnerContentFolder(Long toolSessionId, Long userId) { return toolService.getLearnerContentFolder(toolSessionId, userId); } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getNotebookOutputFactory().getSupportedDefinitionClasses(definitionType); } - + // ****************** REST methods ************************* - /** Rest call to create a new Notebook content. Required fields in toolContentJSON: "title", "instructions". + /** + * Rest call to create a new Notebook content. Required fields in toolContentJSON: "title", "instructions". */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) + throws JSONException { Date updateDate = new Date(); Notebook nb = new Notebook(); @@ -630,10 +675,10 @@ nb.setContentInUse(false); nb.setDefineLater(false); this.saveOrUpdateNotebook(nb); - + // TODO // nb.setConditions(conditions); - + } - + } \ No newline at end of file Index: lams_tool_pixlr/src/java/org/lamsfoundation/lams/tool/pixlr/service/PixlrService.java =================================================================== diff -u -ra207bdecc16a704428826dbf402a97de2e35458b -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_pixlr/src/java/org/lamsfoundation/lams/tool/pixlr/service/PixlrService.java (.../PixlrService.java) (revision a207bdecc16a704428826dbf402a97de2e35458b) +++ lams_tool_pixlr/src/java/org/lamsfoundation/lams/tool/pixlr/service/PixlrService.java (.../PixlrService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -26,28 +26,14 @@ import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; -import java.io.IOException; import java.util.Date; import java.util.Hashtable; import java.util.List; import java.util.SortedMap; -import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; -import org.apache.struts.upload.FormFile; -import org.lamsfoundation.lams.contentrepository.AccessDeniedException; -import org.lamsfoundation.lams.contentrepository.ICredentials; -import org.lamsfoundation.lams.contentrepository.ITicket; -import org.lamsfoundation.lams.contentrepository.InvalidParameterException; -import org.lamsfoundation.lams.contentrepository.LoginException; -import org.lamsfoundation.lams.contentrepository.NodeKey; -import org.lamsfoundation.lams.contentrepository.RepositoryCheckedException; -import org.lamsfoundation.lams.contentrepository.WorkspaceNotFoundException; import org.lamsfoundation.lams.contentrepository.client.IToolContentHandler; -import org.lamsfoundation.lams.contentrepository.service.IRepositoryService; -import org.lamsfoundation.lams.contentrepository.service.SimpleCredentials; import org.lamsfoundation.lams.learning.service.ILearnerService; import org.lamsfoundation.lams.learningdesign.service.ExportToolContentException; import org.lamsfoundation.lams.learningdesign.service.IExportToolContentService; @@ -74,7 +60,6 @@ import org.lamsfoundation.lams.tool.pixlr.model.PixlrUser; import org.lamsfoundation.lams.tool.pixlr.util.PixlrConstants; import org.lamsfoundation.lams.tool.pixlr.util.PixlrException; -import org.lamsfoundation.lams.tool.pixlr.util.PixlrToolContentHandler; import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.usermanagement.User; import org.lamsfoundation.lams.usermanagement.dto.UserDTO; @@ -90,7 +75,8 @@ * As a requirement, all LAMS tool's service bean must implement ToolContentManager and ToolSessionManager. */ -public class PixlrService implements ToolSessionManager, ToolContentManager, IPixlrService, ToolContentImport102Manager { +public class PixlrService + implements ToolSessionManager, ToolContentManager, IPixlrService, ToolContentImport102Manager { private static Logger logger = Logger.getLogger(PixlrService.class.getName()); @@ -123,7 +109,7 @@ } /* ************ Methods from ToolSessionManager ************* */ - + @Override public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException { if (PixlrService.logger.isDebugEnabled()) { @@ -147,14 +133,15 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override @SuppressWarnings("unchecked") - public ToolSessionExportOutputData exportToolSession(List ToolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List ToolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -173,14 +160,14 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return getPixlrOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /* ************ Methods from ToolContentManager ************************* */ - + @Override public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { @@ -267,14 +254,30 @@ pixlrDAO.saveOrUpdate(pixlr); } - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { - // TODO Auto-generated method stub + @Override + public void removeToolContent(Long toolContentId) throws SessionDataExistsException, ToolException { + Pixlr pixlr = pixlrDAO.getByContentId(toolContentId); + if (pixlr == null) { + PixlrService.logger.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (PixlrSession session : pixlr.getPixlrSessions()) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, PixlrConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); + } + } + + pixlrDAO.delete(pixlr); } + @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("Removing Pixlr image for user ID " + userId + " and toolContentId " + toolContentId); + if (PixlrService.logger.isDebugEnabled()) { + PixlrService.logger + .debug("Removing Pixlr image for user ID " + userId + " and toolContentId " + toolContentId); Pixlr pixlr = pixlrDAO.getByContentId(toolContentId); if (pixlr != null) { @@ -296,11 +299,12 @@ * Export the XML fragment for the tool's content, along with any files needed for the content. * * @throws DataMissingException - * if no tool content matches the toolSessionId + * if no tool content matches the toolSessionId * @throws ToolException - * if any other error occurs + * if any other error occurs */ + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { Pixlr pixlr = pixlrDAO.getByContentId(toolContentId); if (pixlr == null) { @@ -316,8 +320,8 @@ // bundling the author image in export try { if (pixlr.getImageFileName() != null) { - File imageFile = new File(PixlrConstants.LAMS_PIXLR_BASE_DIR + File.separator - + pixlr.getImageFileName()); + File imageFile = new File( + PixlrConstants.LAMS_PIXLR_BASE_DIR + File.separator + pixlr.getImageFileName()); if (imageFile.exists()) { String ext = getFileExtension(pixlr.getImageFileName()); @@ -349,19 +353,20 @@ * Import the XML fragment for the tool's content, along with any files needed for the content. * * @throws ToolException - * if any other error occurs + * if any other error occurs */ + @Override public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion, String toVersion) throws ToolException { try { // register version filter class exportContentService.registerImportVersionFilterClass(PixlrImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, pixlrToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof Pixlr)) { - throw new ImportToolContentException("Import Pixlr tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import Pixlr tool content failed. Deserialized object is " + toolPOJO); } Pixlr pixlr = (Pixlr) toolPOJO; @@ -394,10 +399,11 @@ } } + @Override public String getFileExtension(String fileName) { String ext = ""; int i = fileName.lastIndexOf('.'); - if (i > 0 && i < fileName.length() - 1) { + if ((i > 0) && (i < (fileName.length() - 1))) { ext += "." + fileName.substring(i + 1).toLowerCase(); } return ext; @@ -411,6 +417,7 @@ * * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition */ + @Override public SortedMap getToolOutputDefinitions(Long toolContentId, int definitionType) throws ToolException { Pixlr pixlr = getPixlrDAO().getByContentId(toolContentId); @@ -419,24 +426,28 @@ } return getPixlrOutputFactory().getToolOutputDefinitions(pixlr, definitionType); } - + + @Override public String getToolContentTitle(Long toolContentId) { return getPixlrByContentId(toolContentId).getTitle(); } - + + @Override public boolean isContentEdited(Long toolContentId) { return getPixlrByContentId(toolContentId).isDefineLater(); } /* ********** IPixlrService Methods ********************************* */ + @Override public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry) { return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); } + @Override public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(sessionId, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -446,10 +457,12 @@ /** * @param notebookEntry */ + @Override public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } + @Override public Long getDefaultContentIdBySignature(String toolSignature) { Long toolContentId = null; toolContentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature)); @@ -461,6 +474,7 @@ return toolContentId; } + @Override public Pixlr getDefaultContent() { Long defaultContentID = getDefaultContentIdBySignature(PixlrConstants.TOOL_SIGNATURE); Pixlr defaultContent = getPixlrByContentId(defaultContentID); @@ -472,6 +486,7 @@ return defaultContent; } + @Override public Pixlr copyDefaultContent(Long newContentID) { if (newContentID == null) { @@ -488,6 +503,7 @@ return newContent; } + @Override public Pixlr getPixlrByContentId(Long toolContentID) { Pixlr pixlr = pixlrDAO.getByContentId(toolContentID); if (pixlr == null) { @@ -496,6 +512,7 @@ return pixlr; } + @Override public PixlrSession getSessionBySessionId(Long toolSessionId) { PixlrSession pixlrSession = pixlrSessionDAO.getBySessionId(toolSessionId); if (pixlrSession == null) { @@ -504,6 +521,7 @@ return pixlrSession; } + @Override public PixlrUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { return pixlrUserDAO.getByUserIdAndSessionId(userId, toolSessionId); } @@ -512,22 +530,27 @@ return pixlrUserDAO.getByLoginNameAndSessionId(loginName, toolSessionId); } + @Override public PixlrUser getUserByUID(Long uid) { return pixlrUserDAO.getByUID(uid); } + @Override public void saveOrUpdatePixlr(Pixlr pixlr) { pixlrDAO.saveOrUpdate(pixlr); } + @Override public void saveOrUpdatePixlrSession(PixlrSession pixlrSession) { pixlrSessionDAO.saveOrUpdate(pixlrSession); } + @Override public void saveOrUpdatePixlrUser(PixlrUser pixlrUser) { pixlrUserDAO.saveOrUpdate(pixlrUser); } + @Override public PixlrUser createPixlrUser(UserDTO user, PixlrSession pixlrSession) { PixlrUser pixlrUser = new PixlrUser(user, pixlrSession); saveOrUpdatePixlrUser(pixlrUser); @@ -541,15 +564,18 @@ public void setAuditService(IAuditService auditService) { this.auditService = auditService; } - + + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } + @Override public PixlrConfigItem getConfigItem(String key) { return pixlrConfigItemDAO.getConfigItemByKey(key); } + @Override public void saveOrUpdatePixlrConfigItem(PixlrConfigItem item) { pixlrConfigItemDAO.saveOrUpdate(item); } @@ -559,6 +585,7 @@ /** * Import the data for a 1.0.2 Pixlr */ + @Override @SuppressWarnings("unchecked") public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { Date now = new Date(); @@ -567,8 +594,8 @@ pixlr.setCreateBy(new Long(user.getUserID().longValue())); pixlr.setCreateDate(now); pixlr.setDefineLater(Boolean.FALSE); - pixlr.setInstructions(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); + pixlr.setInstructions( + WebUtil.convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY))); pixlr.setLockOnFinished(Boolean.TRUE); pixlr.setTitle((String) importValues.get(ToolContentImport102Manager.CONTENT_TITLE)); pixlr.setToolContentId(toolContentId); @@ -583,11 +610,12 @@ /** * 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { - PixlrService.logger - .warn("Setting the reflective field on a pixlr. This doesn't make sense as the pixlr is for reflection and we don't reflect on reflection!"); + PixlrService.logger.warn( + "Setting the reflective field on a pixlr. This doesn't make sense as the pixlr is for reflection and we don't reflect on reflection!"); Pixlr pixlr = getPixlrByContentId(toolContentId); if (pixlr == null) { throw new DataMissingException("Unable to set reflective data titled " + title @@ -680,6 +708,7 @@ this.pixlrConfigItemDAO = pixlrConfigItemDAO; } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getPixlrOutputFactory().getSupportedDefinitionClasses(definitionType); } Index: lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/SubmitFilesService.java =================================================================== diff -u -ra789c1395e0f8c1f0ded10147c464574c979b69c -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/SubmitFilesService.java (.../SubmitFilesService.java) (revision a789c1395e0f8c1f0ded10147c464574c979b69c) +++ lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/SubmitFilesService.java (.../SubmitFilesService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -79,7 +79,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.sbmt.SubmissionDetails; import org.lamsfoundation.lams.tool.sbmt.SubmitFilesContent; @@ -148,11 +147,13 @@ private class FileDtoComparator implements Comparator { + @Override public int compare(FileDetailsDTO o1, FileDetailsDTO o2) { - if (o1 != null && o2 != null && o1.getDateOfSubmission() != null && o2.getDateOfSubmission() != null) { + 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; + return (o1.getDateOfSubmission().getTime() - o2.getDateOfSubmission().getTime()) > 0 ? 1 : -1; } else if (o1 != null) { return 1; } else { @@ -162,21 +163,24 @@ } + @Override public Long createNotebookEntry(Long sessionId, Integer notebookToolType, String toolSignature, Integer userId, String entryText) { return coreNotebookService.createNotebookEntry(sessionId, notebookToolType, toolSignature, userId, "", entryText); } + @Override public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(sessionId, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); } } + @Override public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } @@ -198,7 +202,7 @@ submitFilesContentDAO.saveOrUpdate(toContent); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { SubmitFilesContent content = getSubmitFilesContent(toolContentId); @@ -210,28 +214,29 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException { + public void removeToolContent(Long toolContentId) throws ToolException { 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); - } + if (submitFilesContent == null) { + SubmitFilesService.log.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (SubmitFilesSession session : submitFilesSessionDAO.getSubmitFilesSessionByContentID(toolContentId)) { + List entries = coreNotebookService.getEntry(session.getSessionID(), + CoreNotebookConstants.NOTEBOOK_TOOL, SbmtConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); } - submitFilesContentDAO.delete(submitFilesContent); } + + submitFilesContentDAO.delete(submitFilesContent); } - + + @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (log.isDebugEnabled()) { - log.debug("Removing Submit Files content for user ID " + userId + " and toolContentId " + toolContentId); + if (SubmitFilesService.log.isDebugEnabled()) { + SubmitFilesService.log.debug( + "Removing Submit Files content for user ID " + userId + " and toolContentId " + toolContentId); } List sessions = submitFilesSessionDAO.getSubmitFilesSessionByContentID(toolContentId); @@ -255,6 +260,7 @@ } } + @Override public List getSessionsByContentID(Long toolContentID) { return submitFilesSessionDAO.getSubmitFilesSessionByContentID(toolContentID); } @@ -264,6 +270,7 @@ * * @throws ExportToolContentException */ + @Override public void exportToolContent(Long toolContentId, String toPath) throws ToolException, DataMissingException { SubmitFilesContent toolContentObj = submitFilesContentDAO.getContentByID(toolContentId); if (toolContentObj == null) { @@ -282,18 +289,19 @@ } } + @Override public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion, String toVersion) throws ToolException { try { // register version filter class exportContentService.registerImportVersionFilterClass(SubmitFilesImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, sbmtToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof SubmitFilesContent)) { - throw new ImportToolContentException("Import Submit tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import Submit tool content failed. Deserialized object is " + toolPOJO); } SubmitFilesContent toolContentObj = (SubmitFilesContent) toolPOJO; @@ -330,6 +338,7 @@ * * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition */ + @Override public SortedMap getToolOutputDefinitions(Long toolContentId, int definitionType) throws ToolException { SubmitFilesContent content = getSubmitFilesContent(toolContentId); @@ -338,15 +347,17 @@ } return getSubmitFilesOutputFactory().getToolOutputDefinitions(content, definitionType); } - + + @Override public String getToolContentTitle(Long toolContentId) { return getSubmitFilesContent(toolContentId).getTitle(); } - + + @Override public boolean isContentEdited(Long toolContentId) { return getSubmitFilesContent(toolContentId).isDefineLater(); } - + @Override public void saveOrUpdateContent(SubmitFilesContent submitFilesContent) { submitFilesContent.setUpdated(new Date()); @@ -401,24 +412,24 @@ try { repositoryService.deleteVersion(ticket, uuid, versionID); } catch (Exception e) { - throw new SubmitFilesException("Exception occured while deleting files from" + " the repository " - + e.getMessage()); + throw new SubmitFilesException( + "Exception occured while deleting files from" + " the repository " + e.getMessage()); } } @Override 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"); + 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())) { + if ((submitContent == null) || !toolContentId.equals(submitContent.getContentID())) { submitContent = new SubmitFilesContent(); submitContent.setContentID(toolContentId); } @@ -431,8 +442,8 @@ 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); + throw new SubmitFilesException( + "Exception occured when lams is creating" + " a submission Session: " + e.getMessage(), e); } } @@ -509,17 +520,17 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return getSubmitFilesOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } @Override public void uploadFileToSession(Long sessionID, FormFile uploadFile, String fileDescription, Integer userID) throws SubmitFilesException { - if (uploadFile == null || StringUtils.isEmpty(uploadFile.getFileName())) { + if ((uploadFile == null) || StringUtils.isEmpty(uploadFile.getFileName())) { throw new SubmitFilesException("Could not find upload file: " + uploadFile); } @@ -562,22 +573,22 @@ */ private NodeKey processFile(FormFile file) { NodeKey node = null; - if (file != null && !StringUtils.isEmpty(file.getFileName())) { + if ((file != null) && !StringUtils.isEmpty(file.getFileName())) { String fileName = file.getFileName(); try { node = getSbmtToolContentHandler().uploadFile(file.getInputStream(), fileName, file.getContentType()); } catch (InvalidParameterException e) { - throw new SubmitFilesException("FileNotFoundException occured while trying to upload File" - + e.getMessage()); + 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()); + 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()); + 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()); + throw new SubmitFilesException( + "FileNotFoundException occured while trying to upload File" + e.getMessage()); } } return node; @@ -589,6 +600,7 @@ * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#getFilesUploadedByUserForContent(java.lang.Long, * java.lang.Long) */ + @Override public List getFilesUploadedByUser(Integer userID, Long sessionID, Locale currentLocale) { List list = submissionDetailsDAO.getBySessionAndLearner(sessionID, userID); SortedSet details = new TreeSet(this.new FileDtoComparator()); @@ -608,6 +620,7 @@ * 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. */ + @Override public SortedMap getFilesUploadedBySession(Long sessionID, Locale currentLocale) { List list = submissionDetailsDAO.getSubmissionDetailsBySession(sessionID); if (list != null) { @@ -619,8 +632,8 @@ SubmissionDetails submissionDetails = (SubmissionDetails) iterator.next(); SubmitUser learner = submissionDetails.getLearner(); if (learner == null) { - SubmitFilesService.log.error("Could not find learer for special submission item:" - + submissionDetails); + SubmitFilesService.log + .error("Could not find learer for special submission item:" + submissionDetails); return null; } SubmitUserDTO submitUserDTO = new SubmitUserDTO(learner); @@ -640,6 +653,7 @@ } } + @Override public FileDetailsDTO getFileDetails(Long detailID, Locale currentLocale) { SubmissionDetails details = submissionDetailsDAO.getSubmissionDetailsByID(detailID); return new FileDetailsDTO(details, currentLocale != null ? NumberFormat.getInstance(currentLocale) : null); @@ -650,10 +664,12 @@ * * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#getUsersBySession(java.lang.Long) */ + @Override public List getUsersBySession(Long sessionID) { return submitUserDAO.getUsersBySession(sessionID); } + @Override public void updateMarks(Long reportID, Float marks, String comments, FormFile markFile) throws InvalidParameterException, RepositoryCheckedException { @@ -664,7 +680,7 @@ report.setMarks(marks); // If there is a new file, delete the existing and add the mark file - if (markFile != null && !StringUtils.isEmpty(markFile.getFileName())) { + if ((markFile != null) && !StringUtils.isEmpty(markFile.getFileName())) { // Delete the existing if (report.getMarkFileUUID() != null) { @@ -689,6 +705,7 @@ } + @Override public void removeMarkFile(Long reportID, Long markFileUUID, Long markFileVersionID) { SubmitFilesReport report = submitFilesReportDAO.getReportByID(reportID); if (report != null) { @@ -700,26 +717,29 @@ } } + @Override 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()); + 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()); + throw new SubmitFilesException( + "ItemNotFoundException occured while trying to download file " + ie.getMessage()); } } + @Override public SubmitFilesSession getSessionById(Long sessionID) { return submitFilesSessionDAO.getSessionByID(sessionID); } + @Override public boolean releaseMarksForSession(Long sessionID) { List list = submissionDetailsDAO.getSubmissionDetailsBySession(sessionID); Iterator iter = list.iterator(); @@ -779,6 +799,7 @@ return true; } + @Override public void finishSubmission(Long sessionID, Integer userID) { SubmitUser learner = submitUserDAO.getLearner(sessionID, userID); learner.setFinished(true); @@ -794,8 +815,8 @@ @SuppressWarnings("unchecked") public void sendMarksToGradebook(SubmitUser user, Long toolSessionID) { submissionDetailsDAO.getSubmissionDetailsBySession(toolSessionID); - List detailsList = submissionDetailsDAO.getBySessionAndLearner(toolSessionID, user - .getUserID()); + List detailsList = submissionDetailsDAO.getBySessionAndLearner(toolSessionID, + user.getUserID()); if (detailsList != null) { Float totalMark = null; for (SubmissionDetails details : detailsList) { @@ -821,6 +842,7 @@ * * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#getToolDefaultContentIdBySignature(java.lang.Long) */ + @Override public Long getToolDefaultContentIdBySignature(String toolSignature) { Long contentId = null; contentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature)); @@ -837,6 +859,7 @@ * * @see org.lamsfoundation.lams.tool.sbmt.service.ISubmitFilesService#createDefaultContent(java.lang.Long) */ + @Override public SubmitFilesContent createDefaultContent(Long contentID) { if (contentID == null) { String error = "Could not retrieve default content id for this tool"; @@ -864,14 +887,16 @@ return defaultContent; } + @Override 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; } - + + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } @@ -881,6 +906,7 @@ /** * Import the data for a 1.0.2 Noticeboard or HTMLNoticeboard */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { Date now = new Date(); SubmitFilesContent toolContentObj = new SubmitFilesContent(); @@ -890,8 +916,8 @@ toolContentObj.setContentInUse(Boolean.FALSE); toolContentObj.setCreated(now); toolContentObj.setDefineLater(Boolean.FALSE); - toolContentObj.setInstruction(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); + toolContentObj.setInstruction( + WebUtil.convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY))); 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); @@ -910,8 +936,9 @@ /** * 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { SubmitFilesContent toolContentObj = getSubmitFilesContent(toolContentId); if (toolContentObj == null) { @@ -923,11 +950,13 @@ toolContentObj.setReflectInstructions(description); } + @Override public SubmitUser getUserByUid(Long learnerID) { return (SubmitUser) submitUserDAO.find(SubmitUser.class, learnerID); } + @Override public SubmitUser createSessionUser(UserDTO userDto, Long sessionID) { SubmitUser learner = submitUserDAO.getLearner(sessionID, userDto.getUserID()); if (learner != null) { @@ -946,11 +975,13 @@ return learner; } + @Override public SubmitUser getSessionUser(Long sessionID, Integer userID) { return submitUserDAO.getLearner(sessionID, userID); } - public SubmitUser createContentUser(Integer userId, String firstName, String lastName, String loginName, Long contentId) { + public SubmitUser createContentUser(Integer userId, String firstName, String lastName, String loginName, + Long contentId) { SubmitUser author = submitUserDAO.getContentUser(contentId, userId); if (author != null) { return author; @@ -968,6 +999,7 @@ } + @Override public SubmitUser createContentUser(UserDTO userDto, Long contentId) { SubmitUser learner = submitUserDAO.getContentUser(contentId, userDto.getUserID()); if (learner != null) { @@ -986,6 +1018,7 @@ } + @Override public SubmitUser getContentUser(Long contentId, Integer userID) { return submitUserDAO.getContentUser(contentId, userID); } @@ -996,31 +1029,31 @@ /** * @param submitFilesContentDAO - * The submitFilesContentDAO to set. + * The submitFilesContentDAO to set. */ public void setSubmitFilesContentDAO(ISubmitFilesContentDAO submitFilesContentDAO) { this.submitFilesContentDAO = submitFilesContentDAO; } /** * @param submitFilesReportDAO - * The submitFilesReportDAO to set. + * The submitFilesReportDAO to set. */ public void setSubmitFilesReportDAO(ISubmitFilesReportDAO submitFilesReportDAO) { this.submitFilesReportDAO = submitFilesReportDAO; } /** * @param submitFilesSessionDAO - * The submitFilesSessionDAO to set. + * The submitFilesSessionDAO to set. */ public void setSubmitFilesSessionDAO(ISubmitFilesSessionDAO submitFilesSessionDAO) { this.submitFilesSessionDAO = submitFilesSessionDAO; } /** * @param submissionDetailsDAO - * The submissionDetailsDAO to set. + * The submissionDetailsDAO to set. */ public void setSubmissionDetailsDAO(ISubmissionDetailsDAO submissionDetailsDAO) { this.submissionDetailsDAO = submissionDetailsDAO; @@ -1035,7 +1068,7 @@ /** * @param sbmtToolContentHandler - * The sbmtToolContentHandler to set. + * The sbmtToolContentHandler to set. */ public void setSbmtToolContentHandler(IToolContentHandler sbmtToolContentHandler) { this.sbmtToolContentHandler = sbmtToolContentHandler; @@ -1050,7 +1083,7 @@ /** * @param learnerDAO - * The learnerDAO to set. + * The learnerDAO to set. */ public void setSubmitUserDAO(ISubmitUserDAO learnerDAO) { submitUserDAO = learnerDAO; @@ -1100,6 +1133,7 @@ this.userManagementService = userManagementService; } + @Override public IEventNotificationService getEventNotificationService() { return eventNotificationService; } @@ -1108,6 +1142,7 @@ this.eventNotificationService = eventNotificationService; } + @Override public String getLocalisedMessage(String key, Object[] args) { return messageService.getMessage(key, args); } @@ -1120,6 +1155,7 @@ this.gradebookService = gradebookService; } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getSubmitFilesOutputFactory().getSupportedDefinitionClasses(definitionType); @@ -1132,14 +1168,15 @@ public void setSubmitFilesOutputFactory(SubmitFilesOutputFactory submitFilesOutputFactory) { this.submitFilesOutputFactory = submitFilesOutputFactory; } - + // ****************** REST methods ************************* - /** Used by the Rest calls to create content. - * Mandatory fields in toolContentJSON: title, instructions + /** + * Used by the Rest calls to create content. Mandatory fields in toolContentJSON: title, instructions */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) + throws JSONException { SubmitFilesContent content = new SubmitFilesContent(); Date updateDate = new Date(); @@ -1149,11 +1186,13 @@ content.setContentID(toolContentID); content.setTitle(toolContentJSON.getString(RestTags.TITLE)); content.setInstruction(toolContentJSON.getString(RestTags.INSTRUCTIONS)); - + content.setContentInUse(false); content.setDefineLater(false); - content.setNotifyTeachersOnFileSubmit(JsonUtil.opt(toolContentJSON, "notifyTeachersOnFileSubmit", Boolean.FALSE)); - content.setNotifyLearnersOnMarkRelease(JsonUtil.opt(toolContentJSON, "notifyLearnersOnMarkRelease", Boolean.FALSE)); + content.setNotifyTeachersOnFileSubmit( + JsonUtil.opt(toolContentJSON, "notifyTeachersOnFileSubmit", Boolean.FALSE)); + content.setNotifyLearnersOnMarkRelease( + JsonUtil.opt(toolContentJSON, "notifyLearnersOnMarkRelease", Boolean.FALSE)); content.setReflectInstructions((String) JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null)); content.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); content.setLockOnFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); @@ -1163,7 +1202,8 @@ SubmitUser user = getContentUser(toolContentID, userID); if (user == null) { - user = createContentUser(userID, toolContentJSON.getString("firstName"), toolContentJSON.getString("lastName"),toolContentJSON.getString("loginName"), toolContentID); + user = createContentUser(userID, toolContentJSON.getString("firstName"), + toolContentJSON.getString("lastName"), toolContentJSON.getString("loginName"), toolContentID); } content.setCreatedBy(user); saveOrUpdateContent(content); Index: lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/service/ScratchieServiceImpl.java =================================================================== diff -u -rc93c1eaabb8c79d6f2bb3f31872e262e52e271af -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/service/ScratchieServiceImpl.java (.../ScratchieServiceImpl.java) (revision c93c1eaabb8c79d6f2bb3f31872e262e52e271af) +++ lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/service/ScratchieServiceImpl.java (.../ScratchieServiceImpl.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -40,7 +40,6 @@ import java.util.Set; import java.util.SortedMap; import java.util.TreeSet; -import java.util.concurrent.Callable; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; @@ -67,7 +66,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.scratchie.ScratchieConstants; import org.lamsfoundation.lams.tool.scratchie.dao.ScratchieAnswerVisitDAO; @@ -90,9 +88,7 @@ import org.lamsfoundation.lams.tool.scratchie.model.ScratchieUser; import org.lamsfoundation.lams.tool.scratchie.util.ScratchieAnswerComparator; import org.lamsfoundation.lams.tool.scratchie.util.ScratchieItemComparator; -import org.lamsfoundation.lams.tool.scratchie.util.ScratchieSessionComparator; import org.lamsfoundation.lams.tool.scratchie.util.ScratchieToolContentHandler; -import org.lamsfoundation.lams.tool.scratchie.web.action.LearningAction; import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.usermanagement.User; import org.lamsfoundation.lams.usermanagement.dto.UserDTO; @@ -207,7 +203,7 @@ @Override public void releaseItemsFromCache(Scratchie scratchie) { - for (ScratchieItem item : (Set) scratchie.getScratchieItems()) { + for (ScratchieItem item : scratchie.getScratchieItems()) { scratchieItemDao.releaseItemFromCache(item); } } @@ -1770,23 +1766,29 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) - throws SessionDataExistsException, ToolException { + public void removeToolContent(Long toolContentId) throws ToolException { Scratchie scratchie = scratchieDao.getByContentId(toolContentId); - if (removeSessionData) { - List list = scratchieSessionDao.getByContentId(toolContentId); - Iterator iter = list.iterator(); - while (iter.hasNext()) { - ScratchieSession session = (ScratchieSession) iter.next(); - scratchieSessionDao.delete(session); + if (scratchie == null) { + ScratchieServiceImpl.log.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (ScratchieSession session : scratchieSessionDao.getByContentId(toolContentId)) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, ScratchieConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); } } + scratchieDao.delete(scratchie); } + @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (log.isDebugEnabled()) { - log.debug("Removing Scratchie content for user ID " + userId + " and toolContentId " + toolContentId); + if (ScratchieServiceImpl.log.isDebugEnabled()) { + ScratchieServiceImpl.log + .debug("Removing Scratchie content for user ID " + userId + " and toolContentId " + toolContentId); } List sessions = scratchieSessionDao.getByContentId(toolContentId); @@ -1801,7 +1803,7 @@ scratchieDao.removeObject(NotebookEntry.class, entry.getUid()); } - if (session.getGroupLeader() != null && session.getGroupLeader().getUid().equals(user.getUid())) { + if ((session.getGroupLeader() != null) && session.getGroupLeader().getUid().equals(user.getUid())) { session.setGroupLeader(null); } @@ -2034,7 +2036,7 @@ // set options Set newAnswers = new LinkedHashSet(); - JSONArray answersData = (JSONArray) questionData.getJSONArray(RestTags.ANSWERS); + JSONArray answersData = questionData.getJSONArray(RestTags.ANSWERS); for (int j = 0; j < answersData.length(); j++) { JSONObject answerData = (JSONObject) answersData.get(j); ScratchieAnswer answer = new ScratchieAnswer(); Index: lams_tool_scribe/src/java/org/lamsfoundation/lams/tool/scribe/service/ScribeService.java =================================================================== diff -u -ra207bdecc16a704428826dbf402a97de2e35458b -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_scribe/src/java/org/lamsfoundation/lams/tool/scribe/service/ScribeService.java (.../ScribeService.java) (revision a207bdecc16a704428826dbf402a97de2e35458b) +++ lams_tool_scribe/src/java/org/lamsfoundation/lams/tool/scribe/service/ScribeService.java (.../ScribeService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -54,7 +54,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.scribe.dao.IScribeDAO; import org.lamsfoundation.lams.tool.scribe.dao.IScribeHeadingDAO; @@ -81,8 +80,8 @@ * As a requirement, all LAMS tool's service bean must implement ToolContentManager and ToolSessionManager. */ -public class ScribeService implements ToolSessionManager, ToolContentManager, ToolContentImport102Manager, ToolRestManager, - IScribeService { +public class ScribeService implements ToolSessionManager, ToolContentManager, ToolContentImport102Manager, + ToolRestManager, IScribeService { private static Logger logger = Logger.getLogger(ScribeService.class.getName()); @@ -109,7 +108,7 @@ } /* ************ Methods from ToolSessionManager ************* */ - + @Override public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException { if (ScribeService.logger.isDebugEnabled()) { @@ -134,13 +133,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -159,10 +159,10 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return null; } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /* ************ Methods from ToolContentManager ************************* */ @@ -191,7 +191,7 @@ Scribe toContent = Scribe.newInstance(fromContent, toContentId); scribeDAO.saveOrUpdate(toContent); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Scribe scribe = scribeDAO.getByContentId(toolContentId); @@ -202,27 +202,43 @@ scribeDAO.saveOrUpdate(scribe); } + @SuppressWarnings("unchecked") @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { - // TODO Auto-generated method stub + public void removeToolContent(Long toolContentId) throws ToolException { + Scribe scribe = scribeDAO.getByContentId(toolContentId); + if (scribe == null) { + ScribeService.logger.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (ScribeSession session : (Set) scribe.getScribeSessions()) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, ScribeConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); + } + } + + scribeDAO.delete(scribe); } - + @Override @SuppressWarnings("unchecked") public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("Removing Scribe contents for user ID " + userId + " and toolContentId " + toolContentId); + if (ScribeService.logger.isDebugEnabled()) { + ScribeService.logger + .debug("Removing Scribe contents for user ID " + userId + " and toolContentId " + toolContentId); } Scribe scribe = scribeDAO.getByContentId(toolContentId); if (scribe == null) { - logger.warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); + ScribeService.logger + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } for (ScribeSession session : (Set) scribe.getScribeSessions()) { - if (session.getAppointedScribe() != null + if ((session.getAppointedScribe() != null) && session.getAppointedScribe().getUserId().equals(userId.longValue())) { for (ScribeUser user : (Set) session.getScribeUsers()) { @@ -253,7 +269,7 @@ } } } - + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { Scribe scribe = scribeDAO.getByContentId(toolContentId); @@ -287,12 +303,12 @@ try { // register version filter class exportContentService.registerImportVersionFilterClass(ScribeImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, scribeToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof Scribe)) { - throw new ImportToolContentException("Import Scribe tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import Scribe tool content failed. Deserialized object is " + toolPOJO); } Scribe scribe = (Scribe) toolPOJO; @@ -311,27 +327,27 @@ throws ToolException { return new TreeMap(); } - + @Override public String getToolContentTitle(Long toolContentId) { return getScribeByContentId(toolContentId).getTitle(); } - + @Override public boolean isContentEdited(Long toolContentId) { return getScribeByContentId(toolContentId).isDefineLater(); } - - + /* ********** IScribeService Methods ************************************** */ + @Override public void createReportEntry(Long toolSessionId) { // creating scribeReports for each heading and add to session. ScribeSession session = scribeSessionDAO.getBySessionId(toolSessionId); // these heading report already copied from content, the skipit. Set entries = session.getScribeReportEntries(); - if (entries != null && entries.size() > 0) { + if ((entries != null) && (entries.size() > 0)) { return; } @@ -353,11 +369,13 @@ } + @Override public void deleteHeadingReport(Long uid) { scribeHeadingDAO.deleteReport(uid); } + @Override public Long getDefaultContentIdBySignature(String toolSignature) { Long toolContentId = null; toolContentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature)); @@ -369,6 +387,7 @@ return toolContentId; } + @Override public Scribe getDefaultContent() { Long defaultContentID = getDefaultContentIdBySignature(ScribeConstants.TOOL_SIGNATURE); Scribe defaultContent = getScribeByContentId(defaultContentID); @@ -380,6 +399,7 @@ return defaultContent; } + @Override public Scribe copyDefaultContent(Long newContentID) { if (newContentID == null) { @@ -396,6 +416,7 @@ return newContent; } + @Override public Scribe getScribeByContentId(Long toolContentID) { Scribe scribe = scribeDAO.getByContentId(toolContentID); if (scribe == null) { @@ -404,6 +425,7 @@ return scribe; } + @Override public ScribeSession getSessionBySessionId(Long toolSessionId) { ScribeSession scribeSession = scribeSessionDAO.getBySessionId(toolSessionId); if (scribeSession == null) { @@ -412,43 +434,50 @@ return scribeSession; } + @Override public ScribeUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { return scribeUserDAO.getByUserIdAndSessionId(userId, toolSessionId); } + @Override public ScribeUser getUserByLoginNameAndSessionId(String loginName, Long toolSessionId) { return scribeUserDAO.getByLoginNameAndSessionId(loginName, toolSessionId); } + @Override public ScribeUser getUserByUID(Long uid) { return scribeUserDAO.getByUID(uid); } + @Override public void saveOrUpdateScribe(Scribe scribe) { scribeDAO.saveOrUpdate(scribe); } + @Override public void saveOrUpdateScribeSession(ScribeSession scribeSession) { scribeSessionDAO.saveOrUpdate(scribeSession); } + @Override public void saveOrUpdateScribeUser(ScribeUser scribeUser) { scribeUserDAO.saveOrUpdate(scribeUser); } + @Override public ScribeUser createScribeUser(UserDTO user, ScribeSession scribeSession) { ScribeUser scribeUser = new ScribeUser(user, scribeSession); saveOrUpdateScribeUser(scribeUser); return scribeUser; } + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } /* ********** Used by Spring to "inject" the linked objects ************* */ - public IScribeDAO getScribeDAO() { return scribeDAO; } @@ -513,14 +542,16 @@ this.coreNotebookService = coreNotebookService; } + @Override public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry) { return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); } + @Override public NotebookEntry getEntry(Long id, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(id, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -532,6 +563,7 @@ /** * Import the data for a 1.0.2 Scribe */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { Date now = new Date(); Scribe scribe = new Scribe(); @@ -554,14 +586,12 @@ } catch (WDDXProcessorConversionException e) { ScribeService.logger.error("Unable to content for activity " + scribe.getTitle() + "properly due to a WDDXProcessorConversionException.", e); - throw new ToolException( - "Invalid import data format for activity " - + scribe.getTitle() - + "- WDDX caused an exception. Some data from the design will have been lost. See log for more details."); + throw new ToolException("Invalid import data format for activity " + scribe.getTitle() + + "- WDDX caused an exception. Some data from the design will have been lost. See log for more details."); } String headingList = (String) importValues.get(ToolContentImport102Manager.CONTENT_BODY); - if (headingList != null && headingList.length() > 0) { + if ((headingList != null) && (headingList.length() > 0)) { String[] headings = headingList.split("\\^"); Set set = new HashSet(); for (int i = 0; i < headings.length; i++) { @@ -580,8 +610,9 @@ } /** 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { Scribe scribe = getScribeByContentId(toolContentId); if (scribe == null) { @@ -599,23 +630,26 @@ this.scribeHeadingDAO = scribeHeadingDAO; } + @Override public void deleteHeading(Long headingUid) { scribeHeadingDAO.deleteById(ScribeHeading.class, headingUid); } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return null; } - + // ****************** REST methods ************************* - - /** Used by the Rest calls to create content. - * Mandatory fields in toolContentJSON: "title", "instructions", "questions". - * Questions must contain a JSONArray of JSONObject objects, which have the following mandatory fields: "displayOrder", "questionText" - * There must be at least one topic object in the "questions" array. + + /** + * Used by the Rest calls to create content. Mandatory fields in toolContentJSON: "title", "instructions", + * "questions". Questions must contain a JSONArray of JSONObject objects, which have the following mandatory fields: + * "displayOrder", "questionText" There must be at least one topic object in the "questions" array. */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) + throws JSONException { Date updateDate = new Date(); @@ -637,12 +671,12 @@ scribe.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); scribe.setShowAggregatedReports(JsonUtil.opt(toolContentJSON, "showAggregatedReports", Boolean.FALSE)); - if ( scribe.getScribeHeadings() == null ) { + if (scribe.getScribeHeadings() == null) { scribe.setScribeHeadings(new HashSet()); } JSONArray topics = toolContentJSON.getJSONArray(RestTags.QUESTIONS); - for ( int i=0; i 0 ) { + if ((defaultHeadings != null) && (defaultHeadings.size() > 0)) { Iterator iter = defaultHeadings.iterator(); - if ( iter.hasNext() ) - heading.setHeadingText(((ScribeHeading)iter.next()).getHeadingText()); + if (iter.hasNext()) { + heading.setHeadingText(((ScribeHeading) iter.next()).getHeadingText()); + } } - if ( heading.getHeadingText() == null ) + if (heading.getHeadingText() == null) { heading.setHeadingText("Heading"); - + } + heading.setScribe(scribe); scribe.getScribeHeadings().add(heading); } Index: lams_tool_spreadsheet/src/java/org/lamsfoundation/lams/tool/spreadsheet/service/SpreadsheetServiceImpl.java =================================================================== diff -u -r216fed3c7edfdf10855196a0e9450c68f6ed4485 -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_spreadsheet/src/java/org/lamsfoundation/lams/tool/spreadsheet/service/SpreadsheetServiceImpl.java (.../SpreadsheetServiceImpl.java) (revision 216fed3c7edfdf10855196a0e9450c68f6ed4485) +++ lams_tool_spreadsheet/src/java/org/lamsfoundation/lams/tool/spreadsheet/service/SpreadsheetServiceImpl.java (.../SpreadsheetServiceImpl.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -27,7 +27,6 @@ import java.util.Date; import java.util.HashMap; import java.util.Hashtable; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -50,7 +49,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.tool.spreadsheet.SpreadsheetConstants; @@ -79,8 +77,8 @@ * @author Andrey Balan * */ -public class SpreadsheetServiceImpl implements ISpreadsheetService, ToolContentManager, ToolSessionManager, - ToolContentImport102Manager { +public class SpreadsheetServiceImpl + implements ISpreadsheetService, ToolContentManager, ToolSessionManager, ToolContentImport102Manager { private static Logger log = Logger.getLogger(SpreadsheetServiceImpl.class.getName()); private SpreadsheetDAO spreadsheetDao; private SpreadsheetUserDAO spreadsheetUserDao; @@ -101,11 +99,13 @@ // Service method // ******************************************************************************* + @Override public Spreadsheet getSpreadsheetByContentId(Long contentId) { Spreadsheet rs = spreadsheetDao.getByContentId(contentId); return rs; } + @Override public Spreadsheet getDefaultContent(Long contentId) throws SpreadsheetApplicationException { if (contentId == null) { String error = messageService.getMessage("error.msg.default.content.not.find"); @@ -120,31 +120,38 @@ return content; } + @Override public void saveOrUpdateUser(SpreadsheetUser spreadsheetUser) { spreadsheetUserDao.saveObject(spreadsheetUser); } + @Override public void saveOrUpdateUserModifiedSpreadsheet(UserModifiedSpreadsheet userModifiedSpreadsheet) { userModifiedSpreadsheetDao.saveObject(userModifiedSpreadsheet); } + @Override public SpreadsheetUser getUserByIDAndContent(Long userId, Long contentId) { return spreadsheetUserDao.getUserByUserIDAndContentID(userId, contentId); } + @Override public SpreadsheetUser getUserByIDAndSession(Long userId, Long sessionId) { return spreadsheetUserDao.getUserByUserIDAndSessionID(userId, sessionId); } + @Override public List getUserListBySessionId(Long sessionId) { List userList = spreadsheetUserDao.getBySessionID(sessionId); return userList; } + @Override public void saveOrUpdateSpreadsheet(Spreadsheet spreadsheet) { spreadsheetDao.saveObject(spreadsheet); } + @Override public List exportForLearner(Long sessionId, SpreadsheetUser learner) { SpreadsheetSession session = spreadsheetSessionDao.getSessionBySessionId(sessionId); if (session == null) { @@ -205,6 +212,7 @@ // return itemList; } + @Override public List exportForTeacher(Long contentId) { Spreadsheet spreadsheet = spreadsheetDao.getByContentId(contentId); List summaryList = new ArrayList(); @@ -238,6 +246,7 @@ return summaryList; } + @Override public Spreadsheet getSpreadsheetBySessionId(Long sessionId) { SpreadsheetSession session = spreadsheetSessionDao.getSessionBySessionId(sessionId); // to skip CGLib problem @@ -246,14 +255,17 @@ return res; } + @Override public SpreadsheetSession getSessionBySessionId(Long sessionId) { return spreadsheetSessionDao.getSessionBySessionId(sessionId); } + @Override public void saveOrUpdateSpreadsheetSession(SpreadsheetSession resSession) { spreadsheetSessionDao.saveObject(resSession); } + @Override public String finishToolSession(Long toolSessionId, Long userId) throws SpreadsheetApplicationException { SpreadsheetUser user = spreadsheetUserDao.getUserByUserIDAndSessionID(userId, toolSessionId); user.setSessionFinished(true); @@ -274,6 +286,7 @@ return nextUrl; } + @Override public List getSummary(Long contentId) { Spreadsheet spreadsheet = spreadsheetDao.getByContentId(contentId); @@ -293,16 +306,18 @@ } @Override - public List getUsersForTablesorter(final Long sessionId, int page, int size, int sorting, String searchString, boolean getNotebookEntries) { - return spreadsheetUserDao.getUsersForTablesorter(sessionId, page, size, sorting, searchString, getNotebookEntries, coreNotebookService); + public List getUsersForTablesorter(final Long sessionId, int page, int size, int sorting, + String searchString, boolean getNotebookEntries) { + return spreadsheetUserDao.getUsersForTablesorter(sessionId, page, size, sorting, searchString, + getNotebookEntries, coreNotebookService); } - + @Override public int getCountUsersBySession(Long sessionId, String searchString) { return spreadsheetUserDao.getCountUsersBySession(sessionId, searchString); } - + @Override public List getStatistics(Long contentId) { List sessionList = spreadsheetSessionDao.getByContentId(contentId); @@ -329,6 +344,7 @@ return statisticList; } + @Override public Map> getReflectList(Long contentId, boolean setEntry) { Map> map = new HashMap>(); @@ -359,15 +375,17 @@ return map; } + @Override public Long createNotebookEntry(Long sessionId, Integer notebookToolType, String toolSignature, Integer userId, String entryText) { return coreNotebookService.createNotebookEntry(sessionId, notebookToolType, toolSignature, userId, "", entryText); } + @Override public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(sessionId, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -377,25 +395,29 @@ /** * @param notebookEntry */ + @Override public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } + @Override public SpreadsheetUser getUser(Long uid) { return (SpreadsheetUser) spreadsheetUserDao.getObject(SpreadsheetUser.class, uid); } + @Override public void releaseMarksForSession(Long sessionId) { List users = spreadsheetUserDao.getBySessionID(sessionId); for (SpreadsheetUser user : users) { - if (user.getUserModifiedSpreadsheet() != null && user.getUserModifiedSpreadsheet().getMark() != null) { + if ((user.getUserModifiedSpreadsheet() != null) && (user.getUserModifiedSpreadsheet().getMark() != null)) { SpreadsheetMark mark = user.getUserModifiedSpreadsheet().getMark(); mark.setDateMarksReleased(new Date()); spreadsheetMarkDao.saveObject(mark); } } } + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } @@ -437,6 +459,7 @@ this.messageService = messageService; } + @Override public MessageService getMessageService() { return messageService; } @@ -504,7 +527,7 @@ try { // register version filter class exportContentService.registerImportVersionFilterClass(SpreadsheetImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, spreadsheetToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof Spreadsheet)) { @@ -562,10 +585,11 @@ spreadsheetDao.saveObject(toContent); } + @Override public String getToolContentTitle(Long toolContentId) { return getSpreadsheetByContentId(toolContentId).getTitle(); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Spreadsheet spreadsheet = spreadsheetDao.getByContentId(toolContentId); @@ -579,26 +603,41 @@ public boolean isContentEdited(Long toolContentId) { return getSpreadsheetByContentId(toolContentId).isDefineLater(); } - + @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId) throws ToolException { Spreadsheet spreadsheet = spreadsheetDao.getByContentId(toolContentId); - if (removeSessionData) { - List list = spreadsheetSessionDao.getByContentId(toolContentId); - Iterator iter = list.iterator(); - while (iter.hasNext()) { - SpreadsheetSession session = (SpreadsheetSession) iter.next(); - spreadsheetSessionDao.delete(session); + if (spreadsheet == null) { + SpreadsheetServiceImpl.log + .warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (SpreadsheetSession session : spreadsheetSessionDao.getByContentId(toolContentId)) { + // this can not be done via DB cascade + List users = spreadsheetUserDao.getBySessionID(session.getSessionId()); + for (SpreadsheetUser user : users) { + UserModifiedSpreadsheet modified = user.getUserModifiedSpreadsheet(); + if (modified != null) { + userModifiedSpreadsheetDao.removeObject(UserModifiedSpreadsheet.class, modified.getUid()); + } } + + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, SpreadsheetConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); + } } + spreadsheetDao.delete(spreadsheet); } @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (log.isDebugEnabled()) { - log.debug("Removing Spreadsheet contents for user ID " + userId + " and toolContentId " + toolContentId); + if (SpreadsheetServiceImpl.log.isDebugEnabled()) { + SpreadsheetServiceImpl.log.debug( + "Removing Spreadsheet contents for user ID " + userId + " and toolContentId " + toolContentId); } List sessions = spreadsheetSessionDao.getByContentId(toolContentId); @@ -608,16 +647,16 @@ if (user != null) { user.setSessionFinished(false); if (user.getUserModifiedSpreadsheet() != null) { - userModifiedSpreadsheetDao.removeObject(UserModifiedSpreadsheet.class, user - .getUserModifiedSpreadsheet().getUid()); + userModifiedSpreadsheetDao.removeObject(UserModifiedSpreadsheet.class, + user.getUserModifiedSpreadsheet().getUid()); } NotebookEntry entry = getEntry(session.getSessionId(), CoreNotebookConstants.NOTEBOOK_TOOL, SpreadsheetConstants.TOOL_SIGNATURE, userId); if (entry != null) { spreadsheetDao.removeObject(NotebookEntry.class, entry.getUid()); } - + spreadsheetUserDao.removeObject(SpreadsheetUser.class, user.getUid()); } } @@ -658,13 +697,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -682,10 +722,10 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return null; } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /* ===============Methods implemented from ToolContentImport102Manager =============== */ @@ -695,8 +735,9 @@ } /** 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { Spreadsheet toolContentObj = getSpreadsheetByContentId(toolContentId); if (toolContentObj == null) { @@ -734,6 +775,7 @@ this.coreNotebookService = coreNotebookService; } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return null; } Index: lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/service/SurveyServiceImpl.java =================================================================== diff -u -ra789c1395e0f8c1f0ded10147c464574c979b69c -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/service/SurveyServiceImpl.java (.../SurveyServiceImpl.java) (revision a789c1395e0f8c1f0ded10147c464574c979b69c) +++ lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/service/SurveyServiceImpl.java (.../SurveyServiceImpl.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -47,7 +47,6 @@ import org.apache.tomcat.util.json.JSONObject; import org.lamsfoundation.lams.events.IEventNotificationService; import org.lamsfoundation.lams.learning.service.ILearnerService; -import org.lamsfoundation.lams.learningdesign.TextSearchConditionComparator; import org.lamsfoundation.lams.learningdesign.service.ExportToolContentException; import org.lamsfoundation.lams.learningdesign.service.IExportToolContentService; import org.lamsfoundation.lams.learningdesign.service.ImportToolContentException; @@ -63,7 +62,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.tool.survey.SurveyConstants; @@ -277,7 +275,7 @@ @Override public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(sessionId, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -358,7 +356,7 @@ // initial a array to hold how many time chose has been done for a option or open text. int numberAvailableOptions = options.size(); // for appendText and open Text Entry will be the last one of choose[] array. - if (answerDto.isAppendText() || answerDto.getType() == SurveyConstants.QUESTION_TYPE_TEXT_ENTRY) { + if (answerDto.isAppendText() || (answerDto.getType() == SurveyConstants.QUESTION_TYPE_TEXT_ENTRY)) { numberAvailableOptions++; } @@ -378,7 +376,7 @@ } } // handle appendText or Open Text Entry - if ((answerDto.isAppendText() || answerDto.getType() == SurveyConstants.QUESTION_TYPE_TEXT_ENTRY) + if ((answerDto.isAppendText() || (answerDto.getType() == SurveyConstants.QUESTION_TYPE_TEXT_ENTRY)) && !StringUtils.isBlank(answer.getAnswerText())) { choiceArray[numberAvailableOptions - 1]++; numberAnswers++; @@ -391,14 +389,14 @@ numberAnswers = 1; } for (SurveyOption option : options) { - double percentage = (double) choiceArray[idx] / (double) numberAnswers * 100d; + double percentage = ((double) choiceArray[idx] / (double) numberAnswers) * 100d; option.setResponse(percentage); option.setResponseFormatStr(new Long(Math.round(percentage)).toString()); option.setResponseCount(choiceArray[idx]); idx++; } - if (answerDto.isAppendText() || answerDto.getType() == SurveyConstants.QUESTION_TYPE_TEXT_ENTRY) { - double percentage = (double) choiceArray[idx] / (double) numberAnswers * 100d; + if (answerDto.isAppendText() || (answerDto.getType() == SurveyConstants.QUESTION_TYPE_TEXT_ENTRY)) { + double percentage = ((double) choiceArray[idx] / (double) numberAnswers) * 100d; answerDto.setOpenResponse(percentage); answerDto.setOpenResponseFormatStr(new Long(Math.round(percentage)).toString()); answerDto.setOpenResponseCount(choiceArray[idx]); @@ -464,9 +462,10 @@ } @Override - public SortedMap>> exportClassPortfolio(Long toolContentID) { + public SortedMap>> exportClassPortfolio( + Long toolContentID) { - //construct sessionToUsers Map + // construct sessionToUsers Map Map> sessionToUsersMap = new HashMap>(); List sessions = surveySessionDao.getByContentId(toolContentID); if (sessions != null) { @@ -493,19 +492,21 @@ } @Override - public SortedMap>> exportLearnerPortfolio(SurveyUser learner) { + public SortedMap>> exportLearnerPortfolio( + SurveyUser learner) { Map> sessionToUsersMap = new HashMap>(); SurveySession session = learner.getSession(); sessionToUsersMap.put(session, Arrays.asList(learner)); - + return getExportSummary(sessionToUsersMap); } /** - * Creates data for export methods. Suitable both for single/multiple users + * Creates data for export methods. Suitable both for single/multiple users * - * @param sessionToUsersMap map containing all session to users pairs that require data to be exported + * @param sessionToUsersMap + * map containing all session to users pairs that require data to be exported * @return */ private SortedMap>> getExportSummary( @@ -585,6 +586,7 @@ return summary; } + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } @@ -692,15 +694,15 @@ Object toolPOJO = exportContentService.importToolContent(toolContentPath, surveyToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof Survey)) { - throw new ImportToolContentException("Import survey tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import survey tool content failed. Deserialized object is " + toolPOJO); } Survey toolContentObj = (Survey) toolPOJO; // reset it to new toolContentId toolContentObj.setContentId(toolContentId); - SurveyUser user = surveyUserDao - .getUserByUserIDAndContentID(new Long(newUserUid.longValue()), toolContentId); + SurveyUser user = surveyUserDao.getUserByUserIDAndContentID(new Long(newUserUid.longValue()), + toolContentId); if (user == null) { UserDTO sysUser = ((User) userManagementService.findById(User.class, newUserUid)).getUserDTO(); user = new SurveyUser(sysUser, toolContentObj); @@ -784,24 +786,29 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId) throws ToolException { Survey survey = surveyDao.getByContentId(toolContentId); - if (removeSessionData) { - List list = surveySessionDao.getByContentId(toolContentId); - Iterator iter = list.iterator(); - while (iter.hasNext()) { - SurveySession session = (SurveySession) iter.next(); - surveySessionDao.delete(session); + if (survey == null) { + SurveyServiceImpl.log.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (SurveySession session : surveySessionDao.getByContentId(toolContentId)) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, SurveyConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); } } + surveyDao.delete(survey); } @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (log.isDebugEnabled()) { - log.debug("Removing Survey answers for user ID " + userId + " and toolContentId " + toolContentId); + if (SurveyServiceImpl.log.isDebugEnabled()) { + SurveyServiceImpl.log + .debug("Removing Survey answers for user ID " + userId + " and toolContentId " + toolContentId); } List answers = surveyAnswerDao.getByToolContentIdAndUserId(toolContentId, userId.longValue()); @@ -848,13 +855,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -872,10 +880,10 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return getSurveyOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /* ===============Methods implemented from ToolContentImport102Manager =============== */ @@ -913,6 +921,7 @@ /** * Import the data for a 1.0.2 Noticeboard or HTMLNoticeboard */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { Date now = new Date(); Survey toolContentObj = new Survey(); @@ -923,8 +932,8 @@ toolContentObj.setContentInUse(Boolean.FALSE); toolContentObj.setCreated(now); toolContentObj.setDefineLater(Boolean.FALSE); - toolContentObj.setInstructions(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); + toolContentObj.setInstructions( + WebUtil.convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY))); toolContentObj.setUpdated(now); Boolean isReusable = WDDXProcessor.convertToBoolean(importValues, @@ -971,8 +980,8 @@ ToolContentImport102Manager.CONTENT_SURVEY_ORDER); item.setSequenceId(order != null ? order.intValue() : dummySequenceNumber++); - item.setDescription(WebUtil.convertNewlines((String) questionMap - .get(ToolContentImport102Manager.CONTENT_SURVEY_QUESTION))); + item.setDescription(WebUtil.convertNewlines( + (String) questionMap.get(ToolContentImport102Manager.CONTENT_SURVEY_QUESTION))); // completion message purposely not supported in 2.0, so value can be dropped. @@ -985,7 +994,7 @@ item.setOptional(isOptional != null ? isOptional.booleanValue() : false); Vector candidates = (Vector) questionMap.get(ToolContentImport102Manager.CONTENT_SURVEY_CANDIDATES); - if (candidates != null && candidates.size() > 0) { + if ((candidates != null) && (candidates.size() > 0)) { item.setOptions(new HashSet()); int dummyCandidateOrder = candidates.size(); // dummy number in case we can't convert // question order @@ -999,8 +1008,8 @@ SurveyOption option = new SurveyOption(); option.setDescription(candidateText); - option.setSequenceId(candidateOrder != null ? candidateOrder.intValue() - : dummyCandidateOrder++); + option.setSequenceId( + candidateOrder != null ? candidateOrder.intValue() : dummyCandidateOrder++); item.getOptions().add(option); } } @@ -1012,19 +1021,18 @@ } catch (WDDXProcessorConversionException e) { SurveyServiceImpl.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."); + 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."); } surveyDao.saveObject(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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { Survey toolContentObj = getSurveyByContentId(toolContentId); if (toolContentObj == null) { @@ -1119,7 +1127,7 @@ public void setSurveyOutputFactory(SurveyOutputFactory surveyOutputFactory) { this.surveyOutputFactory = surveyOutputFactory; } - + // ****************** REST methods ************************* /** @@ -1154,7 +1162,8 @@ survey.setLockWhenFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.TRUE)); survey.setReflectInstructions((String) JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null)); survey.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - survey.setNotifyTeachersOnAnswerSumbit(JsonUtil.opt(toolContentJSON, "notifyTeachersOnAnswerSumbit", Boolean.FALSE)); + survey.setNotifyTeachersOnAnswerSumbit( + JsonUtil.opt(toolContentJSON, "notifyTeachersOnAnswerSumbit", Boolean.FALSE)); survey.setShowOnePage(JsonUtil.opt(toolContentJSON, "showOnePage", Boolean.TRUE)); survey.setShowOtherUsersAnswers(JsonUtil.opt(toolContentJSON, "showOtherUsersAnswers", Boolean.FALSE)); Index: lams_tool_task/src/java/org/lamsfoundation/lams/tool/taskList/service/TaskListServiceImpl.java =================================================================== diff -u -ra789c1395e0f8c1f0ded10147c464574c979b69c -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_task/src/java/org/lamsfoundation/lams/tool/taskList/service/TaskListServiceImpl.java (.../TaskListServiceImpl.java) (revision a789c1395e0f8c1f0ded10147c464574c979b69c) +++ lams_tool_task/src/java/org/lamsfoundation/lams/tool/taskList/service/TaskListServiceImpl.java (.../TaskListServiceImpl.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -54,7 +54,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.tool.taskList.TaskListConstants; @@ -92,8 +91,8 @@ * @author Andrey Balan * @see org.lamsfoundation.lams.tool.taskList.service.ITaskListService */ -public class TaskListServiceImpl implements ITaskListService, ToolContentManager, ToolSessionManager, - ToolContentImport102Manager { +public class TaskListServiceImpl + implements ITaskListService, ToolContentManager, ToolSessionManager, ToolContentImport102Manager { private static Logger log = Logger.getLogger(TaskListServiceImpl.class.getName()); private TaskListDAO taskListDao; private TaskListItemDAO taskListItemDao; @@ -147,9 +146,9 @@ @Override public TaskListItemAttachment uploadTaskListItemFile(FormFile uploadFile, TaskListUser user) throws UploadTaskListFileException { - if (uploadFile == null || StringUtils.isEmpty(uploadFile.getFileName())) { - throw new UploadTaskListFileException(messageService.getMessage("error.msg.upload.file.not.found", - new Object[] { uploadFile })); + if ((uploadFile == null) || StringUtils.isEmpty(uploadFile.getFileName())) { + throw new UploadTaskListFileException( + messageService.getMessage("error.msg.upload.file.not.found", new Object[] { uploadFile })); } // upload file to repository @@ -321,8 +320,8 @@ TaskListItem item = itemList.get(j); // retreiving TaskListItemVisitLog for current taskList and user - TaskListItemVisitLog visitLog = taskListItemVisitDao.getTaskListItemLog(item.getUid(), user - .getUserId()); + TaskListItemVisitLog visitLog = taskListItemVisitDao.getTaskListItemLog(item.getUid(), + user.getUserId()); if (visitLog != null) { complete[i][j] = visitLog.isComplete(); if (visitLog.isComplete()) { @@ -372,8 +371,8 @@ TaskListItemVisitLogSummary taskListItemVisitLogSummary = new TaskListItemVisitLogSummary(); taskListItemVisitLogSummary.setUser(user); - TaskListItemVisitLog visitLog = taskListItemVisitDao.getTaskListItemLog(taskListItem.getUid(), user - .getUserId()); + TaskListItemVisitLog visitLog = taskListItemVisitDao.getTaskListItemLog(taskListItem.getUid(), + user.getUserId()); // If TaskListItemVisitLog exists then fill up taskSummaryItem otherwise put false in a completed field if (visitLog != null) { taskListItemVisitLogSummary.setCompleted(visitLog.isComplete()); @@ -556,7 +555,7 @@ @Override public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(sessionId, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -567,7 +566,7 @@ public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } - + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); @@ -659,6 +658,7 @@ this.coreNotebookService = coreNotebookService; } + @Override public MessageService getMessageService() { return messageService; } @@ -703,7 +703,7 @@ try { // register version filter class exportContentService.registerImportVersionFilterClass(TaskListImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, taskListToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof TaskList)) { @@ -747,16 +747,17 @@ } return getTaskListOutputFactory().getToolOutputDefinitions(taskList, definitionType); } - + + @Override public String getToolContentTitle(Long toolContentId) { return getTaskListByContentId(toolContentId).getTitle(); } - + @Override public boolean isContentEdited(Long toolContentId) { return getTaskListByContentId(toolContentId).isDefineLater(); } - + @Override public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { if (toContentId == null) { @@ -788,7 +789,7 @@ } } } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { TaskList taskList = taskListDao.getByContentId(toolContentId); @@ -799,37 +800,43 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId) throws ToolException { TaskList taskList = taskListDao.getByContentId(toolContentId); - if (removeSessionData) { - List list = taskListSessionDao.getByContentId(toolContentId); - Iterator iter = list.iterator(); - while (iter.hasNext()) { - TaskListSession session = (TaskListSession) iter.next(); - taskListSessionDao.delete(session); + if (taskList == null) { + TaskListServiceImpl.log.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (TaskListSession session : taskListSessionDao.getByContentId(toolContentId)) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, TaskListConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); } } + taskListDao.delete(taskList); } @Override @SuppressWarnings("unchecked") public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (log.isDebugEnabled()) { - log.debug("Removing Task List contents for user ID " + userId + " and toolContentId " + toolContentId); + if (TaskListServiceImpl.log.isDebugEnabled()) { + TaskListServiceImpl.log + .debug("Removing Task List contents for user ID " + userId + " and toolContentId " + toolContentId); } TaskList taskList = taskListDao.getByContentId(toolContentId); if (taskList == null) { - log.warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); + TaskListServiceImpl.log + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } Set items = taskList.getTaskListItems(); for (TaskListItem item : items) { - if (log.isDebugEnabled()) { - log.debug("Removing visit log, comments and attachments for user ID " + userId + " and item UID " - + item.getUid()); + if (TaskListServiceImpl.log.isDebugEnabled()) { + TaskListServiceImpl.log.debug("Removing visit log, comments and attachments for user ID " + userId + + " and item UID " + item.getUid()); } TaskListItemVisitLog visitLog = taskListItemVisitDao.getTaskListItemLog(item.getUid(), userId.longValue()); @@ -911,13 +918,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -937,13 +945,14 @@ * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.lang.String, java.lang.Long, * java.lang.Long) */ + @Override public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return taskListOutputFactory.getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } // ******************************************************************************* @@ -955,8 +964,8 @@ } @Override - public void setReflectiveData(Long toolContentId, String title, String description) throws ToolException, - DataMissingException { + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { TaskList toolContentObj = getTaskListByContentId(toolContentId); if (toolContentObj == null) { @@ -1000,7 +1009,7 @@ * * @param contentId * @param sessionId - * sessionId which defines Group + * sessionId which defines Group * @return */ private List getItemListForGroup(Long contentId, Long sessionId) { @@ -1051,7 +1060,7 @@ */ private NodeKey processFile(FormFile file) throws UploadTaskListFileException { NodeKey node = null; - if (file != null && !StringUtils.isEmpty(file.getFileName())) { + if ((file != null) && !StringUtils.isEmpty(file.getFileName())) { String fileName = file.getFileName(); try { node = taskListToolContentHandler.uploadFile(file.getInputStream(), fileName, file.getContentType()); @@ -1072,6 +1081,7 @@ // Service method // ******************************************************************************* + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getTaskListOutputFactory().getSupportedDefinitionClasses(definitionType); } Index: lams_tool_videorecorder/src/java/org/lamsfoundation/lams/tool/videoRecorder/service/VideoRecorderService.java =================================================================== diff -u -ra207bdecc16a704428826dbf402a97de2e35458b -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_videorecorder/src/java/org/lamsfoundation/lams/tool/videoRecorder/service/VideoRecorderService.java (.../VideoRecorderService.java) (revision a207bdecc16a704428826dbf402a97de2e35458b) +++ lams_tool_videorecorder/src/java/org/lamsfoundation/lams/tool/videoRecorder/service/VideoRecorderService.java (.../VideoRecorderService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -24,35 +24,21 @@ package org.lamsfoundation.lams.tool.videoRecorder.service; -import java.io.FileNotFoundException; -import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Hashtable; import java.util.List; -import java.util.Random; import java.util.Set; import java.util.SortedMap; -import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; -import org.apache.struts.upload.FormFile; -import org.lamsfoundation.lams.contentrepository.AccessDeniedException; -import org.lamsfoundation.lams.contentrepository.ICredentials; -import org.lamsfoundation.lams.contentrepository.ITicket; -import org.lamsfoundation.lams.contentrepository.InvalidParameterException; -import org.lamsfoundation.lams.contentrepository.LoginException; -import org.lamsfoundation.lams.contentrepository.NodeKey; -import org.lamsfoundation.lams.contentrepository.RepositoryCheckedException; -import org.lamsfoundation.lams.contentrepository.WorkspaceNotFoundException; import org.lamsfoundation.lams.contentrepository.client.IToolContentHandler; -import org.lamsfoundation.lams.contentrepository.service.IRepositoryService; -import org.lamsfoundation.lams.contentrepository.service.SimpleCredentials; import org.lamsfoundation.lams.learning.service.ILearnerService; 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.notebook.model.NotebookEntry; +import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; import org.lamsfoundation.lams.notebook.service.ICoreNotebookService; import org.lamsfoundation.lams.tool.ToolContentImport102Manager; import org.lamsfoundation.lams.tool.ToolContentManager; @@ -61,7 +47,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.tool.videoRecorder.dao.IVideoRecorderCommentDAO; @@ -82,22 +67,20 @@ import org.lamsfoundation.lams.tool.videoRecorder.model.VideoRecorderUser; import org.lamsfoundation.lams.tool.videoRecorder.util.VideoRecorderConstants; import org.lamsfoundation.lams.tool.videoRecorder.util.VideoRecorderException; -import org.lamsfoundation.lams.tool.videoRecorder.util.VideoRecorderToolContentHandler; import org.lamsfoundation.lams.usermanagement.User; import org.lamsfoundation.lams.usermanagement.dto.UserDTO; import org.lamsfoundation.lams.util.FileUtil; import org.lamsfoundation.lams.util.MessageService; import org.lamsfoundation.lams.util.WebUtil; -import org.lamsfoundation.lams.util.audit.IAuditService; /** * An implementation of the IVideoRecorderService interface. * * As a requirement, all LAMS tool's service bean must implement ToolContentManager and ToolSessionManager. */ -public class VideoRecorderService implements ToolSessionManager, ToolContentManager, IVideoRecorderService, - ToolContentImport102Manager { +public class VideoRecorderService + implements ToolSessionManager, ToolContentManager, IVideoRecorderService, ToolContentImport102Manager { private static Logger logger = Logger.getLogger(VideoRecorderService.class.getName()); @@ -135,8 +118,8 @@ @Override public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException { if (VideoRecorderService.logger.isDebugEnabled()) { - VideoRecorderService.logger.debug("entering method createToolSession:" + " toolSessionId = " - + toolSessionId + " toolSessionName = " + toolSessionName + " toolContentId = " + toolContentId); + VideoRecorderService.logger.debug("entering method createToolSession:" + " toolSessionId = " + toolSessionId + + " toolSessionName = " + toolSessionName + " toolContentId = " + toolContentId); } VideoRecorderSession session = new VideoRecorderSession(); @@ -157,14 +140,15 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { // TODO Auto-generated method stub return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { // TODO Auto-generated method stub return null; } @@ -184,10 +168,10 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return getVideoRecorderOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } /* ************ Methods from ToolContentManager ************************* */ @@ -229,7 +213,7 @@ VideoRecorder toContent = VideoRecorder.newInstance(fromContent, toContentId); videoRecorderDAO.saveOrUpdate(toContent); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { VideoRecorder videoRecorder = videoRecorderDAO.getByContentId(toolContentId); @@ -240,23 +224,39 @@ videoRecorderDAO.saveOrUpdate(videoRecorder); } + @SuppressWarnings("unchecked") @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { - // TODO Auto-generated method stub + public void removeToolContent(Long toolContentId) throws ToolException { + VideoRecorder videoRecorder = videoRecorderDAO.getByContentId(toolContentId); + if (videoRecorder == null) { + VideoRecorderService.logger + .warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (VideoRecorderSession session : (Set) videoRecorder.getVideoRecorderSessions()) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, VideoRecorderConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); + } + } + + videoRecorderDAO.delete(videoRecorder); } - + @Override @SuppressWarnings("unchecked") public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("Removing Video Recorder contents for user ID " + userId + " and toolContentId " - + toolContentId); + if (VideoRecorderService.logger.isDebugEnabled()) { + VideoRecorderService.logger.debug( + "Removing Video Recorder contents for user ID " + userId + " and toolContentId " + toolContentId); } VideoRecorder videoRecorder = videoRecorderDAO.getByContentId(toolContentId); if (videoRecorder == null) { - logger.warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); + VideoRecorderService.logger + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } @@ -267,8 +267,8 @@ List ratings = videoRecorderRatingDAO.getRatingsByUserId(userId.longValue()); videoRecorderRatingDAO.deleteAll(ratings); - List recordings = videoRecorderRecordingDAO.getBySessionAndUserId( - session.getSessionId(), userId.longValue()); + List recordings = videoRecorderRecordingDAO + .getBySessionAndUserId(session.getSessionId(), userId.longValue()); videoRecorderRecordingDAO.deleteAll(recordings); VideoRecorderUser user = videoRecorderUserDAO.getByUserIdAndSessionId(userId.longValue(), @@ -285,7 +285,7 @@ } } } - + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { VideoRecorder videoRecorder = videoRecorderDAO.getByContentId(toolContentId); @@ -302,7 +302,7 @@ videoRecorder.setToolContentId(null); videoRecorder.setVideoRecorderSessions(null); - VideoRecorderRecording authorRecording = (VideoRecorderRecording) getFirstRecordingByToolContentId(toolContentId); + VideoRecorderRecording authorRecording = getFirstRecordingByToolContentId(toolContentId); if (authorRecording != null) { authorRecording = (VideoRecorderRecording) authorRecording.clone(); @@ -327,7 +327,7 @@ try { // register version filter class exportContentService.registerImportVersionFilterClass(VideoRecorderImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, videoRecorderToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof VideoRecorder)) { @@ -364,17 +364,17 @@ } return getVideoRecorderOutputFactory().getToolOutputDefinitions(videoRecorder, definitionType); } - + @Override public String getToolContentTitle(Long toolContentId) { return getVideoRecorderByContentId(toolContentId).getTitle(); } - + @Override public boolean isContentEdited(Long toolContentId) { return getVideoRecorderByContentId(toolContentId).isDefineLater(); } - + /* ********** IVideoRecorderService Methods ********************************* */ @Override @@ -449,8 +449,8 @@ public VideoRecorderSession getSessionBySessionId(Long toolSessionId) { VideoRecorderSession videoRecorderSession = videoRecorderSessionDAO.getBySessionId(toolSessionId); if (videoRecorderSession == null) { - VideoRecorderService.logger.debug("Could not find the videoRecorder session with toolSessionID:" - + toolSessionId); + VideoRecorderService.logger + .debug("Could not find the videoRecorder session with toolSessionID:" + toolSessionId); } return videoRecorderSession; } @@ -464,48 +464,58 @@ return videoRecorderUserDAO.getByLoginNameAndSessionId(loginName, toolSessionId); } + @Override public VideoRecorderUser getUserByUID(Long uid) { return videoRecorderUserDAO.getByUID(uid); } + @Override public VideoRecorderRecording getRecordingById(Long recordingId) { return videoRecorderRecordingDAO.getRecordingById(recordingId); } + @Override public void deleteVideoRecorderRecording(VideoRecorderRecording videoRecorderRecording) { videoRecorderRecordingDAO.delete(videoRecorderRecording); return; } + @Override public VideoRecorderRating getRatingById(Long ratingId) { return videoRecorderRatingDAO.getRatingById(ratingId); } + @Override public VideoRecorderComment getCommentById(Long commentId) { return videoRecorderCommentDAO.getCommentById(commentId); } + @Override public Set getRatingsByToolSessionId(Long toolSessionId) { List list = videoRecorderRatingDAO.getRatingsByToolSessionId(toolSessionId); return VideoRecorderRatingDTO.getVideoRecorderRatingDTOs(list); } + @Override public List getCommentsByUserId(Long userId) { return videoRecorderCommentDAO.getCommentsByUserId(userId); } + @Override public Set getCommentsByToolSessionId(Long toolSessionId) { List list = videoRecorderCommentDAO.getCommentsByToolSessionId(toolSessionId); return VideoRecorderCommentDTO.getVideoRecorderCommentDTOs(list); } + @Override public List getRecordingsByToolSessionId(Long toolSessionId, Long toolContentId) { List list = videoRecorderRecordingDAO.getByToolSessionId(toolSessionId); list.addAll(videoRecorderRecordingDAO.getByToolContentId(toolContentId)); return VideoRecorderRecordingDTO.getVideoRecorderRecordingDTOs(list); } + @Override public List getRecordingsByToolSessionIdAndUserUid(Long toolSessionId, Long userId, Long toolContentId) { List list = videoRecorderRecordingDAO.getBySessionAndUserUid(toolSessionId, userId); @@ -514,11 +524,13 @@ return VideoRecorderRecordingDTO.getVideoRecorderRecordingDTOs(list); } + @Override public List getRecordingsByToolContentId(Long toolContentId) { List list = videoRecorderRecordingDAO.getByToolContentId(toolContentId); return VideoRecorderRecordingDTO.getVideoRecorderRecordingDTOs(list); } + @Override public VideoRecorderRecording getFirstRecordingByToolContentId(Long toolContentId) { List list = videoRecorderRecordingDAO.getByToolContentId(toolContentId); if (!list.isEmpty()) { @@ -528,30 +540,37 @@ } } + @Override public void saveOrUpdateVideoRecorder(VideoRecorder videoRecorder) { videoRecorderDAO.saveOrUpdate(videoRecorder); } + @Override public void saveOrUpdateVideoRecorderSession(VideoRecorderSession videoRecorderSession) { videoRecorderSessionDAO.saveOrUpdate(videoRecorderSession); } + @Override public void saveOrUpdateVideoRecorderUser(VideoRecorderUser videoRecorderUser) { videoRecorderUserDAO.saveOrUpdate(videoRecorderUser); } + @Override public void saveOrUpdateVideoRecorderRecording(VideoRecorderRecording videoRecorderRecording) { videoRecorderRecordingDAO.saveOrUpdate(videoRecorderRecording); } + @Override public void saveOrUpdateVideoRecorderComment(VideoRecorderComment videoRecorderComment) { videoRecorderCommentDAO.saveOrUpdate(videoRecorderComment); } + @Override public void saveOrUpdateVideoRecorderRating(VideoRecorderRating videoRecorderRating) { videoRecorderRatingDAO.saveOrUpdate(videoRecorderRating); } + @Override public VideoRecorderUser createVideoRecorderUser(UserDTO user, VideoRecorderSession videoRecorderSession) { VideoRecorderUser videoRecorderUser = new VideoRecorderUser(user, videoRecorderSession); saveOrUpdateVideoRecorderUser(videoRecorderUser); @@ -563,15 +582,16 @@ /** * Import the data for a 1.0.2 VideoRecorder */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { Date now = new Date(); VideoRecorder videoRecorder = new VideoRecorder(); videoRecorder.setContentInUse(Boolean.FALSE); videoRecorder.setCreateBy(new Long(user.getUserID().longValue())); videoRecorder.setCreateDate(now); videoRecorder.setDefineLater(Boolean.FALSE); - videoRecorder.setInstructions(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); + videoRecorder.setInstructions( + WebUtil.convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY))); videoRecorder.setLockOnFinished(Boolean.TRUE); videoRecorder.setTitle((String) importValues.get(ToolContentImport102Manager.CONTENT_TITLE)); videoRecorder.setToolContentId(toolContentId); @@ -580,11 +600,12 @@ } /** 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { - VideoRecorderService.logger - .warn("Setting the reflective field on a videoRecorder. This doesn't make sense as the videoRecorder is for reflection and we don't reflect on reflection!"); + VideoRecorderService.logger.warn( + "Setting the reflective field on a videoRecorder. This doesn't make sense as the videoRecorder is for reflection and we don't reflect on reflection!"); VideoRecorder videoRecorder = getVideoRecorderByContentId(toolContentId); if (videoRecorder == null) { throw new DataMissingException("Unable to set reflective data titled " + title @@ -701,6 +722,7 @@ this.videoRecorderOutputFactory = videoRecorderOutputFactory; } + @Override public void releaseConditionsFromCache(VideoRecorder videoRecorder) { if (videoRecorder.getConditions() != null) { for (VideoRecorderCondition condition : videoRecorder.getConditions()) { @@ -709,31 +731,37 @@ } } + @Override public void deleteCondition(VideoRecorderCondition condition) { - if (condition != null && condition.getConditionId() != null) { + if ((condition != null) && (condition.getConditionId() != null)) { videoRecorderDAO.delete(condition); } } + @Override public Long getNbRecordings(Long userID, Long sessionId) { return videoRecorderRecordingDAO.getNbRecordings(userID, sessionId); } + @Override public Long getNbComments(Long userID, Long sessionId) { return videoRecorderCommentDAO.getNbComments(userID, sessionId); } + @Override public Long getNbRatings(Long userID, Long sessionId) { return videoRecorderRatingDAO.getNbRatings(userID, sessionId); } + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } /** * @return String of xml with all needed language elements */ + @Override public String getLanguageXML() { ArrayList languageCollection = new ArrayList(); languageCollection.add(new String("button.ok")); @@ -815,6 +843,7 @@ return languageOutput; } + @Override public String getLanguageXMLForFCK() { ArrayList languageCollection = new ArrayList(); languageCollection.add(new String("button.ok")); @@ -863,10 +892,12 @@ return languageOutput; } + @Override public String getMessage(String key) { return messageService.getMessage(key); } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getVideoRecorderOutputFactory().getSupportedDefinitionClasses(definitionType); } Index: lams_tool_vote/conf/hibernate/mappings/org/lamsfoundation/lams/tool/vote/pojos/VoteUsrAttempt.hbm.xml =================================================================== diff -u -rd56929f06ad90a63082d514e6521adc175f3de27 -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_vote/conf/hibernate/mappings/org/lamsfoundation/lams/tool/vote/pojos/VoteUsrAttempt.hbm.xml (.../VoteUsrAttempt.hbm.xml) (revision d56929f06ad90a63082d514e6521adc175f3de27) +++ lams_tool_vote/conf/hibernate/mappings/org/lamsfoundation/lams/tool/vote/pojos/VoteUsrAttempt.hbm.xml (.../VoteUsrAttempt.hbm.xml) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -36,18 +36,6 @@ - - - - ) voteContent.getVoteQueContents()) { Long votesCount = sessionDTO.getMapStandardUserCount().get(mapIndex); - Long oldTotalVotesCount = (totalMapStandardUserCount.get(mapIndex) != null) ? totalMapStandardUserCount - .get(mapIndex) : 0L; + Long oldTotalVotesCount = (totalMapStandardUserCount.get(mapIndex) != null) + ? totalMapStandardUserCount.get(mapIndex) : 0L; totalMapStandardUserCount.put(mapIndex, oldTotalVotesCount + votesCount); allSessionsVotesCount += votesCount; @@ -409,8 +409,8 @@ // open votes if (voteContent.isAllowText()) { Long votesCount = sessionDTO.getMapStandardUserCount().get(mapIndex); - Long oldTotalVotesCount = (totalMapStandardUserCount.get(mapIndex) != null) ? totalMapStandardUserCount - .get(mapIndex) : 0L; + Long oldTotalVotesCount = (totalMapStandardUserCount.get(mapIndex) != null) + ? totalMapStandardUserCount.get(mapIndex) : 0L; totalMapStandardUserCount.put(mapIndex, oldTotalVotesCount + votesCount); allSessionsVotesCount += votesCount; @@ -423,8 +423,8 @@ totalSessionDTO.setOpenVotes(totalOpenVotes); boolean isExistsOpenVote = totalOpenVotes.size() > 0; totalSessionDTO.setExistsOpenVote(isExistsOpenVote); - totalSessionDTO.setMapStandardNominationsHTMLedContent(sessionDTOs.get(0) - .getMapStandardNominationsHTMLedContent()); + totalSessionDTO.setMapStandardNominationsHTMLedContent( + sessionDTOs.get(0).getMapStandardNominationsHTMLedContent()); totalSessionDTO.setMapStandardQuestionUid(sessionDTOs.get(0).getMapStandardQuestionUid()); totalSessionDTO.setMapStandardToolSessionUid(sessionDTOs.get(0).getMapStandardToolSessionUid()); totalSessionDTO.setMapStandardUserCount(totalMapStandardUserCount); @@ -487,7 +487,7 @@ List monitoredAnswersDTOs = new LinkedList(); for (String userEntry : userEntries) { - if (userEntry == null || userEntry.length() == 0) { + if ((userEntry == null) || (userEntry.length() == 0)) { continue; } @@ -575,8 +575,8 @@ VoteQueUsr user = (VoteQueUsr) userIter.next(); NotebookEntry notebookEntry = this.getEntry(voteSession.getVoteSessionId(), - CoreNotebookConstants.NOTEBOOK_TOOL, VoteAppConstants.MY_SIGNATURE, new Integer(user - .getQueUsrId().toString())); + CoreNotebookConstants.NOTEBOOK_TOOL, VoteAppConstants.MY_SIGNATURE, + new Integer(user.getQueUsrId().toString())); if (notebookEntry != null) { ReflectionDTO reflectionDTO = new ReflectionDTO(); @@ -597,8 +597,8 @@ VoteQueUsr user = (VoteQueUsr) userIter.next(); if (user.getQueUsrId().equals(userID)) { NotebookEntry notebookEntry = this.getEntry(voteSession.getVoteSessionId(), - CoreNotebookConstants.NOTEBOOK_TOOL, VoteAppConstants.MY_SIGNATURE, new Integer(user - .getQueUsrId().toString())); + CoreNotebookConstants.NOTEBOOK_TOOL, VoteAppConstants.MY_SIGNATURE, + new Integer(user.getQueUsrId().toString())); if (notebookEntry != null) { ReflectionDTO reflectionDTO = new ReflectionDTO(); @@ -618,28 +618,34 @@ return reflectionsContainerDTO; } + @Override public VoteContent getVoteContent(Long toolContentID) { return voteContentDAO.getVoteContentByContentId(toolContentID); } + @Override public VoteQueContent getQuestionByDisplayOrder(final Long displayOrder, final Long voteContentUid) { return voteQueContentDAO.getQuestionByDisplayOrder(displayOrder, voteContentUid); } + @Override public VoteQueUsr getUserById(long voteQueUsrId) { VoteQueUsr voteQueUsr = voteUserDAO.getVoteQueUsrById(voteQueUsrId); return voteQueUsr; } + @Override public List getAttemptsForQuestionContentAndSessionUid(final Long questionUid, final Long voteSessionUid) { return voteUsrAttemptDAO.getAttemptsForQuestionContentAndSessionUid(questionUid, voteSessionUid); } + @Override public Set getAttemptsForUserAndSessionUseOpenAnswer(final Long userUid, final Long sessionUid) { return voteUsrAttemptDAO.getAttemptsForUserAndSessionUseOpenAnswer(userUid, sessionUid); } + @Override public Set getAttemptsForUserAndSession(final Long queUsrUid, final Long sessionUid) { return voteUsrAttemptDAO.getAttemptsForUserAndSession(queUsrUid, sessionUid); } @@ -657,7 +663,7 @@ public void saveOrUpdateVoteQueContent(VoteQueContent voteQueContent) { voteQueContentDAO.saveOrUpdateQuestion(voteQueContent); } - + @Override public VoteContent createQuestions(List questionDTOs, VoteContent voteContent) { @@ -694,16 +700,16 @@ return voteContent; } - + @Override public Map buildQuestionMap(VoteContent voteContent, Collection checkedOptions) { Map mapQuestionsContent = new TreeMap(new VoteComparator()); Set questions = voteContent.getVoteQueContents(); - + // should we add questions from data flow from other activities? if (Boolean.TRUE.equals(voteContent.getAssignedDataFlowObject()) - && (voteContent.getMaxExternalInputs() == null || voteContent.getExternalInputsAdded() == null || voteContent - .getExternalInputsAdded() < voteContent.getMaxExternalInputs())) { + && ((voteContent.getMaxExternalInputs() == null) || (voteContent.getExternalInputsAdded() == null) + || (voteContent.getExternalInputsAdded() < voteContent.getMaxExternalInputs()))) { // If we are using tool input, we need to get it now and // create questions. Once they are created, they will be not altered, no matter if another learner gets to // this point and the tool input changed @@ -725,7 +731,7 @@ int nominationIndex = voteContent.getVoteQueContents().size() + 1; for (String[] userAnswers : usersAndAnswers) { if (userAnswers != null) { - if (maxInputs != null && inputsAdded >= maxInputs) { + if ((maxInputs != null) && (inputsAdded >= maxInputs)) { // if we reached the maximum number of inputs, i.e. number of students that will be // taken // into account @@ -738,7 +744,7 @@ nomination.setDisplayOrder(nominationIndex); nomination.setMcContent(voteContent); nomination.setQuestion(questionText); - if (!isNominationExists(nomination, existingNominations)) { + if (!VoteServicePOJO.isNominationExists(nomination, existingNominations)) { saveOrUpdateVoteQueContent(nomination); voteContent.getVoteQueContents().add(nomination); nominationIndex++; @@ -757,7 +763,7 @@ int nominationIndex = voteContent.getVoteQueContents().size() + 1; String[] userAnswers = (String[]) value; for (String questionText : userAnswers) { - if (maxInputs != null && inputsAdded >= maxInputs) { + if ((maxInputs != null) && (inputsAdded >= maxInputs)) { // if we reached the maximum number of inputs, i.e. number of students that will be taken // into account break; @@ -768,21 +774,21 @@ nomination.setDisplayOrder(nominationIndex); nomination.setMcContent(voteContent); nomination.setQuestion(questionText); - if (!isNominationExists(nomination, existingNominations)) { + if (!VoteServicePOJO.isNominationExists(nomination, existingNominations)) { saveOrUpdateVoteQueContent(nomination); voteContent.getVoteQueContents().add(nomination); nominationIndex++; inputsAdded++; } } } - } else if (value instanceof String && !StringUtils.isBlank((String) value)) { + } else if ((value instanceof String) && !StringUtils.isBlank((String) value)) { int nominationIndex = voteContent.getVoteQueContents().size() + 1; VoteQueContent nomination = new VoteQueContent(); nomination.setDisplayOrder(nominationIndex); nomination.setMcContent(voteContent); nomination.setQuestion((String) value); - if (!isNominationExists(nomination, existingNominations)) { + if (!VoteServicePOJO.isNominationExists(nomination, existingNominations)) { saveOrUpdateVoteQueContent(nomination); voteContent.getVoteQueContents().add(nomination); } @@ -793,7 +799,7 @@ int nominationIndex = voteContent.getVoteQueContents().size() + 1; for (SimpleURL[] userUrls : usersAndUrls) { if (userUrls != null) { - if (maxInputs != null && inputsAdded >= maxInputs) { + if ((maxInputs != null) && (inputsAdded >= maxInputs)) { // if we reached the maximum number of inputs, i.e. number of students that will be // taken // into account @@ -808,7 +814,7 @@ String link = "" + url.getNameToDisplay() + ""; nomination.setQuestion(link); - if (!isNominationExists(nomination, existingNominations)) { + if (!VoteServicePOJO.isNominationExists(nomination, existingNominations)) { saveOrUpdateVoteQueContent(nomination); voteContent.getVoteQueContents().add(nomination); nominationIndex++; @@ -829,7 +835,7 @@ int nominationIndex = voteContent.getVoteQueContents().size() + 1; SimpleURL[] userUrls = (SimpleURL[]) value; for (SimpleURL url : userUrls) { - if (maxInputs != null && inputsAdded >= maxInputs) { + if ((maxInputs != null) && (inputsAdded >= maxInputs)) { // if we reached the maximum number of inputs, i.e. number of students that will be taken // into account break; @@ -841,7 +847,7 @@ String link = "" + url.getNameToDisplay() + ""; nomination.setQuestion(link); - if (!isNominationExists(nomination, existingNominations)) { + if (!VoteServicePOJO.isNominationExists(nomination, existingNominations)) { saveOrUpdateVoteQueContent(nomination); voteContent.getVoteQueContents().add(nomination); nominationIndex++; @@ -857,7 +863,7 @@ SimpleURL url = (SimpleURL) value; String link = "" + url.getNameToDisplay() + ""; nomination.setQuestion(link); - if (!isNominationExists(nomination, existingNominations)) { + if (!VoteServicePOJO.isNominationExists(nomination, existingNominations)) { nomination.setMcContent(voteContent); saveOrUpdateVoteQueContent(nomination); voteContent.getVoteQueContents().add(nomination); @@ -871,7 +877,7 @@ for (VoteQueContent question : questions) { String displayOrder = "" + question.getDisplayOrder(); - if ((checkedOptions == null || checkedOptions.contains(displayOrder)) && !displayOrder.equals("0")) { + if (((checkedOptions == null) || checkedOptions.contains(displayOrder)) && !displayOrder.equals("0")) { /* add the question to the questions Map in the displayOrder */ mapQuestionsContent.put(displayOrder.toString(), question.getQuestion()); } @@ -881,9 +887,9 @@ } private static boolean isNominationExists(VoteQueContent nomination, Set existingNominations) { - if (existingNominations != null && nomination != null) { + if ((existingNominations != null) && (nomination != null)) { for (VoteQueContent existingNomination : existingNominations) { - if (existingNomination.getQuestion() != null + if ((existingNomination.getQuestion() != null) && existingNomination.getQuestion().equals(nomination.getQuestion())) { return true; } @@ -947,20 +953,20 @@ public List getAttemptsForUser(final Long userUid) { return voteUsrAttemptDAO.getAttemptsForUser(userUid); } - + @Override public void createAttempt(VoteQueUsr voteQueUsr, Map mapGeneralCheckedOptionsContent, String userEntry, VoteSession voteSession, Long voteContentUid) { Date attempTime = new Date(System.currentTimeMillis()); String timeZone = TimeZone.getDefault().getDisplayName(); - //in case of free entry + // in case of free entry if (mapGeneralCheckedOptionsContent.size() == 0) { VoteQueContent defaultContentFirstQuestion = voteQueContentDAO.getDefaultVoteContentFirstQuestion(); createAttempt(defaultContentFirstQuestion, voteQueUsr, attempTime, timeZone, userEntry, voteSession); - - //if the question is selected + + // if the question is selected } else if (voteContentUid != null) { Iterator itCheckedMap = mapGeneralCheckedOptionsContent.entrySet().iterator(); while (itCheckedMap.hasNext()) { @@ -973,7 +979,7 @@ } } - + private void createAttempt(VoteQueContent question, VoteQueUsr user, Date attempTime, String timeZone, String userEntry, VoteSession session) { @@ -1019,24 +1025,27 @@ voteContentDAO.updateVoteContent(vote); } + @Override public int countSessionComplete() { return voteSessionDAO.countSessionComplete(); } /** * logs hiding of a user entered vote */ + @Override public void hideOpenVote(VoteUsrAttempt voteUsrAttempt) { - auditService.logHideEntry(VoteAppConstants.MY_SIGNATURE, voteUsrAttempt.getQueUsrId(), voteUsrAttempt - .getVoteQueUsr().getUsername(), voteUsrAttempt.getUserEntry()); + auditService.logHideEntry(VoteAppConstants.MY_SIGNATURE, voteUsrAttempt.getQueUsrId(), + voteUsrAttempt.getVoteQueUsr().getUsername(), voteUsrAttempt.getUserEntry()); } /** * logs showing of a user entered vote */ + @Override public void showOpenVote(VoteUsrAttempt voteUsrAttempt) { - auditService.logShowEntry(VoteAppConstants.MY_SIGNATURE, voteUsrAttempt.getQueUsrId(), voteUsrAttempt - .getVoteQueUsr().getUsername(), voteUsrAttempt.getUserEntry()); + auditService.logShowEntry(VoteAppConstants.MY_SIGNATURE, voteUsrAttempt.getQueUsrId(), + voteUsrAttempt.getVoteQueUsr().getUsername(), voteUsrAttempt.getUserEntry()); } @Override @@ -1061,7 +1070,8 @@ } catch (DataAccessException e) { throw new VoteApplicationException( "Exception occured when lams is getting vote voteUsrRespDAO by user id and que content id: " - + e.getMessage(), e); + + e.getMessage(), + e); } } @@ -1075,7 +1085,7 @@ boolean studentActivityOccurredGlobal = studentActivityOccurredGlobal(voteContent); int userEnteredVotesCount = getUserEnteredVotesCountForContent(voteContent.getUid()); - if (studentActivityOccurredGlobal == true || userEnteredVotesCount > 0) { + if ((studentActivityOccurredGlobal == true) || (userEnteredVotesCount > 0)) { return true; } @@ -1181,56 +1191,38 @@ } } + @SuppressWarnings("unchecked") @Override - public void removeToolContent(Long toolContentID, boolean removeSessionData) throws SessionDataExistsException, - ToolException { - - if (toolContentID == null) { - VoteServicePOJO.logger.error("toolContentID is null"); - throw new ToolException("toolContentID is missing"); + public void removeToolContent(Long toolContentId) throws ToolException { + VoteContent voteContent = voteContentDAO.getVoteContentByContentId(toolContentId); + if (voteContent == null) { + VoteServicePOJO.logger.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; } - VoteContent voteContent = voteContentDAO.getVoteContentByContentId(toolContentID); - - if (voteContent != null) { - Iterator sessionIterator = voteContent.getVoteSessions().iterator(); - while (sessionIterator.hasNext()) { - if (removeSessionData == false) { - VoteServicePOJO.logger.error("removeSessionData is false, throwing SessionDataExistsException."); - throw new SessionDataExistsException(); - } - - VoteSession voteSession = (VoteSession) sessionIterator.next(); - - Iterator sessionUsersIterator = voteSession.getVoteQueUsers().iterator(); - while (sessionUsersIterator.hasNext()) { - VoteQueUsr voteQueUsr = (VoteQueUsr) sessionUsersIterator.next(); - - Iterator sessionUsersAttemptsIterator = voteQueUsr.getVoteUsrAttempts().iterator(); - while (sessionUsersAttemptsIterator.hasNext()) { - VoteUsrAttempt voteUsrAttempt = (VoteUsrAttempt) sessionUsersAttemptsIterator.next(); - voteUsrAttemptDAO.removeVoteUsrAttempt(voteUsrAttempt); - } - } + for (VoteSession session : (Set) voteContent.getVoteSessions()) { + List entries = coreNotebookService.getEntry(session.getVoteSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, VoteAppConstants.MY_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); } - // removed all existing responses of toolContent with toolContentID - voteContentDAO.removeVoteById(toolContentID); - } else { - VoteServicePOJO.logger.error("Warning!!!, We should have not come here. voteContent is null."); - throw new ToolException("toolContentID is missing"); } + + voteContentDAO.delete(voteContent); } @SuppressWarnings("unchecked") @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("Removing Vote attempts for user ID " + userId + " and toolContentId " + toolContentId); + if (VoteServicePOJO.logger.isDebugEnabled()) { + VoteServicePOJO.logger + .debug("Removing Vote attempts for user ID " + userId + " and toolContentId " + toolContentId); } VoteContent voteContent = voteContentDAO.getVoteContentByContentId(toolContentId); if (voteContent == null) { - logger.warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); + VoteServicePOJO.logger + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } @@ -1284,8 +1276,8 @@ Object toolPOJO = exportContentService.importToolContent(toolContentPath, voteToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof VoteContent)) { - throw new ImportToolContentException("Import Vote tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import Vote tool content failed. Deserialized object is " + toolPOJO); } VoteContent toolContentObj = (VoteContent) toolPOJO; @@ -1298,7 +1290,7 @@ throw new ToolException(e); } } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { VoteContent voteContent = getVoteContent(toolContentId); @@ -1403,13 +1395,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionID) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionID) + throws DataMissingException, ToolException { throw new ToolException("not yet implemented"); } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIDs) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIDs) + throws DataMissingException, ToolException { throw new ToolException("not yet implemented"); } @@ -1426,7 +1419,7 @@ contentId = toolService.getToolDefaultContentIdBySignature(toolSignature); return contentId; } - + @Override public List getToolSessionsForContent(VoteContent vote) { List listToolSessionIds = voteSessionDAO.getSessionsFromContent(vote); @@ -1468,7 +1461,7 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return voteOutputFactory.getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { Long userId = user.getUserId().longValue(); @@ -1495,7 +1488,7 @@ VoteQueUsr groupLeader = session.getGroupLeader(); // check if leader has submitted answers - if (groupLeader != null && groupLeader.isResponseFinalised()) { + if ((groupLeader != null) && groupLeader.isResponseFinalised()) { // we need to make sure specified user has the same scratches as a leader copyAnswersFromLeader(voteUser, groupLeader); @@ -1514,8 +1507,8 @@ toolContentObj.setCreatedBy(user.getUserID().longValue()); toolContentObj.setCreationDate(now); toolContentObj.setDefineLater(false); - toolContentObj.setInstructions(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); + toolContentObj.setInstructions( + WebUtil.convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY))); toolContentObj.setReflectionSubject(null); toolContentObj.setReflect(false); toolContentObj.setUseSelectLeaderToolOuput(false); @@ -1546,10 +1539,8 @@ } catch (WDDXProcessorConversionException e) { VoteServicePOJO.logger.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."); + 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."); } // leave as empty, no need to set them to anything. @@ -1572,8 +1563,8 @@ } @Override - public void setReflectiveData(Long toolContentId, String title, String description) throws ToolException, - DataMissingException { + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { VoteContent toolContentObj = null; if (toolContentId != null) { @@ -1588,14 +1579,16 @@ toolContentObj.setReflectionSubject(description); } + @Override public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry) { return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); } + @Override public NotebookEntry getEntry(Long id, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(id, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -1870,10 +1863,12 @@ this.messageService = messageService; } + @Override public void removeQuestionsFromCache(VoteContent voteContent) { voteContentDAO.removeQuestionsFromCache(voteContent); } + @Override public void removeVoteContentFromCache(VoteContent voteContent) { voteContentDAO.removeVoteContentFromCache(voteContent); } @@ -1882,12 +1877,14 @@ this.dataFlowDAO = dataFlowDAO; } + @Override public ToolOutput getToolInput(Long requestingToolContentId, Integer learnerId) { // just forwarding to learner service return learnerService.getToolInput(requestingToolContentId, VoteAppConstants.DATA_FLOW_OBJECT_ASSIGMENT_ID, learnerId); } + @Override public void saveDataFlowObjectAssigment(DataFlowObject assignedDataFlowObject) { // this also should be done in learner service, but for simplicity... if (assignedDataFlowObject != null) { @@ -1896,23 +1893,26 @@ } } + @Override public DataFlowObject getAssignedDataFlowObject(Long toolContentId) { return dataFlowDAO.getAssignedDataFlowObject(toolContentId, VoteAppConstants.DATA_FLOW_OBJECT_ASSIGMENT_ID); } + @Override public List getDataFlowObjects(Long toolContentId) { return dataFlowDAO.getDataFlowObjectsByToolContentId(toolContentId); } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getVoteOutputFactory().getSupportedDefinitionClasses(definitionType); } - + // ****************** REST methods ************************* /** - * Rest call to create a new Vote content. Required fields in toolContentJSON: "title", "instructions", - * "answers". The "answers" entry should be a JSONArray of Strings. + * Rest call to create a new Vote content. Required fields in toolContentJSON: "title", "instructions", "answers". + * The "answers" entry should be a JSONArray of Strings. */ @SuppressWarnings("unchecked") @Override @@ -1938,22 +1938,23 @@ vote.setReflect(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); vote.setReflectionSubject(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, (String) null)); vote.setShowResults(JsonUtil.opt(toolContentJSON, "showResults", Boolean.TRUE)); - vote.setUseSelectLeaderToolOuput(JsonUtil.opt(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE)); + vote.setUseSelectLeaderToolOuput( + JsonUtil.opt(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE)); // Is the data flow functionality actually used anywhere? - vote.setAssignedDataFlowObject((Boolean)JsonUtil.opt(toolContentJSON, "assignedDataFlowObject", null)); - vote.setExternalInputsAdded((Short)JsonUtil.opt(toolContentJSON, "externalInputsAdded", null)); + vote.setAssignedDataFlowObject((Boolean) JsonUtil.opt(toolContentJSON, "assignedDataFlowObject", null)); + vote.setExternalInputsAdded((Short) JsonUtil.opt(toolContentJSON, "externalInputsAdded", null)); vote.setMaxExternalInputs(JsonUtil.opt(toolContentJSON, "maxInputs", Short.valueOf("0"))); // submissionDeadline is set in monitoring - + // **************************** Nomination entries ********************* JSONArray answers = toolContentJSON.getJSONArray(RestTags.ANSWERS); - Set newAnswersSet = vote.getVoteQueContents(); + Set newAnswersSet = vote.getVoteQueContents(); for (int i = 0; i < answers.length(); i++) { String answerJSONData = (String) answers.get(i); VoteQueContent answer = new VoteQueContent(); - answer.setDisplayOrder(i+1); + answer.setDisplayOrder(i + 1); answer.setMcContent(vote); answer.setQuestion((String) answers.get(i)); answer.setVoteContent(vote); Index: lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/VoteMonitoringStarterAction.java =================================================================== diff -u -r5b17b810b5302c90b2daf6a5866bf4f6e85bef6a -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/VoteMonitoringStarterAction.java (.../VoteMonitoringStarterAction.java) (revision 5b17b810b5302c90b2daf6a5866bf4f6e85bef6a) +++ lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/VoteMonitoringStarterAction.java (.../VoteMonitoringStarterAction.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -77,6 +77,7 @@ public class VoteMonitoringStarterAction extends Action implements VoteAppConstants { static Logger logger = Logger.getLogger(VoteMonitoringStarterAction.class.getName()); + @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, VoteApplicationException { VoteUtils.cleanUpUserExceptions(request); @@ -95,7 +96,7 @@ return validateParameters; } - //initialiseMonitoringData + // initialiseMonitoringData voteGeneralMonitoringDTO.setRequestLearningReport(new Boolean(false).toString()); /* we have made sure TOOL_CONTENT_ID is passed */ @@ -105,7 +106,7 @@ if (voteContent == null) { VoteUtils.cleanUpUserExceptions(request); voteGeneralMonitoringDTO.setUserExceptionContentDoesNotExist(new Boolean(true).toString()); - return (mapping.findForward(ERROR_LIST)); + return (mapping.findForward(VoteAppConstants.ERROR_LIST)); } voteGeneralMonitoringDTO.setActivityTitle(voteContent.getTitle()); @@ -120,8 +121,8 @@ * get the nominations section is needed for the Edit tab's View Only mode, starts here */ SessionMap sessionMap = new SessionMap(); - sessionMap.put(ACTIVITY_TITLE_KEY, voteContent.getTitle()); - sessionMap.put(ACTIVITY_INSTRUCTIONS_KEY, voteContent.getInstructions()); + sessionMap.put(VoteAppConstants.ACTIVITY_TITLE_KEY, voteContent.getTitle()); + sessionMap.put(VoteAppConstants.ACTIVITY_INSTRUCTIONS_KEY, voteContent.getInstructions()); voteMonitoringForm.setHttpSessionID(sessionMap.getSessionID()); request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap); @@ -141,8 +142,8 @@ } } - request.setAttribute(LIST_QUESTION_DTO, listQuestionDTO); - sessionMap.put(LIST_QUESTION_DTO, listQuestionDTO); + request.setAttribute(VoteAppConstants.LIST_QUESTION_DTO, listQuestionDTO); + sessionMap.put(VoteAppConstants.LIST_QUESTION_DTO, listQuestionDTO); /* this section is related to summary tab. Starts here. */ @@ -153,7 +154,7 @@ } String userExceptionNoToolSessions = voteGeneralMonitoringDTO.getUserExceptionNoToolSessions(); - + Set questions = voteContent.getVoteQueContents(); List listMonitoredAnswersContainerDTO = new LinkedList(); @@ -171,7 +172,7 @@ List> listMonitoredAttemptsContainerDTO = new LinkedList>(); - //populateToolSessionsId + // populateToolSessionsId List sessionIds = voteService.getSessionsFromContent(voteContent); Map summaryToolSessions = new TreeMap(new VoteComparator()); int mapIndex = 1; @@ -198,15 +199,15 @@ } } } - -// //create data for All sessions in total -// if (summaryToolSessions.size() > 1) { -// Map sessionUsersAttempts = populateSessionUsersAttempts(request, -// voteContent, voteSession.getVoteSessionId(), users, questionUid, isUserNamesVisible, -// isLearnerRequest, userId, voteService); -// listMonitoredAttemptsContainerDTO.add(sessionUsersAttempts); -// } + // //create data for All sessions in total + // if (summaryToolSessions.size() > 1) { + // Map sessionUsersAttempts = populateSessionUsersAttempts(request, + // voteContent, voteSession.getVoteSessionId(), users, questionUid, isUserNamesVisible, + // isLearnerRequest, userId, voteService); + // listMonitoredAttemptsContainerDTO.add(sessionUsersAttempts); + // } + Map questionAttemptData = new TreeMap(new VoteComparator()); Iterator listIterator = listMonitoredAttemptsContainerDTO.iterator(); Long mapIndex2 = new Long(1); @@ -222,8 +223,8 @@ } /* ends here. */ - List userEnteredNominations = voteService.getOpenVotes( - voteContent.getUid(), null, null); + List userEnteredNominations = voteService.getOpenVotes(voteContent.getUid(), null, + null); voteGeneralMonitoringDTO.setListMonitoredAnswersContainerDto(listMonitoredAnswersContainerDTO); voteGeneralMonitoringDTO.setListUserEntries(userEnteredNominations); @@ -245,7 +246,7 @@ if (!voteContent.getVoteSessions().isEmpty()) { request.setAttribute(VoteAppConstants.NOTEBOOK_ENTRIES_EXIST, new Boolean(true).toString()); if (userExceptionNoToolSessions.equals("true")) { - //there are no online student activity but there are reflections + // there are no online student activity but there are reflections request.setAttribute(VoteAppConstants.NO_SESSIONS_NOTEBOOK_ENTRIES_EXIST, new Boolean(true).toString()); } } else { @@ -260,7 +261,7 @@ VoteSession voteSession = (VoteSession) iteratorSession.next(); if (voteSession != null) { - if (voteSession.getSessionStatus().equals(COMPLETED)) { + if (voteSession.getSessionStatus().equals(VoteAppConstants.COMPLETED)) { ++countSessionComplete; } @@ -277,7 +278,7 @@ VoteStatsDTO voteStatsDTO = new VoteStatsDTO(); voteStatsDTO.setCountAllUsers(new Integer(countAllUsers).toString()); voteStatsDTO.setCountSessionComplete(new Integer(countSessionComplete).toString()); - request.setAttribute(VOTE_STATS_DTO, voteStatsDTO); + request.setAttribute(VoteAppConstants.VOTE_STATS_DTO, voteStatsDTO); // setting up the advanced summary for LDEV-1662 request.setAttribute("useSelectLeaderToolOuput", voteContent.isUseSelectLeaderToolOuput()); @@ -322,12 +323,11 @@ List sessionDTOs = voteService.getSessionDTOs(new Long(toolContentID)); voteGeneralMonitoringDTO.setSessionDTOs(sessionDTOs); - + boolean isGroupedActivity = voteService.isGroupedActivity(new Long(toolContentID)); request.setAttribute("isGroupedActivity", isGroupedActivity); - - //refreshStatsData + // refreshStatsData /* it is possible that no users has ever logged in for the activity yet */ int countAllUsers2 = voteService.getTotalNumberOfUsers(); if (countAllUsers2 == 0) { @@ -339,10 +339,10 @@ List reflectionsContainerDTO = voteService.getReflectionData(voteContent, null); request.setAttribute(VoteAppConstants.REFLECTIONS_CONTAINER_DTO, reflectionsContainerDTO); - + return mapping.findForward(VoteAppConstants.LOAD_MONITORING); } - + private static Map populateSessionUsersAttempts(HttpServletRequest request, VoteContent voteContent, Long sessionId, List listUsers, String questionUid, boolean isLearnerRequest, Long userId, IVoteService voteService) { @@ -400,7 +400,7 @@ // summary reporting case 2 // just populating data normally just like monitoring summary, except that the data is ony for a // specific session - String userID = (String) request.getSession().getAttribute(USER_ID); + String userID = (String) request.getSession().getAttribute(VoteAppConstants.USER_ID); VoteQueUsr voteQueUsr = voteService.getUserById(new Long(userID).longValue()); while (itUsers.hasNext()) { @@ -427,7 +427,7 @@ VoteQueContent voteQueContent = voteUsrResp.getVoteQueContent(); String entry = voteQueContent.getQuestion(); - String questionUid2 = voteUsrResp.getVoteQueContentId().toString(); + String questionUid2 = voteUsrResp.getVoteQueContent().getUid().toString(); VoteSession localUserSession = voteUsrResp.getVoteQueUsr().getVoteSession(); if (voteContent.getVoteContentId().toString() @@ -477,7 +477,7 @@ VoteQueContent voteQueContent = voteUsrResp.getVoteQueContent(); String entry = voteQueContent.getQuestion(); - String voteQueContentId = voteUsrResp.getVoteQueContentId().toString(); + String voteQueContentId = voteUsrResp.getVoteQueContent().getUid().toString(); VoteSession localUserSession = voteUsrResp.getVoteQueUsr().getVoteSession(); if (voteContent.getVoteContentId().toString() @@ -500,7 +500,8 @@ } - Map mapMonitoredUserContainerDTO = MonitoringUtil.convertToVoteMonitoredUserDTOMap(listMonitoredUserContainerDTO); + Map mapMonitoredUserContainerDTO = MonitoringUtil + .convertToVoteMonitoredUserDTOMap(listMonitoredUserContainerDTO); return mapMonitoredUserContainerDTO; } @@ -511,14 +512,14 @@ if ((strToolContentId == null) || (strToolContentId.length() == 0)) { VoteUtils.cleanUpUserExceptions(request); - return (mapping.findForward(ERROR_LIST)); + return (mapping.findForward(VoteAppConstants.ERROR_LIST)); } else { try { voteMonitoringForm.setToolContentID(strToolContentId); } catch (NumberFormatException e) { - logger.error("add error.numberFormatException to ActionMessages."); + VoteMonitoringStarterAction.logger.error("add error.numberFormatException to ActionMessages."); VoteUtils.cleanUpUserExceptions(request); - return (mapping.findForward(ERROR_LIST)); + return (mapping.findForward(VoteAppConstants.ERROR_LIST)); } } return null; Index: lams_tool_wiki/src/java/org/lamsfoundation/lams/tool/wiki/service/WikiService.java =================================================================== diff -u -ra207bdecc16a704428826dbf402a97de2e35458b -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_wiki/src/java/org/lamsfoundation/lams/tool/wiki/service/WikiService.java (.../WikiService.java) (revision a207bdecc16a704428826dbf402a97de2e35458b) +++ lams_tool_wiki/src/java/org/lamsfoundation/lams/tool/wiki/service/WikiService.java (.../WikiService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -85,7 +85,8 @@ * * As a requirement, all LAMS tool's service bean must implement ToolContentManager and ToolSessionManager. */ -public class WikiService implements ToolSessionManager, ToolContentManager, IWikiService, ToolContentImport102Manager, ToolRestManager { +public class WikiService + implements ToolSessionManager, ToolContentManager, IWikiService, ToolContentImport102Manager, ToolRestManager { private static Logger logger = Logger.getLogger(WikiService.class.getName()); @@ -141,11 +142,11 @@ // Create an empty list to copy the wiki pages into Set sessionWikiPages = new HashSet(); - + // Here we need to clone wikipages and content for tool session versions - //for (WikiPage childPage : wiki.getWikiPages()) { // LDEV-2436 + // for (WikiPage childPage : wiki.getWikiPages()) { // LDEV-2436 for (WikiPage childPage : (List) wikiDAO.findByProperty(WikiPage.class, "parentWiki", wiki)) { - + // check that this page does not already have a session if (childPage.getWikiSession() != null) { continue; @@ -184,13 +185,14 @@ } @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { return null; } @Override - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, - ToolException { + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) + throws DataMissingException, ToolException { return null; } @@ -219,10 +221,10 @@ } return wikiOutputFactory.getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { - //no actions required + // no actions required } @Override @@ -235,17 +237,17 @@ } return wikiOutputFactory.getToolOutputDefinitions(wiki, definitionType); } - + @Override public String getToolContentTitle(Long toolContentId) { return getWikiByContentId(toolContentId).getTitle(); } - + @Override public boolean isContentEdited(Long toolContentId) { return getWikiByContentId(toolContentId).isDefineLater(); } - + /* ************ Methods from ToolContentManager ************************* */ @Override @@ -273,7 +275,7 @@ insertUnsavedWikiContent(toContent); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Wiki wiki = wikiDAO.getByContentId(toolContentId); @@ -285,30 +287,45 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { - // TODO Auto-generated method stub + public void removeToolContent(Long toolContentId) throws SessionDataExistsException, ToolException { + Wiki wiki = wikiDAO.getByContentId(toolContentId); + if (wiki == null) { + WikiService.logger.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (WikiSession session : wiki.getWikiSessions()) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, WikiConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); + } + } + + wikiDAO.delete(wiki); } - + @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("Removing Wiki contents for user ID " + userId + " and toolContentId " + toolContentId); + if (WikiService.logger.isDebugEnabled()) { + WikiService.logger + .debug("Removing Wiki contents for user ID " + userId + " and toolContentId " + toolContentId); } Wiki wiki = wikiDAO.getByContentId(toolContentId); if (wiki == null) { - logger.warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); + WikiService.logger + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } for (WikiSession session : wiki.getWikiSessions()) { /* for (WikiPage page : session.getWikiPages()) { - if (page.getAddedBy() != null && page.getAddedBy().getUserId().equals(userId.longValue())) { - page.setDeleted(true); - wikiPageDAO.update(page); - } + if (page.getAddedBy() != null && page.getAddedBy().getUserId().equals(userId.longValue())) { + page.setDeleted(true); + wikiPageDAO.update(page); + } } */ @@ -325,7 +342,7 @@ } } } - + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { Wiki wiki = wikiDAO.getByContentId(toolContentId); @@ -372,12 +389,12 @@ try { // register version filter class exportContentService.registerImportVersionFilterClass(WikiContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, wikiToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof Wiki)) { - throw new ImportToolContentException("Import Wiki tool content failed. Deserialized object is " - + toolPOJO); + throw new ImportToolContentException( + "Import Wiki tool content failed. Deserialized object is " + toolPOJO); } Wiki wiki = (Wiki) toolPOJO; @@ -407,6 +424,7 @@ * @see org.lamsfoundation.lams.tool.wiki.service.IWikiService#createNotebookEntry(java.lang.Long, * java.lang.Integer, java.lang.String, java.lang.Integer, java.lang.String) */ + @Override public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry) { return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); } @@ -416,9 +434,10 @@ * * @see org.lamsfoundation.lams.tool.wiki.service.IWikiService#getEntry(org.lamsfoundation.lams.notebook.model.NotebookEntry) */ + @Override public NotebookEntry getEntry(Long sessionId, Integer idType, String signature, Integer userID) { List list = coreNotebookService.getEntry(sessionId, idType, signature, userID); - if (list == null || list.isEmpty()) { + if ((list == null) || list.isEmpty()) { return null; } else { return list.get(0); @@ -430,6 +449,7 @@ * * @see org.lamsfoundation.lams.tool.wiki.service.IWikiService#updateEntry(org.lamsfoundation.lams.notebook.model.NotebookEntry) */ + @Override public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } @@ -439,6 +459,7 @@ * * @see org.lamsfoundation.lams.tool.wiki.service.IWikiService#comparePages(String,String) */ + @Override public String comparePages(String old, String current) { String oldArray[] = old.replaceAll("[\\t\\n\\r]", "").split("
"); String currentArray[] = current.replaceAll("[\\t\\n\\r]", "").split("
"); @@ -453,15 +474,15 @@ if (difference.getDeletedEnd() == -1) { // Added for (int i = difference.getAddedStart(); i <= difference.getAddedEnd(); i++) { - result.set(i + resultOffset, "
" - + currentArray[i]); + result.set(i + resultOffset, + "
" + currentArray[i]); } } else if (difference.getAddedEnd() == -1) { // Deleted for (int i = difference.getDeletedStart(); i <= difference.getDeletedEnd(); i++) { - if (result.size() > i + resultOffset) { - result.add(i + resultOffset, "
" - + oldArray[i]); + if (result.size() > (i + resultOffset)) { + result.add(i + resultOffset, + "
" + oldArray[i]); } else { result.add("
" + oldArray[i]); } @@ -471,13 +492,13 @@ // Replaced for (int i = difference.getAddedStart(); i <= difference.getAddedEnd(); i++) { - result.set(i + resultOffset, "
" - + currentArray[i]); + result.set(i + resultOffset, + "
" + currentArray[i]); } for (int i = difference.getDeletedStart(); i <= difference.getDeletedEnd(); i++) { - if (result.size() > i + resultOffset) { - result.add(i + resultOffset, "
" - + oldArray[i]); + if (result.size() > (i + resultOffset)) { + result.add(i + resultOffset, + "
" + oldArray[i]); } else { result.add("
" + oldArray[i]); } @@ -512,6 +533,7 @@ * * @see org.lamsfoundation.lams.tool.wiki.service.IWikiService#getDefaultContentIdBySignature(String) */ + @Override public Long getDefaultContentIdBySignature(String toolSignature) { Long toolContentId = null; toolContentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature)); @@ -528,6 +550,7 @@ * * @see org.lamsfoundation.lams.tool.wiki.service.IWikiService#getDefaultContent() */ + @Override public Wiki getDefaultContent() { Long defaultContentID = getDefaultContentIdBySignature(WikiConstants.TOOL_SIGNATURE); Wiki defaultContent = getWikiByContentId(defaultContentID); @@ -544,6 +567,7 @@ * * @see org.lamsfoundation.lams.tool.wiki.service.IWikiService#copyDefaultContent(Long) */ + @Override public Wiki copyDefaultContent(Long newContentID) { if (newContentID == null) { @@ -596,6 +620,7 @@ return wiki; } + @Override public Wiki getWikiByContentId(Long toolContentID) { Wiki wiki = wikiDAO.getByContentId(toolContentID); if (wiki == null) { @@ -604,6 +629,7 @@ return wiki; } + @Override public WikiSession getSessionBySessionId(Long toolSessionId) { WikiSession wikiSession = wikiSessionDAO.getBySessionId(toolSessionId); if (wikiSession == null) { @@ -612,6 +638,7 @@ return wikiSession; } + @Override public WikiUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { return wikiUserDAO.getByUserIdAndSessionId(userId, toolSessionId); } @@ -620,6 +647,7 @@ return wikiUserDAO.getByLoginNameAndSessionId(loginName, toolSessionId); } + @Override public WikiUser getUserByUID(Long uid) { return wikiUserDAO.getByUID(uid); } @@ -630,6 +658,7 @@ * @see org.lamsfoundation.lams.tool.wiki.service.IWikiService#updateWikiPage(org.lamsfoundation.lams.tool.wiki.web.forms.WikiPageForm, * org.lamsfoundation.lams.tool.wiki.model.WikiPage, org.lamsfoundation.lams.tool.wiki.model.WikiUser) */ + @Override public void updateWikiPage(WikiPageForm wikiPageForm, WikiPage wikiPage, WikiUser user) { if (wikiPage == null) { @@ -667,6 +696,7 @@ * org.lamsfoundation.lams.tool.wiki.model.Wiki, org.lamsfoundation.lams.tool.wiki.model.WikiUser, * org.lamsfoundation.lams.tool.wiki.model.WikiSession) */ + @Override public Long insertWikiPage(WikiPageForm wikiPageForm, Wiki wiki, WikiUser user, WikiSession session) { // First create a new wiki page @@ -703,77 +733,90 @@ return wikiPage.getUid(); } + @Override public void deleteWikiPage(WikiPage wikiPage) { wikiPageDAO.delete(wikiPage); } - + + @Override public void markWikiPageAsDeleted(WikiPage wikiPage) { wikiPage.setDeleted(true); wikiPageDAO.saveOrUpdate(wikiPage); } - + + @Override public void restoreWikiPage(WikiPage wikiPage) { wikiPage.setDeleted(false); wikiPageDAO.saveOrUpdate(wikiPage); } + @Override public void saveOrUpdateWiki(Wiki wiki) { wikiDAO.saveOrUpdate(wiki); } + @Override public void saveOrUpdateWikiPage(WikiPage wikiPage) { wikiPageDAO.saveOrUpdate(wikiPage); } + @Override public WikiPage getWikiPageByWikiAndTitle(Wiki wiki, String title) { return wikiPageDAO.getByWikiAndTitle(wiki, title); } + @Override public WikiPage getWikiBySessionAndTitle(WikiSession wikiSession, String title) { return wikiPageDAO.getBySessionAndTitle(wikiSession, title); } + @Override public WikiPage getWikiPageByUid(Long uid) { List list = wikiPageDAO.findByProperty(WikiPage.class, "uid", uid); - if (list == null || list.size() == 0) { + if ((list == null) || (list.size() == 0)) { return null; } else { return (WikiPage) list.get(0); } } + @Override public WikiPageContent getWikiPageContent(Long uid) { List list = wikiPageContentDAO.findByProperty(WikiPageContent.class, "uid", uid); - if (list == null || list.size() == 0) { + if ((list == null) || (list.size() == 0)) { return null; } else { return (WikiPageContent) list.get(0); } } + @Override public void saveOrUpdateWikiPageContent(WikiPageContent wikiPageContent) { wikiPageContentDAO.saveOrUpdate(wikiPageContent); } + @Override public void saveOrUpdateWikiSession(WikiSession wikiSession) { wikiSessionDAO.saveOrUpdate(wikiSession); } + @Override public void saveOrUpdateWikiUser(WikiUser wikiUser) { wikiUserDAO.saveOrUpdate(wikiUser); } + @Override public WikiUser createWikiUser(UserDTO user, WikiSession wikiSession) { WikiUser wikiUser = new WikiUser(user, wikiSession); saveOrUpdateWikiUser(wikiUser); return wikiUser; } - + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public String getLearnerContentFolder(Long toolSessionId, Long userId) { return toolService.getLearnerContentFolder(toolSessionId, userId); @@ -785,6 +828,7 @@ * @param toolSessionId * @return */ + @Override public int getEditsNum(Long learnerId, Long toolSessionId) { WikiUser wikiUser = getUserByUserIdAndSessionId(learnerId, toolSessionId); @@ -793,7 +837,7 @@ int edits = 0; for (WikiPage wikiPage : wikiSession.getWikiPages()) { for (WikiPageContent wikiPageContent : wikiPage.getWikiContentVersions()) { - if (wikiPageContent.getEditor() != null + if ((wikiPageContent.getEditor() != null) && wikiPageContent.getEditor().getUid().equals(wikiUser.getUid())) { edits++; } @@ -808,6 +852,7 @@ * @param toolSessionId * @return */ + @Override public int getAddsNum(Long learnerId, Long toolSessionId) { WikiUser wikiUser = getUserByUserIdAndSessionId(learnerId, toolSessionId); @@ -816,7 +861,7 @@ int adds = 0; for (WikiPage wikiPage : wikiSession.getWikiPages()) { - if (wikiPage.getAddedBy() != null && wikiPage.getAddedBy().getUid().equals(wikiUser.getUid())) { + if ((wikiPage.getAddedBy() != null) && wikiPage.getAddedBy().getUid().equals(wikiUser.getUid())) { adds++; } } @@ -830,15 +875,16 @@ /** * Import the data for a 1.0.2 Wiki */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { Date now = new Date(); Wiki wiki = new Wiki(); wiki.setContentInUse(Boolean.FALSE); wiki.setCreateBy(new Long(user.getUserID().longValue())); wiki.setCreateDate(now); wiki.setDefineLater(Boolean.FALSE); - wiki.setInstructions(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); + wiki.setInstructions( + WebUtil.convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY))); wiki.setLockOnFinished(Boolean.TRUE); wiki.setTitle((String) importValues.get(ToolContentImport102Manager.CONTENT_TITLE)); wiki.setToolContentId(toolContentId); @@ -857,11 +903,12 @@ /** * 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 { + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { - WikiService.logger - .warn("Setting the reflective field on a wiki. This doesn't make sense as the wiki is for reflection and we don't reflect on reflection!"); + WikiService.logger.warn( + "Setting the reflective field on a wiki. This doesn't make sense as the wiki is for reflection and we don't reflect on reflection!"); Wiki wiki = getWikiByContentId(toolContentId); if (wiki == null) { throw new DataMissingException("Unable to set reflective data titled " + title @@ -966,6 +1013,7 @@ this.wikiOutputFactory = wikiOutputFactory; } + @Override public IEventNotificationService getEventNotificationService() { return eventNotificationService; } @@ -982,10 +1030,12 @@ this.messageService = messageService; } + @Override public String getLocalisedMessage(String key, Object[] args) { return messageService.getMessage(key, args); } + @Override public List getMonitorsByToolSessionId(Long sessionId) { return getLessonService().getMonitorsByToolSessionId(sessionId); } @@ -998,10 +1048,11 @@ this.lessonService = lessonService; } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getWikiOutputFactory().getSupportedDefinitionClasses(definitionType); } - + /* ****************** REST methods **************************************************************************/ /** @@ -1071,9 +1122,9 @@ // Apply the content to the wiki page and save wikiPage.setCurrentWikiContent(wikiPageContent); wikiPage.getWikiContentVersions().add(wikiPageContent); - if ( firstEntry ) { + if (firstEntry) { content.setMainPage(wikiPage); - firstEntry=false; + firstEntry = false; } content.getWikiPages().add(wikiPage); } Index: lams_tool_wookie/src/java/org/lamsfoundation/lams/tool/wookie/service/WookieService.java =================================================================== diff -u -ra207bdecc16a704428826dbf402a97de2e35458b -r9aad33f52b06632e7a8ed3705a7708338bcc00f8 --- lams_tool_wookie/src/java/org/lamsfoundation/lams/tool/wookie/service/WookieService.java (.../WookieService.java) (revision a207bdecc16a704428826dbf402a97de2e35458b) +++ lams_tool_wookie/src/java/org/lamsfoundation/lams/tool/wookie/service/WookieService.java (.../WookieService.java) (revision 9aad33f52b06632e7a8ed3705a7708338bcc00f8) @@ -24,9 +24,6 @@ package org.lamsfoundation.lams.tool.wookie.service; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; import java.util.Date; import java.util.Hashtable; import java.util.List; @@ -49,7 +46,6 @@ import org.lamsfoundation.lams.tool.ToolSessionExportOutputData; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; -import org.lamsfoundation.lams.tool.exception.SessionDataExistsException; import org.lamsfoundation.lams.tool.exception.ToolException; import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.tool.wookie.dao.IWookieConfigItemDAO; @@ -73,239 +69,206 @@ /** * An implementation of the IWookieService interface. * - * As a requirement, all LAMS tool's service bean must implement - * ToolContentManager and ToolSessionManager. + * As a requirement, all LAMS tool's service bean must implement ToolContentManager and ToolSessionManager. */ -public class WookieService implements ToolSessionManager, ToolContentManager, - IWookieService, ToolContentImport102Manager { +public class WookieService + implements ToolSessionManager, ToolContentManager, IWookieService, ToolContentImport102Manager { private static Logger logger = Logger.getLogger(WookieService.class.getName()); - private IWookieDAO wookieDAO = null; + private IWookieDAO wookieDAO = null; - private IWookieSessionDAO wookieSessionDAO = null; + private IWookieSessionDAO wookieSessionDAO = null; - private IWookieUserDAO wookieUserDAO = null; + private IWookieUserDAO wookieUserDAO = null; - private ILearnerService learnerService; + private ILearnerService learnerService; - private ILamsToolService toolService; + private ILamsToolService toolService; - private IToolContentHandler wookieToolContentHandler = null; + private IToolContentHandler wookieToolContentHandler = null; - private IExportToolContentService exportContentService; + private IExportToolContentService exportContentService; - private ICoreNotebookService coreNotebookService; + private ICoreNotebookService coreNotebookService; - private WookieOutputFactory wookieOutputFactory; + private WookieOutputFactory wookieOutputFactory; - private IWookieConfigItemDAO wookieConfigItemDAO; + private IWookieConfigItemDAO wookieConfigItemDAO; - private MessageService messageService; + private MessageService messageService; - private IUserManagementService userManagementService; + private IUserManagementService userManagementService; - public WookieService() { - super(); - } + public WookieService() { + super(); + } - /* ************ Methods from ToolSessionManager ************* */ - - @Override - public void createToolSession(Long toolSessionId, String toolSessionName, - Long toolContentId) throws ToolException { - if (WookieService.logger.isDebugEnabled()) { - WookieService.logger.debug("entering method createToolSession:" - + " toolSessionId = " + toolSessionId - + " toolSessionName = " + toolSessionName - + " toolContentId = " + toolContentId); - } + /* ************ Methods from ToolSessionManager ************* */ - WookieSession session = new WookieSession(); - session.setSessionId(toolSessionId); - session.setSessionName(toolSessionName); - // learner starts - // TODO need to also set other fields. - Wookie wookie = wookieDAO.getByContentId(toolContentId); - session.setWookie(wookie); + @Override + public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException { + if (WookieService.logger.isDebugEnabled()) { + WookieService.logger.debug("entering method createToolSession:" + " toolSessionId = " + toolSessionId + + " toolSessionName = " + toolSessionName + " toolContentId = " + toolContentId); + } - // Create a copy of the widget for the session - // Clone the wookie widget on the external server - String wookieUrl = getWookieURL(); - try { - String newSharedDataKey = toolSessionId.toString() + "_" - + toolContentId.toString(); + WookieSession session = new WookieSession(); + session.setSessionId(toolSessionId); + session.setSessionName(toolSessionName); + // learner starts + // TODO need to also set other fields. + Wookie wookie = wookieDAO.getByContentId(toolContentId); + session.setWookie(wookie); - if (wookieUrl != null) { + // Create a copy of the widget for the session + // Clone the wookie widget on the external server + String wookieUrl = getWookieURL(); + try { + String newSharedDataKey = toolSessionId.toString() + "_" + toolContentId.toString(); - if (wookie.getWidgetIdentifier() != null - && wookie.getWidgetIdentifier() != "") { + if (wookieUrl != null) { - wookieUrl += WookieConstants.RELATIVE_URL_WIDGET_SERVICE; + if ((wookie.getWidgetIdentifier() != null) && (wookie.getWidgetIdentifier() != "")) { - logger.debug("Creating a new clone for session of widget: " - + toolContentId.toString()); - boolean success = WookieUtil.cloneWidget(wookieUrl, - getWookieAPIKey(), wookie.getWidgetIdentifier(), - toolContentId.toString(), newSharedDataKey, wookie - .getCreateBy().toString()); + wookieUrl += WookieConstants.RELATIVE_URL_WIDGET_SERVICE; - if (success) { - session.setWidgetSharedDataKey(newSharedDataKey); - session.setWidgetHeight(wookie.getWidgetHeight()); - session.setWidgetWidth(wookie.getWidgetWidth()); - session.setWidgetMaximise(wookie.getWidgetMaximise()); - session.setWidgetIdentifier(wookie - .getWidgetIdentifier()); - } else { - throw new WookieException( - "Failed to copy widget on wookie server, check log for details."); - } - } + WookieService.logger + .debug("Creating a new clone for session of widget: " + toolContentId.toString()); + boolean success = WookieUtil.cloneWidget(wookieUrl, getWookieAPIKey(), wookie.getWidgetIdentifier(), + toolContentId.toString(), newSharedDataKey, wookie.getCreateBy().toString()); - } else { - throw new WookieException("Wookie url is not set"); - } - } catch (Exception e) { - logger.error("Problem calling wookie server to clone instance", e); - throw new WookieException( - "Problem calling wookie server to clone instance", e); + if (success) { + session.setWidgetSharedDataKey(newSharedDataKey); + session.setWidgetHeight(wookie.getWidgetHeight()); + session.setWidgetWidth(wookie.getWidgetWidth()); + session.setWidgetMaximise(wookie.getWidgetMaximise()); + session.setWidgetIdentifier(wookie.getWidgetIdentifier()); + } else { + throw new WookieException("Failed to copy widget on wookie server, check log for details."); + } } - wookieSessionDAO.saveOrUpdate(session); + } else { + throw new WookieException("Wookie url is not set"); + } + } catch (Exception e) { + WookieService.logger.error("Problem calling wookie server to clone instance", e); + throw new WookieException("Problem calling wookie server to clone instance", e); } - @Override - public String leaveToolSession(Long toolSessionId, Long learnerId) - throws DataMissingException, ToolException { - return learnerService.completeToolSession(toolSessionId, learnerId); - } + wookieSessionDAO.saveOrUpdate(session); + } - @Override - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) - throws DataMissingException, ToolException { - return null; - } + @Override + public String leaveToolSession(Long toolSessionId, Long learnerId) throws DataMissingException, ToolException { + return learnerService.completeToolSession(toolSessionId, learnerId); + } - @Override - @SuppressWarnings("unchecked") - public ToolSessionExportOutputData exportToolSession(List ToolSessionIds) - throws DataMissingException, ToolException { - return null; - } + @Override + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) + throws DataMissingException, ToolException { + return null; + } - @Override - public void removeToolSession(Long toolSessionId) - throws DataMissingException, ToolException { - wookieSessionDAO.deleteBySessionID(toolSessionId); - // TODO check if cascade worked - } + @Override + @SuppressWarnings("unchecked") + public ToolSessionExportOutputData exportToolSession(List ToolSessionIds) + throws DataMissingException, ToolException { + return null; + } - @Override - public SortedMap getToolOutput(List names, - Long toolSessionId, Long learnerId) { - return getWookieOutputFactory().getToolOutput(names, this, - toolSessionId, learnerId); - } + @Override + public void removeToolSession(Long toolSessionId) throws DataMissingException, ToolException { + wookieSessionDAO.deleteBySessionID(toolSessionId); + // TODO check if cascade worked + } - @Override - public ToolOutput getToolOutput(String name, Long toolSessionId, - Long learnerId) { - return getWookieOutputFactory().getToolOutput(name, this, - toolSessionId, learnerId); - } - @Override + public SortedMap getToolOutput(List names, Long toolSessionId, Long learnerId) { + return getWookieOutputFactory().getToolOutput(names, this, toolSessionId, learnerId); + } + + @Override + public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { + return getWookieOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); + } + + @Override public void forceCompleteUser(Long toolSessionId, User user) { // no actions required } - /* ************ Methods from ToolContentManager ************************* */ + /* ************ Methods from ToolContentManager ************************* */ - public void copyToolContent(Long fromContentId, Long toContentId) - throws ToolException { + @Override + public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { - if (WookieService.logger.isDebugEnabled()) { - WookieService.logger.debug("entering method copyToolContent:" - + " fromContentId=" + fromContentId + " toContentId=" - + toContentId); - } + if (WookieService.logger.isDebugEnabled()) { + WookieService.logger.debug("entering method copyToolContent:" + " fromContentId=" + fromContentId + + " toContentId=" + toContentId); + } - if (toContentId == null) { - String error = "Failed to copy tool content: toContentID is null"; - throw new ToolException(error); - } + if (toContentId == null) { + String error = "Failed to copy tool content: toContentID is null"; + throw new ToolException(error); + } - Wookie fromContent = null; - if (fromContentId != null) { - fromContent = wookieDAO.getByContentId(fromContentId); - } - if (fromContent == null) { - // create the fromContent using the default tool content - fromContent = getDefaultContent(); - } - Wookie toContent = Wookie.newInstance(fromContent, toContentId); + Wookie fromContent = null; + if (fromContentId != null) { + fromContent = wookieDAO.getByContentId(fromContentId); + } + if (fromContent == null) { + // create the fromContent using the default tool content + fromContent = getDefaultContent(); + } + Wookie toContent = Wookie.newInstance(fromContent, toContentId); - // Clone the wookie widget on the external server - String wookieUrl = getWookieURL(); - try { - if (wookieUrl != null) { - if (fromContent.getWidgetIdentifier() != null - && fromContent.getWidgetIdentifier() != "") { - wookieUrl += WookieConstants.RELATIVE_URL_WIDGET_SERVICE; + // Clone the wookie widget on the external server + String wookieUrl = getWookieURL(); + try { + if (wookieUrl != null) { + if ((fromContent.getWidgetIdentifier() != null) && (fromContent.getWidgetIdentifier() != "")) { + wookieUrl += WookieConstants.RELATIVE_URL_WIDGET_SERVICE; - logger - .debug("Creating a new clone for copycontent for widget: " - + fromContentId.toString()); - boolean success = WookieUtil.cloneWidget(wookieUrl, - getWookieAPIKey(), fromContent - .getWidgetIdentifier(), fromContentId - .toString(), toContentId.toString(), - fromContent.getCreateBy().toString()); + WookieService.logger + .debug("Creating a new clone for copycontent for widget: " + fromContentId.toString()); + boolean success = WookieUtil.cloneWidget(wookieUrl, getWookieAPIKey(), + fromContent.getWidgetIdentifier(), fromContentId.toString(), toContentId.toString(), + fromContent.getCreateBy().toString()); - if (success) { - toContent - .setWidgetHeight(fromContent.getWidgetHeight()); - toContent.setWidgetWidth(fromContent.getWidgetWidth()); - toContent.setWidgetAuthorUrl(fromContent - .getWidgetAuthorUrl()); - toContent.setWidgetMaximise(fromContent - .getWidgetMaximise()); - toContent.setWidgetIdentifier(fromContent - .getWidgetIdentifier()); - toContent.setCreateBy(fromContent.getCreateBy()); + if (success) { + toContent.setWidgetHeight(fromContent.getWidgetHeight()); + toContent.setWidgetWidth(fromContent.getWidgetWidth()); + toContent.setWidgetAuthorUrl(fromContent.getWidgetAuthorUrl()); + toContent.setWidgetMaximise(fromContent.getWidgetMaximise()); + toContent.setWidgetIdentifier(fromContent.getWidgetIdentifier()); + toContent.setCreateBy(fromContent.getCreateBy()); - // Need to add the author to the widget so authoring - // widget url is different in the copy - User user = (User) userManagementService.findById( - User.class, fromContent.getCreateBy()); - String returnXML = WookieUtil.getWidget(wookieUrl, - getWookieAPIKey(), fromContent - .getWidgetIdentifier(), user - .getUserDTO(), toContentId.toString(), - true); + // Need to add the author to the widget so authoring + // widget url is different in the copy + User user = (User) userManagementService.findById(User.class, fromContent.getCreateBy()); + String returnXML = WookieUtil.getWidget(wookieUrl, getWookieAPIKey(), + fromContent.getWidgetIdentifier(), user.getUserDTO(), toContentId.toString(), true); - toContent.setWidgetAuthorUrl(WookieUtil - .getWidgetUrlFromXML(returnXML)); + toContent.setWidgetAuthorUrl(WookieUtil.getWidgetUrlFromXML(returnXML)); - } else { - throw new WookieException( - "Failed to copy widget on wookie server, check log for details."); - } - } - } else { - throw new WookieException("Wookie url is not set"); - } - } catch (Exception e) { - logger.error("Problem calling wookie server to clone instance", e); - throw new WookieException( - "Problem calling wookie server to clone instance", e); + } else { + throw new WookieException("Failed to copy widget on wookie server, check log for details."); + } } - - wookieDAO.saveOrUpdate(toContent); + } else { + throw new WookieException("Wookie url is not set"); + } + } catch (Exception e) { + WookieService.logger.error("Problem calling wookie server to clone instance", e); + throw new WookieException("Problem calling wookie server to clone instance", e); } - + + wookieDAO.saveOrUpdate(toContent); + } + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Wookie wookie = wookieDAO.getByContentId(toolContentId); @@ -317,20 +280,35 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId) throws ToolException { + Wookie wookie = wookieDAO.getByContentId(toolContentId); + if (wookie == null) { + WookieService.logger.warn("Can not remove the tool content as it does not exist, ID: " + toolContentId); + return; + } + + for (WookieSession session : wookie.getWookieSessions()) { + List entries = coreNotebookService.getEntry(session.getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, WookieConstants.TOOL_SIGNATURE); + for (NotebookEntry entry : entries) { + coreNotebookService.deleteEntry(entry); + } + } + + wookieDAO.delete(wookie); } @Override public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("Resetting Wookie completion flag for user ID " + userId + " and toolContentId " - + toolContentId); + if (WookieService.logger.isDebugEnabled()) { + WookieService.logger.debug( + "Resetting Wookie completion flag for user ID " + userId + " and toolContentId " + toolContentId); } Wookie wookie = getWookieByContentId(toolContentId); if (wookie == null) { - logger.warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); + WookieService.logger + .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content"); return; } @@ -348,428 +326,410 @@ } } - - @Override - public void exportToolContent(Long toolContentId, String rootPath) - throws DataMissingException, ToolException { - Wookie wookie = wookieDAO.getByContentId(toolContentId); - if (wookie == null) { - wookie = getDefaultContent(); - } - if (wookie == null) { - throw new DataMissingException( - "Unable to find default content for the wookie tool"); - } - // set ResourceToolContentHandler as null to avoid copy file node in - // repository again. - wookie = Wookie.newInstance(wookie, toolContentId); - wookie.setWookieSessions(null); + @Override + public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { + Wookie wookie = wookieDAO.getByContentId(toolContentId); + if (wookie == null) { + wookie = getDefaultContent(); + } + if (wookie == null) { + throw new DataMissingException("Unable to find default content for the wookie tool"); + } - try { - exportContentService.exportToolContent(toolContentId, wookie, - wookieToolContentHandler, rootPath); - } catch (ExportToolContentException e) { - throw new ToolException(e); - } + // set ResourceToolContentHandler as null to avoid copy file node in + // repository again. + wookie = Wookie.newInstance(wookie, toolContentId); + wookie.setWookieSessions(null); + + try { + exportContentService.exportToolContent(toolContentId, wookie, wookieToolContentHandler, rootPath); + } catch (ExportToolContentException e) { + throw new ToolException(e); } + } - @Override - public void importToolContent(Long toolContentId, Integer newUserUid, - String toolContentPath, String fromVersion, String toVersion) - throws ToolException { - try { - // register version filter class - exportContentService.registerImportVersionFilterClass(WookieContentVersionFilter.class); - - Object toolPOJO = exportContentService.importToolContent( - toolContentPath, wookieToolContentHandler, fromVersion, - toVersion); - if (!(toolPOJO instanceof Wookie)) { - throw new ImportToolContentException( - "Import Wookie tool content failed. Deserialized object is " - + toolPOJO); - } - Wookie wookie = (Wookie) toolPOJO; + @Override + public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion, + String toVersion) throws ToolException { + try { + // register version filter class + exportContentService.registerImportVersionFilterClass(WookieContentVersionFilter.class); - // reset it to new toolContentId - wookie.setToolContentId(toolContentId); - wookie.setCreateBy(newUserUid); + Object toolPOJO = exportContentService.importToolContent(toolContentPath, wookieToolContentHandler, + fromVersion, toVersion); + if (!(toolPOJO instanceof Wookie)) { + throw new ImportToolContentException( + "Import Wookie tool content failed. Deserialized object is " + toolPOJO); + } + Wookie wookie = (Wookie) toolPOJO; - User user = (User) userManagementService.findById(User.class, - newUserUid); + // reset it to new toolContentId + wookie.setToolContentId(toolContentId); + wookie.setCreateBy(newUserUid); - // If the wookie has an identifier, it has been initiated. Make an - // new instance using the identifier - if (!StringUtils.isEmpty(wookie.getWidgetIdentifier()) - && user != null) { - String wookieUrl = getWookieURL(); - String wookieKey = getWookieAPIKey(); - wookieUrl += WookieConstants.RELATIVE_URL_WIDGET_SERVICE; + User user = (User) userManagementService.findById(User.class, newUserUid); - String returnXML = WookieUtil.getWidget(wookieUrl, wookieKey, - wookie.getWidgetIdentifier(), user.getUserDTO(), - toolContentId.toString(), true); + // If the wookie has an identifier, it has been initiated. Make an + // new instance using the identifier + if (!StringUtils.isEmpty(wookie.getWidgetIdentifier()) && (user != null)) { + String wookieUrl = getWookieURL(); + String wookieKey = getWookieAPIKey(); + wookieUrl += WookieConstants.RELATIVE_URL_WIDGET_SERVICE; - WidgetData widgetData = WookieUtil - .getWidgetDataFromXML(returnXML); - wookie.setWidgetAuthorUrl(widgetData.getUrl()); - wookie.setWidgetIdentifier(wookie.getWidgetIdentifier()); - wookie.setWidgetHeight(widgetData.getHeight()); - wookie.setWidgetMaximise(widgetData.getMaximize()); - wookie.setWidgetWidth(widgetData.getWidth()); - } + String returnXML = WookieUtil.getWidget(wookieUrl, wookieKey, wookie.getWidgetIdentifier(), + user.getUserDTO(), toolContentId.toString(), true); - wookieDAO.saveOrUpdate(wookie); - } catch (ImportToolContentException e) { - throw new ToolException(e); - } catch (Exception e) { - WookieService.logger.error( - "Error during import possibly because of file copy error", - e); - throw new ToolException(e); - } - } + WidgetData widgetData = WookieUtil.getWidgetDataFromXML(returnXML); + wookie.setWidgetAuthorUrl(widgetData.getUrl()); + wookie.setWidgetIdentifier(wookie.getWidgetIdentifier()); + wookie.setWidgetHeight(widgetData.getHeight()); + wookie.setWidgetMaximise(widgetData.getMaximize()); + wookie.setWidgetWidth(widgetData.getWidth()); + } - @Override - public String getFileExtension(String fileName) { - String ext = ""; - int i = fileName.lastIndexOf('.'); - if (i > 0 && i < fileName.length() - 1) { - ext += "." + fileName.substring(i + 1).toLowerCase(); - } - return ext; + wookieDAO.saveOrUpdate(wookie); + } catch (ImportToolContentException e) { + throw new ToolException(e); + } catch (Exception e) { + WookieService.logger.error("Error during import possibly because of file copy error", e); + throw new ToolException(e); } + } - @Override - public SortedMap getToolOutputDefinitions( - Long toolContentId, int definitionType) throws ToolException { - Wookie wookie = getWookieDAO().getByContentId(toolContentId); - if (wookie == null) { - wookie = getDefaultContent(); - } - return getWookieOutputFactory().getToolOutputDefinitions(wookie, - definitionType); + @Override + public String getFileExtension(String fileName) { + String ext = ""; + int i = fileName.lastIndexOf('.'); + if ((i > 0) && (i < (fileName.length() - 1))) { + ext += "." + fileName.substring(i + 1).toLowerCase(); } - - @Override - public String getToolContentTitle(Long toolContentId) { - return getWookieByContentId(toolContentId).getTitle(); - } - - @Override - public boolean isContentEdited(Long toolContentId) { - return getWookieByContentId(toolContentId).isDefineLater(); - } + return ext; + } - @Override - @SuppressWarnings("unchecked") - public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { - return getWookieOutputFactory().getSupportedDefinitionClasses( - definitionType); + @Override + public SortedMap getToolOutputDefinitions(Long toolContentId, int definitionType) + throws ToolException { + Wookie wookie = getWookieDAO().getByContentId(toolContentId); + if (wookie == null) { + wookie = getDefaultContent(); } + return getWookieOutputFactory().getToolOutputDefinitions(wookie, definitionType); + } - /* ********** IWookieService Methods ********************************* */ + @Override + public String getToolContentTitle(Long toolContentId) { + return getWookieByContentId(toolContentId).getTitle(); + } - @Override - public Long createNotebookEntry(Long id, Integer idType, String signature, - Integer userID, String entry) { - return coreNotebookService.createNotebookEntry(id, idType, signature, - userID, "", entry); - } + @Override + public boolean isContentEdited(Long toolContentId) { + return getWookieByContentId(toolContentId).isDefineLater(); + } - 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); - } - } + @Override + @SuppressWarnings("unchecked") + public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { + return getWookieOutputFactory().getSupportedDefinitionClasses(definitionType); + } - /** - * @param notebookEntry - */ - public void updateEntry(NotebookEntry notebookEntry) { - coreNotebookService.updateEntry(notebookEntry); - } + /* ********** IWookieService Methods ********************************* */ - public Long getDefaultContentIdBySignature(String toolSignature) { - Long toolContentId = null; - toolContentId = new Long(toolService - .getToolDefaultContentIdBySignature(toolSignature)); - if (toolContentId == null) { - String error = "Could not retrieve default content id for this tool"; - WookieService.logger.error(error); - throw new WookieException(error); - } - return toolContentId; - } + @Override + public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry) { + return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); + } - public Wookie getDefaultContent() { - Long defaultContentID = getDefaultContentIdBySignature(WookieConstants.TOOL_SIGNATURE); - Wookie defaultContent = getWookieByContentId(defaultContentID); - if (defaultContent == null) { - String error = "Could not retrieve default content record for this tool"; - WookieService.logger.error(error); - throw new WookieException(error); - } - return defaultContent; + @Override + 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 Wookie copyDefaultContent(Long newContentID) { + /** + * @param notebookEntry + */ + @Override + public void updateEntry(NotebookEntry notebookEntry) { + coreNotebookService.updateEntry(notebookEntry); + } - if (newContentID == null) { - String error = "Cannot copy the Wookie tools default content: + " - + "newContentID is null"; - WookieService.logger.error(error); - throw new WookieException(error); - } - - Wookie defaultContent = getDefaultContent(); - // create new wookie using the newContentID - Wookie newContent = new Wookie(); - newContent = Wookie.newInstance(defaultContent, newContentID); - wookieDAO.saveOrUpdate(newContent); - return newContent; + @Override + public Long getDefaultContentIdBySignature(String toolSignature) { + Long toolContentId = null; + toolContentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature)); + if (toolContentId == null) { + String error = "Could not retrieve default content id for this tool"; + WookieService.logger.error(error); + throw new WookieException(error); } + return toolContentId; + } - public Wookie getWookieByContentId(Long toolContentID) { - Wookie wookie = wookieDAO.getByContentId(toolContentID); - if (wookie == null) { - WookieService.logger - .debug("Could not find the content with toolContentID:" - + toolContentID); - } - return wookie; + @Override + public Wookie getDefaultContent() { + Long defaultContentID = getDefaultContentIdBySignature(WookieConstants.TOOL_SIGNATURE); + Wookie defaultContent = getWookieByContentId(defaultContentID); + if (defaultContent == null) { + String error = "Could not retrieve default content record for this tool"; + WookieService.logger.error(error); + throw new WookieException(error); } + return defaultContent; + } - public WookieSession getSessionBySessionId(Long toolSessionId) { - WookieSession wookieSession = wookieSessionDAO - .getBySessionId(toolSessionId); - if (wookieSession == null) { - WookieService.logger - .debug("Could not find the wookie session with toolSessionID:" - + toolSessionId); - } - return wookieSession; - } + @Override + public Wookie copyDefaultContent(Long newContentID) { - public WookieUser getUserByUserIdAndSessionId(Long userId, - Long toolSessionId) { - return wookieUserDAO.getByUserIdAndSessionId(userId, toolSessionId); + if (newContentID == null) { + String error = "Cannot copy the Wookie tools default content: + " + "newContentID is null"; + WookieService.logger.error(error); + throw new WookieException(error); } - public WookieUser getUserByLoginNameAndSessionId(String loginName, - Long toolSessionId) { - return wookieUserDAO.getByLoginNameAndSessionId(loginName, - toolSessionId); - } + Wookie defaultContent = getDefaultContent(); + // create new wookie using the newContentID + Wookie newContent = new Wookie(); + newContent = Wookie.newInstance(defaultContent, newContentID); + wookieDAO.saveOrUpdate(newContent); + return newContent; + } - public WookieUser getUserByUID(Long uid) { - return wookieUserDAO.getByUID(uid); + @Override + public Wookie getWookieByContentId(Long toolContentID) { + Wookie wookie = wookieDAO.getByContentId(toolContentID); + if (wookie == null) { + WookieService.logger.debug("Could not find the content with toolContentID:" + toolContentID); } + return wookie; + } - public void saveOrUpdateWookie(Wookie wookie) { - wookieDAO.saveOrUpdate(wookie); + @Override + public WookieSession getSessionBySessionId(Long toolSessionId) { + WookieSession wookieSession = wookieSessionDAO.getBySessionId(toolSessionId); + if (wookieSession == null) { + WookieService.logger.debug("Could not find the wookie session with toolSessionID:" + toolSessionId); } + return wookieSession; + } - public void saveOrUpdateWookieSession(WookieSession wookieSession) { - wookieSessionDAO.saveOrUpdate(wookieSession); - } + @Override + public WookieUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { + return wookieUserDAO.getByUserIdAndSessionId(userId, toolSessionId); + } - public void saveOrUpdateWookieUser(WookieUser wookieUser) { - wookieUserDAO.saveOrUpdate(wookieUser); - } + public WookieUser getUserByLoginNameAndSessionId(String loginName, Long toolSessionId) { + return wookieUserDAO.getByLoginNameAndSessionId(loginName, toolSessionId); + } - public WookieUser createWookieUser(UserDTO user, WookieSession wookieSession) { - WookieUser wookieUser = new WookieUser(user, wookieSession); - saveOrUpdateWookieUser(wookieUser); - return wookieUser; - } + @Override + public WookieUser getUserByUID(Long uid) { + return wookieUserDAO.getByUID(uid); + } - public WookieConfigItem getConfigItem(String key) { - return wookieConfigItemDAO.getConfigItemByKey(key); - } + @Override + public void saveOrUpdateWookie(Wookie wookie) { + wookieDAO.saveOrUpdate(wookie); + } - public void saveOrUpdateWookieConfigItem(WookieConfigItem item) { - wookieConfigItemDAO.saveOrUpdate(item); - } + @Override + public void saveOrUpdateWookieSession(WookieSession wookieSession) { + wookieSessionDAO.saveOrUpdate(wookieSession); + } - public String getWookieURL() { - String url = null; - WookieConfigItem urlItem = wookieConfigItemDAO - .getConfigItemByKey(WookieConfigItem.KEY_WOOKIE_URL); - if (urlItem != null) { - url = urlItem.getConfigValue(); - } - return url; - } + @Override + public void saveOrUpdateWookieUser(WookieUser wookieUser) { + wookieUserDAO.saveOrUpdate(wookieUser); + } - public String getWookieAPIKey() { - String url = null; - WookieConfigItem apiItem = wookieConfigItemDAO - .getConfigItemByKey(WookieConfigItem.KEY_API); - if (apiItem != null) { - url = apiItem.getConfigValue(); - } - return url; + @Override + public WookieUser createWookieUser(UserDTO user, WookieSession wookieSession) { + WookieUser wookieUser = new WookieUser(user, wookieSession); + saveOrUpdateWookieUser(wookieUser); + return wookieUser; + } + + @Override + public WookieConfigItem getConfigItem(String key) { + return wookieConfigItemDAO.getConfigItemByKey(key); + } + + @Override + public void saveOrUpdateWookieConfigItem(WookieConfigItem item) { + wookieConfigItemDAO.saveOrUpdate(item); + } + + @Override + public String getWookieURL() { + String url = null; + WookieConfigItem urlItem = wookieConfigItemDAO.getConfigItemByKey(WookieConfigItem.KEY_WOOKIE_URL); + if (urlItem != null) { + url = urlItem.getConfigValue(); } + return url; + } - public String getMessage(String key) { - return messageService.getMessage(key); + @Override + public String getWookieAPIKey() { + String url = null; + WookieConfigItem apiItem = wookieConfigItemDAO.getConfigItemByKey(WookieConfigItem.KEY_API); + if (apiItem != null) { + url = apiItem.getConfigValue(); } + return url; + } - /* - * ===============Methods implemented from ToolContentImport102Manager - * =============== - */ + @Override + public String getMessage(String key) { + return messageService.getMessage(key); + } - /** - * Import the data for a 1.0.2 Wookie - */ - @SuppressWarnings("unchecked") - public void import102ToolContent(Long toolContentId, UserDTO user, - Hashtable importValues) { - Date now = new Date(); - Wookie wookie = new Wookie(); - wookie.setContentInUse(Boolean.FALSE); - wookie.setCreateBy(user.getUserID()); - wookie.setCreateDate(now); - wookie.setDefineLater(Boolean.FALSE); - wookie.setInstructions(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); - wookie.setLockOnFinished(Boolean.TRUE); - wookie.setTitle((String) importValues - .get(ToolContentImport102Manager.CONTENT_TITLE)); - wookie.setToolContentId(toolContentId); - wookie.setUpdateDate(now); - wookie.setReflectOnActivity(Boolean.FALSE); - wookieDAO.saveOrUpdate(wookie); - } + /* + * ===============Methods implemented from ToolContentImport102Manager + * =============== + */ - /** - * 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 { + /** + * Import the data for a 1.0.2 Wookie + */ + @Override + @SuppressWarnings("unchecked") + public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { + Date now = new Date(); + Wookie wookie = new Wookie(); + wookie.setContentInUse(Boolean.FALSE); + wookie.setCreateBy(user.getUserID()); + wookie.setCreateDate(now); + wookie.setDefineLater(Boolean.FALSE); + wookie.setInstructions( + WebUtil.convertNewlines((String) importValues.get(ToolContentImport102Manager.CONTENT_BODY))); + wookie.setLockOnFinished(Boolean.TRUE); + wookie.setTitle((String) importValues.get(ToolContentImport102Manager.CONTENT_TITLE)); + wookie.setToolContentId(toolContentId); + wookie.setUpdateDate(now); + wookie.setReflectOnActivity(Boolean.FALSE); + wookieDAO.saveOrUpdate(wookie); + } - WookieService.logger - .warn("Setting the reflective field on a wookie. This doesn't make sense as the wookie is for reflection and we don't reflect on reflection!"); - Wookie wookie = getWookieByContentId(toolContentId); - if (wookie == 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 + */ + @Override + public void setReflectiveData(Long toolContentId, String title, String description) + throws ToolException, DataMissingException { - wookie.setInstructions(description); + WookieService.logger.warn( + "Setting the reflective field on a wookie. This doesn't make sense as the wookie is for reflection and we don't reflect on reflection!"); + Wookie wookie = getWookieByContentId(toolContentId); + if (wookie == null) { + throw new DataMissingException("Unable to set reflective data titled " + title + + " on activity toolContentId " + toolContentId + " as the tool content does not exist."); } - // ========================================================================================= - /* ********** Used by Spring to "inject" the linked objects ************* */ + wookie.setInstructions(description); + } - public IWookieDAO getWookieDAO() { - return wookieDAO; - } + // ========================================================================================= + /* ********** Used by Spring to "inject" the linked objects ************* */ - public void setWookieDAO(IWookieDAO wookieDAO) { - this.wookieDAO = wookieDAO; - } + public IWookieDAO getWookieDAO() { + return wookieDAO; + } - public IToolContentHandler getWookieToolContentHandler() { - return wookieToolContentHandler; - } + public void setWookieDAO(IWookieDAO wookieDAO) { + this.wookieDAO = wookieDAO; + } - public void setWookieToolContentHandler( - IToolContentHandler wookieToolContentHandler) { - this.wookieToolContentHandler = wookieToolContentHandler; - } + public IToolContentHandler getWookieToolContentHandler() { + return wookieToolContentHandler; + } - public IWookieSessionDAO getWookieSessionDAO() { - return wookieSessionDAO; - } + public void setWookieToolContentHandler(IToolContentHandler wookieToolContentHandler) { + this.wookieToolContentHandler = wookieToolContentHandler; + } - public void setWookieSessionDAO(IWookieSessionDAO sessionDAO) { - wookieSessionDAO = sessionDAO; - } + public IWookieSessionDAO getWookieSessionDAO() { + return wookieSessionDAO; + } - public ILamsToolService getToolService() { - return toolService; - } + public void setWookieSessionDAO(IWookieSessionDAO sessionDAO) { + wookieSessionDAO = sessionDAO; + } - public void setToolService(ILamsToolService toolService) { - this.toolService = toolService; - } + public ILamsToolService getToolService() { + return toolService; + } - public IWookieUserDAO getWookieUserDAO() { - return wookieUserDAO; - } + public void setToolService(ILamsToolService toolService) { + this.toolService = toolService; + } - public void setWookieUserDAO(IWookieUserDAO userDAO) { - wookieUserDAO = userDAO; - } + public IWookieUserDAO getWookieUserDAO() { + return wookieUserDAO; + } - public ILearnerService getLearnerService() { - return learnerService; - } + public void setWookieUserDAO(IWookieUserDAO userDAO) { + wookieUserDAO = userDAO; + } - public void setLearnerService(ILearnerService learnerService) { - this.learnerService = learnerService; - } + public ILearnerService getLearnerService() { + return learnerService; + } - public IExportToolContentService getExportContentService() { - return exportContentService; - } + public void setLearnerService(ILearnerService learnerService) { + this.learnerService = learnerService; + } - public void setExportContentService( - IExportToolContentService exportContentService) { - this.exportContentService = exportContentService; - } + public IExportToolContentService getExportContentService() { + return exportContentService; + } - public ICoreNotebookService getCoreNotebookService() { - return coreNotebookService; - } + public void setExportContentService(IExportToolContentService exportContentService) { + this.exportContentService = exportContentService; + } - public void setCoreNotebookService(ICoreNotebookService coreNotebookService) { - this.coreNotebookService = coreNotebookService; - } + public ICoreNotebookService getCoreNotebookService() { + return coreNotebookService; + } - public WookieOutputFactory getWookieOutputFactory() { - return wookieOutputFactory; - } + public void setCoreNotebookService(ICoreNotebookService coreNotebookService) { + this.coreNotebookService = coreNotebookService; + } - public void setWookieOutputFactory(WookieOutputFactory wookieOutputFactory) { - this.wookieOutputFactory = wookieOutputFactory; - } + public WookieOutputFactory getWookieOutputFactory() { + return wookieOutputFactory; + } - public IWookieConfigItemDAO getWookieConfigItemDAO() { - return wookieConfigItemDAO; - } + public void setWookieOutputFactory(WookieOutputFactory wookieOutputFactory) { + this.wookieOutputFactory = wookieOutputFactory; + } - public void setWookieConfigItemDAO(IWookieConfigItemDAO wookieConfigItemDAO) { - this.wookieConfigItemDAO = wookieConfigItemDAO; - } + public IWookieConfigItemDAO getWookieConfigItemDAO() { + return wookieConfigItemDAO; + } - public MessageService getMessageService() { - return messageService; - } + public void setWookieConfigItemDAO(IWookieConfigItemDAO wookieConfigItemDAO) { + this.wookieConfigItemDAO = wookieConfigItemDAO; + } - public void setMessageService(MessageService messageService) { - this.messageService = messageService; - } + public MessageService getMessageService() { + return messageService; + } - public IUserManagementService getUserManagementService() { - return userManagementService; - } + public void setMessageService(MessageService messageService) { + this.messageService = messageService; + } - public void setUserManagementService( - IUserManagementService userManagementService) { - this.userManagementService = userManagementService; - } + public IUserManagementService getUserManagementService() { + return userManagementService; + } + public void setUserManagementService(IUserManagementService userManagementService) { + this.userManagementService = userManagementService; + } + }