Index: lams_tool_notebook/build.properties =================================================================== diff -u -rf7c130109254ea187c148bdd7270455130c2f8a1 -re64f3e306f3139c78e8917240c33ea232e75e848 --- lams_tool_notebook/build.properties (.../build.properties) (revision f7c130109254ea187c148bdd7270455130c2f8a1) +++ lams_tool_notebook/build.properties (.../build.properties) (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -3,7 +3,7 @@ signature=lantbk11 #project version -tool.version=20080229 +tool.version=20080929 package=org/lamsfoundation/lams/tool/notebook package.name=org.lamsfoundation.lams.tool.notebook Index: lams_tool_notebook/conf/hibernate/mappings/org/lamsfoundation/lams/tool/notebook/model/Notebook.hbm.xml =================================================================== diff -u -r91ab70504f55283e714dfb30794c656b33feeac7 -re64f3e306f3139c78e8917240c33ea232e75e848 --- lams_tool_notebook/conf/hibernate/mappings/org/lamsfoundation/lams/tool/notebook/model/Notebook.hbm.xml (.../Notebook.hbm.xml) (revision 91ab70504f55283e714dfb30794c656b33feeac7) +++ lams_tool_notebook/conf/hibernate/mappings/org/lamsfoundation/lams/tool/notebook/model/Notebook.hbm.xml (.../Notebook.hbm.xml) (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -178,6 +178,24 @@ + + + + + + + + + + + + + org.lamsfoundation.lams.tool.notebook.ApplicationResources + + + + org/lamsfoundation/lams/learningdesign/BranchCondition.hbm.xml org/lamsfoundation/lams/tool/notebook/model/Notebook.hbm.xml org/lamsfoundation/lams/tool/notebook/model/NotebookSession.hbm.xml org/lamsfoundation/lams/tool/notebook/model/NotebookUser.hbm.xml org/lamsfoundation/lams/tool/notebook/model/NotebookAttachment.hbm.xml + org/lamsfoundation/lams/tool/notebook/model/NotebookCondition.hbm.xml + + + @@ -39,6 +51,7 @@ + Index: lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/INotebookService.java =================================================================== diff -u -r9e446244a7245a4e8893e4673a801c56e4a35334 -re64f3e306f3139c78e8917240c33ea232e75e848 --- lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/INotebookService.java (.../INotebookService.java) (revision 9e446244a7245a4e8893e4673a801c56e4a35334) +++ lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/INotebookService.java (.../INotebookService.java) (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -24,10 +24,13 @@ package org.lamsfoundation.lams.tool.notebook.service; +import java.util.Collection; + import org.apache.struts.upload.FormFile; import org.lamsfoundation.lams.notebook.model.NotebookEntry; import org.lamsfoundation.lams.tool.notebook.model.Notebook; import org.lamsfoundation.lams.tool.notebook.model.NotebookAttachment; +import org.lamsfoundation.lams.tool.notebook.model.NotebookCondition; import org.lamsfoundation.lams.tool.notebook.model.NotebookSession; import org.lamsfoundation.lams.tool.notebook.model.NotebookUser; import org.lamsfoundation.lams.tool.notebook.util.NotebookException; @@ -37,130 +40,128 @@ * Defines the services available to the web layer from the Notebook Service */ public interface INotebookService { - /** - * Makes a copy of the default content and assigns it a newContentID - * - * @params newContentID - * @return - */ - public Notebook copyDefaultContent(Long newContentID); + /** + * Makes a copy of the default content and assigns it a newContentID + * + * @params newContentID + * @return + */ + public Notebook copyDefaultContent(Long newContentID); - /** - * Returns an instance of the Notebook tools default content. - * - * @return - */ - public Notebook getDefaultContent(); + /** + * Returns an instance of the Notebook tools default content. + * + * @return + */ + public Notebook getDefaultContent(); - /** - * @param toolSignature - * @return - */ - public Long getDefaultContentIdBySignature(String toolSignature); + /** + * @param toolSignature + * @return + */ + public Long getDefaultContentIdBySignature(String toolSignature); - /** - * @param toolContentID - * @return - */ - public Notebook getNotebookByContentId(Long toolContentID); + /** + * @param toolContentID + * @return + */ + public Notebook getNotebookByContentId(Long toolContentID); - /** - * @param toolContentId - * @param file - * @param type - * @return - */ - public NotebookAttachment uploadFileToContent(Long toolContentId, - FormFile file, String type); + /** + * @param toolContentId + * @param file + * @param type + * @return + */ + public NotebookAttachment uploadFileToContent(Long toolContentId, FormFile file, String type); - /** - * @param uuid - * @param versionID - */ - public void deleteFromRepository(Long uuid, Long versionID) - throws NotebookException; + /** + * @param uuid + * @param versionID + */ + public void deleteFromRepository(Long uuid, Long versionID) throws NotebookException; - /** - * @param contentID - * @param uuid - * @param versionID - * @param type - */ - public void deleteInstructionFile(Long contentID, Long uuid, - Long versionID, String type); + /** + * @param contentID + * @param uuid + * @param versionID + * @param type + */ + public void deleteInstructionFile(Long contentID, Long uuid, Long versionID, String type); - /** - * @param notebook - */ - public void saveOrUpdateNotebook(Notebook notebook); + /** + * @param notebook + */ + public void saveOrUpdateNotebook(Notebook notebook); - /** - * @param toolSessionId - * @return - */ - public NotebookSession getSessionBySessionId(Long toolSessionId); + /** + * @param toolSessionId + * @return + */ + public NotebookSession getSessionBySessionId(Long toolSessionId); - /** - * @param notebookSession - */ - public void saveOrUpdateNotebookSession(NotebookSession notebookSession); + /** + * @param notebookSession + */ + public void saveOrUpdateNotebookSession(NotebookSession notebookSession); - /** - * - * @param userId - * @param toolSessionId - * @return - */ - public NotebookUser getUserByUserIdAndSessionId(Long userId, - Long toolSessionId); + /** + * + * @param userId + * @param toolSessionId + * @return + */ + public NotebookUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId); - /** - * - * @param uid - * @return - */ - public NotebookUser getUserByUID(Long uid); + /** + * + * @param uid + * @return + */ + public NotebookUser getUserByUID(Long uid); - /** - * - * @param notebookUser - */ - public void saveOrUpdateNotebookUser(NotebookUser notebookUser); + /** + * + * @param notebookUser + */ + public void saveOrUpdateNotebookUser(NotebookUser notebookUser); - /** - * - * @param user - * @param notebookSession - * @return - */ - public NotebookUser createNotebookUser(UserDTO user, - NotebookSession notebookSession); - - /** - * - * @param id - * @param idType - * @param signature - * @param userID - * @param title - * @param entry - * @return - */ - Long createNotebookEntry(Long id, Integer idType, String signature, - Integer userID, String entry); - - /** - * - * @param uid - * @return - */ - NotebookEntry getEntry(Long uid); - - /** - * - * @param uid - * @param title - * @param entry - */ - void updateEntry(Long uid, String entry); + /** + * + * @param user + * @param notebookSession + * @return + */ + public NotebookUser createNotebookUser(UserDTO user, NotebookSession notebookSession); + + /** + * + * @param id + * @param idType + * @param signature + * @param userID + * @param title + * @param entry + * @return + */ + Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry); + + /** + * + * @param uid + * @return + */ + NotebookEntry getEntry(Long uid); + + /** + * + * @param uid + * @param title + * @param entry + */ + void updateEntry(Long uid, String entry); + + String createConditionName(Collection existingConditions); + + void releaseConditionsFromCache(Notebook notebook); } \ No newline at end of file Index: lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/NotebookOutputFactory.java =================================================================== diff -u --- lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/NotebookOutputFactory.java (revision 0) +++ lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/NotebookOutputFactory.java (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -0,0 +1,156 @@ +/**************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * License Information: http://lamsfoundation.org/licensing/lams/2.0/ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2.0 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA + * + * http://www.gnu.org/licenses/gpl.txt + * **************************************************************** + */ + +/* $Id$ */ +package org.lamsfoundation.lams.tool.notebook.service; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.lamsfoundation.lams.learningdesign.BranchCondition; +import org.lamsfoundation.lams.notebook.model.NotebookEntry; +import org.lamsfoundation.lams.tool.OutputFactory; +import org.lamsfoundation.lams.tool.ToolOutput; +import org.lamsfoundation.lams.tool.ToolOutputDefinition; +import org.lamsfoundation.lams.tool.exception.ToolException; +import org.lamsfoundation.lams.tool.notebook.model.Notebook; +import org.lamsfoundation.lams.tool.notebook.model.NotebookCondition; +import org.lamsfoundation.lams.tool.notebook.model.NotebookUser; +import org.lamsfoundation.lams.tool.notebook.util.NotebookConstants; + +/** + * Output factory for Notebook tool. Currently it provides only one type of output - the entry that user provided. + * + * @author Marcin Cieslak + */ +public class NotebookOutputFactory extends OutputFactory { + + /** + * {@inheritDoc} + */ + @Override + public SortedMap getToolOutputDefinitions(Object toolContentObject) + throws ToolException { + SortedMap definitionMap = new TreeMap(); + if (toolContentObject != null) { + ToolOutputDefinition notebookEntryDefinition = buildStringOutputDefinition(NotebookConstants.TEXT_SEARCH_DEFINITION_NAME); + Notebook notebook = (Notebook) toolContentObject; + // adding all existing conditions + notebookEntryDefinition.setDefaultConditions(new ArrayList(notebook.getConditions())); + // if no conditions were created in the tool instance, a default condition is added; the condition is + // persisted in NotebookService. + if (notebookEntryDefinition.getDefaultConditions().isEmpty()) { + String name = buildConditionName(NotebookConstants.TEXT_SEARCH_DEFINITION_NAME, notebook + .getToolContentId().toString()); + // Default condition checks if the text contains word "LAMS" + NotebookCondition defaultCondition = new NotebookCondition(null, null, 1, name, getI18NText( + NotebookConstants.TEXT_SEARCH_DEFAULT_CONDITION_DISPLAY_NAME_KEY, false), "OUTPUT_STRING", + null, null, null, "LAMS", null, null, null); + notebook.getConditions().add(defaultCondition); + notebookEntryDefinition.getDefaultConditions().add(defaultCondition); + } + notebookEntryDefinition.setShowConditionNameOnly(true); + definitionMap.put(NotebookConstants.TEXT_SEARCH_DEFINITION_NAME, notebookEntryDefinition); + } + + return definitionMap; + } + + /** + * Follows {@link QaServicePOJO#getToolOutput(List, Long, Long)}. + * + */ + public SortedMap getToolOutput(List names, INotebookService notebookService, + Long toolSessionId, Long learnerId) { + + TreeMap outputs = new TreeMap(); + // cached tool output for all text search conditions + ToolOutput notebookEntryOutput = null; + if (names == null) { + // output will be set for all the existing conditions + Notebook qaContent = notebookService.getSessionBySessionId(toolSessionId).getNotebook(); + Set conditions = qaContent.getConditions(); + for (NotebookCondition condition : conditions) { + String name = condition.getName(); + if (isTextSearchConditionName(name) && notebookEntryOutput != null) { + outputs.put(name, notebookEntryOutput); + } else { + ToolOutput output = getToolOutput(name, notebookService, toolSessionId, learnerId); + if (output != null) { + outputs.put(name, output); + if (isTextSearchConditionName(NotebookConstants.TEXT_SEARCH_DEFINITION_NAME)) { + notebookEntryOutput = output; + } + } + } + } + } else { + for (String name : names) { + if (isTextSearchConditionName(name) && notebookEntryOutput != null) { + outputs.put(name, notebookEntryOutput); + } else { + ToolOutput output = getToolOutput(name, notebookService, toolSessionId, learnerId); + if (output != null) { + outputs.put(name, output); + if (isTextSearchConditionName(NotebookConstants.TEXT_SEARCH_DEFINITION_NAME)) { + notebookEntryOutput = output; + } + } + } + } + } + return outputs; + + } + + public ToolOutput getToolOutput(String name, INotebookService qaService, Long toolSessionId, Long learnerId) { + if (isTextSearchConditionName(NotebookConstants.TEXT_SEARCH_DEFINITION_NAME)) { + // entry is loaded from DB + Notebook taskList = qaService.getSessionBySessionId(toolSessionId).getNotebook(); + + NotebookUser user = qaService.getUserByUserIdAndSessionId(learnerId, toolSessionId); + NotebookEntry entry = qaService.getEntry(user.getEntryUID()); + + String value = entry == null ? null : entry.getEntry(); + + return new ToolOutput(name, getI18NText(NotebookConstants.TEXT_SEARCH_DEFINITION_NAME, true), value); + + } + return null; + } + + @Override + protected String[] splitConditionName(String conditionName) { + return super.splitConditionName(conditionName); + } + + protected String buildConditionName(String uniquePart) { + return super.buildConditionName(NotebookConstants.TEXT_SEARCH_DEFINITION_NAME, uniquePart); + } + + private boolean isTextSearchConditionName(String name) { + return name != null && name.startsWith(NotebookConstants.TEXT_SEARCH_DEFINITION_NAME); + } +} \ No newline at end of file Index: lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/NotebookService.java =================================================================== diff -u -r91ab70504f55283e714dfb30794c656b33feeac7 -re64f3e306f3139c78e8917240c33ea232e75e848 --- lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/NotebookService.java (.../NotebookService.java) (revision 91ab70504f55283e714dfb30794c656b33feeac7) +++ lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/NotebookService.java (.../NotebookService.java) (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -26,12 +26,13 @@ import java.io.FileNotFoundException; import java.io.IOException; +import java.util.Collection; 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 java.util.TreeMap; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; @@ -69,6 +70,7 @@ import org.lamsfoundation.lams.tool.notebook.dao.INotebookUserDAO; import org.lamsfoundation.lams.tool.notebook.model.Notebook; import org.lamsfoundation.lams.tool.notebook.model.NotebookAttachment; +import org.lamsfoundation.lams.tool.notebook.model.NotebookCondition; import org.lamsfoundation.lams.tool.notebook.model.NotebookSession; import org.lamsfoundation.lams.tool.notebook.model.NotebookUser; import org.lamsfoundation.lams.tool.notebook.util.NotebookConstants; @@ -82,565 +84,571 @@ /** * An implementation of the INotebookService 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 NotebookService implements ToolSessionManager, ToolContentManager, - INotebookService, ToolContentImport102Manager { +public class NotebookService implements ToolSessionManager, ToolContentManager, INotebookService, + ToolContentImport102Manager { - static Logger logger = Logger.getLogger(NotebookService.class.getName()); + static Logger logger = Logger.getLogger(NotebookService.class.getName()); - private INotebookDAO notebookDAO = null; + private INotebookDAO notebookDAO = null; - private INotebookSessionDAO notebookSessionDAO = null; + private INotebookSessionDAO notebookSessionDAO = null; - private INotebookUserDAO notebookUserDAO = null; + private INotebookUserDAO notebookUserDAO = null; - private INotebookAttachmentDAO notebookAttachmentDAO = null; + private INotebookAttachmentDAO notebookAttachmentDAO = null; - private ILearnerService learnerService; + private ILearnerService learnerService; - private ILamsToolService toolService; + private ILamsToolService toolService; - private IToolContentHandler notebookToolContentHandler = null; + private IToolContentHandler notebookToolContentHandler = null; - private IRepositoryService repositoryService = null; + private IRepositoryService repositoryService = null; - private IAuditService auditService = null; + private IAuditService auditService = null; - private IExportToolContentService exportContentService; + private IExportToolContentService exportContentService; - private ICoreNotebookService coreNotebookService; + private ICoreNotebookService coreNotebookService; - public NotebookService() { - super(); - // TODO Auto-generated constructor stub - } + private NotebookOutputFactory notebookOutputFactory; - /* ************ Methods from ToolSessionManager ************* */ - public void createToolSession(Long toolSessionId, String toolSessionName, - Long toolContentId) throws ToolException { - if (logger.isDebugEnabled()) { - logger.debug("entering method createToolSession:" - + " toolSessionId = " + toolSessionId - + " toolSessionName = " + toolSessionName - + " toolContentId = " + toolContentId); - } + private Random generator = new Random(); - NotebookSession session = new NotebookSession(); - session.setSessionId(toolSessionId); - session.setSessionName(toolSessionName); - // learner starts - // TODO need to also set other fields. - Notebook notebook = notebookDAO.getByContentId(toolContentId); - session.setNotebook(notebook); - notebookSessionDAO.saveOrUpdate(session); - } + public NotebookService() { + super(); + // TODO Auto-generated constructor stub + } - public String leaveToolSession(Long toolSessionId, Long learnerId) - throws DataMissingException, ToolException { - return learnerService.completeToolSession(toolSessionId, learnerId); + /* ************ Methods from ToolSessionManager ************* */ + public void createToolSession(Long toolSessionId, String toolSessionName, Long toolContentId) throws ToolException { + if (NotebookService.logger.isDebugEnabled()) { + NotebookService.logger.debug("entering method createToolSession:" + " toolSessionId = " + toolSessionId + + " toolSessionName = " + toolSessionName + " toolContentId = " + toolContentId); } - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) - throws DataMissingException, ToolException { - // TODO Auto-generated method stub - return null; - } + NotebookSession session = new NotebookSession(); + session.setSessionId(toolSessionId); + session.setSessionName(toolSessionName); + // learner starts + // TODO need to also set other fields. + Notebook notebook = notebookDAO.getByContentId(toolContentId); + session.setNotebook(notebook); + notebookSessionDAO.saveOrUpdate(session); + } - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) - throws DataMissingException, ToolException { - // TODO Auto-generated method stub - return null; - } + public String leaveToolSession(Long toolSessionId, Long learnerId) throws DataMissingException, ToolException { + return learnerService.completeToolSession(toolSessionId, learnerId); + } - public void removeToolSession(Long toolSessionId) - throws DataMissingException, ToolException { - notebookSessionDAO.deleteBySessionID(toolSessionId); - // TODO check if cascade worked - } + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + // TODO Auto-generated method stub + return null; + } - /** - * Get the tool output for the given tool output names. - * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.util.List, java.lang.Long, java.lang.Long) - */ - public SortedMap getToolOutput(List names, - Long toolSessionId, Long learnerId) { - return new TreeMap(); - } + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, + ToolException { + // TODO Auto-generated method stub + return null; + } - /** - * Get the tool output for the given tool output name. - * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.lang.String, java.lang.Long, java.lang.Long) - */ - public ToolOutput getToolOutput(String name, Long toolSessionId, - Long learnerId) { - return null; - } + public void removeToolSession(Long toolSessionId) throws DataMissingException, ToolException { + notebookSessionDAO.deleteBySessionID(toolSessionId); + // TODO check if cascade worked + } - /* ************ Methods from ToolContentManager ************************* */ + /** + * Get the tool output for the given tool output names. + * + * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.util.List, java.lang.Long, + * java.lang.Long) + */ + public SortedMap getToolOutput(List names, Long toolSessionId, Long learnerId) { + return getNotebookOutputFactory().getToolOutput(names, this, toolSessionId, learnerId); + } - public void copyToolContent(Long fromContentId, Long toContentId) - throws ToolException { + /** + * Get the tool output for the given tool output name. + * + * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.lang.String, java.lang.Long, + * java.lang.Long) + */ + public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { + return getNotebookOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); + } - if (logger.isDebugEnabled()) { - logger.debug("entering method copyToolContent:" + " fromContentId=" - + fromContentId + " toContentId=" + toContentId); - } + /* ************ Methods from ToolContentManager ************************* */ - if (toContentId == null) { - String error = "Failed to copy tool content: toContentID is null"; - throw new ToolException(error); - } + public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { - Notebook fromContent = null; - if ( fromContentId != null ) { - fromContent = notebookDAO.getByContentId(fromContentId); - } - if (fromContent == null) { - // create the fromContent using the default tool content - fromContent = getDefaultContent(); - } - Notebook toContent = Notebook.newInstance(fromContent, toContentId, - notebookToolContentHandler); - notebookDAO.saveOrUpdate(toContent); + if (NotebookService.logger.isDebugEnabled()) { + NotebookService.logger.debug("entering method copyToolContent:" + " fromContentId=" + fromContentId + + " toContentId=" + toContentId); } - public void setAsDefineLater(Long toolContentId, boolean value) - throws DataMissingException, ToolException { - Notebook notebook = notebookDAO.getByContentId(toolContentId); - if (notebook == null) { - throw new ToolException("Could not find tool with toolContentID: " - + toolContentId); - } - notebook.setDefineLater(value); - notebookDAO.saveOrUpdate(notebook); + if (toContentId == null) { + String error = "Failed to copy tool content: toContentID is null"; + throw new ToolException(error); } - public void setAsRunOffline(Long toolContentId, boolean value) - throws DataMissingException, ToolException { - Notebook notebook = notebookDAO.getByContentId(toolContentId); - if (notebook == null) { - throw new ToolException("Could not find tool with toolContentID: " - + toolContentId); - } - notebook.setRunOffline(value); - notebookDAO.saveOrUpdate(notebook); + Notebook fromContent = null; + if (fromContentId != null) { + fromContent = notebookDAO.getByContentId(fromContentId); } + if (fromContent == null) { + // create the fromContent using the default tool content + fromContent = getDefaultContent(); + } + Notebook toContent = Notebook.newInstance(fromContent, toContentId, notebookToolContentHandler); + notebookDAO.saveOrUpdate(toContent); + } - public void removeToolContent(Long toolContentId, boolean removeSessionData) - throws SessionDataExistsException, ToolException { - // TODO Auto-generated method stub + public void setAsDefineLater(Long toolContentId, boolean value) throws DataMissingException, ToolException { + Notebook notebook = notebookDAO.getByContentId(toolContentId); + if (notebook == null) { + throw new ToolException("Could not find tool with toolContentID: " + toolContentId); } + notebook.setDefineLater(value); + notebookDAO.saveOrUpdate(notebook); + } - /** - * 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 - * @throws ToolException - * if any other error occurs - */ - - public void exportToolContent(Long toolContentId, String rootPath) - throws DataMissingException, ToolException { - Notebook notebook = notebookDAO.getByContentId(toolContentId); - if (notebook == null) { - notebook = getDefaultContent(); - } - if (notebook == null) - throw new DataMissingException("Unable to find default content for the notebook tool"); - - // set ResourceToolContentHandler as null to avoid copy file node in - // repository again. - notebook = Notebook.newInstance(notebook, toolContentId, - null); - notebook.setToolContentHandler(null); - notebook.setNotebookSessions(null); - Set atts = notebook.getNotebookAttachments(); - for (NotebookAttachment att : atts) { - att.setNotebook(null); - } - try { - exportContentService.registerFileClassForExport( - NotebookAttachment.class.getName(), "fileUuid", - "fileVersionId"); - exportContentService.exportToolContent(toolContentId, - notebook, notebookToolContentHandler, rootPath); - } catch (ExportToolContentException e) { - throw new ToolException(e); - } + public void setAsRunOffline(Long toolContentId, boolean value) throws DataMissingException, ToolException { + Notebook notebook = notebookDAO.getByContentId(toolContentId); + if (notebook == null) { + throw new ToolException("Could not find tool with toolContentID: " + toolContentId); } + notebook.setRunOffline(value); + notebookDAO.saveOrUpdate(notebook); + } - /** - * Import the XML fragment for the tool's content, along with any files - * needed for the content. - * - * @throws ToolException - * if any other error occurs - */ - public void importToolContent(Long toolContentId, Integer newUserUid, - String toolContentPath,String fromVersion,String toVersion) throws ToolException { - try { - exportContentService.registerFileClassForImport( - NotebookAttachment.class.getName(), "fileUuid", - "fileVersionId", "fileName", "fileType", null, null); + public void removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, + ToolException { + // TODO Auto-generated method stub + } - Object toolPOJO = exportContentService.importToolContent( - toolContentPath, notebookToolContentHandler,fromVersion,toVersion); - if (!(toolPOJO instanceof Notebook)) - throw new ImportToolContentException( - "Import Notebook tool content failed. Deserialized object is " - + toolPOJO); - Notebook notebook = (Notebook) toolPOJO; + /** + * 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 + * @throws ToolException + * if any other error occurs + */ - // reset it to new toolContentId - notebook.setToolContentId(toolContentId); - notebook.setCreateBy(new Long(newUserUid.longValue())); - - notebookDAO.saveOrUpdate(notebook); - } catch (ImportToolContentException e) { - throw new ToolException(e); - } + public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { + Notebook notebook = notebookDAO.getByContentId(toolContentId); + if (notebook == null) { + notebook = getDefaultContent(); } + if (notebook == null) { + throw new DataMissingException("Unable to find default content for the notebook tool"); + } - /** Get the definitions for possible output for an activity, based on the toolContentId. These may be definitions that are always - * available for the tool (e.g. number of marks for Multiple Choice) or a custom definition created for a particular activity - * such as the answer to the third question contains the word Koala and hence the need for the toolContentId - * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition - */ - public SortedMap getToolOutputDefinitions(Long toolContentId) throws ToolException { - return new TreeMap(); + // set ResourceToolContentHandler as null to avoid copy file node in + // repository again. + notebook = Notebook.newInstance(notebook, toolContentId, null); + notebook.setToolContentHandler(null); + notebook.setNotebookSessions(null); + Set atts = notebook.getNotebookAttachments(); + for (NotebookAttachment att : atts) { + att.setNotebook(null); } + try { + exportContentService.registerFileClassForExport(NotebookAttachment.class.getName(), "fileUuid", + "fileVersionId"); + exportContentService.exportToolContent(toolContentId, notebook, notebookToolContentHandler, rootPath); + } catch (ExportToolContentException e) { + throw new ToolException(e); + } + } - /* ********** INotebookService Methods ********************************* */ + /** + * Import the XML fragment for the tool's content, along with any files needed for the content. + * + * @throws ToolException + * if any other error occurs + */ + public void importToolContent(Long toolContentId, Integer newUserUid, String toolContentPath, String fromVersion, + String toVersion) throws ToolException { + try { + exportContentService.registerFileClassForImport(NotebookAttachment.class.getName(), "fileUuid", + "fileVersionId", "fileName", "fileType", null, null); - public Long createNotebookEntry(Long id, Integer idType, String signature, - Integer userID, String entry) { - return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); - } + Object toolPOJO = exportContentService.importToolContent(toolContentPath, notebookToolContentHandler, + fromVersion, toVersion); + if (!(toolPOJO instanceof Notebook)) { + throw new ImportToolContentException("Import Notebook tool content failed. Deserialized object is " + + toolPOJO); + } + Notebook notebook = (Notebook) toolPOJO; - public NotebookEntry getEntry(Long uid) { - return coreNotebookService.getEntry(uid); + // reset it to new toolContentId + notebook.setToolContentId(toolContentId); + notebook.setCreateBy(new Long(newUserUid.longValue())); + + notebookDAO.saveOrUpdate(notebook); + } catch (ImportToolContentException e) { + throw new ToolException(e); } + } - public void updateEntry(Long uid, String entry) { - coreNotebookService.updateEntry(uid, "", entry); + /** + * Get the definitions for possible output for an activity, based on the toolContentId. These may be definitions + * that are always available for the tool (e.g. number of marks for Multiple Choice) or a custom definition created + * for a particular activity such as the answer to the third question contains the word Koala and hence the need for + * the toolContentId + * + * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition + */ + public SortedMap getToolOutputDefinitions(Long toolContentId) throws ToolException { + Notebook notebook = getNotebookDAO().getByContentId(toolContentId); + + if (notebook == null) { + notebook = getDefaultContent(); } - - 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); - throw new NotebookException(error); - } - return toolContentId; + // If there are no user added conditions, the default condition will be added in the output factory. It also + // needs to be persisted. + boolean defaultConditionToBeAdded = notebook.getConditions().isEmpty(); + SortedMap map = getNotebookOutputFactory().getToolOutputDefinitions(notebook); + if (defaultConditionToBeAdded && !notebook.getConditions().isEmpty()) { + saveOrUpdateNotebook(notebook); } + return map; + } - public Notebook getDefaultContent() { - Long defaultContentID = getDefaultContentIdBySignature(NotebookConstants.TOOL_SIGNATURE); - Notebook defaultContent = getNotebookByContentId(defaultContentID); - if (defaultContent == null) { - String error = "Could not retrieve default content record for this tool"; - logger.error(error); - throw new NotebookException(error); - } - return defaultContent; - } + /* ********** INotebookService Methods ********************************* */ - public Notebook copyDefaultContent(Long newContentID) { + public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry) { + return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); + } - if (newContentID == null) { - String error = "Cannot copy the Notebook tools default content: + " - + "newContentID is null"; - logger.error(error); - throw new NotebookException(error); - } + public NotebookEntry getEntry(Long uid) { + return coreNotebookService.getEntry(uid); + } - Notebook defaultContent = getDefaultContent(); - // create new notebook using the newContentID - Notebook newContent = new Notebook(); - newContent = Notebook.newInstance(defaultContent, newContentID, - notebookToolContentHandler); - notebookDAO.saveOrUpdate(newContent); - return newContent; - } + public void updateEntry(Long uid, String entry) { + coreNotebookService.updateEntry(uid, "", entry); + } - public Notebook getNotebookByContentId(Long toolContentID) { - Notebook notebook = (Notebook) notebookDAO - .getByContentId(toolContentID); - if (notebook == null) { - logger.debug("Could not find the content with toolContentID:" - + toolContentID); - } - return notebook; + 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"; + NotebookService.logger.error(error); + throw new NotebookException(error); } + return toolContentId; + } - public NotebookSession getSessionBySessionId(Long toolSessionId) { - NotebookSession notebookSession = notebookSessionDAO - .getBySessionId(toolSessionId); - if (notebookSession == null) { - logger - .debug("Could not find the notebook session with toolSessionID:" - + toolSessionId); - } - return notebookSession; + public Notebook getDefaultContent() { + Long defaultContentID = getDefaultContentIdBySignature(NotebookConstants.TOOL_SIGNATURE); + Notebook defaultContent = getNotebookByContentId(defaultContentID); + if (defaultContent == null) { + String error = "Could not retrieve default content record for this tool"; + NotebookService.logger.error(error); + throw new NotebookException(error); } + return defaultContent; + } - public NotebookUser getUserByUserIdAndSessionId(Long userId, - Long toolSessionId) { - return notebookUserDAO.getByUserIdAndSessionId(userId, toolSessionId); + public Notebook copyDefaultContent(Long newContentID) { + + if (newContentID == null) { + String error = "Cannot copy the Notebook tools default content: + " + "newContentID is null"; + NotebookService.logger.error(error); + throw new NotebookException(error); } - public NotebookUser getUserByLoginNameAndSessionId(String loginName, - Long toolSessionId) { - return notebookUserDAO.getByLoginNameAndSessionId(loginName, - toolSessionId); + Notebook defaultContent = getDefaultContent(); + // create new notebook using the newContentID + Notebook newContent = new Notebook(); + newContent = Notebook.newInstance(defaultContent, newContentID, notebookToolContentHandler); + notebookDAO.saveOrUpdate(newContent); + return newContent; + } + + public Notebook getNotebookByContentId(Long toolContentID) { + Notebook notebook = notebookDAO.getByContentId(toolContentID); + if (notebook == null) { + NotebookService.logger.debug("Could not find the content with toolContentID:" + toolContentID); } + return notebook; + } - public NotebookUser getUserByUID(Long uid) { - return notebookUserDAO.getByUID(uid); + public NotebookSession getSessionBySessionId(Long toolSessionId) { + NotebookSession notebookSession = notebookSessionDAO.getBySessionId(toolSessionId); + if (notebookSession == null) { + NotebookService.logger.debug("Could not find the notebook session with toolSessionID:" + toolSessionId); } + return notebookSession; + } - public NotebookAttachment uploadFileToContent(Long toolContentId, - FormFile file, String type) { - if (file == null || StringUtils.isEmpty(file.getFileName())) - throw new NotebookException("Could not find upload file: " + file); + public NotebookUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { + return notebookUserDAO.getByUserIdAndSessionId(userId, toolSessionId); + } - NodeKey nodeKey = processFile(file, type); + public NotebookUser getUserByLoginNameAndSessionId(String loginName, Long toolSessionId) { + return notebookUserDAO.getByLoginNameAndSessionId(loginName, toolSessionId); + } - NotebookAttachment attachment = new NotebookAttachment(nodeKey.getVersion(), type, file.getFileName(), nodeKey.getUuid(), new Date()); - return attachment; - } + public NotebookUser getUserByUID(Long uid) { + return notebookUserDAO.getByUID(uid); + } - public void deleteFromRepository(Long uuid, Long versionID) - throws NotebookException { - ITicket ticket = getRepositoryLoginTicket(); - try { - repositoryService.deleteVersion(ticket, uuid, versionID); - } catch (Exception e) { - throw new NotebookException( - "Exception occured while deleting files from" - + " the repository " + e.getMessage()); - } + public NotebookAttachment uploadFileToContent(Long toolContentId, FormFile file, String type) { + if (file == null || StringUtils.isEmpty(file.getFileName())) { + throw new NotebookException("Could not find upload file: " + file); } - public void deleteInstructionFile(Long contentID, Long uuid, - Long versionID, String type) { - notebookDAO.deleteInstructionFile(contentID, uuid, versionID, type); + NodeKey nodeKey = processFile(file, type); - } + NotebookAttachment attachment = new NotebookAttachment(nodeKey.getVersion(), type, file.getFileName(), nodeKey + .getUuid(), new Date()); + return attachment; + } - public void saveOrUpdateNotebook(Notebook notebook) { - notebookDAO.saveOrUpdate(notebook); + public void deleteFromRepository(Long uuid, Long versionID) throws NotebookException { + ITicket ticket = getRepositoryLoginTicket(); + try { + repositoryService.deleteVersion(ticket, uuid, versionID); + } catch (Exception e) { + throw new NotebookException("Exception occured while deleting files from" + " the repository " + + e.getMessage()); } + } - public void saveOrUpdateNotebookSession(NotebookSession notebookSession) { - notebookSessionDAO.saveOrUpdate(notebookSession); - } + public void deleteInstructionFile(Long contentID, Long uuid, Long versionID, String type) { + notebookDAO.deleteInstructionFile(contentID, uuid, versionID, type); - public void saveOrUpdateNotebookUser(NotebookUser notebookUser) { - notebookUserDAO.saveOrUpdate(notebookUser); - } + } - public NotebookUser createNotebookUser(UserDTO user, - NotebookSession notebookSession) { - NotebookUser notebookUser = new NotebookUser(user, notebookSession); - saveOrUpdateNotebookUser(notebookUser); - return notebookUser; - } + public void saveOrUpdateNotebook(Notebook notebook) { + notebookDAO.saveOrUpdate(notebook); + } - public IAuditService getAuditService() { - return auditService; - } + public void saveOrUpdateNotebookSession(NotebookSession notebookSession) { + notebookSessionDAO.saveOrUpdate(notebookSession); + } - public void setAuditService(IAuditService auditService) { - this.auditService = auditService; - } + public void saveOrUpdateNotebookUser(NotebookUser notebookUser) { + notebookUserDAO.saveOrUpdate(notebookUser); + } - private NodeKey processFile(FormFile file, String type) { - NodeKey node = null; - if (file != null && !StringUtils.isEmpty(file.getFileName())) { - String fileName = file.getFileName(); - try { - node = getNotebookToolContentHandler().uploadFile( - file.getInputStream(), fileName, file.getContentType(), - type); - } catch (InvalidParameterException e) { - throw new NotebookException( - "InvalidParameterException occured while trying to upload File" - + e.getMessage()); - } catch (FileNotFoundException e) { - throw new NotebookException( - "FileNotFoundException occured while trying to upload File" - + e.getMessage()); - } catch (RepositoryCheckedException e) { - throw new NotebookException( - "RepositoryCheckedException occured while trying to upload File" - + e.getMessage()); - } catch (IOException e) { - throw new NotebookException( - "IOException occured while trying to upload File" - + e.getMessage()); - } - } - return node; + public NotebookUser createNotebookUser(UserDTO user, NotebookSession notebookSession) { + NotebookUser notebookUser = new NotebookUser(user, notebookSession); + saveOrUpdateNotebookUser(notebookUser); + return notebookUser; + } + + public IAuditService getAuditService() { + return auditService; + } + + public void setAuditService(IAuditService auditService) { + this.auditService = auditService; + } + + private NodeKey processFile(FormFile file, String type) { + NodeKey node = null; + if (file != null && !StringUtils.isEmpty(file.getFileName())) { + String fileName = file.getFileName(); + try { + node = getNotebookToolContentHandler().uploadFile(file.getInputStream(), fileName, + file.getContentType(), type); + } catch (InvalidParameterException e) { + throw new NotebookException("InvalidParameterException occured while trying to upload File" + + e.getMessage()); + } catch (FileNotFoundException e) { + throw new NotebookException("FileNotFoundException occured while trying to upload File" + + e.getMessage()); + } catch (RepositoryCheckedException e) { + throw new NotebookException("RepositoryCheckedException occured while trying to upload File" + + e.getMessage()); + } catch (IOException e) { + throw new NotebookException("IOException occured while trying to upload File" + e.getMessage()); + } } + return node; + } - /** - * This method verifies the credentials of the SubmitFiles Tool and gives it - * the Ticket to login and access the Content Repository. - * - * A valid ticket is needed in order to access the content from the - * repository. This method would be called evertime the tool needs to - * upload/download files from the content repository. - * - * @return ITicket The ticket for repostory access - * @throws SubmitFilesException - */ - private ITicket getRepositoryLoginTicket() throws NotebookException { - repositoryService = RepositoryProxy.getRepositoryService(); - ICredentials credentials = new SimpleCredentials( - NotebookToolContentHandler.repositoryUser, - NotebookToolContentHandler.repositoryId); - try { - ITicket ticket = repositoryService.login(credentials, - NotebookToolContentHandler.repositoryWorkspaceName); - return ticket; - } catch (AccessDeniedException ae) { - throw new NotebookException("Access Denied to repository." - + ae.getMessage()); - } catch (WorkspaceNotFoundException we) { - throw new NotebookException("Workspace not found." - + we.getMessage()); - } catch (LoginException e) { - throw new NotebookException("Login failed." + e.getMessage()); - } + /** + * This method verifies the credentials of the SubmitFiles Tool and gives it the Ticket to login and + * access the Content Repository. + * + * A valid ticket is needed in order to access the content from the repository. This method would be called evertime + * the tool needs to upload/download files from the content repository. + * + * @return ITicket The ticket for repostory access + * @throws SubmitFilesException + */ + private ITicket getRepositoryLoginTicket() throws NotebookException { + repositoryService = RepositoryProxy.getRepositoryService(); + ICredentials credentials = new SimpleCredentials(NotebookToolContentHandler.repositoryUser, + NotebookToolContentHandler.repositoryId); + try { + ITicket ticket = repositoryService.login(credentials, NotebookToolContentHandler.repositoryWorkspaceName); + return ticket; + } catch (AccessDeniedException ae) { + throw new NotebookException("Access Denied to repository." + ae.getMessage()); + } catch (WorkspaceNotFoundException we) { + throw new NotebookException("Workspace not found." + we.getMessage()); + } catch (LoginException e) { + throw new NotebookException("Login failed." + e.getMessage()); } + } - /* ===============Methods implemented from ToolContentImport102Manager =============== */ - + /* ===============Methods implemented from ToolContentImport102Manager =============== */ /** * Import the data for a 1.0.2 Notebook */ - 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.setLockOnFinished(Boolean.TRUE); - notebook.setOfflineInstructions(null); - notebook.setOnlineInstructions(null); - notebook.setRunOffline(Boolean.FALSE); - notebook.setTitle((String)importValues.get(ToolContentImport102Manager.CONTENT_TITLE)); - notebook.setToolContentId(toolContentId); - notebook.setUpdateDate(now); - notebook.setAllowRichEditor(Boolean.FALSE); - // leave as empty, no need to set them to anything. - //setNotebookAttachments(Set notebookAttachments); - //setNotebookSessions(Set notebookSessions); - notebookDAO.saveOrUpdate(notebook); + 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.setLockOnFinished(Boolean.TRUE); + notebook.setOfflineInstructions(null); + notebook.setOnlineInstructions(null); + notebook.setRunOffline(Boolean.FALSE); + notebook.setTitle((String) importValues.get(ToolContentImport102Manager.CONTENT_TITLE)); + notebook.setToolContentId(toolContentId); + notebook.setUpdateDate(now); + notebook.setAllowRichEditor(Boolean.FALSE); + // leave as empty, no need to set them to anything. + // setNotebookAttachments(Set notebookAttachments); + // setNotebookSessions(Set notebookSessions); + notebookDAO.saveOrUpdate(notebook); } /** 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 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 - +" on activity toolContentId "+toolContentId - +" as the tool content does not exist."); - } - - notebook.setInstructions(description); + 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 + + " on activity toolContentId " + toolContentId + " as the tool content does not exist."); + } + + notebook.setInstructions(description); } - - //========================================================================================= - /* ********** Used by Spring to "inject" the linked objects ************* */ - public INotebookAttachmentDAO getNotebookAttachmentDAO() { - return notebookAttachmentDAO; - } + // ========================================================================================= + /* ********** Used by Spring to "inject" the linked objects ************* */ - public void setNotebookAttachmentDAO(INotebookAttachmentDAO attachmentDAO) { - this.notebookAttachmentDAO = attachmentDAO; - } + public INotebookAttachmentDAO getNotebookAttachmentDAO() { + return notebookAttachmentDAO; + } - public INotebookDAO getNotebookDAO() { - return notebookDAO; - } + public void setNotebookAttachmentDAO(INotebookAttachmentDAO attachmentDAO) { + notebookAttachmentDAO = attachmentDAO; + } - public void setNotebookDAO(INotebookDAO notebookDAO) { - this.notebookDAO = notebookDAO; - } + public INotebookDAO getNotebookDAO() { + return notebookDAO; + } - public IToolContentHandler getNotebookToolContentHandler() { - return notebookToolContentHandler; - } + public void setNotebookDAO(INotebookDAO notebookDAO) { + this.notebookDAO = notebookDAO; + } - public void setNotebookToolContentHandler( - IToolContentHandler notebookToolContentHandler) { - this.notebookToolContentHandler = notebookToolContentHandler; - } + public IToolContentHandler getNotebookToolContentHandler() { + return notebookToolContentHandler; + } - public INotebookSessionDAO getNotebookSessionDAO() { - return notebookSessionDAO; - } + public void setNotebookToolContentHandler(IToolContentHandler notebookToolContentHandler) { + this.notebookToolContentHandler = notebookToolContentHandler; + } - public void setNotebookSessionDAO(INotebookSessionDAO sessionDAO) { - this.notebookSessionDAO = sessionDAO; - } + public INotebookSessionDAO getNotebookSessionDAO() { + return notebookSessionDAO; + } - public ILamsToolService getToolService() { - return toolService; - } + public void setNotebookSessionDAO(INotebookSessionDAO sessionDAO) { + notebookSessionDAO = sessionDAO; + } - public void setToolService(ILamsToolService toolService) { - this.toolService = toolService; - } + public ILamsToolService getToolService() { + return toolService; + } - public INotebookUserDAO getNotebookUserDAO() { - return notebookUserDAO; - } + public void setToolService(ILamsToolService toolService) { + this.toolService = toolService; + } - public void setNotebookUserDAO(INotebookUserDAO userDAO) { - this.notebookUserDAO = userDAO; - } + public INotebookUserDAO getNotebookUserDAO() { + return notebookUserDAO; + } - public ILearnerService getLearnerService() { - return learnerService; - } + public void setNotebookUserDAO(INotebookUserDAO userDAO) { + notebookUserDAO = 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 void setCoreNotebookService(ICoreNotebookService coreNotebookService) { + this.coreNotebookService = coreNotebookService; + } + + public NotebookOutputFactory getNotebookOutputFactory() { + return notebookOutputFactory; + } + + public void setNotebookOutputFactory(NotebookOutputFactory notebookOutputFactory) { + this.notebookOutputFactory = notebookOutputFactory; + } + + /** + * {@inheritDoc} + */ + public String createConditionName(Collection existingConditions) { + String uniqueNumber = null; + do { + uniqueNumber = String.valueOf(Math.abs(generator.nextInt())); + for (NotebookCondition condition : existingConditions) { + String[] splitedName = getNotebookOutputFactory().splitConditionName(condition.getName()); + if (uniqueNumber.equals(splitedName[1])) { + uniqueNumber = null; + } + } + } while (uniqueNumber == null); + return getNotebookOutputFactory().buildConditionName(uniqueNumber); + } + + public void releaseConditionsFromCache(Notebook notebook) { + if (notebook.getConditions() != null) { + for (NotebookCondition condition : notebook.getConditions()) { + getNotebookDAO().releaseFromCache(condition); + } } -} + } +} \ No newline at end of file Index: lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/util/NotebookConditionComparator.java =================================================================== diff -u --- lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/util/NotebookConditionComparator.java (revision 0) +++ lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/util/NotebookConditionComparator.java (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -0,0 +1,50 @@ +/**************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * License Information: http://lamsfoundation.org/licensing/lams/2.0/ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2.0 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA + * + * http://www.gnu.org/licenses/gpl.txt + * **************************************************************** + */ + +/* $Id$ */ +package org.lamsfoundation.lams.tool.notebook.util; + +import java.util.Comparator; + +import org.lamsfoundation.lams.tool.notebook.model.NotebookCondition; + +/** + * Comparator for NotebookCondition. Only the order ID is compared. + * + * @author Marcin Cieslak + * @see org.lamsfoundation.lams.tool.notebook.NotebookCondition + */ +public class NotebookConditionComparator implements Comparator { + + /** + * {@inheritDoc} + */ + public int compare(NotebookCondition o1, NotebookCondition o2) { + if (o1 != null && o2 != null) { + return o1.getOrderId() - o2.getOrderId(); + } else if (o1 != null) { + return 1; + } else { + return -1; + } + } +} \ No newline at end of file Index: lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/util/NotebookConstants.java =================================================================== diff -u -r08950e1090443c3423a3d1c587416a2fccd8bbdf -re64f3e306f3139c78e8917240c33ea232e75e848 --- lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/util/NotebookConstants.java (.../NotebookConstants.java) (revision 08950e1090443c3423a3d1c587416a2fccd8bbdf) +++ lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/util/NotebookConstants.java (.../NotebookConstants.java) (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -25,27 +25,41 @@ package org.lamsfoundation.lams.tool.notebook.util; public interface NotebookConstants { - public static final String TOOL_SIGNATURE = "lantbk11"; - - // Notebook session status - public static final Integer SESSION_NOT_STARTED = new Integer(0); - public static final Integer SESSION_IN_PROGRESS = new Integer(1); - public static final Integer SESSION_COMPLETED = new Integer(2); - - public static final String AUTHORING_DEFAULT_TAB = "1"; - public static final String ATTACHMENT_LIST = "attachmentList"; - public static final String DELETED_ATTACHMENT_LIST = "deletedAttachmentList"; - public static final String AUTH_SESSION_ID_COUNTER = "authoringSessionIdCounter"; - public static final String AUTH_SESSION_ID = "authoringSessionId"; - - public static final int MONITORING_SUMMARY_MAX_MESSAGES = 5; - - // Attribute names - public static final String ATTR_MESSAGE = "message"; - public static final String ATTR_SESSION_MAP = "sessionMap"; - - // Parameter names - public static final String PARAM_PARENT_PAGE = "parentPage"; - - static final String FILTER_REPLACE_TEXT = "***"; -} + public static final String TOOL_SIGNATURE = "lantbk11"; + + // Notebook session status + public static final Integer SESSION_NOT_STARTED = new Integer(0); + public static final Integer SESSION_IN_PROGRESS = new Integer(1); + public static final Integer SESSION_COMPLETED = new Integer(2); + + public static final String AUTHORING_DEFAULT_TAB = "1"; + public static final String ATTACHMENT_LIST = "attachmentList"; + public static final String DELETED_ATTACHMENT_LIST = "deletedAttachmentList"; + public static final String AUTH_SESSION_ID_COUNTER = "authoringSessionIdCounter"; + public static final String AUTH_SESSION_ID = "authoringSessionId"; + + public static final int MONITORING_SUMMARY_MAX_MESSAGES = 5; + + // Attribute names + public static final String ATTR_MESSAGE = "message"; + public static final String ATTR_SESSION_MAP = "sessionMap"; + + // Parameter names + public static final String PARAM_PARENT_PAGE = "parentPage"; + + static final String FILTER_REPLACE_TEXT = "***"; + + public static final String ATTR_SESSION_MAP_ID = "sessionMapID"; + public static final String ATTR_CONDITION_SET = "conditionList"; + + public static final String PARAM_ORDER_ID = "orderId"; + public static final String ATTR_DELETED_CONDITION_LIST = "deletedConditionList"; + public static final String TEXT_SEARCH_DEFINITION_NAME = "text.search.output.definition.notebook"; + public static final String TEXT_SEARCH_DEFAULT_CONDITION_DISPLAY_NAME_KEY = "text.search.output.definition.notebook.default.condition"; + public static final String SUCCESS = "success"; + public static final String ERROR_MSG_CONDITION = "error.condition"; + public static final String ERROR_MSG_NAME_BLANK = "error.condition.name.blank"; + public static final String ERROR_MSG_NAME_DUPLICATED = "error.condition.duplicated.name"; + + public static final String DEFINE_LATER = "defineLater"; +} \ No newline at end of file Index: lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/web/actions/AuthoringAction.java =================================================================== diff -u -r7dd15ff5149a5f87efd7cef5304819bf1bd0b78f -re64f3e306f3139c78e8917240c33ea232e75e848 --- lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/web/actions/AuthoringAction.java (.../AuthoringAction.java) (revision 7dd15ff5149a5f87efd7cef5304819bf1bd0b78f) +++ lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/web/actions/AuthoringAction.java (.../AuthoringAction.java) (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -24,12 +24,15 @@ package org.lamsfoundation.lams.tool.notebook.web.actions; +import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -46,8 +49,10 @@ import org.lamsfoundation.lams.tool.ToolAccessMode; import org.lamsfoundation.lams.tool.notebook.model.Notebook; import org.lamsfoundation.lams.tool.notebook.model.NotebookAttachment; +import org.lamsfoundation.lams.tool.notebook.model.NotebookCondition; import org.lamsfoundation.lams.tool.notebook.service.INotebookService; import org.lamsfoundation.lams.tool.notebook.service.NotebookServiceProxy; +import org.lamsfoundation.lams.tool.notebook.util.NotebookConditionComparator; import org.lamsfoundation.lams.tool.notebook.util.NotebookConstants; import org.lamsfoundation.lams.tool.notebook.web.forms.AuthoringForm; import org.lamsfoundation.lams.util.FileValidatorUtil; @@ -60,419 +65,419 @@ * @author * @version * - * @struts.action path="/authoring" name="authoringForm" parameter="dispatch" - * scope="request" validate="false" + * @struts.action path="/authoring" name="authoringForm" parameter="dispatch" scope="request" validate="false" * * @struts.action-forward name="success" path="tiles:/authoring/main" * @struts.action-forward name="message_page" path="tiles:/generic/message" */ public class AuthoringAction extends LamsDispatchAction { - private static Logger logger = Logger.getLogger(AuthoringAction.class); + private static Logger logger = Logger.getLogger(AuthoringAction.class); - public INotebookService notebookService; + public INotebookService notebookService; - // Authoring SessionMap key names - private static final String KEY_TOOL_CONTENT_ID = "toolContentID"; + // Authoring SessionMap key names + private static final String KEY_TOOL_CONTENT_ID = "toolContentID"; + private static final String KEY_CONTENT_FOLDER_ID = "contentFolderID"; + private static final String KEY_MODE = "mode"; + private static final String KEY_ONLINE_FILES = "onlineFiles"; + private static final String KEY_OFFLINE_FILES = "offlineFiles"; + private static final String KEY_UNSAVED_ONLINE_FILES = "unsavedOnlineFiles"; + private static final String KEY_UNSAVED_OFFLINE_FILES = "unsavedOfflineFiles"; + private static final String KEY_DELETED_FILES = "deletedFiles"; - private static final String KEY_CONTENT_FOLDER_ID = "contentFolderID"; + /** + * Default method when no dispatch parameter is specified. It is expected that the parameter + * toolContentID will be passed in. This will be used to retrieve content for this tool. + * + */ + @Override + protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { - private static final String KEY_MODE = "mode"; + // Extract toolContentID from parameters. + Long toolContentID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID)); - private static final String KEY_ONLINE_FILES = "onlineFiles"; + String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID); - private static final String KEY_OFFLINE_FILES = "offlineFiles"; + ToolAccessMode mode = WebUtil.readToolAccessModeParam(request, "mode", true); - private static final String KEY_UNSAVED_ONLINE_FILES = "unsavedOnlineFiles"; + // set up notebookService + if (notebookService == null) { + notebookService = NotebookServiceProxy.getNotebookService(this.getServlet().getServletContext()); + } - private static final String KEY_UNSAVED_OFFLINE_FILES = "unsavedOfflineFiles"; + // retrieving Notebook with given toolContentID + Notebook notebook = notebookService.getNotebookByContentId(toolContentID); + if (notebook == null) { + notebook = notebookService.copyDefaultContent(toolContentID); + notebook.setCreateDate(new Date()); + notebookService.saveOrUpdateNotebook(notebook); + // TODO NOTE: this causes DB orphans when LD not saved. + } - private static final String KEY_DELETED_FILES = "deletedFiles"; + if (mode != null && mode.isTeacher()) { + // Set the defineLater flag so that learners cannot use content + // while we + // are editing. This flag is released when updateContent is called. + notebook.setDefineLater(true); + notebookService.saveOrUpdateNotebook(notebook); + } - /** - * Default method when no dispatch parameter is specified. It is expected - * that the parameter toolContentID will be passed in. This - * will be used to retrieve content for this tool. - * - */ - protected ActionForward unspecified(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) { + // Set up the authForm. + AuthoringForm authForm = (AuthoringForm) form; + updateAuthForm(authForm, notebook); - // Extract toolContentID from parameters. - Long toolContentID = new Long(WebUtil.readLongParam(request, - AttributeNames.PARAM_TOOL_CONTENT_ID)); + // Set up sessionMap + SessionMap map = createSessionMap(notebook, getAccessMode(request), contentFolderID, + toolContentID); + authForm.setSessionMapID(map.getSessionID()); - String contentFolderID = WebUtil.readStrParam(request, - AttributeNames.PARAM_CONTENT_FOLDER_ID); + // add the sessionMap to HTTPSession. + request.getSession().setAttribute(map.getSessionID(), map); + request.setAttribute(NotebookConstants.ATTR_SESSION_MAP, map); - ToolAccessMode mode = WebUtil.readToolAccessModeParam(request, "mode", - true); + return mapping.findForward("success"); + } - // set up notebookService - if (notebookService == null) { - notebookService = NotebookServiceProxy.getNotebookService(this - .getServlet().getServletContext()); - } + public ActionForward updateContent(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { + // TODO need error checking. - // retrieving Notebook with given toolContentID - Notebook notebook = notebookService - .getNotebookByContentId(toolContentID); - if (notebook == null) { - notebook = notebookService.copyDefaultContent(toolContentID); - notebook.setCreateDate(new Date()); - notebookService.saveOrUpdateNotebook(notebook); - // TODO NOTE: this causes DB orphans when LD not saved. - } + // get authForm and session map. + AuthoringForm authForm = (AuthoringForm) form; + SessionMap map = getSessionMap(request, authForm); - if (mode != null && mode.isTeacher()) { - // Set the defineLater flag so that learners cannot use content - // while we - // are editing. This flag is released when updateContent is called. - notebook.setDefineLater(true); - notebookService.saveOrUpdateNotebook(notebook); - } + // get notebook content. + Notebook notebook = notebookService.getNotebookByContentId((Long) map.get(AuthoringAction.KEY_TOOL_CONTENT_ID)); - // Set up the authForm. - AuthoringForm authForm = (AuthoringForm) form; - updateAuthForm(authForm, notebook); + // update notebook content using form inputs. + ToolAccessMode mode = (ToolAccessMode) map.get(AuthoringAction.KEY_MODE); + updateNotebook(notebook, authForm, mode); - // Set up sessionMap - SessionMap map = createSessionMap(notebook, - getAccessMode(request), contentFolderID, toolContentID); - authForm.setSessionMapID(map.getSessionID()); + // remove attachments marked for deletion. + Set attachments = notebook.getNotebookAttachments(); + if (attachments == null) { + attachments = new HashSet(); + } - // add the sessionMap to HTTPSession. - request.getSession().setAttribute(map.getSessionID(), map); - request.setAttribute(NotebookConstants.ATTR_SESSION_MAP, map); + for (NotebookAttachment att : getAttList(AuthoringAction.KEY_DELETED_FILES, map)) { + // remove from db, leave in repository + attachments.remove(att); + } - return mapping.findForward("success"); + // add unsaved attachments + attachments.addAll(getAttList(AuthoringAction.KEY_UNSAVED_ONLINE_FILES, map)); + attachments.addAll(getAttList(AuthoringAction.KEY_UNSAVED_OFFLINE_FILES, map)); + + // set attachments in case it didn't exist + notebook.setNotebookAttachments(attachments); + + notebookService.releaseConditionsFromCache(notebook); + + Set conditions = notebook.getConditions(); + if (conditions == null) { + conditions = new TreeSet(new NotebookConditionComparator()); } + SortedSet conditionSet = (SortedSet) map + .get(NotebookConstants.ATTR_CONDITION_SET); + conditions.addAll(conditionSet); - public ActionForward updateContent(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) { - // TODO need error checking. + List deletedConditionList = (List) map + .get(NotebookConstants.ATTR_DELETED_CONDITION_LIST); + if (deletedConditionList != null) { + for (NotebookCondition condition : deletedConditionList) { + // remove from db, leave in repository + conditions.remove(condition); + } + } - // get authForm and session map. - AuthoringForm authForm = (AuthoringForm) form; - SessionMap map = getSessionMap(request, authForm); + // set attachments in case it didn't exist + notebook.setConditions(conditionSet); - // get notebook content. - Notebook notebook = notebookService.getNotebookByContentId((Long) map - .get(KEY_TOOL_CONTENT_ID)); + // set the update date + notebook.setUpdateDate(new Date()); - // update notebook content using form inputs. - ToolAccessMode mode = (ToolAccessMode) map.get(KEY_MODE); - updateNotebook(notebook, authForm, mode); + // releasing defineLater flag so that learner can start using the tool. + notebook.setDefineLater(false); - // remove attachments marked for deletion. - Set attachments = notebook.getNotebookAttachments(); - if (attachments == null) { - attachments = new HashSet(); - } + notebookService.saveOrUpdateNotebook(notebook); - for (NotebookAttachment att : getAttList(KEY_DELETED_FILES, map)) { - // remove from db, leave in repository - attachments.remove(att); - } + request.setAttribute(AuthoringConstants.LAMS_AUTHORING_SUCCESS_FLAG, Boolean.TRUE); - // add unsaved attachments - attachments.addAll(getAttList(KEY_UNSAVED_ONLINE_FILES, map)); - attachments.addAll(getAttList(KEY_UNSAVED_OFFLINE_FILES, map)); + // add the sessionMapID to form + authForm.setSessionMapID(map.getSessionID()); - // set attachments in case it didn't exist - notebook.setNotebookAttachments(attachments); + request.setAttribute(NotebookConstants.ATTR_SESSION_MAP, map); - // set the update date - notebook.setUpdateDate(new Date()); + return mapping.findForward("success"); + } - // releasing defineLater flag so that learner can start using the tool. - notebook.setDefineLater(false); + public ActionForward uploadOnline(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { + return uploadFile(mapping, (AuthoringForm) form, IToolContentHandler.TYPE_ONLINE, request); + } - notebookService.saveOrUpdateNotebook(notebook); + public ActionForward uploadOffline(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { + return uploadFile(mapping, (AuthoringForm) form, IToolContentHandler.TYPE_OFFLINE, request); + } - request.setAttribute(AuthoringConstants.LAMS_AUTHORING_SUCCESS_FLAG, - Boolean.TRUE); + public ActionForward deleteOnline(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { + return deleteFile(mapping, (AuthoringForm) form, IToolContentHandler.TYPE_ONLINE, request); + } - // add the sessionMapID to form - authForm.setSessionMapID(map.getSessionID()); + public ActionForward deleteOffline(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { + return deleteFile(mapping, (AuthoringForm) form, IToolContentHandler.TYPE_OFFLINE, request); + } - request.setAttribute(NotebookConstants.ATTR_SESSION_MAP, map); + public ActionForward removeUnsavedOnline(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { + return removeUnsaved(mapping, (AuthoringForm) form, IToolContentHandler.TYPE_ONLINE, request); + } - return mapping.findForward("success"); - } + public ActionForward removeUnsavedOffline(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { + return removeUnsaved(mapping, (AuthoringForm) form, IToolContentHandler.TYPE_OFFLINE, request); + } - public ActionForward uploadOnline(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) { - return uploadFile(mapping, (AuthoringForm) form, - IToolContentHandler.TYPE_ONLINE, request); - } + /* ========== Private Methods ********** */ - public ActionForward uploadOffline(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) { - return uploadFile(mapping, (AuthoringForm) form, - IToolContentHandler.TYPE_OFFLINE, request); - } + private ActionForward uploadFile(ActionMapping mapping, AuthoringForm authForm, String type, + HttpServletRequest request) { + SessionMap map = getSessionMap(request, authForm); - public ActionForward deleteOnline(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) { - return deleteFile(mapping, (AuthoringForm) form, - IToolContentHandler.TYPE_ONLINE, request); - } + FormFile file; + List unsavedFiles; + List savedFiles; + if (StringUtils.equals(IToolContentHandler.TYPE_OFFLINE, type)) { + file = authForm.getOfflineFile(); + unsavedFiles = getAttList(AuthoringAction.KEY_UNSAVED_OFFLINE_FILES, map); - public ActionForward deleteOffline(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) { - return deleteFile(mapping, (AuthoringForm) form, - IToolContentHandler.TYPE_OFFLINE, request); - } + savedFiles = getAttList(AuthoringAction.KEY_OFFLINE_FILES, map); + } else { + file = authForm.getOnlineFile(); + unsavedFiles = getAttList(AuthoringAction.KEY_UNSAVED_ONLINE_FILES, map); - public ActionForward removeUnsavedOnline(ActionMapping mapping, - ActionForm form, HttpServletRequest request, - HttpServletResponse response) { - return removeUnsaved(mapping, (AuthoringForm) form, - IToolContentHandler.TYPE_ONLINE, request); + savedFiles = getAttList(AuthoringAction.KEY_ONLINE_FILES, map); } - public ActionForward removeUnsavedOffline(ActionMapping mapping, - ActionForm form, HttpServletRequest request, - HttpServletResponse response) { - return removeUnsaved(mapping, (AuthoringForm) form, - IToolContentHandler.TYPE_OFFLINE, request); + // validate file max size + ActionMessages errors = new ActionMessages(); + FileValidatorUtil.validateFileSize(file, true, errors); + if (!errors.isEmpty()) { + request.setAttribute(NotebookConstants.ATTR_SESSION_MAP, map); + this.saveErrors(request, errors); + return mapping.findForward("success"); } - /* ========== Private Methods ********** */ + if (file.getFileName().length() != 0) { - private ActionForward uploadFile(ActionMapping mapping, - AuthoringForm authForm, String type, HttpServletRequest request) { - SessionMap map = getSessionMap(request, authForm); + // upload file to repository + NotebookAttachment newAtt = notebookService.uploadFileToContent((Long) map + .get(AuthoringAction.KEY_TOOL_CONTENT_ID), file, type); - FormFile file; - List unsavedFiles; - List savedFiles; - if (StringUtils.equals(IToolContentHandler.TYPE_OFFLINE, type)) { - file = (FormFile) authForm.getOfflineFile(); - unsavedFiles = getAttList(KEY_UNSAVED_OFFLINE_FILES, map); + // Add attachment to unsavedFiles + // check to see if file with same name exists + NotebookAttachment currAtt; + Iterator iter = savedFiles.iterator(); + while (iter.hasNext()) { + currAtt = (NotebookAttachment) iter.next(); + if (StringUtils.equals(currAtt.getFileName(), newAtt.getFileName()) + && StringUtils.equals(currAtt.getFileType(), newAtt.getFileType())) { + // move from this this list to deleted list. + getAttList(AuthoringAction.KEY_DELETED_FILES, map).add(currAtt); + iter.remove(); + break; + } + } + unsavedFiles.add(newAtt); - savedFiles = getAttList(KEY_OFFLINE_FILES, map); - } else { - file = (FormFile) authForm.getOnlineFile(); - unsavedFiles = getAttList(KEY_UNSAVED_ONLINE_FILES, map); + request.setAttribute(NotebookConstants.ATTR_SESSION_MAP, map); + request.setAttribute("unsavedChanges", new Boolean(true)); + } + return mapping.findForward("success"); + } - savedFiles = getAttList(KEY_ONLINE_FILES, map); - } + private ActionForward deleteFile(ActionMapping mapping, AuthoringForm authForm, String type, + HttpServletRequest request) { + SessionMap map = getSessionMap(request, authForm); - // validate file max size - ActionMessages errors = new ActionMessages(); - FileValidatorUtil.validateFileSize(file, true, errors); - if (!errors.isEmpty()) { - request.setAttribute(NotebookConstants.ATTR_SESSION_MAP, map); - this.saveErrors(request, errors); - return mapping.findForward("success"); - } + List fileList; + if (StringUtils.equals(IToolContentHandler.TYPE_OFFLINE, type)) { + fileList = getAttList(AuthoringAction.KEY_OFFLINE_FILES, map); + } else { + fileList = getAttList(AuthoringAction.KEY_ONLINE_FILES, map); + } - if (file.getFileName().length() != 0) { + Iterator iter = fileList.iterator(); - // upload file to repository - NotebookAttachment newAtt = notebookService.uploadFileToContent( - (Long) map.get(KEY_TOOL_CONTENT_ID), file, type); + while (iter.hasNext()) { + NotebookAttachment att = (NotebookAttachment) iter.next(); - // Add attachment to unsavedFiles - // check to see if file with same name exists - NotebookAttachment currAtt; - Iterator iter = savedFiles.iterator(); - while (iter.hasNext()) { - currAtt = (NotebookAttachment) iter.next(); - if (StringUtils.equals(currAtt.getFileName(), newAtt.getFileName()) - && StringUtils.equals(currAtt.getFileType(), newAtt.getFileType())) { - // move from this this list to deleted list. - getAttList(KEY_DELETED_FILES, map).add(currAtt); - iter.remove(); - break; - } - } - unsavedFiles.add(newAtt); + if (att.getFileUuid().equals(authForm.getDeleteFileUuid())) { + // move to delete file list, deleted at next updateContent + getAttList(AuthoringAction.KEY_DELETED_FILES, map).add(att); - request.setAttribute(NotebookConstants.ATTR_SESSION_MAP, map); - request.setAttribute("unsavedChanges", new Boolean(true)); - } - return mapping.findForward("success"); + // remove from this list + iter.remove(); + break; + } } - private ActionForward deleteFile(ActionMapping mapping, - AuthoringForm authForm, String type, HttpServletRequest request) { - SessionMap map = getSessionMap(request, authForm); + request.setAttribute(NotebookConstants.ATTR_SESSION_MAP, map); + request.setAttribute("unsavedChanges", new Boolean(true)); - List fileList; - if (StringUtils.equals(IToolContentHandler.TYPE_OFFLINE, type)) { - fileList = getAttList(KEY_OFFLINE_FILES, map); - } else { - fileList = getAttList(KEY_ONLINE_FILES, map); - } + return mapping.findForward("success"); + } - Iterator iter = fileList.iterator(); + private ActionForward removeUnsaved(ActionMapping mapping, AuthoringForm authForm, String type, + HttpServletRequest request) { + SessionMap map = getSessionMap(request, authForm); - while (iter.hasNext()) { - NotebookAttachment att = (NotebookAttachment) iter.next(); + List unsavedFiles; - if (att.getFileUuid().equals(authForm.getDeleteFileUuid())) { - // move to delete file list, deleted at next updateContent - getAttList(KEY_DELETED_FILES, map).add(att); + if (StringUtils.equals(IToolContentHandler.TYPE_OFFLINE, type)) { + unsavedFiles = getAttList(AuthoringAction.KEY_UNSAVED_OFFLINE_FILES, map); + } else { + unsavedFiles = getAttList(AuthoringAction.KEY_UNSAVED_ONLINE_FILES, map); + } - // remove from this list - iter.remove(); - break; - } - } + Iterator iter = unsavedFiles.iterator(); + while (iter.hasNext()) { + NotebookAttachment att = (NotebookAttachment) iter.next(); - request.setAttribute(NotebookConstants.ATTR_SESSION_MAP, map); - request.setAttribute("unsavedChanges", new Boolean(true)); - - return mapping.findForward("success"); + if (att.getFileUuid().equals(authForm.getDeleteFileUuid())) { + // delete from repository and list + notebookService.deleteFromRepository(att.getFileUuid(), att.getFileVersionId()); + iter.remove(); + break; + } } - private ActionForward removeUnsaved(ActionMapping mapping, - AuthoringForm authForm, String type, HttpServletRequest request) { - SessionMap map = getSessionMap(request, authForm); + request.setAttribute(NotebookConstants.ATTR_SESSION_MAP, map); + request.setAttribute("unsavedChanges", new Boolean(true)); - List unsavedFiles; + return mapping.findForward("success"); + } - if (StringUtils.equals(IToolContentHandler.TYPE_OFFLINE, type)) { - unsavedFiles = getAttList(KEY_UNSAVED_OFFLINE_FILES, map); - } else { - unsavedFiles = getAttList(KEY_UNSAVED_ONLINE_FILES, map); - } + /** + * Updates Notebook content using AuthoringForm inputs. + * + * @param authForm + * @param mode + * @return + */ + private void updateNotebook(Notebook notebook, AuthoringForm authForm, ToolAccessMode mode) { + notebook.setTitle(authForm.getTitle()); + notebook.setInstructions(authForm.getInstructions()); + if (mode.isAuthor()) { // Teacher cannot modify following + notebook.setOfflineInstructions(authForm.getOnlineInstruction()); + notebook.setOnlineInstructions(authForm.getOfflineInstruction()); + notebook.setLockOnFinished(authForm.isLockOnFinished()); + notebook.setAllowRichEditor(authForm.isAllowRichEditor()); - Iterator iter = unsavedFiles.iterator(); - while (iter.hasNext()) { - NotebookAttachment att = (NotebookAttachment) iter.next(); - - if (att.getFileUuid().equals(authForm.getDeleteFileUuid())) { - // delete from repository and list - notebookService.deleteFromRepository(att.getFileUuid(), att - .getFileVersionId()); - iter.remove(); - break; - } - } - - request.setAttribute(NotebookConstants.ATTR_SESSION_MAP, map); - request.setAttribute("unsavedChanges", new Boolean(true)); - - return mapping.findForward("success"); } + } - /** - * Updates Notebook content using AuthoringForm inputs. - * - * @param authForm - * @param mode - * @return - */ - private void updateNotebook(Notebook notebook, AuthoringForm authForm, - ToolAccessMode mode) { - notebook.setTitle(authForm.getTitle()); - notebook.setInstructions(authForm.getInstructions()); - if (mode.isAuthor()) { // Teacher cannot modify following - notebook.setOfflineInstructions(authForm.getOnlineInstruction()); - notebook.setOnlineInstructions(authForm.getOfflineInstruction()); - notebook.setLockOnFinished(authForm.isLockOnFinished()); - notebook.setAllowRichEditor(authForm.isAllowRichEditor()); - } - } + /** + * Updates AuthoringForm using Notebook content. + * + * @param notebook + * @param authForm + * @return + */ + private void updateAuthForm(AuthoringForm authForm, Notebook notebook) { + authForm.setTitle(notebook.getTitle()); + authForm.setInstructions(notebook.getInstructions()); + authForm.setOnlineInstruction(notebook.getOnlineInstructions()); + authForm.setOfflineInstruction(notebook.getOfflineInstructions()); + authForm.setLockOnFinished(notebook.isLockOnFinished()); + authForm.setAllowRichEditor(notebook.isAllowRichEditor()); - /** - * Updates AuthoringForm using Notebook content. - * - * @param notebook - * @param authForm - * @return - */ - private void updateAuthForm(AuthoringForm authForm, Notebook notebook) { - authForm.setTitle(notebook.getTitle()); - authForm.setInstructions(notebook.getInstructions()); - authForm.setOnlineInstruction(notebook.getOnlineInstructions()); - authForm.setOfflineInstruction(notebook.getOfflineInstructions()); - authForm.setLockOnFinished(notebook.isLockOnFinished()); - authForm.setAllowRichEditor(notebook.isAllowRichEditor()); - } + } - /** - * Updates SessionMap using Notebook content. - * - * @param notebook - * @param mode - */ - private SessionMap createSessionMap(Notebook notebook, - ToolAccessMode mode, String contentFolderID, Long toolContentID) { + /** + * Updates SessionMap using Notebook content. + * + * @param notebook + * @param mode + */ + private SessionMap createSessionMap(Notebook notebook, ToolAccessMode mode, String contentFolderID, + Long toolContentID) { - SessionMap map = new SessionMap(); + SessionMap map = new SessionMap(); - map.put(KEY_MODE, mode); - map.put(KEY_CONTENT_FOLDER_ID, contentFolderID); - map.put(KEY_TOOL_CONTENT_ID, toolContentID); - map.put(KEY_ONLINE_FILES, new LinkedList()); - map.put(KEY_OFFLINE_FILES, new LinkedList()); - map.put(KEY_UNSAVED_ONLINE_FILES, new LinkedList()); - map - .put(KEY_UNSAVED_OFFLINE_FILES, - new LinkedList()); - map.put(KEY_DELETED_FILES, new LinkedList()); + map.put(AuthoringAction.KEY_MODE, mode); + map.put(AuthoringAction.KEY_CONTENT_FOLDER_ID, contentFolderID); + map.put(AuthoringAction.KEY_TOOL_CONTENT_ID, toolContentID); + map.put(AuthoringAction.KEY_ONLINE_FILES, new LinkedList()); + map.put(AuthoringAction.KEY_OFFLINE_FILES, new LinkedList()); + map.put(AuthoringAction.KEY_UNSAVED_ONLINE_FILES, new LinkedList()); + map.put(AuthoringAction.KEY_UNSAVED_OFFLINE_FILES, new LinkedList()); + map.put(AuthoringAction.KEY_DELETED_FILES, new LinkedList()); + map.put(NotebookConstants.ATTR_DELETED_CONDITION_LIST, new ArrayList()); - Iterator iter = notebook.getNotebookAttachments().iterator(); - while (iter.hasNext()) { - NotebookAttachment attachment = (NotebookAttachment) iter.next(); - String type = attachment.getFileType(); - if (type.equals(IToolContentHandler.TYPE_OFFLINE)) { - getAttList(KEY_OFFLINE_FILES, map).add(attachment); - } - if (type.equals(IToolContentHandler.TYPE_ONLINE)) { - getAttList(KEY_ONLINE_FILES, map).add(attachment); - } - } - - return map; + Iterator iter = notebook.getNotebookAttachments().iterator(); + while (iter.hasNext()) { + NotebookAttachment attachment = (NotebookAttachment) iter.next(); + String type = attachment.getFileType(); + if (type.equals(IToolContentHandler.TYPE_OFFLINE)) { + getAttList(AuthoringAction.KEY_OFFLINE_FILES, map).add(attachment); + } + if (type.equals(IToolContentHandler.TYPE_ONLINE)) { + getAttList(AuthoringAction.KEY_ONLINE_FILES, map).add(attachment); + } } - /** - * Get ToolAccessMode from HttpRequest parameters. Default value is AUTHOR - * mode. - * - * @param request - * @return - */ - private ToolAccessMode getAccessMode(HttpServletRequest request) { - ToolAccessMode mode; - String modeStr = request.getParameter(AttributeNames.ATTR_MODE); - if (StringUtils.equalsIgnoreCase(modeStr, ToolAccessMode.TEACHER - .toString())) - mode = ToolAccessMode.TEACHER; - else - mode = ToolAccessMode.AUTHOR; - return mode; - } + SortedSet set = new TreeSet(new NotebookConditionComparator()); - /** - * Retrieves a List of attachments from the map using the key. - * - * @param key - * @param map - * @return - */ - private List getAttList(String key, - SessionMap map) { - List list = (List) map.get(key); - return list; + if (notebook.getConditions() != null) { + set.addAll(notebook.getConditions()); } + map.put(NotebookConstants.ATTR_CONDITION_SET, set); + return map; + } - /** - * Retrieve the SessionMap from the HttpSession. - * - * @param request - * @param authForm - * @return - */ - private SessionMap getSessionMap( - HttpServletRequest request, AuthoringForm authForm) { - return (SessionMap) request.getSession().getAttribute( - authForm.getSessionMapID()); + /** + * Get ToolAccessMode from HttpRequest parameters. Default value is AUTHOR mode. + * + * @param request + * @return + */ + private ToolAccessMode getAccessMode(HttpServletRequest request) { + ToolAccessMode mode; + String modeStr = request.getParameter(AttributeNames.ATTR_MODE); + if (StringUtils.equalsIgnoreCase(modeStr, ToolAccessMode.TEACHER.toString())) { + mode = ToolAccessMode.TEACHER; + } else { + mode = ToolAccessMode.AUTHOR; } + return mode; + } + + /** + * Retrieves a List of attachments from the map using the key. + * + * @param key + * @param map + * @return + */ + private List getAttList(String key, SessionMap map) { + List list = (List) map.get(key); + return list; + } + + /** + * Retrieve the SessionMap from the HttpSession. + * + * @param request + * @param authForm + * @return + */ + private SessionMap getSessionMap(HttpServletRequest request, AuthoringForm authForm) { + return (SessionMap) request.getSession().getAttribute(authForm.getSessionMapID()); + } } \ No newline at end of file Index: lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/web/actions/AuthoringNotebookConditionAction.java =================================================================== diff -u --- lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/web/actions/AuthoringNotebookConditionAction.java (revision 0) +++ lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/web/actions/AuthoringNotebookConditionAction.java (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -0,0 +1,413 @@ +/**************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * License Information: http://lamsfoundation.org/licensing/lams/2.0/ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2.0 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA + * + * http://www.gnu.org/licenses/gpl.txt + * **************************************************************** + */ + +package org.lamsfoundation.lams.tool.notebook.web.actions; + +import java.util.ArrayList; +import java.util.List; +import java.util.SortedSet; +import java.util.TreeSet; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.math.NumberUtils; +import org.apache.struts.action.Action; +import org.apache.struts.action.ActionErrors; +import org.apache.struts.action.ActionForm; +import org.apache.struts.action.ActionForward; +import org.apache.struts.action.ActionMapping; +import org.apache.struts.action.ActionMessage; +import org.apache.struts.action.ActionMessages; +import org.lamsfoundation.lams.tool.notebook.model.NotebookCondition; +import org.lamsfoundation.lams.tool.notebook.service.INotebookService; +import org.lamsfoundation.lams.tool.notebook.service.NotebookServiceProxy; +import org.lamsfoundation.lams.tool.notebook.util.NotebookConditionComparator; +import org.lamsfoundation.lams.tool.notebook.util.NotebookConstants; +import org.lamsfoundation.lams.tool.notebook.util.NotebookException; +import org.lamsfoundation.lams.tool.notebook.web.forms.AuthoringForm; +import org.lamsfoundation.lams.tool.notebook.web.forms.NotebookConditionForm; +import org.lamsfoundation.lams.util.WebUtil; +import org.lamsfoundation.lams.web.util.SessionMap; + +/** + * Auxiliary action in author mode. It contains operations with NotebookCondition. The rest of operations are located in + * AuthoringAction action. + * + * @author Marcin Cieslak + * @see org.lamsfoundation.lams.tool.notebook.web.action.AuthoringAction + * + */ +public class AuthoringNotebookConditionAction extends Action { + public INotebookService notebookService; + + @Override + public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) throws Exception { + + String param = mapping.getParameter(); + + if (param.equals("newConditionInit")) { + return newConditionInit(mapping, form, request, response); + } + if (param.equals("editCondition")) { + return editCondition(mapping, form, request, response); + } + if (param.equals("saveOrUpdateCondition")) { + return saveOrUpdateCondition(mapping, form, request, response); + } + if (param.equals("removeCondition")) { + return removeCondition(mapping, form, request, response); + } + if (param.equals("upCondition")) { + return upCondition(mapping, form, request, response); + } + if (param.equals("downCondition")) { + return downCondition(mapping, form, request, response); + } + + return null; + } + + /** + * Display empty page for new taskList item. + * + * @param mapping + * @param form + * @param request + * @param response + * @return + */ + private ActionForward newConditionInit(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { + String sessionMapID = WebUtil.readStrParam(request, NotebookConstants.ATTR_SESSION_MAP_ID); + ((NotebookConditionForm) form).setSessionMapID(sessionMapID); + ((NotebookConditionForm) form).setOrderId(-1); + return mapping.findForward("addcondition"); + } + + /** + * Display edit page for existed taskList item. + * + * @param mapping + * @param form + * @param request + * @param response + * @return + */ + private ActionForward editCondition(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { + + NotebookConditionForm notebookConditionForm = (NotebookConditionForm) form; + String sessionMapID = notebookConditionForm.getSessionMapID(); + SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); + + int orderId = NumberUtils.stringToInt(request.getParameter(NotebookConstants.PARAM_ORDER_ID), -1); + NotebookCondition condition = null; + if (orderId != -1) { + SortedSet conditionSet = getNotebookConditionSet(sessionMap); + List conditionList = new ArrayList(conditionSet); + condition = conditionList.get(orderId); + if (condition != null) { + populateConditionToForm(orderId, condition, (NotebookConditionForm) form, request); + } + } + return condition == null ? null : mapping.findForward("addcondition"); + } + + /** + * This method will get necessary information from taskList item form and save or update into + * HttpSession NotebookItemList. Notice, this save is not persist them into database, just save + * HttpSession temporarily. Only they will be persist when the entire authoring page is being + * persisted. + * + * @param mapping + * @param form + * @param request + * @param response + * @return + * @throws ServletException + */ + private ActionForward saveOrUpdateCondition(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { + + NotebookConditionForm conditionForm = (NotebookConditionForm) form; + ActionErrors errors = validateNotebookCondition(conditionForm, request); + + if (!errors.isEmpty()) { + this.addErrors(request, errors); + return mapping.findForward("addcondition"); + } + + try { + extractFormToNotebookCondition(request, conditionForm); + } catch (Exception e) { + // any upload exception will display as normal error message rather then throw exception directly + errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(NotebookConstants.ERROR_MSG_CONDITION, e + .getMessage())); + if (!errors.isEmpty()) { + this.addErrors(request, errors); + return mapping.findForward("addcondition"); + } + } + // set session map ID so that itemlist.jsp can get sessionMAP + request.setAttribute(NotebookConstants.ATTR_SESSION_MAP_ID, conditionForm.getSessionMapID()); + // return null to close this window + return mapping.findForward(NotebookConstants.SUCCESS); + } + + /** + * Remove taskList item from HttpSession list and update page display. As authoring rule, all persist only happen + * when user submit whole page. So this remove is just impact HttpSession values. + * + * @param mapping + * @param form + * @param request + * @param response + * @return + */ + private ActionForward removeCondition(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { + + // get back sessionMAP + String sessionMapID = WebUtil.readStrParam(request, NotebookConstants.ATTR_SESSION_MAP_ID); + SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); + + int orderId = NumberUtils.stringToInt(request.getParameter(NotebookConstants.PARAM_ORDER_ID), -1); + if (orderId != -1) { + SortedSet conditionSet = getNotebookConditionSet(sessionMap); + List conditionList = new ArrayList(conditionSet); + NotebookCondition condition = conditionList.remove(orderId); + conditionSet.clear(); + conditionSet.addAll(conditionList); + // add to delList + List delList = getDeletedNotebookConditionList(sessionMap); + delList.add(condition); + } + + request.setAttribute(NotebookConstants.ATTR_SESSION_MAP_ID, sessionMapID); + return mapping.findForward(NotebookConstants.SUCCESS); + } + + /** + * Move up current item. + * + * @param mapping + * @param form + * @param request + * @param response + * @return + */ + private ActionForward upCondition(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { + return switchItem(mapping, request, true); + } + + /** + * Move down current item. + * + * @param mapping + * @param form + * @param request + * @param response + * @return + */ + private ActionForward downCondition(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { + return switchItem(mapping, request, false); + } + + private ActionForward switchItem(ActionMapping mapping, HttpServletRequest request, boolean up) { + // get back sessionMAP + String sessionMapID = WebUtil.readStrParam(request, NotebookConstants.ATTR_SESSION_MAP_ID); + SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); + + int orderId = NumberUtils.stringToInt(request.getParameter(NotebookConstants.PARAM_ORDER_ID), -1); + if (orderId != -1) { + SortedSet conditionSet = getNotebookConditionSet(sessionMap); + List conditionList = new ArrayList(conditionSet); + // get current and the target item, and switch their sequnece + NotebookCondition condition = conditionList.get(orderId); + NotebookCondition repCondition; + if (up) { + repCondition = conditionList.get(--orderId); + } else { + repCondition = conditionList.get(++orderId); + } + int upSeqId = repCondition.getOrderId(); + repCondition.setOrderId(condition.getOrderId()); + condition.setOrderId(upSeqId); + + // put back list, it will be sorted again + conditionSet.clear(); + conditionSet.addAll(conditionList); + } + + request.setAttribute(NotebookConstants.ATTR_SESSION_MAP_ID, sessionMapID); + return mapping.findForward(NotebookConstants.SUCCESS); + } + + // ************************************************************************************* + // Private methods for internal needs + // ************************************************************************************* + + /** + * List save current taskList items. + * + * @param request + * @return + */ + private SortedSet getNotebookConditionSet(SessionMap sessionMap) { + SortedSet set = (SortedSet) sessionMap + .get(NotebookConstants.ATTR_CONDITION_SET); + if (set == null) { + set = new TreeSet(new NotebookConditionComparator()); + sessionMap.put(NotebookConstants.ATTR_CONDITION_SET, set); + } + return set; + } + + /** + * List save deleted taskList items, which could be persisted or non-persisted items. + * + * @param request + * @return + */ + private List getDeletedNotebookConditionList(SessionMap sessionMap) { + return getListFromSession(sessionMap, NotebookConstants.ATTR_DELETED_CONDITION_LIST); + } + + /** + * Get java.util.List from HttpSession by given name. + * + * @param request + * @param name + * @return + */ + private List getListFromSession(SessionMap sessionMap, String name) { + List list = (List) sessionMap.get(name); + if (list == null) { + list = new ArrayList(); + sessionMap.put(name, list); + } + return list; + } + + /** + * This method will populate taskList item information to its form for edit use. + * + * @param orderId + * @param condition + * @param form + * @param request + */ + private void populateConditionToForm(int orderId, NotebookCondition condition, NotebookConditionForm form, + HttpServletRequest request) { + form.populateForm(condition); + if (orderId >= 0) { + form.setOrderId(orderId + 1); + } + } + + /** + * Extract form content to taskListContent. + * + * @param request + * @param form + * @throws NotebookException + */ + private void extractFormToNotebookCondition(HttpServletRequest request, NotebookConditionForm form) + throws Exception { + /* + * BE CAREFUL: This method will copy necessary info from request form to a old or new NotebookItem instance. It + * gets all info EXCEPT NotebookItem.createDate and NotebookItem.createBy, which need be set when persisting + * this taskList item. + */ + + SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(form.getSessionMapID()); + // check whether it is "edit(old item)" or "add(new item)" + SortedSet conditionSet = getNotebookConditionSet(sessionMap); + int orderId = form.getOrderId(); + NotebookCondition condition = null; + + if (orderId == -1) { // add + String properConditionName = getNotebookService().createConditionName(conditionSet); + condition = form.extractCondition(); + condition.setName(properConditionName); + int maxSeq = 1; + if (conditionSet != null && conditionSet.size() > 0) { + NotebookCondition last = conditionSet.last(); + maxSeq = last.getOrderId() + 1; + } + condition.setOrderId(maxSeq); + conditionSet.add(condition); + } else { // edit + List conditionList = new ArrayList(conditionSet); + condition = conditionList.get(orderId - 1); + form.extractCondition(condition); + } + } + + /** + * Validate taskListCondition + * + * @param conditionForm + * @return + */ + private ActionErrors validateNotebookCondition(NotebookConditionForm conditionForm, HttpServletRequest request) { + ActionErrors errors = new ActionErrors(); + + String formConditionName = conditionForm.getDisplayName(); + if (StringUtils.isBlank(formConditionName)) { + errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(NotebookConstants.ERROR_MSG_NAME_BLANK)); + } else { + + Integer formConditionSequenceId = conditionForm.getOrderId(); + + String sessionMapID = conditionForm.getSessionMapID(); + SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); + SortedSet conditionList = getNotebookConditionSet(sessionMap); + for (NotebookCondition condition : conditionList) { + if (formConditionName.equals(condition.getName()) + && !formConditionSequenceId.equals(new Integer(condition.getOrderId() - 1).toString())) { + errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage( + NotebookConstants.ERROR_MSG_NAME_DUPLICATED)); + break; + } + } + } + return errors; + } + + private ActionMessages validate(AuthoringForm taskListForm, ActionMapping mapping, HttpServletRequest request) { + return new ActionMessages(); + } + + private INotebookService getNotebookService() { + if (notebookService == null) { + notebookService = NotebookServiceProxy.getNotebookService(this.getServlet().getServletContext()); + } + return notebookService; + } +} \ No newline at end of file Index: lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/web/forms/NotebookConditionForm.java =================================================================== diff -u --- lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/web/forms/NotebookConditionForm.java (revision 0) +++ lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/web/forms/NotebookConditionForm.java (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -0,0 +1,61 @@ +package org.lamsfoundation.lams.tool.notebook.web.forms; + +import org.lamsfoundation.lams.tool.notebook.model.NotebookCondition; +import org.lamsfoundation.lams.web.TextSearchActionForm; + +/** + * A text search form with additional parameters for Q&A needs. + * + * @author Marcin Cieslak + * @struts.form name="notebookConditionForm" + */ +public class NotebookConditionForm extends TextSearchActionForm { + + private Integer orderId; + private String displayName; + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String name) { + displayName = name; + } + + public NotebookConditionForm() { + } + + public void populateForm(NotebookCondition condition) { + super.populateForm(condition); + setOrderId(condition.getOrderId()); + setDisplayName(condition.getDisplayName()); + } + + public Integer getOrderId() { + return orderId; + } + + public void setOrderId(Integer orderId) { + this.orderId = orderId; + } + + /** + * Fills a new NotebookCondition with data contained in this form. Note that some cruicial data is missing, so the + * condition is NOT complete. + * + * @return created condition + */ + public NotebookCondition extractCondition() { + return new NotebookCondition(null, null, getOrderId(), null, getDisplayName(), "OUTPUT_STRING", null, null, + null, getAllWords(), getPhrase(), getAnyWords(), getExcludedWords()); + } + + public void extractCondition(NotebookCondition condition) { + condition.setOrderId(getOrderId()); + condition.setDisplayName(getDisplayName()); + condition.setAllWords(getAllWords()); + condition.setPhrase(getPhrase()); + condition.setAnyWords(getAnyWords()); + condition.setExcludedWords(getExcludedWords()); + } +} \ No newline at end of file Index: lams_tool_notebook/web/WEB-INF/lams.tld =================================================================== diff -u -rc5b655c3c11fa9d9b1d76e0ef602acf6363e45f9 -re64f3e306f3139c78e8917240c33ea232e75e848 --- lams_tool_notebook/web/WEB-INF/lams.tld (.../lams.tld) (revision c5b655c3c11fa9d9b1d76e0ef602acf6363e45f9) +++ lams_tool_notebook/web/WEB-INF/lams.tld (.../lams.tld) (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -467,6 +467,10 @@ ImgButtonWrapper /WEB-INF/tags/ImgButtonWrapper.tag + + TextSearch + /WEB-INF/tags/TextSearch.tag + textarea org.lamsfoundation.lams.web.tag.LAMSMultiLinesTextareaTag Index: lams_tool_notebook/web/WEB-INF/tags/TextSearch.tag =================================================================== diff -u --- lams_tool_notebook/web/WEB-INF/tags/TextSearch.tag (revision 0) +++ lams_tool_notebook/web/WEB-INF/tags/TextSearch.tag (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -0,0 +1,136 @@ +<% +/**************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * License Information: http://lamsfoundation.org/licensing/lams/2.0/ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2.0 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + * USA + * + * http://www.gnu.org/licenses/gpl.txt + * **************************************************************** + */ + + /** + * TextSearch.tag + * Author: Marcin Cieslak + * Description: Displays form for creating text search conditions. + */ + + %> +<%@ tag body-content="scriptless" %> +<%@ taglib uri="tags-core" prefix="c" %> +<%@ taglib uri="tags-fmt" prefix="fmt" %> +<%@ taglib uri="tags-html" prefix="html" %> +<%@ taglib uri="tags-lams" prefix="lams" %> + +<%-- Required attributes --%> +<%@ attribute name="sessionMapID" required="true" rtexprvalue="true" %> +<%@ attribute name="wrapInFormTag" required="true" rtexprvalue="true" %> + +<%-- Optional attributes --%> +<%@ attribute name="action" required="false" rtexprvalue="true" %> +<%@ attribute name="formID" required="false" rtexprvalue="true" %> +<%@ attribute name="headingLabelKey" required="false" rtexprvalue="true" %> +<%@ attribute name="allWordsLabelKey" required="false" rtexprvalue="true" %> +<%@ attribute name="phraseLabelKey" required="false" rtexprvalue="true" %> +<%@ attribute name="anyWordsLabelKey" required="false" rtexprvalue="true" %> +<%@ attribute name="excludedWordsLabelKey" required="false" rtexprvalue="true" %> +<%@ attribute name="saveButtonLabelKey" required="false" rtexprvalue="true" %> +<%@ attribute name="cancelButtonLabelKey" required="false" rtexprvalue="true" %> +<%@ attribute name="cancelAction" required="false" rtexprvalue="true" %> + +<%-- Default value for message key --%> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + +

+ + + + + + + + + + + + + + + + + +
+ + + +
+ + + +
+ + + +
+ + + +
+ + + + + + + + + + \ No newline at end of file Index: lams_tool_notebook/web/WEB-INF/web.xml =================================================================== diff -u -re851ecbb7a28dba597688df7f4466b2ab603405c -re64f3e306f3139c78e8917240c33ea232e75e848 --- lams_tool_notebook/web/WEB-INF/web.xml (.../web.xml) (revision e851ecbb7a28dba597688df7f4466b2ab603405c) +++ lams_tool_notebook/web/WEB-INF/web.xml (.../web.xml) (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -17,6 +17,7 @@ classpath:/org/lamsfoundation/lams/learning/learningApplicationContext.xml classpath:/org/lamsfoundation/lams/contentrepository/applicationContext.xml classpath:/org/lamsfoundation/lams/tool/notebook/notebookApplicationContext.xml + classpath:/org/lamsfoundation/lams/tool/notebook/dbupdates/autopatchContext.xml @@ -63,8 +64,8 @@ - org.lamsfoundation.lams.web.SessionListener - + org.lamsfoundation.lams.web.session.SetMaxTimeoutListener + @@ -144,6 +145,10 @@ /exportPortfolio + + 120 + + + <%@ include file="/common/messages.jsp"%> + + +

+ +

+ +
+ +
+
+ +
+ <%-- Text search form fields are being included --%> + +
+ + + + + + + Index: lams_tool_notebook/web/pages/authoring/authoring.jsp =================================================================== diff -u -rbd376d76233dad7d0a0775762385918fcbb96f4c -re64f3e306f3139c78e8917240c33ea232e75e848 --- lams_tool_notebook/web/pages/authoring/authoring.jsp (.../authoring.jsp) (revision bd376d76233dad7d0a0775762385918fcbb96f4c) +++ lams_tool_notebook/web/pages/authoring/authoring.jsp (.../authoring.jsp) (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -24,6 +24,7 @@ + @@ -57,6 +58,8 @@ +
+ + + + + + + +
+

+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ +
+ ${status.index + 1} + + ${condition.displayName} + + + " + onclick="upCondition(${status.index},'${sessionMapID}')"> + + "> + + + + + + "> + + + " + onclick="downCondition(${status.index},'${sessionMapID}')"> + + + " + onclick="editCondition(${status.index},'${sessionMapID}')" /> + + " + onclick="deleteCondition(${status.index},'${sessionMapID}')" /> +
+
+ +<%-- This script will works when a new resoruce Condition submit in order to refresh "TaskList List" panel. --%> + Index: lams_tool_notebook/web/pages/authoring/conditions.jsp =================================================================== diff -u --- lams_tool_notebook/web/pages/authoring/conditions.jsp (revision 0) +++ lams_tool_notebook/web/pages/authoring/conditions.jsp (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -0,0 +1,110 @@ +<%@ include file="/common/taglibs.jsp"%> + + + + + +
+ + <%@ include file="/pages/authoring/conditionList.jsp"%> +
+ +

+ ');" class="button-add-item"> + +

+ + +

+ +

Index: lams_tool_notebook/web/pages/authoring/headItems.jsp =================================================================== diff -u -r718784fe6546fcb251380d712a2c81c6bb29e029 -re64f3e306f3139c78e8917240c33ea232e75e848 --- lams_tool_notebook/web/pages/authoring/headItems.jsp (.../headItems.jsp) (revision 718784fe6546fcb251380d712a2c81c6bb29e029) +++ lams_tool_notebook/web/pages/authoring/headItems.jsp (.../headItems.jsp) (revision e64f3e306f3139c78e8917240c33ea232e75e848) @@ -1,9 +1,10 @@ <%@ include file="/common/taglibs.jsp"%> - + + + - \ No newline at end of file + + \ No newline at end of file