Example usage for com.liferay.portal.kernel.service ServiceContext isCommandUpdate

List of usage examples for com.liferay.portal.kernel.service ServiceContext isCommandUpdate

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.service ServiceContext isCommandUpdate.

Prototype

public boolean isCommandUpdate() 

Source Link

Document

Returns true if this service context contains an update command (i.e.

Usage

From source file:com.liferay.blogs.service.impl.BlogsEntryLocalServiceImpl.java

License:Open Source License

@Indexable(type = IndexableType.REINDEX)
@Override//from   w ww.ja  va 2s.c  om
public BlogsEntry updateStatus(long userId, long entryId, int status, ServiceContext serviceContext,
        Map<String, Serializable> workflowContext) throws PortalException {

    // Entry

    User user = userPersistence.findByPrimaryKey(userId);
    Date now = new Date();

    BlogsEntry entry = blogsEntryPersistence.findByPrimaryKey(entryId);

    int oldStatus = entry.getStatus();

    if ((status == WorkflowConstants.STATUS_APPROVED) && now.before(entry.getDisplayDate())) {

        status = WorkflowConstants.STATUS_SCHEDULED;
    }

    entry.setStatus(status);
    entry.setStatusByUserId(user.getUserId());
    entry.setStatusByUserName(user.getFullName());
    entry.setStatusDate(serviceContext.getModifiedDate(now));

    if ((status == WorkflowConstants.STATUS_APPROVED) && Validator.isNull(entry.getUrlTitle())) {

        entry.setUrlTitle(getUniqueUrlTitle(entryId, entry.getGroupId(), entry.getTitle()));
    }

    blogsEntryPersistence.update(entry);

    // Statistics

    blogsStatsUserLocalService.updateStatsUser(entry.getGroupId(), entry.getUserId(), entry.getDisplayDate());

    AssetEntry assetEntry = assetEntryLocalService.fetchEntry(BlogsEntry.class.getName(), entryId);

    if ((assetEntry == null) || (assetEntry.getPublishDate() == null)) {
        serviceContext.setCommand(Constants.ADD);
    }

    JSONObject extraDataJSONObject = JSONFactoryUtil.createJSONObject();

    extraDataJSONObject.put("title", entry.getTitle());

    if (status == WorkflowConstants.STATUS_APPROVED) {

        // Asset

        assetEntryLocalService.updateEntry(BlogsEntry.class.getName(), entryId, entry.getDisplayDate(), null,
                true, true);

        // Social

        if ((oldStatus != WorkflowConstants.STATUS_IN_TRASH)
                && (oldStatus != WorkflowConstants.STATUS_SCHEDULED)) {

            if (serviceContext.isCommandUpdate()) {
                SocialActivityManagerUtil.addActivity(user.getUserId(), entry, BlogsActivityKeys.UPDATE_ENTRY,
                        extraDataJSONObject.toString(), 0);
            } else {
                SocialActivityManagerUtil.addUniqueActivity(user.getUserId(), entry,
                        BlogsActivityKeys.ADD_ENTRY, extraDataJSONObject.toString(), 0);
            }
        }

        // Trash

        if (oldStatus == WorkflowConstants.STATUS_IN_TRASH) {
            if (PropsValues.BLOGS_ENTRY_COMMENTS_ENABLED) {
                CommentManagerUtil.restoreDiscussionFromTrash(BlogsEntry.class.getName(), entryId);
            }

            trashEntryLocalService.deleteEntry(BlogsEntry.class.getName(), entryId);
        }

        if (oldStatus != WorkflowConstants.STATUS_IN_TRASH) {

            // Subscriptions

            notifySubscribers(userId, entry, serviceContext, workflowContext);

            // Ping

            String[] trackbacks = (String[]) serviceContext.getAttribute("trackbacks");
            Boolean pingOldTrackbacks = ParamUtil.getBoolean(serviceContext, "pingOldTrackbacks");

            pingGoogle(entry, serviceContext);
            pingPingback(entry, serviceContext);
            pingTrackbacks(entry, trackbacks, pingOldTrackbacks, serviceContext);
        }
    } else {

        // Asset

        assetEntryLocalService.updateVisible(BlogsEntry.class.getName(), entryId, false);

        // Social

        if ((status == WorkflowConstants.STATUS_SCHEDULED)
                && (oldStatus != WorkflowConstants.STATUS_IN_TRASH)) {

            if (serviceContext.isCommandUpdate()) {
                SocialActivityManagerUtil.addActivity(user.getUserId(), entry, BlogsActivityKeys.UPDATE_ENTRY,
                        extraDataJSONObject.toString(), 0);
            } else {
                SocialActivityManagerUtil.addUniqueActivity(user.getUserId(), entry,
                        BlogsActivityKeys.ADD_ENTRY, extraDataJSONObject.toString(), 0);
            }
        }

        // Trash

        if (status == WorkflowConstants.STATUS_IN_TRASH) {
            if (PropsValues.BLOGS_ENTRY_COMMENTS_ENABLED) {
                CommentManagerUtil.moveDiscussionToTrash(BlogsEntry.class.getName(), entryId);
            }

            trashEntryLocalService.addTrashEntry(userId, entry.getGroupId(), BlogsEntry.class.getName(),
                    entry.getEntryId(), entry.getUuid(), null, oldStatus, null, null);
        } else if (oldStatus == WorkflowConstants.STATUS_IN_TRASH) {
            if (PropsValues.BLOGS_ENTRY_COMMENTS_ENABLED) {
                CommentManagerUtil.restoreDiscussionFromTrash(BlogsEntry.class.getName(), entryId);
            }

            trashEntryLocalService.deleteEntry(BlogsEntry.class.getName(), entryId);
        }
    }

    return entry;
}

From source file:com.liferay.blogs.service.impl.BlogsEntryLocalServiceImpl.java

License:Open Source License

protected void notifySubscribers(long userId, BlogsEntry entry, ServiceContext serviceContext,
        Map<String, Serializable> workflowContext) throws PortalException {

    String entryURL = (String) workflowContext.get(WorkflowConstants.CONTEXT_URL);

    if (!entry.isApproved() || Validator.isNull(entryURL)) {
        return;/*from w w w.  ja va2s. co  m*/
    }

    BlogsGroupServiceSettings blogsGroupServiceSettings = BlogsGroupServiceSettings
            .getInstance(entry.getGroupId());

    boolean sendEmailEntryUpdated = GetterUtil.getBoolean(serviceContext.getAttribute("sendEmailEntryUpdated"));

    if (serviceContext.isCommandAdd() && blogsGroupServiceSettings.isEmailEntryAddedEnabled()) {
    } else if (sendEmailEntryUpdated && serviceContext.isCommandUpdate()
            && blogsGroupServiceSettings.isEmailEntryUpdatedEnabled()) {
    } else {
        return;
    }

    Group group = groupPersistence.findByPrimaryKey(entry.getGroupId());

    String entryTitle = entry.getTitle();

    String fromName = blogsGroupServiceSettings.getEmailFromName();
    String fromAddress = blogsGroupServiceSettings.getEmailFromAddress();

    LocalizedValuesMap subjectLocalizedValuesMap = null;
    LocalizedValuesMap bodyLocalizedValuesMap = null;

    if (serviceContext.isCommandUpdate()) {
        subjectLocalizedValuesMap = blogsGroupServiceSettings.getEmailEntryUpdatedSubject();
        bodyLocalizedValuesMap = blogsGroupServiceSettings.getEmailEntryUpdatedBody();
    } else {
        subjectLocalizedValuesMap = blogsGroupServiceSettings.getEmailEntryAddedSubject();
        bodyLocalizedValuesMap = blogsGroupServiceSettings.getEmailEntryAddedBody();
    }

    SubscriptionSender subscriptionSender = new GroupSubscriptionCheckSubscriptionSender(
            BlogsPermission.RESOURCE_NAME);

    subscriptionSender.setClassPK(entry.getEntryId());
    subscriptionSender.setClassName(entry.getModelClassName());
    subscriptionSender.setCompanyId(entry.getCompanyId());
    subscriptionSender.setContextAttribute("[$BLOGS_ENTRY_CONTENT$]",
            StringUtil.shorten(HtmlUtil.stripHtml(entry.getContent()), 500), false);
    subscriptionSender.setContextAttributes("[$BLOGS_ENTRY_CREATE_DATE$]",
            Time.getSimpleDate(entry.getCreateDate(), "yyyy/MM/dd"), "[$BLOGS_ENTRY_DESCRIPTION$]",
            entry.getDescription(), "[$BLOGS_ENTRY_SITE_NAME$]",
            group.getDescriptiveName(serviceContext.getLocale()), "[$BLOGS_ENTRY_STATUS_BY_USER_NAME$]",
            entry.getStatusByUserName(), "[$BLOGS_ENTRY_TITLE$]", entryTitle, "[$BLOGS_ENTRY_UPDATE_COMMENT$]",
            HtmlUtil.replaceNewLine(
                    GetterUtil.getString(serviceContext.getAttribute("emailEntryUpdatedComment"))),
            "[$BLOGS_ENTRY_URL$]", entryURL, "[$BLOGS_ENTRY_USER_PORTRAIT_URL$]",
            workflowContext.get(WorkflowConstants.CONTEXT_USER_PORTRAIT_URL), "[$BLOGS_ENTRY_USER_URL$]",
            workflowContext.get(WorkflowConstants.CONTEXT_USER_URL));
    subscriptionSender.setContextCreatorUserPrefix("BLOGS_ENTRY");
    subscriptionSender.setCreatorUserId(entry.getUserId());
    subscriptionSender.setCurrentUserId(userId);
    subscriptionSender.setEntryTitle(entryTitle);
    subscriptionSender.setEntryURL(entryURL);
    subscriptionSender.setFrom(fromAddress, fromName);
    subscriptionSender.setHtmlFormat(true);

    if (bodyLocalizedValuesMap != null) {
        subscriptionSender.setLocalizedBodyMap(LocalizationUtil.getMap(bodyLocalizedValuesMap));
    }

    if (subjectLocalizedValuesMap != null) {
        subscriptionSender.setLocalizedSubjectMap(LocalizationUtil.getMap(subjectLocalizedValuesMap));
    }

    subscriptionSender.setMailId("blogs_entry", entry.getEntryId());

    int notificationType = UserNotificationDefinition.NOTIFICATION_TYPE_ADD_ENTRY;

    if (serviceContext.isCommandUpdate()) {
        notificationType = UserNotificationDefinition.NOTIFICATION_TYPE_UPDATE_ENTRY;
    }

    subscriptionSender.setNotificationType(notificationType);

    String portletId = PortletProviderUtil.getPortletId(BlogsEntry.class.getName(),
            PortletProvider.Action.VIEW);

    subscriptionSender.setPortletId(portletId);
    subscriptionSender.setReplyToAddress(fromAddress);
    subscriptionSender.setScopeGroupId(entry.getGroupId());
    subscriptionSender.setServiceContext(serviceContext);

    subscriptionSender.addPersistedSubscribers(BlogsEntry.class.getName(), entry.getGroupId());

    subscriptionSender.addPersistedSubscribers(BlogsEntry.class.getName(), entry.getEntryId());

    subscriptionSender.flushNotificationsAsync();
}

From source file:com.liferay.bookmarks.service.impl.BookmarksEntryLocalServiceImpl.java

License:Open Source License

protected void notifySubscribers(long userId, BookmarksEntry entry, ServiceContext serviceContext)
        throws PortalException {

    String layoutFullURL = serviceContext.getLayoutFullURL();

    if (!entry.isApproved() || Validator.isNull(layoutFullURL)) {
        return;//from   w ww  .j av  a  2  s  .c  om
    }

    BookmarksGroupServiceOverriddenConfiguration bookmarksGroupServiceOverriddenConfiguration = configurationProvider
            .getConfiguration(BookmarksGroupServiceOverriddenConfiguration.class,
                    new GroupServiceSettingsLocator(entry.getGroupId(), BookmarksConstants.SERVICE_NAME));

    if ((serviceContext.isCommandAdd()
            && !bookmarksGroupServiceOverriddenConfiguration.emailEntryAddedEnabled())
            || (serviceContext.isCommandUpdate()
                    && !bookmarksGroupServiceOverriddenConfiguration.emailEntryUpdatedEnabled())) {

        return;
    }

    String statusByUserName = StringPool.BLANK;

    try {
        User user = userLocalService.getUserById(serviceContext.getGuestOrUserId());

        statusByUserName = user.getFullName();
    } catch (Exception e) {
        _log.error(e, e);
    }

    String entryTitle = entry.getName();

    StringBundler sb = new StringBundler(7);

    sb.append(layoutFullURL);
    sb.append(Portal.FRIENDLY_URL_SEPARATOR);
    sb.append("bookmarks");
    sb.append(StringPool.SLASH);
    sb.append("folder");
    sb.append(StringPool.SLASH);
    sb.append(entry.getFolderId());

    String entryURL = sb.toString();

    String fromName = bookmarksGroupServiceOverriddenConfiguration.emailFromName();
    String fromAddress = bookmarksGroupServiceOverriddenConfiguration.emailFromAddress();

    LocalizedValuesMap subjectLocalizedValuesMap = null;
    LocalizedValuesMap bodyLocalizedValuesMap = null;

    if (serviceContext.isCommandUpdate()) {
        subjectLocalizedValuesMap = bookmarksGroupServiceOverriddenConfiguration.emailEntryUpdatedSubject();
        bodyLocalizedValuesMap = bookmarksGroupServiceOverriddenConfiguration.emailEntryUpdatedBody();
    } else {
        subjectLocalizedValuesMap = bookmarksGroupServiceOverriddenConfiguration.emailEntryAddedSubject();
        bodyLocalizedValuesMap = bookmarksGroupServiceOverriddenConfiguration.emailEntryAddedBody();
    }

    SubscriptionSender subscriptionSender = new GroupSubscriptionCheckSubscriptionSender(
            BookmarksResourcePermissionChecker.RESOURCE_NAME);

    subscriptionSender.setClassName(entry.getModelClassName());
    subscriptionSender.setClassPK(entry.getEntryId());
    subscriptionSender.setCompanyId(entry.getCompanyId());
    subscriptionSender.setContextAttributes("[$BOOKMARKS_ENTRY_STATUS_BY_USER_NAME$]", statusByUserName,
            "[$BOOKMARKS_ENTRY_URL$]", entryURL);
    subscriptionSender.setContextCreatorUserPrefix("BOOKMARKS_ENTRY");
    subscriptionSender.setCreatorUserId(entry.getUserId());
    subscriptionSender.setCurrentUserId(userId);
    subscriptionSender.setEntryTitle(entryTitle);
    subscriptionSender.setEntryURL(entryURL);
    subscriptionSender.setFrom(fromAddress, fromName);
    subscriptionSender.setHtmlFormat(true);

    if (bodyLocalizedValuesMap != null) {
        subscriptionSender.setLocalizedBodyMap(LocalizationUtil.getMap(bodyLocalizedValuesMap));
    }

    if (subjectLocalizedValuesMap != null) {
        subscriptionSender.setLocalizedSubjectMap(LocalizationUtil.getMap(subjectLocalizedValuesMap));
    }

    subscriptionSender.setMailId("bookmarks_entry", entry.getEntryId());

    int notificationType = UserNotificationDefinition.NOTIFICATION_TYPE_ADD_ENTRY;

    if (serviceContext.isCommandUpdate()) {
        notificationType = UserNotificationDefinition.NOTIFICATION_TYPE_UPDATE_ENTRY;
    }

    subscriptionSender.setNotificationType(notificationType);

    subscriptionSender.setPortletId(BookmarksPortletKeys.BOOKMARKS);
    subscriptionSender.setReplyToAddress(fromAddress);
    subscriptionSender.setScopeGroupId(entry.getGroupId());
    subscriptionSender.setServiceContext(serviceContext);

    BookmarksFolder folder = entry.getFolder();

    if (folder != null) {
        subscriptionSender.addPersistedSubscribers(BookmarksFolder.class.getName(), folder.getFolderId());

        for (Long ancestorFolderId : folder.getAncestorFolderIds()) {
            subscriptionSender.addPersistedSubscribers(BookmarksFolder.class.getName(), ancestorFolderId);
        }
    }

    subscriptionSender.addPersistedSubscribers(BookmarksFolder.class.getName(), entry.getGroupId());

    subscriptionSender.addPersistedSubscribers(BookmarksEntry.class.getName(), entry.getEntryId());

    subscriptionSender.flushNotificationsAsync();
}

From source file:com.liferay.document.library.internal.service.SubscriptionDLAppHelperLocalServiceWrapper.java

License:Open Source License

protected void notifySubscribers(long userId, FileVersion fileVersion, String entryURL,
        ServiceContext serviceContext) throws PortalException {

    if (!fileVersion.isApproved() || Validator.isNull(entryURL)) {
        return;/* ww  w  . j a  v a 2  s. c o  m*/
    }

    DLGroupServiceSettings dlGroupServiceSettings = DLGroupServiceSettings
            .getInstance(fileVersion.getGroupId());

    boolean commandUpdate = false;

    if (serviceContext.isCommandUpdate() || Constants.CHECKIN.equals(serviceContext.getCommand())) {

        commandUpdate = true;
    }

    if (serviceContext.isCommandAdd() && dlGroupServiceSettings.isEmailFileEntryAddedEnabled()) {
    } else if (commandUpdate && dlGroupServiceSettings.isEmailFileEntryUpdatedEnabled()) {
    } else {
        return;
    }

    String entryTitle = fileVersion.getTitle();

    String fromName = dlGroupServiceSettings.getEmailFromName();
    String fromAddress = dlGroupServiceSettings.getEmailFromAddress();

    LocalizedValuesMap subjectLocalizedValuesMap = null;
    LocalizedValuesMap bodyLocalizedValuesMap = null;

    if (commandUpdate) {
        subjectLocalizedValuesMap = dlGroupServiceSettings.getEmailFileEntryUpdatedSubject();
        bodyLocalizedValuesMap = dlGroupServiceSettings.getEmailFileEntryUpdatedBody();
    } else {
        subjectLocalizedValuesMap = dlGroupServiceSettings.getEmailFileEntryAddedSubject();
        bodyLocalizedValuesMap = dlGroupServiceSettings.getEmailFileEntryAddedBody();
    }

    FileEntry fileEntry = fileVersion.getFileEntry();

    Folder folder = null;

    long folderId = fileEntry.getFolderId();

    if (folderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
        folder = _dlAppLocalService.getFolder(folderId);
    }

    SubscriptionSender subscriptionSender = new GroupSubscriptionCheckSubscriptionSender(
            DLPermission.RESOURCE_NAME);

    DLFileEntry dlFileEntry = (DLFileEntry) fileEntry.getModel();

    DLFileEntryType dlFileEntryType = _dlFileEntryTypeLocalService
            .getDLFileEntryType(dlFileEntry.getFileEntryTypeId());

    subscriptionSender.setClassPK(fileVersion.getFileEntryId());
    subscriptionSender.setClassName(DLFileEntryConstants.getClassName());
    subscriptionSender.setCompanyId(fileVersion.getCompanyId());

    if (folder != null) {
        subscriptionSender.setContextAttribute("[$FOLDER_NAME$]", folder.getName(), true);
    } else {
        subscriptionSender.setLocalizedContextAttribute("[$FOLDER_NAME$]",
                new EscapableLocalizableFunction(locale -> LanguageUtil.get(locale, "home")));
    }

    subscriptionSender.setContextAttributes("[$DOCUMENT_STATUS_BY_USER_NAME$]",
            fileVersion.getStatusByUserName(), "[$DOCUMENT_TITLE$]", entryTitle, "[$DOCUMENT_URL$]", entryURL);
    subscriptionSender.setContextCreatorUserPrefix("DOCUMENT");
    subscriptionSender.setCreatorUserId(fileVersion.getUserId());
    subscriptionSender.setCurrentUserId(userId);
    subscriptionSender.setEntryTitle(entryTitle);
    subscriptionSender.setEntryURL(entryURL);
    subscriptionSender.setFrom(fromAddress, fromName);
    subscriptionSender.setHtmlFormat(true);
    subscriptionSender.setLocalizedBodyMap(LocalizationUtil.getMap(bodyLocalizedValuesMap));
    subscriptionSender.setLocalizedContextAttribute("[$DOCUMENT_TYPE$]",
            new EscapableLocalizableFunction(locale -> dlFileEntryType.getName(locale)));
    subscriptionSender.setLocalizedSubjectMap(LocalizationUtil.getMap(subjectLocalizedValuesMap));
    subscriptionSender.setMailId("file_entry", fileVersion.getFileEntryId());

    int notificationType = UserNotificationDefinition.NOTIFICATION_TYPE_ADD_ENTRY;

    if (commandUpdate) {
        notificationType = UserNotificationDefinition.NOTIFICATION_TYPE_UPDATE_ENTRY;
    }

    subscriptionSender.setNotificationType(notificationType);

    String portletId = PortletProviderUtil.getPortletId(FileEntry.class.getName(), PortletProvider.Action.VIEW);

    subscriptionSender.setPortletId(portletId);

    subscriptionSender.setReplyToAddress(fromAddress);
    subscriptionSender.setScopeGroupId(fileVersion.getGroupId());
    subscriptionSender.setServiceContext(serviceContext);

    subscriptionSender.addPersistedSubscribers(DLFolder.class.getName(), fileVersion.getGroupId());

    if (folder != null) {
        subscriptionSender.addPersistedSubscribers(DLFolder.class.getName(), folder.getFolderId());

        for (Long ancestorFolderId : folder.getAncestorFolderIds()) {
            subscriptionSender.addPersistedSubscribers(DLFolder.class.getName(), ancestorFolderId);
        }
    }

    if (dlFileEntryType.getFileEntryTypeId() == DLFileEntryTypeConstants.FILE_ENTRY_TYPE_ID_BASIC_DOCUMENT) {

        subscriptionSender.addPersistedSubscribers(DLFileEntryType.class.getName(), fileVersion.getGroupId());
    } else {
        subscriptionSender.addPersistedSubscribers(DLFileEntryType.class.getName(),
                dlFileEntryType.getFileEntryTypeId());
    }

    subscriptionSender.addPersistedSubscribers(DLFileEntry.class.getName(), fileEntry.getFileEntryId());

    subscriptionSender.flushNotificationsAsync();
}

From source file:com.liferay.journal.service.impl.JournalArticleLocalServiceImpl.java

License:Open Source License

/**
 * Updates the workflow status of the web content article.
 *
 * @param  userId the primary key of the user updating the web content
 *         article's status//from w w  w  .jav  a2s .co m
 * @param  article the web content article
 * @param  status the web content article's workflow status. For more
 *         information see {@link WorkflowConstants} for constants starting
 *         with the "STATUS_" prefix.
 * @param  articleURL the web content article's accessible URL
 * @param  serviceContext the service context to be applied. Can set the
 *         modification date, status date, and portlet preferences. With
 *         respect to social activities, by setting the service context's
 *         command to {@link Constants#UPDATE}, the invocation is considered
 *         a web content update activity; otherwise it is considered a web
 *         content add activity.
 * @param  workflowContext the web content article's configured workflow
 *         context
 * @return the updated web content article
 */
@Indexable(type = IndexableType.REINDEX)
@Override
public JournalArticle updateStatus(long userId, JournalArticle article, int status, String articleURL,
        ServiceContext serviceContext, Map<String, Serializable> workflowContext) throws PortalException {

    // Article

    User user = userLocalService.getUser(userId);
    Date now = new Date();

    if ((status == WorkflowConstants.STATUS_APPROVED)
            && (article.getClassNameId() == JournalArticleConstants.CLASSNAME_ID_DEFAULT)
            && (article.getDisplayDate() != null) && now.before(article.getDisplayDate())) {

        status = WorkflowConstants.STATUS_SCHEDULED;
    }

    int oldStatus = article.getStatus();

    Date modifiedDate = serviceContext.getModifiedDate(now);

    article.setModifiedDate(modifiedDate);

    if (status == WorkflowConstants.STATUS_APPROVED) {
        Date expirationDate = article.getExpirationDate();

        if ((expirationDate != null) && expirationDate.before(now)) {
            article.setExpirationDate(null);
        }
    }

    if (status == WorkflowConstants.STATUS_EXPIRED) {
        article.setExpirationDate(now);
    }

    article.setStatus(status);
    article.setStatusByUserId(user.getUserId());
    article.setStatusByUserName(user.getFullName());
    article.setStatusDate(modifiedDate);

    journalArticlePersistence.update(article);

    if (isExpireAllArticleVersions(article.getCompanyId())) {
        setArticlesExpirationDate(article);
    }

    if (hasModifiedLatestApprovedVersion(article.getGroupId(), article.getArticleId(), article.getVersion())) {

        if (status == WorkflowConstants.STATUS_APPROVED) {
            updateUrlTitles(article.getGroupId(), article.getArticleId(), article.getUrlTitle());

            // Asset

            String title = article.getTitleMapAsXML();
            String description = article.getDescriptionMapAsXML();

            if ((oldStatus != WorkflowConstants.STATUS_APPROVED)
                    && (article.getVersion() != JournalArticleConstants.VERSION_DEFAULT)) {

                AssetEntry draftAssetEntry = assetEntryLocalService.fetchEntry(JournalArticle.class.getName(),
                        article.getPrimaryKey());

                if (draftAssetEntry != null) {
                    long[] assetCategoryIds = draftAssetEntry.getCategoryIds();
                    String[] assetTagNames = draftAssetEntry.getTagNames();

                    List<AssetLink> assetLinks = assetLinkLocalService.getDirectLinks(
                            draftAssetEntry.getEntryId(), AssetLinkConstants.TYPE_RELATED, false);

                    long[] assetLinkEntryIds = ListUtil.toLongArray(assetLinks, AssetLink.ENTRY_ID2_ACCESSOR);

                    AssetEntry assetEntry = assetEntryLocalService.updateEntry(userId, article.getGroupId(),
                            article.getCreateDate(), article.getModifiedDate(), JournalArticle.class.getName(),
                            article.getResourcePrimKey(), article.getUuid(), getClassTypeId(article),
                            assetCategoryIds, assetTagNames, isListable(article), false, null, null, null, null,
                            ContentTypes.TEXT_HTML, title, description, description, null,
                            article.getLayoutUuid(), 0, 0, draftAssetEntry.getPriority());

                    assetLinkLocalService.updateLinks(userId, assetEntry.getEntryId(), assetLinkEntryIds,
                            AssetLinkConstants.TYPE_RELATED);

                    assetEntryLocalService.deleteEntry(draftAssetEntry);
                }
            }

            if (article.getClassNameId() == JournalArticleConstants.CLASSNAME_ID_DEFAULT) {

                assetEntryLocalService.updateEntry(JournalArticle.class.getName(), article.getResourcePrimKey(),
                        article.getDisplayDate(), article.getExpirationDate(), isListable(article), true);
            }

            // Social

            JSONObject extraDataJSONObject = JSONFactoryUtil.createJSONObject();

            extraDataJSONObject.put("title", title);

            if (serviceContext.isCommandUpdate()) {
                SocialActivityManagerUtil.addActivity(user.getUserId(), article,
                        JournalActivityKeys.UPDATE_ARTICLE, extraDataJSONObject.toString(), 0);
            } else {
                SocialActivityManagerUtil.addUniqueActivity(user.getUserId(), article,
                        JournalActivityKeys.ADD_ARTICLE, extraDataJSONObject.toString(), 0);
            }
        } else if (oldStatus == WorkflowConstants.STATUS_APPROVED) {
            updatePreviousApprovedArticle(article);
        }
    }

    if ((article.getClassNameId() == JournalArticleConstants.CLASSNAME_ID_DEFAULT)
            && (oldStatus != WorkflowConstants.STATUS_IN_TRASH)
            && (status != WorkflowConstants.STATUS_IN_TRASH)) {

        // Email

        if ((oldStatus == WorkflowConstants.STATUS_PENDING) && ((status == WorkflowConstants.STATUS_APPROVED)
                || (status == WorkflowConstants.STATUS_DENIED))) {

            String msg = "granted";

            if (status == WorkflowConstants.STATUS_DENIED) {
                msg = "denied";
            }

            try {
                PortletPreferences preferences = ServiceContextUtil.getPortletPreferences(serviceContext);

                articleURL = buildArticleURL(articleURL, article.getGroupId(), article.getFolderId(),
                        article.getArticleId());

                sendEmail(article, articleURL, preferences, msg, serviceContext);
            } catch (Exception e) {
                _log.error("Unable to send email to notify the change of status " + "to " + msg
                        + " for article " + article.getId() + ": " + e.getMessage());
            }
        }

        // Subscriptions

        String action = "update";

        if (article.getVersion() == 1.0) {
            action = "add";
        }

        notifySubscribers(user.getUserId(), article, action, serviceContext);
    }

    return article;
}

From source file:com.liferay.message.boards.internal.service.SubscriptionMBMessageLocalServiceWrapper.java

License:Open Source License

protected MBSubscriptionSender getSubscriptionSender(long userId, MBCategory category, MBMessage message,
        String messageURL, String entryTitle, boolean htmlFormat, String messageBody, String messageSubject,
        String messageSubjectPrefix, String inReplyTo, String fromName, String fromAddress,
        String replyToAddress, String emailAddress, String fullName,
        LocalizedValuesMap subjectLocalizedValuesMap, LocalizedValuesMap bodyLocalizedValuesMap,
        ServiceContext serviceContext) {

    MBSubscriptionSender subscriptionSender = new MBSubscriptionSender(MBPermission.RESOURCE_NAME);

    subscriptionSender.setAnonymous(message.isAnonymous());
    subscriptionSender.setBulk(PropsValues.MESSAGE_BOARDS_EMAIL_BULK);
    subscriptionSender.setClassName(message.getModelClassName());
    subscriptionSender.setClassPK(message.getMessageId());
    subscriptionSender.setCompanyId(message.getCompanyId());
    subscriptionSender.setContextAttribute("[$MESSAGE_BODY$]", messageBody, false);

    long groupId = message.getGroupId();

    if (category.getCategoryId() != MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {

        subscriptionSender.setContextAttribute("[$CATEGORY_NAME$]", category.getName(), true);
    } else {/* w ww .ja v a2s  . c  o m*/
        try {
            Group group = _groupLocalService.getGroup(groupId);

            subscriptionSender.setLocalizedContextAttribute("[$CATEGORY_NAME$]",
                    new EscapableLocalizableFunction(locale -> _getLocalizedRootCategoryName(group, locale)));
        } catch (PortalException pe) {
            ReflectionUtil.throwException(pe);
        }
    }

    subscriptionSender.setContextAttributes("[$MAILING_LIST_ADDRESS$]", replyToAddress, "[$MESSAGE_ID$]",
            message.getMessageId(), "[$MESSAGE_SUBJECT$]", messageSubject, "[$MESSAGE_SUBJECT_PREFIX$]",
            messageSubjectPrefix, "[$MESSAGE_URL$]", messageURL, "[$MESSAGE_USER_ADDRESS$]", emailAddress,
            "[$MESSAGE_USER_NAME$]", fullName);
    subscriptionSender.setCurrentUserId(userId);
    subscriptionSender.setEntryTitle(entryTitle);
    subscriptionSender.setEntryURL(messageURL);
    subscriptionSender.setFrom(fromAddress, fromName);
    subscriptionSender.setFullName(fullName);
    subscriptionSender.setHtmlFormat(htmlFormat);
    subscriptionSender.setInReplyTo(inReplyTo);

    if (bodyLocalizedValuesMap != null) {
        subscriptionSender.setLocalizedBodyMap(LocalizationUtil.getMap(bodyLocalizedValuesMap));
    }

    if (subjectLocalizedValuesMap != null) {
        subscriptionSender.setLocalizedSubjectMap(LocalizationUtil.getMap(subjectLocalizedValuesMap));
    }

    Date modifiedDate = message.getModifiedDate();

    subscriptionSender.setMailId(MBUtil.MESSAGE_POP_PORTLET_PREFIX, message.getCategoryId(),
            message.getMessageId(), modifiedDate.getTime());

    int notificationType = UserNotificationDefinition.NOTIFICATION_TYPE_ADD_ENTRY;

    if (serviceContext.isCommandUpdate()) {
        notificationType = UserNotificationDefinition.NOTIFICATION_TYPE_UPDATE_ENTRY;
    }

    subscriptionSender.setNotificationType(notificationType);

    String portletId = PortletProviderUtil.getPortletId(MBMessage.class.getName(), PortletProvider.Action.VIEW);

    subscriptionSender.setPortletId(portletId);

    subscriptionSender.setReplyToAddress(replyToAddress);
    subscriptionSender.setScopeGroupId(groupId);
    subscriptionSender.setServiceContext(serviceContext);
    subscriptionSender.setUniqueMailId(false);

    return subscriptionSender;
}

From source file:com.liferay.message.boards.internal.service.SubscriptionMBMessageLocalServiceWrapper.java

License:Open Source License

protected void notifyDiscussionSubscribers(long userId, MBMessage message, ServiceContext serviceContext)
        throws PortalException {

    if (!PrefsPropsUtil.getBoolean(message.getCompanyId(), PropsKeys.DISCUSSION_EMAIL_COMMENTS_ADDED_ENABLED)) {

        return;//w w w .  j av a  2 s.  com
    }

    MBDiscussion mbDiscussion = _mbDiscussionLocalService.getThreadDiscussion(message.getThreadId());

    String contentURL = (String) serviceContext.getAttribute("contentURL");

    contentURL = _http.addParameter(contentURL, serviceContext.getAttribute("namespace") + "messageId",
            message.getMessageId());

    String userAddress = StringPool.BLANK;
    String userName = (String) serviceContext.getAttribute("pingbackUserName");

    if (Validator.isNull(userName)) {
        userAddress = _portal.getUserEmailAddress(message.getUserId());
        userName = _portal.getUserName(message.getUserId(), StringPool.BLANK);
    }

    String fromName = PrefsPropsUtil.getString(message.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
    String fromAddress = PrefsPropsUtil.getString(message.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);

    String subject = PrefsPropsUtil.getContent(message.getCompanyId(), PropsKeys.DISCUSSION_EMAIL_SUBJECT);
    String body = PrefsPropsUtil.getContent(message.getCompanyId(), PropsKeys.DISCUSSION_EMAIL_BODY);

    SubscriptionSender subscriptionSender = new SubscriptionSender();

    subscriptionSender.setBody(body);
    subscriptionSender.setCompanyId(message.getCompanyId());
    subscriptionSender.setClassName(MBDiscussion.class.getName());
    subscriptionSender.setClassPK(mbDiscussion.getDiscussionId());
    subscriptionSender.setContextAttribute("[$COMMENTS_BODY$]", message.getBody(message.isFormatBBCode()),
            false);
    subscriptionSender.setContextAttributes("[$COMMENTS_USER_ADDRESS$]", userAddress, "[$COMMENTS_USER_NAME$]",
            userName, "[$CONTENT_URL$]", contentURL);
    subscriptionSender.setCurrentUserId(userId);
    subscriptionSender.setEntryTitle(message.getBody());
    subscriptionSender.setEntryURL(contentURL);
    subscriptionSender.setFrom(fromAddress, fromName);
    subscriptionSender.setHtmlFormat(true);

    Date modifiedDate = message.getModifiedDate();

    subscriptionSender.setMailId("mb_discussion", message.getCategoryId(), message.getMessageId(),
            modifiedDate.getTime());

    int notificationType = UserNotificationDefinition.NOTIFICATION_TYPE_ADD_ENTRY;

    if (serviceContext.isCommandUpdate()) {
        notificationType = UserNotificationDefinition.NOTIFICATION_TYPE_UPDATE_ENTRY;
    }

    subscriptionSender.setNotificationType(notificationType);

    String portletId = PortletProviderUtil.getPortletId(Comment.class.getName(), PortletProvider.Action.VIEW);

    subscriptionSender.setPortletId(portletId);

    subscriptionSender.setScopeGroupId(message.getGroupId());
    subscriptionSender.setServiceContext(serviceContext);
    subscriptionSender.setSubject(subject);
    subscriptionSender.setUniqueMailId(false);

    String className = (String) serviceContext.getAttribute("className");
    long classPK = ParamUtil.getLong(serviceContext, "classPK");

    subscriptionSender.addPersistedSubscribers(className, classPK);

    subscriptionSender.flushNotificationsAsync();
}

From source file:com.liferay.message.boards.internal.service.SubscriptionMBMessageLocalServiceWrapper.java

License:Open Source License

protected void notifySubscribers(long userId, MBMessage message, String messageURL,
        ServiceContext serviceContext) throws PortalException {

    if (!message.isApproved() || Validator.isNull(messageURL)) {
        return;/*from  w  w w .jav  a 2  s  . c o m*/
    }

    if (message.isDiscussion()) {
        try {
            notifyDiscussionSubscribers(userId, message, serviceContext);
        } catch (Exception e) {
            _log.error(e, e);
        }

        return;
    }

    MBGroupServiceSettings mbGroupServiceSettings = MBGroupServiceSettings.getInstance(message.getGroupId());

    if (serviceContext.isCommandAdd() && mbGroupServiceSettings.isEmailMessageAddedEnabled()) {
    } else if (serviceContext.isCommandUpdate() && mbGroupServiceSettings.isEmailMessageUpdatedEnabled()) {
    } else {
        return;
    }

    Company company = _companyLocalService.getCompany(message.getCompanyId());

    User user = _userLocalService.getUser(userId);

    String emailAddress = user.getEmailAddress();
    String fullName = user.getFullName();

    if (message.isAnonymous()) {
        emailAddress = StringPool.BLANK;
        fullName = serviceContext.translate("anonymous");
    }

    MBCategory category = message.getCategory();

    List<Long> categoryIds = new ArrayList<>();

    categoryIds.add(message.getCategoryId());

    if (message.getCategoryId() != MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {

        categoryIds.addAll(category.getAncestorCategoryIds());
    }

    String entryTitle = message.getSubject();

    String fromName = mbGroupServiceSettings.getEmailFromName();
    String fromAddress = mbGroupServiceSettings.getEmailFromAddress();

    String replyToAddress = StringPool.BLANK;

    if (PropsValues.POP_SERVER_NOTIFICATIONS_ENABLED) {
        replyToAddress = MBUtil.getReplyToAddress(message.getCategoryId(), message.getMessageId(),
                company.getMx(), fromAddress);
    }

    LocalizedValuesMap subjectLocalizedValuesMap = null;
    LocalizedValuesMap bodyLocalizedValuesMap = null;

    if (serviceContext.isCommandUpdate()) {
        subjectLocalizedValuesMap = mbGroupServiceSettings.getEmailMessageUpdatedSubject();
        bodyLocalizedValuesMap = mbGroupServiceSettings.getEmailMessageUpdatedBody();
    } else {
        subjectLocalizedValuesMap = mbGroupServiceSettings.getEmailMessageAddedSubject();
        bodyLocalizedValuesMap = mbGroupServiceSettings.getEmailMessageAddedBody();
    }

    boolean htmlFormat = mbGroupServiceSettings.isEmailHtmlFormat();

    String messageBody = message.getBody();

    if (htmlFormat && message.isFormatBBCode()) {
        try {
            messageBody = BBCodeTranslatorUtil.getHTML(messageBody);

            HttpServletRequest request = serviceContext.getRequest();

            if (request != null) {
                ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

                messageBody = MBUtil.replaceMessageBodyPaths(themeDisplay, messageBody);
            }
        } catch (Exception e) {
            _log.error(StringBundler.concat("Unable to parse message ", String.valueOf(message.getMessageId()),
                    ": ", e.getMessage()));
        }
    }

    String inReplyTo = null;
    String messageSubject = message.getSubject();
    String messageSubjectPrefix = StringPool.BLANK;

    if (message.getParentMessageId() != MBMessageConstants.DEFAULT_PARENT_MESSAGE_ID) {

        MBMessage parentMessage = _mbMessageLocalService.getMessage(message.getParentMessageId());

        Date modifiedDate = parentMessage.getModifiedDate();

        inReplyTo = _portal.getMailId(company.getMx(), MBUtil.MESSAGE_POP_PORTLET_PREFIX,
                message.getCategoryId(), parentMessage.getMessageId(), modifiedDate.getTime());

        if (messageSubject.startsWith(MBMessageConstants.MESSAGE_SUBJECT_PREFIX_RE)) {

            messageSubjectPrefix = MBMessageConstants.MESSAGE_SUBJECT_PREFIX_RE;

            messageSubject = messageSubject.substring(messageSubjectPrefix.length());
        }
    }

    SubscriptionSender subscriptionSender = getSubscriptionSender(userId, category, message, messageURL,
            entryTitle, htmlFormat, messageBody, messageSubject, messageSubjectPrefix, inReplyTo, fromName,
            fromAddress, replyToAddress, emailAddress, fullName, subjectLocalizedValuesMap,
            bodyLocalizedValuesMap, serviceContext);

    subscriptionSender.addPersistedSubscribers(MBCategory.class.getName(), message.getGroupId());

    for (long categoryId : categoryIds) {
        if (categoryId != MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {
            subscriptionSender.addPersistedSubscribers(MBCategory.class.getName(), categoryId);
        }
    }

    subscriptionSender.addPersistedSubscribers(MBThread.class.getName(), message.getThreadId());

    subscriptionSender.flushNotificationsAsync();

    if (!MailingListThreadLocal.isSourceMailingList()) {
        for (long categoryId : categoryIds) {
            MBSubscriptionSender sourceMailingListSubscriptionSender = getSubscriptionSender(userId, category,
                    message, messageURL, entryTitle, htmlFormat, messageBody, messageSubject,
                    messageSubjectPrefix, inReplyTo, fromName, fromAddress, replyToAddress, emailAddress,
                    fullName, subjectLocalizedValuesMap, bodyLocalizedValuesMap, serviceContext);

            sourceMailingListSubscriptionSender.setBulk(false);

            sourceMailingListSubscriptionSender.addMailingListSubscriber(message.getGroupId(), categoryId);

            sourceMailingListSubscriptionSender.flushNotificationsAsync();
        }
    }
}