Index: lams_build/lib/lams/lams.jar =================================================================== diff -u -rf7f4808672a3ca66927a662a165bbe66ab5608f4 -r0aae4208886026f429f05b458b79c14f8d7030d4 Binary files differ Index: lams_central/src/java/org/lamsfoundation/lams/authoring/service/AuthoringService.java =================================================================== diff -u -r07865c855b32c77613ed72dd81cd499033dca4dd -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_central/src/java/org/lamsfoundation/lams/authoring/service/AuthoringService.java (.../AuthoringService.java) (revision 07865c855b32c77613ed72dd81cd499033dca4dd) +++ lams_central/src/java/org/lamsfoundation/lams/authoring/service/AuthoringService.java (.../AuthoringService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -788,9 +788,11 @@ x1 = activity.getXcoord() == null ? 0 : activity.getXcoord(); y1 = activity.getYcoord() == null ? 0 : activity.getYcoord(); } - + if (toActivity.isBranchingActivity()) { - BranchingActivity branchingActivity = (BranchingActivity) toActivity; + // get real instance instead of lazy loaded proxy + BranchingActivity branchingActivity = (BranchingActivity) activityDAO + .getActivityByActivityId(toActivity.getActivityId()); x2 = branchingActivity.getEndXcoord(); y2 = branchingActivity.getEndYcoord(); } else { Index: lams_common/src/java/org/lamsfoundation/lams/learningdesign/Grouper.java =================================================================== diff -u -rb25a6d2d1cebe3c69d4af018aa14198533a0d4c5 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_common/src/java/org/lamsfoundation/lams/learningdesign/Grouper.java (.../Grouper.java) (revision b25a6d2d1cebe3c69d4af018aa14198533a0d4c5) +++ lams_common/src/java/org/lamsfoundation/lams/learningdesign/Grouper.java (.../Grouper.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -33,210 +33,228 @@ import org.lamsfoundation.lams.usermanagement.User; import org.lamsfoundation.lams.util.MessageService; - - - /** - * This is interface that defines the contract for performing grouping - * algorithm. + * This is interface that defines the contract for performing grouping algorithm. * - * It would be nicer to get the message service directly from within the classes, rather than have a setter. - * But can't think of a way to directly access it when the grouper object doesn't - * have any link to the Spring context. (Fiona Malikoff) + * It would be nicer to get the message service directly from within the classes, rather than have a setter. But can't + * think of a way to directly access it when the grouper object doesn't have any link to the Spring context. (Fiona + * Malikoff) * * @author Jacky Fang - * @since 2005-3-24 + * @since 2005-3-24 * @version 1.1 * */ -public abstract class Grouper -{ - - private static Logger log = Logger.getLogger(Grouper.class); +public abstract class Grouper { - String DEFAULT_GROUP_NAME_PREFIX_I18N = "group.name.prefix"; - private MessageService commonMessageService; + private static Logger log = Logger.getLogger(Grouper.class); - /** Set the message service, needed for the I18N of the default group name prefix. - * Should call this method before calling doGrouping() or getPrefix() */ - public void setCommonMessageService(MessageService commonMessageService) { - this.commonMessageService = commonMessageService; - } - - protected MessageService getCommonMessageService() { - return commonMessageService; - } + String DEFAULT_GROUP_NAME_PREFIX_I18N = "group.name.prefix"; + private MessageService commonMessageService; - /** - * Do the grouping for a list of learners that the teacher requested. If you don't supply a name, you may get a system - * generated name. - * @param grouping the grouping that is used to perform groups creation. - * @param name for this group (optional) - * @param learners the list of learners that the teacher requested. + /** + * Set the message service, needed for the I18N of the default group name prefix. Should call this method before + * calling doGrouping() or getPrefix() */ - public abstract void doGrouping(Grouping grouping, String groupName, List learners) throws GroupingException; - - /** - * Do the grouping for a single learner. Should call setCommonMessageService() before calling this method. - * If you don't supply a name, you may get a system generated name. - * @param grouping the grouping that is used to perform groups creation. - * @param name for this group (optional) - * @param learner the learner teacher want to add. - */ - public abstract void doGrouping(Grouping grouping, String groupName, User learner) throws GroupingException; + public void setCommonMessageService(MessageService commonMessageService) { + this.commonMessageService = commonMessageService; + } - /** - * Do the grouping for a list of learners that the teacher requested. If you don't supply an id, you may get a group with a - * system generated name. - * @param grouping the grouping that is used to perform groups creation. - * @param id of the group (optional) - * @param learner the learner teacher want to add. - * @throws GroupingException if the group does not exist. + protected MessageService getCommonMessageService() { + return commonMessageService; + } + + /** + * Do the grouping for a list of learners that the teacher requested. If you don't supply a name, you may get a + * system generated name. + * + * @param grouping + * the grouping that is used to perform groups creation. + * @param name + * for this group (optional) + * @param learners + * the list of learners that the teacher requested. */ - public abstract void doGrouping(Grouping chosenGrouping,Long groupId, List learners) throws GroupingException; + public abstract void doGrouping(Grouping grouping, String groupName, List learners) throws GroupingException; - /** - * Get the default group name prefix - * @return default group name prefix - */ - public String getPrefix() { - String prefix = commonMessageService != null ? commonMessageService.getMessage(DEFAULT_GROUP_NAME_PREFIX_I18N) : ""; - prefix = prefix.trim(); - return prefix.length()>0 ? prefix : "Group"; - } - - /** - * Remove the give learners from the given group. Cannot remove learners if the group is already in use (i.e. - * a tool session exists) + /** + * Do the grouping for a single learner. Should call setCommonMessageService() before calling this method. If you + * don't supply a name, you may get a system generated name. * + * @param grouping + * the grouping that is used to perform groups creation. + * @param name + * for this group (optional) + * @param learner + * the learner teacher want to add. + */ + public abstract void doGrouping(Grouping grouping, String groupName, User learner) throws GroupingException; + + /** + * Do the grouping for a list of learners that the teacher requested. If you don't supply an id, you may get a group + * with a system generated name. + * + * @param grouping + * the grouping that is used to perform groups creation. + * @param id + * of the group (optional) + * @param learner + * the learner teacher want to add. + * @throws GroupingException + * if the group does not exist. + */ + public abstract void doGrouping(Grouping chosenGrouping, Long groupId, List learners) throws GroupingException; + + /** + * Get the default group name prefix + * + * @return default group name prefix + */ + public String getPrefix() { + String prefix = commonMessageService != null ? commonMessageService.getMessage(DEFAULT_GROUP_NAME_PREFIX_I18N) + : ""; + prefix = prefix.trim(); + return prefix.length() > 0 ? prefix : "Group"; + } + + /** + * Remove the give learners from the given group. Cannot remove learners if the group is already in use (i.e. a tool + * session exists) + * * Trims the name of the group before checking if it is null or before matching to a group. * - * @param grouping (mandatory) - * @param groupID if not null only remove user from this group, if null remove learner from any group. - * @param learner the learner to be removed (mandatory) + * @param grouping + * (mandatory) + * @param groupID + * if not null only remove user from this group, if null remove learner from any group. + * @param learner + * the learner to be removed (mandatory) */ - public void removeLearnersFromGroup(Grouping grouping, Long groupID, List learners) throws GroupingException - { - Set groups = grouping.getGroups(); - Iterator iter = groups.iterator(); - boolean groupFound = false; - - while (iter.hasNext() && ! groupFound ) { - Group group = (Group) iter.next(); + public void removeLearnersFromGroup(Grouping grouping, Long groupID, List learners) throws GroupingException { + Set groups = grouping.getGroups(); + Iterator iter = groups.iterator(); + boolean groupFound = false; - if ( groupID == null || groupID.equals(group.getGroupId()) ) { - - groupFound = groupID != null; - - if ( group.mayBeDeleted() ) { - - boolean removed = group.getUsers().removeAll(learners); - if ( removed ) { - if ( log.isDebugEnabled() ) { - log.debug("Removed "+learners.size()+" users from group "+group.getGroupName()); - } - } - - } else { - String error = "Tried to remove a group which cannot be removed (tool sessions probably exist). Group "+group+" grouping "+grouping+". Not removing the group."; - log.error(error); - throw new GroupingException(error); - } - + while (iter.hasNext() && !groupFound) { + Group group = (Group) iter.next(); + if ((groupID == null) || groupID.equals(group.getGroupId())) { + groupFound = groupID != null; + if (group.mayBeDeleted()) { + boolean removed = group.getUsers().removeAll(learners); + if (removed) { + if (Grouper.log.isDebugEnabled()) { + Grouper.log + .debug("Removed " + learners.size() + " users from group " + group.getGroupName()); } + } + } else { + String error = "Tried to remove a group which cannot be removed (tool sessions probably exist). Group " + + group + " grouping " + grouping + ". Not removing the group."; + Grouper.log.error(error); + throw new GroupingException(error); } + } + } } - /** - * Create an empty group for the given grouping. Trims the name of the group before creating the group. - * If the group name group name already exists then it appends a datetime string to make the name unique. Gives - * it 5 attempts to make it unique then gives up. + /** + * Create an empty group for the given grouping. Trims the name of the group before creating the group. If the group + * name group name already exists then it appends a datetime string to make the name unique. Gives it 5 attempts to + * make it unique then gives up. * * Throws a GroupingException if name is null or blank. * - * @param grouping (mandatory) - * @param name (mandatory) - * @param forceName (mandatory) + * @param grouping + * (mandatory) + * @param name + * (mandatory) + * @param forceName + * (mandatory) */ - public Group createGroup(Grouping grouping, String name) throws GroupingException - { - String trimmedName = name.trim(); - if ( trimmedName == null || trimmedName.length()==0 ) { - log.warn("Tried to add a group with no name to grouping "+grouping+". Not creating group."); - return null; - } - Set emptySet = new HashSet(); - Group newGroup = Group.createLearnerGroup(grouping,trimmedName,emptySet); - - if ( newGroup == null ) { - trimmedName = trimmedName + " " + new Long(System.currentTimeMillis()).toString(); - newGroup = Group.createLearnerGroup(grouping, trimmedName, emptySet); - } + public Group createGroup(Grouping grouping, String name) throws GroupingException { + String trimmedName = name.trim(); + if ((trimmedName == null) || (trimmedName.length() == 0)) { + Grouper.log.warn("Tried to add a group with no name to grouping " + grouping + ". Not creating group."); + return null; + } + Set emptySet = new HashSet(); + Group newGroup = Group.createLearnerGroup(grouping, trimmedName, emptySet); - if ( newGroup == null ) { - // what, still not unique? Okay try sticking a number on the end. Try 5 times then give up - log.warn("Having trouble creating a unique name for a group. Have tried "+trimmedName); - int attempt = 1; - while ( newGroup == null && attempt < 5) { - newGroup = Group.createLearnerGroup(grouping, trimmedName+" "+new Integer(attempt).toString(), emptySet); - } - if ( newGroup == null ) { - String error = "Unable to create a unique name for a group. Tried 5 variations on "+trimmedName+" now giving up."; - log.error(error); - throw new GroupingException(error); + if (newGroup == null) { + trimmedName = trimmedName + " " + new Long(System.currentTimeMillis()).toString(); + newGroup = Group.createLearnerGroup(grouping, trimmedName, emptySet); + } - } - } + if (newGroup == null) { + // what, still not unique? Okay try sticking a number on the end. Try 5 times then give up + Grouper.log.warn("Having trouble creating a unique name for a group. Have tried " + trimmedName); + int attempt = 1; + while ((newGroup == null) && (attempt < 5)) { + newGroup = Group.createLearnerGroup(grouping, trimmedName + " " + new Integer(attempt).toString(), + emptySet); + } + if (newGroup == null) { + String error = "Unable to create a unique name for a group. Tried 5 variations on " + trimmedName + + " now giving up."; + Grouper.log.error(error); + throw new GroupingException(error); - if ( newGroup != null ) - grouping.getGroups().add(newGroup); + } + } - return newGroup; - + if (newGroup != null) { + grouping.getGroups().add(newGroup); } - /** - * Remove a group for the given grouping. If the group is already used (e.g. a tool session exists) - * then it throws a GroupingException. If the group does not exist, nothing happens. + return newGroup; + + } + + /** + * Remove a group for the given grouping. If the group is already used (e.g. a tool session exists) then it throws a + * GroupingException. If the group does not exist, nothing happens. * * Trims the name of the group before selecting the group. * * When a group is removed all the users in the group become ungrouped. * * Also throws a GroupingException if groupName is null or blank. - * - * @param grouping (mandatory) - * @param groupID (mandatory) + * + * @param grouping + * (mandatory) + * @param groupID + * (mandatory) */ public void removeGroup(Grouping grouping, Long groupID) throws GroupingException { - - Iterator iter = grouping.getGroups().iterator(); - boolean groupDeleted = false; - - while (!groupDeleted && iter.hasNext()) { - Group group = (Group) iter.next(); - if ( group.getGroupId().equals(groupID) ) { - - if ( group.mayBeDeleted() ) { - - // all okay so we can delete - if ( log.isDebugEnabled() ) { - log.warn("Deleting group "+group.getGroupName()+" for grouping "+grouping); - } - iter.remove(); - groupDeleted = true; - - } else { - String error = "Tried to remove a group which cannot be removed (tool sessions probably exist). Group "+group+" grouping "+grouping+". Not removing the group."; - log.error(error); - throw new GroupingException(error); - } - } + + Iterator iter = grouping.getGroups().iterator(); + boolean groupDeleted = false; + + while (!groupDeleted && iter.hasNext()) { + Group group = (Group) iter.next(); + if (group.getGroupId().equals(groupID)) { + + if (group.mayBeDeleted()) { + + // all okay so we can delete + if (Grouper.log.isDebugEnabled()) { + Grouper.log.warn("Deleting group " + group.getGroupName() + " for grouping " + grouping); + } + iter.remove(); + groupDeleted = true; + + } else { + String error = "Tried to remove a group which cannot be removed (tool sessions probably exist). Group " + + group + " grouping " + grouping + ". Not removing the group."; + Grouper.log.error(error); + throw new GroupingException(error); } - - if ( !groupDeleted ) { - log.warn("Tried to remove a group "+groupID+" but the group does not exist for grouping "+grouping+"."); - } + } } + if (!groupDeleted) { + Grouper.log.warn("Tried to remove a group " + groupID + " but the group does not exist for grouping " + + grouping + "."); + } + } } \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/tool/ToolContentManager.java =================================================================== diff -u -r40eb54374e84591563d8b6a679ac719dbc85c8f7 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- 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 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -44,11 +44,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; @@ -70,8 +70,8 @@ * Remove tool's content according specified the content id. It will be needed by lams to modify the learning * design. * - * 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 session data for this toolContentId exists and removeSessionData = true, then the tool should delete the * session data as well as the content data. @@ -82,15 +82,15 @@ * If no matching data exists, the tool should return without throwing an exception. * * @param toolContentId - * the requested tool content id. + * the requested tool content id. * @param removeSessionData - * should it remove any related session data? + * should it remove any related session data? * @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, boolean removeSessionData) + throws SessionDataExistsException, ToolException; + /** * Removes content previously added by the given user. */ @@ -100,17 +100,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,20 +123,25 @@ * * @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? */ public boolean isContentEdited(Long toolContentId); + + /** + * Can the activity be modified? + */ + public boolean isReadOnly(Long toolContentId); } \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/tool/service/ILamsCoreToolService.java =================================================================== diff -u -ra0bce7961a19548c58f5b0025160f124785f9951 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_common/src/java/org/lamsfoundation/lams/tool/service/ILamsCoreToolService.java (.../ILamsCoreToolService.java) (revision a0bce7961a19548c58f5b0025160f124785f9951) +++ lams_common/src/java/org/lamsfoundation/lams/tool/service/ILamsCoreToolService.java (.../ILamsCoreToolService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -24,7 +24,6 @@ package org.lamsfoundation.lams.tool.service; import java.util.List; -import java.util.Set; import java.util.SortedMap; import org.lamsfoundation.lams.learningdesign.Activity; @@ -70,32 +69,32 @@ * @see org.lamsfoundation.lams.learningdesign.ToolActivity#createToolSessionForActivity(org.lamsfoundation.lams.usermanagement.User,org.lamsfoundation.lams.lesson.Lesson) * * @param learner - * the learner who is running the activity. + * the learner who is running the activity. * @param activity - * the requested activity. + * the requested activity. * @return toolSession if a new one created, null otherwise. */ ToolSession createToolSession(User learner, ToolActivity activity, Lesson lesson) throws DataIntegrityViolationException, RequiredGroupMissingException; - + /** * Returns the previously created ToolSession for a learner and activity. It is queried base on learner. * * @param learner - * the learner who owns the tool session. + * the learner who owns the tool session. * @param activity - * the activity that associate with the tool session. + * the activity that associate with the tool session. * @return the requested tool session. * @throws LamsToolServiceException - * the known error condition when we are getting the tool session + * the known error condition when we are getting the tool session */ ToolSession getToolSessionByLearner(User learner, Activity activity) throws LamsToolServiceException; /** * Returns the tool session according to tool session id. * * @param toolSessionId - * the requested tool session id. + * the requested tool session id. * @return the tool session object */ ToolSession getToolSessionById(Long toolSessionId); @@ -105,71 +104,75 @@ * activity and return the tool session with requested learner information. * * @param learner - * the requested learner + * the requested learner * @param toolActivity - * the requested activity. + * the requested activity. * @return the tool session. * @throws LamsToolServiceException - * the known error condition when we are getting the tool session + * the known error condition when we are getting the tool session */ - ToolSession getToolSessionByActivity(User learner, ToolActivity toolActivity) - throws LamsToolServiceException; + ToolSession getToolSessionByActivity(User learner, ToolActivity toolActivity) throws LamsToolServiceException; /** * Notify tools to create their tool sessions in their own tables. * * @param toolSession - * the tool session generated by lams. + * the tool session generated by lams. * @param activity - * the activity correspondent to that tool session. + * the activity correspondent to that tool session. */ void notifyToolsToCreateSession(ToolSession toolSession, ToolActivity activity) throws ToolException; /** * Calls the tool to copy the content for an activity. Used when copying a learning design. * * @param toolActivity - * the tool activity defined in the design. + * the tool activity defined in the design. * @param customCSV - * custom comma-separated values used for tool adapters + * custom comma-separated values used for tool adapters * @throws DataMissingException, - * ToolException + * ToolException * @see org.lamsfoundation.lams.tool.service.ILamsCoreToolService#notifyToolToCopyContent(org.lamsfoundation.lams.learningdesign.ToolActivity) */ - Long notifyToolToCopyContent(ToolActivity toolActivity, String customCSV) throws DataMissingException, - ToolException; + Long notifyToolToCopyContent(ToolActivity toolActivity, String customCSV) + throws DataMissingException, ToolException; /** * Calls the tool to copy the content for an activity. Used when copying an activity in authoring. Can't use the * notifyToolToCopyContent(ToolActivity, boolean) version in authoring as the tool activity won't exist if the user * hasn't saved the sequence yet. But the tool content (as that is saved by the tool) may already exist. * * @param toolContentId - * the content to be copied. + * the content to be copied. * @param customCSV - * the customCSV required if this is a tooladapter tool, otherwise null + * the customCSV required if this is a tooladapter tool, otherwise null * @throws DataMissingException, - * ToolException + * ToolException * @see org.lamsfoundation.lams.tool.service.ILamsCoreToolService#notifyToolToCopyContent(org.lamsfoundation.lams.learningdesign.ToolActivity) */ - Long notifyToolToCopyContent(Long toolContentId, String customCSV) throws DataMissingException, - ToolException; + Long notifyToolToCopyContent(Long toolContentId, String customCSV) throws DataMissingException, ToolException; /** * Ask a tool to delete a tool content. If any related tool session data exists then it should be deleted. * * @param toolActivity - * the tool activity defined in the design. + * the tool activity defined in the design. * @throws ToolException */ void notifyToolToDeleteContent(ToolActivity toolActivity) throws ToolException; - + /** - * Ask a tool to delete content entered by the given user, if exists. + * Ask an activity to delete content entered by the given user, if exists. + * @return whether the activity should be persisted afterwards */ - void notifyToolToDeleteLearnerContent(ToolActivity toolActivity, Integer userId) throws ToolException; - + boolean removeLearnerContent(Activity activity, User learner) throws ToolException; + /** + * Checks whether the activity's read-only flag can be reset. + */ + boolean isActivityReadOnly(Activity activity); + + /** * Ask a tool for its OutputDefinitions, based on the given toolContentId. If the tool doesn't have any content * matching the toolContentId then it should create the OutputDefinitions based on the tool's default content. * @@ -204,8 +207,7 @@ * * @throws ToolException */ - ToolOutput getOutputFromTool(String conditionName, Long toolSessionId, Integer learnerId) - throws ToolException; + ToolOutput getOutputFromTool(String conditionName, Long toolSessionId, Integer learnerId) throws ToolException; /** * Ask a tool for one particular ToolOutput, based on the given toolSessionId. If the tool doesn't have any content @@ -215,8 +217,7 @@ * * @throws ToolException */ - ToolOutput getOutputFromTool(String conditionName, ToolSession toolSession, Integer learnerId) - throws ToolException; + ToolOutput getOutputFromTool(String conditionName, ToolSession toolSession, Integer learnerId) throws ToolException; /** * Ask a tool for a set of ToolOutputs, based on the given toolSessionId. @@ -253,9 +254,9 @@ * * @throws ToolException */ - SortedMap getOutputFromTool(List names, ToolSession toolSession, - Integer learnerId) throws ToolException; - + SortedMap getOutputFromTool(List names, ToolSession toolSession, Integer learnerId) + throws ToolException; + /** * Notifies tool that the user is force completed. Currently it's been utilized only by leader aware tools, which * copy results from leader to non-leader. @@ -266,7 +267,7 @@ * @throws ToolException */ void forceCompleteActivity(ToolSession toolSession, User learner) throws ToolException; - + /** * Get activity's max possible mark. * @@ -279,19 +280,19 @@ * Update the tool session data. * * @param toolSession - * the new tool session object. + * the new tool session object. */ void updateToolSession(ToolSession toolSession); /** * Return tool activity url for a learner. See also getToolPreviewURL, getToolLearnerProgressURL * * @param lesson - * id - needed for the SystemToolActivities + * id - needed for the SystemToolActivities * @param activity - * the requested activity - should be either a ToolActivity or a SystemToolActivity + * the requested activity - should be either a ToolActivity or a SystemToolActivity * @param learner - * the current learner. + * the current learner. * @return the tool access url with tool session id or activity id */ String getToolLearnerURL(Long lessonID, Activity activity, User learner) throws LamsToolServiceException; @@ -301,37 +302,35 @@ * getToolLearnerProgressURL * * @param lesson - * id - needed for the SystemToolActivities + * id - needed for the SystemToolActivities * @param activity - * the requested activity - should be either a ToolActivity or a SystemToolActivity + * the requested activity - should be either a ToolActivity or a SystemToolActivity * @param learner - * the current learner. + * the current learner. * @return the tool access url with tool session id or activity id */ - String getToolLearnerPreviewURL(Long lessonID, Activity activity, User learner) - throws LamsToolServiceException; + String getToolLearnerPreviewURL(Long lessonID, Activity activity, User learner) throws LamsToolServiceException; /** * Return tool activity url for running a tool in preview mode. See also getToolLearnerURL, getToolPreviewURL * * @param lesson - * id - needed for the SystemToolActivities + * id - needed for the SystemToolActivities * @param activity - * the requested activity - should be either a ToolActivity or a SystemToolActivity + * the requested activity - should be either a ToolActivity or a SystemToolActivity * @param learner - * the current learner. + * the current learner. * @return the tool access url with tool session id or activity id */ - String getToolLearnerProgressURL(Long lessonID, Activity activity, User learner) - throws LamsToolServiceException; + String getToolLearnerProgressURL(Long lessonID, Activity activity, User learner) throws LamsToolServiceException; /** * Return tool activity url for monitoring. * * @param lesson - * id - needed for the SystemToolActivities + * id - needed for the SystemToolActivities * @param activity - * the requested activity - should be either a ToolActivity or a SystemToolActivity + * the requested activity - should be either a ToolActivity or a SystemToolActivity * @return the tool access url with tool session id or activity id */ String getToolMonitoringURL(Long lessonID, Activity activity) throws LamsToolServiceException; @@ -340,23 +339,23 @@ * Return the contribution url for monitoring. * * @param lesson - * id - needed for the SystemToolActivities + * id - needed for the SystemToolActivities * @param activity - * the requested activity - should be either a ToolActivity or a SystemToolActivity + * the requested activity - should be either a ToolActivity or a SystemToolActivity * @return the tool access url with tool session id or activity id */ String getToolContributionURL(Long lessonID, Activity activity) throws LamsToolServiceException; boolean isContentEdited(Activity activity); - + String getToolAuthorURL(Long lessonID, ToolActivity activity, ToolAccessMode mode); - + /** * Get all the tool sessions for a lesson. The resulting list is not sorted. * * @return list of ToolSession objects */ - List getToolSessionsByLesson(Lesson lesson); + List getToolSessionsByLesson(Lesson lesson); /** * Delete a tool session. Calls the tool to delete its session details and then deletes the main tool session @@ -370,11 +369,11 @@ *

* * @param activity - * the activity that requested tool session belongs to. + * the activity that requested tool session belongs to. * @param learner - * the user who invloved the tool session. + * the user who invloved the tool session. * @param toolURL - * the target url. + * the target url. * @throws LamsToolServiceException * @return the url with tool session id. */ @@ -387,9 +386,9 @@ *

* * @param activity - * the requested activity. + * the requested activity. * @param toolURL - * the target url + * the target url * @return the url with tool content id. */ String setupToolURLWithToolContent(ToolActivity activity, String toolURL); Index: lams_common/src/java/org/lamsfoundation/lams/tool/service/LamsCoreToolService.java =================================================================== diff -u -ra0bce7961a19548c58f5b0025160f124785f9951 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_common/src/java/org/lamsfoundation/lams/tool/service/LamsCoreToolService.java (.../LamsCoreToolService.java) (revision a0bce7961a19548c58f5b0025160f124785f9951) +++ lams_common/src/java/org/lamsfoundation/lams/tool/service/LamsCoreToolService.java (.../LamsCoreToolService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -23,7 +23,6 @@ /* $$Id$$ */ package org.lamsfoundation.lams.tool.service; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; @@ -33,6 +32,12 @@ import org.apache.log4j.Logger; import org.lamsfoundation.lams.learningdesign.Activity; import org.lamsfoundation.lams.learningdesign.ActivityEvaluation; +import org.lamsfoundation.lams.learningdesign.ComplexActivity; +import org.lamsfoundation.lams.learningdesign.GateActivity; +import org.lamsfoundation.lams.learningdesign.GateUser; +import org.lamsfoundation.lams.learningdesign.Group; +import org.lamsfoundation.lams.learningdesign.Grouping; +import org.lamsfoundation.lams.learningdesign.GroupingActivity; import org.lamsfoundation.lams.learningdesign.ToolActivity; import org.lamsfoundation.lams.lesson.Lesson; import org.lamsfoundation.lams.tool.SystemTool; @@ -92,7 +97,7 @@ /** * @param toolSessionDAO - * The toolSessionDAO to set. + * The toolSessionDAO to set. */ public void setToolSessionDAO(IToolSessionDAO toolSessionDAO) { this.toolSessionDAO = toolSessionDAO; @@ -108,16 +113,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 +182,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 +193,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 +220,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 @@ -263,20 +268,85 @@ throw new ToolException(message, e); } } - + @Override - public void notifyToolToDeleteLearnerContent(ToolActivity toolActivity, Integer userId) throws ToolException { - try { + public boolean removeLearnerContent(Activity activity, User learner) throws ToolException { + if (activity.isToolActivity()) { + ToolActivity toolActivity = (ToolActivity) activity; + try { + ToolContentManager contentManager = (ToolContentManager) findToolService(toolActivity.getTool()); + contentManager.removeLearnerContent(toolActivity.getToolContentId(), learner.getUserId()); + } catch (NoSuchBeanDefinitionException e) { + String message = "A tool which is defined in the database appears to missing from the classpath. Unable to delete learner content. ToolActivity " + + toolActivity; + LamsCoreToolService.log.error(message, e); + throw new ToolException(message, e); + } + } else if (activity.isGroupingActivity()) { + GroupingActivity groupingActivity = (GroupingActivity) activity; + Grouping grouping = groupingActivity.getCreateGrouping(); + Group group = grouping.getGroupBy(learner); + if (!group.isNull()) { + return group.getUsers().remove(learner); + } + } else if (activity.isGateActivity()) { + GateActivity gateActivity = (GateActivity) activity; + Iterator gateUserIterator = gateActivity.getAllGateUsers().iterator(); + boolean removed = false; + while (gateUserIterator.hasNext()) { + User user = gateUserIterator.next().getUser(); + // there can be more than one entry (why?!), so do not "break" + if (learner.getUserId().equals(user.getUserId())) { + removed = true; + gateUserIterator.remove(); + } + } + return removed; + } + + return false; + } + + @SuppressWarnings("unchecked") + @Override + public boolean isActivityReadOnly(Activity activity) { + if (activity.isToolActivity()) { + ToolActivity toolActivity = (ToolActivity) activity; ToolContentManager contentManager = (ToolContentManager) findToolService(toolActivity.getTool()); - contentManager.removeLearnerContent(toolActivity.getToolContentId(), userId); - } catch (NoSuchBeanDefinitionException e) { - String message = "A tool which is defined in the database appears to missing from the classpath. Unable to delete learner content. ToolActivity " - + toolActivity; - LamsCoreToolService.log.error(message, e); - throw new ToolException(message, e); + return contentManager.isReadOnly(toolActivity.getToolContentId()); + } else if (activity.isGroupingActivity()) { + GroupingActivity groupingActivity = (GroupingActivity) activity; + Grouping grouping = groupingActivity.getCreateGrouping(); + for (Group group : (Set) grouping.getGroups()) { + if (!group.getUsers().isEmpty()) { + return true; + } + } + return false; + } else if (activity.isGateActivity()) { + GateActivity gateActivity = (GateActivity) activity; + return !gateActivity.getAllGateUsers().isEmpty(); } + + // just check the flag + return isActivityReadOnlyFlag(activity); } + @SuppressWarnings("unchecked") + private boolean isActivityReadOnlyFlag(Activity activity) { + if (activity.isComplexActivity()) { + for (Activity childActivity : (Set) ((ComplexActivity) systemToolDAO.find(ComplexActivity.class, + activity.getActivityId())).getActivities()) { + if (isActivityReadOnlyFlag(childActivity)) { + return true; + } + } + return false; + } else { + return activity.isActivityReadOnly(); + } + } + @Override public SortedMap getOutputDefinitionsFromTool(Long toolContentId, int definitionType) throws ToolException { @@ -305,8 +375,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 +438,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 +482,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 +514,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 +555,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(), @@ -507,23 +572,23 @@ if (map != null) { for (String key : map.keySet()) { ToolOutputDefinition definition = map.get(key); - if (actEvals != null && actEvals.size() > 0) { + if ((actEvals != null) && (actEvals.size() > 0)) { // get first evaluation ActivityEvaluation actEval = actEvals.iterator().next(); if (actEval.getToolOutputDefinition().equals(key)) { Object upperLimit = definition.getEndValue(); - if (upperLimit != null && upperLimit instanceof Long) { + if ((upperLimit != null) && (upperLimit instanceof Long)) { return (Long) upperLimit; } break; } } else { - if (definition.isDefaultGradebookMark() != null && definition.isDefaultGradebookMark()) { + if ((definition.isDefaultGradebookMark() != null) && definition.isDefaultGradebookMark()) { Object upperLimit = definition.getEndValue(); - if (upperLimit != null && upperLimit instanceof Long) { + if ((upperLimit != null) && (upperLimit instanceof Long)) { return (Long) upperLimit; } break; @@ -552,8 +617,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 +677,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 +716,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,34 +747,35 @@ 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) { + if ((url != null) && (userID != null)) { url = WebUtil.appendParameterToURL(url, AttributeNames.PARAM_USER_ID, userID.toString()); } return url; } 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()); + if ((url != null) && (activity != null)) { + url = WebUtil.appendParameterToURL(url, AttributeNames.PARAM_ACTIVITY_ID, + activity.getActivityId().toString()); } - if (url != null && lessonID != null) { + if ((url != null) && (lessonID != null)) { url = WebUtil.appendParameterToURL(url, AttributeNames.PARAM_LESSON_ID, lessonID.toString()); } return url; } @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/toolApplicationContext.xml =================================================================== diff -u -r078ffcc5cce6214e179857ace04486fa04a7e3a2 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_common/src/java/org/lamsfoundation/lams/toolApplicationContext.xml (.../toolApplicationContext.xml) (revision 078ffcc5cce6214e179857ace04486fa04a7e3a2) +++ lams_common/src/java/org/lamsfoundation/lams/toolApplicationContext.xml (.../toolApplicationContext.xml) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -62,6 +62,9 @@ PROPAGATION_REQUIRED PROPAGATION_REQUIRED PROPAGATION_REQUIRED + + PROPAGATION_REQUIRES_NEW + PROPAGATION_REQUIRED PROPAGATION_REQUIRED,readOnly Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/MonitoringService.java =================================================================== diff -u -ra0bce7961a19548c58f5b0025160f124785f9951 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/MonitoringService.java (.../MonitoringService.java) (revision a0bce7961a19548c58f5b0025160f124785f9951) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/MonitoringService.java (.../MonitoringService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; +import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; @@ -126,9 +127,8 @@ * to utilize the Spring's IOC and declarative transaction management. *

*

- * It needs to implement ApplicationContextAware interface - * because we need to load up tool's service dynamically according to the - * selected learning design. + * It needs to implement ApplicationContextAware interface because we need to load up tool's service + * dynamically according to the selected learning design. *

* * TODO Analyse the efficiency of the grouping algorithms for adding/removing users. Possible performance issue. @@ -369,8 +369,8 @@ LearningDesign originalLearningDesign = authoringService.getLearningDesign(new Long(learningDesignId)); if (originalLearningDesign == null) { - throw new MonitoringServiceException("Learning design for id=" + learningDesignId - + " is missing. Unable to initialize lesson."); + throw new MonitoringServiceException( + "Learning design for id=" + learningDesignId + " is missing. Unable to initialize lesson."); } Lesson precedingLesson = (precedingLessonId == null) ? null : lessonDAO.getLesson(precedingLessonId); @@ -416,8 +416,8 @@ Boolean liveEditEnabled) { LearningDesign originalLearningDesign = authoringService.getLearningDesign(new Long(learningDesignId)); if (originalLearningDesign == null) { - throw new MonitoringServiceException("Learning design for id=" + learningDesignId - + " is missing. Unable to initialize lesson."); + throw new MonitoringServiceException( + "Learning design for id=" + learningDesignId + " is missing. Unable to initialize lesson."); } User user = userID != null ? (User) baseDAO.find(User.class, userID) : null; @@ -434,15 +434,15 @@ Integer scheduledNumberDaysToLessonFinish, Lesson precedingLesson) { LearningDesign learningDesign = authoringService.getLearningDesign(learningDesignID); if (learningDesign == null) { - throw new MonitoringServiceException("Learning design for id=" + learningDesignID - + " is missing. Unable to initialize lesson."); + throw new MonitoringServiceException( + "Learning design for id=" + learningDesignID + " is missing. Unable to initialize lesson."); } Lesson lesson = createNewLesson(lessonName, lessonDescription, user, learningDesign, enableLessonIntro, displayDesignImage, learnerExportAvailable, learnerPresenceAvailable, learnerImAvailable, liveEditEnabled, enableLessonNotifications, learnerRestart, scheduledNumberDaysToLessonFinish, precedingLesson); - writeAuditLog(MonitoringService.AUDIT_LESSON_CREATED_KEY, new Object[] { lessonName, learningDesign.getTitle(), - learnerExportAvailable }); + writeAuditLog(MonitoringService.AUDIT_LESSON_CREATED_KEY, + new Object[] { lessonName, learningDesign.getTitle(), learnerExportAvailable }); return lesson; } @@ -452,8 +452,8 @@ Boolean learnerImAvailable, Boolean liveEditEnabled, Boolean enableLessonNotifications, Boolean learnerRestart, Integer scheduledNumberDaysToLessonFinish, Lesson precedingLesson) { // copy the current learning design - LearningDesign copiedLearningDesign = authoringService.copyLearningDesign(originalLearningDesign, new Integer( - copyType), user, workspaceFolder, true, null, customCSV); + LearningDesign copiedLearningDesign = authoringService.copyLearningDesign(originalLearningDesign, + new Integer(copyType), user, workspaceFolder, true, null, customCSV); authoringService.saveLearningDesign(copiedLearningDesign); // Make all efforts to make sure it has a title @@ -574,15 +574,15 @@ if (requestedLesson.isLessonStarted()) { // can't schedule it as it is already started. If the UI is correct, // this should never happen. - MonitoringService.log.error("Lesson for id=" + lessonId - + " has been started. Unable to schedule lesson start."); + MonitoringService.log + .error("Lesson for id=" + lessonId + " has been started. Unable to schedule lesson start."); return; } if (requestedLesson.getScheduleStartDate() != null) { // can't reschedule! - MonitoringService.log.error("Lesson for id=" + lessonId - + " is already scheduled and cannot be rescheduled."); + MonitoringService.log + .error("Lesson for id=" + lessonId + " is already scheduled and cannot be rescheduled."); return; } @@ -592,12 +592,10 @@ Date tzStartLessonDate = DateUtil.convertFromTimeZoneToDefault(userTimeZone, startDate); // setup the message for scheduling job - JobDetail startLessonJob = JobBuilder - .newJob(StartScheduleLessonJob.class) + JobDetail startLessonJob = JobBuilder.newJob(StartScheduleLessonJob.class) .withIdentity("startLessonOnSchedule:" + lessonId) - .withDescription( - requestedLesson.getLessonName() + ":" - + (requestedLesson.getUser() == null ? "" : requestedLesson.getUser().getFullName())) + .withDescription(requestedLesson.getLessonName() + ":" + + (requestedLesson.getUser() == null ? "" : requestedLesson.getUser().getFullName())) .usingJobData(MonitoringConstants.KEY_LESSON_ID, new Long(lessonId)) .usingJobData(MonitoringConstants.KEY_USER_ID, new Integer(userId)).build(); @@ -611,8 +609,8 @@ scheduler.scheduleJob(startLessonJob, startLessonTrigger); setLessonState(requestedLesson, Lesson.NOT_STARTED_STATE); } catch (SchedulerException e) { - throw new MonitoringServiceException("Error occurred at " - + "[startLessonOnSchedule]- fail to start scheduling", e); + throw new MonitoringServiceException( + "Error occurred at " + "[startLessonOnSchedule]- fail to start scheduling", e); } if (MonitoringService.log.isDebugEnabled()) { @@ -659,14 +657,10 @@ finishLessonTrigger = finishLessonTrigger.getTriggerBuilder().startAt(endDate).build(); } else { // setup the message for scheduling job - finishLessonJob = JobBuilder - .newJob(FinishScheduleLessonJob.class) + finishLessonJob = JobBuilder.newJob(FinishScheduleLessonJob.class) .withIdentity("finishLessonOnSchedule:" + lessonId) - .withDescription( - requestedLesson.getLessonName() - + ":" - + (requestedLesson.getUser() == null ? "" : requestedLesson.getUser() - .getFullName())) + .withDescription(requestedLesson.getLessonName() + ":" + + (requestedLesson.getUser() == null ? "" : requestedLesson.getUser().getFullName())) .usingJobData(MonitoringConstants.KEY_LESSON_ID, new Long(lessonId)) .usingJobData(MonitoringConstants.KEY_USER_ID, new Integer(userId)).build(); @@ -682,8 +676,8 @@ if (scheduledNumberDaysToLessonFinish > 0) { scheduler.rescheduleJob(finishLessonTrigger.getKey(), finishLessonTrigger); if (MonitoringService.log.isDebugEnabled()) { - MonitoringService.log.debug("Finish lesson [" + lessonId + "] job has been rescheduled to " - + endDate); + MonitoringService.log + .debug("Finish lesson [" + lessonId + "] job has been rescheduled to " + endDate); } } else { scheduler.deleteJob(finishLessonTrigger.getJobKey()); @@ -694,13 +688,13 @@ } else if (scheduledNumberDaysToLessonFinish > 0) { scheduler.scheduleJob(finishLessonJob, finishLessonTrigger); if (MonitoringService.log.isDebugEnabled()) { - MonitoringService.log.debug("Finish lesson [" + lessonId + "] job has been scheduled to " - + endDate); + MonitoringService.log + .debug("Finish lesson [" + lessonId + "] job has been scheduled to " + endDate); } } } catch (SchedulerException e) { - throw new MonitoringServiceException("Error occurred at " - + "[finishLessonOnSchedule]- fail to start scheduling", e); + throw new MonitoringServiceException( + "Error occurred at " + "[finishLessonOnSchedule]- fail to start scheduling", e); } } @@ -716,10 +710,8 @@ securityService.isLessonMonitor(lessonId, userId, "start lesson", true); } if (requestedLesson.isLessonStarted()) { - MonitoringService.log - .warn("Lesson " - + lessonId - + " has been started. No need to start the lesson. The lesson was probably scheduled, and then the staff used \"Start now\". This message would have then been created by the schedule start"); + MonitoringService.log.warn("Lesson " + lessonId + + " has been started. No need to start the lesson. The lesson was probably scheduled, and then the staff used \"Start now\". This message would have then been created by the schedule start"); return; } @@ -756,13 +748,14 @@ } @Override - public Integer startSystemActivity(Activity activity, Integer currentMaxId, Date lessonStartTime, String lessonName) { + public Integer startSystemActivity(Activity activity, Integer currentMaxId, Date lessonStartTime, + String lessonName) { Integer newMaxId = null; // if it is schedule gate, we need to initialize the sheduler for it. if (activity.getActivityTypeId().intValue() == Activity.SCHEDULE_GATE_ACTIVITY_TYPE) { - ScheduleGateActivity gateActivity = (ScheduleGateActivity) activityDAO.getActivityByActivityId(activity - .getActivityId()); + ScheduleGateActivity gateActivity = (ScheduleGateActivity) activityDAO + .getActivityByActivityId(activity.getActivityId()); // do not run the scheduler if the gate is basen on user completing previous activity if (!Boolean.TRUE.equals(gateActivity.getGateActivityCompletionBased())) { activity = runGateScheduler(gateActivity, lessonStartTime, lessonName); @@ -782,8 +775,8 @@ activity.setGrouping(grouping); if (MonitoringService.log.isDebugEnabled()) { - MonitoringService.log.debug("startLesson: Created chosen grouping " + grouping - + " for branching activity " + activity); + MonitoringService.log.debug( + "startLesson: Created chosen grouping " + grouping + " for branching activity " + activity); } newMaxId = new Integer(currentMaxId.intValue() + 1); activity.setInitialised(true); @@ -820,7 +813,8 @@ // start the scheduling job try { if (((scheduleGate.getGateStartTimeOffset() == null) && (scheduleGate.getGateEndTimeOffset() == null)) - || ((scheduleGate.getGateStartTimeOffset() != null) && (scheduleGate.getGateEndTimeOffset() == null))) { + || ((scheduleGate.getGateStartTimeOffset() != null) + && (scheduleGate.getGateEndTimeOffset() == null))) { scheduler.scheduleJob(openScheduleGateJob, openGateTrigger); } else if (openGateTrigger.getStartTime().before(closeGateTrigger.getStartTime())) { scheduler.scheduleJob(openScheduleGateJob, openGateTrigger); @@ -894,8 +888,8 @@ requestedLesson.setPreviousLessonStateId(requestedLesson.getLessonStateId()); requestedLesson.setLessonStateId(status); lessonDAO.updateLesson(requestedLesson); - logEventService.logEvent(LogEvent.TYPE_TEACHER_LESSON_CHANGE_STATE, requestedLesson.getUser().getUserId(), - null, requestedLesson.getLessonId(), null); + logEventService.logEvent(LogEvent.TYPE_TEACHER_LESSON_CHANGE_STATE, requestedLesson.getUser().getUserId(), null, + requestedLesson.getLessonId(), null); } /** @@ -933,8 +927,8 @@ } lessonDAO.updateLesson(requestedLesson); - logEventService.logEvent(LogEvent.TYPE_TEACHER_LESSON_CHANGE_STATE, requestedLesson.getUser().getUserId(), - null, requestedLesson.getLessonId(), null); + logEventService.logEvent(LogEvent.TYPE_TEACHER_LESSON_CHANGE_STATE, requestedLesson.getUser().getUserId(), null, + requestedLesson.getLessonId(), null); } @Override @@ -999,10 +993,10 @@ try { scheduler.unscheduleJob(TriggerKey.triggerKey("openGateTrigger:" + gate.getActivityId())); } catch (SchedulerException e) { - MonitoringService.log.error( + MonitoringService.log + .error("Error unscheduling trigger for gate activity id:" + gate.getActivityId(), e); + throw new MonitoringServiceException( "Error unscheduling trigger for gate activity id:" + gate.getActivityId(), e); - throw new MonitoringServiceException("Error unscheduling trigger for gate activity id:" - + gate.getActivityId(), e); } } @@ -1060,11 +1054,11 @@ // check if the target activity or its parents were completed // if yes, we move user backward, otherwise forward - if ((learnerProgress != null) - && (learnerProgress.getCompletedActivities().containsKey(stopActivity) || ((parentActivity != null) && (learnerProgress - .getCompletedActivities().containsKey(parentActivity) || ((parentActivity - .getParentActivity() != null) && learnerProgress.getCompletedActivities().containsKey( - parentActivity.getParentActivity())))))) { + if ((learnerProgress != null) && (learnerProgress.getCompletedActivities().containsKey(stopActivity) + || ((parentActivity != null) && (learnerProgress.getCompletedActivities() + .containsKey(parentActivity) + || ((parentActivity.getParentActivity() != null) && learnerProgress.getCompletedActivities() + .containsKey(parentActivity.getParentActivity())))))) { return forceUncompleteActivity(learnerProgress, stopActivity, removeLearnerContent); } @@ -1104,8 +1098,8 @@ String stopReason = forceCompleteActivity(learner, lessonId, learnerProgress, currentActivity, stopPreviousActivity, new ArrayList()); - return stopReason != null ? stopReason : messageService - .getMessage(MonitoringService.FORCE_COMPLETE_STOP_MESSAGE_STOPPED_UNEXPECTEDLY); + return stopReason != null ? stopReason + : messageService.getMessage(MonitoringService.FORCE_COMPLETE_STOP_MESSAGE_STOPPED_UNEXPECTEDLY); } /** @@ -1150,8 +1144,8 @@ } learnerService.completeActivity(learner.getUserId(), activity, lessonId); if (MonitoringService.log.isDebugEnabled()) { - MonitoringService.log.debug("Grouping activity [" + activity.getActivityId() - + "] is completed."); + MonitoringService.log + .debug("Grouping activity [" + activity.getActivityId() + "] is completed."); } } else { // except random grouping, stop here @@ -1162,8 +1156,8 @@ // if group already exist learnerService.completeActivity(learner.getUserId(), activity, lessonId); if (MonitoringService.log.isDebugEnabled()) { - MonitoringService.log.debug("Grouping activity [" + activity.getActivityId() - + "] is completed."); + MonitoringService.log + .debug("Grouping activity [" + activity.getActivityId() + "] is completed."); } } @@ -1201,9 +1195,9 @@ // Let activity know that the user is force completed. Currently it's been utilized only by leader // aware tools, it copies results from leader to non-leader. lamsCoreToolService.forceCompleteActivity(toolSession, progress.getUser()); - - learnerService.completeToolSession(toolSession.getToolSessionId(), new Long(learner.getUserId() - .longValue())); + + learnerService.completeToolSession(toolSession.getToolSessionId(), + new Long(learner.getUserId().longValue())); learnerService.completeActivity(learner.getUserId(), activity, lessonId); if (MonitoringService.log.isDebugEnabled()) { MonitoringService.log.debug("Tool activity [" + activity.getActivityId() + "] is completed."); @@ -1288,9 +1282,9 @@ boolean removeLearnerContent) { User learner = learnerProgress.getUser(); Activity currentActivity = learnerProgress.getCurrentActivity(); - // set of activities for which "attempted" and "completed" status will be removed - Set uncompleteActivities = new HashSet(); - uncompleteActivities.add(targetActivity); + // list of activities for which "attempted" and "completed" status will be removed + // in last-to-first order + List uncompleteActivities = new LinkedList(); if (currentActivity == null) { // Learner has finished the whole lesson. Find the last activity by traversing the transition. @@ -1302,8 +1296,8 @@ } // check if the target is a part of complex activity - CompletedActivityProgress completedActivityProgress = learnerProgress.getCompletedActivities().get( - targetActivity); + CompletedActivityProgress completedActivityProgress = learnerProgress.getCompletedActivities() + .get(targetActivity); Activity previousActivity = null; Activity targetParentActivity = targetActivity.getParentActivity(); if (targetParentActivity != null) { @@ -1339,36 +1333,57 @@ // remove completed activities step by step, all the way from current to target activity while (!currentActivity.equals(targetActivity)) { - uncompleteActivities.add(currentActivity); - if (currentActivity.isComplexActivity()) { if (currentActivity.equals(targetParentActivity)) { + uncompleteActivities.add(currentActivity); // we came to the complex activity which contains our target currentActivity = targetActivity; while (currentActivity.getTransitionFrom() != null) { // find the last activity in the branch and carry on with backwards traversal currentActivity = currentActivity.getTransitionFrom().getToActivity(); } + continue; } else { - ComplexActivity complexActivity = (ComplexActivity) getActivityById(currentActivity.getActivityId()); + ComplexActivity complexActivity = (ComplexActivity) getActivityById( + currentActivity.getActivityId()); // forget all records within complex activity for (Activity childActivity : (Set) complexActivity.getActivities()) { - uncompleteActivities.add(childActivity); - if (childActivity.isComplexActivity()) { - ComplexActivity complexChildActivity = (ComplexActivity) getActivityById(childActivity - .getActivityId()); - uncompleteActivities.addAll(complexChildActivity.getActivities()); - } - - // mark the activity to be "unbranched" if (childActivity.isSequenceActivity()) { + // mark the activity to be "unbranched" groupings.add(childActivity); + + // get real instance instead of a lazy loaded proxy + Activity sequenceChildActivity = ((SequenceActivity) activityDAO + .getActivityByActivityId(childActivity.getActivityId())).getDefaultActivity(); + List sequenceChildActivities = new LinkedList(); + while (sequenceChildActivity != null) { + sequenceChildActivities.add(sequenceChildActivity); + if (sequenceChildActivity.getTransitionFrom() != null) { + sequenceChildActivity = sequenceChildActivity.getTransitionFrom().getToActivity(); + } else { + sequenceChildActivity = null; + } + } + + // parent activity goes as the last one + Collections.reverse(sequenceChildActivities); + uncompleteActivities.addAll(sequenceChildActivities); + + } else if (childActivity.isComplexActivity()) { + ComplexActivity complexChildActivity = (ComplexActivity) getActivityById( + childActivity.getActivityId()); + uncompleteActivities.addAll(complexChildActivity.getActivities()); } + + uncompleteActivities.add(childActivity); } } } + // the parent activity needs to go as the last one, so add the activity only here + uncompleteActivities.add(currentActivity); + Transition transitionTo = currentActivity.getTransitionTo(); if (transitionTo == null) { // reached beginning of either sequence or complex activity @@ -1396,23 +1411,24 @@ } } + uncompleteActivities.add(targetActivity); + + boolean resetReadOnly = true; // forget that user completed and attempted activiites for (Activity activity : uncompleteActivities) { learnerProgress.getAttemptedActivities().remove(activity); learnerProgress.getCompletedActivities().remove(activity); - if (removeLearnerContent && activity.isToolActivity()) { - ToolActivity toolActivity = (ToolActivity) getActivityById(activity.getActivityId()); - // remove learner content from this activity - lamsCoreToolService.notifyToolToDeleteLearnerContent(toolActivity, learner.getUserId()); + if (removeLearnerContent) { + resetReadOnly = removeLearnerContent(activity, learner, resetReadOnly); } } // set target activity as attempted learnerProgress.getAttemptedActivities().put(targetActivity, completedActivityProgress.getStartDate()); if (targetParentActivity != null) { // set parent as attempted - learnerProgress.getAttemptedActivities() - .put(targetParentActivity, completedActivityProgress.getStartDate()); + learnerProgress.getAttemptedActivities().put(targetParentActivity, + completedActivityProgress.getStartDate()); targetParentActivity = targetActivity.getParentActivity(); if (targetParentActivity != null) { // if target was part of branch, then immediate parent was Sequence @@ -1441,8 +1457,8 @@ Group group = sequenceActivity.getSoleGroupForBranch(); if ((group != null) && group.hasLearner(learner)) { // remove learner from the branch - removeUsersFromBranch(sequenceActivity.getActivityId(), new String[] { learner.getUserId() - .toString() }); + removeUsersFromBranch(sequenceActivity.getActivityId(), + new String[] { learner.getUserId().toString() }); } } else { MonitoringService.log.warn("Unknow activity type marked for ungrouping: " + activity.getActivityId()); @@ -1489,8 +1505,8 @@ } flashMessage = new FlashMessage("getLessonLearners", lessonLearners); } else { - flashMessage = new FlashMessage("getLessonLearners", messageService.getMessage("NO.SUCH.LESSON", - new Object[] { lessonID }), FlashMessage.ERROR); + flashMessage = new FlashMessage("getLessonLearners", + messageService.getMessage("NO.SUCH.LESSON", new Object[] { lessonID }), FlashMessage.ERROR); } return flashMessage.serializeMessage(); } @@ -1510,8 +1526,8 @@ } flashMessage = new FlashMessage("getLessonStaff", lessonStaff); } else { - flashMessage = new FlashMessage("getLessonStaff", messageService.getMessage("NO.SUCH.LESSON", - new Object[] { lessonID }), FlashMessage.ERROR); + flashMessage = new FlashMessage("getLessonStaff", + messageService.getMessage("NO.SUCH.LESSON", new Object[] { lessonID }), FlashMessage.ERROR); } return flashMessage.serializeMessage(); } @@ -1630,8 +1646,8 @@ Set sortedUsers = new TreeSet(new Comparator() { @Override public int compare(User usr0, User usr1) { - return ((usr0.getFirstName() + usr0.getLastName() + usr0.getLogin()).compareTo(usr1.getFirstName() - + usr1.getLastName() + usr1.getLogin())); + return ((usr0.getFirstName() + usr0.getLastName() + usr0.getLogin()) + .compareTo(usr1.getFirstName() + usr1.getLastName() + usr1.getLogin())); } }); sortedUsers.addAll(users); @@ -1738,8 +1754,8 @@ Activity activity = activityDAO.getActivityByActivityId(activityID); if (activity == null) { - MonitoringService.log.error("getActivityMonitorURL activity missing. Activity ID " + activityID - + " activity " + activity); + MonitoringService.log.error( + "getActivityMonitorURL activity missing. Activity ID " + activityID + " activity " + activity); } else if (activity.isToolActivity() || activity.isSystemToolActivity()) { return lamsCoreToolService.getToolMonitoringURL(lessonID, activity) + "&contentFolderID=" + contentFolderID; @@ -1767,8 +1783,8 @@ flashMessage = FlashMessage.getUserNotAuthorized("moveLesson", userID); } } else { - flashMessage = new FlashMessage("moveLesson", messageService.getMessage("NO.SUCH.LESSON", - new Object[] { lessonID }), FlashMessage.ERROR); + flashMessage = new FlashMessage("moveLesson", + messageService.getMessage("NO.SUCH.LESSON", new Object[] { lessonID }), FlashMessage.ERROR); } return flashMessage.serializeMessage(); @@ -1780,8 +1796,8 @@ GateActivity gate = (GateActivity) activityDAO.getActivityByActivityId(activityID); FlashMessage flashMessage; if (gate == null) { - flashMessage = new FlashMessage("releaseGate", messageService.getMessage("INVALID.ACTIVITYID", - new Object[] { activityID }), FlashMessage.ERROR); + flashMessage = new FlashMessage("releaseGate", + messageService.getMessage("INVALID.ACTIVITYID", new Object[] { activityID }), FlashMessage.ERROR); } else { // release gate gate = openGate(activityID); @@ -1798,10 +1814,10 @@ Grouping grouping = groupingActivity.getCreateGrouping(); if (!grouping.isChosenGrouping()) { - MonitoringService.log.error("GroupingActivity [" + groupingActivity.getActivityId() - + "] does not have chosen grouping."); - throw new MonitoringServiceException("GroupingActivity [" + groupingActivity.getActivityId() - + "] is not chosen grouping."); + MonitoringService.log.error( + "GroupingActivity [" + groupingActivity.getActivityId() + "] does not have chosen grouping."); + throw new MonitoringServiceException( + "GroupingActivity [" + groupingActivity.getActivityId() + "] is not chosen grouping."); } try { // try to sorted group list by orderID. @@ -1840,8 +1856,8 @@ MonitoringService.log.debug("Persist grouping for [" + grouping.getGroupingId() + "] success."); } catch (WDDXProcessorConversionException e) { - throw new MonitoringServiceException("Perform chosen grouping occurs error when parsing WDDX package:" - + e.getMessage()); + throw new MonitoringServiceException( + "Perform chosen grouping occurs error when parsing WDDX package:" + e.getMessage()); } } @@ -1870,8 +1886,8 @@ newLessonClass.setStaffGroup(Group.createStaffGroup(newLessonClass, staffGroupName, new HashSet(staffs))); // setup learner group // TODO:need confirm group name! - newLessonClass.getGroups().add( - Group.createLearnerGroup(newLessonClass, learnerGroupName, new HashSet(organizationUsers))); + newLessonClass.getGroups() + .add(Group.createLearnerGroup(newLessonClass, learnerGroupName, new HashSet(organizationUsers))); lessonClassDAO.updateLessonClass(newLessonClass); @@ -1902,10 +1918,10 @@ Boolean learnerExportAvailable, Boolean learnerPresenceAvailable, Boolean learnerImAvailable, Boolean liveEditEnabled, Boolean enableLessonNotifications, Boolean learnerRestart, Integer scheduledNumberDaysToLessonFinish, Lesson precedingLesson) { - Lesson newLesson = Lesson.createNewLessonWithoutClass(lessonName, lessonDescription, user, - copiedLearningDesign, enableLessonIntro, displayDesignImage, learnerExportAvailable, - learnerPresenceAvailable, learnerImAvailable, liveEditEnabled, enableLessonNotifications, - learnerRestart, scheduledNumberDaysToLessonFinish); + Lesson newLesson = Lesson.createNewLessonWithoutClass(lessonName, lessonDescription, user, copiedLearningDesign, + enableLessonIntro, displayDesignImage, learnerExportAvailable, learnerPresenceAvailable, + learnerImAvailable, liveEditEnabled, enableLessonNotifications, learnerRestart, + scheduledNumberDaysToLessonFinish); if (precedingLesson != null) { HashSet precedingLessons = new HashSet(); precedingLessons.add(precedingLesson); @@ -1927,7 +1943,7 @@ // make a copy of lazily initialized activities Set activities = new HashSet(copiedLearningDesign.getActivities()); LessonClass newLessonClass = new LessonClass(null, // grouping id - new HashSet(),// groups + new HashSet(), // groups activities, null, // staff group null);// lesson return newLessonClass; @@ -1976,8 +1992,8 @@ Set learners = lesson.getAllLearners(); if (MonitoringService.log.isDebugEnabled()) { - MonitoringService.log.debug("getClassMembersNotGrouped: Lesson " + lessonID + " has " + learners.size() - + " learners."); + MonitoringService.log + .debug("getClassMembersNotGrouped: Lesson " + lessonID + " has " + learners.size() + " learners."); } Iterator iter = grouping.getGroups().iterator(); @@ -1991,8 +2007,8 @@ } if (MonitoringService.log.isDebugEnabled()) { - MonitoringService.log.debug("getClassMembersNotGrouped: Lesson " + lessonID + " has " + learners.size() - + " learners."); + MonitoringService.log + .debug("getClassMembersNotGrouped: Lesson " + lessonID + " has " + learners.size() + " learners."); } SortedSet sortedUsers = new TreeSet(new LastNameAlphabeticComparator()); @@ -2049,10 +2065,8 @@ && (grouping.getGroups().size() >= grouping.getMaxNumberOfGroups())) { boolean usedForBranching = grouping.isUsedForBranching(); if (!usedForBranching) { - MonitoringService.log - .info("Setting max number of groups to null for grouping " - + grouping - + " we have been asked to add a group in excess of the max number of groups (probably via the Chosen Grouping screen)."); + MonitoringService.log.info("Setting max number of groups to null for grouping " + grouping + + " we have been asked to add a group in excess of the max number of groups (probably via the Chosen Grouping screen)."); grouping.setMaxNumberOfGroups(null); // must be null and not // 0 or the groups will // be lost via Live @@ -2370,26 +2384,26 @@ // init Lesson with user as creator Lesson newLesson = this.initializeLesson(lesson.getLessonName(), - lesson.getLessonDescription(), - lesson.getLearningDesign().getLearningDesignId(), group.getOrganisationId(), - userDto.getUserID(), null, lesson.isEnableLessonIntro(), - lesson.isDisplayDesignImage(), lesson.getLearnerExportAvailable(), - lesson.getLearnerPresenceAvailable(), lesson.getLearnerImAvailable(), - lesson.getLiveEditEnabled(), lesson.getEnableLessonNotifications(), - lesson.getLearnerRestart(), null, null); + lesson.getLessonDescription(), lesson.getLearningDesign().getLearningDesignId(), + group.getOrganisationId(), userDto.getUserID(), null, + lesson.isEnableLessonIntro(), lesson.isDisplayDesignImage(), + lesson.getLearnerExportAvailable(), lesson.getLearnerPresenceAvailable(), + lesson.getLearnerImAvailable(), lesson.getLiveEditEnabled(), + lesson.getEnableLessonNotifications(), lesson.getLearnerRestart(), null, null); // save LessonClasses - newLesson = this - .createLessonClassForLesson(newLesson.getLessonId(), group, learnerGroupName, - learnerUsers, staffGroupName, staffUsers, userDto.getUserID()); + newLesson = this.createLessonClassForLesson(newLesson.getLessonId(), group, + learnerGroupName, learnerUsers, staffGroupName, staffUsers, + userDto.getUserID()); // start Lessons // TODO user-specified creator; must be someone in staff group this.startLesson(newLesson.getLessonId(), staffUsers.get(0).getUserId()); result++; } else { - throw new MonitoringServiceException("No learners specified, can't create any Lessons."); + throw new MonitoringServiceException( + "No learners specified, can't create any Lessons."); } } else { throw new MonitoringServiceException("No staff specified, can't create any Lessons."); @@ -2461,4 +2475,25 @@ String message = messageService.getMessage(messageKey, args); auditService.log(MonitoringConstants.MONITORING_MODULE_NAME, message); } + + /** + * Removes learner content from ToolActivities and resets read-only flag, if possible. + */ + private boolean removeLearnerContent(Activity activity, User learner, boolean resetReadOnly) { + activity = getActivityById(activity.getActivityId()); + // remove learner content from this activity + boolean update = lamsCoreToolService.removeLearnerContent(activity, learner); + if (update) { + activityDAO.update(activity); + } + // if the activity reports it is readOnly, resetReadOnly becomes false + // if resetReadOnly was ever set to false, it will never become true (latch) + resetReadOnly &= !lamsCoreToolService.isActivityReadOnly(activity); + if (resetReadOnly) { + activity.setReadOnly(false); + activityDAO.update(activity); + } + + return resetReadOnly; + } } \ No newline at end of file Index: lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java =================================================================== diff -u -r8235ff2b4eb95000b9a16627df990faf66eeb5ac -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java (.../AssessmentServiceImpl.java) (revision 8235ff2b4eb95000b9a16627df990faf66eeb5ac) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java (.../AssessmentServiceImpl.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -1867,6 +1867,15 @@ return getAssessmentByContentId(toolContentId).isDefineLater(); } + public boolean isReadOnly(Long toolContentId) { + for (AssessmentSession session : assessmentSessionDao.getByContentId(toolContentId)) { + if (!session.getAssessmentUsers().isEmpty()) { + return true; + } + } + return false; + } + /* ===============Methods implemented from ToolContentImport102Manager =============== */ /** Index: lams_tool_bbb/src/java/org/lamsfoundation/lams/tool/bbb/service/BbbService.java =================================================================== diff -u -ra0bce7961a19548c58f5b0025160f124785f9951 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_bbb/src/java/org/lamsfoundation/lams/tool/bbb/service/BbbService.java (.../BbbService.java) (revision a0bce7961a19548c58f5b0025160f124785f9951) +++ lams_tool_bbb/src/java/org/lamsfoundation/lams/tool/bbb/service/BbbService.java (.../BbbService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -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 } /* 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,22 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { // TODO Auto-generated method stub } - + + @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 +238,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 +266,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 +291,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 +304,100 @@ * * @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(); } - + + @Override + public boolean isReadOnly(Long toolContentId) { + Bbb content = getBbbByContentId(toolContentId); + for (BbbSession session : content.getBbbSessions()) { + for (BbbUser user : session.getBbbUsers()) { + if (user.getNotebookEntryUID() != null) { + // we don't remove users in removeLearnerContent() + // we just set their notebook entry to NULL + return true; + } + } + } + + return false; + } + /* 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 +409,7 @@ return newContent; } + @Override @SuppressWarnings("unchecked") public Bbb getBbbByContentId(Long toolContentID) { List list = bbbDAO.findByProperty(Bbb.class, "toolContentId", toolContentID); @@ -380,6 +420,7 @@ } } + @Override @SuppressWarnings("unchecked") public BbbSession getSessionBySessionId(Long toolSessionId) { List list = bbbSessionDAO.findByProperty(BbbSession.class, "sessionId", toolSessionId); @@ -390,6 +431,7 @@ } } + @Override @SuppressWarnings("unchecked") public BbbUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { Map map = new HashMap(); @@ -403,6 +445,7 @@ } } + @Override @SuppressWarnings("unchecked") public BbbUser getUserByUID(Long uid) { List list = bbbUserDAO.findByProperty(BbbUser.class, "uid", uid); @@ -413,159 +456,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 +609,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 +624,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 -ra0bce7961a19548c58f5b0025160f124785f9951 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/ChatService.java (.../ChatService.java) (revision a0bce7961a19548c58f5b0025160f124785f9951) +++ lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/ChatService.java (.../ChatService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -85,7 +85,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 +115,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 +172,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,7 +200,7 @@ 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 @@ -229,7 +232,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 +243,23 @@ chatDAO.saveOrUpdate(chat); } - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + @Override + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { // TODO Auto-generated method stub } + @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 +287,7 @@ } } - + /** * Export the XML fragment for the tool's content, along with any files needed for the content. * @@ -290,6 +297,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 +324,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 +357,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 +369,31 @@ 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(); } + @Override + public boolean isReadOnly(Long toolContentId) { + Chat chat = chatDAO.getByContentId(toolContentId); + for (ChatSession session : (Set) chat.getChatSessions()) { + if (!session.getChatMessages().isEmpty()) { + // we don't remove users in removeLearnerContent(), just messages + return true; + } + } + + return false; + } + /* 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 -r37c1972aaf34449bc4d3741c87b49f666840ebcb -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_daco/src/java/org/lamsfoundation/lams/tool/daco/service/DacoServiceImpl.java (.../DacoServiceImpl.java) (revision 37c1972aaf34449bc4d3741c87b49f666840ebcb) +++ lams_tool_daco/src/java/org/lamsfoundation/lams/tool/daco/service/DacoServiceImpl.java (.../DacoServiceImpl.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -190,8 +190,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 +220,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 +253,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 +321,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 +340,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 +409,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 +450,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 +505,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 +523,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,7 +588,7 @@ 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 @@ -610,13 +612,24 @@ public String getToolContentTitle(Long toolContentId) { return getDacoByContentId(toolContentId).getTitle(); } - + @Override public boolean isContentEdited(Long toolContentId) { return getDacoByContentId(toolContentId).isDefineLater(); } - + @Override + public boolean isReadOnly(Long toolContentId) { + for (DacoSession session : dacoSessionDao.getByContentId(toolContentId)) { + if (!dacoUserDao.getBySessionId(session.getSessionId()).isEmpty()) { + return true; + } + } + + return false; + } + + @Override public DacoUser getUser(Long uid) { return (DacoUser) dacoUserDao.getObject(DacoUser.class, uid); } @@ -634,18 +647,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 +688,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 +711,8 @@ } return learnerService.completeToolSession(toolSessionId, learnerId); } - + + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } @@ -716,7 +732,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,21 +761,24 @@ 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, boolean removeSessionData) + throws SessionDataExistsException, ToolException { Daco daco = dacoDao.getByContentId(toolContentId); if (removeSessionData) { List list = dacoSessionDao.getByContentId(toolContentId); @@ -770,9 +789,11 @@ 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 +820,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 +840,7 @@ dacoQuestionDao.saveObject(question); } + @Override public void saveOrUpdateDacoSession(DacoSession resSession) { dacoSessionDao.saveObject(resSession); } @@ -836,11 +861,11 @@ public ICoreNotebookService getCoreNotebookService() { return coreNotebookService; } - + public IUserManagementService getUserManagementService() { return userManagementService; } - + public void setCoreNotebookService(ICoreNotebookService coreNotebookService) { this.coreNotebookService = coreNotebookService; } @@ -905,6 +930,7 @@ this.eventNotificationService = eventNotificationService; } + @Override public int getRecordNum(Long userID, Long sessionId) { return dacoAnswerDao.getUserRecordCount(userID, sessionId); } @@ -917,6 +943,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 -r37c1972aaf34449bc4d3741c87b49f666840ebcb -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_eadventure/src/java/org/eucm/lams/tool/eadventure/service/EadventureServiceImpl.java (.../EadventureServiceImpl.java) (revision 37c1972aaf34449bc4d3741c87b49f666840ebcb) +++ lams_tool_eadventure/src/java/org/eucm/lams/tool/eadventure/service/EadventureServiceImpl.java (.../EadventureServiceImpl.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -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; @@ -117,24 +116,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 +159,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 +188,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 +217,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 +230,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 +242,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"); @@ -264,81 +264,92 @@ } //TODO revisar - /* public List getAuthoredItems(Long eadventureUid) { - return eadventureItemDao.getAuthoringItems(eadventureUid); + /* 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 + @Override public List exportBySessionId(Long sessionId, Long userId) { EadventureSession session = eadventureSessionDao.getSessionBySessionId(sessionId); if (session == null) { @@ -350,87 +361,85 @@ Eadventure ead = session.getEadventure(); Summary sum = new Summary(session.getSessionId(), session.getSessionName(), ead, false); - - //List userList = getUserListBySessionItem(session.getSessionId(), ead.getUid()); boolean[] existList = new boolean[1]; String[] reportList = new String[1]; - - EadventureUser eadUser = eadventureUserDao.getUserByUserIDAndSessionID(userId,sessionId); + + 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 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){ + 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 +448,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 +485,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 +531,9 @@ } return nextUrl; } - + //TODO revisar!!!! monitoring + @Override public List getSummary(Long contentId) { List groupList = new ArrayList(); @@ -529,45 +545,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){ + 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 +617,7 @@ return map; } + @Override public List getUserListBySessionItem(Long sessionId, Long itemUid) { List logList = eadventureItemVisitDao.getEadventureItemLogBySession(sessionId, itemUid); List userList = new ArrayList(logList.size()); @@ -611,6 +631,7 @@ } //TODO revisar Monitoring!!! + @Override public void setItemVisible(Long itemUid, boolean visible) { /*EadventureItem item = eadventureItemDao.getByUid(itemUid); if (item != null) { @@ -631,15 +652,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 +672,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 +719,77 @@ } 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,7 +821,7 @@ * @param packageDirectory * @return */ - + //TODO creo que vga a sobrar private String findWebsiteInitialItem(String packageDirectory) { File file = new File(packageDirectory); @@ -801,8 +830,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(); @@ -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) { @@ -898,19 +929,21 @@ try { //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 exportContentService.registerFileClassForImport(Eadventure.class.getName(), "fileUuid", "fileVersionId", "fileName", "fileType", null, "initialItem"); @@ -941,27 +974,24 @@ // 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: 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"); @@ -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,12 +1074,25 @@ 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 boolean isReadOnly(Long toolContentId) { + for (EadventureSession session : eadventureSessionDao.getByContentId(toolContentId)) { + if (!eadventureUserDao.getBySessionID(session.getSessionId()).isEmpty()) { + return true; + } + } + + return false; + } + + @Override + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { Eadventure eadventure = eadventureDao.getByContentId(toolContentId); if (removeSessionData) { List list = eadventureSessionDao.getByContentId(toolContentId); @@ -1059,14 +1105,17 @@ 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 +1142,7 @@ } } + @Override public void removeParams(Long toolContentId) { List params = getEadventureParamByContentId(toolContentId); if (params != null) { @@ -1137,13 +1187,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,7 +1212,7 @@ 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 @@ -1172,6 +1223,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(); Eadventure toolContentObj = new Eadventure(); @@ -1182,8 +1234,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 +1265,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 +1336,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 +1400,7 @@ this.coreNotebookService = coreNotebookService; } + @Override public IEventNotificationService getEventNotificationService() { return eventNotificationService; } @@ -1357,6 +1409,7 @@ this.eventNotificationService = eventNotificationService; } + @Override public String getLocalisedMessage(String key, Object[] args) { return messageService.getMessage(key, args); } @@ -1373,17 +1426,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!!! - + /*public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { - return getEadventureOutputFactory().getSupportedDefinitionClasses(definitionType); + return getEadventureOutputFactory().getSupportedDefinitionClasses(definitionType); }*/ public EadventureOutputFactory getEadventureOutputFactory() { @@ -1393,211 +1447,219 @@ 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 + @Override public boolean setAppletInput(String name, String value, String userId, String toolContentID) { //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("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)); + //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)); + 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())); + 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 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 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 -rd9233ffdc6627f56c33fcf37ddc9f6c2c7fbcb4c -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/service/ForumService.java (.../ForumService.java) (revision d9233ffdc6627f56c33fcf37ddc9f6c2c7fbcb4c) +++ lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/service/ForumService.java (.../ForumService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -126,7 +126,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 @@ -184,6 +185,7 @@ this.auditService = auditService; } + @Override public IAuditService getAuditService() { return auditService; } @@ -200,15 +202,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 +223,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 +269,7 @@ return message; } + @Override public Message updateTopic(Message message) throws PersistenceException { // update message @@ -277,7 +285,7 @@ return message; } - + @Override public List getMessageAsDTO(Long messageUid) throws PersistenceException { MessageSeq msgSeq = messageSeqDao.getByMessageId(messageUid); @@ -286,10 +294,12 @@ return msgDtoList; } + @Override public void updateContainedReport(Message message) { messageDao.saveOrUpdate(message); } + @Override public Message updateMessageHideFlag(Long messageId, boolean hideFlag) { Message message = getMessage(messageId); @@ -318,10 +328,12 @@ return messageDao.getByIdForUpdate(messageUid); } + @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); @@ -364,20 +376,20 @@ // 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()); @@ -395,7 +407,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); } @@ -421,65 +433,65 @@ 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 { + do { - List msgSeqs = messageSeqDao.getNextThreadByThreadId(rootTopicId, lastThreadMessageUid); - if ( msgSeqs.size() == 0 ) { + 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 ) { + 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 ) { + if ((usePagingSize >= 0) && (count >= usePagingSize)) { foundEnough = true; } - } - } while ( ! foundEnough); + } + } 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(); + 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,12 +527,12 @@ 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) { return forumUserDao.getUsersForTablesorter(sessionId, page, size, sorting); } - + @Override public int getCountUsersBySession(Long sessionId) { return forumUserDao.getCountUsersBySession(sessionId); @@ -539,7 +551,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; } @@ -614,8 +626,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); } } @@ -652,7 +664,7 @@ currentUser.setSessionFinished(true); forumUserDao.save(currentUser); } - + @Override public AverageRatingDTO rateMessage(Long messageId, Long userId, Long toolSessionID, float rating) { ForumUser imageGalleryUser = getUserByUserAndSession(userId, toolSessionID); @@ -670,12 +682,12 @@ //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); @@ -715,7 +727,6 @@ return dto; } - /** * Process an uploaded file. * @@ -727,7 +738,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()); @@ -797,7 +808,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); @@ -808,12 +819,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); @@ -822,6 +833,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"); @@ -844,7 +856,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; } @@ -870,9 +882,10 @@ forum.setDefineLater(false); forum.setContentInUse(false); } - - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + + @Override + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { Forum forum = forumDao.getByContentId(toolContentId); if (removeSessionData) { List list = forumToolSessionDao.getByContentId(toolContentId); @@ -885,10 +898,12 @@ forumDao.delete(forum); } + @Override @SuppressWarnings("unchecked") 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); @@ -961,7 +976,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); @@ -988,15 +1003,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; @@ -1050,13 +1065,28 @@ public String getToolContentTitle(Long toolContentId) { return getForumByContentId(toolContentId).getTitle(); } - + @Override public boolean isContentEdited(Long toolContentId) { return getForumByContentId(toolContentId).isDefineLater(); } - + @Override + public boolean isReadOnly(Long toolContentId) { + for (ForumToolSession session : (List) forumToolSessionDao.getByContentId(toolContentId)) { + for (ForumUser user : (List) forumUserDao.getBySessionId(session.getSessionId())) { + // we don't remove users in removeLearnerContent() + // we just remove or hide messages + if (!messageDao.getByUserAndSession(user.getUid(), session.getSessionId()).isEmpty()) { + return true; + } + } + } + + return false; + } + + @Override public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException { ForumToolSession session = new ForumToolSession(); session.setSessionId(toolSessionId); @@ -1070,9 +1100,9 @@ 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); @@ -1082,7 +1112,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."); } } @@ -1111,13 +1141,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; } @@ -1137,7 +1168,7 @@ 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 @@ -1153,7 +1184,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); } @@ -1174,6 +1206,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(); @@ -1192,8 +1225,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); @@ -1262,8 +1295,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); @@ -1276,19 +1309,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) { @@ -1450,6 +1482,7 @@ this.coreNotebookService = coreNotebookService; } + @Override public IEventNotificationService getEventNotificationService() { return eventNotificationService; } @@ -1458,6 +1491,7 @@ this.eventNotificationService = eventNotificationService; } + @Override public String getLocalisedMessage(String key, Object[] args) { return messageService.getMessage(key, args); } @@ -1469,14 +1503,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 { @@ -1498,6 +1533,7 @@ * @param userId * @return */ + @Override public int getNewMessagesNum(Message message, Long userId) { Timestamp timestamp = timestampDao.getTimestamp(message.getUid(), userId); if (timestamp == null) { @@ -1508,6 +1544,7 @@ } } + @Override public void saveTimestamp(Long rootTopicId, ForumUser forumUser) { Timestamp timestamp = timestampDao.getTimestamp(rootTopicId, forumUser.getUid()); if (timestamp != null) { @@ -1521,6 +1558,7 @@ timestampDao.saveOrUpdate(timestamp); } + @Override public void sendNotificationsOnNewPosting(Long forumId, Long sessionId, Message message) { Forum forum = getForum(forumId); ForumUser postAuthor = message.getCreatedBy(); @@ -1532,7 +1570,7 @@ if (forum.isNotifyLearnersOnForumPosting()) { List learners = lessonService.getLearnersHaveAttemptedActivity(activity); - if (learners != null && !learners.isEmpty()) { + if ((learners != null) && !learners.isEmpty()) { ArrayList learnerIds = new ArrayList(); for (User learner : learners) { learnerIds.add(learner.getUserId()); @@ -1553,19 +1591,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(); @@ -1575,7 +1615,7 @@ 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 @@ -1593,58 +1633,62 @@ 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); + // 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 +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,14 +174,15 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return null; } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { //no actions required } /* ************ Methods from ToolContentManager ************************* */ + @Override public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { if (GmapService.logger.isDebugEnabled()) { @@ -214,19 +216,23 @@ gmap.setDefineLater(false); gmapDAO.saveOrUpdate(gmap); } - - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + + @Override + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { // TODO Auto-generated method stub } + @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 +259,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 +310,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 +362,38 @@ * * @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(); } - + + @Override + public boolean isReadOnly(Long toolContentId) { + Gmap gmap = gmapDAO.getByContentId(toolContentId); + for (GmapMarker marker : gmap.getGmapMarkers()) { + if (!marker.isAuthored()) { + // in removeLearnerContent we only remove markers, not users + return true; + } + } + + return false; + } + /* ********** IGmapService Methods ********************************* */ + @Override public Long getDefaultContentIdBySignature(String toolSignature) { Long toolContentId = null; toolContentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature)); @@ -380,6 +405,7 @@ return toolContentId; } + @Override public Gmap getDefaultContent() { Long defaultContentID = getDefaultContentIdBySignature(GmapConstants.TOOL_SIGNATURE); Gmap defaultContent = getGmapByContentId(defaultContentID); @@ -391,6 +417,7 @@ return defaultContent; } + @Override public Gmap copyDefaultContent(Long newContentID) { if (newContentID == null) { @@ -407,6 +434,7 @@ return newContent; } + @Override public Gmap getGmapByContentId(Long toolContentID) { Gmap gmap = gmapDAO.getByContentId(toolContentID); if (gmap == null) { @@ -415,6 +443,7 @@ return gmap; } + @Override public GmapSession getSessionBySessionId(Long toolSessionId) { GmapSession gmapSession = gmapSessionDAO.getBySessionId(toolSessionId); if (gmapSession == null) { @@ -423,6 +452,7 @@ return gmapSession; } + @Override public GmapUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { return gmapUserDAO.getByUserIdAndSessionId(userId, toolSessionId); } @@ -431,40 +461,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 +515,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 +571,8 @@ GmapService.logger.debug("MarkerXML string was empty"); } } - + + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } @@ -541,6 +582,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 +598,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 +696,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 +714,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 -r37c1972aaf34449bc4d3741c87b49f666840ebcb -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_images/src/java/org/lamsfoundation/lams/tool/imageGallery/service/ImageGalleryServiceImpl.java (.../ImageGalleryServiceImpl.java) (revision 37c1972aaf34449bc4d3741c87b49f666840ebcb) +++ lams_tool_images/src/java/org/lamsfoundation/lams/tool/imageGallery/service/ImageGalleryServiceImpl.java (.../ImageGalleryServiceImpl.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -58,8 +58,6 @@ 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.rating.ToolRatingManager; -import org.lamsfoundation.lams.rating.dto.ItemRatingCriteriaDTO; import org.lamsfoundation.lams.rating.dto.ItemRatingDTO; import org.lamsfoundation.lams.rating.model.RatingCriteria; import org.lamsfoundation.lams.rating.service.IRatingService; @@ -110,8 +108,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_"; @@ -157,7 +155,7 @@ private IExportToolContentService exportContentService; private ICoreNotebookService coreNotebookService; - + private IRatingService ratingService; private IEventNotificationService eventNotificationService; @@ -222,18 +220,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); } @@ -360,7 +359,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); @@ -371,7 +370,7 @@ public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } - + @Override public ItemRatingDTO getRatingCriteriaDtos(Long contentId, Long imageUid, Long userId) { @@ -381,29 +380,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); @@ -471,7 +471,8 @@ List users = imageGalleryUserDao.getBySessionID(session.getSessionId()); for (ImageGalleryUser user : users) { - UserImageContributionDTO userContribution = createUserContribution(image, user, session, ratingForGroup); + UserImageContributionDTO userContribution = createUserContribution(image, user, session, + ratingForGroup); group.add(userContribution); } @@ -592,7 +593,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 @@ -607,7 +609,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 @@ -623,17 +626,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")); } } @@ -648,9 +651,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; @@ -668,12 +671,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(); @@ -695,7 +698,7 @@ public void setMessageService(MessageService messageService) { this.messageService = messageService; } - + public void setImageGalleryDao(ImageGalleryDAO imageGalleryDao) { this.imageGalleryDao = imageGalleryDao; } @@ -771,7 +774,7 @@ Set images = toolContentObj.getImageGalleryItems(); for (ImageGalleryItem image : images) { image.setComments(null); - + //convert file extension to lower case String fileName = image.getFileName(); String[] fileNameParts = fileName.split("\\."); @@ -815,15 +818,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; @@ -905,15 +908,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); @@ -927,10 +930,21 @@ public boolean isContentEdited(Long toolContentId) { return getImageGalleryByContentId(toolContentId).isDefineLater(); } - + @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public boolean isReadOnly(Long toolContentId) { + for (ImageGallerySession session : imageGallerySessionDao.getByContentId(toolContentId)) { + if (!imageGalleryUserDao.getBySessionID(session.getSessionId()).isEmpty()) { + return true; + } + } + + return false; + } + + @Override + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { ImageGallery imageGallery = imageGalleryDao.getByContentId(toolContentId); if (removeSessionData) { List list = imageGallerySessionDao.getByContentId(toolContentId); @@ -946,15 +960,17 @@ @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(); @@ -998,19 +1014,21 @@ } } - ImageGalleryUser user = imageGalleryUserDao.getUserByUserIDAndContentID(userId.longValue(), toolContentId); - if (user != null) { - NotebookEntry entry = getEntry(user.getSession().getSessionId(), CoreNotebookConstants.NOTEBOOK_TOOL, - ImageGalleryConstants.TOOL_SIGNATURE, userId); - if (entry != null) { - imageGalleryDao.removeObject(NotebookEntry.class, entry.getUid()); - } + for (ImageGallerySession session : imageGallerySessionDao.getByContentId(toolContentId)) { + ImageGalleryUser user = imageGalleryUserDao.getUserByUserIDAndSessionID(userId.longValue(), + session.getSessionId()); + if (user != null) { + NotebookEntry entry = getEntry(user.getSession().getSessionId(), CoreNotebookConstants.NOTEBOOK_TOOL, + ImageGalleryConstants.TOOL_SIGNATURE, userId); + if (entry != null) { + imageGalleryDao.removeObject(NotebookEntry.class, entry.getUid()); + } - imageGalleryUserDao.removeObject(ImageGalleryUser.class, user.getUid()); + imageGalleryUserDao.removeObject(ImageGalleryUser.class, user.getUid()); + } } - } - + @Override public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException { ImageGallerySession session = new ImageGallerySession(); @@ -1046,13 +1064,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; } @@ -1070,7 +1089,7 @@ 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 @@ -1081,12 +1100,14 @@ /** * 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) { @@ -1123,7 +1144,7 @@ public void setCoreNotebookService(ICoreNotebookService coreNotebookService) { this.coreNotebookService = coreNotebookService; } - + public void setRatingService(IRatingService ratingService) { this.ratingService = ratingService; } @@ -1132,6 +1153,7 @@ this.eventNotificationService = eventNotificationService; } + @Override public String getLocalisedMessage(String key, Object[] args) { return messageService.getMessage(key, args); } @@ -1144,14 +1166,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()); @@ -1169,6 +1194,7 @@ return images; } + @Override @Deprecated public Object[] getRatingForGroup(Long imageUid, Long sessionId) { List users = imageGalleryUserDao.getBySessionID(sessionId); @@ -1233,7 +1259,7 @@ 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); @@ -1250,6 +1276,7 @@ return userContribution; } + @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 -r4a60402cb4b47c88641cb8eb75b0b09360e1a7ad -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_imscc/src/java/org/lamsfoundation/lams/tool/commonCartridge/service/CommonCartridgeServiceImpl.java (.../CommonCartridgeServiceImpl.java) (revision 4a60402cb4b47c88641cb8eb75b0b09360e1a7ad) +++ lams_tool_imscc/src/java/org/lamsfoundation/lams/tool/commonCartridge/service/CommonCartridgeServiceImpl.java (.../CommonCartridgeServiceImpl.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -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; @@ -109,8 +105,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 +132,7 @@ private ILamsToolService toolService; private ILearnerService learnerService; - + private IAuditService auditService; private IUserManagementService userManagementService; @@ -149,6 +145,7 @@ private ILessonService lessonService; + @Override public IVersionedNode getFileNode(Long itemUid, String relPathString) throws CommonCartridgeApplicationException { CommonCartridgeItem item = (CommonCartridgeItem) commonCartridgeItemDao.getObject(CommonCartridgeItem.class, itemUid); @@ -227,11 +224,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 +245,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 +289,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 +312,7 @@ return items; } + @Override public List exportBySessionId(Long sessionId, boolean skipHide) { CommonCartridgeSession session = commonCartridgeSessionDao.getSessionBySessionId(sessionId); if (session == null) { @@ -342,6 +350,7 @@ return itemList; } + @Override public List> exportByContentId(Long contentId) { CommonCartridge commonCartridge = commonCartridgeDao.getByContentId(contentId); List> groupList = new ArrayList(); @@ -379,26 +388,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 +424,7 @@ } } + @Override public void setItemComplete(Long commonCartridgeItemUid, Long userId, Long sessionId) { CommonCartridgeItemVisitLog log = commonCartridgeItemVisitDao.getCommonCartridgeItemLog(commonCartridgeItemUid, userId); @@ -427,6 +441,7 @@ commonCartridgeItemVisitDao.saveObject(log); } + @Override public void setItemAccess(Long commonCartridgeItemUid, Long userId, Long sessionId) { CommonCartridgeItemVisitLog log = commonCartridgeItemVisitDao.getCommonCartridgeItemLog(commonCartridgeItemUid, userId); @@ -443,6 +458,7 @@ } } + @Override public String finishToolSession(Long toolSessionId, Long userId) throws CommonCartridgeApplicationException { CommonCartridgeUser user = commonCartridgeUserDao.getUserByUserIDAndSessionID(userId, toolSessionId); user.setSessionFinished(true); @@ -463,6 +479,7 @@ return nextUrl; } + @Override public int checkMiniView(Long toolSessionId, Long userUid) { int miniView = commonCartridgeItemVisitDao.getUserViewLogCount(toolSessionId, userUid); CommonCartridgeSession session = commonCartridgeSessionDao.getSessionBySessionId(toolSessionId); @@ -475,10 +492,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 +547,7 @@ } + @Override public Map> getReflectList(Long contentId, boolean setEntry) { Map> map = new HashMap>(); @@ -558,9 +578,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 +591,7 @@ return userList; } + @Override public void setItemVisible(Long itemUid, boolean visible) { CommonCartridgeItem item = commonCartridgeItemDao.getByUid(itemUid); if (item != null) { @@ -590,15 +612,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 +632,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 +668,7 @@ return contentId; } + @Override public List uploadCommonCartridgeFile(CommonCartridgeItem item, FormFile file) throws UploadCommonCartridgeFileException { try { @@ -655,43 +682,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 +756,8 @@ this.commonCartridgeSessionDao = commonCartridgeSessionDao; } - public void setCommonCartridgeToolContentHandler(CommonCartridgeToolContentHandler commonCartridgeToolContentHandler) { + public void setCommonCartridgeToolContentHandler( + CommonCartridgeToolContentHandler commonCartridgeToolContentHandler) { this.commonCartridgeToolContentHandler = commonCartridgeToolContentHandler; } @@ -759,6 +789,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 +816,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 +837,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 +861,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 +874,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 +912,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,15 +925,29 @@ } 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 boolean isReadOnly(Long toolContentId) { + CommonCartridge cartridge = commonCartridgeDao.getByContentId(toolContentId); + for (CommonCartridgeItem item : (Set) cartridge.getCommonCartridgeItems()) { + if (!item.isCreateByAuthor()) { + // we don't remove users in removeLearnerContent() + // we just remove their items + return true; + } + } + + return false; + } + + @Override + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { CommonCartridge commonCartridge = commonCartridgeDao.getByContentId(toolContentId); if (removeSessionData) { List list = commonCartridgeSessionDao.getByContentId(toolContentId); @@ -909,17 +959,19 @@ } 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 +989,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 +1050,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,7 +1075,7 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return null; } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { //no actions required @@ -1033,6 +1086,7 @@ /** * Import the data for a 1.0.2 Noticeboard or HTMLNoticeboard */ + @Override public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { } @@ -1044,7 +1098,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 +1115,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 +1155,7 @@ this.coreNotebookService = coreNotebookService; } + @Override public IEventNotificationService getEventNotificationService() { return eventNotificationService; } @@ -1108,6 +1164,7 @@ this.eventNotificationService = eventNotificationService; } + @Override public String getLocalisedMessage(String key, Object[] args) { return messageService.getMessage(key, args); } @@ -1127,6 +1184,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 -ra0bce7961a19548c58f5b0025160f124785f9951 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_kaltura/src/java/org/lamsfoundation/lams/tool/kaltura/service/KalturaService.java (.../KalturaService.java) (revision a0bce7961a19548c58f5b0025160f124785f9951) +++ lams_tool_kaltura/src/java/org/lamsfoundation/lams/tool/kaltura/service/KalturaService.java (.../KalturaService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -85,19 +85,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 +107,9 @@ private ILearnerService learnerService; private ILamsToolService toolService; - + private IUserManagementService userManagementService; - + private MessageService messageService; private IToolContentHandler kalturaToolContentHandler = null; @@ -129,8 +129,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 +149,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,7 +174,7 @@ 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 @@ -184,8 +185,8 @@ @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 +215,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); @@ -233,16 +234,17 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { } - + + @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 +276,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 +321,28 @@ 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(); } - + + @Override + public boolean isReadOnly(Long toolContentId) { + Kaltura kaltura = kalturaDao.getByContentId(toolContentId); + for (KalturaSession session : (Set) kaltura.getKalturaSessions()) { + if (session.getKalturaUsers().isEmpty()) { + return true; + } + } + + return false; + } + /* ********** IKalturaService Methods ********************************* */ @Override public Long createNotebookEntry(Long sessionId, Integer notebookToolType, String toolSignature, Integer userId, @@ -340,7 +355,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 +366,7 @@ public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } - + @Override public List getReflectList(Kaltura kaltura) { List reflectList = new LinkedList(); @@ -367,18 +382,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,12 +410,12 @@ } 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 if (itemRating == null) { // add @@ -410,31 +425,31 @@ } itemRating.setRating(rating); kalturaRatingDao.insertOrUpdate(itemRating); - + //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()); @@ -444,24 +459,25 @@ for (KalturaItem item : allItems) { //hide hidden items from learner and ignore this parameter for teacher - boolean isHidden = isMonitoring || !isMonitoring && !item.isHidden(); - + 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) )) { - + 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 +493,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 +509,7 @@ kalturaItemDao.update(item); } } - + @Override public void hideComment(Long commentUid, boolean isHiding) { KalturaComment comment = kalturaCommentDao.getCommentByUid(commentUid); @@ -502,12 +518,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 +535,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 +547,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 +558,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 +574,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 +583,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 +597,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 +632,7 @@ public void setAuditService(IAuditService auditService) { this.auditService = auditService; } - + @Override public String getLocalisedMessage(String key, Object[] args) { return messageService.getMessage(key, args); @@ -627,14 +643,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 +668,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 +712,7 @@ public void setExportContentService(IExportToolContentService exportContentService) { this.exportContentService = exportContentService; } - + public void setUserManagementService(IUserManagementService userManagementService) { this.userManagementService = userManagementService; } @@ -710,15 +728,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/McServicePOJO.java =================================================================== diff -u -r8235ff2b4eb95000b9a16627df990faf66eeb5ac -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/McServicePOJO.java (.../McServicePOJO.java) (revision 8235ff2b4eb95000b9a16627df990faf66eeb5ac) +++ lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/McServicePOJO.java (.../McServicePOJO.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -118,8 +118,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; @@ -144,10 +144,10 @@ public McServicePOJO() { } - + @Override public McQueUsr checkLeaderSelectToolForSessionLeader(McQueUsr user, Long toolSessionId) { - if (user == null || toolSessionId == null) { + if ((user == null) || (toolSessionId == null)) { return null; } @@ -159,12 +159,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(); @@ -180,7 +180,7 @@ return leader; } - + @Override public void copyAnswersFromLeader(McQueUsr user, McQueUsr leader) { @@ -190,7 +190,7 @@ List leaderAttempts = this.getFinalizedUserAttempts(leader); for (McUsrAttempt leaderAttempt : leaderAttempts) { - + McQueContent question = leaderAttempt.getMcQueContent(); McUsrAttempt userAttempt = mcUsrAttemptDAO.getUserAttemptByQuestion(user.getUid(), question.getUid()); @@ -201,7 +201,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()); @@ -219,7 +219,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); } } @@ -231,7 +232,7 @@ throw new McApplicationException("Exception occured when lams is loading mc content: " + e.getMessage(), e); } } - + @Override public void setDefineLater(String strToolContentID, boolean value) { @@ -247,8 +248,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); } } @@ -259,8 +260,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); } } @@ -269,8 +270,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); } } @@ -279,11 +280,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) { @@ -334,15 +335,15 @@ Long optionUid = optionDTO.getUid(); String optionText = optionDTO.getCandidateAnswer(); boolean isCorrectOption = "Correct".equals(optionDTO.getCorrect()); - + //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); @@ -351,7 +352,7 @@ newOptions.add(option); displayOrderOption++; } - + question.setMcOptionsContents(newOptions); // updating the existing question content @@ -360,14 +361,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 { @@ -380,7 +381,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); @@ -410,8 +411,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); } } @@ -425,12 +426,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()); @@ -455,7 +457,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); } @@ -470,11 +473,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(); @@ -484,7 +487,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); @@ -501,17 +504,17 @@ learnerAnswersDTOList.add(learnerAnswersDTO); } - + //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 for (McOptsContent option : learnerAnswersDTO.getOptions()) { if (selectedOptionUid.equals(option.getUid())) { @@ -524,7 +527,7 @@ return learnerAnswersDTOList; } - + @Override public List buildGroupsMarkData(McContent mcContent, boolean isFullAttemptDetailsRequired) { List listMonitoredMarksContainerDTO = new LinkedList(); @@ -541,7 +544,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()) { @@ -573,8 +577,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 @@ -591,7 +595,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++; @@ -631,19 +635,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); } } @@ -652,8 +657,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); } } @@ -662,8 +667,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); } } @@ -673,8 +678,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); } } @@ -683,8 +688,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); } } @@ -693,8 +698,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); } } @@ -703,8 +708,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); } } @@ -718,8 +723,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); } } @@ -728,7 +733,7 @@ if (uid == null) { return null; } - + return mcQueContentDAO.findMcQuestionContentByUid(uid); } @@ -737,62 +742,62 @@ 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); + 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 List modifiedQuestions = new ArrayList(); //create list of modified question marks - List modifiedQuestionsMarksOnly= new ArrayList(); + 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 if (!oldQuestion.getQuestion().equals(questionDTO.getQuestion())) { isQuestionModified = true; } - + //mark is different if (oldQuestion.getMark().intValue() != (new Integer(questionDTO.getMark())).intValue()) { isQuestionMarkModified = true; } - + //options are different Set oldOptions = oldQuestion.getMcOptionsContents(); List optionDTOs = questionDTO.getListCandidateAnswersDTO(); @@ -807,27 +812,27 @@ } } } - + 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 List userAttempts = getFinalizedUserAttempts(user); Iterator iter = userAttempts.iterator(); @@ -837,20 +842,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; } @@ -873,7 +878,7 @@ } if (isRemoveQuestionResult) { - + Integer oldMark = userAttempt.getMark(); if (oldMark != null) { newTotalMark -= oldMark; @@ -885,7 +890,6 @@ // [+] doing nothing if the new question was added - } // propagade new total mark to Gradebook if it was changed @@ -896,54 +900,53 @@ } } - } - + @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(); greenColor.setFillForegroundColor(IndexedColors.GREEN.getIndex()); greenColor.setFillPattern(CellStyle.SOLID_FOREGROUND); - + // ======================================================= 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); @@ -957,17 +960,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); @@ -980,13 +983,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++) { @@ -1010,7 +1013,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++; @@ -1019,14 +1022,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) { @@ -1037,10 +1040,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++) { @@ -1050,30 +1053,30 @@ 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 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 @@ -1091,15 +1094,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); @@ -1120,22 +1123,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(); @@ -1229,8 +1232,8 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { if (toolContentId == null) { McServicePOJO.logger.error("toolContentId is null"); @@ -1251,7 +1254,7 @@ Iterator sessionUsersIterator = mcSession.getMcQueUsers().iterator(); while (sessionUsersIterator.hasNext()) { McQueUsr mcQueUsr = (McQueUsr) sessionUsersIterator.next(); - + mcUsrAttemptDAO.removeAllUserAttempts(mcQueUsr.getUid()); } } @@ -1261,7 +1264,7 @@ throw new ToolException("toolContentId is missing"); } } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { McContent mcContent = getMcContent(toolContentId); @@ -1270,14 +1273,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); @@ -1293,7 +1296,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); } @@ -1304,7 +1307,7 @@ } } } - + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { McContent toolContentObj = mcContentDAO.findMcContentById(toolContentId); @@ -1333,11 +1336,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; @@ -1363,21 +1366,34 @@ @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(); } - + + @Override + public boolean isReadOnly(Long toolContentId) { + McContent content = mcContentDAO.findMcContentById(toolContentId); + for (McSession session : (Set) content.getMcSessions()) { + if (!session.getMcQueUsers().isEmpty()) { + return true; + } + } + + return false; + } + /** * 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; @@ -1474,13 +1490,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"); } @@ -1494,7 +1511,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(); @@ -1521,7 +1538,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); @@ -1531,17 +1548,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); } @@ -1695,7 +1715,7 @@ public void setExportContentService(IExportToolContentService exportContentService) { this.exportContentService = exportContentService; } - + public void setGradebookService(IGradebookService gradebookService) { this.gradebookService = gradebookService; } @@ -1713,14 +1733,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)); @@ -1770,10 +1791,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); @@ -1782,12 +1801,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)); @@ -1800,10 +1819,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); @@ -1815,19 +1834,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(); @@ -1849,8 +1868,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(); @@ -1871,8 +1890,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) { @@ -1887,20 +1907,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); } @@ -1950,21 +1973,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(); @@ -1977,11 +2004,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)); @@ -1990,23 +2018,21 @@ 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) content.getQaSessions()) { + if (!session.getQaQueUsers().isEmpty()) { + return true; + } + } + + return false; + } + + @Override public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentID) throws ToolException { if (toolSessionId == null) { @@ -1071,6 +1088,7 @@ /** * ToolSessionManager CONTRACT */ + @Override public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { throw new ToolException("not yet implemented"); @@ -1079,6 +1097,7 @@ /** * ToolSessionManager CONTRACT */ + @Override public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, ToolException { throw new ToolException("not yet implemented"); @@ -1120,7 +1139,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 +1149,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 +1171,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 +1242,7 @@ this.qaToolContentHandler = qaToolContentHandler; } + @Override public IAuditService getAuditService() { return auditService; } @@ -1244,6 +1266,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 +1362,7 @@ this.messageService = messageService; } + @Override public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } @@ -1393,7 +1417,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 -r37c1972aaf34449bc4d3741c87b49f666840ebcb -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/service/ResourceServiceImpl.java (.../ResourceServiceImpl.java) (revision 37c1972aaf34449bc4d3741c87b49f666840ebcb) +++ lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/service/ResourceServiceImpl.java (.../ResourceServiceImpl.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -208,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. @@ -221,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()); @@ -284,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()); } } @@ -401,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; } @@ -511,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. GroupSummary group = new GroupSummary(); @@ -523,7 +523,7 @@ items.addAll(resource.getResourceItems()); // add this session's resource items items.addAll(session.getResourceItems()); - + for (ResourceItem item : items) { ItemSummary itemSummary = new ItemSummary(item); // set viewNumber according visit log @@ -532,7 +532,7 @@ } group.getItems().add(itemSummary); } - + groupList.add(group); } @@ -555,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; @@ -576,8 +576,8 @@ 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); } @@ -615,7 +615,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); @@ -631,7 +631,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(); @@ -676,7 +676,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()); @@ -722,8 +722,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 @@ -748,8 +748,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()); @@ -765,7 +765,7 @@ throw new UploadResourceFileException(messageService.getMessage("error.msg.ims.application")); } } - + /** * Find out default.htm/html or index.htm/html in the given directory folder * @@ -779,8 +779,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(); @@ -791,7 +792,7 @@ return false; } }); - if (initFiles != null && initFiles.length > 0) { + if ((initFiles != null) && (initFiles.length > 0)) { return initFiles[0].getName(); } else { return null; @@ -802,20 +803,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 // ******************************************************************************* @@ -852,7 +853,7 @@ try { // register version filter class exportContentService.registerImportVersionFilterClass(ResourceImportContentVersionFilter.class); - + exportContentService.registerFileClassForImport(ResourceItem.class.getName(), "fileUuid", "fileVersionId", "fileName", "fileType", null, "initialItem"); @@ -935,12 +936,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); @@ -954,10 +955,22 @@ public boolean isContentEdited(Long toolContentId) { return getResourceByContentId(toolContentId).isDefineLater(); } - + @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public boolean isReadOnly(Long toolContentId) { + List sessions = resourceSessionDao.getByContentId(toolContentId); + for (ResourceSession session : sessions) { + if (!resourceUserDao.getBySessionID(session.getSessionId()).isEmpty()) { + return true; + } + } + + return false; + } + + @Override + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { Resource resource = resourceDao.getByContentId(toolContentId); if (removeSessionData) { List list = resourceSessionDao.getByContentId(toolContentId); @@ -973,13 +986,15 @@ @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; } @@ -1014,7 +1029,7 @@ if (entry != null) { resourceDao.removeObject(NotebookEntry.class, entry.getUid()); } - + resourceUserDao.removeObject(ResourceUser.class, user.getUid()); } } @@ -1055,13 +1070,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; } @@ -1079,7 +1095,7 @@ 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 @@ -1098,8 +1114,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); @@ -1155,7 +1171,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()) { @@ -1200,10 +1216,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); @@ -1218,7 +1232,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\'" @@ -1235,8 +1249,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) { @@ -1248,10 +1263,11 @@ toolContentObj.setReflectInstructions(description); } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getResourceOutputFactory().getSupportedDefinitionClasses(definitionType); } - + // ***************************************************************************** // set methods for Spring Bean // ***************************************************************************** @@ -1342,17 +1358,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(); @@ -1366,9 +1383,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); @@ -1380,41 +1398,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) selection.getLeaderselectionSessions()) { - /* if (session.getGroupLeader() != null && session.getGroupLeader().getUserId().equals(userId.longValue())) { session.setGroupLeader(null); leaderselectionSessionDAO.update(session); } - */ LeaderselectionUser user = leaderselectionUserDAO.getByUserIdAndSessionId(userId.longValue(), session.getSessionId()); @@ -259,8 +259,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 +287,41 @@ 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(); } - + + @Override + public boolean isReadOnly(Long toolContentId) { + Leaderselection selection = leaderselectionDAO.getByContentId(toolContentId); + for (LeaderselectionSession session : (Set) selection.getLeaderselectionSessions()) { + if (session.getGroupLeader() != null) { + return true; + } + } + + return false; + } + /* ********** 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 +331,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 +368,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 +380,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 +391,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 +407,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 +416,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 +487,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 +582,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 +613,5 @@ leaderselection.setDefineLater(false); saveOrUpdateLeaderselection(leaderselection); } - + } Index: lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/service/MindmapService.java =================================================================== diff -u -ra0bce7961a19548c58f5b0025160f124785f9951 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/service/MindmapService.java (.../MindmapService.java) (revision a0bce7961a19548c58f5b0025160f124785f9951) +++ lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/service/MindmapService.java (.../MindmapService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -132,13 +132,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; } @@ -157,7 +158,7 @@ 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 @@ -170,6 +171,7 @@ * @param toolSessionId * @return */ + @Override public int getNumNodes(Long learnerId, Long toolSessionId) { MindmapUser mindmapUser = getUserByUserIdAndSessionId(learnerId, toolSessionId); // MindmapSession mindmapSession = getSessionBySessionId(toolSessionId); @@ -180,6 +182,7 @@ /* * Methods from ToolContentManager Called on adding lesson. */ + @Override public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { if (MindmapService.logger.isDebugEnabled()) { @@ -239,8 +242,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); @@ -266,6 +269,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) { @@ -292,6 +296,7 @@ * @param mindmapUser * @return rootNodeModel */ + @Override public NodeModel getMindmapXMLFromDatabase(Long rootNodeId, Long mindmapId, NodeModel rootNodeModel, MindmapUser mindmapUser) { List mindmapNodes = getMindmapNodeByParentId(rootNodeId, mindmapId); @@ -331,6 +336,7 @@ return rootNodeModel; } + @Override public void getChildMindmapNodes(List branches, MindmapNode rootMindmapNode, MindmapUser mindmapUser, Mindmap mindmap, MindmapSession mindmapSession) { for (Iterator iterator = branches.iterator(); iterator.hasNext();) { @@ -361,6 +367,7 @@ } } + @Override public String getLanguageXML() { ArrayList languageCollection = new ArrayList(); languageCollection.add(new String("local.title")); @@ -380,7 +387,7 @@ return languageOutput; } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Mindmap mindmap = mindmapDAO.getByContentId(toolContentId); @@ -391,22 +398,24 @@ mindmapDAO.saveOrUpdate(mindmap); } - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + @Override + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { // TODO Auto-generated method stub } + @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; } @@ -448,8 +457,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); @@ -469,6 +478,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) { @@ -514,6 +524,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 { @@ -523,8 +534,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; @@ -570,6 +581,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); @@ -579,32 +591,55 @@ 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(); } + @Override + public boolean isReadOnly(Long toolContentId) { + Mindmap mindmap = mindmapDAO.getByContentId(toolContentId); + + for (MindmapSession session : (Set) mindmap.getMindmapSessions()) { + for (MindmapUser user : (Set) session.getMindmapUsers()) { + if (!mindmapNodeDAO.getMindmapNodesBySessionIdAndUserId(session.getSessionId(), user.getUserId()) + .isEmpty()) { + return true; + } + } + + } + return false; + } + /* 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)); @@ -616,6 +651,7 @@ return toolContentId; } + @Override public Mindmap getDefaultContent() { Long defaultContentID = getDefaultContentIdBySignature(MindmapConstants.TOOL_SIGNATURE); Mindmap defaultContent = getMindmapByContentId(defaultContentID); @@ -628,6 +664,7 @@ return defaultContent; } + @Override public Mindmap copyDefaultContent(Long newContentID) { if (newContentID == null) { @@ -644,6 +681,7 @@ return newContent; } + @Override public Mindmap getMindmapByContentId(Long toolContentID) { Mindmap mindmap = mindmapDAO.getByContentId(toolContentID); if (mindmap == null) { @@ -652,6 +690,7 @@ return mindmap; } + @Override public Mindmap getMindmapByUid(Long Uid) { Mindmap mindmap = mindmapDAO.getMindmapByUid(Uid); if (mindmap == null) { @@ -660,6 +699,7 @@ return mindmap; } + @Override public MindmapSession getSessionBySessionId(Long toolSessionId) { MindmapSession mindmapSession = mindmapSessionDAO.getBySessionId(toolSessionId); if (mindmapSession == null) { @@ -668,6 +708,7 @@ return mindmapSession; } + @Override public MindmapUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { return mindmapUserDAO.getByUserIdAndSessionId(userId, toolSessionId); } @@ -676,26 +717,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); @@ -715,15 +762,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); @@ -735,11 +783,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 @@ -824,6 +873,7 @@ this.mindmapOutputFactory = mindmapOutputFactory; } + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } @@ -836,62 +886,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; } @@ -904,42 +969,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(); @@ -966,7 +1040,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/dao/INoticeboardUserDAO.java =================================================================== diff -u -r4aae0391a4892385de3df761a655e0ab8b1c0183 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_nb/src/java/org/lamsfoundation/lams/tool/noticeboard/dao/INoticeboardUserDAO.java (.../INoticeboardUserDAO.java) (revision 4aae0391a4892385de3df761a655e0ab8b1c0183) +++ lams_tool_nb/src/java/org/lamsfoundation/lams/tool/noticeboard/dao/INoticeboardUserDAO.java (.../INoticeboardUserDAO.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -26,77 +26,73 @@ import java.util.List; -import org.lamsfoundation.lams.tool.noticeboard.NoticeboardUser; +import org.lamsfoundation.lams.dao.IBaseDAO; import org.lamsfoundation.lams.tool.noticeboard.NoticeboardSession; +import org.lamsfoundation.lams.tool.noticeboard.NoticeboardUser; /** * @author mtruong * - *

Interface for the NoticeboardSession DAO, defines methods needed to access/modify - * noticeboard users (learners of the noticeboard activity)

+ *

+ * Interface for the NoticeboardSession DAO, defines methods needed to access/modify noticeboard users (learners + * of the noticeboard activity) + *

*/ -public interface INoticeboardUserDAO { - - +public interface INoticeboardUserDAO extends IBaseDAO { + /** - *

Return the persistent instance of a NoticeboardUser - * with the given user id userId, - * returns null if not found.

- * - * @param userId The id of a NoticeboardUser - * @return the persistent instance of a NoticeboardUser or null if not found. - */ + *

+ * Return the persistent instance of a NoticeboardUser with the given user id userId, returns null if + * not found. + *

+ * + * @param userId + * The id of a NoticeboardUser + * @return the persistent instance of a NoticeboardUser or null if not found. + */ public NoticeboardUser getNbUser(Long userId, Long toolSessionId); - + /** - *

Return the persistent instance of a NoticeboardUser - * who has the user id userId and tool session id - * sessionId - * returns null if not found.

- * - * @param userId. The id of the learner - * @param sessionId. The tool session id to which this user belongs to. - * @return the persistent instance of a NoticeboardUser or null if not found. - */ - public NoticeboardUser getNbUserBySession(Long userId, Long sessionId); - - /** - *

Persist the given persistent instance of NoticeboardUser.

- * - * @param nbUser The instance of NoticeboardUser to persist. - */ - public void saveNbUser(NoticeboardUser nbUser); - - /** - *

Update the given persistent instance of NoticeboardUser.

+ *

+ * Return the persistent instance of a NoticeboardUser who has the user id userId and tool session id + * sessionId returns null if not found. + *

* - * @param nbUser The instance of NoticeboardUser to persist. + * @param userId. + * The id of the learner + * @param sessionId. + * The tool session id to which this user belongs to. + * @return the persistent instance of a NoticeboardUser or null if not found. */ - public void updateNbUser(NoticeboardUser nbUser); - + public NoticeboardUser getNbUserBySession(Long userId, Long sessionId); + /** - *

Delete the given instance of NoticeboardUser

+ *

+ * Persist the given persistent instance of NoticeboardUser. + *

* - * @param nbUser The instance of NoticeboardUser to delete. + * @param nbUser + * The instance of NoticeboardUser to persist. */ - public void removeNbUser(NoticeboardUser nbUser); - + public void saveNbUser(NoticeboardUser nbUser); + /** - *

Delete the given instance of NoticeboardUser with the - * given user id userId + *

+ * Update the given persistent instance of NoticeboardUser. + *

* - * @param userId The noticeboard user id. + * @param nbUser + * The instance of NoticeboardUser to persist. */ - public void removeNbUser(Long userId); - + public void updateNbUser(NoticeboardUser nbUser); + /** - * Returns the number of users that are in this particular - * session. + * Returns the number of users that are in this particular session. * * @param nbSession * @return the number of users that are in this session */ public int getNumberOfUsers(NoticeboardSession nbSession); - + public List getNbUsersBySession(Long sessionId); } \ No newline at end of file Index: lams_tool_nb/src/java/org/lamsfoundation/lams/tool/noticeboard/dao/hibernate/NoticeboardUserDAO.java =================================================================== diff -u -r5bc0c373e879c3c57bd5b6ab04c76c98a419848b -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_nb/src/java/org/lamsfoundation/lams/tool/noticeboard/dao/hibernate/NoticeboardUserDAO.java (.../NoticeboardUserDAO.java) (revision 5bc0c373e879c3c57bd5b6ab04c76c98a419848b) +++ lams_tool_nb/src/java/org/lamsfoundation/lams/tool/noticeboard/dao/hibernate/NoticeboardUserDAO.java (.../NoticeboardUserDAO.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -35,100 +35,74 @@ /** * @author mtruong - *

Hibernate implementation for database access to Noticeboard users (learners) for the noticeboard tool.

+ *

+ * Hibernate implementation for database access to Noticeboard users (learners) for the noticeboard tool. + *

*/ @Repository public class NoticeboardUserDAO extends LAMSBaseDAO implements INoticeboardUserDAO { - - private static final String FIND_NB_USER = "from " + NoticeboardUser.class.getName() + " as nb where nb.userId=?"; - - private static final String FIND_NB_USER_BY_SESSION = "from " + NoticeboardUser.class.getName() + " as nb where nb.userId=? and nb.nbSession.nbSessionId=?"; - + private static final String FIND_NB_USER_BY_SESSION = "from " + NoticeboardUser.class.getName() + + " as nb where nb.userId=? and nb.nbSession.nbSessionId=?"; + private static final String COUNT_USERS_IN_SESSION = "select nu.userId from NoticeboardUser nu where nu.nbSession= :nbSession"; - - - /** @see org.lamsfoundation.lams.tool.noticeboard.dao.INoticeboardUserDAO#getNbUserByID(java.lang.Long) */ - public NoticeboardUser getNbUser(Long userId, Long sessionId) - { - String query = "from NoticeboardUser user where user.userId=? and user.nbSession.nbSessionId=?"; - Object[] values = new Object[2]; - values[0] = userId; - values[1] = sessionId; - List users = doFind(query,values); - if(users!=null && users.size() == 0) - { - return null; - } - else - { - return (NoticeboardUser)users.get(0); - } - } - - /** @see org.lamsfoundation.lams.tool.noticeboard.dao.INoticeboardUserDAO#getNbUserBySession(java.lang.Long, java.lang.Long)*/ - public NoticeboardUser getNbUserBySession(Long userId, Long sessionId) - { - List usersReturned = getSessionFactory().getCurrentSession().createQuery(FIND_NB_USER_BY_SESSION) - .setLong(0,userId.longValue()) - .setLong(1, sessionId.longValue()) - .list(); - - if(usersReturned != null && usersReturned.size() > 0){ - NoticeboardUser nb = (NoticeboardUser) usersReturned.get(0); - return nb; - } - else - return null; + /** + * @see org.lamsfoundation.lams.tool.noticeboard.dao.INoticeboardUserDAO#getNbUserByID(java.lang.Long) + */ + public NoticeboardUser getNbUser(Long userId, Long sessionId) { + String query = "from NoticeboardUser user where user.userId=? and user.nbSession.nbSessionId=?"; + Object[] values = new Object[2]; + values[0] = userId; + values[1] = sessionId; + List users = doFind(query, values); + if (users != null && users.size() == 0) { + return null; + } else { + return (NoticeboardUser) users.get(0); } + } - /** @see org.lamsfoundation.lams.tool.noticeboard.dao.INoticeboardUserDAO#saveNbUser(org.lamsfoundation.lams.tool.noticeboard.NoticeboardUser) */ - public void saveNbUser(NoticeboardUser nbUser) - { - this.getSession().save(nbUser); + /** + * @see org.lamsfoundation.lams.tool.noticeboard.dao.INoticeboardUserDAO#getNbUserBySession(java.lang.Long, + * java.lang.Long) + */ + public NoticeboardUser getNbUserBySession(Long userId, Long sessionId) { + List usersReturned = getSessionFactory().getCurrentSession().createQuery(FIND_NB_USER_BY_SESSION) + .setLong(0, userId.longValue()).setLong(1, sessionId.longValue()).list(); + + if (usersReturned != null && usersReturned.size() > 0) { + NoticeboardUser nb = (NoticeboardUser) usersReturned.get(0); + return nb; + } else + return null; + } - - /** @see org.lamsfoundation.lams.tool.noticeboard.dao.INoticeboardUserDAO#updateNbUser(org.lamsfoundation.lams.tool.noticeboard.NoticeboardUser) */ - public void updateNbUser(NoticeboardUser nbUser) - { - this.getSession().update(nbUser); + + /** + * @see org.lamsfoundation.lams.tool.noticeboard.dao.INoticeboardUserDAO#saveNbUser(org.lamsfoundation.lams.tool.noticeboard.NoticeboardUser) + */ + public void saveNbUser(NoticeboardUser nbUser) { + this.getSession().save(nbUser); } - - /** @see org.lamsfoundation.lams.tool.noticeboard.dao.INoticeboardUserDAO#removeNbUser(java.lang.Long) */ - public void removeNbUser(Long userId) - { - if ( userId != null) { - //String query = "from org.lamsfoundation.lams.tool.noticeboard.NoticeboardContent as nb where nb.nbContentId=?"; - List list = getSessionFactory().getCurrentSession().createQuery(FIND_NB_USER) - .setLong(0,userId.longValue()) - .list(); - - if(list != null && list.size() > 0){ - NoticeboardUser nb = (NoticeboardUser) list.get(0); - getSessionFactory().getCurrentSession().setFlushMode(FlushMode.AUTO); - this.getSession().delete(nb); - this.getSession().flush(); - } - } - + + /** + * @see org.lamsfoundation.lams.tool.noticeboard.dao.INoticeboardUserDAO#updateNbUser(org.lamsfoundation.lams.tool.noticeboard.NoticeboardUser) + */ + public void updateNbUser(NoticeboardUser nbUser) { + this.getSession().update(nbUser); } - - /** @see org.lamsfoundation.lams.tool.noticeboard.dao.INoticeboardUserDAO#removeNbUser(org.lamsfoundation.lams.tool.noticeboard.NoticeboardUser) */ - public void removeNbUser(NoticeboardUser nbUser) - { - removeNbUser(nbUser.getUserId()); + + /** + * @see org.lamsfoundation.lams.tool.noticeboard.dao.INoticeboardUserDAO#getNumberOfUsers((org.lamsfoundation.lams. + * tool.noticeboard.NoticeboardSession) + */ + public int getNumberOfUsers(NoticeboardSession nbSession) { + return (doFindByNamedParam(COUNT_USERS_IN_SESSION, new String[] { "nbSession" }, new Object[] { nbSession })) + .size(); } - - /** @see org.lamsfoundation.lams.tool.noticeboard.dao.INoticeboardUserDAO#getNumberOfUsers((org.lamsfoundation.lams.tool.noticeboard.NoticeboardSession) */ - public int getNumberOfUsers(NoticeboardSession nbSession) - { - return (doFindByNamedParam(COUNT_USERS_IN_SESSION, - new String[] {"nbSession"}, - new Object[] {nbSession})).size(); - } - + public List getNbUsersBySession(Long sessionId) { - String query = "from NoticeboardUser user where user.nbSession.nbSessionId=?"; - return doFind(query,sessionId); + String query = "from NoticeboardUser user where user.nbSession.nbSessionId=?"; + return doFind(query, sessionId); } } \ No newline at end of file Index: lams_tool_nb/src/java/org/lamsfoundation/lams/tool/noticeboard/service/NoticeboardServicePOJO.java =================================================================== diff -u -ra0bce7961a19548c58f5b0025160f124785f9951 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_nb/src/java/org/lamsfoundation/lams/tool/noticeboard/service/NoticeboardServicePOJO.java (.../NoticeboardServicePOJO.java) (revision a0bce7961a19548c58f5b0025160f124785f9951) +++ lams_tool_nb/src/java/org/lamsfoundation/lams/tool/noticeboard/service/NoticeboardServicePOJO.java (.../NoticeboardServicePOJO.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -220,20 +220,13 @@ @Override public void removeUser(NoticeboardUser nbUser) { - NoticeboardSession session = nbUser.getNbSession(); - session.getNbUsers().remove(nbUser); - nbUserDAO.removeNbUser(nbUser); + nbUserDAO.delete(nbUser); } @Override public void removeUser(Long nbUserId, Long toolSessionId) { - if (nbUserId == null) { - throw new NbApplicationException("User ID is missing"); - } NoticeboardUser user = retrieveNoticeboardUser(nbUserId, toolSessionId); - NoticeboardSession session = user.getNbSession(); - session.getNbUsers().remove(user); - nbUserDAO.removeNbUser(nbUserId); + nbUserDAO.delete(user); } @Override @@ -306,7 +299,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,8 +329,8 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + 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) { @@ -350,14 +344,14 @@ @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; } @@ -370,7 +364,7 @@ nbContentDAO.delete(entry); } - nbUserDAO.removeNbUser(user.getUid()); + nbUserDAO.delete(user); } } } @@ -388,8 +382,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 +428,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); @@ -467,15 +461,27 @@ } @Override + public boolean isReadOnly(Long toolContentId) { + NoticeboardContent nbContent = nbContentDAO.findNbContentById(toolContentId); + for (NoticeboardSession session : nbContent.getNbSessions()) { + if (!session.getNbUsers().isEmpty()) { + return true; + } + } + + return false; + } + + @Override public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException { if ((toolSessionId == null) || (toolContentId == null)) { String error = "Failed to create tool session. The tool session id or tool content id is invalid"; throw new ToolException(error); } 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,18 +495,19 @@ } @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 = (Long) i.next(); + Long id = i.next(); getAndCheckSessionIDandObject(id); } @@ -522,7 +529,7 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return null; } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { //no actions required @@ -546,8 +553,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 +645,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 -ra0bce7961a19548c58f5b0025160f124785f9951 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/NotebookService.java (.../NotebookService.java) (revision a0bce7961a19548c58f5b0025160f124785f9951) +++ lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/NotebookService.java (.../NotebookService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -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,7 +162,7 @@ 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 @@ -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,25 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { } - + + @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 +241,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 +271,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 +306,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 +315,47 @@ } 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(); } - + + @Override + public boolean isReadOnly(Long toolContentId) { + Notebook notebook = notebookDAO.getByContentId(toolContentId); + for (NotebookSession session : (Set) notebook.getNotebookSessions()) { + if (!session.getNotebookUsers().isEmpty()) { + return true; + } + } + + return false; + } + /* ********** 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 +367,7 @@ return toolContentId; } + @Override public Notebook getDefaultContent() { Long defaultContentID = getDefaultContentIdBySignature(NotebookConstants.TOOL_SIGNATURE); Notebook defaultContent = getNotebookByContentId(defaultContentID); @@ -357,6 +383,7 @@ return defaultContent; } + @Override public Notebook copyDefaultContent(Long newContentID) { if (newContentID == null) { @@ -373,6 +400,7 @@ return newContent; } + @Override public Notebook getNotebookByContentId(Long toolContentID) { Notebook notebook = notebookDAO.getByContentId(toolContentID); if (notebook == null) { @@ -381,6 +409,7 @@ return notebook; } + @Override public NotebookSession getSessionBySessionId(Long toolSessionId) { NotebookSession notebookSession = notebookSessionDAO.getBySessionId(toolSessionId); if (notebookSession == null) { @@ -389,6 +418,7 @@ return notebookSession; } + @Override public NotebookUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { return notebookUserDAO.getByUserIdAndSessionId(userId, toolSessionId); } @@ -397,28 +427,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 +472,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 +493,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 +582,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 +602,7 @@ /** * {@inheritDoc} */ + @Override public String createConditionName(Collection existingConditions) { String uniqueNumber = null; do { @@ -579,6 +617,7 @@ return getNotebookOutputFactory().buildUserEntryConditionName(uniqueNumber); } + @Override public void releaseConditionsFromCache(Notebook notebook) { if (notebook.getConditions() != null) { for (NotebookCondition condition : notebook.getConditions()) { @@ -587,8 +626,9 @@ } } + @Override public void deleteCondition(NotebookCondition condition) { - if (condition != null && condition.getConditionId() != null) { + if ((condition != null) && (condition.getConditionId() != null)) { notebookDAO.delete(condition); } } @@ -597,22 +637,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 +673,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 -ra0bce7961a19548c58f5b0025160f124785f9951 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_pixlr/src/java/org/lamsfoundation/lams/tool/pixlr/service/PixlrService.java (.../PixlrService.java) (revision a0bce7961a19548c58f5b0025160f124785f9951) +++ lams_tool_pixlr/src/java/org/lamsfoundation/lams/tool/pixlr/service/PixlrService.java (.../PixlrService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -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 } /* ************ Methods from ToolContentManager ************************* */ - + @Override public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { @@ -267,14 +254,17 @@ pixlrDAO.saveOrUpdate(pixlr); } - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + @Override + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { // TODO Auto-generated method stub } + @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 +286,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 +307,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 +340,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 +386,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 +404,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 +413,40 @@ } 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(); } + @Override + public boolean isReadOnly(Long toolContentId) { + Pixlr pixlr = pixlrDAO.getByContentId(toolContentId); + for (PixlrSession session : pixlr.getPixlrSessions()) { + if (!session.getPixlrUsers().isEmpty()) { + return true; + } + } + + return false; + } + /* ********** 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 +456,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 +473,7 @@ return toolContentId; } + @Override public Pixlr getDefaultContent() { Long defaultContentID = getDefaultContentIdBySignature(PixlrConstants.TOOL_SIGNATURE); Pixlr defaultContent = getPixlrByContentId(defaultContentID); @@ -472,6 +485,7 @@ return defaultContent; } + @Override public Pixlr copyDefaultContent(Long newContentID) { if (newContentID == null) { @@ -488,6 +502,7 @@ return newContent; } + @Override public Pixlr getPixlrByContentId(Long toolContentID) { Pixlr pixlr = pixlrDAO.getByContentId(toolContentID); if (pixlr == null) { @@ -496,6 +511,7 @@ return pixlr; } + @Override public PixlrSession getSessionBySessionId(Long toolSessionId) { PixlrSession pixlrSession = pixlrSessionDAO.getBySessionId(toolSessionId); if (pixlrSession == null) { @@ -504,6 +520,7 @@ return pixlrSession; } + @Override public PixlrUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { return pixlrUserDAO.getByUserIdAndSessionId(userId, toolSessionId); } @@ -512,22 +529,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 +563,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 +584,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 +593,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 +609,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 +707,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 -r37c1972aaf34449bc4d3741c87b49f666840ebcb -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/SubmitFilesService.java (.../SubmitFilesService.java) (revision 37c1972aaf34449bc4d3741c87b49f666840ebcb) +++ lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/SubmitFilesService.java (.../SubmitFilesService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -148,11 +148,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 +164,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 +203,7 @@ submitFilesContentDAO.saveOrUpdate(toContent); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { SubmitFilesContent content = getSubmitFilesContent(toolContentId); @@ -215,7 +220,7 @@ if (submitFilesContent != null) { // if session data exist and removeSessionData=false, throw an exception List submissionData = submitFilesSessionDAO.getSubmitFilesSessionByContentID(toolContentId); - if (!(submissionData == null || submissionData.isEmpty()) && !removeSessionData) { + 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) { @@ -228,10 +233,12 @@ 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 +262,7 @@ } } + @Override public List getSessionsByContentID(Long toolContentID) { return submitFilesSessionDAO.getSubmitFilesSessionByContentID(toolContentID); } @@ -264,6 +272,7 @@ * * @throws ExportToolContentException */ + @Override public void exportToolContent(Long toolContentId, String toPath) throws ToolException, DataMissingException { SubmitFilesContent toolContentObj = submitFilesContentDAO.getContentByID(toolContentId); if (toolContentObj == null) { @@ -282,18 +291,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 +340,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,16 +349,30 @@ } 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 boolean isReadOnly(Long toolContentId) { + List sessions = submitFilesSessionDAO.getSubmitFilesSessionByContentID(toolContentId); + for (SubmitFilesSession session : sessions) { + if (!submitUserDAO.getUsersBySession(session.getSessionID()).isEmpty()) { + return true; + } + } + + return false; + } + + @Override public void saveOrUpdateContent(SubmitFilesContent submitFilesContent) { submitFilesContent.setUpdated(new Date()); submitFilesContentDAO.saveOrUpdate(submitFilesContent); @@ -401,24 +426,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 +456,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,7 +534,7 @@ 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 @@ -519,7 +544,7 @@ 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 +587,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 +614,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 +634,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 +646,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 +667,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 +678,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 +694,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 +719,7 @@ } + @Override public void removeMarkFile(Long reportID, Long markFileUUID, Long markFileVersionID) { SubmitFilesReport report = submitFilesReportDAO.getReportByID(reportID); if (report != null) { @@ -700,26 +731,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 +813,7 @@ return true; } + @Override public void finishSubmission(Long sessionID, Integer userID) { SubmitUser learner = submitUserDAO.getLearner(sessionID, userID); learner.setFinished(true); @@ -794,8 +829,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 +856,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 +873,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 +901,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 +920,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 +930,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 +950,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 +964,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 +989,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 +1013,7 @@ } + @Override public SubmitUser createContentUser(UserDTO userDto, Long contentId) { SubmitUser learner = submitUserDAO.getContentUser(contentId, userDto.getUserID()); if (learner != null) { @@ -986,6 +1032,7 @@ } + @Override public SubmitUser getContentUser(Long contentId, Integer userID) { return submitUserDAO.getContentUser(contentId, userID); } @@ -996,31 +1043,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 +1082,7 @@ /** * @param sbmtToolContentHandler - * The sbmtToolContentHandler to set. + * The sbmtToolContentHandler to set. */ public void setSbmtToolContentHandler(IToolContentHandler sbmtToolContentHandler) { this.sbmtToolContentHandler = sbmtToolContentHandler; @@ -1050,7 +1097,7 @@ /** * @param learnerDAO - * The learnerDAO to set. + * The learnerDAO to set. */ public void setSubmitUserDAO(ISubmitUserDAO learnerDAO) { submitUserDAO = learnerDAO; @@ -1100,6 +1147,7 @@ this.userManagementService = userManagementService; } + @Override public IEventNotificationService getEventNotificationService() { return eventNotificationService; } @@ -1108,6 +1156,7 @@ this.eventNotificationService = eventNotificationService; } + @Override public String getLocalisedMessage(String key, Object[] args) { return messageService.getMessage(key, args); } @@ -1120,6 +1169,7 @@ this.gradebookService = gradebookService; } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getSubmitFilesOutputFactory().getSupportedDefinitionClasses(definitionType); @@ -1132,14 +1182,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 +1200,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 +1216,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 -r8235ff2b4eb95000b9a16627df990faf66eeb5ac -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/service/ScratchieServiceImpl.java (.../ScratchieServiceImpl.java) (revision 8235ff2b4eb95000b9a16627df990faf66eeb5ac) +++ lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/service/ScratchieServiceImpl.java (.../ScratchieServiceImpl.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -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; @@ -90,9 +89,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 +204,7 @@ @Override public void releaseItemsFromCache(Scratchie scratchie) { - for (ScratchieItem item : (Set) scratchie.getScratchieItems()) { + for (ScratchieItem item : scratchie.getScratchieItems()) { scratchieItemDao.releaseItemFromCache(item); } } @@ -1770,6 +1767,18 @@ } @Override + public boolean isReadOnly(Long toolContentId) { + List sessions = scratchieSessionDao.getByContentId(toolContentId); + for (ScratchieSession session : sessions) { + if (!scratchieUserDao.getBySessionID(session.getSessionId()).isEmpty()) { + return true; + } + } + + return false; + } + + @Override public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, ToolException { Scratchie scratchie = scratchieDao.getByContentId(toolContentId); @@ -1784,9 +1793,11 @@ 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 +1812,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 +2045,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 -ra0bce7961a19548c58f5b0025160f124785f9951 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_scribe/src/java/org/lamsfoundation/lams/tool/scribe/service/ScribeService.java (.../ScribeService.java) (revision a0bce7961a19548c58f5b0025160f124785f9951) +++ lams_tool_scribe/src/java/org/lamsfoundation/lams/tool/scribe/service/ScribeService.java (.../ScribeService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -81,8 +81,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 +109,7 @@ } /* ************ Methods from ToolSessionManager ************* */ - + @Override public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException { if (ScribeService.logger.isDebugEnabled()) { @@ -134,13 +134,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,7 +160,7 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return null; } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { //no actions required @@ -191,7 +192,7 @@ Scribe toContent = Scribe.newInstance(fromContent, toContentId); scribeDAO.saveOrUpdate(toContent); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Scribe scribe = scribeDAO.getByContentId(toolContentId); @@ -203,26 +204,28 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { // TODO Auto-generated method stub } - + @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 +256,7 @@ } } } - + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { Scribe scribe = scribeDAO.getByContentId(toolContentId); @@ -287,12 +290,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 +314,40 @@ 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(); } - - + + @Override + public boolean isReadOnly(Long toolContentId) { + Scribe scribe = scribeDAO.getByContentId(toolContentId); + for (ScribeSession session : (Set) scribe.getScribeSessions()) { + if ((session.getAppointedScribe() != null) || !session.getScribeUsers().isEmpty()) { + return true; + + } + } + + return false; + } + /* ********** 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 -r37c1972aaf34449bc4d3741c87b49f666840ebcb -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_spreadsheet/src/java/org/lamsfoundation/lams/tool/spreadsheet/service/SpreadsheetServiceImpl.java (.../SpreadsheetServiceImpl.java) (revision 37c1972aaf34449bc4d3741c87b49f666840ebcb) +++ lams_tool_spreadsheet/src/java/org/lamsfoundation/lams/tool/spreadsheet/service/SpreadsheetServiceImpl.java (.../SpreadsheetServiceImpl.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -97,8 +97,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; @@ -510,7 +510,7 @@ try { // register version filter class exportContentService.registerImportVersionFilterClass(SpreadsheetImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, spreadsheetToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof Spreadsheet)) { @@ -571,7 +571,7 @@ public String getToolContentTitle(Long toolContentId) { return getSpreadsheetByContentId(toolContentId).getTitle(); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Spreadsheet spreadsheet = spreadsheetDao.getByContentId(toolContentId); @@ -585,10 +585,22 @@ public boolean isContentEdited(Long toolContentId) { return getSpreadsheetByContentId(toolContentId).isDefineLater(); } - + @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public boolean isReadOnly(Long toolContentId) { + List sessions = spreadsheetSessionDao.getByContentId(toolContentId); + for (SpreadsheetSession session : sessions) { + if (!spreadsheetUserDao.getBySessionID(session.getSessionId()).isEmpty()) { + return true; + } + } + + return false; + } + + @Override + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { Spreadsheet spreadsheet = spreadsheetDao.getByContentId(toolContentId); if (removeSessionData) { List list = spreadsheetSessionDao.getByContentId(toolContentId); @@ -614,16 +626,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()); } } @@ -664,13 +676,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; } @@ -688,7 +701,7 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return null; } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { //no actions required @@ -701,8 +714,8 @@ } /** 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 { Spreadsheet toolContentObj = getSpreadsheetByContentId(toolContentId); if (toolContentObj == null) { Index: lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/service/SurveyServiceImpl.java =================================================================== diff -u -r37c1972aaf34449bc4d3741c87b49f666840ebcb -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/service/SurveyServiceImpl.java (.../SurveyServiceImpl.java) (revision 37c1972aaf34449bc4d3741c87b49f666840ebcb) +++ lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/service/SurveyServiceImpl.java (.../SurveyServiceImpl.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -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; @@ -277,7 +276,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 +357,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 +377,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 +390,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,7 +463,8 @@ } @Override - public SortedMap>> exportClassPortfolio(Long toolContentID) { + public SortedMap>> exportClassPortfolio( + Long toolContentID) { //construct sessionToUsers Map Map> sessionToUsersMap = new HashMap>(); @@ -493,19 +493,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 +587,7 @@ return summary; } + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } @@ -692,15 +695,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,8 +787,20 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public boolean isReadOnly(Long toolContentId) { + List sessions = surveySessionDao.getByContentId(toolContentId); + for (SurveySession session : sessions) { + if (!surveyUserDao.getBySessionID(session.getSessionId()).isEmpty()) { + return true; + } + } + + return false; + } + + @Override + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { Survey survey = surveyDao.getByContentId(toolContentId); if (removeSessionData) { List list = surveySessionDao.getByContentId(toolContentId); @@ -800,8 +815,9 @@ @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 +864,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,7 +889,7 @@ 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 @@ -913,6 +930,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 +941,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 +989,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 +1003,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 +1017,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 +1030,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 +1136,7 @@ public void setSurveyOutputFactory(SurveyOutputFactory surveyOutputFactory) { this.surveyOutputFactory = surveyOutputFactory; } - + // ****************** REST methods ************************* /** @@ -1154,7 +1171,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 -r37c1972aaf34449bc4d3741c87b49f666840ebcb -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_task/src/java/org/lamsfoundation/lams/tool/taskList/service/TaskListServiceImpl.java (.../TaskListServiceImpl.java) (revision 37c1972aaf34449bc4d3741c87b49f666840ebcb) +++ lams_tool_task/src/java/org/lamsfoundation/lams/tool/taskList/service/TaskListServiceImpl.java (.../TaskListServiceImpl.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -92,8 +92,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 +147,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 +321,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 +372,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 +556,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 +567,7 @@ public void updateEntry(NotebookEntry notebookEntry) { coreNotebookService.updateEntry(notebookEntry); } - + @Override public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); @@ -659,6 +659,7 @@ this.coreNotebookService = coreNotebookService; } + @Override public MessageService getMessageService() { return messageService; } @@ -703,7 +704,7 @@ try { // register version filter class exportContentService.registerImportVersionFilterClass(TaskListImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, taskListToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof TaskList)) { @@ -747,17 +748,30 @@ } 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 boolean isReadOnly(Long toolContentId) { + List sessions = taskListSessionDao.getByContentId(toolContentId); + for (TaskListSession session : sessions) { + if (!taskListUserDao.getBySessionID(session.getSessionId()).isEmpty()) { + return true; + } + } + + return false; + } + + @Override public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { if (toContentId == null) { throw new ToolException("Failed to create the SharedTaskListFiles tool seession"); @@ -788,7 +802,7 @@ } } } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { TaskList taskList = taskListDao.getByContentId(toolContentId); @@ -799,8 +813,8 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { TaskList taskList = taskListDao.getByContentId(toolContentId); if (removeSessionData) { List list = taskListSessionDao.getByContentId(toolContentId); @@ -816,20 +830,22 @@ @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 +927,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,10 +954,11 @@ * @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 @@ -955,8 +973,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 +1018,7 @@ * * @param contentId * @param sessionId - * sessionId which defines Group + * sessionId which defines Group * @return */ private List getItemListForGroup(Long contentId, Long sessionId) { @@ -1051,7 +1069,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 +1090,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 -ra0bce7961a19548c58f5b0025160f124785f9951 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_videorecorder/src/java/org/lamsfoundation/lams/tool/videoRecorder/service/VideoRecorderService.java (.../VideoRecorderService.java) (revision a0bce7961a19548c58f5b0025160f124785f9951) +++ lams_tool_videorecorder/src/java/org/lamsfoundation/lams/tool/videoRecorder/service/VideoRecorderService.java (.../VideoRecorderService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -24,30 +24,15 @@ 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; @@ -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,7 +168,7 @@ 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 @@ -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); @@ -241,22 +225,23 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { // TODO Auto-generated method stub } - + @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 +252,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 +270,7 @@ } } } - + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { VideoRecorder videoRecorder = videoRecorderDAO.getByContentId(toolContentId); @@ -302,7 +287,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 +312,7 @@ try { // register version filter class exportContentService.registerImportVersionFilterClass(VideoRecorderImportContentVersionFilter.class); - + Object toolPOJO = exportContentService.importToolContent(toolContentPath, videoRecorderToolContentHandler, fromVersion, toVersion); if (!(toolPOJO instanceof VideoRecorder)) { @@ -364,17 +349,31 @@ } 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(); } - + + @Override + public boolean isReadOnly(Long toolContentId) { + VideoRecorder videoRecorder = videoRecorderDAO.getByContentId(toolContentId); + for (VideoRecorderSession session : (Set) videoRecorder.getVideoRecorderSessions()) { + if (!videoRecorderCommentDAO.getCommentsByToolSessionId(session.getSessionId()).isEmpty() + || !videoRecorderRatingDAO.getRatingsByToolSessionId(session.getSessionId()).isEmpty() + || !videoRecorderRecordingDAO.getByToolSessionId(session.getSessionId()).isEmpty()) { + return true; + } + } + + return false; + } + /* ********** IVideoRecorderService Methods ********************************* */ @Override @@ -449,8 +448,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 +463,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 +523,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 +539,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 +581,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 +599,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 +721,7 @@ this.videoRecorderOutputFactory = videoRecorderOutputFactory; } + @Override public void releaseConditionsFromCache(VideoRecorder videoRecorder) { if (videoRecorder.getConditions() != null) { for (VideoRecorderCondition condition : videoRecorder.getConditions()) { @@ -709,31 +730,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 +842,7 @@ return languageOutput; } + @Override public String getLanguageXMLForFCK() { ArrayList languageCollection = new ArrayList(); languageCollection.add(new String("button.ok")); @@ -863,10 +891,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/src/java/org/lamsfoundation/lams/tool/vote/service/VoteServicePOJO.java =================================================================== diff -u -r373b83109d4d8b8c5316aadc1e1e4972fde5f788 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/service/VoteServicePOJO.java (.../VoteServicePOJO.java) (revision 373b83109d4d8b8c5316aadc1e1e4972fde5f788) +++ lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/service/VoteServicePOJO.java (.../VoteServicePOJO.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -146,7 +146,7 @@ @Override public VoteQueUsr checkLeaderSelectToolForSessionLeader(VoteQueUsr user, Long toolSessionId) { - if (user == null || toolSessionId == null) { + if ((user == null) || (toolSessionId == null)) { return null; } @@ -163,7 +163,7 @@ // create new user in a DB if (leader == null) { - logger.debug("creating new user with userId: " + leaderUserId); + VoteServicePOJO.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(); @@ -258,7 +258,8 @@ String noHTMLNomination = VoteUtils.stripHTML(question.getQuestion()); mapStandardNominationsContent.put(mapIndex, noHTMLNomination); - int votesCount = voteUsrAttemptDAO.getStandardAttemptsForQuestionContentAndSessionUid(question.getUid(), toolSessionUid); + int votesCount = voteUsrAttemptDAO.getStandardAttemptsForQuestionContentAndSessionUid(question.getUid(), + toolSessionUid); totalStandardVotesCount += votesCount; mapStandardUserCount.put(mapIndex, new Long(votesCount)); @@ -292,9 +293,9 @@ voteGeneralLearnerFlowDTO.setMapStandardUserCount(mapStandardUserCount); voteGeneralLearnerFlowDTO.setMapStandardToolSessionUid(mapStandardToolSessionUid); voteGeneralLearnerFlowDTO.setMapStandardQuestionUid(mapStandardQuestionUid); - request.setAttribute(VOTE_GENERAL_LEARNER_FLOW_DTO, voteGeneralLearnerFlowDTO); + request.setAttribute(VoteAppConstants.VOTE_GENERAL_LEARNER_FLOW_DTO, voteGeneralLearnerFlowDTO); - request.setAttribute(LIST_USER_ENTRIES_CONTENT, userEntries); + request.setAttribute(VoteAppConstants.LIST_USER_ENTRIES_CONTENT, userEntries); // return value is only used in VoteChartGeneratorAction return voteGeneralLearnerFlowDTO; @@ -396,8 +397,8 @@ Long mapIndex = 1L; for (VoteQueContent question : (Set) 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 +410,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 +424,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 +488,7 @@ List monitoredAnswersDTOs = new LinkedList(); for (String userEntry : userEntries) { - if (userEntry == null || userEntry.length() == 0) { + if ((userEntry == null) || (userEntry.length() == 0)) { continue; } @@ -575,8 +576,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 +598,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 +619,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 +664,7 @@ public void saveOrUpdateVoteQueContent(VoteQueContent voteQueContent) { voteQueContentDAO.saveOrUpdateQuestion(voteQueContent); } - + @Override public VoteContent createQuestions(List questionDTOs, VoteContent voteContent) { @@ -694,16 +701,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 +732,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 +745,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 +764,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 +775,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 +800,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 +815,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 +836,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 +848,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 +864,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 +878,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 +888,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,7 +954,7 @@ public List getAttemptsForUser(final Long userUid) { return voteUsrAttemptDAO.getAttemptsForUser(userUid); } - + @Override public void createAttempt(VoteQueUsr voteQueUsr, Map mapGeneralCheckedOptionsContent, String userEntry, VoteSession voteSession, Long voteContentUid) { @@ -959,8 +966,8 @@ 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 +980,7 @@ } } - + private void createAttempt(VoteQueContent question, VoteQueUsr user, Date attempTime, String timeZone, String userEntry, VoteSession session) { @@ -1019,24 +1026,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 +1071,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 +1086,7 @@ boolean studentActivityOccurredGlobal = studentActivityOccurredGlobal(voteContent); int userEnteredVotesCount = getUserEnteredVotesCountForContent(voteContent.getUid()); - if (studentActivityOccurredGlobal == true || userEnteredVotesCount > 0) { + if ((studentActivityOccurredGlobal == true) || (userEnteredVotesCount > 0)) { return true; } @@ -1182,8 +1193,8 @@ } @Override - public void removeToolContent(Long toolContentID, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentID, boolean removeSessionData) + throws SessionDataExistsException, ToolException { if (toolContentID == null) { VoteServicePOJO.logger.error("toolContentID is null"); @@ -1224,13 +1235,15 @@ @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 +1297,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 +1311,7 @@ throw new ToolException(e); } } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { VoteContent voteContent = getVoteContent(toolContentId); @@ -1403,13 +1416,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 +1440,7 @@ contentId = toolService.getToolDefaultContentIdBySignature(toolSignature); return contentId; } - + @Override public List getToolSessionsForContent(VoteContent vote) { List listToolSessionIds = voteSessionDAO.getSessionsFromContent(vote); @@ -1460,6 +1474,18 @@ } @Override + public boolean isReadOnly(Long toolContentId) { + VoteContent voteContent = voteContentDAO.getVoteContentByContentId(toolContentId); + for (VoteSession session : (Set) voteContent.getVoteSessions()) { + if (!session.getVoteQueUsers().isEmpty()) { + return true; + } + } + + return false; + } + + @Override public SortedMap getToolOutput(List names, Long toolSessionId, Long learnerId) { return voteOutputFactory.getToolOutput(names, this, toolSessionId, learnerId); } @@ -1468,7 +1494,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 +1521,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 +1540,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 +1572,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 +1596,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 +1612,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 +1896,12 @@ this.messageService = messageService; } + @Override public void removeQuestionsFromCache(VoteContent voteContent) { voteContentDAO.removeQuestionsFromCache(voteContent); } + @Override public void removeVoteContentFromCache(VoteContent voteContent) { voteContentDAO.removeVoteContentFromCache(voteContent); } @@ -1882,12 +1910,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 +1926,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 +1971,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_wiki/src/java/org/lamsfoundation/lams/tool/wiki/service/WikiService.java =================================================================== diff -u -ra0bce7961a19548c58f5b0025160f124785f9951 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_wiki/src/java/org/lamsfoundation/lams/tool/wiki/service/WikiService.java (.../WikiService.java) (revision a0bce7961a19548c58f5b0025160f124785f9951) +++ lams_tool_wiki/src/java/org/lamsfoundation/lams/tool/wiki/service/WikiService.java (.../WikiService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -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 : (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,7 +221,7 @@ } return wikiOutputFactory.getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public void forceCompleteUser(Long toolSessionId, User user) { //no actions required @@ -235,17 +237,29 @@ } 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(); } - + + @Override + public boolean isReadOnly(Long toolContentId) { + Wiki wiki = wikiDAO.getByContentId(toolContentId); + for (WikiSession session : wiki.getWikiSessions()) { + if (!session.getWikiPages().isEmpty()) { + return true; + } + } + + return false; + } + /* ************ Methods from ToolContentManager ************************* */ @Override @@ -273,7 +287,7 @@ insertUnsavedWikiContent(toContent); } - + @Override public void resetDefineLater(Long toolContentId) throws DataMissingException, ToolException { Wiki wiki = wikiDAO.getByContentId(toolContentId); @@ -285,30 +299,32 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { // TODO Auto-generated method stub } - + @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 +341,7 @@ } } } - + @Override public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { Wiki wiki = wikiDAO.getByContentId(toolContentId); @@ -372,12 +388,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 +423,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 +433,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 +448,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 +458,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 +473,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 +491,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 +532,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 +549,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 +566,7 @@ * * @see org.lamsfoundation.lams.tool.wiki.service.IWikiService#copyDefaultContent(Long) */ + @Override public Wiki copyDefaultContent(Long newContentID) { if (newContentID == null) { @@ -596,6 +619,7 @@ return wiki; } + @Override public Wiki getWikiByContentId(Long toolContentID) { Wiki wiki = wikiDAO.getByContentId(toolContentID); if (wiki == null) { @@ -604,6 +628,7 @@ return wiki; } + @Override public WikiSession getSessionBySessionId(Long toolSessionId) { WikiSession wikiSession = wikiSessionDAO.getBySessionId(toolSessionId); if (wikiSession == null) { @@ -612,6 +637,7 @@ return wikiSession; } + @Override public WikiUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { return wikiUserDAO.getByUserIdAndSessionId(userId, toolSessionId); } @@ -620,6 +646,7 @@ return wikiUserDAO.getByLoginNameAndSessionId(loginName, toolSessionId); } + @Override public WikiUser getUserByUID(Long uid) { return wikiUserDAO.getByUID(uid); } @@ -630,6 +657,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 +695,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 +732,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 +827,7 @@ * @param toolSessionId * @return */ + @Override public int getEditsNum(Long learnerId, Long toolSessionId) { WikiUser wikiUser = getUserByUserIdAndSessionId(learnerId, toolSessionId); @@ -793,7 +836,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 +851,7 @@ * @param toolSessionId * @return */ + @Override public int getAddsNum(Long learnerId, Long toolSessionId) { WikiUser wikiUser = getUserByUserIdAndSessionId(learnerId, toolSessionId); @@ -816,7 +860,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 +874,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 +902,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 +1012,7 @@ this.wikiOutputFactory = wikiOutputFactory; } + @Override public IEventNotificationService getEventNotificationService() { return eventNotificationService; } @@ -982,10 +1029,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 +1047,11 @@ this.lessonService = lessonService; } + @Override public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getWikiOutputFactory().getSupportedDefinitionClasses(definitionType); } - + /* ****************** REST methods **************************************************************************/ /** @@ -1071,9 +1121,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 -ra0bce7961a19548c58f5b0025160f124785f9951 -r0aae4208886026f429f05b458b79c14f8d7030d4 --- lams_tool_wookie/src/java/org/lamsfoundation/lams/tool/wookie/service/WookieService.java (.../WookieService.java) (revision a0bce7961a19548c58f5b0025160f124785f9951) +++ lams_tool_wookie/src/java/org/lamsfoundation/lams/tool/wookie/service/WookieService.java (.../WookieService.java) (revision 0aae4208886026f429f05b458b79c14f8d7030d4) @@ -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; @@ -73,239 +70,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 +281,21 @@ } @Override - public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, - ToolException { + public void removeToolContent(Long toolContentId, boolean removeSessionData) + throws SessionDataExistsException, ToolException { } @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 +313,425 @@ } } - - @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 + public boolean isReadOnly(Long toolContentId) { + Wookie wookie = getWookieByContentId(toolContentId); - /** - * @param notebookEntry - */ - public void updateEntry(NotebookEntry notebookEntry) { - coreNotebookService.updateEntry(notebookEntry); - } - - 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); + for (WookieSession session : wookie.getWookieSessions()) { + for (WookieUser user : session.getWookieUsers()) { + if (user.isFinishedActivity()) { + return true; } - return toolContentId; + } } - 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; - } + return false; + } - public Wookie copyDefaultContent(Long newContentID) { + @Override + @SuppressWarnings("unchecked") + public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { + return getWookieOutputFactory().getSupportedDefinitionClasses(definitionType); + } - if (newContentID == null) { - String error = "Cannot copy the Wookie tools default content: + " - + "newContentID is null"; - WookieService.logger.error(error); - throw new WookieException(error); - } + /* ********** IWookieService Methods ********************************* */ - 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 createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry) { + return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); + } - 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 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 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; - } + /** + * @param notebookEntry + */ + @Override + public void updateEntry(NotebookEntry notebookEntry) { + coreNotebookService.updateEntry(notebookEntry); + } - public WookieUser getUserByUserIdAndSessionId(Long userId, - Long toolSessionId) { - return wookieUserDAO.getByUserIdAndSessionId(userId, toolSessionId); + @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 WookieUser getUserByLoginNameAndSessionId(String loginName, - Long toolSessionId) { - return wookieUserDAO.getByLoginNameAndSessionId(loginName, - toolSessionId); + @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 WookieUser getUserByUID(Long uid) { - return wookieUserDAO.getByUID(uid); - } + @Override + public Wookie copyDefaultContent(Long newContentID) { - public void saveOrUpdateWookie(Wookie wookie) { - wookieDAO.saveOrUpdate(wookie); + if (newContentID == null) { + String error = "Cannot copy the Wookie tools default content: + " + "newContentID is null"; + WookieService.logger.error(error); + throw new WookieException(error); } - public void saveOrUpdateWookieSession(WookieSession wookieSession) { - wookieSessionDAO.saveOrUpdate(wookieSession); - } + Wookie defaultContent = getDefaultContent(); + // create new wookie using the newContentID + Wookie newContent = new Wookie(); + newContent = Wookie.newInstance(defaultContent, newContentID); + wookieDAO.saveOrUpdate(newContent); + return newContent; + } - public void saveOrUpdateWookieUser(WookieUser wookieUser) { - wookieUserDAO.saveOrUpdate(wookieUser); + @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 WookieUser createWookieUser(UserDTO user, WookieSession wookieSession) { - WookieUser wookieUser = new WookieUser(user, wookieSession); - saveOrUpdateWookieUser(wookieUser); - return wookieUser; + @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 WookieConfigItem getConfigItem(String key) { - return wookieConfigItemDAO.getConfigItemByKey(key); - } + @Override + public WookieUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { + return wookieUserDAO.getByUserIdAndSessionId(userId, toolSessionId); + } - public void saveOrUpdateWookieConfigItem(WookieConfigItem item) { - wookieConfigItemDAO.saveOrUpdate(item); - } + public WookieUser getUserByLoginNameAndSessionId(String loginName, Long toolSessionId) { + return wookieUserDAO.getByLoginNameAndSessionId(loginName, toolSessionId); + } - public String getWookieURL() { - String url = null; - WookieConfigItem urlItem = wookieConfigItemDAO - .getConfigItemByKey(WookieConfigItem.KEY_WOOKIE_URL); - if (urlItem != null) { - url = urlItem.getConfigValue(); - } - return url; - } + @Override + public WookieUser getUserByUID(Long uid) { + return wookieUserDAO.getByUID(uid); + } - public String getWookieAPIKey() { - String url = null; - WookieConfigItem apiItem = wookieConfigItemDAO - .getConfigItemByKey(WookieConfigItem.KEY_API); - if (apiItem != null) { - url = apiItem.getConfigValue(); - } - return url; + @Override + public void saveOrUpdateWookie(Wookie wookie) { + wookieDAO.saveOrUpdate(wookie); + } + + @Override + public void saveOrUpdateWookieSession(WookieSession wookieSession) { + wookieSessionDAO.saveOrUpdate(wookieSession); + } + + @Override + public void saveOrUpdateWookieUser(WookieUser wookieUser) { + wookieUserDAO.saveOrUpdate(wookieUser); + } + + @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; + } + }