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

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

Introduction

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

Prototype

@JSON(include = false)
    public HttpServletRequest getRequest() 

Source Link

Usage

From source file:com.liferay.asset.publisher.web.servlet.taglib.ui.OrderingAndGroupingFormNavigatorEntry.java

License:Open Source License

@Override
public boolean isVisible(User user, Object object) {
    if (!isDynamicAssetSelection()) {
        return false;
    }/*from   ww  w  .  j  av  a 2s.c  om*/

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    ThemeDisplay themeDisplay = serviceContext.getThemeDisplay();

    PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

    Portlet portlet = _portletLocalService.getPortletById(themeDisplay.getCompanyId(),
            portletDisplay.getPortletResource());

    AssetPublisherCustomizer assetPublisherCustomizer = assetPublisherCustomizerRegistry
            .getAssetPublisherCustomizer(portlet.getRootPortletId());

    if (assetPublisherCustomizer == null) {
        return true;
    }

    return assetPublisherCustomizer.isOrderingAndGroupingEnabled(serviceContext.getRequest());
}

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 ww w.  j  a v a2s. c  o  m*/

    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 pingPingback(BlogsEntry entry, ServiceContext serviceContext) throws PortalException {

    if (!PropsValues.BLOGS_PINGBACK_ENABLED || !entry.isAllowPingbacks() || !entry.isApproved()) {

        return;/*from www  .jav a2  s. co m*/
    }

    HttpServletRequest request = serviceContext.getRequest();

    if (request == null) {
        return;
    }

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

    String layoutFullURL = PortalUtil.getLayoutFullURL(themeDisplay);

    if (Validator.isNull(layoutFullURL)) {
        return;
    }

    String sourceUri = layoutFullURL + Portal.FRIENDLY_URL_SEPARATOR + "blogs/" + entry.getUrlTitle();

    Source source = new Source(entry.getContent());

    List<StartTag> tags = source.getAllStartTags("a");

    for (StartTag tag : tags) {
        String targetUri = tag.getAttributeValue("href");

        if (Validator.isNotNull(targetUri)) {
            try {
                LinkbackProducerUtil.sendPingback(sourceUri, targetUri);
            } catch (Exception e) {
                _log.error("Error while sending pingback " + targetUri, e);
            }
        }
    }
}

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

License:Open Source License

protected void pingTrackbacks(BlogsEntry entry, String[] trackbacks, boolean pingOldTrackbacks,
        ServiceContext serviceContext) throws PortalException {

    if (!PropsValues.BLOGS_TRACKBACK_ENABLED || !entry.isAllowTrackbacks() || !entry.isApproved()) {

        return;//from   w  w  w. j  av  a  2  s  .c om
    }

    HttpServletRequest request = serviceContext.getRequest();

    if (request == null) {
        return;
    }

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

    String layoutFullURL = PortalUtil.getLayoutFullURL(themeDisplay);

    if (Validator.isNull(layoutFullURL)) {
        return;
    }

    Map<String, String> parts = new HashMap<>();

    String excerpt = StringUtil.shorten(HtmlUtil.extractText(entry.getContent()),
            PropsValues.BLOGS_LINKBACK_EXCERPT_LENGTH);
    String url = layoutFullURL + Portal.FRIENDLY_URL_SEPARATOR + "blogs/" + entry.getUrlTitle();

    parts.put("title", entry.getTitle());
    parts.put("excerpt", excerpt);
    parts.put("url", url);
    parts.put("blog_name", entry.getUserName());

    Set<String> trackbacksSet = null;

    if (ArrayUtil.isNotEmpty(trackbacks)) {
        trackbacksSet = SetUtil.fromArray(trackbacks);
    } else {
        trackbacksSet = new HashSet<>();
    }

    if (pingOldTrackbacks) {
        trackbacksSet.addAll(SetUtil.fromArray(StringUtil.split(entry.getTrackbacks())));

        entry.setTrackbacks(StringPool.BLANK);

        blogsEntryPersistence.update(entry);
    }

    Set<String> oldTrackbacks = SetUtil.fromArray(StringUtil.split(entry.getTrackbacks()));

    Set<String> validTrackbacks = new HashSet<>();

    for (String trackback : trackbacksSet) {
        if (oldTrackbacks.contains(trackback)) {
            continue;
        }

        try {
            if (LinkbackProducerUtil.sendTrackback(trackback, parts)) {
                validTrackbacks.add(trackback);
            }
        } catch (Exception e) {
            _log.error("Error while sending trackback at " + trackback, e);
        }
    }

    if (!validTrackbacks.isEmpty()) {
        String newTrackbacks = StringUtil.merge(validTrackbacks);

        if (Validator.isNotNull(entry.getTrackbacks())) {
            newTrackbacks += StringPool.COMMA + entry.getTrackbacks();
        }

        entry.setTrackbacks(newTrackbacks);

        blogsEntryPersistence.update(entry);
    }
}

From source file:com.liferay.calendar.web.internal.social.CalendarActivityInterpreter.java

License:Open Source License

@Override
protected String getPath(SocialActivity activity, ServiceContext serviceContext) throws Exception {

    long plid = _portal.getPlidFromPortletId(serviceContext.getScopeGroupId(), CalendarPortletKeys.CALENDAR);

    PortletURL portletURL = PortletURLFactoryUtil.create(serviceContext.getRequest(),
            CalendarPortletKeys.CALENDAR, plid, PortletRequest.RENDER_PHASE);

    portletURL.setParameter("mvcPath", "/view_calendar_booking.jsp");
    portletURL.setParameter("backURL", serviceContext.getCurrentURL());
    portletURL.setParameter("calendarBookingId", String.valueOf(activity.getClassPK()));

    return portletURL.toString();
}

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

License:Open Source License

protected List<Serializable> getFieldValues(DDMStructure ddmStructure, String fieldName, String fieldNamespace,
        ServiceContext serviceContext) throws PortalException {

    DDMFormField ddmFormField = ddmStructure.getDDMFormField(fieldName);

    String fieldDataType = ddmFormField.getDataType();
    String fieldType = ddmFormField.getType();

    LocalizedValue predefinedValue = ddmFormField.getPredefinedValue();

    List<String> fieldNames = getFieldNames(fieldNamespace, fieldName, serviceContext);

    List<Serializable> fieldValues = new ArrayList<>(fieldNames.size());

    for (String fieldNameValue : fieldNames) {
        Serializable fieldValue = serviceContext.getAttribute(fieldNameValue);

        if (Validator.isNull(fieldValue)) {
            fieldValue = predefinedValue.getString(serviceContext.getLocale());
        }/*  w  w  w  .  j  a  v  a 2  s  .c  om*/

        if (fieldType.equals(DDMImpl.TYPE_CHECKBOX) && Validator.isNull(fieldValue)) {

            fieldValue = "false";
        } else if (fieldDataType.equals(FieldConstants.DATE)) {
            Date fieldValueDate = null;

            if (Validator.isNull(fieldValue)) {
                int fieldValueMonth = GetterUtil
                        .getInteger(serviceContext.getAttribute(fieldNameValue + "Month"));
                int fieldValueDay = GetterUtil.getInteger(serviceContext.getAttribute(fieldNameValue + "Day"));
                int fieldValueYear = GetterUtil
                        .getInteger(serviceContext.getAttribute(fieldNameValue + "Year"));

                fieldValueDate = _portal.getDate(fieldValueMonth, fieldValueDay, fieldValueYear,
                        TimeZoneUtil.getTimeZone("UTC"), null);
            } else {
                try {
                    fieldValueDate = DateUtil.parseDate(String.valueOf(fieldValue), serviceContext.getLocale());
                } catch (ParseException pe) {
                    _log.error("Unable to parse date " + fieldValue);
                }
            }

            if (fieldValueDate != null) {
                fieldValue = String.valueOf(fieldValueDate.getTime());
            }
        } else if (fieldDataType.equals(FieldConstants.IMAGE) && Validator.isNull(fieldValue)) {

            HttpServletRequest request = serviceContext.getRequest();

            if (request instanceof UploadRequest) {
                String imageFieldValue = getImageFieldValue((UploadRequest) request, fieldNameValue);

                if (Validator.isNotNull(imageFieldValue)) {
                    fieldValue = imageFieldValue;
                }
            }
        }

        if (Validator.isNull(fieldValue)) {
            return null;
        }

        if (DDMImpl.TYPE_SELECT.equals(fieldType)) {
            String predefinedValueString = predefinedValue.getString(serviceContext.getLocale());

            if (!fieldValue.equals(predefinedValueString) && (fieldValue instanceof String)) {

                fieldValue = new String[] { String.valueOf(fieldValue) };

                fieldValue = JSONFactoryUtil.serialize(fieldValue);
            }
        }

        Serializable fieldValueSerializable = FieldConstants.getSerializable(fieldDataType,
                GetterUtil.getString(fieldValue));

        fieldValues.add(fieldValueSerializable);
    }

    return fieldValues;
}

From source file:com.liferay.exportimport.internal.notifications.ExportImportUserNotificationHandler.java

License:Open Source License

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

    Locale locale = _portal.getLocale(serviceContext.getRequest());

    ResourceBundle resourceBundle = _resourceBundleLoader.loadResourceBundle(locale);

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

    ExportImportConfiguration exportImportConfiguration = null;

    try {// w  w w .  j  av  a  2 s .  co  m
        exportImportConfiguration = _exportImportConfigurationLocalService
                .getExportImportConfiguration(jsonObject.getLong("exportImportConfigurationId"));
    } catch (PortalException pe) {
        if (_log.isDebugEnabled()) {
            _log.debug(pe, pe);
        }

        return LanguageUtil.get(resourceBundle, "the-process-referenced-by-this-notification-does-not-exist");
    }

    String message = "x-"
            + ExportImportConfigurationConstants.getTypeLabel(exportImportConfiguration.getType());

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

    if (status == BackgroundTaskConstants.STATUS_SUCCESSFUL) {
        message += "-process-finished-successfully";
    } else if (status == BackgroundTaskConstants.STATUS_FAILED) {
        message += "-process-failed";
    } else {
        return "Unable to process notification: " + HtmlUtil.escape(jsonObject.toString());
    }

    long backgroundTaskId = jsonObject.getLong("backgroundTaskId");

    BackgroundTaskDisplay backgroundTaskDisplay = _backgroundTaskDisplayFactory
            .getBackgroundTaskDisplay(backgroundTaskId);

    String processName = backgroundTaskDisplay.getDisplayName(serviceContext.getRequest());

    return LanguageUtil.format(resourceBundle, message, processName);
}

From source file:com.liferay.exportimport.internal.notifications.ExportImportUserNotificationHandler.java

License:Open Source License

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

    PortletURL renderURL = PortletURLFactoryUtil.create(serviceContext.getRequest(),
            ExportImportPortletKeys.EXPORT_IMPORT, PortletRequest.RENDER_PHASE);

    renderURL.setParameter("mvcPath", "/view_export_import.jsp");

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

    long backgroundTaskId = jsonObject.getLong("backgroundTaskId");

    BackgroundTask backgroundTask = _backgroundTaskLocalService.fetchBackgroundTask(backgroundTaskId);

    if (backgroundTask == null) {
        return StringPool.BLANK;
    }//  w w  w. j  a  v a2  s . c o  m

    renderURL.setParameter("backgroundTaskId", String.valueOf(backgroundTaskId));

    renderURL.setParameter("backURL", serviceContext.getCurrentURL());

    return renderURL.toString();
}

From source file:com.liferay.mentions.internal.service.MentionsWikiPageServiceWrapper.java

License:Open Source License

protected String getDiffsURL(WikiPage page, WikiPage previousVersionPage, ServiceContext serviceContext)
        throws PortalException {

    if (previousVersionPage == null) {
        return StringPool.BLANK;
    }// ww w . j a v  a2s .com

    HttpServletRequest request = serviceContext.getRequest();

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

    PortletURL portletURL = null;

    long plid = serviceContext.getPlid();

    if (plid == LayoutConstants.DEFAULT_PLID) {
        portletURL = PortalUtil.getControlPanelPortletURL(request, WikiPortletKeys.WIKI_ADMIN,
                PortletRequest.RENDER_PHASE);
    } else {
        portletURL = PortletURLFactoryUtil.create(request, WikiConstants.SERVICE_NAME, plid,
                PortletRequest.RENDER_PHASE);
    }

    portletURL.setParameter("mvcRenderCommandName", "/wiki/compare_versions");
    portletURL.setParameter("nodeId", String.valueOf(page.getNodeId()));
    portletURL.setParameter("title", page.getTitle());
    portletURL.setParameter("sourceVersion", String.valueOf(previousVersionPage.getVersion()));
    portletURL.setParameter("targetVersion", String.valueOf(page.getVersion()));
    portletURL.setParameter("type", "html");

    return portletURL.toString();
}

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.j  a va  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();
        }
    }
}