Example usage for com.liferay.portal.kernel.model User getTimeZone

List of usage examples for com.liferay.portal.kernel.model User getTimeZone

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.model User getTimeZone.

Prototype

public java.util.TimeZone getTimeZone();

Source Link

Usage

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

License:Open Source License

@Override
public BlogsEntry addEntry(long userId, String title, String subtitle, String urlTitle, String description,
        String content, int displayDateMonth, int displayDateDay, int displayDateYear, int displayDateHour,
        int displayDateMinute, boolean allowPingbacks, boolean allowTrackbacks, String[] trackbacks,
        String coverImageCaption, ImageSelector coverImageImageSelector, ImageSelector smallImageImageSelector,
        ServiceContext serviceContext) throws PortalException {

    User user = userPersistence.findByPrimaryKey(userId);

    Date displayDate = PortalUtil.getDate(displayDateMonth, displayDateDay, displayDateYear, displayDateHour,
            displayDateMinute, user.getTimeZone(), EntryDisplayDateException.class);

    return addEntry(userId, title, subtitle, urlTitle, description, content, displayDate, allowPingbacks,
            allowTrackbacks, trackbacks, coverImageCaption, coverImageImageSelector, smallImageImageSelector,
            serviceContext);/*from w w w  . j ava 2  s.c  o  m*/
}

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

License:Open Source License

@Override
public BlogsEntry updateEntry(long userId, long entryId, String title, String subtitle, String urlTitle,
        String description, String content, int displayDateMonth, int displayDateDay, int displayDateYear,
        int displayDateHour, int displayDateMinute, boolean allowPingbacks, boolean allowTrackbacks,
        String[] trackbacks, String coverImageCaption, ImageSelector coverImageImageSelector,
        ImageSelector smallImageImageSelector, ServiceContext serviceContext) throws PortalException {

    User user = userPersistence.findByPrimaryKey(userId);

    Date displayDate = PortalUtil.getDate(displayDateMonth, displayDateDay, displayDateYear, displayDateHour,
            displayDateMinute, user.getTimeZone(), EntryDisplayDateException.class);

    return updateEntry(userId, entryId, title, subtitle, urlTitle, description, content, displayDate,
            allowPingbacks, allowTrackbacks, trackbacks, coverImageCaption, coverImageImageSelector,
            smallImageImageSelector, serviceContext);
}

From source file:com.liferay.calendar.notification.impl.NotificationTemplateContextFactory.java

License:Open Source License

public static NotificationTemplateContext getInstance(NotificationType notificationType,
        NotificationTemplateType notificationTemplateType, CalendarBooking calendarBooking, User user)
        throws Exception {

    CalendarBooking parentCalendarBooking = calendarBooking.getParentCalendarBooking();

    Calendar calendar = parentCalendarBooking.getCalendar();

    NotificationTemplateContext notificationTemplateContext = new NotificationTemplateContext();

    CalendarNotificationTemplate calendarNotificationTemplate = CalendarNotificationTemplateLocalServiceUtil
            .fetchCalendarNotificationTemplate(calendar.getCalendarId(), notificationType,
                    notificationTemplateType);

    notificationTemplateContext.setCalendarNotificationTemplate(calendarNotificationTemplate);

    notificationTemplateContext.setCompanyId(calendarBooking.getCompanyId());
    notificationTemplateContext.setGroupId(calendarBooking.getGroupId());
    notificationTemplateContext.setCalendarId(calendar.getCalendarId());
    notificationTemplateContext.setNotificationTemplateType(notificationTemplateType);
    notificationTemplateContext.setNotificationType(notificationType);

    // Attributes

    Map<String, Serializable> attributes = new HashMap<>();

    TimeZone userTimezone = user.getTimeZone();

    Format dateFormatDateTime = FastDateFormatFactoryUtil.getDateTime(user.getLocale(),
            CalendarUtil.getCalendarBookingDisplayTimeZone(calendarBooking, userTimezone));

    String userTimezoneDisplayName = userTimezone.getDisplayName(false, TimeZone.SHORT, user.getLocale());

    String endTime = dateFormatDateTime.format(calendarBooking.getEndTime()) + StringPool.SPACE
            + userTimezoneDisplayName;//from  ww  w . ja v  a 2s  .c o  m

    attributes.put("endTime", endTime);

    attributes.put("location", calendarBooking.getLocation());

    Group group = GroupLocalServiceUtil.getGroup(user.getCompanyId(), GroupConstants.GUEST);

    String portalURL = _getPortalURL(group.getCompanyId(), group.getGroupId());

    attributes.put("portalURL", portalURL);

    PortletConfig portletConfig = getPortletConfig();

    ResourceBundle resourceBundle = portletConfig.getResourceBundle(user.getLocale());

    attributes.put("portletName",
            LanguageUtil.get(resourceBundle, "javax.portlet.title.".concat(CalendarPortletKeys.CALENDAR)));

    String startTime = dateFormatDateTime.format(calendarBooking.getStartTime()) + StringPool.SPACE
            + userTimezoneDisplayName;

    attributes.put("startTime", startTime);

    attributes.put("title", calendarBooking.getTitle(user.getLocale()));

    String calendarBookingURL = _getCalendarBookingURL(user, calendarBooking.getCalendarBookingId());

    attributes.put("url", calendarBookingURL);

    notificationTemplateContext.setAttributes(attributes);

    return notificationTemplateContext;
}

From source file:com.liferay.expando.web.internal.portlet.ExpandoPortlet.java

License:Open Source License

protected Serializable getValue(PortletRequest portletRequest, String name, int type) throws PortalException {

    String delimiter = StringPool.COMMA;

    Serializable value = null;//from  ww  w .  ja v a 2s. c om

    if (type == ExpandoColumnConstants.BOOLEAN) {
        value = ParamUtil.getBoolean(portletRequest, name);
    } else if (type == ExpandoColumnConstants.BOOLEAN_ARRAY) {
    } else if (type == ExpandoColumnConstants.DATE) {
        User user = _portal.getUser(portletRequest);

        int valueDateMonth = ParamUtil.getInteger(portletRequest, name + "Month");
        int valueDateDay = ParamUtil.getInteger(portletRequest, name + "Day");
        int valueDateYear = ParamUtil.getInteger(portletRequest, name + "Year");
        int valueDateHour = ParamUtil.getInteger(portletRequest, name + "Hour");
        int valueDateMinute = ParamUtil.getInteger(portletRequest, name + "Minute");
        int valueDateAmPm = ParamUtil.getInteger(portletRequest, name + "AmPm");

        if (valueDateAmPm == Calendar.PM) {
            valueDateHour += 12;
        }

        value = _portal.getDate(valueDateMonth, valueDateDay, valueDateYear, valueDateHour, valueDateMinute,
                user.getTimeZone(), ValueDataException.class);
    } else if (type == ExpandoColumnConstants.DATE_ARRAY) {
    } else if (type == ExpandoColumnConstants.DOUBLE) {
        value = ParamUtil.getDouble(portletRequest, name);
    } else if (type == ExpandoColumnConstants.DOUBLE_ARRAY) {
        String paramValue = ParamUtil.getString(portletRequest, name);

        if (paramValue.contains(StringPool.NEW_LINE)) {
            delimiter = StringPool.NEW_LINE;
        }

        String[] values = StringUtil.split(paramValue, delimiter);

        value = GetterUtil.getDoubleValues(values);
    } else if (type == ExpandoColumnConstants.FLOAT) {
        value = ParamUtil.getFloat(portletRequest, name);
    } else if (type == ExpandoColumnConstants.FLOAT_ARRAY) {
        String paramValue = ParamUtil.getString(portletRequest, name);

        if (paramValue.contains(StringPool.NEW_LINE)) {
            delimiter = StringPool.NEW_LINE;
        }

        String[] values = StringUtil.split(paramValue, delimiter);

        value = GetterUtil.getFloatValues(values);
    } else if (type == ExpandoColumnConstants.INTEGER) {
        value = ParamUtil.getInteger(portletRequest, name);
    } else if (type == ExpandoColumnConstants.INTEGER_ARRAY) {
        String paramValue = ParamUtil.getString(portletRequest, name);

        if (paramValue.contains(StringPool.NEW_LINE)) {
            delimiter = StringPool.NEW_LINE;
        }

        String[] values = StringUtil.split(paramValue, delimiter);

        value = GetterUtil.getIntegerValues(values);
    } else if (type == ExpandoColumnConstants.LONG) {
        value = ParamUtil.getLong(portletRequest, name);
    } else if (type == ExpandoColumnConstants.LONG_ARRAY) {
        String paramValue = ParamUtil.getString(portletRequest, name);

        if (paramValue.contains(StringPool.NEW_LINE)) {
            delimiter = StringPool.NEW_LINE;
        }

        String[] values = StringUtil.split(paramValue, delimiter);

        value = GetterUtil.getLongValues(values);
    } else if (type == ExpandoColumnConstants.NUMBER) {
        value = ParamUtil.getNumber(portletRequest, name);
    } else if (type == ExpandoColumnConstants.NUMBER_ARRAY) {
        String paramValue = ParamUtil.getString(portletRequest, name);

        if (paramValue.contains(StringPool.NEW_LINE)) {
            delimiter = StringPool.NEW_LINE;
        }

        String[] values = StringUtil.split(paramValue, delimiter);

        value = GetterUtil.getNumberValues(values);
    } else if (type == ExpandoColumnConstants.SHORT) {
        value = ParamUtil.getShort(portletRequest, name);
    } else if (type == ExpandoColumnConstants.SHORT_ARRAY) {
        String paramValue = ParamUtil.getString(portletRequest, name);

        if (paramValue.contains(StringPool.NEW_LINE)) {
            delimiter = StringPool.NEW_LINE;
        }

        String[] values = StringUtil.split(paramValue, delimiter);

        value = GetterUtil.getShortValues(values);
    } else if (type == ExpandoColumnConstants.STRING_ARRAY) {
        String paramValue = ParamUtil.getString(portletRequest, name);

        if (paramValue.contains(StringPool.NEW_LINE)) {
            delimiter = StringPool.NEW_LINE;
        }

        value = StringUtil.split(paramValue, delimiter);
    } else if (type == ExpandoColumnConstants.STRING_LOCALIZED) {
        value = (Serializable) LocalizationUtil.getLocalizationMap(portletRequest, name);
    } else {
        value = ParamUtil.getString(portletRequest, name);
    }

    return value;
}

From source file:com.liferay.exportimport.resources.importer.internal.util.LARImporter.java

License:Open Source License

@Override
public void importResources() throws Exception {
    if ((_privateLARInputStream == null) && (_publicLARInputStream == null)) {

        return;/*from w  ww .  j  a  v a2s. c o m*/
    }

    User user = UserLocalServiceUtil.getUser(userId);

    boolean privateLayout = false;

    if ((_privateLARInputStream != null) || targetClassName.equals(LayoutSetPrototype.class.getName())) {

        privateLayout = true;
    }

    long[] layoutIds = ExportImportHelperUtil.getAllLayoutIds(groupId, privateLayout);

    Map<String, Serializable> settingsMap = ExportImportConfigurationSettingsMapFactory
            .buildImportLayoutSettingsMap(userId, groupId, privateLayout, layoutIds, getParameterMap(),
                    user.getLocale(), user.getTimeZone());

    ExportImportConfiguration exportImportConfiguration = ExportImportConfigurationLocalServiceUtil
            .addExportImportConfiguration(userId, groupId, StringPool.BLANK, StringPool.BLANK,
                    ExportImportConfigurationConstants.TYPE_IMPORT_LAYOUT, settingsMap, new ServiceContext());

    InputStream inputStream = _publicLARInputStream;

    if (_privateLARInputStream != null) {
        inputStream = _privateLARInputStream;
    }

    ExportImportLocalServiceUtil.importLayouts(exportImportConfiguration, inputStream);
}

From source file:com.liferay.exportimport.staging.StagingImpl.java

License:Open Source License

@Override
public long copyRemoteLayouts(long sourceGroupId, boolean privateLayout, Map<Long, Boolean> layoutIdMap,
        String name, Map<String, String[]> parameterMap, String remoteAddress, int remotePort,
        String remotePathContext, boolean secureConnection, long remoteGroupId, boolean remotePrivateLayout)
        throws PortalException {

    validateRemoteGroup(sourceGroupId, remoteGroupId, remoteAddress, remotePort, remotePathContext,
            secureConnection);/*from  w  w w . ja va2  s. c o  m*/

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    User user = permissionChecker.getUser();

    Map<String, Serializable> publishLayoutRemoteSettingsMap = ExportImportConfigurationSettingsMapFactory
            .buildPublishLayoutRemoteSettingsMap(user.getUserId(), sourceGroupId, privateLayout, layoutIdMap,
                    parameterMap, remoteAddress, remotePort, remotePathContext, secureConnection, remoteGroupId,
                    remotePrivateLayout, user.getLocale(), user.getTimeZone());

    ExportImportConfiguration exportImportConfiguration = null;

    if (Validator.isNotNull(name)) {
        exportImportConfiguration = _exportImportConfigurationLocalService.addDraftExportImportConfiguration(
                user.getUserId(), name, ExportImportConfigurationConstants.TYPE_PUBLISH_LAYOUT_REMOTE,
                publishLayoutRemoteSettingsMap);
    } else {
        exportImportConfiguration = _exportImportConfigurationLocalService.addDraftExportImportConfiguration(
                user.getUserId(), ExportImportConfigurationConstants.TYPE_PUBLISH_LAYOUT_REMOTE,
                publishLayoutRemoteSettingsMap);
    }

    return doCopyRemoteLayouts(exportImportConfiguration, remoteAddress, remotePort, remotePathContext,
            secureConnection, remotePrivateLayout);
}

From source file:com.liferay.exportimport.staging.StagingImpl.java

License:Open Source License

@Override
public long publishPortlet(long userId, long sourceGroupId, long targetGroupId, long sourcePlid,
        long targetPlid, String portletId, Map<String, String[]> parameterMap) throws PortalException {

    User user = _userLocalService.getUser(userId);

    Map<String, Serializable> publishPortletSettingsMap = ExportImportConfigurationSettingsMapFactory
            .buildPublishPortletSettingsMap(userId, sourceGroupId, sourcePlid, targetGroupId, targetPlid,
                    portletId, parameterMap, user.getLocale(), user.getTimeZone());

    ExportImportConfiguration exportImportConfiguration = _exportImportConfigurationLocalService
            .addDraftExportImportConfiguration(userId, ExportImportConfigurationConstants.TYPE_PUBLISH_PORTLET,
                    publishPortletSettingsMap);

    return publishPortlet(userId, exportImportConfiguration);
}

From source file:com.liferay.exportimport.staging.StagingImpl.java

License:Open Source License

@Override
public long publishToRemote(PortletRequest portletRequest) throws PortalException {

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

    User user = themeDisplay.getUser();

    long groupId = ParamUtil.getLong(portletRequest, "groupId");

    Group group = _groupLocalService.getGroup(groupId);

    UnicodeProperties groupTypeSettingsProperties = group.getTypeSettingsProperties();

    long remoteGroupId = ParamUtil.getLong(portletRequest, "remoteGroupId",
            GetterUtil.getLong(groupTypeSettingsProperties.getProperty("remoteGroupId")));

    Map<String, Serializable> publishLayoutRemoteSettingsMap = null;
    String remoteAddress = null;//from w w w .  j a  v  a  2  s.co  m
    int remotePort = 0;
    String remotePathContext = null;
    boolean secureConnection = false;
    boolean remotePrivateLayout = false;

    long exportImportConfigurationId = ParamUtil.getLong(portletRequest, "exportImportConfigurationId");

    String name = ParamUtil.getString(portletRequest, "name");

    if (exportImportConfigurationId > 0) {
        ExportImportConfiguration exportImportConfiguration = _exportImportConfigurationLocalService
                .fetchExportImportConfiguration(exportImportConfigurationId);

        if (exportImportConfiguration != null) {
            publishLayoutRemoteSettingsMap = exportImportConfiguration.getSettingsMap();

            remoteAddress = MapUtil.getString(publishLayoutRemoteSettingsMap, "remoteAddress");
            remotePort = MapUtil.getInteger(publishLayoutRemoteSettingsMap, "remotePort");
            remotePathContext = MapUtil.getString(publishLayoutRemoteSettingsMap, "remotePathContext");
            secureConnection = MapUtil.getBoolean(publishLayoutRemoteSettingsMap, "secureConnection");
            remotePrivateLayout = MapUtil.getBoolean(publishLayoutRemoteSettingsMap, "remotePrivateLayout");

            if (!Validator.isBlank(name)) {
                Map<String, String[]> parameterMap = (Map<String, String[]>) publishLayoutRemoteSettingsMap
                        .get("parameterMap");

                parameterMap.put("name", new String[] { name });
            }
        }
    }

    if (publishLayoutRemoteSettingsMap == null) {
        boolean privateLayout = getPrivateLayout(portletRequest);
        Map<Long, Boolean> layoutIdMap = _exportImportHelper.getLayoutIdMap(portletRequest);
        Map<String, String[]> parameterMap = ExportImportConfigurationParameterMapFactory
                .buildParameterMap(portletRequest);
        remoteAddress = ParamUtil.getString(portletRequest, "remoteAddress",
                groupTypeSettingsProperties.getProperty("remoteAddress"));
        remotePort = ParamUtil.getInteger(portletRequest, "remotePort",
                GetterUtil.getInteger(groupTypeSettingsProperties.getProperty("remotePort")));
        remotePathContext = ParamUtil.getString(portletRequest, "remotePathContext",
                groupTypeSettingsProperties.getProperty("remotePathContext"));
        secureConnection = ParamUtil.getBoolean(portletRequest, "secureConnection",
                GetterUtil.getBoolean(groupTypeSettingsProperties.getProperty("secureConnection")));
        remotePrivateLayout = ParamUtil.getBoolean(portletRequest, "remotePrivateLayout");

        publishLayoutRemoteSettingsMap = ExportImportConfigurationSettingsMapFactory
                .buildPublishLayoutRemoteSettingsMap(user.getUserId(), groupId, privateLayout, layoutIdMap,
                        parameterMap, remoteAddress, remotePort, remotePathContext, secureConnection,
                        remoteGroupId, remotePrivateLayout, user.getLocale(), user.getTimeZone());
    }

    remoteAddress = stripProtocolFromRemoteAddress(remoteAddress);

    validateRemote(groupId, remoteAddress, remotePort, remotePathContext, secureConnection, remoteGroupId);

    ExportImportConfiguration exportImportConfiguration = null;

    if (Validator.isNotNull(name)) {
        exportImportConfiguration = _exportImportConfigurationLocalService.addDraftExportImportConfiguration(
                user.getUserId(), name, ExportImportConfigurationConstants.TYPE_PUBLISH_LAYOUT_REMOTE,
                publishLayoutRemoteSettingsMap);
    } else {
        exportImportConfiguration = _exportImportConfigurationLocalService.addDraftExportImportConfiguration(
                user.getUserId(), ExportImportConfigurationConstants.TYPE_PUBLISH_LAYOUT_REMOTE,
                publishLayoutRemoteSettingsMap);
    }

    return doCopyRemoteLayouts(exportImportConfiguration, remoteAddress, remotePort, remotePathContext,
            secureConnection, remotePrivateLayout);
}

From source file:com.liferay.journal.exportimport.data.handler.JournalArticleStagedModelDataHandler.java

License:Open Source License

@Override
protected void doImportStagedModel(PortletDataContext portletDataContext, JournalArticle article)
        throws Exception {

    long userId = portletDataContext.getUserId(article.getUserUuid());

    long authorId = _journalCreationStrategy.getAuthorUserId(portletDataContext, article);

    if (authorId != JournalCreationStrategy.USE_DEFAULT_USER_ID_STRATEGY) {
        userId = authorId;//from w ww  .j  a va  2  s  .  c om
    }

    User user = _userLocalService.getUser(userId);

    Map<Long, Long> folderIds = (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(JournalFolder.class);

    long folderId = MapUtil.getLong(folderIds, article.getFolderId(), article.getFolderId());

    String articleId = article.getArticleId();

    boolean autoArticleId = false;

    if (Validator.isNumber(articleId)
            || (_journalArticleLocalService.fetchArticle(portletDataContext.getScopeGroupId(), articleId,
                    JournalArticleConstants.VERSION_DEFAULT) != null)) {

        autoArticleId = true;
    }

    Map<String, String> articleIds = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(JournalArticle.class + ".articleId");

    String newArticleId = articleIds.get(articleId);

    if (Validator.isNotNull(newArticleId)) {

        // A sibling of a different version was already assigned a new
        // article id

        articleId = newArticleId;
        autoArticleId = false;
    }

    String content = article.getContent();

    content = _journalArticleExportImportContentProcessor.replaceImportContentReferences(portletDataContext,
            article, content);

    article.setContent(content);

    String newContent = _journalCreationStrategy.getTransformedContent(portletDataContext, article);

    if (newContent != JournalCreationStrategy.ARTICLE_CONTENT_UNCHANGED) {
        article.setContent(newContent);
    }

    Date displayDate = article.getDisplayDate();

    int displayDateMonth = 0;
    int displayDateDay = 0;
    int displayDateYear = 0;
    int displayDateHour = 0;
    int displayDateMinute = 0;

    if (displayDate != null) {
        Calendar displayCal = CalendarFactoryUtil.getCalendar(user.getTimeZone());

        displayCal.setTime(displayDate);

        displayDateMonth = displayCal.get(Calendar.MONTH);
        displayDateDay = displayCal.get(Calendar.DATE);
        displayDateYear = displayCal.get(Calendar.YEAR);
        displayDateHour = displayCal.get(Calendar.HOUR);
        displayDateMinute = displayCal.get(Calendar.MINUTE);

        if (displayCal.get(Calendar.AM_PM) == Calendar.PM) {
            displayDateHour += 12;
        }
    }

    Date expirationDate = article.getExpirationDate();

    int expirationDateMonth = 0;
    int expirationDateDay = 0;
    int expirationDateYear = 0;
    int expirationDateHour = 0;
    int expirationDateMinute = 0;
    boolean neverExpire = true;

    if (expirationDate != null) {
        Calendar expirationCal = CalendarFactoryUtil.getCalendar(user.getTimeZone());

        expirationCal.setTime(expirationDate);

        expirationDateMonth = expirationCal.get(Calendar.MONTH);
        expirationDateDay = expirationCal.get(Calendar.DATE);
        expirationDateYear = expirationCal.get(Calendar.YEAR);
        expirationDateHour = expirationCal.get(Calendar.HOUR);
        expirationDateMinute = expirationCal.get(Calendar.MINUTE);

        neverExpire = false;

        if (expirationCal.get(Calendar.AM_PM) == Calendar.PM) {
            expirationDateHour += 12;
        }
    }

    Date reviewDate = article.getReviewDate();

    int reviewDateMonth = 0;
    int reviewDateDay = 0;
    int reviewDateYear = 0;
    int reviewDateHour = 0;
    int reviewDateMinute = 0;
    boolean neverReview = true;

    if (reviewDate != null) {
        Calendar reviewCal = CalendarFactoryUtil.getCalendar(user.getTimeZone());

        reviewCal.setTime(reviewDate);

        reviewDateMonth = reviewCal.get(Calendar.MONTH);
        reviewDateDay = reviewCal.get(Calendar.DATE);
        reviewDateYear = reviewCal.get(Calendar.YEAR);
        reviewDateHour = reviewCal.get(Calendar.HOUR);
        reviewDateMinute = reviewCal.get(Calendar.MINUTE);

        neverReview = false;

        if (reviewCal.get(Calendar.AM_PM) == Calendar.PM) {
            reviewDateHour += 12;
        }
    }

    Map<String, String> ddmStructureKeys = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(DDMStructure.class + ".ddmStructureKey");

    String parentDDMStructureKey = MapUtil.getString(ddmStructureKeys, article.getDDMStructureKey(),
            article.getDDMStructureKey());

    Map<String, Long> ddmStructureIds = (Map<String, Long>) portletDataContext
            .getNewPrimaryKeysMap(DDMStructure.class);

    long ddmStructureId = 0;

    if (article.getClassNameId() != 0) {
        ddmStructureId = ddmStructureIds.get(article.getClassPK());
    }

    Map<String, String> ddmTemplateKeys = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(DDMTemplate.class + ".ddmTemplateKey");

    String parentDDMTemplateKey = MapUtil.getString(ddmTemplateKeys, article.getDDMTemplateKey(),
            article.getDDMTemplateKey());

    File smallFile = null;

    try {
        Element articleElement = portletDataContext.getImportDataStagedModelElement(article);

        if (article.isSmallImage()) {
            String smallImagePath = articleElement.attributeValue("small-image-path");

            if (Validator.isNotNull(article.getSmallImageURL())) {
                String smallImageURL = _journalArticleExportImportContentProcessor
                        .replaceImportContentReferences(portletDataContext, article,
                                article.getSmallImageURL());

                article.setSmallImageURL(smallImageURL);
            } else if (Validator.isNotNull(smallImagePath)) {
                byte[] bytes = portletDataContext.getZipEntryAsByteArray(smallImagePath);

                if (bytes != null) {
                    smallFile = FileUtil.createTempFile(article.getSmallImageType());

                    FileUtil.write(smallFile, bytes);
                }
            }
        }

        JournalArticle latestArticle = _journalArticleLocalService
                .fetchLatestArticle(article.getResourcePrimKey());

        if ((latestArticle != null) && (latestArticle.getId() == article.getId())) {

            List<Element> attachmentElements = portletDataContext.getReferenceDataElements(article,
                    DLFileEntry.class, PortletDataContext.REFERENCE_TYPE_WEAK);

            for (Element attachmentElement : attachmentElements) {
                String path = attachmentElement.attributeValue("path");

                FileEntry fileEntry = (FileEntry) portletDataContext.getZipEntryAsObject(path);

                InputStream inputStream = null;

                try {
                    String binPath = attachmentElement.attributeValue("bin-path");

                    if (Validator.isNull(binPath) && portletDataContext.isPerformDirectBinaryImport()) {

                        try {
                            inputStream = FileEntryUtil.getContentStream(fileEntry);
                        } catch (NoSuchFileException nsfe) {
                        }
                    } else {
                        inputStream = portletDataContext.getZipEntryAsInputStream(binPath);
                    }

                    if (inputStream == null) {
                        if (_log.isWarnEnabled()) {
                            _log.warn("Unable to import attachment for file " + "entry "
                                    + fileEntry.getFileEntryId());
                        }

                        continue;
                    }

                    TempFileEntryUtil.addTempFileEntry(portletDataContext.getScopeGroupId(), userId,
                            JournalArticleStagedModelDataHandler.class.getName(), fileEntry.getFileName(),
                            inputStream, fileEntry.getMimeType());
                } finally {
                    StreamUtil.cleanUp(inputStream);
                }
            }
        }

        String articleURL = null;

        boolean addGroupPermissions = _journalCreationStrategy.addGroupPermissions(portletDataContext, article);
        boolean addGuestPermissions = _journalCreationStrategy.addGuestPermissions(portletDataContext, article);

        ServiceContext serviceContext = portletDataContext.createServiceContext(article);

        serviceContext.setAddGroupPermissions(addGroupPermissions);
        serviceContext.setAddGuestPermissions(addGuestPermissions);

        if ((expirationDate != null) && expirationDate.before(new Date())) {
            article.setStatus(WorkflowConstants.STATUS_EXPIRED);
        }

        if ((article.getStatus() != WorkflowConstants.STATUS_APPROVED)
                && (article.getStatus() != WorkflowConstants.STATUS_SCHEDULED)) {

            serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);
        }

        JournalArticle importedArticle = null;

        String articleResourceUuid = articleElement.attributeValue("article-resource-uuid");

        // Used when importing LARs with journal schemas under 1.1.0

        _setLegacyValues(article);

        if (portletDataContext.isDataStrategyMirror()) {
            serviceContext.setUuid(article.getUuid());
            serviceContext.setAttribute("articleResourceUuid", articleResourceUuid);
            serviceContext.setAttribute("urlTitle", article.getUrlTitle());

            boolean preloaded = GetterUtil.getBoolean(articleElement.attributeValue("preloaded"));

            JournalArticle existingArticle = fetchExistingArticle(articleResourceUuid,
                    portletDataContext.getScopeGroupId(), articleId, newArticleId, preloaded);

            JournalArticle existingArticleVersion = null;

            if (existingArticle != null) {
                existingArticleVersion = fetchExistingArticleVersion(article.getUuid(),
                        portletDataContext.getScopeGroupId(), existingArticle.getArticleId(),
                        article.getVersion());
            }

            if ((existingArticle != null) && (existingArticleVersion == null)) {

                autoArticleId = false;
                articleId = existingArticle.getArticleId();
            }

            if (existingArticleVersion == null) {
                importedArticle = _journalArticleLocalService.addArticle(userId,
                        portletDataContext.getScopeGroupId(), folderId, article.getClassNameId(),
                        ddmStructureId, articleId, autoArticleId, article.getVersion(), article.getTitleMap(),
                        article.getDescriptionMap(), article.getContent(), parentDDMStructureKey,
                        parentDDMTemplateKey, article.getLayoutUuid(), displayDateMonth, displayDateDay,
                        displayDateYear, displayDateHour, displayDateMinute, expirationDateMonth,
                        expirationDateDay, expirationDateYear, expirationDateHour, expirationDateMinute,
                        neverExpire, reviewDateMonth, reviewDateDay, reviewDateYear, reviewDateHour,
                        reviewDateMinute, neverReview, article.isIndexable(), article.isSmallImage(),
                        article.getSmallImageURL(), smallFile, null, articleURL, serviceContext);
            } else {
                importedArticle = _journalArticleLocalService.updateArticle(userId,
                        existingArticle.getGroupId(), folderId, existingArticle.getArticleId(),
                        article.getVersion(), article.getTitleMap(), article.getDescriptionMap(),
                        article.getContent(), parentDDMStructureKey, parentDDMTemplateKey,
                        article.getLayoutUuid(), displayDateMonth, displayDateDay, displayDateYear,
                        displayDateHour, displayDateMinute, expirationDateMonth, expirationDateDay,
                        expirationDateYear, expirationDateHour, expirationDateMinute, neverExpire,
                        reviewDateMonth, reviewDateDay, reviewDateYear, reviewDateHour, reviewDateMinute,
                        neverReview, article.isIndexable(), article.isSmallImage(), article.getSmallImageURL(),
                        smallFile, null, articleURL, serviceContext);

                String articleUuid = article.getUuid();
                String importedArticleUuid = importedArticle.getUuid();

                if (!articleUuid.equals(importedArticleUuid)) {
                    importedArticle.setUuid(articleUuid);

                    _journalArticleLocalService.updateJournalArticle(importedArticle);
                }
            }
        } else {
            importedArticle = _journalArticleLocalService.addArticle(userId,
                    portletDataContext.getScopeGroupId(), folderId, article.getClassNameId(), ddmStructureId,
                    articleId, autoArticleId, article.getVersion(), article.getTitleMap(),
                    article.getDescriptionMap(), article.getContent(), parentDDMStructureKey,
                    parentDDMTemplateKey, article.getLayoutUuid(), displayDateMonth, displayDateDay,
                    displayDateYear, displayDateHour, displayDateMinute, expirationDateMonth, expirationDateDay,
                    expirationDateYear, expirationDateHour, expirationDateMinute, neverExpire, reviewDateMonth,
                    reviewDateDay, reviewDateYear, reviewDateHour, reviewDateMinute, neverReview,
                    article.isIndexable(), article.isSmallImage(), article.getSmallImageURL(), smallFile, null,
                    articleURL, serviceContext);
        }

        portletDataContext.importClassedModel(article, importedArticle);

        if (Validator.isNull(newArticleId)) {
            articleIds.put(article.getArticleId(), importedArticle.getArticleId());
        }

        Map<Long, Long> articlePrimaryKeys = (Map<Long, Long>) portletDataContext
                .getNewPrimaryKeysMap(JournalArticle.class + ".primaryKey");

        articlePrimaryKeys.put(article.getPrimaryKey(), importedArticle.getPrimaryKey());
    } finally {
        if (smallFile != null) {
            smallFile.delete();
        }
    }
}

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

License:Open Source License

/**
 * Adds a web content article with additional parameters.
 *
 * <p>/* w  w  w.j a v a2  s.  co m*/
 * The web content articles hold HTML content wrapped in XML. The XML lets
 * you specify the article's default locale and available locales. Here is a
 * content example:
 * </p>
 *
 * <p>
 * <pre>
 * <code>
 * &lt;?xml version='1.0' encoding='UTF-8'?&gt;
 * &lt;root default-locale="en_US" available-locales="en_US"&gt;
 *    &lt;static-content language-id="en_US"&gt;
 *       &lt;![CDATA[&lt;p&gt;&lt;b&gt;&lt;i&gt;test&lt;i&gt; content&lt;b&gt;&lt;/p&gt;]]&gt;
 *    &lt;/static-content&gt;
 * &lt;/root&gt;
 * </code>
 * </pre>
 * </p>
 *
 * @param  userId the primary key of the web content article's creator/owner
 * @param  groupId the primary key of the web content article's group
 * @param  folderId the primary key of the web content article folder
 * @param  classNameId the primary key of the DDMStructure class if the web
 *         content article is related to a DDM structure, the primary key of
 *         the class name associated with the article, or
 *         JournalArticleConstants.CLASSNAME_ID_DEFAULT in the journal-api
 *         module otherwise
 * @param  classPK the primary key of the DDM structure, if the primary key
 *         of the DDMStructure class is given as the
 *         <code>classNameId</code> parameter, the primary key of the class
 *         associated with the web content article, or <code>0</code>
 *         otherwise
 * @param  articleId the primary key of the web content article
 * @param  autoArticleId whether to auto generate the web content article ID
 * @param  version the web content article's version
 * @param  titleMap the web content article's locales and localized titles
 * @param  descriptionMap the web content article's locales and localized
 *         descriptions
 * @param  content the HTML content wrapped in XML
 * @param  ddmStructureKey the primary key of the web content article's DDM
 *         structure, if the article is related to a DDM structure, or
 *         <code>null</code> otherwise
 * @param  ddmTemplateKey the primary key of the web content article's DDM
 *         template
 * @param  layoutUuid the unique string identifying the web content
 *         article's display page
 * @param  displayDateMonth the month the web content article is set to
 *         display
 * @param  displayDateDay the calendar day the web content article is set to
 *         display
 * @param  displayDateYear the year the web content article is set to
 *         display
 * @param  displayDateHour the hour the web content article is set to
 *         display
 * @param  displayDateMinute the minute the web content article is set to
 *         display
 * @param  expirationDateMonth the month the web content article is set to
 *         expire
 * @param  expirationDateDay the calendar day the web content article is set
 *         to expire
 * @param  expirationDateYear the year the web content article is set to
 *         expire
 * @param  expirationDateHour the hour the web content article is set to
 *         expire
 * @param  expirationDateMinute the minute the web content article is set to
 *         expire
 * @param  neverExpire whether the web content article is not set to auto
 *         expire
 * @param  reviewDateMonth the month the web content article is set for
 *         review
 * @param  reviewDateDay the calendar day the web content article is set for
 *         review
 * @param  reviewDateYear the year the web content article is set for review
 * @param  reviewDateHour the hour the web content article is set for review
 * @param  reviewDateMinute the minute the web content article is set for
 *         review
 * @param  neverReview whether the web content article is not set for review
 * @param  indexable whether the web content article is searchable
 * @param  smallImage whether the web content article has a small image
 * @param  smallImageURL the web content article's small image URL
 * @param  smallImageFile the web content article's small image file
 * @param  images the web content's images
 * @param  articleURL the web content article's accessible URL
 * @param  serviceContext the service context to be applied. Can set the
 *         UUID, creation date, modification date, expando bridge
 *         attributes, guest permissions, group permissions, asset category
 *         IDs, asset tag names, asset link entry IDs, URL title, and
 *         workflow actions for the web content article. Can also set
 *         whether to add the default guest and group permissions.
 * @return the web content article
 */
@Indexable(type = IndexableType.REINDEX)
@Override
public JournalArticle addArticle(long userId, long groupId, long folderId, long classNameId, long classPK,
        String articleId, boolean autoArticleId, double version, Map<Locale, String> titleMap,
        Map<Locale, String> descriptionMap, String content, String ddmStructureKey, String ddmTemplateKey,
        String layoutUuid, int displayDateMonth, int displayDateDay, int displayDateYear, int displayDateHour,
        int displayDateMinute, int expirationDateMonth, int expirationDateDay, int expirationDateYear,
        int expirationDateHour, int expirationDateMinute, boolean neverExpire, int reviewDateMonth,
        int reviewDateDay, int reviewDateYear, int reviewDateHour, int reviewDateMinute, boolean neverReview,
        boolean indexable, boolean smallImage, String smallImageURL, File smallImageFile,
        Map<String, byte[]> images, String articleURL, ServiceContext serviceContext) throws PortalException {

    // Article

    User user = userLocalService.getUser(userId);
    articleId = StringUtil.toUpperCase(StringUtil.trim(articleId));

    Date displayDate = null;
    Date expirationDate = null;
    Date reviewDate = null;

    if (classNameId == JournalArticleConstants.CLASSNAME_ID_DEFAULT) {
        displayDate = PortalUtil.getDate(displayDateMonth, displayDateDay, displayDateYear, displayDateHour,
                displayDateMinute, user.getTimeZone(), null);

        if (!neverExpire) {
            expirationDate = PortalUtil.getDate(expirationDateMonth, expirationDateDay, expirationDateYear,
                    expirationDateHour, expirationDateMinute, user.getTimeZone(),
                    ArticleExpirationDateException.class);
        }

        if (!neverReview) {
            reviewDate = PortalUtil.getDate(reviewDateMonth, reviewDateDay, reviewDateYear, reviewDateHour,
                    reviewDateMinute, user.getTimeZone(), ArticleReviewDateException.class);
        }
    }

    byte[] smallImageBytes = null;

    try {
        smallImageBytes = FileUtil.getBytes(smallImageFile);
    } catch (IOException ioe) {
    }

    Date now = new Date();

    validateDDMStructureId(groupId, folderId, ddmStructureKey);

    if (autoArticleId) {
        articleId = String.valueOf(counterLocalService.increment());
    }

    validate(user.getCompanyId(), groupId, classNameId, articleId, autoArticleId, version, titleMap, content,
            ddmStructureKey, ddmTemplateKey, displayDate, expirationDate, smallImage, smallImageURL,
            smallImageFile, smallImageBytes, serviceContext);

    validateReferences(groupId, ddmStructureKey, ddmTemplateKey, layoutUuid, smallImage, smallImageURL,
            smallImageBytes, 0, content);

    serviceContext.setAttribute("articleId", articleId);

    long id = counterLocalService.increment();

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

    long resourcePrimKey = journalArticleResourceLocalService.getArticleResourcePrimKey(articleResourceUuid,
            groupId, articleId);

    JournalArticle article = journalArticlePersistence.create(id);

    Locale locale = getArticleDefaultLocale(content);

    String title = titleMap.get(locale);

    article.setUuid(serviceContext.getUuid());
    article.setResourcePrimKey(resourcePrimKey);
    article.setGroupId(groupId);
    article.setCompanyId(user.getCompanyId());
    article.setUserId(user.getUserId());
    article.setUserName(user.getFullName());
    article.setFolderId(folderId);
    article.setClassNameId(classNameId);
    article.setClassPK(classPK);
    article.setTreePath(article.buildTreePath());
    article.setArticleId(articleId);
    article.setVersion(version);
    article.setUrlTitle(getUniqueUrlTitle(id, groupId, articleId, title, null, serviceContext));

    content = format(user, groupId, article, content);

    article.setContent(content);

    article.setDDMStructureKey(ddmStructureKey);
    article.setDDMTemplateKey(ddmTemplateKey);
    article.setDefaultLanguageId(LocaleUtil.toLanguageId(locale));
    article.setLayoutUuid(layoutUuid);
    article.setDisplayDate(displayDate);
    article.setExpirationDate(expirationDate);
    article.setReviewDate(reviewDate);
    article.setIndexable(indexable);
    article.setSmallImage(smallImage);
    article.setSmallImageId(counterLocalService.increment());
    article.setSmallImageURL(smallImageURL);

    if ((expirationDate == null) || expirationDate.after(now)) {
        article.setStatus(WorkflowConstants.STATUS_DRAFT);
    } else {
        article.setStatus(WorkflowConstants.STATUS_EXPIRED);
    }

    article.setStatusByUserId(userId);
    article.setStatusDate(serviceContext.getModifiedDate(now));
    article.setExpandoBridgeAttributes(serviceContext);

    journalArticlePersistence.update(article);

    // Article localization

    _addArticleLocalizedFields(user.getCompanyId(), article.getId(), titleMap, descriptionMap);

    // Resources

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {

        addArticleResources(article, serviceContext.isAddGroupPermissions(),
                serviceContext.isAddGuestPermissions());
    } else {
        addArticleResources(article, serviceContext.getGroupPermissions(),
                serviceContext.getGuestPermissions());
    }

    // Small image

    saveImages(smallImage, article.getSmallImageId(), smallImageFile, smallImageBytes);

    // Asset

    updateAsset(userId, article, serviceContext.getAssetCategoryIds(), serviceContext.getAssetTagNames(),
            serviceContext.getAssetLinkEntryIds(), serviceContext.getAssetPriority());

    // Dynamic data mapping

    if (classNameLocalService.getClassNameId(DDMStructure.class) == classNameId) {

        updateDDMStructurePredefinedValues(classPK, content, serviceContext);
    } else {
        updateDDMLinks(id, groupId, ddmStructureKey, ddmTemplateKey, true);
    }

    // Email

    PortletPreferences preferences = ServiceContextUtil.getPortletPreferences(serviceContext);

    articleURL = buildArticleURL(articleURL, groupId, folderId, articleId);

    serviceContext.setAttribute("articleURL", articleURL);

    sendEmail(article, articleURL, preferences, "requested", serviceContext);

    // Workflow

    if (classNameId == JournalArticleConstants.CLASSNAME_ID_DEFAULT) {
        startWorkflowInstance(userId, article, serviceContext);
    } else {
        updateStatus(userId, article, WorkflowConstants.STATUS_APPROVED, null, serviceContext,
                new HashMap<String, Serializable>());
    }

    return journalArticlePersistence.findByPrimaryKey(article.getId());
}