Index: lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/ChatService.java =================================================================== RCS file: /usr/local/cvsroot/lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/ChatService.java,v diff -u -r1.44 -r1.45 --- lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/ChatService.java 13 Aug 2008 05:00:44 -0000 1.44 +++ lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/ChatService.java 15 Oct 2008 02:18:45 -0000 1.45 @@ -117,1122 +117,1021 @@ /** * An implementation of the IChatService 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 ChatService implements ToolSessionManager, ToolContentManager, - ToolContentImport102Manager, IChatService { +public class ChatService implements ToolSessionManager, ToolContentManager, ToolContentImport102Manager, IChatService { - static Logger logger = Logger.getLogger(ChatService.class.getName()); + static Logger logger = Logger.getLogger(ChatService.class.getName()); - private IChatDAO chatDAO = null; + private IChatDAO chatDAO = null; - private IChatSessionDAO chatSessionDAO = null; + private IChatSessionDAO chatSessionDAO = null; - private IChatUserDAO chatUserDAO = null; + private IChatUserDAO chatUserDAO = null; - private IChatMessageDAO chatMessageDAO = null; + private IChatMessageDAO chatMessageDAO = null; - private IChatAttachmentDAO chatAttachmentDAO = null; + private IChatAttachmentDAO chatAttachmentDAO = null; - private ILearnerService learnerService; + private ILearnerService learnerService; - private ILamsToolService toolService; + private ILamsToolService toolService; - private IToolContentHandler chatToolContentHandler = null; + private IToolContentHandler chatToolContentHandler = 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; - // - private IdentifierGenerator idGenerator; + // + private IdentifierGenerator idGenerator; - public ChatService() { - super(); + public ChatService() { + super(); - // configure the indentifier generator - idGenerator = new UUIDHexGenerator(); - ((Configurable) idGenerator).configure(Hibernate.STRING, - new Properties(), null); + // configure the indentifier generator + idGenerator = new UUIDHexGenerator(); + ((Configurable) idGenerator).configure(Hibernate.STRING, new Properties(), null); + } + + /* 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); } - /* ************ 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); - } + ChatSession session = new ChatSession(); + session.setSessionId(toolSessionId); + session.setSessionName(toolSessionName); - ChatSession session = new ChatSession(); - session.setSessionId(toolSessionId); - session.setSessionName(toolSessionName); + String jabberRoom = (String) idGenerator.generate(null, null) + "@" + + Configuration.get(ConfigurationKeys.XMPP_CONFERENCE); + session.setJabberRoom(jabberRoom); - String jabberRoom = (String) idGenerator.generate(null, null) + "@" - + Configuration.get(ConfigurationKeys.XMPP_CONFERENCE); - session.setJabberRoom(jabberRoom); + // the jabber room is created when the first learner starts + session.setRoomCreated(false); - // the jabber room is created when the first learner starts - session.setRoomCreated(false); + Chat chat = chatDAO.getByContentId(toolContentId); + session.setChat(chat); + chatSessionDAO.saveOrUpdate(session); + } - Chat chat = chatDAO.getByContentId(toolContentId); - session.setChat(chat); - chatSessionDAO.saveOrUpdate(session); - } + public String leaveToolSession(Long toolSessionId, Long learnerId) throws DataMissingException, ToolException { - public String leaveToolSession(Long toolSessionId, Long learnerId) - throws DataMissingException, ToolException { + // TODO issues with session status/start date/ end date. Need to + // reimplement method. - // TODO issues with session status/start date/ end date. Need to - // reimplement method. + // if (logger.isDebugEnabled()) { + // logger.debug("entering method leaveToolSession:" + // + " toolSessionId=" + toolSessionId + " learnerId=" + // + learnerId); + // } + // + // if (toolSessionId == null) { + // logger + // .error("Fail to leave tool Session based on null tool session id."); + // throw new ToolException( + // "Fail to remove tool Session based on null tool session id."); + // } + // if (learnerId == null) { + // logger.error("Fail to leave tool Session based on null learner."); + // throw new ToolException( + // "Fail to remove tool Session based on null learner."); + // } + // + // ChatSession session = chatSessionDAO.getBySessionId(toolSessionId); + // if (session != null) { + // session.setStatus(ChatConstants.SESSION_COMPLETED); + // chatSessionDAO.saveOrUpdate(session); + // } else { + // logger + // .error("Fail to leave tool Session.Could not find submit file " + // + "session by given session id: " + toolSessionId); + // throw new DataMissingException( + // "Fail to leave tool Session." + // + "Could not find submit file session by given session id: " + // + toolSessionId); + // } + return learnerService.completeToolSession(toolSessionId, learnerId); + } - // if (logger.isDebugEnabled()) { - // logger.debug("entering method leaveToolSession:" - // + " toolSessionId=" + toolSessionId + " learnerId=" - // + learnerId); - // } - // - // if (toolSessionId == null) { - // logger - // .error("Fail to leave tool Session based on null tool session id."); - // throw new ToolException( - // "Fail to remove tool Session based on null tool session id."); - // } - // if (learnerId == null) { - // logger.error("Fail to leave tool Session based on null learner."); - // throw new ToolException( - // "Fail to remove tool Session based on null learner."); - // } - // - // ChatSession session = chatSessionDAO.getBySessionId(toolSessionId); - // if (session != null) { - // session.setStatus(ChatConstants.SESSION_COMPLETED); - // chatSessionDAO.saveOrUpdate(session); - // } else { - // logger - // .error("Fail to leave tool Session.Could not find submit file " - // + "session by given session id: " + toolSessionId); - // throw new DataMissingException( - // "Fail to leave tool Session." - // + "Could not find submit file session by given session id: " - // + toolSessionId); - // } - return learnerService.completeToolSession(toolSessionId, learnerId); - } + public ToolSessionExportOutputData exportToolSession(Long toolSessionId) throws DataMissingException, ToolException { + // TODO Auto-generated method stub + return null; + } - public ToolSessionExportOutputData exportToolSession(Long toolSessionId) - throws DataMissingException, ToolException { - // TODO Auto-generated method stub - return null; - } + public ToolSessionExportOutputData exportToolSession(List toolSessionIds) throws DataMissingException, + ToolException { + // TODO Auto-generated method stub + return null; + } - public ToolSessionExportOutputData exportToolSession(List toolSessionIds) - throws DataMissingException, ToolException { - // TODO Auto-generated method stub - return null; - } + public void removeToolSession(Long toolSessionId) throws DataMissingException, ToolException { + chatSessionDAO.deleteBySessionID(toolSessionId); + // TODO check if cascade worked + // do we need to remove room on jabber server ? + } - public void removeToolSession(Long toolSessionId) - throws DataMissingException, ToolException { - chatSessionDAO.deleteBySessionID(toolSessionId); - // TODO check if cascade worked - // do we need to remove room on jabber server ? - } + /** + * Get the tool output for the given tool output names. + * + * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.util.List, java.lang.Long, + * java.lang.Long) + */ + public SortedMap getToolOutput(List names, Long toolSessionId, Long learnerId) { + return new TreeMap(); + } - /** - * Get the tool output for the given tool output names. - * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.util.List, java.lang.Long, java.lang.Long) - */ - public SortedMap getToolOutput(List names, - Long toolSessionId, Long learnerId) { - return new TreeMap(); - } + /** + * Get the tool output for the given tool output name. + * + * @see org.lamsfoundation.lams.tool.ToolSessionManager#getToolOutput(java.lang.String, java.lang.Long, + * java.lang.Long) + */ + public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { + return null; + } - /** - * 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; - } + /* Methods from ToolContentManager */ + public void copyToolContent(Long fromContentId, Long toContentId) throws ToolException { - /* ************ Methods from ToolContentManager ************************* */ + if (logger.isDebugEnabled()) { + logger.debug("entering method copyToolContent:" + " fromContentId=" + fromContentId + " toContentId=" + + toContentId); + } - public void copyToolContent(Long fromContentId, Long toContentId) - throws ToolException { - - if (logger.isDebugEnabled()) { - logger.debug("entering method copyToolContent:" + " fromContentId=" - + fromContentId + " toContentId=" + toContentId); - } - - if (toContentId == null) { - String error = "Failed to copy tool content: toContentID is null"; - throw new ToolException(error); - } - - Chat fromContent = null; - if (fromContentId != null) { - fromContent = chatDAO.getByContentId(fromContentId); - } - if (fromContent == null) { - // create the fromContent using the default tool content - fromContent = getDefaultContent(); - } - Chat toContent = Chat.newInstance(fromContent, toContentId, - chatToolContentHandler); - chatDAO.saveOrUpdate(toContent); + if (toContentId == null) { + String error = "Failed to copy tool content: toContentID is null"; + throw new ToolException(error); } - public void setAsDefineLater(Long toolContentId, boolean value) - throws DataMissingException, ToolException { - Chat chat = chatDAO.getByContentId(toolContentId); - if (chat == null) { - throw new ToolException("Could not find tool with toolContentID: "+ toolContentId); - } - chat.setDefineLater(value); - chatDAO.saveOrUpdate(chat); + Chat fromContent = null; + if (fromContentId != null) { + fromContent = chatDAO.getByContentId(fromContentId); } + if (fromContent == null) { + // create the fromContent using the default tool content + fromContent = getDefaultContent(); + } + Chat toContent = Chat.newInstance(fromContent, toContentId, chatToolContentHandler); + chatDAO.saveOrUpdate(toContent); + } - public void setAsRunOffline(Long toolContentId, boolean value) - throws DataMissingException, ToolException { - Chat chat = chatDAO.getByContentId(toolContentId); - if(chat == null){ - throw new ToolException("Could not find tool with toolContentID: " + toolContentId); - } - chat.setRunOffline(value); - chatDAO.saveOrUpdate(chat); + public void setAsDefineLater(Long toolContentId, boolean value) throws DataMissingException, ToolException { + Chat chat = chatDAO.getByContentId(toolContentId); + if (chat == null) { + throw new ToolException("Could not find tool with toolContentID: " + toolContentId); } + chat.setDefineLater(value); + chatDAO.saveOrUpdate(chat); + } - public void removeToolContent(Long toolContentId, boolean removeSessionData) - throws SessionDataExistsException, ToolException { - // TODO Auto-generated method stub + public void setAsRunOffline(Long toolContentId, boolean value) throws DataMissingException, ToolException { + Chat chat = chatDAO.getByContentId(toolContentId); + if (chat == null) { + throw new ToolException("Could not find tool with toolContentID: " + toolContentId); } + chat.setRunOffline(value); + chatDAO.saveOrUpdate(chat); + } - /** - * 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 removeToolContent(Long toolContentId, boolean removeSessionData) throws SessionDataExistsException, + ToolException { + // TODO Auto-generated method stub + } - public void exportToolContent(Long toolContentId, String rootPath) - throws DataMissingException, ToolException { - Chat chat = chatDAO.getByContentId(toolContentId); - if (chat == null) - chat = getDefaultContent(); - if (chat == null) - throw new DataMissingException( - "Unable to find default content for the chat tool"); + /** + * 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 + */ - // set ResourceToolContentHandler as null to avoid copy file node in - // repository again. - chat = Chat.newInstance(chat, toolContentId, null); - chat.setToolContentHandler(null); - chat.setChatSessions(null); - Set atts = chat.getChatAttachments(); - for (ChatAttachment att : atts) { - att.setChat(null); - } - try { - exportContentService - .registerFileClassForExport(ChatAttachment.class.getName(), - "fileUuid", "fileVersionId"); - exportContentService.exportToolContent(toolContentId, chat, - chatToolContentHandler, rootPath); - } catch (ExportToolContentException e) { - throw new ToolException(e); - } + public void exportToolContent(Long toolContentId, String rootPath) throws DataMissingException, ToolException { + Chat chat = chatDAO.getByContentId(toolContentId); + if (chat == null) + chat = getDefaultContent(); + if (chat == null) + throw new DataMissingException("Unable to find default content for the chat tool"); + + // set ResourceToolContentHandler as null to avoid copy file node in + // repository again. + chat = Chat.newInstance(chat, toolContentId, null); + chat.setToolContentHandler(null); + chat.setChatSessions(null); + Set atts = chat.getChatAttachments(); + for (ChatAttachment att : atts) { + att.setChat(null); } + try { + exportContentService + .registerFileClassForExport(ChatAttachment.class.getName(), "fileUuid", "fileVersionId"); + exportContentService.exportToolContent(toolContentId, chat, chatToolContentHandler, rootPath); + } catch (ExportToolContentException e) { + throw new ToolException(e); + } + } - /** - * 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( - ChatAttachment.class.getName(), "fileUuid", - "fileVersionId", "fileName", "fileType", null, null); + /** + * 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(ChatAttachment.class.getName(), "fileUuid", + "fileVersionId", "fileName", "fileType", null, null); - Object toolPOJO = exportContentService.importToolContent( - toolContentPath, chatToolContentHandler, fromVersion, - toVersion); - if (!(toolPOJO instanceof Chat)) - throw new ImportToolContentException( - "Import Chat tool content failed. Deserialized object is " - + toolPOJO); - Chat chat = (Chat) toolPOJO; + Object toolPOJO = exportContentService.importToolContent(toolContentPath, chatToolContentHandler, + fromVersion, toVersion); + if (!(toolPOJO instanceof Chat)) + throw new ImportToolContentException("Import Chat tool content failed. Deserialized object is " + + toolPOJO); + Chat chat = (Chat) toolPOJO; - // reset it to new toolContentId - chat.setToolContentId(toolContentId); - chat.setCreateBy(new Long(newUserUid.longValue())); + // reset it to new toolContentId + chat.setToolContentId(toolContentId); + chat.setCreateBy(new Long(newUserUid.longValue())); - chatDAO.saveOrUpdate(chat); - } catch (ImportToolContentException e) { - throw new ToolException(e); - } + chatDAO.saveOrUpdate(chat); + } catch (ImportToolContentException e) { + throw new ToolException(e); } - - /** Get the definitions for possible output for an activity, based on the toolContentId. These may be definitions that are always - * available for the tool (e.g. number of marks for Multiple Choice) or a custom definition created for a particular activity - * such as the answer to the third question contains the word Koala and hence the need for the toolContentId + } + + /** + * Get the definitions for possible output for an activity, based on the toolContentId. These may be definitions + * that are always available for the tool (e.g. number of marks for Multiple Choice) or a custom definition created + * for a particular activity such as the answer to the third question contains the word Koala and hence the need for + * the toolContentId + * * @return SortedMap of ToolOutputDefinitions with the key being the name of each definition */ - public SortedMap getToolOutputDefinitions(Long toolContentId) throws ToolException { - return new TreeMap(); - } - + public SortedMap getToolOutputDefinitions(Long toolContentId) throws ToolException { + return new TreeMap(); + } - /* ********** IChatService Methods ************************************** */ - public Long getDefaultContentIdBySignature(String toolSignature) { - Long toolContentId = null; - toolContentId = new Long(toolService - .getToolDefaultContentIdBySignature(toolSignature)); - if (toolContentId == null) { - String error = "Could not retrieve default content id for this tool"; - logger.error(error); - throw new ChatException(error); - } - return toolContentId; + /* IChatService Methods */ + public Long getDefaultContentIdBySignature(String toolSignature) { + Long toolContentId = null; + toolContentId = new Long(toolService.getToolDefaultContentIdBySignature(toolSignature)); + if (toolContentId == null) { + String error = "Could not retrieve default content id for this tool"; + logger.error(error); + throw new ChatException(error); } + return toolContentId; + } - public Chat getDefaultContent() { - Long defaultContentID = getDefaultContentIdBySignature(ChatConstants.TOOL_SIGNATURE); - Chat defaultContent = getChatByContentId(defaultContentID); - if (defaultContent == null) { - String error = "Could not retrieve default content record for this tool"; - logger.error(error); - throw new ChatException(error); - } - return defaultContent; + public Chat getDefaultContent() { + Long defaultContentID = getDefaultContentIdBySignature(ChatConstants.TOOL_SIGNATURE); + Chat defaultContent = getChatByContentId(defaultContentID); + if (defaultContent == null) { + String error = "Could not retrieve default content record for this tool"; + logger.error(error); + throw new ChatException(error); } + return defaultContent; + } - public Chat copyDefaultContent(Long newContentID) { + public Chat copyDefaultContent(Long newContentID) { - if (newContentID == null) { - String error = "Cannot copy the Chat tools default content: + " - + "newContentID is null"; - logger.error(error); - throw new ChatException(error); - } - - Chat defaultContent = getDefaultContent(); - // create new chat using the newContentID - Chat newContent = new Chat(); - newContent = Chat.newInstance(defaultContent, newContentID, - chatToolContentHandler); - chatDAO.saveOrUpdate(newContent); - return newContent; + if (newContentID == null) { + String error = "Cannot copy the Chat tools default content: + " + "newContentID is null"; + logger.error(error); + throw new ChatException(error); } - public Chat getChatByContentId(Long toolContentID) { - Chat chat = (Chat) chatDAO.getByContentId(toolContentID); - if (chat == null) { - logger.debug("Could not find the content with toolContentID:" - + toolContentID); - } - return chat; - } + Chat defaultContent = getDefaultContent(); + // create new chat using the newContentID + Chat newContent = new Chat(); + newContent = Chat.newInstance(defaultContent, newContentID, chatToolContentHandler); + chatDAO.saveOrUpdate(newContent); + return newContent; + } - public ChatSession getSessionBySessionId(Long toolSessionId) { - ChatSession chatSession = chatSessionDAO.getBySessionId(toolSessionId); - if (chatSession == null) { - logger.debug("Could not find the chat session with toolSessionID:" - + toolSessionId); - } - return chatSession; + public Chat getChatByContentId(Long toolContentID) { + Chat chat = (Chat) chatDAO.getByContentId(toolContentID); + if (chat == null) { + logger.debug("Could not find the content with toolContentID:" + toolContentID); } + return chat; + } - public ChatSession getSessionByJabberRoom(String jabberRoom) { - ChatSession chatSession = chatSessionDAO.getByJabberRoom(jabberRoom); - if (chatSession == null) { - logger.debug("Could not find the chat session with jabberRoom:" - + jabberRoom); - } - return chatSession; + public ChatSession getSessionBySessionId(Long toolSessionId) { + ChatSession chatSession = chatSessionDAO.getBySessionId(toolSessionId); + if (chatSession == null) { + logger.debug("Could not find the chat session with toolSessionID:" + toolSessionId); } + return chatSession; + } - public ChatUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { - return chatUserDAO.getByUserIdAndSessionId(userId, toolSessionId); + public ChatSession getSessionByJabberRoom(String jabberRoom) { + ChatSession chatSession = chatSessionDAO.getByJabberRoom(jabberRoom); + if (chatSession == null) { + logger.debug("Could not find the chat session with jabberRoom:" + jabberRoom); } + return chatSession; + } - public ChatUser getUserByLoginNameAndSessionId(String loginName, - Long toolSessionId) { - return chatUserDAO.getByLoginNameAndSessionId(loginName, toolSessionId); - } + public ChatUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { + return chatUserDAO.getByUserIdAndSessionId(userId, toolSessionId); + } - public ChatUser getUserByJabberIDAndJabberRoom(String jabberID, - String jabberRoom) { - return chatUserDAO.getByJabberIDAndJabberRoom(jabberID, jabberRoom); - } + public ChatUser getUserByLoginNameAndSessionId(String loginName, Long toolSessionId) { + return chatUserDAO.getByLoginNameAndSessionId(loginName, toolSessionId); + } - public ChatUser getUserByUID(Long uid) { - return chatUserDAO.getByUID(uid); - } + public ChatUser getUserByJabberIDAndJabberRoom(String jabberID, String jabberRoom) { + return chatUserDAO.getByJabberIDAndJabberRoom(jabberID, jabberRoom); + } - public ChatUser getUserByJabberNicknameAndSessionID(String jabberNickname, - Long sessionID) { - return chatUserDAO.getByJabberNicknameAndSessionID(jabberNickname, - sessionID); - } + public ChatUser getUserByUID(Long uid) { + return chatUserDAO.getByUID(uid); + } - public List getMessagesForUser(ChatUser chatUser) { - return chatMessageDAO.getForUser(chatUser); - } + public ChatUser getUserByJabberNicknameAndSessionID(String jabberNickname, Long sessionID) { + return chatUserDAO.getByJabberNicknameAndSessionID(jabberNickname, sessionID); + } - public ChatAttachment uploadFileToContent(Long toolContentId, - FormFile file, String type) { - if (file == null || StringUtils.isEmpty(file.getFileName())) - throw new ChatException("Could not find upload file: " + file); + public List getMessagesForUser(ChatUser chatUser) { + return chatMessageDAO.getForUser(chatUser); + } - NodeKey nodeKey = processFile(file, type); + public ChatAttachment uploadFileToContent(Long toolContentId, FormFile file, String type) { + if (file == null || StringUtils.isEmpty(file.getFileName())) + throw new ChatException("Could not find upload file: " + file); - ChatAttachment attachment = new ChatAttachment(); - attachment.setFileType(type); - attachment.setFileUuid(nodeKey.getUuid()); - attachment.setFileVersionId(nodeKey.getVersion()); - attachment.setFileName(file.getFileName()); - attachment.setCreateDate(new Date()); + NodeKey nodeKey = processFile(file, type); - return attachment; - } + ChatAttachment attachment = new ChatAttachment(); + attachment.setFileType(type); + attachment.setFileUuid(nodeKey.getUuid()); + attachment.setFileVersionId(nodeKey.getVersion()); + attachment.setFileName(file.getFileName()); + attachment.setCreateDate(new Date()); - public void deleteFromRepository(Long uuid, Long versionID) - throws ChatException { - ITicket ticket = getRepositoryLoginTicket(); - try { - repositoryService.deleteVersion(ticket, uuid, versionID); - } catch (Exception e) { - throw new ChatException( - "Exception occured while deleting files from" - + " the repository " + e.getMessage()); - } - } + return attachment; + } - public void deleteInstructionFile(Long contentID, Long uuid, - Long versionID, String type) { - chatDAO.deleteInstructionFile(contentID, uuid, versionID, type); - + public void deleteFromRepository(Long uuid, Long versionID) throws ChatException { + ITicket ticket = getRepositoryLoginTicket(); + try { + repositoryService.deleteVersion(ticket, uuid, versionID); + } catch (Exception e) { + throw new ChatException("Exception occured while deleting files from" + " the repository " + e.getMessage()); } + } - public void saveOrUpdateChat(Chat chat) { - updateMessageFilters(chat); - chatDAO.saveOrUpdate(chat); - } + public void deleteInstructionFile(Long contentID, Long uuid, Long versionID, String type) { + chatDAO.deleteInstructionFile(contentID, uuid, versionID, type); - public void saveOrUpdateChatSession(ChatSession chatSession) { - chatSessionDAO.saveOrUpdate(chatSession); - } + } - public void saveOrUpdateChatUser(ChatUser chatUser) { - chatUserDAO.saveOrUpdate(chatUser); - } + public void saveOrUpdateChat(Chat chat) { + updateMessageFilters(chat); + chatDAO.saveOrUpdate(chat); + } - public void saveOrUpdateChatMessage(ChatMessage chatMessage) { - chatMessageDAO.saveOrUpdate(chatMessage); - } + public void saveOrUpdateChatSession(ChatSession chatSession) { + chatSessionDAO.saveOrUpdate(chatSession); + } - public synchronized ChatUser createChatUser(UserDTO user, - ChatSession chatSession) { - ChatUser chatUser = new ChatUser(user, chatSession); - chatUser.setJabberId(createJabberId(user)); - chatUser.setJabberNickname(createJabberNickname(chatUser)); - saveOrUpdateChatUser(chatUser); - return chatUser; - } + public void saveOrUpdateChatUser(ChatUser chatUser) { + chatUserDAO.saveOrUpdate(chatUser); + } - public String createJabberNickname(ChatUser chatUser) { - String desiredJabberNickname = chatUser.getFirstName() + " " - + chatUser.getLastName(); - String jabberNickname = desiredJabberNickname; + public void saveOrUpdateChatMessage(ChatMessage chatMessage) { + chatMessageDAO.saveOrUpdate(chatMessage); + } - boolean valid = false; - int count = 1; + public synchronized ChatUser createChatUser(UserDTO user, ChatSession chatSession) { + ChatUser chatUser = new ChatUser(user, chatSession); + chatUser.setJabberId(createJabberId(user)); + chatUser.setJabberNickname(createJabberNickname(chatUser)); + saveOrUpdateChatUser(chatUser); + return chatUser; + } - // TODO may need max tries to prevent possibly entering infinite loop. - while (!valid) { - if (getUserByJabberNicknameAndSessionID(jabberNickname, chatUser - .getChatSession().getSessionId()) == null) { - // jabberNickname is available - valid = true; - } else { - jabberNickname = desiredJabberNickname + " " + count; - count++; - } - } + public String createJabberNickname(ChatUser chatUser) { + String desiredJabberNickname = chatUser.getFirstName() + " " + chatUser.getLastName(); + String jabberNickname = desiredJabberNickname; - return jabberNickname; + boolean valid = false; + int count = 1; + + // TODO may need max tries to prevent possibly entering infinite loop. + while (!valid) { + if (getUserByJabberNicknameAndSessionID(jabberNickname, chatUser.getChatSession().getSessionId()) == null) { + // jabberNickname is available + valid = true; + } else { + jabberNickname = desiredJabberNickname + " " + count; + count++; + } } - public void createJabberRoom(ChatSession chatSession) { - try { - XMPPConnection.DEBUG_ENABLED = false; - XMPPConnection con = new XMPPConnection(Configuration - .get(ConfigurationKeys.XMPP_DOMAIN)); - - - con.login(Configuration.get(ConfigurationKeys.XMPP_ADMIN), - Configuration.get(ConfigurationKeys.XMPP_PASSWORD)); + return jabberNickname; + } - // Create a MultiUserChat using an XMPPConnection for a room -// String jabberRoom = new Long(System.currentTimeMillis()).toString() -// + "@" -// + Configuration.get(ConfigurationKeys.XMPP_CONFERENCE); + public void createJabberRoom(ChatSession chatSession) { + try { + XMPPConnection.DEBUG_ENABLED = false; + XMPPConnection con = new XMPPConnection(Configuration.get(ConfigurationKeys.XMPP_DOMAIN)); + con.login(Configuration.get(ConfigurationKeys.XMPP_ADMIN), Configuration + .get(ConfigurationKeys.XMPP_PASSWORD)); - MultiUserChat muc = new MultiUserChat(con, chatSession.getJabberRoom()); + // Create a MultiUserChat using an XMPPConnection for a room + // String jabberRoom = new Long(System.currentTimeMillis()).toString() + // + "@" + // + Configuration.get(ConfigurationKeys.XMPP_CONFERENCE); - // Create the room - muc.create("nick"); + MultiUserChat muc = new MultiUserChat(con, chatSession.getJabberRoom()); - // Get the the room's configuration form - Form form = muc.getConfigurationForm(); + // Create the room + muc.create("nick"); - // Create a new form to submit based on the original form - Form submitForm = form.createAnswerForm(); + // Get the the room's configuration form + Form form = muc.getConfigurationForm(); - // Add default answers to the form to submit - for (Iterator fields = form.getFields(); fields.hasNext();) { - FormField field = (FormField) fields.next(); - if (!FormField.TYPE_HIDDEN.equals(field.getType()) - && field.getVariable() != null) { - // Sets the default value as the answer - submitForm.setDefaultAnswer(field.getVariable()); - } - } + // Create a new form to submit based on the original form + Form submitForm = form.createAnswerForm(); - // Sets the new owner of the room - submitForm.setAnswer("muc#roomconfig_persistentroom", true); - // Send the completed form (with default values) to the server to - // configure the room - muc.sendConfigurationForm(submitForm); - - chatSession.setRoomCreated(true); - con.close(); - - } catch (XMPPException e) { - logger.error(e); - logger.error(e.getXMPPError()); - // TODO should we continue ? + // Add default answers to the form to submit + for (Iterator fields = form.getFields(); fields.hasNext();) { + FormField field = (FormField) fields.next(); + if (!FormField.TYPE_HIDDEN.equals(field.getType()) && field.getVariable() != null) { + // Sets the default value as the answer + submitForm.setDefaultAnswer(field.getVariable()); } - } + } - public void processIncomingMessages(NodeList messageElems) { + // Sets the new owner of the room + submitForm.setAnswer("muc#roomconfig_persistentroom", true); + // Send the completed form (with default values) to the server to + // configure the room + muc.sendConfigurationForm(submitForm); - for (int i = 0; i < messageElems.getLength(); i++) { - // extract message attributes - Node message = messageElems.item(i); - NamedNodeMap nnm = message.getAttributes(); + chatSession.setRoomCreated(true); + con.close(); - Node from = nnm.getNamedItem("from"); - Node to = nnm.getNamedItem("to"); - Node type = nnm.getNamedItem("type"); + } catch (XMPPException e) { + logger.error(e); + logger.error(e.getXMPPError()); + // TODO should we continue ? + } + } - Node body = getBodyElement(message); + public void processIncomingMessages(NodeList messageElems) { - // save the messages. - ChatMessage chatMessage = new ChatMessage(); - String jabberRoom; - String toNick = ""; + for (int i = 0; i < messageElems.getLength(); i++) { + // extract message attributes + Node message = messageElems.item(i); + NamedNodeMap nnm = message.getAttributes(); - // setting to field - if (type.getNodeValue().equals("chat")) { - // we are sending to an individual user. - // extract the jabber room from the to field. - // format is room@domain/nick - int index = to.getNodeValue().lastIndexOf("/"); - if (index == -1) { - logger - .debug("processIncomingMessages: malformed 'to' attribute :" - + to.getNodeValue()); - return; // somethings wrong, ignore packet - } - jabberRoom = to.getNodeValue().substring(0, index); - toNick = to.getNodeValue().substring(index + 1); - } else if (type.getNodeValue().equals("groupchat")) { - // we are sending to the whole room. - // format is room@domain - jabberRoom = to.getNodeValue(); - } else { - logger.debug("processIncomingMessages: unknown type: " - + type.getNodeValue()); - return; - } + Node from = nnm.getNamedItem("from"); + Node to = nnm.getNamedItem("to"); + Node type = nnm.getNamedItem("type"); - ChatSession chatSession = this.getSessionByJabberRoom(jabberRoom); - ChatUser toChatUser = getUserByJabberNicknameAndSessionID(toNick, - chatSession.getSessionId()); - chatMessage.setChatSession(chatSession); - chatMessage.setToUser(toChatUser); + Node body = getBodyElement(message); - // setting from field - int index = from.getNodeValue().lastIndexOf("@"); - if (index == -1) { - logger - .debug("processIncomingMessages: malformed 'from' attribute :" - + from.getNodeValue()); - return; // somethings wrong, ignore packet - } - String JidUsername = from.getNodeValue().substring(0, index); - // NB: JID and userId are the same. - Long userId; - try { - userId = new Long(JidUsername); - } catch (NumberFormatException e) { - logger - .debug("processIncomingMessages: malformed JID username: " - + JidUsername); - return; - } - ChatUser fromUser = getUserByUserIdAndSessionId(userId, chatSession - .getSessionId()); - chatMessage.setFromUser(fromUser); + // save the messages. + ChatMessage chatMessage = new ChatMessage(); + String jabberRoom; + String toNick = ""; - chatMessage.setType(type.getNodeValue()); - Node bodyText = body.getFirstChild(); - String bodyTextStr = ""; - if (bodyText != null) { - bodyTextStr = bodyText.getNodeValue(); - } - chatMessage.setBody(bodyTextStr); - chatMessage.setSendDate(new Date()); - chatMessage.setHidden(Boolean.FALSE); - saveOrUpdateChatMessage(chatMessage); + // setting to field + if (type.getNodeValue().equals("chat")) { + // we are sending to an individual user. + // extract the jabber room from the to field. + // format is room@domain/nick + int index = to.getNodeValue().lastIndexOf("/"); + if (index == -1) { + logger.debug("processIncomingMessages: malformed 'to' attribute :" + to.getNodeValue()); + return; // somethings wrong, ignore packet } + jabberRoom = to.getNodeValue().substring(0, index); + toNick = to.getNodeValue().substring(index + 1); + } else if (type.getNodeValue().equals("groupchat")) { + // we are sending to the whole room. + // format is room@domain + jabberRoom = to.getNodeValue(); + } else { + logger.debug("processIncomingMessages: unknown type: " + type.getNodeValue()); + return; + } + + ChatSession chatSession = this.getSessionByJabberRoom(jabberRoom); + ChatUser toChatUser = getUserByJabberNicknameAndSessionID(toNick, chatSession.getSessionId()); + chatMessage.setChatSession(chatSession); + chatMessage.setToUser(toChatUser); + + // setting from field + int index = from.getNodeValue().lastIndexOf("@"); + if (index == -1) { + logger.debug("processIncomingMessages: malformed 'from' attribute :" + from.getNodeValue()); + return; // somethings wrong, ignore packet + } + String JidUsername = from.getNodeValue().substring(0, index); + // NB: JID and userId are the same. + Long userId; + try { + userId = new Long(JidUsername); + } catch (NumberFormatException e) { + logger.debug("processIncomingMessages: malformed JID username: " + JidUsername); + return; + } + ChatUser fromUser = getUserByUserIdAndSessionId(userId, chatSession.getSessionId()); + chatMessage.setFromUser(fromUser); + + chatMessage.setType(type.getNodeValue()); + Node bodyText = body.getFirstChild(); + String bodyTextStr = ""; + if (bodyText != null) { + bodyTextStr = bodyText.getNodeValue(); + } + chatMessage.setBody(bodyTextStr); + chatMessage.setSendDate(new Date()); + chatMessage.setHidden(Boolean.FALSE); + saveOrUpdateChatMessage(chatMessage); } + } - public List processIncomingPresence(Node presence) { - NamedNodeMap nnm = presence.getAttributes(); + public List processIncomingPresence(Node presence) { + NamedNodeMap nnm = presence.getAttributes(); - Node from = nnm.getNamedItem("from"); - Node to = nnm.getNamedItem("to"); - if (from == null || to == null) { - // somethings wrong, return empty list - logger - .debug("malformed presence xml: no from or to attributes present"); - return null; - } - /* - // Note: Removed xmlns check due to problems with firefox 3 - // checking presence packet for correct values - Node xElem = presence.getFirstChild(); - if (xElem == null) { - logger.debug("malformed presence xml: no x element present"); - } - nnm = xElem.getAttributes(); - Node xmlns = nnm.getNamedItem("xmlns"); - if (xmlns == null - || !xmlns.getNodeValue().equals( - "http://jabber.org/protocol/muc")) { - logger - .debug("malformed presence xml: xmlns attribute for x element not available or incorrect"); - return null; - } - */ + Node from = nnm.getNamedItem("from"); + Node to = nnm.getNamedItem("to"); + if (from == null || to == null) { + // somethings wrong, return empty list + logger.debug("malformed presence xml: no from or to attributes present"); + return null; + } + /* + * // Note: Removed xmlns check due to problems with firefox 3 // checking presence packet for correct values + * Node xElem = presence.getFirstChild(); if (xElem == null) { + * logger.debug("malformed presence xml: no x element present"); } nnm = xElem.getAttributes(); Node xmlns = + * nnm.getNamedItem("xmlns"); if (xmlns == null || !xmlns.getNodeValue().equals( + * "http://jabber.org/protocol/muc")) { logger + * .debug("malformed presence xml: xmlns attribute for x element not available or incorrect"); return null; } + */ - // get the Chat User - String jabberID = from.getNodeValue().split("/")[0]; - String jabberRoom = to.getNodeValue().split("/")[0]; + // get the Chat User + String jabberID = from.getNodeValue().split("/")[0]; + String jabberRoom = to.getNodeValue().split("/")[0]; - ChatUser chatUser = getUserByJabberIDAndJabberRoom(jabberID, jabberRoom); + ChatUser chatUser = getUserByJabberIDAndJabberRoom(jabberID, jabberRoom); - List chatMessageList = getMessagesForUser(chatUser); - logger.debug("MESSAGE COUNT" + chatMessageList.size()); + List chatMessageList = getMessagesForUser(chatUser); + logger.debug("MESSAGE COUNT" + chatMessageList.size()); - List xmlMessageList = new ArrayList(); - try { - DocumentBuilderFactory factory = DocumentBuilderFactory - .newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.newDocument(); - for (Iterator iter = chatMessageList.iterator(); iter.hasNext();) { - ChatMessage message = (ChatMessage) iter.next(); + List xmlMessageList = new ArrayList(); + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); + for (Iterator iter = chatMessageList.iterator(); iter.hasNext();) { + ChatMessage message = (ChatMessage) iter.next(); - Element messageElement = document.createElement("message"); - messageElement.setAttribute("from", jabberRoom + "/" - + message.getFromUser().getJabberNickname()); - messageElement - .setAttribute("to", jabberID + "/lams_chatclient"); - messageElement.setAttribute("type", message.getType()); + Element messageElement = document.createElement("message"); + messageElement.setAttribute("from", jabberRoom + "/" + message.getFromUser().getJabberNickname()); + messageElement.setAttribute("to", jabberID + "/lams_chatclient"); + messageElement.setAttribute("type", message.getType()); - Element bodyElement = document.createElement("body"); - Text bodyText = document.createTextNode(message.getBody()); - bodyElement.appendChild(bodyText); + Element bodyElement = document.createElement("body"); + Text bodyText = document.createTextNode(message.getBody()); + bodyElement.appendChild(bodyText); - Element xElement = document.createElement("x"); - xElement.setAttribute("xmlns", "jabber:x:delay"); - xElement.setAttribute("stamp", "TODO"); // TODO generate the - // stamp attribute - xElement.setAttribute("from", jabberRoom + "/" - + message.getFromUser().getJabberNickname()); + Element xElement = document.createElement("x"); + xElement.setAttribute("xmlns", "jabber:x:delay"); + xElement.setAttribute("stamp", "TODO"); // TODO generate the + // stamp attribute + xElement.setAttribute("from", jabberRoom + "/" + message.getFromUser().getJabberNickname()); - messageElement.appendChild(bodyElement); - messageElement.appendChild(xElement); - filterMessage(messageElement, chatUser.getChatSession() - .getChat()); + messageElement.appendChild(bodyElement); + messageElement.appendChild(xElement); + filterMessage(messageElement, chatUser.getChatSession().getChat()); - xmlMessageList.add(messageElement); - // printXMLNode(messageElement, ""); - } - } catch (ParserConfigurationException e) { - e.printStackTrace(); - logger.debug("parser configuration exception"); - return null; - } - return xmlMessageList; + xmlMessageList.add(messageElement); + // printXMLNode(messageElement, ""); + } + } catch (ParserConfigurationException e) { + e.printStackTrace(); + logger.debug("parser configuration exception"); + return null; } + return xmlMessageList; + } - private void printXMLNode(Node node, String tab) { - System.out.print(tab + node.getNodeName() + ":"); + private void printXMLNode(Node node, String tab) { + System.out.print(tab + node.getNodeName() + ":"); - NamedNodeMap nnm = node.getAttributes(); - for (int j = 0; j < nnm.getLength(); j++) { - Node m = nnm.item(j); - System.out.print(" " + m.getNodeName() + "=" + m.getNodeValue()); - } - System.out.print(" => " + node.getNodeValue() + "\n"); + NamedNodeMap nnm = node.getAttributes(); + for (int j = 0; j < nnm.getLength(); j++) { + Node m = nnm.item(j); + System.out.print(" " + m.getNodeName() + "=" + m.getNodeValue()); + } + System.out.print(" => " + node.getNodeValue() + "\n"); - NodeList nl = node.getChildNodes(); - for (int i = 0; i < nl.getLength(); i++) { - Node n = nl.item(i); - printXMLNode(n, tab + " "); - } - + NodeList nl = node.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + Node n = nl.item(i); + printXMLNode(n, tab + " "); } - public void filterMessage(Node message, Chat chat) { - Pattern pattern = getFilterPattern(chat); - if (pattern == null) { - return; - } + } - // get the message body node - Node body = getBodyElement(message); - if (body == null) { - // no body node present - return; - } + public void filterMessage(Node message, Chat chat) { + Pattern pattern = getFilterPattern(chat); + if (pattern == null) { + return; + } - // get the text node - Node bodyText = body.getFirstChild(); - if (bodyText == null) { - // no text present - return; - } + // get the message body node + Node body = getBodyElement(message); + if (body == null) { + // no body node present + return; + } - // filter the message. - Matcher matcher = pattern.matcher(bodyText.getNodeValue()); - bodyText.setNodeValue(matcher - .replaceAll(ChatConstants.FILTER_REPLACE_TEXT)); + // get the text node + Node bodyText = body.getFirstChild(); + if (bodyText == null) { + // no text present + return; } - public void filterMessage(Node message) { - NamedNodeMap nnm = message.getAttributes(); - String from = nnm.getNamedItem("from").getNodeValue(); + // filter the message. + Matcher matcher = pattern.matcher(bodyText.getNodeValue()); + bodyText.setNodeValue(matcher.replaceAll(ChatConstants.FILTER_REPLACE_TEXT)); + } - // extracting jabber room. - int index = from.lastIndexOf("/"); - String jabberRoom; - if (index != -1) { - jabberRoom = from.substring(0, index); - } else { - jabberRoom = from; - } + public void filterMessage(Node message) { + NamedNodeMap nnm = message.getAttributes(); + String from = nnm.getNamedItem("from").getNodeValue(); - // get the chat content3 - Chat chat = getSessionByJabberRoom(jabberRoom).getChat(); - filterMessage(message, chat); + // extracting jabber room. + int index = from.lastIndexOf("/"); + String jabberRoom; + if (index != -1) { + jabberRoom = from.substring(0, index); + } else { + jabberRoom = from; } - public void filterMessage(ChatMessageDTO messageDTO, Chat chat) { - Pattern pattern = getFilterPattern(chat); + // get the chat content3 + Chat chat = getSessionByJabberRoom(jabberRoom).getChat(); + filterMessage(message, chat); + } - if (pattern == null) { - return; - } + public void filterMessage(ChatMessageDTO messageDTO, Chat chat) { + Pattern pattern = getFilterPattern(chat); - Matcher matcher = pattern.matcher(messageDTO.getBody()); - messageDTO.setBody(matcher - .replaceAll(ChatConstants.FILTER_REPLACE_TEXT)); + if (pattern == null) { + return; } - private Pattern getFilterPattern(Chat chat) { - if (!chat.isFilteringEnabled()) { - return null; - } + Matcher matcher = pattern.matcher(messageDTO.getBody()); + messageDTO.setBody(matcher.replaceAll(ChatConstants.FILTER_REPLACE_TEXT)); + } - // get the filter - ChatMessageFilter filter = messageFilters.get(chat.getToolContentId()); - if (filter == null) { - // this is the first message we have see for this toolContentId - // update the available filters. - filter = updateMessageFilters(chat); - } - - // get the pattern - Pattern pattern = filter.getPattern(); - if (pattern == null) { - // no pattern available. This occurs when filtering is enabled but - // no valid keywords have been defined. - return null; - } - return pattern; + private Pattern getFilterPattern(Chat chat) { + if (!chat.isFilteringEnabled()) { + return null; } - public ChatMessageFilter updateMessageFilters(Chat chat) { - ChatMessageFilter filter = new ChatMessageFilter(chat); - messageFilters.put(chat.getToolContentId(), filter); - return filter; + // get the filter + ChatMessageFilter filter = messageFilters.get(chat.getToolContentId()); + if (filter == null) { + // this is the first message we have see for this toolContentId + // update the available filters. + filter = updateMessageFilters(chat); } - public ChatMessage getMessageByUID(Long messageUID) { - return chatMessageDAO.getByUID(messageUID); + // get the pattern + Pattern pattern = filter.getPattern(); + if (pattern == null) { + // no pattern available. This occurs when filtering is enabled but + // no valid keywords have been defined. + return null; } + return pattern; + } - public List getLastestMessages(ChatSession chatSession, int max) { - return chatMessageDAO.getLatest(chatSession, max); - } + public ChatMessageFilter updateMessageFilters(Chat chat) { + ChatMessageFilter filter = new ChatMessageFilter(chat); + messageFilters.put(chat.getToolContentId(), filter); + return filter; + } - public IAuditService getAuditService() { - return auditService; - } + public ChatMessage getMessageByUID(Long messageUID) { + return chatMessageDAO.getByUID(messageUID); + } - public void setAuditService(IAuditService auditService) { - this.auditService = auditService; - } + public List getLastestMessages(ChatSession chatSession, int max) { + return chatMessageDAO.getLatest(chatSession, max); + } - public void auditEditMessage(ChatMessage chatMessage, String messageBody) { - auditService.logChange(ChatConstants.TOOL_SIGNATURE, chatMessage - .getFromUser().getUserId(), chatMessage.getFromUser() - .getLoginName(), chatMessage.getBody(), messageBody); - } + public IAuditService getAuditService() { + return auditService; + } - public void auditHideShowMessage(ChatMessage chatMessage, - boolean messageHidden) { - if (messageHidden) { - auditService.logHideEntry(ChatConstants.TOOL_SIGNATURE, chatMessage - .getFromUser().getUserId(), chatMessage.getFromUser() - .getLoginName(), chatMessage.toString()); - } else { - auditService.logShowEntry(ChatConstants.TOOL_SIGNATURE, chatMessage - .getFromUser().getUserId(), chatMessage.getFromUser() - .getLoginName(), chatMessage.toString()); - } + public void setAuditService(IAuditService auditService) { + this.auditService = auditService; + } + + public void auditEditMessage(ChatMessage chatMessage, String messageBody) { + auditService.logChange(ChatConstants.TOOL_SIGNATURE, chatMessage.getFromUser().getUserId(), chatMessage + .getFromUser().getLoginName(), chatMessage.getBody(), messageBody); + } + + public void auditHideShowMessage(ChatMessage chatMessage, boolean messageHidden) { + if (messageHidden) { + auditService.logHideEntry(ChatConstants.TOOL_SIGNATURE, chatMessage.getFromUser().getUserId(), chatMessage + .getFromUser().getLoginName(), chatMessage.toString()); + } else { + auditService.logShowEntry(ChatConstants.TOOL_SIGNATURE, chatMessage.getFromUser().getUserId(), chatMessage + .getFromUser().getLoginName(), chatMessage.toString()); } + } - /* ********** Private methods ********** */ - private Map messageFilters = new ConcurrentHashMap(); + /* Private methods */ + private Map messageFilters = new ConcurrentHashMap(); - private Node getBodyElement(Node message) { - // get the body element - NodeList nl = message.getChildNodes(); - Node body = null; - for (int j = 0; j < nl.getLength(); j++) { - // We are looking for the element. - // More than one may exists, we will take the first one we see - // We ignore and elements - // TODO check that the first one is right. may have problems with - // multiple langauges. - Node msgChild = nl.item(j); - if (msgChild.getNodeName() == "body") { - body = msgChild; - break; - } - } - return body; + private Node getBodyElement(Node message) { + // get the body element + NodeList nl = message.getChildNodes(); + Node body = null; + for (int j = 0; j < nl.getLength(); j++) { + // We are looking for the element. + // More than one may exists, we will take the first one we see + // We ignore and elements + // TODO check that the first one is right. may have problems with + // multiple langauges. + Node msgChild = nl.item(j); + if (msgChild.getNodeName() == "body") { + body = msgChild; + break; + } } + return body; + } - /** - * Registers a new Jabber Id on the jabber server using the users login as - * the jabber name and password TODO This is only temporary, most likely it - * will need to be moved to the lams core service since it will be used by - * both IM Chat Tool. Users in the system should only have a single jabber - * id - */ - private String createJabberId(UserDTO user) { - try { - XMPPConnection con = new XMPPConnection(Configuration - .get(ConfigurationKeys.XMPP_DOMAIN)); + /** + * Registers a new Jabber Id on the jabber server using the users login as the jabber name and password TODO This is + * only temporary, most likely it will need to be moved to the lams core service since it will be used by both IM + * Chat Tool. Users in the system should only have a single jabber id + */ + private String createJabberId(UserDTO user) { + try { + XMPPConnection con = new XMPPConnection(Configuration.get(ConfigurationKeys.XMPP_DOMAIN)); - AccountManager manager = con.getAccountManager(); - if (manager.supportsAccountCreation()) { - // using the lams userId as jabber username and password. - manager.createAccount(user.getUserID().toString(), user - .getUserID().toString()); - } + AccountManager manager = con.getAccountManager(); + if (manager.supportsAccountCreation()) { + // using the lams userId as jabber username and password. + manager.createAccount(user.getUserID().toString(), user.getUserID().toString()); + } - } catch (XMPPException e) { - logger.error(e); - // TODO handle exception - } - return user.getUserID() + "@" - + Configuration.get(ConfigurationKeys.XMPP_DOMAIN); + } catch (XMPPException e) { + logger.error(e); + // TODO handle exception } + return user.getUserID() + "@" + Configuration.get(ConfigurationKeys.XMPP_DOMAIN); + } - private NodeKey processFile(FormFile file, String type) { - NodeKey node = null; - if (file != null && !StringUtils.isEmpty(file.getFileName())) { - String fileName = file.getFileName(); - try { - node = getChatToolContentHandler().uploadFile( - file.getInputStream(), fileName, file.getContentType(), - type); - } catch (InvalidParameterException e) { - throw new ChatException( - "InvalidParameterException occured while trying to upload File" - + e.getMessage()); - } catch (FileNotFoundException e) { - throw new ChatException( - "FileNotFoundException occured while trying to upload File" - + e.getMessage()); - } catch (RepositoryCheckedException e) { - throw new ChatException( - "RepositoryCheckedException occured while trying to upload File" - + e.getMessage()); - } catch (IOException e) { - throw new ChatException( - "IOException occured while trying to upload File" - + e.getMessage()); - } - } - return node; + private NodeKey processFile(FormFile file, String type) { + NodeKey node = null; + if (file != null && !StringUtils.isEmpty(file.getFileName())) { + String fileName = file.getFileName(); + try { + node = getChatToolContentHandler().uploadFile(file.getInputStream(), fileName, file.getContentType(), + type); + } catch (InvalidParameterException e) { + throw new ChatException("InvalidParameterException occured while trying to upload File" + + e.getMessage()); + } catch (FileNotFoundException e) { + throw new ChatException("FileNotFoundException occured while trying to upload File" + e.getMessage()); + } catch (RepositoryCheckedException e) { + throw new ChatException("RepositoryCheckedException occured while trying to upload File" + + e.getMessage()); + } catch (IOException e) { + throw new ChatException("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 ChatException { - repositoryService = RepositoryProxy.getRepositoryService(); - ICredentials credentials = new SimpleCredentials( - ChatToolContentHandler.repositoryUser, - ChatToolContentHandler.repositoryId); - try { - ITicket ticket = repositoryService.login(credentials, - ChatToolContentHandler.repositoryWorkspaceName); - return ticket; - } catch (AccessDeniedException ae) { - throw new ChatException("Access Denied to repository." - + ae.getMessage()); - } catch (WorkspaceNotFoundException we) { - throw new ChatException("Workspace not found." + we.getMessage()); - } catch (LoginException e) { - throw new ChatException("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 ChatException { + repositoryService = RepositoryProxy.getRepositoryService(); + ICredentials credentials = new SimpleCredentials(ChatToolContentHandler.repositoryUser, + ChatToolContentHandler.repositoryId); + try { + ITicket ticket = repositoryService.login(credentials, ChatToolContentHandler.repositoryWorkspaceName); + return ticket; + } catch (AccessDeniedException ae) { + throw new ChatException("Access Denied to repository." + ae.getMessage()); + } catch (WorkspaceNotFoundException we) { + throw new ChatException("Workspace not found." + we.getMessage()); + } catch (LoginException e) { + throw new ChatException("Login failed." + e.getMessage()); } + } - /* ********** Used by Spring to "inject" the linked objects ************* */ + /* Used by Spring to "inject" the linked objects */ - public IChatAttachmentDAO getChatAttachmentDAO() { - return chatAttachmentDAO; - } + public IChatAttachmentDAO getChatAttachmentDAO() { + return chatAttachmentDAO; + } - public void setChatAttachmentDAO(IChatAttachmentDAO attachmentDAO) { - this.chatAttachmentDAO = attachmentDAO; - } + public void setChatAttachmentDAO(IChatAttachmentDAO attachmentDAO) { + this.chatAttachmentDAO = attachmentDAO; + } - public IChatDAO getChatDAO() { - return chatDAO; - } + public IChatDAO getChatDAO() { + return chatDAO; + } - public void setChatDAO(IChatDAO chatDAO) { - this.chatDAO = chatDAO; - } + public void setChatDAO(IChatDAO chatDAO) { + this.chatDAO = chatDAO; + } - public IToolContentHandler getChatToolContentHandler() { - return chatToolContentHandler; - } + public IToolContentHandler getChatToolContentHandler() { + return chatToolContentHandler; + } - public void setChatToolContentHandler( - IToolContentHandler chatToolContentHandler) { - this.chatToolContentHandler = chatToolContentHandler; - } + public void setChatToolContentHandler(IToolContentHandler chatToolContentHandler) { + this.chatToolContentHandler = chatToolContentHandler; + } - public IChatSessionDAO getChatSessionDAO() { - return chatSessionDAO; - } + public IChatSessionDAO getChatSessionDAO() { + return chatSessionDAO; + } - public void setChatSessionDAO(IChatSessionDAO sessionDAO) { - this.chatSessionDAO = sessionDAO; - } + public void setChatSessionDAO(IChatSessionDAO sessionDAO) { + this.chatSessionDAO = sessionDAO; + } - public ILamsToolService getToolService() { - return toolService; - } + public ILamsToolService getToolService() { + return toolService; + } - public void setToolService(ILamsToolService toolService) { - this.toolService = toolService; - } + public void setToolService(ILamsToolService toolService) { + this.toolService = toolService; + } - public IChatUserDAO getChatUserDAO() { - return chatUserDAO; - } + public IChatUserDAO getChatUserDAO() { + return chatUserDAO; + } - public void setChatUserDAO(IChatUserDAO userDAO) { - this.chatUserDAO = userDAO; - } + public void setChatUserDAO(IChatUserDAO userDAO) { + this.chatUserDAO = userDAO; + } - public IChatMessageDAO getChatMessageDAO() { - return chatMessageDAO; - } + public IChatMessageDAO getChatMessageDAO() { + return chatMessageDAO; + } - public void setChatMessageDAO(IChatMessageDAO messageDAO) { - this.chatMessageDAO = messageDAO; - } + public void setChatMessageDAO(IChatMessageDAO messageDAO) { + this.chatMessageDAO = messageDAO; + } - public ILearnerService getLearnerService() { - return learnerService; - } + public ILearnerService getLearnerService() { + return learnerService; + } - public void setLearnerService(ILearnerService learnerService) { - this.learnerService = learnerService; - } + public void setLearnerService(ILearnerService learnerService) { + this.learnerService = learnerService; + } - public IExportToolContentService getExportContentService() { - return exportContentService; - } + public IExportToolContentService getExportContentService() { + return exportContentService; + } - public void setExportContentService( - IExportToolContentService exportContentService) { - this.exportContentService = exportContentService; - } + public void setExportContentService(IExportToolContentService exportContentService) { + this.exportContentService = exportContentService; + } - public Map getMessageCountBySession(Long chatUID) { - return chatMessageDAO.getCountBySession(chatUID); - } + public Map getMessageCountBySession(Long chatUID) { + return chatMessageDAO.getCountBySession(chatUID); + } - public Map getMessageCountByFromUser(Long sessionUID) { - return chatMessageDAO.getCountByFromUser(sessionUID); - } + public Map getMessageCountByFromUser(Long sessionUID) { + return chatMessageDAO.getCountByFromUser(sessionUID); + } - public ICoreNotebookService getCoreNotebookService() { - return coreNotebookService; - } + public ICoreNotebookService getCoreNotebookService() { + return coreNotebookService; + } - public void setCoreNotebookService(ICoreNotebookService coreNotebookService) { - this.coreNotebookService = coreNotebookService; - } + public void setCoreNotebookService(ICoreNotebookService coreNotebookService) { + this.coreNotebookService = coreNotebookService; + } - public Long createNotebookEntry(Long id, Integer idType, String signature, - Integer userID, String entry) { - return coreNotebookService.createNotebookEntry(id, idType, signature, - userID, "", entry); - } + public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry) { + return coreNotebookService.createNotebookEntry(id, idType, signature, userID, "", entry); + } - public NotebookEntry getEntry(Long id, Integer idType, String signature, - Integer userID) { + public NotebookEntry getEntry(Long id, Integer idType, String signature, Integer userID) { - List list = coreNotebookService.getEntry(id, idType, - signature, userID); - if (list == null || list.isEmpty()) { - return null; - } else { - return list.get(0); - } + List list = coreNotebookService.getEntry(id, idType, signature, userID); + if (list == null || list.isEmpty()) { + return null; + } else { + return list.get(0); } + } - /** - * @param notebookEntry - */ - public void updateEntry(NotebookEntry notebookEntry) { - coreNotebookService.updateEntry(notebookEntry); - } + /** + * @param notebookEntry + */ + public void updateEntry(NotebookEntry notebookEntry) { + coreNotebookService.updateEntry(notebookEntry); + } - /* - * ===============Methods implemented from ToolContentImport102Manager - * =============== - */ + /* + * ===============Methods implemented from ToolContentImport102Manager =============== + */ - /** - * Import the data for a 1.0.2 Chat - */ - public void import102ToolContent(Long toolContentId, UserDTO user, - Hashtable importValues) { - Date now = new Date(); - Chat chat = new Chat(); - chat.setContentInUse(Boolean.FALSE); - chat.setCreateBy(new Long(user.getUserID().longValue())); - chat.setCreateDate(now); - chat.setDefineLater(Boolean.FALSE); - chat.setFilterKeywords(null); - chat.setFilteringEnabled(Boolean.FALSE); - chat.setInstructions(WebUtil.convertNewlines((String) importValues - .get(ToolContentImport102Manager.CONTENT_BODY))); - chat.setLockOnFinished(Boolean.FALSE); - chat.setOfflineInstructions(null); - chat.setOnlineInstructions(null); - chat.setReflectInstructions(null); - chat.setReflectOnActivity(Boolean.FALSE); - chat.setRunOffline(Boolean.FALSE); - chat.setTitle((String) importValues - .get(ToolContentImport102Manager.CONTENT_TITLE)); - chat.setToolContentId(toolContentId); - chat.setUpdateDate(now); + /** + * Import the data for a 1.0.2 Chat + */ + public void import102ToolContent(Long toolContentId, UserDTO user, Hashtable importValues) { + Date now = new Date(); + Chat chat = new Chat(); + chat.setContentInUse(Boolean.FALSE); + chat.setCreateBy(new Long(user.getUserID().longValue())); + chat.setCreateDate(now); + chat.setDefineLater(Boolean.FALSE); + chat.setFilterKeywords(null); + chat.setFilteringEnabled(Boolean.FALSE); + chat.setInstructions(WebUtil.convertNewlines((String) importValues + .get(ToolContentImport102Manager.CONTENT_BODY))); + chat.setLockOnFinished(Boolean.FALSE); + chat.setOfflineInstructions(null); + chat.setOnlineInstructions(null); + chat.setReflectInstructions(null); + chat.setReflectOnActivity(Boolean.FALSE); + chat.setRunOffline(Boolean.FALSE); + chat.setTitle((String) importValues.get(ToolContentImport102Manager.CONTENT_TITLE)); + chat.setToolContentId(toolContentId); + chat.setUpdateDate(now); - try { - Boolean isReusable = WDDXProcessor.convertToBoolean(importValues, - ToolContentImport102Manager.CONTENT_REUSABLE); - chat.setLockOnFinished(isReusable != null ? !isReusable - .booleanValue() : true); - } catch (WDDXProcessorConversionException e) { - logger.error("Unable to content for activity " + chat.getTitle() - + "properly due to a WDDXProcessorConversionException.", e); - throw new ToolException( - "Invalid import data format for activity " - + chat.getTitle() - + "- WDDX caused an exception. Some data from the design will have been lost. See log for more details."); - } - - // leave as empty, no need to set them to anything. - // setChatAttachments(Set chatAttachments); - // setChatSessions(Set chatSessions); - chatDAO.saveOrUpdate(chat); + try { + Boolean isReusable = WDDXProcessor.convertToBoolean(importValues, + ToolContentImport102Manager.CONTENT_REUSABLE); + chat.setLockOnFinished(isReusable != null ? !isReusable.booleanValue() : true); + } catch (WDDXProcessorConversionException e) { + logger.error("Unable to content for activity " + chat.getTitle() + + "properly due to a WDDXProcessorConversionException.", e); + throw new ToolException( + "Invalid import data format for activity " + + chat.getTitle() + + "- WDDX caused an exception. Some data from the design will have been lost. See log for more details."); } - /** - * 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 { + // leave as empty, no need to set them to anything. + // setChatAttachments(Set chatAttachments); + // setChatSessions(Set chatSessions); + chatDAO.saveOrUpdate(chat); + } - Chat chat = getChatByContentId(toolContentId); - if (chat == null) { - throw new DataMissingException( - "Unable to set reflective data titled " + title - + " on activity toolContentId " + toolContentId - + " as the tool content does not exist."); - } + /** + * Set the description, throws away the title value as this is not supported in 2.0 + */ + public void setReflectiveData(Long toolContentId, String title, String description) throws ToolException, + DataMissingException { - chat.setReflectOnActivity(Boolean.TRUE); - chat.setReflectInstructions(description); + Chat chat = getChatByContentId(toolContentId); + if (chat == null) { + throw new DataMissingException("Unable to set reflective data titled " + title + + " on activity toolContentId " + toolContentId + " as the tool content does not exist."); } - // ========================================================================================= + chat.setReflectOnActivity(Boolean.TRUE); + chat.setReflectInstructions(description); + } + + // ========================================================================================= } Index: lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/IChatService.java =================================================================== RCS file: /usr/local/cvsroot/lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/IChatService.java,v diff -u -r1.14 -r1.15 --- lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/IChatService.java 24 Nov 2006 00:28:46 -0000 1.14 +++ lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/IChatService.java 15 Oct 2008 02:18:45 -0000 1.15 @@ -45,218 +45,209 @@ * Defines the services available to the web layer from the Chat Service */ public interface IChatService { - /** - * Makes a copy of the default content and assigns it a newContentID - * - * @params newContentID - * @return - */ - public Chat copyDefaultContent(Long newContentID); + /** + * Makes a copy of the default content and assigns it a newContentID + * + * @params newContentID + * @return + */ + public Chat copyDefaultContent(Long newContentID); - /** - * Returns an instance of the Chat tools default content. - * - * @return - */ - public Chat getDefaultContent(); + /** + * Returns an instance of the Chat tools default content. + * + * @return + */ + public Chat getDefaultContent(); - /** - * @param toolSignature - * @return - */ - public Long getDefaultContentIdBySignature(String toolSignature); + /** + * @param toolSignature + * @return + */ + public Long getDefaultContentIdBySignature(String toolSignature); - /** - * @param toolContentID - * @return - */ - public Chat getChatByContentId(Long toolContentID); + /** + * @param toolContentID + * @return + */ + public Chat getChatByContentId(Long toolContentID); - /** - * @param toolContentId - * @param file - * @param type - * @return - */ - public ChatAttachment uploadFileToContent(Long toolContentId, - FormFile file, String type); + /** + * @param toolContentId + * @param file + * @param type + * @return + */ + public ChatAttachment uploadFileToContent(Long toolContentId, FormFile file, String type); - /** - * @param uuid - * @param versionID - */ - public void deleteFromRepository(Long uuid, Long versionID) - throws ChatException; + /** + * @param uuid + * @param versionID + */ + public void deleteFromRepository(Long uuid, Long versionID) throws ChatException; - /** - * @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 chat - */ - public void saveOrUpdateChat(Chat chat); + /** + * @param chat + */ + public void saveOrUpdateChat(Chat chat); - /** - * @param toolSessionId - * @return - */ - public ChatSession getSessionBySessionId(Long toolSessionId); + /** + * @param toolSessionId + * @return + */ + public ChatSession getSessionBySessionId(Long toolSessionId); - /** - * - * @param jabberRoom - * @return - */ - public ChatSession getSessionByJabberRoom(String jabberRoom); + /** + * + * @param jabberRoom + * @return + */ + public ChatSession getSessionByJabberRoom(String jabberRoom); - /** - * @param chatSession - */ - public void saveOrUpdateChatSession(ChatSession chatSession); + /** + * @param chatSession + */ + public void saveOrUpdateChatSession(ChatSession chatSession); - /** - * - * @param userId - * @param toolSessionId - * @return - */ - public ChatUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId); + /** + * + * @param userId + * @param toolSessionId + * @return + */ + public ChatUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId); - /** - * - * @param loginName - * @param sessionID - * @return - */ - public ChatUser getUserByLoginNameAndSessionId(String loginName, - Long sessionId); + /** + * + * @param loginName + * @param sessionID + * @return + */ + public ChatUser getUserByLoginNameAndSessionId(String loginName, Long sessionId); - /** - * - * @param jabberID - * @param jabberRoom - * @return - */ - public ChatUser getUserByJabberIDAndJabberRoom(String jabberID, - String jabberRoom); + /** + * + * @param jabberID + * @param jabberRoom + * @return + */ + public ChatUser getUserByJabberIDAndJabberRoom(String jabberID, String jabberRoom); - /** - * - * @param uid - * @return - */ - public ChatUser getUserByUID(Long uid); + /** + * + * @param uid + * @return + */ + public ChatUser getUserByUID(Long uid); - /** - * - * @param jabberNickname - * @param sessionID - * @return - */ - public ChatUser getUserByJabberNicknameAndSessionID(String jabberNickname, - Long sessionID); + /** + * + * @param jabberNickname + * @param sessionID + * @return + */ + public ChatUser getUserByJabberNicknameAndSessionID(String jabberNickname, Long sessionID); - /** - * - * @param chatUser - */ - public void saveOrUpdateChatUser(ChatUser chatUser); + /** + * + * @param chatUser + */ + public void saveOrUpdateChatUser(ChatUser chatUser); - /** - * - * @param chatUser - * @return - */ - public List getMessagesForUser(ChatUser chatUser); + /** + * + * @param chatUser + * @return + */ + public List getMessagesForUser(ChatUser chatUser); - /** - * - * @param chatMessage - */ - public void saveOrUpdateChatMessage(ChatMessage chatMessage); + /** + * + * @param chatMessage + */ + public void saveOrUpdateChatMessage(ChatMessage chatMessage); - /** - * - * @param user - * @param chatSession - * @return - */ - public ChatUser createChatUser(UserDTO user, ChatSession chatSession); + /** + * + * @param user + * @param chatSession + * @return + */ + public ChatUser createChatUser(UserDTO user, ChatSession chatSession); - /** - * - * @param chatSession - */ - public void createJabberRoom(ChatSession chatSession); + /** + * + * @param chatSession + */ + public void createJabberRoom(ChatSession chatSession); - /** - * - * @param messageElems - */ - public void processIncomingMessages(NodeList messageElems); + /** + * + * @param messageElems + */ + public void processIncomingMessages(NodeList messageElems); - /** - * - * @param presenceElems - */ - public List processIncomingPresence(Node presence); + /** + * + * @param presenceElems + */ + public List processIncomingPresence(Node presence); - /** - * - * @param toolContentID - * @param pattern - */ - public ChatMessageFilter updateMessageFilters(Chat chat); + /** + * + * @param toolContentID + * @param pattern + */ + public ChatMessageFilter updateMessageFilters(Chat chat); - /** - * - * @param node - */ - public void filterMessage(Node message); + /** + * + * @param node + */ + public void filterMessage(Node message); - /** - * - * @param message - * @param chat - */ - public void filterMessage(Node message, Chat chat); + /** + * + * @param message + * @param chat + */ + public void filterMessage(Node message, Chat chat); - /** - * - * @param messageDTO - * @param chat - */ - public void filterMessage(ChatMessageDTO messageDTO, Chat chat); + /** + * + * @param messageDTO + * @param chat + */ + public void filterMessage(ChatMessageDTO messageDTO, Chat chat); - /** - * - * @param messageUID - * @return - */ - public ChatMessage getMessageByUID(Long messageUID); + /** + * + * @param messageUID + * @return + */ + public ChatMessage getMessageByUID(Long messageUID); - public List getLastestMessages(ChatSession chatSession, int max); + public List getLastestMessages(ChatSession chatSession, int max); - public void auditEditMessage(ChatMessage chatMessage, String messageBody); + public void auditEditMessage(ChatMessage chatMessage, String messageBody); - public void auditHideShowMessage(ChatMessage chatMessage, - boolean messageHidden); + public void auditHideShowMessage(ChatMessage chatMessage, boolean messageHidden); - public Map getMessageCountBySession(Long chatUID); + public Map getMessageCountBySession(Long chatUID); - public Map getMessageCountByFromUser(Long sessionUID); + public Map getMessageCountByFromUser(Long sessionUID); - public Long createNotebookEntry(Long id, Integer idType, String signature, - Integer userID, String entry); + public Long createNotebookEntry(Long id, Integer idType, String signature, Integer userID, String entry); - public NotebookEntry getEntry(Long id, Integer idType, String signature, - Integer userID); - - public void updateEntry(NotebookEntry notebookEntry); + public NotebookEntry getEntry(Long id, Integer idType, String signature, Integer userID); + + public void updateEntry(NotebookEntry notebookEntry); } \ No newline at end of file Index: lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/web/actions/LearningAction.java =================================================================== RCS file: /usr/local/cvsroot/lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/web/actions/LearningAction.java,v diff -u -r1.25 -r1.26 --- lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/web/actions/LearningAction.java 30 Apr 2008 02:26:13 -0000 1.25 +++ lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/web/actions/LearningAction.java 15 Oct 2008 02:18:45 -0000 1.26 @@ -63,207 +63,185 @@ * @author * @version * - * @struts.action path="/learning" parameter="dispatch" scope="request" - * name="learningForm" + * @struts.action path="/learning" parameter="dispatch" scope="request" name="learningForm" * @struts.action-forward name="learning" path="tiles:/learning/main" * @struts.action-forward name="runOffline" path="tiles:/learning/runOffline" * @struts.action-forward name="defineLater" path="tiles:/learning/defineLater" * @struts.action-forward name="notebook" path="tiles:/learning/notebook" */ public class LearningAction extends LamsDispatchAction { - private static Logger log = Logger.getLogger(LearningAction.class); + private static Logger log = Logger.getLogger(LearningAction.class); - private IChatService chatService; + private IChatService chatService; - public ActionForward unspecified(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) - throws Exception { - // 'toolSessionID' and 'mode' paramters are expected to be present. - ToolAccessMode mode = WebUtil.readToolAccessModeParam(request, - AttributeNames.PARAM_MODE, false); + public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) throws Exception { + // 'toolSessionID' and 'mode' paramters are expected to be present. + ToolAccessMode mode = WebUtil.readToolAccessModeParam(request, AttributeNames.PARAM_MODE, false); - Long toolSessionID = WebUtil.readLongParam(request, - AttributeNames.PARAM_TOOL_SESSION_ID); + Long toolSessionID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID); - // set up chatService - if (chatService == null) { - chatService = ChatServiceProxy.getChatService(this.getServlet() - .getServletContext()); - } + // set up chatService + if (chatService == null) { + chatService = ChatServiceProxy.getChatService(this.getServlet().getServletContext()); + } - // Retrieve the session and content. - ChatSession chatSession = chatService - .getSessionBySessionId(toolSessionID); - if (chatSession == null) { - throw new ChatException( - "Cannot retreive session with toolSessionID" - + toolSessionID); - } + // Retrieve the session and content. + ChatSession chatSession = chatService.getSessionBySessionId(toolSessionID); + if (chatSession == null) { + throw new ChatException("Cannot retreive session with toolSessionID" + toolSessionID); + } - Chat chat = chatSession.getChat(); + Chat chat = chatSession.getChat(); - // Retrieve the current user - ChatUser chatUser = getCurrentUser(toolSessionID); + // Retrieve the current user + ChatUser chatUser = getCurrentUser(toolSessionID); - // check defineLater - if (chat.isDefineLater()) { - return mapping.findForward("defineLater"); - } + // check defineLater + if (chat.isDefineLater()) { + return mapping.findForward("defineLater"); + } - request.setAttribute("MODE", mode.toString()); + request.setAttribute("MODE", mode.toString()); - // Create the room if it doesnt exist - log.debug(chatSession.isRoomCreated()); - if (!chatSession.isRoomCreated()) { - chatService.createJabberRoom(chatSession); - chatService.saveOrUpdateChatSession(chatSession); - } + // Create the room if it doesnt exist + log.debug(chatSession.isRoomCreated()); + if (!chatSession.isRoomCreated()) { + chatService.createJabberRoom(chatSession); + chatService.saveOrUpdateChatSession(chatSession); + } - ChatDTO chatDTO = new ChatDTO(chat); - request.setAttribute("chatDTO", chatDTO); + ChatDTO chatDTO = new ChatDTO(chat); + request.setAttribute("chatDTO", chatDTO); - request.setAttribute("XMPPDOMAIN", Configuration - .get(ConfigurationKeys.XMPP_DOMAIN)); - request.setAttribute("CONFERENCEROOM", chatSession.getJabberRoom()); + request.setAttribute("XMPPDOMAIN", Configuration.get(ConfigurationKeys.XMPP_DOMAIN)); + request.setAttribute("CONFERENCEROOM", chatSession.getJabberRoom()); - ChatUserDTO chatUserDTO = new ChatUserDTO(chatUser); - if (chatUser.isFinishedActivity()) { - // get the notebook entry. - NotebookEntry notebookEntry = chatService.getEntry(toolSessionID, - CoreNotebookConstants.NOTEBOOK_TOOL, - ChatConstants.TOOL_SIGNATURE, chatUser.getUserId() - .intValue()); - if (notebookEntry != null) { - chatUserDTO.notebookEntry = notebookEntry.getEntry(); - } - } - request.setAttribute("chatUserDTO", chatUserDTO); + ChatUserDTO chatUserDTO = new ChatUserDTO(chatUser); + if (chatUser.isFinishedActivity()) { + // get the notebook entry. + NotebookEntry notebookEntry = chatService.getEntry(toolSessionID, CoreNotebookConstants.NOTEBOOK_TOOL, + ChatConstants.TOOL_SIGNATURE, chatUser.getUserId().intValue()); + if (notebookEntry != null) { + chatUserDTO.notebookEntry = notebookEntry.getEntry(); + } + } + request.setAttribute("chatUserDTO", chatUserDTO); - // Ensure that the content is use flag is set. - if (!chat.isContentInUse()) { - chat.setContentInUse(new Boolean(true)); - chatService.saveOrUpdateChat(chat); - } + // Ensure that the content is use flag is set. + if (!chat.isContentInUse()) { + chat.setContentInUse(new Boolean(true)); + chatService.saveOrUpdateChat(chat); + } - // check runOffline - if (chat.isRunOffline()) { - return mapping.findForward("runOffline"); - } - - return mapping.findForward("learning"); - + // check runOffline + if (chat.isRunOffline()) { + return mapping.findForward("runOffline"); } - private ChatUser getCurrentUser(Long toolSessionId) { - UserDTO user = (UserDTO) SessionManager.getSession().getAttribute( - AttributeNames.USER); + return mapping.findForward("learning"); - // attempt to retrieve user using userId and toolSessionId - ChatUser chatUser = chatService.getUserByUserIdAndSessionId(new Long( - user.getUserID().intValue()), toolSessionId); + } - if (chatUser == null) { - ChatSession chatSession = chatService - .getSessionBySessionId(toolSessionId); - chatUser = chatService.createChatUser(user, chatSession); - } + private ChatUser getCurrentUser(Long toolSessionId) { + UserDTO user = (UserDTO) SessionManager.getSession().getAttribute(AttributeNames.USER); - return chatUser; + // attempt to retrieve user using userId and toolSessionId + ChatUser chatUser = chatService.getUserByUserIdAndSessionId(new Long(user.getUserID().intValue()), + toolSessionId); + + if (chatUser == null) { + ChatSession chatSession = chatService.getSessionBySessionId(toolSessionId); + chatUser = chatService.createChatUser(user, chatSession); } - public ActionForward finishActivity(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) { + return chatUser; + } - LearningForm lrnForm = (LearningForm) form; + public ActionForward finishActivity(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { - // set the finished flag - ChatUser chatUser = chatService.getUserByUID(lrnForm.getChatUserUID()); - if (chatUser != null) { - chatUser.setFinishedActivity(true); - chatService.saveOrUpdateChatUser(chatUser); - } else { - log.error("finishActivity(): couldn't find ChatUser with uid: " - + lrnForm.getChatUserUID()); - } + LearningForm lrnForm = (LearningForm) form; - ToolSessionManager sessionMgrService = ChatServiceProxy - .getChatSessionManager(getServlet().getServletContext()); + // set the finished flag + ChatUser chatUser = chatService.getUserByUID(lrnForm.getChatUserUID()); + if (chatUser != null) { + chatUser.setFinishedActivity(true); + chatService.saveOrUpdateChatUser(chatUser); + } else { + log.error("finishActivity(): couldn't find ChatUser with uid: " + lrnForm.getChatUserUID()); + } - HttpSession ss = SessionManager.getSession(); - UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); - Long userID = new Long(user.getUserID().longValue()); - Long toolSessionID = chatUser.getChatSession().getSessionId(); + ToolSessionManager sessionMgrService = ChatServiceProxy.getChatSessionManager(getServlet().getServletContext()); - String nextActivityUrl; - try { - nextActivityUrl = sessionMgrService.leaveToolSession(toolSessionID, - userID); - response.sendRedirect(nextActivityUrl); - } catch (DataMissingException e) { - throw new ChatException(e); - } catch (ToolException e) { - throw new ChatException(e); - } catch (IOException e) { - throw new ChatException(e); - } + HttpSession ss = SessionManager.getSession(); + UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); + Long userID = new Long(user.getUserID().longValue()); + Long toolSessionID = chatUser.getChatSession().getSessionId(); - return null; // TODO need to return proper page. + String nextActivityUrl; + try { + nextActivityUrl = sessionMgrService.leaveToolSession(toolSessionID, userID); + response.sendRedirect(nextActivityUrl); + } catch (DataMissingException e) { + throw new ChatException(e); + } catch (ToolException e) { + throw new ChatException(e); + } catch (IOException e) { + throw new ChatException(e); } - public ActionForward openNotebook(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) { + return null; // TODO need to return proper page. + } - LearningForm lrnForm = (LearningForm) form; + public ActionForward openNotebook(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { - // set the finished flag - ChatUser chatUser = chatService.getUserByUID(lrnForm.getChatUserUID()); - ChatDTO chatDTO = new ChatDTO(chatUser.getChatSession().getChat()); + LearningForm lrnForm = (LearningForm) form; - request.setAttribute("chatDTO", chatDTO); + // set the finished flag + ChatUser chatUser = chatService.getUserByUID(lrnForm.getChatUserUID()); + ChatDTO chatDTO = new ChatDTO(chatUser.getChatSession().getChat()); - NotebookEntry notebookEntry = chatService.getEntry(chatUser - .getChatSession().getSessionId(), - CoreNotebookConstants.NOTEBOOK_TOOL, - ChatConstants.TOOL_SIGNATURE, chatUser.getUserId().intValue()); + request.setAttribute("chatDTO", chatDTO); - if (notebookEntry != null) { - lrnForm.setEntryText(notebookEntry.getEntry()); - } + NotebookEntry notebookEntry = chatService.getEntry(chatUser.getChatSession().getSessionId(), + CoreNotebookConstants.NOTEBOOK_TOOL, ChatConstants.TOOL_SIGNATURE, chatUser.getUserId().intValue()); - return mapping.findForward("notebook"); + if (notebookEntry != null) { + lrnForm.setEntryText(notebookEntry.getEntry()); } - public ActionForward submitReflection(ActionMapping mapping, - ActionForm form, HttpServletRequest request, - HttpServletResponse response) { + return mapping.findForward("notebook"); + } - // save the reflection entry and call the notebook. + public ActionForward submitReflection(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) { - LearningForm lrnForm = (LearningForm) form; + // save the reflection entry and call the notebook. - ChatUser chatUser = chatService.getUserByUID(lrnForm.getChatUserUID()); - Long toolSessionID = chatUser.getChatSession().getSessionId(); - Integer userID = chatUser.getUserId().intValue(); + LearningForm lrnForm = (LearningForm) form; - // check for existing notebook entry - NotebookEntry entry = chatService.getEntry(toolSessionID, - CoreNotebookConstants.NOTEBOOK_TOOL, - ChatConstants.TOOL_SIGNATURE, userID); + ChatUser chatUser = chatService.getUserByUID(lrnForm.getChatUserUID()); + Long toolSessionID = chatUser.getChatSession().getSessionId(); + Integer userID = chatUser.getUserId().intValue(); - if (entry == null) { - // create new entry - chatService.createNotebookEntry(toolSessionID, - CoreNotebookConstants.NOTEBOOK_TOOL, - ChatConstants.TOOL_SIGNATURE, userID, lrnForm - .getEntryText()); - } else { - // update existing entry - entry.setEntry(lrnForm.getEntryText()); - entry.setLastModified(new Date()); - chatService.updateEntry(entry); - } + // check for existing notebook entry + NotebookEntry entry = chatService.getEntry(toolSessionID, CoreNotebookConstants.NOTEBOOK_TOOL, + ChatConstants.TOOL_SIGNATURE, userID); - return finishActivity(mapping, form, request, response); + if (entry == null) { + // create new entry + chatService.createNotebookEntry(toolSessionID, CoreNotebookConstants.NOTEBOOK_TOOL, + ChatConstants.TOOL_SIGNATURE, userID, lrnForm.getEntryText()); + } else { + // update existing entry + entry.setEntry(lrnForm.getEntryText()); + entry.setLastModified(new Date()); + chatService.updateEntry(entry); } + + return finishActivity(mapping, form, request, response); + } }