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

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

Introduction

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

Prototype

public Locale getLocale() 

Source Link

Usage

From source file:com.bemis.portal.report.service.impl.ReportRequestLocalServiceImpl.java

License:Open Source License

@Override
public ReportRequest addReportRequest(final long reportDefinitionId, String reportFormat,
        final Set<String> reportFields, Set<String> sortFields,
        final Map<ReportParameter, Serializable> reportParametersValues, ServiceContext serviceContext)
        throws PortalException {

    final User user = userLocalService.getUser(serviceContext.getGuestOrUserId());

    Date now = new Date();

    final long reportRequestId = counterLocalService.increment();

    ReportRequest reportRequest = reportRequestPersistence.create(reportRequestId);

    reportRequest.setGroupId(user.getGroupId());
    reportRequest.setCompanyId(user.getCompanyId());
    reportRequest.setUserId(user.getUserId());
    reportRequest.setUserName(user.getFullName());
    reportRequest.setCreateDate(serviceContext.getCreateDate(now));
    reportRequest.setModifiedDate(serviceContext.getModifiedDate(now));

    final ReportDefinition reportDefinition = reportDefinitionLocalService
            .getReportDefinition(reportDefinitionId);

    reportRequest.setReportDefinitionCategory(reportDefinition.getCategory());

    reportRequest.setReportFormat(reportFormat);
    reportRequest.setReportDefinitionId(reportDefinitionId);
    reportRequest.setReportDefinitionName(reportDefinition.getTitle(serviceContext.getLocale()));
    reportRequest.setSelectedFields(StringUtils.join(reportFields, StringPool.COMMA));
    reportRequest.setSortFields(StringUtils.join(sortFields, StringPool.COMMA));

    String reportParametersString = reportParametersValuesSerializer.serialize(reportParametersValues);

    reportRequest.setParameters(reportParametersString);

    reportRequest.setExpandoBridgeAttributes(serviceContext);

    reportRequestPersistence.update(reportRequest);

    /*/*w w w . j  a v  a2 s  .  com*/
          // Resources
            
          resourceLocalService.addModelResources(reportRequest, serviceContext);
    */

    return reportRequest;
}

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  . j  a va2 s  . c  om*/
    }

    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.blogs.web.social.BlogsActivityInterpreter.java

License:Open Source License

@Override
protected Object[] getTitleArguments(String groupName, SocialActivity activity, String link, String title,
        ServiceContext serviceContext) throws Exception {

    String creatorUserName = getUserName(activity.getUserId(), serviceContext);
    String receiverUserName = getUserName(activity.getReceiverUserId(), serviceContext);

    BlogsEntry entry = _blogsEntryLocalService.getEntry(activity.getClassPK());

    String displayDate = StringPool.BLANK;

    if ((activity.getType() == BlogsActivityKeys.ADD_ENTRY)
            && (entry.getStatus() == WorkflowConstants.STATUS_SCHEDULED)) {

        link = null;/*from  w  w  w .jav  a2 s  .  com*/

        Format dateFormatDate = FastDateFormatFactoryUtil.getSimpleDateFormat("MMMM d",
                serviceContext.getLocale(), serviceContext.getTimeZone());

        displayDate = dateFormatDate.format(entry.getDisplayDate());
    }

    return new Object[] { groupName, creatorUserName, receiverUserName, wrapLink(link, title), displayDate };
}

From source file:com.liferay.comment.web.internal.notifications.CommentUserNotificationHandler.java

License:Open Source License

@Override
protected String getTitle(JSONObject jsonObject, AssetRenderer assetRenderer, ServiceContext serviceContext) {

    MBDiscussion mbDiscussion = fetchDiscussion(jsonObject);

    if (mbDiscussion == null) {
        return null;
    }//from  w w  w  .  j ava 2  s.  c o  m

    String message = StringPool.BLANK;

    int notificationType = jsonObject.getInt("notificationType");

    if (notificationType == UserNotificationDefinition.NOTIFICATION_TYPE_ADD_ENTRY) {

        if (assetRenderer != null) {
            message = "x-added-a-new-comment-to-x";
        } else {
            message = "x-added-a-new-comment";
        }
    } else if (notificationType == UserNotificationDefinition.NOTIFICATION_TYPE_UPDATE_ENTRY) {

        if (assetRenderer != null) {
            message = "x-updated-a-comment-to-x";
        } else {
            message = "x-updated-a-comment";
        }
    }

    if (assetRenderer != null) {
        message = LanguageUtil.format(serviceContext.getLocale(), message,
                new String[] {
                        HtmlUtil.escape(_portal.getUserName(jsonObject.getLong("userId"), StringPool.BLANK)),
                        HtmlUtil.escape(assetRenderer.getTitle(serviceContext.getLocale())) },
                false);
    } else {
        message = LanguageUtil.format(serviceContext.getLocale(), message,
                new String[] {
                        HtmlUtil.escape(_portal.getUserName(jsonObject.getLong("userId"), StringPool.BLANK)) },
                false);
    }

    return message;
}

From source file:com.liferay.contacts.web.internal.notifications.ContactsCenterUserNotificationHandler.java

License:Open Source License

@Override
protected String getBody(UserNotificationEvent userNotificationEvent, ServiceContext serviceContext)
        throws Exception {

    JSONObject jsonObject = JSONFactoryUtil.createJSONObject(userNotificationEvent.getPayload());

    long socialRequestId = jsonObject.getLong("classPK");

    SocialRequest socialRequest = _socialRequestLocalService.fetchSocialRequest(socialRequestId);

    if (socialRequest == null) {
        _userNotificationEventLocalService
                .deleteUserNotificationEvent(userNotificationEvent.getUserNotificationEventId());

        return null;
    }//from  w ww  . j  a v  a 2 s.  c  o  m

    String creatorUserName = getUserNameLink(socialRequest.getUserId(), serviceContext);

    ResourceBundle resourceBundle = _resourceBundleLoader.loadResourceBundle(serviceContext.getLocale());

    String title = StringPool.BLANK;

    if (socialRequest.getType() == SocialRelationConstants.TYPE_BI_CONNECTION) {

        title = ResourceBundleUtil.getString(resourceBundle, serviceContext.getLocale(),
                "request-social-networking-summary-add-connection", new Object[] { creatorUserName });
    } else {
        title = ResourceBundleUtil.getString(resourceBundle, serviceContext.getLocale(),
                "x-sends-you-a-social-relationship-request", new Object[] { creatorUserName });
    }

    if ((socialRequest.getStatus() != SocialRequestConstants.STATUS_PENDING)
            || (socialRequest.getModifiedDate() > userNotificationEvent.getTimestamp())) {

        return StringUtil.replace(_BODY, new String[] { "[$BODY$]", "[$TITLE$]" },
                new String[] { StringPool.BLANK, title });
    }

    LiferayPortletResponse liferayPortletResponse = serviceContext.getLiferayPortletResponse();

    PortletURL confirmURL = liferayPortletResponse.createActionURL(ContactsPortletKeys.CONTACTS_CENTER);

    confirmURL.setParameter(ActionRequest.ACTION_NAME, "updateSocialRequest");
    confirmURL.setParameter("redirect", serviceContext.getLayoutFullURL());
    confirmURL.setParameter("socialRequestId", String.valueOf(socialRequestId));
    confirmURL.setParameter("status", String.valueOf(SocialRequestConstants.STATUS_CONFIRM));
    confirmURL.setParameter("userNotificationEventId",
            String.valueOf(userNotificationEvent.getUserNotificationEventId()));
    confirmURL.setWindowState(WindowState.NORMAL);

    PortletURL ignoreURL = liferayPortletResponse.createActionURL(ContactsPortletKeys.CONTACTS_CENTER);

    ignoreURL.setParameter(ActionRequest.ACTION_NAME, "updateSocialRequest");
    ignoreURL.setParameter("redirect", serviceContext.getLayoutFullURL());
    ignoreURL.setParameter("socialRequestId", String.valueOf(socialRequestId));
    ignoreURL.setParameter("status", String.valueOf(SocialRequestConstants.STATUS_IGNORE));
    ignoreURL.setParameter("userNotificationEventId",
            String.valueOf(userNotificationEvent.getUserNotificationEventId()));
    ignoreURL.setWindowState(WindowState.NORMAL);

    return StringUtil.replace(getBodyTemplate(),
            new String[] { "[$CONFIRM$]", "[$CONFIRM_URL$]", "[$IGNORE$]", "[$IGNORE_URL$]", "[$TITLE$]" },
            new String[] { serviceContext.translate("confirm"), confirmURL.toString(),
                    serviceContext.translate("ignore"), ignoreURL.toString(), title });
}

From source file:com.liferay.document.library.repository.cmis.internal.CMISRepository.java

License:Open Source License

@Override
public void revertFileEntry(long userId, long fileEntryId, String version, ServiceContext serviceContext)
        throws PortalException {

    try {/* w  w w.  ja v a  2s.c  o  m*/
        Session session = getSession();

        Document document = getDocument(session, fileEntryId);

        Document oldVersion = null;

        List<Document> documentVersions = document.getAllVersions();

        for (Document currentVersion : documentVersions) {
            String currentVersionLabel = currentVersion.getVersionLabel();

            if (Validator.isNull(currentVersionLabel)) {
                currentVersionLabel = DLFileEntryConstants.VERSION_DEFAULT;
            }

            if (currentVersionLabel.equals(version)) {
                oldVersion = currentVersion;

                break;
            }
        }

        String mimeType = oldVersion.getContentStreamMimeType();
        String changeLog = LanguageUtil.format(serviceContext.getLocale(), "reverted-to-x", version, false);
        String title = oldVersion.getName();
        ContentStream contentStream = oldVersion.getContentStream();

        updateFileEntry(userId, fileEntryId, contentStream.getFileName(), mimeType, title, StringPool.BLANK,
                changeLog, true, contentStream.getStream(), contentStream.getLength(), serviceContext);
    } catch (PortalException | SystemException e) {
        throw e;
    } catch (Exception e) {
        processException(e);

        throw new RepositoryException(e);
    }
}

From source file:com.liferay.document.library.repository.external.ExtRepositoryAdapter.java

License:Open Source License

@Override
public void revertFileEntry(long userId, long fileEntryId, String version, ServiceContext serviceContext)
        throws PortalException {

    String extRepositoryFileEntryKey = getExtRepositoryObjectKey(fileEntryId);

    ExtRepositoryFileEntry extRepositoryFileEntry = _extRepository
            .getExtRepositoryObject(ExtRepositoryObjectType.FILE, extRepositoryFileEntryKey);

    ExtRepositoryFileVersion extRepositoryFileVersion = null;

    List<ExtRepositoryFileVersion> extRepositoryFileVersions = _extRepository
            .getExtRepositoryFileVersions(extRepositoryFileEntry);

    for (ExtRepositoryFileVersion curExtRepositoryFileVersion : extRepositoryFileVersions) {

        String curVersion = curExtRepositoryFileVersion.getVersion();

        if (curVersion.equals(version)) {
            extRepositoryFileVersion = curExtRepositoryFileVersion;

            break;
        }/* ww w.ja  v  a  2  s.com*/
    }

    if (extRepositoryFileVersion != null) {
        InputStream inputStream = _extRepository.getContentStream(extRepositoryFileVersion);

        boolean needsCheckIn = false;

        if (!isCheckedOut(extRepositoryFileEntry)) {
            try {
                _extRepository.checkOutExtRepositoryFileEntry(extRepositoryFileEntryKey);

                needsCheckIn = true;
            } catch (UnsupportedOperationException uoe) {
            }
        }

        _extRepository.updateExtRepositoryFileEntry(extRepositoryFileEntryKey,
                extRepositoryFileVersion.getMimeType(), inputStream);

        String changeLog = LanguageUtil.format(serviceContext.getLocale(), "reverted-to-x", version, false);

        if (needsCheckIn) {
            try {
                _extRepository.checkInExtRepositoryFileEntry(extRepositoryFileEntryKey, true, changeLog);
            } catch (UnsupportedOperationException uoe) {
            }
        }
    } else {
        throw new NoSuchFileVersionException("No file version with {extRepositoryModelKey="
                + extRepositoryFileEntry.getExtRepositoryModelKey() + ", version: " + version + "}");
    }
}

From source file:com.liferay.dynamic.data.lists.service.impl.DDLRecordLocalServiceImpl.java

License:Open Source License

/**
 * Adds a record referencing the record set.
 *
 * @param  userId the primary key of the record's creator/owner
 * @param  groupId the primary key of the record's group
 * @param  recordSetId the primary key of the record set
 * @param  displayIndex the index position in which the record is displayed
 *         in the spreadsheet view//  w w  w .  j  a v a  2s .c  om
 * @param  ddmFormValues the record values. See <code>DDMFormValues</code>
 *         in the <code>dynamic.data.mapping.api</code> module.
 * @param  serviceContext the service context to be applied. This can set
 *         the UUID, guest permissions, and group permissions for the
 *         record.
 * @return the record
 * @throws PortalException if a portal exception occurred
 */
@Indexable(type = IndexableType.REINDEX)
@Override
public DDLRecord addRecord(long userId, long groupId, long recordSetId, int displayIndex,
        DDMFormValues ddmFormValues, ServiceContext serviceContext) throws PortalException {

    // Record

    User user = userLocalService.getUser(userId);

    DDLRecordSet recordSet = ddlRecordSetPersistence.findByPrimaryKey(recordSetId);

    validate(groupId, recordSet);

    long recordId = counterLocalService.increment();

    DDLRecord record = ddlRecordPersistence.create(recordId);

    record.setUuid(serviceContext.getUuid());
    record.setGroupId(groupId);
    record.setCompanyId(user.getCompanyId());
    record.setUserId(user.getUserId());
    record.setUserName(user.getFullName());
    record.setVersionUserId(user.getUserId());
    record.setVersionUserName(user.getFullName());

    long ddmStorageId = storageEngine.create(recordSet.getCompanyId(), recordSet.getDDMStructureId(),
            ddmFormValues, serviceContext);

    record.setDDMStorageId(ddmStorageId);

    record.setRecordSetId(recordSetId);
    record.setVersion(DDLRecordConstants.VERSION_DEFAULT);
    record.setDisplayIndex(displayIndex);

    ddlRecordPersistence.update(record);

    // Record version

    DDLRecordVersion recordVersion = addRecordVersion(user, record, ddmStorageId,
            DDLRecordConstants.VERSION_DEFAULT, displayIndex, WorkflowConstants.STATUS_DRAFT);

    // Asset

    Locale locale = serviceContext.getLocale();

    updateAsset(userId, record, recordVersion, serviceContext.getAssetCategoryIds(),
            serviceContext.getAssetTagNames(), locale, serviceContext.getAssetPriority());

    // Workflow

    WorkflowHandlerRegistryUtil.startWorkflowInstance(user.getCompanyId(), groupId, userId,
            getWorkflowAssetClassName(recordSet), recordVersion.getRecordVersionId(), recordVersion,
            serviceContext);

    return record;
}

From source file:com.liferay.dynamic.data.lists.service.impl.DDLRecordLocalServiceImpl.java

License:Open Source License

/**
 * Adds a record that's based on the fields map and that references the
 * record set./*from  www  . j a  va 2s.  co m*/
 *
 * @param      userId the primary key of the record's creator/owner
 * @param      groupId the primary key of the record's group
 * @param      recordSetId the primary key of the record set
 * @param      displayIndex the index position in which the record is
 *             displayed in the spreadsheet view
 * @param      fieldsMap the record values. The fieldsMap is a map of field
 *             names and their serializable values.
 * @param      serviceContext the service context to be applied. This can
 *             set the UUID, guest permissions, and group permissions for
 *             the record.
 * @return     the record
 * @throws     PortalException if a portal exception occurred
 * @deprecated As of 1.1.0, replaced by {@link #addRecord(long, long, int,
 *             DDMFormValues, ServiceContext)}
 */
@Deprecated
@Override
public DDLRecord addRecord(long userId, long groupId, long recordSetId, int displayIndex,
        Map<String, Serializable> fieldsMap, ServiceContext serviceContext) throws PortalException {

    DDLRecordSet recordSet = ddlRecordSetPersistence.findByPrimaryKey(recordSetId);

    DDMStructure ddmStructure = recordSet.getDDMStructure();

    Fields fields = toFields(ddmStructure.getStructureId(), fieldsMap, serviceContext.getLocale(),
            LocaleUtil.getSiteDefault(), true);

    return ddlRecordLocalService.addRecord(userId, groupId, recordSetId, displayIndex, fields, serviceContext);
}

From source file:com.liferay.dynamic.data.lists.service.impl.DDLRecordLocalServiceImpl.java

License:Open Source License

/**
 * Updates a record, replacing its display index and values.
 *
 * @param      userId the primary key of the user updating the record
 * @param      recordId the primary key of the record
 * @param      displayIndex the index position in which the record is
 *             displayed in the spreadsheet view
 * @param      fieldsMap the record values. The fieldsMap is a map of field
 *             names and its Serializable values.
 * @param      mergeFields whether to merge the new fields with the existing
 *             ones; otherwise replace the existing fields
 * @param      serviceContext the service context to be applied. This can
 *             set the record modified date.
 * @return     the record//  w w w.  ja v a2  s .  c  o  m
 * @throws     PortalException if a portal exception occurred
 * @deprecated As of 1.1.0, replaced by {@link #updateRecord(long, long,
 *             boolean, int, DDMFormValues, ServiceContext)}
 */
@Deprecated
@Override
public DDLRecord updateRecord(long userId, long recordId, int displayIndex, Map<String, Serializable> fieldsMap,
        boolean mergeFields, ServiceContext serviceContext) throws PortalException {

    DDLRecord record = ddlRecordPersistence.findByPrimaryKey(recordId);

    DDMFormValues oldDDMFormValues = record.getDDMFormValues();

    DDLRecordSet recordSet = record.getRecordSet();

    DDMStructure ddmStructure = recordSet.getDDMStructure();

    Fields fields = toFields(ddmStructure.getStructureId(), fieldsMap, serviceContext.getLocale(),
            oldDDMFormValues.getDefaultLocale(), false);

    return ddlRecordLocalService.updateRecord(userId, recordId, false, displayIndex, fields, mergeFields,
            serviceContext);
}