diff --git a/msgcntr/messageforums-api/src/java/org/sakaiproject/api/app/messageforums/MessageForumsForumManager.java b/msgcntr/messageforums-api/src/java/org/sakaiproject/api/app/messageforums/MessageForumsForumManager.java index 946a08f9eb30..995a3f2f2e16 100644 --- a/msgcntr/messageforums-api/src/java/org/sakaiproject/api/app/messageforums/MessageForumsForumManager.java +++ b/msgcntr/messageforums-api/src/java/org/sakaiproject/api/app/messageforums/MessageForumsForumManager.java @@ -111,9 +111,9 @@ public interface MessageForumsForumManager { /** * Save a discussion forum topic */ - public void saveDiscussionForumTopic(DiscussionTopic topic); - public void saveDiscussionForumTopic(DiscussionTopic topic, boolean parentForumDraftStatus); - public void saveDiscussionForumTopic(DiscussionTopic topic, boolean parentForumDraftStatus, String currentUser, boolean logEvent); + public DiscussionTopic saveDiscussionForumTopic(DiscussionTopic topic); + public DiscussionTopic saveDiscussionForumTopic(DiscussionTopic topic, boolean parentForumDraftStatus); + public DiscussionTopic saveDiscussionForumTopic(DiscussionTopic topic, boolean parentForumDraftStatus, String currentUser, boolean logEvent); /** * Create and save an empty private discussion forum topic */ @@ -130,8 +130,12 @@ public interface MessageForumsForumManager { * Delete a private forum topic */ public void deletePrivateForumTopic(PrivateTopic topic); - - + + /** + * Create an empty message + */ + Message createMessage(final DiscussionTopic topic); + /** * Create and save an empty open discussion forum topic */ diff --git a/msgcntr/messageforums-api/src/java/org/sakaiproject/api/app/messageforums/MessageForumsMessageManager.java b/msgcntr/messageforums-api/src/java/org/sakaiproject/api/app/messageforums/MessageForumsMessageManager.java index 8864bf9c5f62..a17f15e4dd6e 100644 --- a/msgcntr/messageforums-api/src/java/org/sakaiproject/api/app/messageforums/MessageForumsMessageManager.java +++ b/msgcntr/messageforums-api/src/java/org/sakaiproject/api/app/messageforums/MessageForumsMessageManager.java @@ -37,9 +37,9 @@ public interface MessageForumsMessageManager { public Message createOpenMessage(); - public Message saveMessage(Message message); + public Message saveOrUpdateMessage(Message message); - public Message saveMessage(Message message, boolean logEvent); + public Message saveOrUpdateMessage(Message message, boolean logEvent); /** * * @param message message @@ -50,7 +50,32 @@ public interface MessageForumsMessageManager { * @return * */ - public Message saveMessage(Message message, boolean logEvent, String toolId, String userId, String contextId); + public Message saveOrUpdateMessage(Message message, boolean logEvent, String toolId, String userId, String contextId); + /** + * + * @param message + * @param logEvent + * @param ignoreLockedTopicForum set true if you want to allow the message + * to be updated even if the topic or forum is locked (ie marking as read or + * commenting on a moderated message) + * @return Message saved or updated, with the assigned id. Different object + * that the one passed as parameter. + */ + public Message saveOrUpdateMessage(Message message, boolean logEvent, boolean ignoreLockedTopicForum); + + String saveMessage(Message message); + + String saveMessage(Message message, boolean logEvent); + /** + * + * @param message message + * @param logEvent logEvent + * @param toolId id of the forums tool + * @param userId user id + * @param contextId context id + * + */ + String saveMessage(Message message, boolean logEvent, String toolId, String userId, String contextId); /** * @@ -60,8 +85,10 @@ public interface MessageForumsMessageManager { * to be updated even if the topic or forum is locked (ie marking as read or * commenting on a moderated message) */ - public Message saveMessage(Message message, boolean logEvent, boolean ignoreLockedTopicForum); + String saveMessage(Message message, boolean logEvent, boolean ignoreLockedTopicForum); + String saveMessage(Message message, boolean logEvent, String toolId, String userId, String contextId, + boolean ignoreLockedTopicForum); public void deleteMessage(Message message); public Message getMessageById(Long messageId); diff --git a/msgcntr/messageforums-api/src/java/org/sakaiproject/api/app/messageforums/PermissionLevelManager.java b/msgcntr/messageforums-api/src/java/org/sakaiproject/api/app/messageforums/PermissionLevelManager.java index 8a3e4da5c88a..75568c2991d3 100644 --- a/msgcntr/messageforums-api/src/java/org/sakaiproject/api/app/messageforums/PermissionLevelManager.java +++ b/msgcntr/messageforums-api/src/java/org/sakaiproject/api/app/messageforums/PermissionLevelManager.java @@ -90,8 +90,8 @@ public interface PermissionLevelManager { public List getDefaultPermissionLevels(); public DBMembershipItem createDBMembershipItem(String name, String permissionLevelName, Integer type); - public void saveDBMembershipItem(DBMembershipItem item); - public void savePermissionLevel(PermissionLevel level); + public DBMembershipItem saveDBMembershipItem(DBMembershipItem item); + public PermissionLevel savePermissionLevel(PermissionLevel level); /** * diff --git a/msgcntr/messageforums-app/src/java/org/sakaiproject/tool/messageforums/DiscussionForumTool.java b/msgcntr/messageforums-app/src/java/org/sakaiproject/tool/messageforums/DiscussionForumTool.java index 23542aed1272..95a103f21c3e 100644 --- a/msgcntr/messageforums-app/src/java/org/sakaiproject/tool/messageforums/DiscussionForumTool.java +++ b/msgcntr/messageforums-app/src/java/org/sakaiproject/tool/messageforums/DiscussionForumTool.java @@ -4746,7 +4746,7 @@ public String processDfMsgRevisedPost() LRS_Statement statement = forumManager.getStatementForUserPosted(dMsg.getTitle(), SAKAI_VERB.responded).orElse(null); Message persistedMessage = forumManager.saveMessage(dMsg, new ForumsMessageEventParams(ForumsMessageEventParams.MessageEvent.REVISE, statement)); - + messageManager.markMessageReadForUser(dfTopic.getId(), persistedMessage.getId(), true); List messageList = selectedTopic.getMessages(); @@ -5376,7 +5376,7 @@ public String processAddCommentToDeniedMsg() .getTopicByIdWithMessages(selectedTopic.getTopic().getId())); LRS_Statement statement = forumManager.getStatementForUserPosted(currMessage.getTitle(), SAKAI_VERB.responded).orElse(null); Message persistedMessage = forumManager.saveMessage(currMessage, new ForumsMessageEventParams(ForumsMessageEventParams.MessageEvent.REVISE, statement), true); - + if (displayDeniedMsg) // only displayed if from Deny & Comment path { setSuccessMessage(getResourceBundleString("cdfm_denied_alert")); @@ -6987,7 +6987,7 @@ else if (target instanceof Topic){ setupMembershipItemPermission(membershipItem, permBean); // save DBMembershiptItem here to get an id so we can add to the set - permissionLevelManager.saveDBMembershipItem(membershipItem); + membershipItem = permissionLevelManager.saveDBMembershipItem(membershipItem); membershipItemSet.add(membershipItem); } @@ -8206,7 +8206,7 @@ private DiscussionTopicBean duplicateTopic(Long originalTopicId, DiscussionForum log.debug("About to getMembershipItemCopy()"); DBMembershipItem newItem = getMembershipItemCopy(oldItem); if (newItem != null) { - permissionLevelManager.saveDBMembershipItem(newItem); + newItem = permissionLevelManager.saveDBMembershipItem(newItem); newTopic.addMembershipItem(newItem); } } @@ -8859,7 +8859,7 @@ public String processMoveThread() { if (log.isDebugEnabled()) log.debug("processMoveThread messageId = " + mes.getId()); if (log.isDebugEnabled()) log.debug("processMoveThread message title = " + mes.getTitle()); mes.setTopic(desttopic); - messageManager.saveMessage(mes); + mes = messageManager.saveOrUpdateMessage(mes); // mfr_move_history_t stores only records that are used to display reminder links. Not all moves are recorded in this // table. @@ -8879,7 +8879,7 @@ public String processMoveThread() { if (log.isDebugEnabled()) log.debug("processMoveThread messageId = " + childMsg.getId()); if (log.isDebugEnabled()) log.debug("processMoveThread message title = " + childMsg.getTitle()); childMsg.setTopic(desttopic); - messageManager.saveMessage(childMsg); + childMsg = messageManager.saveOrUpdateMessage(childMsg); messageManager.saveMessageMoveHistory(childMsg.getId(), desttopicId, sourceTopicId, checkReminder); eventmsg = "Moving message " + childMsg.getId() + " from topic " + sourceTopicId + " to topic " + desttopicId; eventTrackingService.post(eventTrackingService.newEvent(DiscussionForumService.EVENT_FORUMS_MOVE_THREAD, eventmsg, true)); diff --git a/msgcntr/messageforums-component-impl/pom.xml b/msgcntr/messageforums-component-impl/pom.xml index d3cd90e35fe1..9909bdfd4211 100644 --- a/msgcntr/messageforums-component-impl/pom.xml +++ b/msgcntr/messageforums-component-impl/pom.xml @@ -103,6 +103,10 @@ org.sakaiproject.rubrics rubrics-service-api + + org.apache.commons + commons-lang3 + diff --git a/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/DiscussionForumServiceImpl.java b/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/DiscussionForumServiceImpl.java index 0e6a82048125..d51259b38e2f 100644 --- a/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/DiscussionForumServiceImpl.java +++ b/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/DiscussionForumServiceImpl.java @@ -20,6 +20,9 @@ **********************************************************************************/ package org.sakaiproject.component.app.messageforums; +import java.nio.charset.StandardCharsets; +import java.text.ParseException; +import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -30,17 +33,14 @@ import java.util.Map.Entry; import java.util.Set; import java.util.Stack; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; -import lombok.Setter; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.codec.binary.Base64; -import org.sakaiproject.tool.api.SessionManager; -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; import org.sakaiproject.api.app.messageforums.Area; import org.sakaiproject.api.app.messageforums.AreaManager; import org.sakaiproject.api.app.messageforums.Attachment; @@ -48,6 +48,7 @@ import org.sakaiproject.api.app.messageforums.DiscussionForum; import org.sakaiproject.api.app.messageforums.DiscussionForumService; import org.sakaiproject.api.app.messageforums.DiscussionTopic; +import org.sakaiproject.api.app.messageforums.Message; import org.sakaiproject.api.app.messageforums.MessageForumsForumManager; import org.sakaiproject.api.app.messageforums.MessageForumsMessageManager; import org.sakaiproject.api.app.messageforums.MessageForumsTypeManager; @@ -59,35 +60,71 @@ import org.sakaiproject.authz.api.AuthzGroupService; import org.sakaiproject.authz.api.GroupNotDefinedException; import org.sakaiproject.authz.api.Role; -import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.api.ContentHostingService; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.entity.api.Entity; +import org.sakaiproject.entity.api.EntityManager; import org.sakaiproject.entity.api.EntityTransferrer; import org.sakaiproject.entity.api.HttpAccess; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; -import org.sakaiproject.entity.api.EntityManager; import org.sakaiproject.exception.IdUnusedException; -import org.sakaiproject.service.gradebook.shared.GradebookService; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SiteService; +import org.sakaiproject.tool.api.SessionManager; import org.sakaiproject.tool.api.ToolManager; import org.sakaiproject.util.Validator; import org.sakaiproject.util.cover.LinkMigrationHelper; +import org.w3c.dom.DOMException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; + @Slf4j public class DiscussionForumServiceImpl implements DiscussionForumService, EntityTransferrer { + private static final String CONTENT_GROUP = "/content/group/"; + private static final String ARCHIVING = "archiving "; private static final String MESSAGEFORUM = "messageforum"; private static final String DISCUSSION_FORUM = "discussion_forum"; private static final String DISCUSSION_TOPIC = "discussion_topic"; private static final String DISCUSSION_FORUM_TITLE = "category"; private static final String DISCUSSION_FORUM_DESC = "body"; private static final String DISCUSSION_FORUM_SHORT_DESC = "summary"; + + private static final String MESSAGES = "messages"; + private static final String MESSAGE = "message"; + private static final String MESSAGE_TITLE = "title"; + private static final String MESSAGE_AUTHOR_NAME = "author_name"; + private static final String MESSAGE_CREATED_BY = "created_by"; + private static final String MESSAGE_MODIFIED_BY = "modified_by"; + private static final String MESSAGE_CREATED_DATE = "created_date"; + private static final String MESSAGE_MODIFIED_DATE = "modified_date"; + private static final String MESSAGE_BODY = "body"; + private static final String MESSAGE_IN_REPLY_TO = "in_reply_to"; + private static final String MESSAGE_GRADE_ASSIGNMENT_NAME = "grade_assignment_name"; + private static final String MESSAGE_LABEL = "label"; + private static final String MESSAGE_TYPE_UUID = "type_uuid"; + private static final String MESSAGE_UUID = "uuid"; + private static final String MESSAGE_APPROVED = "approved"; + private static final String MESSAGE_DELETED = "deleted"; + private static final String MESSAGE_HAS_ATTACHMENTS = "has_attachments"; + private static final String MESSAGE_NUM_READER = "num_readers"; + private static final String MESSAGE_THREAD_ID = "thread_id"; + private static final String MESSAGE_THREAD_LAST_POST = "thread_last_post"; + private static final String MESSAGE_DATE_THREAD_LAST_UPDATED = "date_thread_last_updated"; + private static final String MESSAGE_TOPIC = "topic"; + private static final String TOPIC_TITLE = "subject"; + private static final String ID = "id"; private static final String DRAFT = "draft"; private static final String LOCKED = "locked"; private static final String MODERATED = "moderated"; @@ -109,57 +146,52 @@ public class DiscussionForumServiceImpl implements DiscussionForumService, Entit private static final String PERMISSION_NAME = "permission_name"; private static final String PERMISSION_LEVEL_NAME = "permission_level_name"; private static final String CUSTOM_PERMISSIONS = "permission_levels"; - + private static final String ARCHIVE_VERSION = "2.4"; // in case new features are added in future exports private static final String VERSION_ATTR = "version"; + @Getter + @Setter private MessageForumsForumManager forumManager; + @Getter + @Setter private AreaManager areaManager; + @Getter + @Setter private MessageForumsMessageManager messageManager; + @Getter + @Setter private MessageForumsTypeManager typeManager; + @Getter + @Setter private DiscussionForumManager dfManager; + @Getter + @Setter private PermissionLevelManager permissionManager; + @Setter private ContentHostingService contentHostingService; + @Setter private AuthzGroupService authzGroupService; + @Setter private EntityManager entityManager; - @Setter private SessionManager sessionManager; + @Setter + private SessionManager sessionManager; + @Setter private SiteService siteService; + @Setter private ToolManager toolManager; - - public void setToolManager(ToolManager toolManager) { - this.toolManager = toolManager; - } - - public void setSiteService(SiteService siteService) { - this.siteService = siteService; - } - public void setEntityManager(EntityManager entityManager) { - this.entityManager = entityManager; - } - - public void setContentHostingService(ContentHostingService contentHostingService) { - this.contentHostingService = contentHostingService; - } - - public void setAuthzGroupService(AuthzGroupService authzGroupService) { - this.authzGroupService = authzGroupService; - } + private final Base64 base64Encoder = new Base64(); - public void init() throws Exception - { - log.info("init()"); - entityManager.registerEntityProducer(this, REFERENCE_ROOT); + public void init() throws Exception { + log.info("init()"); + entityManager.registerEntityProducer(this, REFERENCE_ROOT); } - public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments) - { - Base64 base64Encoder = new Base64(); + public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments) { StringBuilder results = new StringBuilder(); - - try { - int forumCount = 0; - results.append("archiving ").append(getLabel()).append(" context " + Entity.SEPARATOR).append(siteId) + try { + results.append(ARCHIVING).append(getLabel()).append(" context " + Entity.SEPARATOR).append(siteId) .append(Entity.SEPARATOR).append(SiteService.MAIN_CONTAINER).append(".\n"); // start with an element with our very own (service) name Element element = doc.createElement(DiscussionForumService.class.getName()); @@ -167,210 +199,241 @@ public String archive(String siteId, Document doc, Stack stack, String archivePa ((Element) stack.peek()).appendChild(element); stack.push(element); - if (siteId != null && siteId.trim().length() > 0) { + if (StringUtils.isNotEmpty(siteId)) { Area dfArea = areaManager.getAreaByContextIdAndTypeId(siteId, typeManager.getDiscussionForumType()); - if (dfArea != null) - { - Element dfElement = doc.createElement(MESSAGEFORUM); - - //List forums = dfManager.getDiscussionForumsByContextId(siteId); - List forums = dfManager.getDiscussionForumsWithTopicsMembershipNoAttachments(siteId); - - if (forums != null && !forums.isEmpty()) - { - Iterator forumsIter = forums.iterator(); - while (forumsIter.hasNext()) - { - DiscussionForum forum = (DiscussionForum)forumsIter.next(); - - if (forum != null) - { - forumCount++; - Element df_data = doc.createElement(DISCUSSION_FORUM); - df_data.setAttribute(DISCUSSION_FORUM_TITLE, forum.getTitle()); - df_data.setAttribute(DRAFT, forum.getDraft().toString()); - df_data.setAttribute(LOCKED, forum.getLocked().toString()); - df_data.setAttribute(MODERATED, forum.getModerated().toString()); - df_data.setAttribute(SORT_INDEX, forum.getSortIndex().toString()); - - - try { - String encoded = new String(base64Encoder.encode(forum.getExtendedDescription().getBytes())); - df_data.setAttribute(DISCUSSION_FORUM_DESC, encoded); - } - catch(Exception e) { - //log.warn("Encode DF Extended Desc - " + e); - df_data.setAttribute(DISCUSSION_FORUM_DESC, ""); - } + if (dfArea != null) { + Element messageForumElement = doc.createElement(MESSAGEFORUM); - try { - String encoded = new String(base64Encoder.encode(forum.getShortDescription().getBytes())); - df_data.setAttribute(DISCUSSION_FORUM_SHORT_DESC, encoded); - } - catch(Exception e) { - //log.warn("Encode DF Short Desc - " + e); - df_data.setAttribute(DISCUSSION_FORUM_SHORT_DESC, ""); - } + // APPEND DISCUSSION FORUM ELEMENTS + int discussionForumCount = appendDiscussionForumElements(siteId, doc, messageForumElement); - List atts = forumManager.getForumById(true, forum.getId()).getAttachments(); - for (int i = 0; i < atts.size(); i++) - { - Element forum_attachment = doc.createElement(ATTACHMENT); - String attachId = ((Attachment)atts.get(i)).getAttachmentId(); - - forum_attachment.setAttribute(ATTACH_ID, attachId); - df_data.appendChild(forum_attachment); - } - - Set forumMembershipItems = forum.getMembershipItemSet(); - if (forumMembershipItems != null && forumMembershipItems.size() > 0) { - Element forum_permissions = doc.createElement(PERMISSIONS); - Iterator membershipIter = forumMembershipItems.iterator(); - while (membershipIter.hasNext()) { - DBMembershipItem membershipItem = (DBMembershipItem) membershipIter.next(); - Element permission = doc.createElement(PERMISSION); - permission.setAttribute(PERMISSION_TYPE, membershipItem.getType().toString()); - permission.setAttribute(PERMISSION_NAME, membershipItem.getName()); - permission.setAttribute(PERMISSION_LEVEL_NAME, membershipItem.getPermissionLevelName()); - - if (PermissionLevelManager.PERMISSION_LEVEL_NAME_CUSTOM.equals(membershipItem.getPermissionLevelName())){ - List customPerms = permissionManager.getCustomPermissions(); - if (customPerms != null && customPerms.size() > 0) { - Element customPermissions = doc.createElement(CUSTOM_PERMISSIONS); - for (int i = 0; i < customPerms.size(); i++) { - String name = (String)customPerms.get(i); - String hasPermission = permissionManager.getCustomPermissionByName(name, membershipItem.getPermissionLevel()).toString(); - customPermissions.setAttribute(name, hasPermission); - } - permission.appendChild(customPermissions); - } - } - - forum_permissions.appendChild(permission); - } - df_data.appendChild(forum_permissions); - } + results.append(ARCHIVING).append(getLabel()).append(": (").append(discussionForumCount) + .append(") messageforum DF items archived successfully.\n"); - List topicList = dfManager.getTopicsByIdWithMessagesMembershipAndAttachments(forum.getId()); - if (topicList != null && topicList.size() > 0) { - Iterator topicIter = topicList.iterator(); - while (topicIter.hasNext()) { - DiscussionTopic topic = (DiscussionTopic) topicIter.next(); - Element topic_data = doc.createElement(DISCUSSION_TOPIC); - topic_data.setAttribute(TOPIC_TITLE, topic.getTitle()); - topic_data.setAttribute(DRAFT, topic.getDraft().toString()); - topic_data.setAttribute(LOCKED, topic.getLocked().toString()); - topic_data.setAttribute(MODERATED, topic.getModerated().toString()); - if (topic.getSortIndex() != null) { - topic_data.setAttribute(SORT_INDEX, topic.getSortIndex().toString()); - } else { - topic_data.setAttribute(SORT_INDEX, ""); - } - Element topic_properties = doc.createElement(PROPERTIES); - Element topic_short_desc = doc.createElement(PROPERTY); - - try { - String encoded = new String(base64Encoder.encode(topic.getShortDescription().getBytes())); - topic_short_desc.setAttribute(NAME, TOPIC_SHORT_DESC); - topic_short_desc.setAttribute(ENCODE, BASE64); - topic_short_desc.setAttribute(VALUE, encoded); - } catch(Exception e) { - //log.warn("Encode Topic Short Desc - " + e); - topic_short_desc.setAttribute(NAME, TOPIC_SHORT_DESC); - topic_short_desc.setAttribute(ENCODE, BASE64); - topic_short_desc.setAttribute(VALUE, ""); - } + ((Element) stack.peek()).appendChild(messageForumElement); + stack.push(messageForumElement); + } else { + results.append(ARCHIVING).append(getLabel()).append(": empty messageforum DF archived.\n"); + } + } + stack.pop(); - topic_properties.appendChild(topic_short_desc); + } catch (DOMException e) { + log.error(e.getMessage(), e); + } + return results.toString(); + } - Element topic_long_desc = doc.createElement(PROPERTY); + private int appendDiscussionForumElements(String siteId, Document doc, Element messageForumElement) { + int discussionForumCount = 0; + List discussionForums = dfManager.getDiscussionForumsWithTopicsMembershipNoAttachments(siteId); + if (CollectionUtils.isNotEmpty(discussionForums)) { + for (DiscussionForum discussionForum : discussionForums) { + if (discussionForum != null) { + discussionForumCount++; + final Element discussionForumElement = doc.createElement(DISCUSSION_FORUM); + discussionForumElement.setAttribute(DISCUSSION_FORUM_TITLE, discussionForum.getTitle()); + discussionForumElement.setAttribute(DRAFT, discussionForum.getDraft().toString()); + discussionForumElement.setAttribute(LOCKED, discussionForum.getLocked().toString()); + discussionForumElement.setAttribute(MODERATED, discussionForum.getModerated().toString()); + discussionForumElement.setAttribute(SORT_INDEX, discussionForum.getSortIndex().toString()); + discussionForumElement.setAttribute(DISCUSSION_FORUM_DESC, + getEncodedString(discussionForum.getExtendedDescription())); + discussionForumElement.setAttribute(DISCUSSION_FORUM_SHORT_DESC, + getEncodedString(discussionForum.getShortDescription())); + + // attachments + List atts = discussionForum.getAttachments(); + appendAttachmentElements(doc, discussionForumElement, atts); + + // permissions + Set forumMembershipItems = discussionForum.getMembershipItemSet(); + appendPermissionsElement(doc, discussionForumElement, forumMembershipItems); + + // APPEND DISCUSSION TOPIC ELEMENTS + appendDiscussionTopicElements(doc, discussionForum, discussionForumElement); + messageForumElement.appendChild(discussionForumElement); + } + } + } + return discussionForumCount; + } - try { - String encoded = new String(base64Encoder.encode(topic.getExtendedDescription().getBytes())); - topic_long_desc.setAttribute(NAME, TOPIC_LONG_DESC); - topic_long_desc.setAttribute(ENCODE, BASE64); - topic_long_desc.setAttribute(VALUE, encoded); - } catch(Exception e) { - //log.warn("Encode Topic Ext Desc - " + e); - topic_long_desc.setAttribute(NAME, TOPIC_LONG_DESC); - topic_long_desc.setAttribute(ENCODE, BASE64); - topic_long_desc.setAttribute(VALUE, ""); - } + private void appendDiscussionTopicElements(Document doc, DiscussionForum forum, Element discussionForumElement) { + List discussionTopics = dfManager + .getTopicsByIdWithMessagesMembershipAndAttachments(forum.getId()); + if (CollectionUtils.isNotEmpty(discussionTopics)) { + for (DiscussionTopic discussionTopic : discussionTopics) { + final Element discussionTopicElement = doc.createElement(DISCUSSION_TOPIC); + discussionTopicElement.setAttribute(TOPIC_TITLE, discussionTopic.getTitle()); + discussionTopicElement.setAttribute(DRAFT, discussionTopic.getDraft().toString()); + discussionTopicElement.setAttribute(LOCKED, discussionTopic.getLocked().toString()); + discussionTopicElement.setAttribute(MODERATED, discussionTopic.getModerated().toString()); + if (discussionTopic.getSortIndex() != null) { + discussionTopicElement.setAttribute(SORT_INDEX, discussionTopic.getSortIndex().toString()); + } else { + discussionTopicElement.setAttribute(SORT_INDEX, StringUtils.EMPTY); + } + final Element discussionTopicPropertiesElement = appendDiscussionTopicPropertiesElement(doc, + discussionTopic); + discussionTopicElement.appendChild(discussionTopicPropertiesElement); + + // permissions + final Set membershipItems = discussionTopic.getMembershipItemSet(); + appendPermissionsElement(doc, discussionTopicElement, membershipItems); + + // attachments + final List attachments = discussionTopic.getAttachments(); + appendAttachmentElements(doc, discussionTopicElement, attachments); + + // APPEND MESSAGE ELEMENTS + Element messagesElement = appendMessagesElements(doc, discussionTopic.getMessages(), null, + discussionTopicElement); + if (messagesElement != null) { + discussionTopicElement.appendChild(messagesElement); + } + discussionForumElement.appendChild(discussionTopicElement); + } + } + } + private Element appendMessagesElements(Document doc, List messages, Message parentMessage, + Element discussionTopicElement) { + Element messagesElement = null; + if (CollectionUtils.isNotEmpty(messages)) { + List startConversationMessages = null; + if (parentMessage == null) { + startConversationMessages = messages.stream().filter(m -> (parentMessage == m.getInReplyTo())) + .collect(Collectors.toList()); + } else { + startConversationMessages = messages.stream().filter(m -> (parentMessage.equals(m.getInReplyTo()))) + .collect(Collectors.toList()); + } + if (CollectionUtils.isNotEmpty(startConversationMessages)) { + messagesElement = doc.createElement(MESSAGES); + for (Message startConversationMessage : startConversationMessages) { + appendMessageElement(doc, messages, discussionTopicElement, messagesElement, + startConversationMessage); + } + } + } + return messagesElement; + } + private void appendMessageElement(Document doc, List messages, Element discussionTopicElement, + final Element messagesElement, Message message) { + final Element messageElement = doc.createElement(MESSAGE); + messageElement.setAttribute(ID, message.getId().toString()); + if (message.getInReplyTo() != null) { + messageElement.setAttribute(MESSAGE_IN_REPLY_TO, message.getInReplyTo().getId().toString()); + } else { + messageElement.setAttribute(MESSAGE_IN_REPLY_TO, StringUtils.EMPTY); + } + messageElement.setAttribute(MESSAGE_TITLE, message.getTitle()); + messageElement.setAttribute(MESSAGE_AUTHOR_NAME, message.getAuthor()); + messageElement.setAttribute(MESSAGE_CREATED_BY, message.getCreatedBy()); + messageElement.setAttribute(MESSAGE_CREATED_DATE, message.getCreated().toString()); + messageElement.setAttribute(MESSAGE_MODIFIED_BY, message.getModifiedBy()); + messageElement.setAttribute(MESSAGE_MODIFIED_DATE, message.getModified().toString()); + messageElement.setAttribute(DRAFT, message.getDraft().toString()); + messageElement.setAttribute(MESSAGE_GRADE_ASSIGNMENT_NAME, message.getGradeAssignmentName()); + messageElement.setAttribute(MESSAGE_LABEL, message.getLabel()); + messageElement.setAttribute(MESSAGE_TYPE_UUID, message.getTypeUuid()); + messageElement.setAttribute(MESSAGE_UUID, message.getUuid()); + messageElement.setAttribute(MESSAGE_APPROVED, message.getApproved().toString()); + messageElement.setAttribute(MESSAGE_DELETED, message.getDeleted().toString()); + messageElement.setAttribute(MESSAGE_HAS_ATTACHMENTS, message.getHasAttachments().toString()); + messageElement.setAttribute(MESSAGE_NUM_READER, message.getNumReaders().toString()); + if (message.getThreadId() != null) { + messageElement.setAttribute(MESSAGE_THREAD_ID, message.getThreadId().toString()); + } else { + messageElement.setAttribute(MESSAGE_THREAD_ID, StringUtils.EMPTY); + } + if (message.getThreadLastPost() != null) { + messageElement.setAttribute(MESSAGE_THREAD_LAST_POST, message.getThreadLastPost().toString()); + } else { + messageElement.setAttribute(MESSAGE_THREAD_LAST_POST, StringUtils.EMPTY); + } + if(message.getDateThreadlastUpdated() != null) { + messageElement.setAttribute(MESSAGE_DATE_THREAD_LAST_UPDATED, message.getDateThreadlastUpdated().toString()); + } else { + messageElement.setAttribute(MESSAGE_DATE_THREAD_LAST_UPDATED, StringUtils.EMPTY); + } + messageElement.setAttribute(MESSAGE_TOPIC, message.getTopic().toString()); + messageElement.setAttribute(MESSAGE_BODY, getEncodedString(message.getBody())); - topic_properties.appendChild(topic_long_desc); - - topic_data.appendChild(topic_properties); - - // permissions - Set topicMembershipItems = topic.getMembershipItemSet(); - if (topicMembershipItems != null && topicMembershipItems.size() > 0) { - Element topic_permissions = doc.createElement(PERMISSIONS); - Iterator topicMembershipIter = topicMembershipItems.iterator(); - while (topicMembershipIter.hasNext()) { - DBMembershipItem membershipItem = (DBMembershipItem) topicMembershipIter.next(); - Element permission = doc.createElement(PERMISSION); - permission.setAttribute(PERMISSION_TYPE, membershipItem.getType().toString()); - permission.setAttribute(PERMISSION_NAME, membershipItem.getName()); - permission.setAttribute(PERMISSION_LEVEL_NAME, membershipItem.getPermissionLevelName()); - topic_permissions.appendChild(permission); - - if (PermissionLevelManager.PERMISSION_LEVEL_NAME_CUSTOM.equals(membershipItem.getPermissionLevelName())){ - List customPerms = permissionManager.getCustomPermissions(); - if (customPerms != null && customPerms.size() > 0) { - Element customPermissions = doc.createElement(CUSTOM_PERMISSIONS); - for (int i = 0; i < customPerms.size(); i++) { - String name = (String)customPerms.get(i); - String hasPermission = permissionManager.getCustomPermissionByName(name, membershipItem.getPermissionLevel()).toString(); - customPermissions.setAttribute(name, hasPermission); - } - permission.appendChild(customPermissions); - } - } - } - topic_data.appendChild(topic_permissions); - } - - List topicAtts = forumManager.getTopicByIdWithAttachments(topic.getId()).getAttachments(); - for (int j = 0; j < topicAtts.size(); j++) - { - Element topic_attachment = doc.createElement(ATTACHMENT); - String attachId = ((Attachment)topicAtts.get(j)).getAttachmentId(); + // attachments + final List messageAttachments = message.getAttachments(); + appendAttachmentElements(doc, messageElement, messageAttachments); + messages.remove(message); + Element childMessagesElement = appendMessagesElements(doc, messages, message, discussionTopicElement); + if (childMessagesElement != null) { + messageElement.appendChild(childMessagesElement); + } + messagesElement.appendChild(messageElement); + } - topic_attachment.setAttribute(ATTACH_ID, attachId); - topic_data.appendChild(topic_attachment); - } + private Element appendDiscussionTopicPropertiesElement(Document doc, DiscussionTopic discussionTopic) { + Element discussionTopicShortDescElement = doc.createElement(PROPERTY); + discussionTopicShortDescElement.setAttribute(NAME, TOPIC_SHORT_DESC); + discussionTopicShortDescElement.setAttribute(ENCODE, BASE64); + try { + String encoded = new String(base64Encoder.encode(discussionTopic.getShortDescription().getBytes())); + discussionTopicShortDescElement.setAttribute(VALUE, encoded); + } catch (Exception e) { + discussionTopicShortDescElement.setAttribute(VALUE, StringUtils.EMPTY); + } + Element discussionTopicLongDescElement = doc.createElement(PROPERTY); + discussionTopicLongDescElement.setAttribute(NAME, TOPIC_LONG_DESC); + discussionTopicLongDescElement.setAttribute(ENCODE, BASE64); + try { + String encoded = new String(base64Encoder.encode(discussionTopic.getExtendedDescription().getBytes())); + discussionTopicLongDescElement.setAttribute(VALUE, encoded); + } catch (Exception e) { + discussionTopicLongDescElement.setAttribute(VALUE, StringUtils.EMPTY); + } + final Element discussionTopicPropertiesElement = doc.createElement(PROPERTIES); + discussionTopicPropertiesElement.appendChild(discussionTopicShortDescElement); + discussionTopicPropertiesElement.appendChild(discussionTopicLongDescElement); + return discussionTopicPropertiesElement; + } - df_data.appendChild(topic_data); - } - } + private void appendAttachmentElements(Document doc, Element parentElement, List attachments) { + if (CollectionUtils.isNotEmpty(attachments)) { + for (Attachment attachment : attachments) { + final Element attachmentElement = doc.createElement(ATTACHMENT); + String attachId = attachment.getAttachmentId(); + attachmentElement.setAttribute(ATTACH_ID, attachId); + parentElement.appendChild(attachmentElement); + } + } + } - dfElement.appendChild(df_data); - } + private void appendPermissionsElement(Document doc, Element parentElement, Set membershipItems) { + if (CollectionUtils.isNotEmpty(membershipItems)) { + final Element permissionsElement = doc.createElement(PERMISSIONS); + for (DBMembershipItem membershipItem : membershipItems) { + final Element permissionElement = doc.createElement(PERMISSION); + permissionElement.setAttribute(PERMISSION_TYPE, membershipItem.getType().toString()); + permissionElement.setAttribute(PERMISSION_NAME, membershipItem.getName()); + permissionElement.setAttribute(PERMISSION_LEVEL_NAME, membershipItem.getPermissionLevelName()); + + if (PermissionLevelManager.PERMISSION_LEVEL_NAME_CUSTOM.equals(membershipItem.getPermissionLevelName())) { + List customPerms = permissionManager.getCustomPermissions(); + if (CollectionUtils.isNotEmpty(customPerms)) { + Element customPermissions = doc.createElement(CUSTOM_PERMISSIONS); + for (String name : customPerms) { + String hasPermission = permissionManager.getCustomPermissionByName(name, membershipItem.getPermissionLevel()).toString(); + customPermissions.setAttribute(name, hasPermission); } + permissionElement.appendChild(customPermissions); } - results.append("archiving ").append(getLabel()).append(": (").append(forumCount) - .append(") messageforum DF items archived successfully.\n"); - - ((Element) stack.peek()).appendChild(dfElement); - stack.push(dfElement); - } - else - { - results.append("archiving ").append(getLabel()).append(": empty messageforum DF archived.\n"); } - + permissionsElement.appendChild(permissionElement); } - stack.pop(); - - } - catch (DOMException e) - { - log.error(e.getMessage(), e); + parentElement.appendChild(permissionsElement); } - return results.toString(); } public Entity getEntity(Reference ref) @@ -483,7 +546,7 @@ public Map transferCopyEntities(String fromContext, String toCon DBMembershipItem newItem = getMembershipItemCopy(oldItem); if (newItem != null) { - permissionManager.saveDBMembershipItem(newItem); + newItem = permissionManager.saveDBMembershipItem(newItem); newForum.addMembershipItem(newItem); } } @@ -564,7 +627,7 @@ public Map transferCopyEntities(String fromContext, String toCon if(allowedPermNames.contains(oldItem.getName())) { DBMembershipItem newItem = getMembershipItemCopy(oldItem); if (newItem != null) { - permissionManager.saveDBMembershipItem(newItem); + newItem = permissionManager.saveDBMembershipItem(newItem); newTopic.addMembershipItem(newItem); } } @@ -602,362 +665,443 @@ public Map transferCopyEntities(String fromContext, String toCon return transversalMap; } - public String merge(String siteId, Element root, String archivePath, String fromSiteId, Map attachmentNames, Map userIdTrans, Set userListAllowImport) - { - List existingForums = dfManager.getDiscussionForumsByContextId(siteId); - int numExistingForums = existingForums.size(); - - Base64 base64Encoder = new Base64(); - StringBuilder results = new StringBuilder(); - if (siteId != null && siteId.trim().length() > 0) - { - try - { - NodeList allChildrenNodes = root.getChildNodes(); - int length = allChildrenNodes.getLength(); - for (int i = 0; i < length; i++) - { - Node siteNode = allChildrenNodes.item(i); - if (siteNode.getNodeType() == Node.ELEMENT_NODE) - { - Element siteElement = (Element) siteNode; - if (siteElement.getTagName().equals(MESSAGEFORUM)) - { - NodeList allForumNodes = siteElement.getChildNodes(); - int lengthForum = allForumNodes.getLength(); - for (int j = 0; j < lengthForum; j++) - { - Node child1 = allForumNodes.item(j); - if (child1.getNodeType() == Node.ELEMENT_NODE) - { - Element forumElement = (Element) child1; - if (forumElement.getTagName().equals(DISCUSSION_FORUM)) - { - DiscussionForum dfForum = forumManager.createDiscussionForum(); + public String merge(final String siteId, final Element root, final String archivePath, final String fromSiteId, + final Map attachmentNames, final Map userIdTrans, final Set userListAllowImport) { + final StringBuilder results = new StringBuilder(); + if (StringUtils.isNotBlank(siteId)) { + results.append("merging ").append(getLabel()).append(" context " + Entity.SEPARATOR).append(siteId) + .append(Entity.SEPARATOR).append(SiteService.MAIN_CONTAINER).append(".\n"); + try { + final List elements = getChildElementList(root); + final List messageForumElementList = elements.stream() + .filter(element -> MESSAGEFORUM.equals(element.getTagName())).collect(Collectors.toList()); + mergeMessageForumElements(siteId, fromSiteId, attachmentNames, messageForumElementList.get(0)); + } catch (Exception e) { + results.append("merging ").append(getLabel()).append(" failed.\n"); + log.error(e.getMessage(), e); + } + } + return results.toString(); + } - String forumTitle = forumElement.getAttribute(DISCUSSION_FORUM_TITLE); - dfForum.setTitle(forumTitle); + private void mergeMessageForumElements(final String siteId, final String fromSiteId, + final Map attachmentNames, final Element siteElement) throws Exception { + final NodeList messageForumChildNodeList = siteElement.getChildNodes(); - String forumDraft = forumElement.getAttribute(DRAFT); - if(forumDraft != null && forumDraft.length() >0) - dfForum.setDraft(Boolean.valueOf(forumDraft)); + final List discussionForumElementsList = IntStream.range(0, messageForumChildNodeList.getLength()) + .mapToObj(messageForumChildNodeList::item).filter(node -> node.getNodeType() == Node.ELEMENT_NODE) + .map(element -> (Element) element).filter(element -> DISCUSSION_FORUM.equals(element.getTagName())) + .collect(Collectors.toList()); - String forumLocked = forumElement.getAttribute(LOCKED); - if(forumLocked != null && forumLocked.length() >0) - dfForum.setLocked(Boolean.valueOf(forumLocked)); - - String forumModerated = forumElement.getAttribute(MODERATED); - if(forumModerated != null && forumModerated.length() >0) - { - dfForum.setModerated(Boolean.valueOf(forumModerated)); - } - else - { - dfForum.setModerated(Boolean.FALSE); - } - - String forumPostFirst = forumElement.getAttribute(POST_FIRST); - if(forumPostFirst != null && forumPostFirst.length() >0) - { - dfForum.setPostFirst(Boolean.valueOf(forumPostFirst)); - } - else - { - dfForum.setPostFirst(Boolean.FALSE); - } - - String forumSortIndex = forumElement.getAttribute(SORT_INDEX); - if(forumSortIndex != null && forumSortIndex.length() > 0) { - try { - Integer sortIndex = Integer.valueOf(forumSortIndex); - sortIndex = sortIndex + numExistingForums; - dfForum.setSortIndex(sortIndex); - } catch (NumberFormatException nfe) { - // do nothing b/c invalid - } - } + for (Element discussionForumElement : discussionForumElementsList) { + mergeDiscussionForumElements(siteId, fromSiteId, attachmentNames, discussionForumElement); + } + } - String forumDesc = forumElement.getAttribute(DISCUSSION_FORUM_DESC); - String trimBody = null; - if(forumDesc != null && forumDesc.length() >0) - { - trimBody = trimToNull(forumDesc); - if (trimBody != null && trimBody.length() >0) - { - byte[] decoded = base64Encoder.decode(trimBody.getBytes()); - trimBody = new String(decoded, "UTF-8"); - } - } - if(trimBody != null) - { - dfForum.setExtendedDescription(trimBody); - } + private void mergeDiscussionForumElements(final String siteId, final String fromSiteId, + final Map attachmentNames, final Element discussionForumElement) throws Exception { - String forumShortDesc = forumElement.getAttribute(DISCUSSION_FORUM_SHORT_DESC); - String trimSummary = null; - if(forumShortDesc != null && forumShortDesc.length() >0) - { - trimSummary = trimToNull(forumShortDesc); - if (trimSummary != null && trimSummary.length() >0) - { - byte[] decoded = base64Encoder.decode(trimSummary.getBytes()); - trimSummary = new String(decoded, "UTF-8"); - } - } - if(trimSummary != null) - { - dfForum.setShortDescription(trimSummary); - } + final DiscussionForum discussionForum = forumManager.createDiscussionForum(); - NodeList forumDetailNodes = forumElement.getChildNodes(); - boolean hasTopic = false; - for(int k=0; k 0) { - String oldUrl = oldAttachId; - if (oldUrl.startsWith("/content/attachment/")) - { - String newUrl = (String) attachmentNames.get(oldUrl); - if (newUrl != null) - { - oldAttachId = Validator.escapeQuestionMark(newUrl); - } - } - else if (oldUrl.startsWith("/content/group/" + fromSiteId + "/")) - { - String newUrl = "/content/group/" + siteId - + oldUrl.substring(15 + fromSiteId.length()); - oldAttachId = Validator.escapeQuestionMark(newUrl); - } - Attachment newAttachment = copyAttachment(oldAttachId, siteId); - if (newAttachment != null) - dfForum.addAttachment(newAttachment); - } - } - // PERMISSIONS - else if(forumChildElement.getTagName().equals(PERMISSIONS)) { - Set membershipItemSet = getMembershipItemSetFromPermissionElement(forumChildElement, siteId); - if (membershipItemSet != null && membershipItemSet.size() > 0) { - Iterator membershipIter = membershipItemSet.iterator(); - while (membershipIter.hasNext()) { - DBMembershipItem oldItem = (DBMembershipItem)membershipIter.next(); - - DBMembershipItem newItem = getMembershipItemCopy(oldItem); - if (newItem != null) { - permissionManager.saveDBMembershipItem(newItem); - dfForum.addMembershipItem(newItem); - } - - } - } - } + discussionForum.setTitle(discussionForumElement.getAttribute(DISCUSSION_FORUM_TITLE)); - else if(forumChildElement.getTagName().equals(DISCUSSION_TOPIC)) - { - DiscussionTopic dfTopic = forumManager.createDiscussionForumTopic(dfForum); - - String topicTitle = forumChildElement.getAttribute(TOPIC_TITLE); - dfTopic.setTitle(topicTitle); - - String topicDraft = forumChildElement.getAttribute(DRAFT); - if(topicDraft != null && topicDraft.length() >0) - dfTopic.setDraft(Boolean.valueOf(topicDraft)); - - String topicLocked = forumChildElement.getAttribute(LOCKED); - if(topicLocked != null && topicLocked.length() >0) - dfTopic.setLocked(Boolean.valueOf(topicLocked)); - - String topicModerated = forumChildElement.getAttribute(MODERATED); - if(topicModerated != null && topicModerated.length() >0) - dfTopic.setModerated(Boolean.valueOf(topicModerated)); - else - dfTopic.setModerated(Boolean.FALSE); - - String topicPostFirst = forumChildElement.getAttribute(POST_FIRST); - if(topicPostFirst != null && topicPostFirst.length() >0) - dfTopic.setPostFirst(Boolean.valueOf(topicPostFirst)); - else - dfTopic.setPostFirst(Boolean.FALSE); - - String sortIndex = forumChildElement.getAttribute(SORT_INDEX); - if (sortIndex != null) { - try { - Integer sortIndexAsInt = Integer.valueOf(sortIndex); - dfTopic.setSortIndex(sortIndexAsInt); - } catch (NumberFormatException nfe) { - dfTopic.setSortIndex(null); - } - } - - NodeList topicPropertiesNodes = forumChildElement.getChildNodes(); - for(int m=0; m0) - { - trimDesc = trimToNull(topicDesc); - if (trimDesc != null && trimDesc.length() >0) - { - byte[] decoded = base64Encoder.decode(trimDesc.getBytes()); - trimDesc = new String(decoded, "UTF-8"); - } - } - if(trimDesc != null) - { - dfTopic.setShortDescription(trimDesc); - } - } - else - dfTopic.setShortDescription(propertyElement.getAttribute(VALUE)); - } - if(TOPIC_LONG_DESC.equals(propertyElement.getAttribute(NAME))) - { - - if(BASE64.equals(propertyElement.getAttribute(ENCODE))) - { - String topicDesc = propertyElement.getAttribute(VALUE); - String trimDesc = null; - if(topicDesc != null && topicDesc.length() >0) - { - trimDesc = trimToNull(topicDesc); - if (trimDesc != null && trimDesc.length() >0) - { - byte[] decoded = base64Encoder.decode(trimDesc.getBytes()); - trimDesc = new String(decoded, "UTF-8"); - } - } - if(trimDesc != null) - { - dfTopic.setExtendedDescription(trimDesc); - } - } - else - dfTopic.setExtendedDescription(propertyElement.getAttribute(VALUE)); - } - } - } - } - } - else if (propertiesElement.getTagName().equals(ATTACHMENT)) - { - String oldAttachId = propertiesElement.getAttribute(ATTACH_ID); - if (oldAttachId != null && oldAttachId.trim().length() > 0) { - String oldUrl = oldAttachId; - if (oldUrl.startsWith("/content/attachment/")) - { - String newUrl = (String) attachmentNames.get(oldUrl); - if (newUrl != null) - { - oldAttachId = Validator.escapeQuestionMark(newUrl); - } - } - else if (oldUrl.startsWith("/content/group/" + fromSiteId + "/")) - { - String newUrl = "/content/group/" + siteId - + oldUrl.substring(15 + fromSiteId.length()); - oldAttachId = Validator.escapeQuestionMark(newUrl); - } - Attachment newAttachment = copyAttachment(oldAttachId, siteId); - if (newAttachment != null) { - dfTopic.addAttachment(newAttachment); - } - } - } - - else if (propertiesElement.getTagName().equals(PERMISSIONS)) { - Set membershipItemSet = getMembershipItemSetFromPermissionElement(propertiesElement, siteId); - if (membershipItemSet != null && membershipItemSet.size() > 0) { - Iterator membershipIter = membershipItemSet.iterator(); - while (membershipIter.hasNext()) { - DBMembershipItem oldItem = (DBMembershipItem)membershipIter.next(); - DBMembershipItem newItem = getMembershipItemCopy(oldItem); - if (newItem != null) { - permissionManager.saveDBMembershipItem(newItem); - dfTopic.addMembershipItem(newItem); - } - - } - } - } - } - } - - if(!hasTopic) - { - Area area = areaManager.getDiscussionArea(siteId); - dfForum.setArea(area); - if (!getImportAsDraft()) - { - dfForum = forumManager.saveDiscussionForum(dfForum, dfForum.getDraft()); - } - else - { - dfForum.setDraft(Boolean.valueOf("true")); - dfForum = forumManager.saveDiscussionForum(dfForum, true); - } - } - hasTopic = true; - - forumManager.saveDiscussionForumTopic(dfTopic, dfForum.getDraft()); - } - } - } + final String forumDraft = discussionForumElement.getAttribute(DRAFT); + if (StringUtils.isNotEmpty(forumDraft)) { + discussionForum.setDraft(Boolean.valueOf(forumDraft)); + } - if(!hasTopic) - { - Area area = areaManager.getDiscussionArea(siteId); - dfForum.setArea(area); - if (!getImportAsDraft()) - { - forumManager.saveDiscussionForum(dfForum, dfForum.getDraft()); - } - else - { - dfForum.setDraft(Boolean.valueOf("true")); - forumManager.saveDiscussionForum(dfForum, true); - } - } - } - } - } - } + final String forumLocked = discussionForumElement.getAttribute(LOCKED); + if (StringUtils.isNotEmpty(forumLocked)) { + discussionForum.setLocked(Boolean.valueOf(forumLocked)); + } + + final String forumModerated = discussionForumElement.getAttribute(MODERATED); + if (StringUtils.isNotEmpty(forumModerated)) { + discussionForum.setModerated(Boolean.valueOf(forumModerated)); + } else { + discussionForum.setModerated(Boolean.FALSE); + } + + final String forumPostFirst = discussionForumElement.getAttribute(POST_FIRST); + if (StringUtils.isNotEmpty(forumPostFirst)) { + discussionForum.setPostFirst(Boolean.valueOf(forumPostFirst)); + } else { + discussionForum.setPostFirst(Boolean.FALSE); + } + + final String forumSortIndex = discussionForumElement.getAttribute(SORT_INDEX); + if (StringUtils.isNotEmpty(forumSortIndex)) { + try { + Integer sortIndex = Integer.valueOf(forumSortIndex); + int numExistingForums = dfManager.getDiscussionForumsByContextId(siteId).size(); + sortIndex += numExistingForums; + discussionForum.setSortIndex(sortIndex); + } catch (NumberFormatException nfe) { + // do nothing b/c invalid + } + } + discussionForum + .setExtendedDescription(getDecodedString(discussionForumElement.getAttribute(DISCUSSION_FORUM_DESC))); + discussionForum.setShortDescription( + getDecodedString(discussionForumElement.getAttribute(DISCUSSION_FORUM_SHORT_DESC))); + + final Area area = areaManager.getDiscussionArea(siteId); + discussionForum.setArea(area); + + // Discussion Forum is saved inside this method + mergeDiscussionForumDetailNodeList(siteId, fromSiteId, attachmentNames, discussionForumElement, + discussionForum); + } + + private void mergeDiscussionForumDetailNodeList(final String siteId, final String fromSiteId, + final Map attachmentNames, final Element discussionForumElement, + DiscussionForum discussionForum) throws Exception { + + final NodeList discussionForumDetailNodeList = discussionForumElement.getChildNodes(); + final List elements = IntStream.range(0, discussionForumDetailNodeList.getLength()) + .mapToObj(discussionForumDetailNodeList::item).filter(node -> node.getNodeType() == Node.ELEMENT_NODE) + .map(element -> (Element) element).collect(Collectors.toList()); + + final List attachmentElementList = getAttachmentElementList(elements); + for (Element attachmentElement : attachmentElementList) { + final Attachment newAttachment = mergeAttachmentElement(siteId, fromSiteId, attachmentNames, + attachmentElement); + if (newAttachment != null) { + discussionForum.addAttachment(newAttachment); + } + } + + final List permissionsElementList = getPermissionsElements(elements); + for (Element permissionsElement : permissionsElementList) { + mergeDiscussionForumPermissionsElement(siteId, discussionForum, permissionsElement); + } + + DiscussionForum discussionForumReturn = discussionForum; + // Save the discussion forum before saving discussion topic + if (!getImportAsDraft()) { + discussionForumReturn = forumManager.saveDiscussionForum(discussionForum, discussionForum.getDraft()); + } else { + discussionForumReturn.setDraft(Boolean.TRUE); + discussionForumReturn = forumManager.saveDiscussionForum(discussionForum, Boolean.TRUE); + } + + final List discussionTopicElementList = getDiscussionTopicElementList(elements); + for (Element discussionTopicElement : discussionTopicElementList) { + mergeDiscussionTopicElement(siteId, fromSiteId, attachmentNames, discussionForumReturn, discussionTopicElement); + } + } + + private List getDiscussionTopicElementList(List elements) { + return elements.stream() + .filter(e -> DISCUSSION_TOPIC.equals(e.getTagName())).collect(Collectors.toList()); + } + + private List getPermissionsElements(List elements) { + return elements.stream().filter(e -> PERMISSIONS.equals(e.getTagName())) + .collect(Collectors.toList()); + } + + private void mergeDiscussionForumPermissionsElement(final String siteId, final DiscussionForum discussionForum, + final Element permissionElement) { + final Set membershipItemSet = getMembershipItemSetFromPermissionElement(permissionElement, + siteId); + if (CollectionUtils.isNotEmpty(membershipItemSet)) { + discussionForum.setMembershipItemSet(membershipItemSet); + } + } + + private Attachment mergeAttachmentElement(final String siteId, final String fromSiteId, + final Map attachmentNames, final Element attachmentElement) { + String oldAttachId = attachmentElement.getAttribute(ATTACH_ID); + if (StringUtils.isNotBlank(oldAttachId)) { + String oldUrl = oldAttachId; + if (oldUrl.startsWith("/content/attachment/")) { + String newUrl = attachmentNames.get(oldUrl); + oldAttachId = StringUtils.replace(newUrl, "?", "_"); + } else if (oldUrl.startsWith(CONTENT_GROUP + fromSiteId + "/")) { + String newUrl = CONTENT_GROUP + siteId + oldUrl.substring(15 + fromSiteId.length()); + oldAttachId = StringUtils.replace(newUrl, "?", "_"); + } + return copyAttachment(oldAttachId, siteId); + } + return null; + } + + private void mergeDiscussionTopicElement(final String siteId, final String fromSiteId, + final Map attachmentNames, final DiscussionForum discussionForum, + final Element discussionTopicElement) throws Exception { + + DiscussionTopic discussionTopic = forumManager.createDiscussionForumTopic(discussionForum); + + setDiscussionTopicValues(discussionTopicElement, discussionTopic); + + final List elements = getChildElementList(discussionTopicElement); + + final List propertiesElementList = elements.stream().filter(e -> PROPERTIES.equals(e.getTagName())) + .collect(Collectors.toList()); + for (Element propertiesElement : propertiesElementList) { + mergeDiscussionTopicPropertiesNodes(discussionTopic, propertiesElement); + } + + final List attachmentElementList = getAttachmentElementList(elements); + for (Element attachmentElement : attachmentElementList) { + final Attachment newAttachment = mergeAttachmentElement(siteId, fromSiteId, attachmentNames, + attachmentElement); + if (newAttachment != null) { + discussionTopic.addAttachment(newAttachment); + } + } + + final List permissionsElementList = getPermissionsElements(elements); + for (Element permissionsElement : permissionsElementList) { + mergeDiscussionTopicPermissionsElement(siteId, discussionTopic, permissionsElement); + } + + // Discussion topic have to be saved before its messages + discussionTopic = forumManager.saveDiscussionForumTopic(discussionTopic, discussionForum.getDraft()); + + discussionTopic.setBaseForum(discussionForum); + + // Messages have to be merged after the topic in order to control the ids of the + // "onReplyTo" attribute + final List messagesElementList = getMessagesElementList(elements); + for (Element messagesElement : messagesElementList) { + mergeDiscussionTopicMessagesElement(siteId, fromSiteId, attachmentNames, discussionTopic, messagesElement, null); + } + } + + private void setDiscussionTopicValues(Element discussionTopicElement, DiscussionTopic discussionTopic) { + final String topicTitle = discussionTopicElement.getAttribute(TOPIC_TITLE); + discussionTopic.setTitle(topicTitle); + + final String topicDraft = discussionTopicElement.getAttribute(DRAFT); + if (StringUtils.isNotEmpty(topicDraft)) { + discussionTopic.setDraft(Boolean.valueOf(topicDraft)); + } + + final String topicLocked = discussionTopicElement.getAttribute(LOCKED); + if (StringUtils.isNotEmpty(topicLocked)) { + discussionTopic.setLocked(Boolean.valueOf(topicLocked)); + } + + final String topicModerated = discussionTopicElement.getAttribute(MODERATED); + if (StringUtils.isNotEmpty(topicModerated)) { + discussionTopic.setModerated(Boolean.valueOf(topicModerated)); + } else { + discussionTopic.setModerated(Boolean.FALSE); + } + + final String topicPostFirst = discussionTopicElement.getAttribute(POST_FIRST); + if (StringUtils.isNotEmpty(topicPostFirst)) { + discussionTopic.setPostFirst(Boolean.valueOf(topicPostFirst)); + } else { + discussionTopic.setPostFirst(Boolean.FALSE); + } + + final String sortIndex = discussionTopicElement.getAttribute(SORT_INDEX); + if (StringUtils.isNotBlank(sortIndex)) { + try { + Integer sortIndexAsInt = Integer.valueOf(sortIndex); + discussionTopic.setSortIndex(sortIndexAsInt); + } catch (NumberFormatException nfe) { + discussionTopic.setSortIndex(null); + } + } + } + + private List getMessagesElementList(List elements) { + return elements.stream().filter(e -> MESSAGES.equals(e.getTagName())) + .collect(Collectors.toList()); + } + + private List getChildElementList(Element discussionTopicElement) { + final NodeList discussionTopicChildNodeList = discussionTopicElement.getChildNodes(); + final Stream discussionTopicChildnodes = IntStream.range(0, discussionTopicChildNodeList.getLength()) + .mapToObj(discussionTopicChildNodeList::item); + + return discussionTopicChildnodes.filter(node -> node.getNodeType() == Node.ELEMENT_NODE) + .map(element -> (Element) element).collect(Collectors.toList()); + } + + private List getAttachmentElementList(List elements) { + return elements.stream().filter(e -> ATTACHMENT.equals(e.getTagName())) + .collect(Collectors.toList()); + } + + private void mergeDiscussionTopicPropertiesNodes(final DiscussionTopic discussionTopic, final Element propertiesElement) { + final NodeList propertyList = propertiesElement.getChildNodes(); + for (int n = 0; n < propertyList.getLength(); n++) { + final Node propertyNode = propertyList.item(n); + if (propertyNode.getNodeType() == Node.ELEMENT_NODE) { + final Element propertyElement = (Element) propertyNode; + if (propertyElement.getTagName().equals(PROPERTY)) { + if (TOPIC_SHORT_DESC.equals(propertyElement.getAttribute(NAME))) { + final String shortDescription = getDescriptionFromPropertyElement(propertyElement); + discussionTopic.setShortDescription(shortDescription); + } else if (TOPIC_LONG_DESC.equals(propertyElement.getAttribute(NAME))) { + final String extendedDescription = getDescriptionFromPropertyElement(propertyElement); + discussionTopic.setExtendedDescription(extendedDescription); } } } - catch (Exception e) - { - results.append("merging ").append(getLabel()).append(" failed.\n"); + } + } + + private void mergeDiscussionTopicPermissionsElement(final String siteId, final DiscussionTopic discussionTopic, + final Element permissionElement) { + final Set membershipItemSet = getMembershipItemSetFromPermissionElement(permissionElement, + siteId); + if (CollectionUtils.isNotEmpty(membershipItemSet)) { + discussionTopic.setMembershipItemSet(membershipItemSet); + } + } + + private void mergeDiscussionTopicMessagesElement(final String siteId, final String fromSiteId, final Map attachmentNames, final DiscussionTopic discussionTopic, + final Element messagesElement, final String messageIdInReplyTo) throws Exception { + final NodeList messagesNodeList = messagesElement.getChildNodes(); + for (int m = 0; m < messagesNodeList.getLength(); m++) { + final Node messageNode = messagesNodeList.item(m); + final Element messageElement = (Element) messageNode; + + Message message = createMessage(discussionTopic, messageIdInReplyTo, messageElement); + + // Merge messages in reply to this message once the new id is known + final List elements = getChildElementList(messageElement); + + final List attachmentElementList = getAttachmentElementList(elements); + + for (Element attachmentElement : attachmentElementList) { + final Attachment newAttachment = mergeAttachmentElement(siteId, fromSiteId, attachmentNames, + attachmentElement); + if (newAttachment != null) { + message.addAttachment(newAttachment); + } + } + + // Save the message to get the new id + String messageId = messageManager.saveMessage(message); + + final List messagesElementList = getMessagesElementList(elements); + for (Element messagesChildElement : messagesElementList) { + mergeDiscussionTopicMessagesElement(siteId, fromSiteId, attachmentNames, discussionTopic, messagesChildElement, messageId); } + } + } + private Message createMessage(final DiscussionTopic discussionTopic, final String messageIdInReplyTo, + final Element messageElement) throws ParseException { + final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); + final Message message = messageManager.createMessage(messageElement.getAttribute(MESSAGE_TYPE_UUID)); + + try { + message.setId(Long.valueOf(messageElement.getAttribute(ID))); + } catch (Exception e) { + log.error("ERROR merging messages: Message with wrong or null id", e); + throw e; + } + message.setTitle(messageElement.getAttribute(MESSAGE_TITLE)); + message.setAuthor(messageElement.getAttribute(MESSAGE_AUTHOR_NAME)); + try { + message.setDraft(Boolean.valueOf(messageElement.getAttribute(DRAFT))); + } catch (Exception e) { + log.error( + "ERROR merging messages: Wrong date format or null in draft in message with id: " + message.getId(), + e); + throw e; + } + message.setCreatedBy(messageElement.getAttribute(MESSAGE_CREATED_BY)); + + try { + message.setCreated(formatter.parse(messageElement.getAttribute(MESSAGE_CREATED_DATE))); + } catch (ParseException e) { + log.error("ERROR merging messages: Wrong date format or null in created date in message with id: " + + message.getId(), e); + throw e; + } + + message.setModifiedBy(messageElement.getAttribute(MESSAGE_MODIFIED_BY)); + try { + message.setModified(formatter.parse(messageElement.getAttribute(MESSAGE_MODIFIED_DATE))); + } catch (ParseException e) { + log.error("ERROR merging messages: Wrong date format or null in modified date in message with id: " + + message.getId(), e); + throw e; + } + message.setUuid(messageElement.getAttribute(MESSAGE_UUID)); + message.setDeleted(nullSafeToBoolean(messageElement.getAttribute(MESSAGE_DELETED))); + message.setHasAttachments(nullSafeToBoolean(messageElement.getAttribute(MESSAGE_HAS_ATTACHMENTS))); + message.setApproved(nullSafeToBoolean(messageElement.getAttribute(MESSAGE_APPROVED))); + message.setGradeAssignmentName(messageElement.getAttribute(MESSAGE_GRADE_ASSIGNMENT_NAME)); + message.setLabel(messageElement.getAttribute(MESSAGE_LABEL)); + message.setNumReaders(nullSafeToInteger(messageElement.getAttribute(MESSAGE_NUM_READER))); + message.setThreadId(nullSafeToLong(messageElement.getAttribute(MESSAGE_THREAD_ID))); + message.setThreadLastPost(nullSafeToLong(messageElement.getAttribute(MESSAGE_THREAD_LAST_POST))); + final String dateThreadLastUpdated = messageElement.getAttribute(MESSAGE_DATE_THREAD_LAST_UPDATED); + if (StringUtils.isNotBlank(dateThreadLastUpdated)) { + try { + message.setDateThreadlastUpdated(formatter.parse(dateThreadLastUpdated)); + } catch (ParseException e) { + log.error( + "ERROR merging messages: Wrong date format or null in thread last updated in message with id: " + + message.getId()); + throw e; + } + } + if (StringUtils.isNotBlank(messageIdInReplyTo)) { + message.setInReplyTo(messageManager.getMessageById(Long.valueOf(messageIdInReplyTo))); + } + message.setBody(getDecodedString(messageElement.getAttribute(MESSAGE_BODY))); + + // Set the topic of the message + message.setTopic(discussionTopic); + return message; + } + + private String getDescriptionFromPropertyElement(final Element propertyElement) { + if (BASE64.equals(propertyElement.getAttribute(ENCODE))) { + return getDecodedString(propertyElement.getAttribute(VALUE)); + } else { + return propertyElement.getAttribute(VALUE); + } + } + + private String getDecodedString(final String inputString) { + if (StringUtils.isNotBlank(inputString)) { + return new String(base64Encoder.decode(inputString.getBytes()), StandardCharsets.UTF_8); + } + return StringUtils.EMPTY; + } + + private String getEncodedString(final String inputString) { + try { + return new String(base64Encoder.encode(inputString.getBytes())); + } catch (Exception e) { + return StringUtils.EMPTY; } - return null; + } + + private Long nullSafeToLong(String stringToConvert) { + Long longToReturn = null; + if (StringUtils.isNotBlank(stringToConvert)) { + longToReturn = Long.valueOf(stringToConvert); + } + return longToReturn; + } + + private Boolean nullSafeToBoolean(String stringToConvert) { + Boolean booleanToReturn = null; + if (StringUtils.isNotBlank(stringToConvert)) { + booleanToReturn = Boolean.valueOf(stringToConvert); + } + return booleanToReturn; + } + + private Integer nullSafeToInteger(String stringToConvert) { + Integer integerToReturn = null; + if (StringUtils.isNumeric(stringToConvert)) { + integerToReturn = Integer.valueOf(stringToConvert); + } + return integerToReturn; } public boolean parseEntityReference(String reference, Reference ref) @@ -1025,26 +1169,6 @@ protected String[] split(String source, String splitter) } // split - public MessageForumsForumManager getForumManager() - { - return forumManager; - } - - public void setForumManager(MessageForumsForumManager forumManager) - { - this.forumManager = forumManager; - } - - public AreaManager getAreaManager() - { - return areaManager; - } - - public void setAreaManager(AreaManager areaManager) - { - this.areaManager = areaManager; - } - public String trimToNull(String value) { if (value == null) return null; @@ -1130,7 +1254,7 @@ private Set getMembershipItemSetFromPermissionElement(Element permissionsElement } } // save DBMembershipItem here to get an id so we can add to the set - permissionManager.saveDBMembershipItem(membershipItem); + membershipItem = permissionManager.saveDBMembershipItem(membershipItem); membershipItemSet.add(membershipItem); } } @@ -1205,42 +1329,6 @@ private DBMembershipItem getMembershipItemCopy(DBMembershipItem itemToCopy) { return newItem; } - public MessageForumsMessageManager getMessageManager() - { - return messageManager; - } - - public void setMessageManager(MessageForumsMessageManager messageManager) - { - this.messageManager = messageManager; - } - - public MessageForumsTypeManager getTypeManager() - { - return typeManager; - } - - public void setTypeManager(MessageForumsTypeManager typeManager) - { - this.typeManager = typeManager; - } - - public DiscussionForumManager getDfManager() { - return dfManager; - } - - public void setDfManager(DiscussionForumManager dfManager) { - this.dfManager = dfManager; - } - - public void setPermissionManager(PermissionLevelManager permissionManager) { - this.permissionManager = permissionManager; - } - - public PermissionLevelManager getPermissionManager() { - return permissionManager; - } - public Map transferCopyEntities(String fromContext, String toContext, List ids, List options, boolean cleanup) { Map transversalMap = new HashMap<>(); @@ -1344,12 +1432,13 @@ public void updateEntityReferences(String toContext, Map transve } } } - - private String replaceAllRefs(String msgBody, Set> entrySet){ - if(msgBody != null){ - msgBody = LinkMigrationHelper.migrateAllLinks(entrySet, msgBody); - } - return msgBody; + + private String replaceAllRefs(String msgBody, Set> entrySet) { + String msgBodyToReturn = msgBody; + if (msgBody != null) { + msgBodyToReturn = LinkMigrationHelper.migrateAllLinks(entrySet, msgBody); + } + return msgBodyToReturn; } private Boolean getImportAsDraft() { diff --git a/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/MessageForumsForumManagerImpl.java b/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/MessageForumsForumManagerImpl.java index 09e948b73f77..2fde5895c317 100644 --- a/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/MessageForumsForumManagerImpl.java +++ b/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/MessageForumsForumManagerImpl.java @@ -32,14 +32,11 @@ import java.util.SortedSet; import java.util.TreeSet; -import lombok.extern.slf4j.Slf4j; import lombok.Getter; import lombok.Setter; import org.hibernate.Query; import org.hibernate.collection.internal.PersistentSet; import org.sakaiproject.hibernate.HibernateUtils; -import org.springframework.orm.hibernate4.HibernateCallback; -import org.springframework.orm.hibernate4.support.HibernateDaoSupport; import org.sakaiproject.api.app.messageforums.ActorPermissions; import org.sakaiproject.api.app.messageforums.Area; @@ -48,6 +45,7 @@ import org.sakaiproject.api.app.messageforums.DiscussionForum; import org.sakaiproject.api.app.messageforums.DiscussionForumService; import org.sakaiproject.api.app.messageforums.DiscussionTopic; +import org.sakaiproject.api.app.messageforums.Message; import org.sakaiproject.api.app.messageforums.MessageForumsForumManager; import org.sakaiproject.api.app.messageforums.MessageForumsTypeManager; import org.sakaiproject.api.app.messageforums.MessageForumsUser; @@ -62,6 +60,7 @@ import org.sakaiproject.component.app.messageforums.dao.hibernate.DiscussionForumImpl; import org.sakaiproject.component.app.messageforums.dao.hibernate.DiscussionTopicImpl; import org.sakaiproject.component.app.messageforums.dao.hibernate.MessageForumsUserImpl; +import org.sakaiproject.component.app.messageforums.dao.hibernate.MessageImpl; import org.sakaiproject.component.app.messageforums.dao.hibernate.OpenTopicImpl; import org.sakaiproject.component.app.messageforums.dao.hibernate.PrivateForumImpl; import org.sakaiproject.component.app.messageforums.dao.hibernate.PrivateTopicImpl; @@ -74,11 +73,15 @@ import org.sakaiproject.rubrics.logic.RubricsConstants; import org.sakaiproject.rubrics.logic.RubricsService; import org.sakaiproject.site.api.Site; -import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.site.api.SiteService; +import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.tool.api.Placement; import org.sakaiproject.tool.api.SessionManager; import org.sakaiproject.tool.api.ToolManager; +import org.springframework.orm.hibernate4.HibernateCallback; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +import lombok.extern.slf4j.Slf4j; /** * The forums are sorted by this java class. The topics are sorted by the order-by in the hbm file. @@ -884,71 +887,78 @@ public DiscussionTopic createDiscussionForumTopic(DiscussionForum forum) { } - public void saveDiscussionForumTopic(DiscussionTopic topic) { - saveDiscussionForumTopic(topic, false); + public DiscussionTopic saveDiscussionForumTopic(DiscussionTopic topic) { + return saveDiscussionForumTopic(topic, false); } /** * Save a discussion forum topic */ - public void saveDiscussionForumTopic(DiscussionTopic topic, boolean parentForumDraftStatus) { - saveDiscussionForumTopic(topic, parentForumDraftStatus, getCurrentUser(), true); + public DiscussionTopic saveDiscussionForumTopic(DiscussionTopic topic, boolean parentForumDraftStatus) { + return saveDiscussionForumTopic(topic, parentForumDraftStatus, getCurrentUser(), true); } - public void saveDiscussionForumTopic(DiscussionTopic topic, boolean parentForumDraftStatus, String currentUser, boolean logEvent) { + public DiscussionTopic saveDiscussionForumTopic(DiscussionTopic topic, boolean parentForumDraftStatus, String currentUser, boolean logEvent) { boolean isNew = topic.getId() == null; + topic.setModified(new Date()); + + transformNullsToFalse(topic, currentUser); + + //make sure availability is set properly + topic.setAvailability(ForumScheduleNotificationCover.makeAvailableHelper(topic.getAvailabilityRestricted(), topic.getOpenDate(), topic.getCloseDate())); + + DiscussionTopic topicReturn = topic; + if (isNew) { + DiscussionForum discussionForum = (DiscussionForum) getForumByIdWithTopics(topic.getBaseForum().getId()); + discussionForum.addTopic(topic); + } else { + topicReturn = (DiscussionTopic) getSessionFactory().getCurrentSession().merge(topic); + } + + if(topicReturn.getId() != null){ + ForumScheduleNotificationCover.scheduleAvailability(topicReturn); + } + + log.debug("saveDiscussionForumTopic executed with topicId: " + topicReturn.getId()); + return topicReturn; + } + + private void transformNullsToFalse(DiscussionTopic topic, String currentUser) { if (topic.getMutable() == null) { topic.setMutable(Boolean.FALSE); } if (topic.getSortIndex() == null) { topic.setSortIndex(Integer.valueOf(0)); } - topic.setModified(new Date()); if(currentUser!=null){ - topic.setModifiedBy(currentUser); + topic.setModifiedBy(currentUser); } - if (topic.getModerated() == null) { topic.setModerated(Boolean.FALSE); } - if (topic.getPostFirst() == null) { topic.setPostFirst(Boolean.FALSE); } - if (topic.getPostAnonymous() == null) { topic.setPostAnonymous(Boolean.FALSE); } - if (topic.getRevealIDsToRoles() == null) { topic.setRevealIDsToRoles(Boolean.FALSE); } + } - //make sure availability is set properly - topic.setAvailability(ForumScheduleNotificationCover.makeAvailableHelper(topic.getAvailabilityRestricted(), topic.getOpenDate(), topic.getCloseDate())); - - if (isNew) { - DiscussionForum discussionForum = (DiscussionForum) getForumByIdWithTopics(topic.getBaseForum().getId()); - discussionForum.addTopic(topic); - saveDiscussionForum(discussionForum, parentForumDraftStatus, logEvent, currentUser); - } else { - getHibernateTemplate().merge(topic); + public Message createMessage(final DiscussionTopic topic) { + final Message message = new MessageImpl(); + message.setUuid(getNextUuid()); + message.setTypeUuid(typeManager.getDiscussionForumType()); + message.setCreated(new Date()); + if (getCurrentUser() != null) { + topic.setCreatedBy(getCurrentUser()); } - //now schedule any jobs that are needed for the open/close dates - //this will require having the ID of the topic (if its a new one) - if(topic.getId() == null){ - Topic topicTmp = getTopicByUuid(topic.getUuid()); - if(topicTmp != null){ - //set the ID so that the forum scheduler can schedule any needed jobs - topic.setId(topicTmp.getId()); - } - } - if(topic.getId() != null){ - ForumScheduleNotificationCover.scheduleAvailability(topic); - } - - log.debug("saveDiscussionForumTopic executed with topicId: " + topic.getId()); + message.setDraft(topic.getDraft()); + log.debug("createDiscussionForumTopic executed"); + return message; } public OpenTopic createOpenForumTopic(OpenForum forum) { @@ -1312,55 +1322,30 @@ public List getForumByTypeAndContextWithTopicsAllAttachments(final String typeUu tempForum.setSortIndex(Integer.valueOf(sort_index++)); } - return resultList; + return resultList; } - - public List getForumByTypeAndContextWithTopicsMembership(final String typeUuid, final String contextId) - { - if (typeUuid == null || contextId == null) { - throw new IllegalArgumentException("Null Argument"); - } - - HibernateCallback hcb = session -> { - Query q = session.getNamedQuery(QUERY_BY_TYPE_AND_CONTEXT_WITH_ALL_TOPICS_MEMBERSHIP); - q.setString("typeUuid", typeUuid); - q.setString("contextId", contextId); - return q.list(); - }; - - BaseForum tempForum = null; - Set resultSet = new HashSet(); - List temp = getHibernateTemplate().execute(hcb); - - for (Iterator i = temp.iterator(); i.hasNext();) - { - Object[] results = (Object[]) i.next(); - - if (results != null) { - if (results[0] instanceof BaseForum) { - tempForum = (BaseForum)results[0]; - tempForum.setArea((Area)results[1]); - } else { - tempForum = (BaseForum)results[1]; - tempForum.setArea((Area)results[0]); - } - resultSet.add(tempForum); - } - } - List resultList = Util.setToList(resultSet); - Collections.sort(resultList, FORUM_SORT_INDEX_CREATED_DATE_COMPARATOR_DESC); + public List getForumByTypeAndContextWithTopicsMembership(final String typeUuid, final String contextId) { + if (typeUuid == null || contextId == null) { + throw new IllegalArgumentException("Null Argument"); + } + final HibernateCallback> hcb = session -> { + Query q = session.getNamedQuery(QUERY_BY_TYPE_AND_CONTEXT_WITH_ALL_TOPICS_MEMBERSHIP); + q.setString("typeUuid", typeUuid); + q.setString("contextId", contextId); + return q.list(); + }; - // Now that the list is sorted, lets index the forums - int sort_index = 1; - for(Iterator i = resultList.iterator(); i.hasNext(); ) { - tempForum = (BaseForum)i.next(); + final List resultList = getHibernateTemplate().execute(hcb); - tempForum.setSortIndex(Integer.valueOf(sort_index++)); - } + Collections.sort(resultList, FORUM_SORT_INDEX_CREATED_DATE_COMPARATOR_DESC); - return resultList; + // Now that the list is sorted, lets index the forums + for (int sortIndex = 0; sortIndex < resultList.size(); sortIndex++) { + resultList.get(sortIndex).setSortIndex(Integer.valueOf(sortIndex + 1)); } + return resultList; + } public int getNumModTopicCurrentUserHasModPermForWithPermissionLevel(final List membershipList) { diff --git a/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/MessageForumsMessageManagerImpl.java b/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/MessageForumsMessageManagerImpl.java index 5a245df770a3..5b1e021fabef 100644 --- a/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/MessageForumsMessageManagerImpl.java +++ b/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/MessageForumsMessageManagerImpl.java @@ -1063,7 +1063,7 @@ public void markMessageReadForUser(Long topicId, Long messageId, boolean read, S if (message.getTopic().getBaseForum()==null && message.getTopic().getOpenForum() != null) message.getTopic().setBaseForum((BaseForum) message.getTopic().getOpenForum()); - this.saveMessage(message, false, toolId, userId, context, true); + this.saveOrUpdateMessage(message, false, toolId, userId, context, true); if (isMessageFromForums) eventTrackingService.post(eventTrackingService.newEvent(DiscussionForumService.EVENT_FORUMS_READ, getEventMessage(message, toolId, userId, context), false)); @@ -1261,35 +1261,33 @@ public Attachment createAttachment() { return attachment; } - public Message saveMessage(Message message) { - return saveMessage(message, true); + public Message saveOrUpdateMessage(Message message) { + return saveOrUpdateMessage(message, true); } - public Message saveMessage(Message message, boolean logEvent) { - return saveMessage(message, logEvent, toolManager.getCurrentTool().getId(), getCurrentUser(), getContextId()); + public Message saveOrUpdateMessage(Message message, boolean logEvent) { + return saveOrUpdateMessage(message, logEvent, toolManager.getCurrentTool().getId(), getCurrentUser(), getContextId()); } - - public Message saveMessage(Message message, boolean logEvent, boolean ignoreLockedTopicForum) { - return saveMessage(message, logEvent, toolManager.getCurrentTool().getId(), getCurrentUser(), getContextId(), ignoreLockedTopicForum); + + public Message saveOrUpdateMessage(Message message, boolean logEvent, boolean ignoreLockedTopicForum) { + return saveOrUpdateMessage(message, logEvent, toolManager.getCurrentTool().getId(), getCurrentUser(), getContextId(), ignoreLockedTopicForum); } - - public Message saveMessage(Message message, boolean logEvent, String toolId, String userId, String contextId){ - return saveMessage(message, logEvent, toolId, userId, contextId, false); + + public Message saveOrUpdateMessage(Message message, boolean logEvent, String toolId, String userId, String contextId){ + return saveOrUpdateMessage(message, logEvent, toolId, userId, contextId, false); } - - public Message saveMessage(Message message, boolean logEvent, String toolId, String userId, String contextId, boolean ignoreLockedTopicForum){ + + public Message saveOrUpdateMessage(Message message, boolean logEvent, String toolId, String userId, String contextId, boolean ignoreLockedTopicForum){ boolean isNew = message.getId() == null; - - if (!ignoreLockedTopicForum && !(message instanceof PrivateMessage)){ - if (isForumOrTopicLocked(message.getTopic().getBaseForum().getId(), message.getTopic().getId())) { - log.info("saveMessage executed [messageId: " + (isNew ? "new" : message.getId().toString()) + "] but forum is locked -- save aborted"); - throw new LockedException("Message could not be saved [messageId: " + (isNew ? "new" : message.getId().toString()) + "]"); - } + + if (!ignoreLockedTopicForum && !(message instanceof PrivateMessage) && isForumOrTopicLocked(message.getTopic().getBaseForum().getId(), message.getTopic().getId())) { + log.warn("Forum or Topic is locked for [messageId: {}] not saving", (isNew ? "new" : message.getId().toString())); + throw new LockedException("Message could not be saved [messageId: " + (isNew ? "new" : message.getId().toString()) + "]"); } - + message.setModified(new Date()); if(getCurrentUser()!=null){ - message.setModifiedBy(getCurrentUser()); + message.setModifiedBy(getCurrentUser()); } if(message.getUuid() == null || message.getCreated() == null || message.getCreatedBy() == null || message.getModified() == null @@ -1303,25 +1301,19 @@ public Message saveMessage(Message message, boolean logEvent, String toolId, Str if (message.getNumReaders() == null) message.setNumReaders(0); - - //MSGCNTR-448 if this is a top new top level message make sure the thread date is set - if (logEvent) { - if (isNew && message.getDateThreadlastUpdated() == null) { - //we don't need to do this on non log events - message.setDateThreadlastUpdated(new Date()); - if (message.getInReplyTo() != null) { - if (message.getInReplyTo().getThreadId() != null) { - message.setThreadId(message.getInReplyTo().getThreadId()); - } else { - message.setThreadId(message.getInReplyTo().getId()); - } - } - } - } + manageThreadId(message, logEvent, isNew); + + final Message persistedMessage = (Message) getSessionFactory().getCurrentSession().merge(message); - Message persistedMessage = getHibernateTemplate().merge(message); + handleEvent(message, logEvent, toolId, userId, contextId, isNew, persistedMessage); + + log.debug("message " + persistedMessage.getId() + " saved successfully"); + return persistedMessage; + } + private void handleEvent(Message message, boolean logEvent, String toolId, String userId, String contextId, + boolean isNew, Message persistedMessage) { if (logEvent && !isMessageFromForums(persistedMessage)) { // Forums handles events itself if (isNew) { eventTrackingService.post(eventTrackingService.newEvent(DiscussionForumService.EVENT_MESSAGES_ADD, getEventMessage(persistedMessage, toolId, userId, contextId), false)); @@ -1329,9 +1321,105 @@ public Message saveMessage(Message message, boolean logEvent, String toolId, Str eventTrackingService.post(eventTrackingService.newEvent(DiscussionForumService.EVENT_MESSAGES_RESPONSE, getEventMessage(persistedMessage, toolId, userId, contextId), false)); } } - - log.debug("message " + persistedMessage.getId() + " saved successfully"); - return persistedMessage; + } + + private void manageThreadId(Message message, boolean logEvent, boolean isNew) { + //MSGCNTR-448 if this is a top new top level message make sure the thread date is set + if (logEvent && isNew && message.getDateThreadlastUpdated() == null) { + //we don't need to do this on non log events + message.setDateThreadlastUpdated(new Date()); + if (message.getInReplyTo() != null) { + if (message.getInReplyTo().getThreadId() != null) { + message.setThreadId(message.getInReplyTo().getThreadId()); + } else { + message.setThreadId(message.getInReplyTo().getId()); + } + } + } + } + + @Override + public String saveMessage(Message message) { + return saveMessage(message, true); + } + + @Override + public String saveMessage(Message message, boolean logEvent) { + return saveMessage(message, logEvent, toolManager.getCurrentTool().getId(), getCurrentUser(), getContextId()); + } + + @Override + public String saveMessage(Message message, boolean logEvent, String toolId, String userId, String contextId) { + return saveMessage(message, logEvent, toolId, userId, contextId, false); + } + + @Override + public String saveMessage(Message message, boolean logEvent, boolean ignoreLockedTopicForum) { + return saveMessage(message, logEvent, toolManager.getCurrentTool().getId(), getCurrentUser(), getContextId(), ignoreLockedTopicForum); + } + + @Override + public String saveMessage(Message message, boolean logEvent, String toolId, String userId, String contextId, + boolean ignoreLockedTopicForum) { + + if (!ignoreLockedTopicForum && !(message instanceof PrivateMessage) + && isForumOrTopicLocked(message.getTopic().getBaseForum().getId(), message.getTopic().getId())) { + log.warn("saveMessage executed [messageId: new] but forum is locked -- save aborted"); + throw new LockedException("Message could not be saved [messageId: new]"); + } + + if (message.getModified() == null) { + message.setModified(new Date()); + } + if (message.getModifiedBy() == null && getCurrentUser() != null) { + message.setModifiedBy(getCurrentUser()); + } + if (message.getUuid() == null || message.getCreated() == null || message.getCreatedBy() == null + || message.getModified() == null || message.getModifiedBy() == null || message.getTitle() == null + || message.getAuthor() == null || message.getHasAttachments() == null || message.getTypeUuid() == null + || message.getDraft() == null) { + log.error("null attribute(s) for saving message in MessageForumsMessageManagerImpl.saveMessage"); + } + + if (message.getNumReaders() == null) { + message.setNumReaders(0); + } + manageThreadId(message, logEvent); + + final Message messageReturn = (Message) getSessionFactory().getCurrentSession().merge(message); + + handleEvent(messageReturn, logEvent, toolId, userId, contextId); + + log.debug("new message with id " + messageReturn.getId().toString() + " saved successfully"); + return messageReturn.getId().toString(); + } + + private void handleEvent(Message message, boolean logEvent, String toolId, String userId, String contextId) { + if (logEvent) { + if (isMessageFromForums(message)) { + eventTrackingService.post(eventTrackingService.newEvent(DiscussionForumService.EVENT_FORUMS_ADD, + getEventMessage(message, toolId, userId, contextId), false)); + } else { + eventTrackingService.post(eventTrackingService.newEvent(DiscussionForumService.EVENT_MESSAGES_ADD, + getEventMessage(message, toolId, userId, contextId), false)); + } + } + } + + private void manageThreadId(Message message, boolean logEvent) { + // MSGCNTR-448 if this is a top new top level message make sure the thread date + // is set + if (logEvent && message.getDateThreadlastUpdated() == null) { + // we don't need to do this on non log events + message.setDateThreadlastUpdated(new Date()); + if (message.getInReplyTo() != null) { + if (message.getInReplyTo().getThreadId() != null) { + message.setThreadId(message.getInReplyTo().getThreadId()); + } else { + message.setThreadId(message.getInReplyTo().getId()); + } + } + } } public void deleteMessage(Message message) { @@ -2002,5 +2090,5 @@ public List findMovedHistoryByMessageId(final Long messageid){ return getHibernateTemplate().execute(hcb); } - + } diff --git a/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/PermissionLevelManagerImpl.java b/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/PermissionLevelManagerImpl.java index c4f3643ef511..ee5f5c268f0b 100644 --- a/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/PermissionLevelManagerImpl.java +++ b/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/PermissionLevelManagerImpl.java @@ -302,12 +302,12 @@ public DBMembershipItem createDBMembershipItem(String name, String permissionLev return newDBMembershipItem; } - public void saveDBMembershipItem(DBMembershipItem item){ - getHibernateTemplate().saveOrUpdate(item); + public DBMembershipItem saveDBMembershipItem(DBMembershipItem item){ + return (DBMembershipItem) getSessionFactory().getCurrentSession().merge(item); } - public void savePermissionLevel(PermissionLevel level) { - getHibernateTemplate().saveOrUpdate(level); + public PermissionLevel savePermissionLevel(PermissionLevel level) { + return (PermissionLevel) getSessionFactory().getCurrentSession().merge(level); } public PermissionLevel getDefaultOwnerPermissionLevel(){ @@ -716,42 +716,42 @@ private void loadDefaultTypeAndPermissionLevelData() { PermissionsMask mask = getDefaultOwnerPermissionsMask(); PermissionLevel permLevel = createPermissionLevel(PermissionLevelManager.PERMISSION_LEVEL_NAME_OWNER, ownerType, mask); - savePermissionLevel(permLevel); + permLevel = savePermissionLevel(permLevel); } if (getDefaultPermissionLevel(authorType) == null) { PermissionsMask mask = getDefaultAuthorPermissionsMask(); PermissionLevel permLevel = createPermissionLevel(PermissionLevelManager.PERMISSION_LEVEL_NAME_AUTHOR, authorType, mask); - savePermissionLevel(permLevel); + permLevel = savePermissionLevel(permLevel); } if (getDefaultPermissionLevel(contributorType) == null) { PermissionsMask mask = getDefaultContributorPermissionsMask(); PermissionLevel permLevel = createPermissionLevel(PermissionLevelManager.PERMISSION_LEVEL_NAME_CONTRIBUTOR, contributorType, mask); - savePermissionLevel(permLevel); + permLevel = savePermissionLevel(permLevel); } if (getDefaultPermissionLevel(reviewerType) == null) { PermissionsMask mask = getDefaultReviewerPermissionsMask(); PermissionLevel permLevel = createPermissionLevel(PermissionLevelManager.PERMISSION_LEVEL_NAME_REVIEWER, reviewerType, mask); - savePermissionLevel(permLevel); + permLevel = savePermissionLevel(permLevel); } if (getDefaultPermissionLevel(noneditingAuthorType) == null) { PermissionsMask mask = getDefaultNoneditingAuthorPermissionsMask(); PermissionLevel permLevel = createPermissionLevel(PermissionLevelManager.PERMISSION_LEVEL_NAME_NONEDITING_AUTHOR, noneditingAuthorType, mask); - savePermissionLevel(permLevel); + permLevel = savePermissionLevel(permLevel); } if (getDefaultPermissionLevel(noneType) == null) { PermissionsMask mask = getDefaultNonePermissionsMask(); PermissionLevel permLevel = createPermissionLevel(PermissionLevelManager.PERMISSION_LEVEL_NAME_NONE, noneType, mask); - savePermissionLevel(permLevel); + permLevel = savePermissionLevel(permLevel); } } catch (Exception e) { log.warn("Error loading initial default types and/or permissions", e); diff --git a/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/ui/DiscussionForumManagerImpl.java b/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/ui/DiscussionForumManagerImpl.java index f1f0cb170b15..f706501b728c 100644 --- a/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/ui/DiscussionForumManagerImpl.java +++ b/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/ui/DiscussionForumManagerImpl.java @@ -33,6 +33,7 @@ import java.util.Vector; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.CollectionUtils; import org.sakaiproject.tool.api.Tool; import org.springframework.orm.hibernate4.support.HibernateDaoSupport; @@ -63,7 +64,6 @@ import org.sakaiproject.api.app.messageforums.events.ForumsTopicEventParams; import org.sakaiproject.api.app.messageforums.events.ForumsTopicEventParams.TopicEvent; import org.sakaiproject.api.app.messageforums.ui.DiscussionForumManager; -import org.sakaiproject.api.app.messageforums.ui.UIPermissionsManager; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.AuthzGroupService; import org.sakaiproject.authz.api.GroupNotDefinedException; @@ -78,7 +78,6 @@ import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.api.ContentHostingService; import org.sakaiproject.content.api.ContentResource; -import org.sakaiproject.entitybroker.EntityBroker; import org.sakaiproject.event.api.Event; import org.sakaiproject.event.api.EventTrackingService; import org.sakaiproject.event.api.LearningResourceStoreService; @@ -121,8 +120,6 @@ public class DiscussionForumManagerImpl extends HibernateDaoSupport implements private Map courseMemberMap = null; private boolean usingHelper = false; // just a flag until moved to database from helper private ContentHostingService contentHostingService; - private UIPermissionsManager permissionsManager; - private EntityBroker entityBroker; private MemoryService memoryService; private Cache> allowedFunctionsCache; private EventTrackingService eventTrackingService; @@ -137,11 +134,7 @@ public void init() log.info("init()"); allowedFunctionsCache = memoryService.getCache("org.sakaiproject.component.app.messageforums.ui.DiscussionForumManagerImpl.allowedFunctionsCache"); } - - public void setEntityBroker(EntityBroker entityBroker) { - this.entityBroker = entityBroker; - } - + public void setContentHostingService(ContentHostingService contentHostingService) { this.contentHostingService = contentHostingService; } @@ -476,17 +469,17 @@ public Message saveMessage(Message message, ForumsMessageEventParams params, boo { message.setTopic(getTopicById(message.getTopic().getId())); } - if(this.getAnonRole()==true&&message.getCreatedBy()==null) + if(this.getAnonRole() && message.getCreatedBy() == null) { message.setCreatedBy(".anon"); } - if(this.getAnonRole()==true&&message.getModifiedBy()==null) + if(this.getAnonRole() && message.getModifiedBy() == null) { message.setModifiedBy(".anon"); } // save the message first to ensure we have a valid message id - Message persistedMessage = messageManager.saveMessage(message, false, ignoreLockedTopicForum); + final Message persistedMessage = messageManager.saveOrUpdateMessage(message, false, ignoreLockedTopicForum); if (params != null) { Event event = eventTrackingService.newEvent(params.event.type, getEventMessage(persistedMessage), null, params.event.modification, NotificationService.NOTI_OPTIONAL, params.lrsStatement); @@ -760,22 +753,19 @@ public boolean hasNextTopic(DiscussionTopic topic) { for (Iterator iter = forum.getTopics().iterator(); iter.hasNext();) { - try{ - DiscussionTopic t = (DiscussionTopic) iter.next(); - if (next && getTopicAccess(t)) - { - return true; - } - if (t != null && getTopicAccess(t)) - { - if (t.getId().equals(topic.getId())) + try{ + DiscussionTopic t = (DiscussionTopic) iter.next(); + if (next && getTopicAccess(t)) { - next = true; + return true; } + if (t != null && getTopicAccess(t) && t.getId().equals(topic.getId())) + { + next = true; + } + }catch (Exception e) { + log.error(e.getMessage()); } - }catch (Exception e) { - log.error(e.getMessage()); - } } } @@ -1152,61 +1142,22 @@ public DiscussionForum saveForum(DiscussionForum forum, boolean draft, String co } boolean saveArea = forum.getId() == null; - forum.setDraft(Boolean.valueOf(draft)); -// ActorPermissions originalForumActorPermissions = null; -// if (saveArea) -// { -// originalForumActorPermissions = new ActorPermissionsImpl(); -// } -// else -// { -// originalForumActorPermissions = forum.getActorPermissions(); -// } -// // setcontributors -// List holdContributors = new ArrayList(); -// holdContributors = Arrays.asList(forum.getActorPermissions() -// .getContributors().toArray()); -// originalForumActorPermissions.setContributors(new UniqueArrayList());// clearing list at this -// // point. -// if (holdContributors != null && holdContributors.size() > 0) -// { -// Iterator iter = holdContributors.iterator(); -// while (iter.hasNext()) -// { -// MessageForumsUser user = (MessageForumsUser) iter.next(); -// forum.getActorPermissions().addContributor(user); -// } -// } -// // setAccessors -// List holdAccessors = new ArrayList(); -// holdAccessors = Arrays.asList(forum.getActorPermissions().getAccessors() -// .toArray()); -// originalForumActorPermissions.setAccessors(new UniqueArrayList());// clearing list at this point. -// if (holdAccessors != null && holdAccessors.size() > 0) -// { -// Iterator iter = holdAccessors.iterator(); -// while (iter.hasNext()) -// { -// MessageForumsUser user = (MessageForumsUser) iter.next(); -// forum.getActorPermissions().addAccesssor(user); -// } -// } - - forum = forumManager.saveDiscussionForum(forum, draft, logEvent, currentUser); + forum.setDraft(draft); + + final DiscussionForum forumReturn = forumManager.saveDiscussionForum(forum, draft, logEvent, currentUser); //set flag to false since permissions could have changed. This will force a clearing and resetting //of the permissions cache. - threadLocalManager.set("message_center_permission_set", Boolean.valueOf(false)); + threadLocalManager.set("message_center_permission_set", Boolean.FALSE); if (saveArea) { - //Area area = getDiscussionForumArea(); String dfType = typeManager.getDiscussionForumType(); Area area = areaManager.getAreaByContextIdAndTypeId(contextId, dfType); - forum.setArea(area); - forum.setSortIndex(Integer.valueOf(0)); - area.addDiscussionForum(forum); + forumReturn.setArea(area); + forumReturn.setSortIndex(0); + area.addDiscussionForum(forumReturn); areaManager.saveArea(area, currentUser); } - return forum; + return forumReturn; } @Override @@ -1776,11 +1727,7 @@ public boolean isForumOwner(Long forumId, String forumCreatedBy, String userId, { log.debug("isForumOwner(DiscussionForum " + forumId + ")"); } - if (forumCreatedBy.equals(userId) && !isRoleSwapView(siteId)) - { - return true; - } - return false; + return forumCreatedBy.equals(userId) && !isRoleSwapView(siteId); } private boolean isRoleSwapView(String siteId) @@ -1813,11 +1760,7 @@ public boolean isTopicOwner(Long topicId, String topicCreatedBy, String userId, { log.debug("isTopicOwner(DiscussionTopic " + topicId + ")"); } - if (topicCreatedBy.equals(userId) && !isRoleSwapView(siteId)) - { - return true; - } - return false; + return topicCreatedBy.equals(userId) && !isRoleSwapView(siteId); } private boolean getTopicAccess(DiscussionTopic t) @@ -2380,8 +2323,8 @@ public Map getReadStatusForMessagesWithId(List msgIds, Stri log.debug("getDiscussionForumsWithTopics()"); - Map msgIdStatusMap = new HashMap(); - if (msgIds == null || msgIds.size() == 0) { + Map msgIdStatusMap = new HashMap<>(); + if (CollectionUtils.isEmpty(msgIds)) { log.debug("empty map returns b/c no msgIds passed to getReadStatusForMessagesWithId"); return msgIdStatusMap; } @@ -2389,7 +2332,7 @@ public Map getReadStatusForMessagesWithId(List msgIds, Stri if (userId == null) { log.debug("empty user assume that all messages are read"); for (int i =0; i < msgIds.size(); i++) { - msgIdStatusMap.put(msgIds.get(i), Boolean.valueOf(true)); + msgIdStatusMap.put(msgIds.get(i), Boolean.TRUE); } return msgIdStatusMap; } diff --git a/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/ui/PrivateMessageManagerImpl.java b/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/ui/PrivateMessageManagerImpl.java index 227481571afc..0dd274dd52d9 100644 --- a/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/ui/PrivateMessageManagerImpl.java +++ b/msgcntr/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/ui/PrivateMessageManagerImpl.java @@ -328,7 +328,7 @@ public PrivateForum initializationHelper(PrivateForum forum, Area area, String u */ public void savePrivateMessage(Message message) { - messageManager.saveMessage(message); + messageManager.saveOrUpdateMessage(message); } /** @@ -336,7 +336,7 @@ public void savePrivateMessage(Message message) */ public void savePrivateMessage(Message message, boolean logEvent) { - messageManager.saveMessage(message, logEvent); + messageManager.saveOrUpdateMessage(message, logEvent); } public Message getMessageById(Long id) diff --git a/msgcntr/messageforums-hbm/src/java/org/sakaiproject/component/app/messageforums/dao/hibernate/OpenForum.hbm.xml b/msgcntr/messageforums-hbm/src/java/org/sakaiproject/component/app/messageforums/dao/hibernate/OpenForum.hbm.xml index c7941556baa7..88f3d8aa85f8 100644 --- a/msgcntr/messageforums-hbm/src/java/org/sakaiproject/component/app/messageforums/dao/hibernate/OpenForum.hbm.xml +++ b/msgcntr/messageforums-hbm/src/java/org/sakaiproject/component/app/messageforums/dao/hibernate/OpenForum.hbm.xml @@ -209,14 +209,11 @@ - diff --git a/msgcntr/messageforums-hbm/src/java/org/sakaiproject/component/app/messageforums/dao/hibernate/Topic.hbm.xml b/msgcntr/messageforums-hbm/src/java/org/sakaiproject/component/app/messageforums/dao/hibernate/Topic.hbm.xml index fb90c7b04b5a..bb6ecdff8846 100644 --- a/msgcntr/messageforums-hbm/src/java/org/sakaiproject/component/app/messageforums/dao/hibernate/Topic.hbm.xml +++ b/msgcntr/messageforums-hbm/src/java/org/sakaiproject/component/app/messageforums/dao/hibernate/Topic.hbm.xml @@ -52,7 +52,7 @@ - +