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

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

Introduction

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

Prototype

public Serializable getAttribute(String name) 

Source Link

Document

Returns the serializable object associated with the name of the standard parameter of this service context.

Usage

From source file:com.bemis.portal.fileuploader.service.impl.FileUploaderLocalServiceImpl.java

License:Open Source License

/**
 * Uploads the file into the destination folder
 * If the file does not exist, adds the file. If exists, updates the existing file
 * Adds tags and categories to documents
 *
 * @param file/*w w w. j a  va2 s . c o  m*/
 * @param fileDescription
 * @param fileName
 * @param changeLog
 * @param serviceContext
 * @return FileEntry
 * @throws PortalException
 */
public FileEntry uploadFile(File file, String fileDescription, String fileName, String changeLog,
        ServiceContext serviceContext) throws PortalException {

    if (_log.isDebugEnabled()) {
        _log.debug("Invoking uploadFile....");
    }

    long companyId = serviceContext.getCompanyId();
    long groupId = serviceContext.getScopeGroupId();
    long userId = serviceContext.getUserId();

    // see https://issues.liferay.com/browse/LPS-66607

    User user = userLocalService.getUser(userId);

    // Check permissions

    _fileUploadHelper.checkPermission(companyId, groupId, userId);

    String title = FilenameUtils.removeExtension(fileName);

    long folderId = GetterUtil.getLong(serviceContext.getAttribute(DESTINATION_FOLDER_ID));

    fileName = file.getName();

    String mimeType = MimeTypesUtil.getContentType(fileName);

    boolean majorVersion = true;

    DLFileEntry dlFileEntry = _dlFileEntryLocalService.fetchFileEntry(groupId, folderId, title);

    FileEntry fileEntry = null;

    if (Validator.isNull(dlFileEntry)) {
        fileEntry = addFileEntry(userId, groupId, folderId, fileName, mimeType, title, fileDescription,
                changeLog, file, serviceContext);
    } else {
        fileEntry = updateFileEntry(userId, dlFileEntry, fileName, mimeType, title, fileDescription, changeLog,
                majorVersion, file, serviceContext);
    }

    FileVersion fileVersion = fileEntry.getFileVersion();

    long[] assetCategoryIds = _fileUploadHelper.getAssetCategoryIds(groupId, title, serviceContext);

    String[] assetTagNames = serviceContext.getAssetTagNames();

    if (_log.isDebugEnabled()) {
        _log.debug(">>> Updating FileEntry with tags and categories");
    }

    _dlAppLocalService.updateAsset(userId, fileEntry, fileVersion, assetCategoryIds, assetTagNames, null);

    // Post processing uploaded file

    _fileUploadHelper.postProcessUpload(file, fileEntry.getFileEntryId(), serviceContext);

    return fileEntry;
}

From source file:com.liferay.asset.publisher.web.portlet.AssetPublisherPortlet.java

License:Open Source License

public void getFieldValue(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
        throws PortletException {

    ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

    try {/*from  w ww.  j a va  2 s  . c om*/
        ServiceContext serviceContext = ServiceContextFactory.getInstance(resourceRequest);

        long structureId = ParamUtil.getLong(resourceRequest, "structureId");

        Fields fields = (Fields) serviceContext.getAttribute(Fields.class.getName() + structureId);

        if (fields == null) {
            String fieldsNamespace = ParamUtil.getString(resourceRequest, "fieldsNamespace");

            fields = DDMUtil.getFields(structureId, fieldsNamespace, serviceContext);
        }

        String fieldName = ParamUtil.getString(resourceRequest, "name");

        Field field = fields.get(fieldName);

        Serializable fieldValue = field.getValue(themeDisplay.getLocale(), 0);

        JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

        if (fieldValue != null) {
            jsonObject.put("success", true);
        } else {
            jsonObject.put("success", false);

            writeJSON(resourceRequest, resourceResponse, jsonObject);

            return;
        }

        DDMStructure ddmStructure = field.getDDMStructure();

        String type = ddmStructure.getFieldType(fieldName);

        Serializable displayValue = DDMUtil.getDisplayFieldValue(themeDisplay, fieldValue, type);

        jsonObject.put("displayValue", String.valueOf(displayValue));

        if (fieldValue instanceof Boolean) {
            jsonObject.put("value", (Boolean) fieldValue);
        } else if (fieldValue instanceof Date) {
            DateFormat dateFormat = DateFormatFactoryUtil.getSimpleDateFormat("yyyyMM ddHHmmss");

            jsonObject.put("value", dateFormat.format(fieldValue));
        } else if (fieldValue instanceof Double) {
            jsonObject.put("value", (Double) fieldValue);
        } else if (fieldValue instanceof Float) {
            jsonObject.put("value", (Float) fieldValue);
        } else if (fieldValue instanceof Integer) {
            jsonObject.put("value", (Integer) fieldValue);
        } else if (fieldValue instanceof Number) {
            jsonObject.put("value", String.valueOf(fieldValue));
        } else {
            jsonObject.put("value", (String) fieldValue);
        }

        writeJSON(resourceRequest, resourceResponse, jsonObject);
    } catch (Exception e) {
        throw new PortletException(e);
    }
}

From source file:com.liferay.blogs.internal.util.PingbackMethodImplTest.java

License:Open Source License

@Test
public void testBuildServiceContext() throws Exception {
    PingbackMethodImpl pingbackMethodImpl = getPingbackMethodImpl();

    ServiceContext serviceContext = pingbackMethodImpl.buildServiceContext(_COMPANY_ID, _GROUP_ID, _URL_TITLE);

    Assert.assertEquals(_PINGBACK_USER_NAME, serviceContext.getAttribute("pingbackUserName"));
    Assert.assertEquals(_LAYOUT_FULL_URL + "/-/" + _FRIENDLY_URL_MAPPING + "/" + _URL_TITLE,
            serviceContext.getAttribute("redirect"));
    Assert.assertEquals(_LAYOUT_FULL_URL, serviceContext.getLayoutFullURL());
}

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

License:Open Source License

@Indexable(type = IndexableType.REINDEX)
@Override// w w  w.ja  va  2  s .  c o  m
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 String getEntryURL(BlogsEntry entry, ServiceContext serviceContext) throws PortalException {

    String entryURL = GetterUtil.getString(serviceContext.getAttribute("entryURL"));

    if (Validator.isNotNull(entryURL)) {
        return entryURL;
    }//from  w  ww  .j  a  va 2s.c  om

    HttpServletRequest request = serviceContext.getRequest();

    if (request == null) {
        return StringPool.BLANK;
    }

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

    if (Validator.isNotNull(portletId)) {
        String layoutURL = LayoutURLUtil.getLayoutURL(entry.getGroupId(), portletId, serviceContext);

        if (Validator.isNotNull(layoutURL)) {
            return layoutURL + Portal.FRIENDLY_URL_SEPARATOR + "blogs" + StringPool.SLASH + entry.getEntryId();
        }
    }

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

    if (Validator.isNull(portletId)) {
        return StringPool.BLANK;
    }

    PortletURL portletURL = PortalUtil.getControlPanelPortletURL(request, portletId,
            PortletRequest.RENDER_PHASE);

    portletURL.setParameter("mvcRenderCommandName", "/blogs/view_entry");
    portletURL.setParameter("entryId", String.valueOf(entry.getEntryId()));

    return portletURL.toString();
}

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  ww  w .j a  v a  2 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.dynamic.data.lists.form.web.internal.converter.serializer.CalculateDDLFormRuleActionSerializer.java

License:Open Source License

@Override
public String serialize() {
    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    DDMForm ddmForm = (DDMForm) serviceContext.getAttribute("form");

    Map<String, DDMFormField> ddmFormFieldMap = ddmForm.getDDMFormFieldsMap(true);

    String expression = removeBrackets(_calculateDDLFormRuleAction.getExpression());

    Stream<String> ddmFormFieldStream = ddmFormFieldMap.keySet().stream();

    ddmFormFieldStream = ddmFormFieldStream.filter(ddmFormField -> expression.contains(ddmFormField));

    Set<String> ddmFormFields = ddmFormFieldStream.collect(Collectors.toSet());

    String newExpression = expression;

    int start = Integer.MAX_VALUE;
    int end = Integer.MIN_VALUE;

    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < expression.length(); i++) {
        char token = expression.charAt(i);

        sb.append(token);//from   w w w. j av a  2s  . c  o m

        String compareStr = sb.toString();

        boolean match = matchAnyField(compareStr, ddmFormFields);

        if (match) {
            if (start == Integer.MAX_VALUE) {
                start = i;
            }

            if (i == (expression.length() - 1)) {
                end = expression.length();
            }
        } else {
            end = i;
            sb = new StringBuffer();

            if (end > start) {
                newExpression = replace(expression, newExpression, start, end);
            }

            start = Integer.MAX_VALUE;
            end = Integer.MIN_VALUE;
        }
    }

    if (end > start) {
        newExpression = replace(expression, newExpression, start, end);
    }

    return String.format(_functionCallBinaryExpressionFormat, "calculate",
            _calculateDDLFormRuleAction.getTarget(), newExpression);
}

From source file:com.liferay.dynamic.data.mapping.internal.util.DDMImpl.java

License:Open Source License

@Override
public Fields getFields(long ddmStructureId, long ddmTemplateId, String fieldNamespace,
        ServiceContext serviceContext) throws PortalException {

    DDMStructure ddmStructure = getDDMStructure(ddmStructureId, ddmTemplateId);

    Set<String> fieldNames = ddmStructure.getFieldNames();

    boolean translating = true;

    String defaultLanguageId = (String) serviceContext.getAttribute("defaultLanguageId");
    String toLanguageId = (String) serviceContext.getAttribute("toLanguageId");

    if (Validator.isNull(toLanguageId) || Objects.equals(defaultLanguageId, toLanguageId)) {

        translating = false;//w w  w  .j a  v a2s.  c om
    }

    Fields fields = new Fields();

    for (String fieldName : fieldNames) {
        boolean localizable = GetterUtil.getBoolean(ddmStructure.getFieldProperty(fieldName, "localizable"),
                true);

        if (!localizable && translating && !fieldName.startsWith(StringPool.UNDERLINE)) {

            continue;
        }

        List<Serializable> fieldValues = getFieldValues(ddmStructure, fieldName, fieldNamespace,
                serviceContext);

        if ((fieldValues == null) || fieldValues.isEmpty()) {
            continue;
        }

        Field field = createField(ddmStructure, fieldName, fieldValues, serviceContext);

        fields.put(field);
    }

    return fields;
}

From source file:com.liferay.dynamic.data.mapping.internal.util.DDMImpl.java

License:Open Source License

@Override
public Fields getFields(long ddmStructureId, ServiceContext serviceContext) throws PortalException {

    String serializedDDMFormValues = GetterUtil.getString(serviceContext.getAttribute("ddmFormValues"));

    if (Validator.isNotNull(serializedDDMFormValues)) {
        return getFields(ddmStructureId, serializedDDMFormValues);
    }/*  w  ww. j  a  v a 2 s  .c o m*/

    return getFields(ddmStructureId, 0, serviceContext);
}

From source file:com.liferay.dynamic.data.mapping.internal.util.DDMImpl.java

License:Open Source License

@Override
public Fields getFields(long ddmStructureId, String fieldNamespace, ServiceContext serviceContext)
        throws PortalException {

    String serializedDDMFormValues = GetterUtil
            .getString(serviceContext.getAttribute(fieldNamespace + "ddmFormValues"));

    if (Validator.isNotNull(serializedDDMFormValues)) {
        return getFields(ddmStructureId, serializedDDMFormValues);
    }//from   ww w . j  a v a2 s.co  m

    return getFields(ddmStructureId, 0, fieldNamespace, serviceContext);
}