Example usage for com.liferay.portal.kernel.transaction TransactionInvokerUtil invoke

List of usage examples for com.liferay.portal.kernel.transaction TransactionInvokerUtil invoke

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.transaction TransactionInvokerUtil invoke.

Prototype

public static <T> T invoke(TransactionConfig transactionConfig, Callable<T> callable) throws Throwable 

Source Link

Usage

From source file:com.liferay.blogs.web.internal.portlet.action.EditEntryMVCActionCommand.java

License:Open Source License

@Override
protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {

    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

    try {/*from w ww  .j  a va  2 s .co m*/
        BlogsEntry entry = null;
        List<BlogsEntryAttachmentFileEntryReference> blogsEntryAttachmentFileEntryReferences = null;

        UploadException uploadException = (UploadException) actionRequest
                .getAttribute(WebKeys.UPLOAD_EXCEPTION);

        if (uploadException != null) {
            Throwable cause = uploadException.getCause();

            if (uploadException.isExceededFileSizeLimit()) {
                throw new FileSizeException(cause);
            }

            if (uploadException.isExceededLiferayFileItemSizeLimit()) {
                throw new LiferayFileItemException(cause);
            }

            if (uploadException.isExceededUploadRequestSizeLimit()) {
                throw new UploadRequestSizeException(cause);
            }

            throw new PortalException(cause);
        } else if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) {

            Callable<Object[]> updateEntryCallable = new UpdateEntryCallable(actionRequest);

            Object[] returnValue = TransactionInvokerUtil.invoke(_transactionConfig, updateEntryCallable);

            entry = (BlogsEntry) returnValue[0];
            blogsEntryAttachmentFileEntryReferences = (List<BlogsEntryAttachmentFileEntryReference>) returnValue[1];
        } else if (cmd.equals(Constants.DELETE)) {
            deleteEntries(actionRequest, false);
        } else if (cmd.equals(Constants.MOVE_TO_TRASH)) {
            deleteEntries(actionRequest, true);
        } else if (cmd.equals(Constants.RESTORE)) {
            restoreTrashEntries(actionRequest);
        } else if (cmd.equals(Constants.SUBSCRIBE)) {
            subscribe(actionRequest);
        } else if (cmd.equals(Constants.UNSUBSCRIBE)) {
            unsubscribe(actionRequest);
        }

        String redirect = ParamUtil.getString(actionRequest, "redirect");
        String portletId = HttpUtil.getParameter(redirect, "p_p_id", false);

        int workflowAction = ParamUtil.getInteger(actionRequest, "workflowAction",
                WorkflowConstants.ACTION_SAVE_DRAFT);

        boolean ajax = ParamUtil.getBoolean(actionRequest, "ajax");

        if (ajax) {
            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

            JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

            for (BlogsEntryAttachmentFileEntryReference blogsEntryAttachmentFileEntryReference : blogsEntryAttachmentFileEntryReferences) {

                JSONObject blogsEntryFileEntryReferencesJSONObject = JSONFactoryUtil.createJSONObject();

                blogsEntryFileEntryReferencesJSONObject.put("attributeDataImageId",
                        EditorConstants.ATTRIBUTE_DATA_IMAGE_ID);
                blogsEntryFileEntryReferencesJSONObject.put("fileEntryId", String.valueOf(
                        blogsEntryAttachmentFileEntryReference.getTempBlogsEntryAttachmentFileEntryId()));
                blogsEntryFileEntryReferencesJSONObject.put("fileEntryUrl",
                        PortletFileRepositoryUtil.getPortletFileEntryURL(null,
                                blogsEntryAttachmentFileEntryReference.getBlogsEntryAttachmentFileEntry(),
                                StringPool.BLANK));

                jsonArray.put(blogsEntryFileEntryReferencesJSONObject);
            }

            jsonObject.put("blogsEntryAttachmentReferences", jsonArray);
            jsonObject.put("coverImageFileEntryId", entry.getCoverImageFileEntryId());
            jsonObject.put("entryId", entry.getEntryId());
            jsonObject.put("redirect", redirect);

            JSONPortletResponseUtil.writeJSON(actionRequest, actionResponse, jsonObject);

            return;
        }

        if ((entry != null) && (workflowAction == WorkflowConstants.ACTION_SAVE_DRAFT)) {

            redirect = getSaveAndContinueRedirect(actionRequest, entry, redirect);

            sendRedirect(actionRequest, actionResponse, redirect);
        } else {
            WindowState windowState = actionRequest.getWindowState();

            if (!windowState.equals(LiferayWindowState.POP_UP)) {
                sendRedirect(actionRequest, actionResponse, redirect);
            } else {
                redirect = PortalUtil.escapeRedirect(redirect);

                if (Validator.isNotNull(redirect)) {
                    if (cmd.equals(Constants.ADD) && (entry != null)) {
                        String namespace = PortalUtil.getPortletNamespace(portletId);

                        redirect = HttpUtil.addParameter(redirect, namespace + "className",
                                BlogsEntry.class.getName());
                        redirect = HttpUtil.addParameter(redirect, namespace + "classPK", entry.getEntryId());
                    }

                    actionRequest.setAttribute(WebKeys.REDIRECT, redirect);
                }
            }
        }
    } catch (AssetCategoryException | AssetTagException e) {
        SessionErrors.add(actionRequest, e.getClass(), e);

        actionResponse.setRenderParameter("mvcRenderCommandName", "/blogs/edit_entry");

        hideDefaultSuccessMessage(actionRequest);
    } catch (EntryContentException | EntryCoverImageCropException | EntryDescriptionException
            | EntryDisplayDateException | EntrySmallImageNameException | EntrySmallImageScaleException
            | EntryTitleException | EntryUrlTitleException | FileSizeException | LiferayFileItemException
            | SanitizerException | UploadRequestSizeException e) {

        SessionErrors.add(actionRequest, e.getClass());

        actionResponse.setRenderParameter("mvcRenderCommandName", "/blogs/edit_entry");

        hideDefaultSuccessMessage(actionRequest);
    } catch (NoSuchEntryException | PrincipalException e) {
        SessionErrors.add(actionRequest, e.getClass());

        actionResponse.setRenderParameter("mvcPath", "/blogs/error.jsp");

        hideDefaultSuccessMessage(actionRequest);
    } catch (Throwable t) {
        _log.error(t, t);

        actionResponse.setRenderParameter("mvcPath", "/blogs/error.jsp");

        hideDefaultSuccessMessage(actionRequest);
    }
}

From source file:com.liferay.dynamic.data.lists.form.web.internal.portlet.action.SaveRecordSetMVCResourceCommand.java

License:Open Source License

protected DDLRecordSet saveRecordSetInTransaction(final ResourceRequest resourceRequest,
        final ResourceResponse resourceResponse) throws Throwable {

    Callable<DDLRecordSet> callable = new Callable<DDLRecordSet>() {

        @Override/*from w  w w  .ja  v  a2  s  .c  o m*/
        public DDLRecordSet call() throws Exception {
            return saveRecordSetMVCCommandHelper.saveRecordSet(resourceRequest, resourceResponse);
        }

    };

    return TransactionInvokerUtil.invoke(_transactionConfig, callable);
}

From source file:com.liferay.dynamic.data.mapping.form.web.internal.portlet.action.SaveFormInstanceMVCResourceCommand.java

License:Open Source License

protected DDMFormInstance saveFormInstanceInTransaction(final ResourceRequest resourceRequest,
        final ResourceResponse resourceResponse) throws Throwable {

    Callable<DDMFormInstance> callable = new Callable<DDMFormInstance>() {

        @Override/* w ww  .  jav  a2  s.c o m*/
        public DDMFormInstance call() throws Exception {
            return saveFormInstanceMVCCommandHelper.saveFormInstance(resourceRequest, resourceResponse);
        }

    };

    return TransactionInvokerUtil.invoke(_transactionConfig, callable);
}

From source file:com.liferay.exportimport.internal.background.task.LayoutImportBackgroundTaskExecutor.java

License:Open Source License

@Override
public BackgroundTaskResult execute(BackgroundTask backgroundTask) throws Exception {

    ExportImportConfiguration exportImportConfiguration = getExportImportConfiguration(backgroundTask);

    List<FileEntry> attachmentsFileEntries = backgroundTask.getAttachmentsFileEntries();

    File file = null;/*  w  w w .j  a  v a 2 s  .  co  m*/

    for (FileEntry attachmentsFileEntry : attachmentsFileEntries) {
        try {
            file = FileUtil.createTempFile("lar");

            FileUtil.write(file, attachmentsFileEntry.getContentStream());

            TransactionInvokerUtil.invoke(transactionConfig,
                    new LayoutImportCallable(exportImportConfiguration, file));
        } catch (IOException ioe) {
            StringBundler sb = new StringBundler(3);

            sb.append("Unable to process LAR file while executing ");
            sb.append("LayoutImportBackgroundTaskExecutor: ");

            if (!Objects.isNull(attachmentsFileEntry)
                    && Validator.isNotNull(attachmentsFileEntry.getFileName())) {

                sb.append(attachmentsFileEntry.getFileName());
            } else {
                sb.append("unknown file name");
            }

            throw new SystemException(sb.toString(), ioe);
        } catch (Throwable t) {
            if (_log.isDebugEnabled()) {
                _log.debug(t, t);
            } else if (_log.isWarnEnabled()) {
                _log.warn("Unable to import layouts: " + t.getMessage());
            }

            throw new SystemException(t);
        } finally {
            FileUtil.delete(file);
        }
    }

    return BackgroundTaskResult.SUCCESS;
}

From source file:com.liferay.exportimport.internal.background.task.LayoutStagingBackgroundTaskExecutor.java

License:Open Source License

@Override
public BackgroundTaskResult execute(BackgroundTask backgroundTask) throws PortalException {

    ExportImportConfiguration exportImportConfiguration = getExportImportConfiguration(backgroundTask);

    Map<String, Serializable> settingsMap = exportImportConfiguration.getSettingsMap();

    long userId = MapUtil.getLong(settingsMap, "userId");
    long targetGroupId = MapUtil.getLong(settingsMap, "targetGroupId");
    long sourceGroupId = MapUtil.getLong(settingsMap, "sourceGroupId");

    clearBackgroundTaskStatus(backgroundTask);

    File file = null;//from w  w w .ja  v a2 s  .c o m
    MissingReferences missingReferences = null;

    try {
        ExportImportThreadLocal.setLayoutStagingInProcess(true);

        Group targetGroup = GroupLocalServiceUtil.fetchGroup(targetGroupId);

        if (targetGroup == null) {
            throw new NoSuchGroupException(
                    "Target group does not exists with the primary key " + targetGroupId);
        }

        Group sourceGroup = GroupLocalServiceUtil.getGroup(sourceGroupId);

        if (sourceGroup.hasStagingGroup()) {
            Group stagingGroup = sourceGroup.getStagingGroup();

            if (stagingGroup.getGroupId() == targetGroupId) {
                ExportImportThreadLocal.setInitialLayoutStagingInProcess(true);

                TrashEntryLocalServiceUtil.deleteEntries(sourceGroupId, true);
            }
        }

        ExportImportLifecycleManagerUtil.fireExportImportLifecycleEvent(EVENT_PUBLICATION_LAYOUT_LOCAL_STARTED,
                PROCESS_FLAG_LAYOUT_STAGING_IN_PROCESS,
                String.valueOf(exportImportConfiguration.getExportImportConfigurationId()),
                exportImportConfiguration);

        boolean privateLayout = MapUtil.getBoolean(settingsMap, "privateLayout");

        initThreadLocals(sourceGroupId, privateLayout);

        file = ExportImportLocalServiceUtil.exportLayoutsAsFile(exportImportConfiguration);

        markBackgroundTask(backgroundTask.getBackgroundTaskId(), "exported");

        missingReferences = TransactionInvokerUtil.invoke(transactionConfig,
                new LayoutStagingImportCallable(backgroundTask.getBackgroundTaskId(), exportImportConfiguration,
                        file, sourceGroupId, targetGroupId, userId));

        ExportImportThreadLocal.setInitialLayoutStagingInProcess(false);
        ExportImportThreadLocal.setLayoutStagingInProcess(false);

        ExportImportLifecycleManagerUtil.fireExportImportLifecycleEvent(
                EVENT_PUBLICATION_LAYOUT_LOCAL_SUCCEEDED, PROCESS_FLAG_LAYOUT_STAGING_IN_PROCESS,
                String.valueOf(exportImportConfiguration.getExportImportConfigurationId()),
                exportImportConfiguration);
    } catch (Throwable t) {
        ExportImportThreadLocal.setInitialLayoutStagingInProcess(false);
        ExportImportThreadLocal.setLayoutStagingInProcess(false);

        ExportImportLifecycleManagerUtil.fireExportImportLifecycleEvent(EVENT_PUBLICATION_LAYOUT_LOCAL_FAILED,
                PROCESS_FLAG_LAYOUT_STAGING_IN_PROCESS,
                String.valueOf(exportImportConfiguration.getExportImportConfigurationId()),
                exportImportConfiguration, t);

        if (_log.isDebugEnabled()) {
            _log.debug(t, t);
        } else if (_log.isWarnEnabled()) {
            _log.warn("Unable to publish layout: " + t.getMessage());
        }

        Group sourceGroup = GroupLocalServiceUtil.getGroup(sourceGroupId);

        if (sourceGroup.hasStagingGroup()) {
            ServiceContext serviceContext = new ServiceContext();

            serviceContext.setUserId(userId);

            StagingLocalServiceUtil.disableStaging(sourceGroup, serviceContext);

            List<BackgroundTask> queuedBackgroundTasks = BackgroundTaskManagerUtil.getBackgroundTasks(
                    sourceGroupId, LayoutStagingBackgroundTaskExecutor.class.getName(),
                    BackgroundTaskConstants.STATUS_QUEUED);

            for (BackgroundTask queuedBackgroundTask : queuedBackgroundTasks) {

                BackgroundTaskManagerUtil.amendBackgroundTask(queuedBackgroundTask.getBackgroundTaskId(), null,
                        BackgroundTaskConstants.STATUS_CANCELLED, new ServiceContext());
            }
        }

        deleteTempLarOnFailure(file);

        throw new SystemException(t);
    }

    deleteTempLarOnSuccess(file);

    return processMissingReferences(backgroundTask.getBackgroundTaskId(), missingReferences);
}

From source file:com.liferay.exportimport.internal.background.task.PortletImportBackgroundTaskExecutor.java

License:Open Source License

@Override
public BackgroundTaskResult execute(BackgroundTask backgroundTask) throws Exception {

    ExportImportConfiguration exportImportConfiguration = getExportImportConfiguration(backgroundTask);

    List<FileEntry> attachmentsFileEntries = backgroundTask.getAttachmentsFileEntries();

    File file = null;//from  w  w  w  . j  av a2  s .  com

    for (FileEntry attachmentsFileEntry : attachmentsFileEntries) {
        try {
            file = FileUtil.createTempFile("lar");

            FileUtil.write(file, attachmentsFileEntry.getContentStream());

            TransactionInvokerUtil.invoke(transactionConfig,
                    new PortletImportCallable(exportImportConfiguration, file));
        } catch (Throwable t) {
            if (_log.isDebugEnabled()) {
                _log.debug(t, t);
            } else if (_log.isWarnEnabled()) {
                _log.warn("Unable to import portlet: " + t.getMessage());
            }

            throw new SystemException(t);
        } finally {
            FileUtil.delete(file);
        }
    }

    return BackgroundTaskResult.SUCCESS;
}

From source file:com.liferay.exportimport.internal.background.task.PortletStagingBackgroundTaskExecutor.java

License:Open Source License

@Override
public BackgroundTaskResult execute(BackgroundTask backgroundTask) throws Exception {

    ExportImportConfiguration exportImportConfiguration = getExportImportConfiguration(backgroundTask);

    File file = null;/*from   w  ww.  j  a v  a 2  s  . c om*/
    MissingReferences missingReferences = null;

    try {
        ExportImportThreadLocal.setPortletStagingInProcess(true);

        ExportImportLifecycleManagerUtil.fireExportImportLifecycleEvent(EVENT_PUBLICATION_PORTLET_LOCAL_STARTED,
                PROCESS_FLAG_PORTLET_STAGING_IN_PROCESS,
                String.valueOf(exportImportConfiguration.getExportImportConfigurationId()),
                exportImportConfiguration);

        file = ExportImportLocalServiceUtil.exportPortletInfoAsFile(exportImportConfiguration);

        markBackgroundTask(backgroundTask.getBackgroundTaskId(), "exported");

        missingReferences = TransactionInvokerUtil.invoke(transactionConfig, new PortletStagingCallable(
                backgroundTask.getBackgroundTaskId(), exportImportConfiguration, file));

        ExportImportThreadLocal.setPortletStagingInProcess(false);

        ExportImportLifecycleManagerUtil.fireExportImportLifecycleEvent(
                EVENT_PUBLICATION_PORTLET_LOCAL_SUCCEEDED, PROCESS_FLAG_PORTLET_STAGING_IN_PROCESS,
                String.valueOf(exportImportConfiguration.getExportImportConfigurationId()),
                exportImportConfiguration);
    } catch (Throwable t) {
        ExportImportThreadLocal.setPortletStagingInProcess(false);

        ExportImportLifecycleManagerUtil.fireExportImportLifecycleEvent(EVENT_PUBLICATION_PORTLET_LOCAL_FAILED,
                PROCESS_FLAG_PORTLET_STAGING_IN_PROCESS,
                String.valueOf(exportImportConfiguration.getExportImportConfigurationId()),
                exportImportConfiguration);

        if (_log.isDebugEnabled()) {
            _log.debug(t, t);
        } else if (_log.isWarnEnabled()) {
            _log.warn("Unable to publish portlet: " + t.getMessage());
        }

        deleteTempLarOnFailure(file);

        throw new SystemException(t);
    }

    deleteTempLarOnSuccess(file);

    return processMissingReferences(backgroundTask.getBackgroundTaskId(), missingReferences);
}

From source file:com.liferay.layout.admin.web.internal.exportimport.data.handler.LayoutStagedModelDataHandler.java

License:Open Source License

@Override
protected void doImportStagedModel(PortletDataContext portletDataContext, Layout layout) throws Exception {

    final long groupId = portletDataContext.getGroupId();
    long userId = portletDataContext.getUserId(layout.getUserUuid());

    Element layoutElement = portletDataContext.getImportDataStagedModelElement(layout);

    long layoutId = GetterUtil.getLong(layoutElement.attributeValue("layout-id"));

    long oldLayoutId = layoutId;

    final boolean privateLayout = portletDataContext.isPrivateLayout();

    Map<Long, Layout> layouts = (Map<Long, Layout>) portletDataContext
            .getNewPrimaryKeysMap(Layout.class + ".layout");

    Layout existingLayout = null;// w  ww  . j a  v  a  2  s. c  om
    Layout importedLayout = null;

    String friendlyURL = layout.getFriendlyURL();

    String layoutsImportMode = MapUtil.getString(portletDataContext.getParameterMap(),
            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE,
            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_UUID);

    if (layoutsImportMode.equals(PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_ADD_AS_NEW)) {

        layoutId = _layoutLocalService.getNextLayoutId(groupId, privateLayout);

        friendlyURL = StringPool.SLASH + layoutId;
    } else if (layoutsImportMode.equals(PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_NAME)) {

        Locale locale = LocaleUtil.getSiteDefault();

        String localizedName = layout.getName(locale);

        List<Layout> previousLayouts = _layoutLocalService.getLayouts(groupId, privateLayout);

        for (Layout curLayout : previousLayouts) {
            if (localizedName.equals(curLayout.getName(locale))
                    || friendlyURL.equals(curLayout.getFriendlyURL())) {

                existingLayout = curLayout;

                break;
            }
        }

        if (existingLayout == null) {
            layoutId = _layoutLocalService.getNextLayoutId(groupId, privateLayout);
        }
    } else if (layoutsImportMode.equals(PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {

        existingLayout = _layoutLocalService.fetchLayoutByUuidAndGroupId(layout.getUuid(), groupId,
                privateLayout);

        if (SitesUtil.isLayoutModifiedSinceLastMerge(existingLayout)) {
            layouts.put(oldLayoutId, existingLayout);

            return;
        }

        LayoutFriendlyURL layoutFriendlyURL = _layoutFriendlyURLLocalService
                .fetchFirstLayoutFriendlyURL(groupId, privateLayout, friendlyURL);

        if ((layoutFriendlyURL != null) && (existingLayout == null)) {
            Layout mergeFailFriendlyURLLayout = _layoutLocalService.getLayout(layoutFriendlyURL.getPlid());

            SitesUtil.addMergeFailFriendlyURLLayout(mergeFailFriendlyURLLayout);

            if (!_log.isWarnEnabled()) {
                return;
            }

            StringBundler sb = new StringBundler(6);

            sb.append("Layout with layout ID ");
            sb.append(layout.getLayoutId());
            sb.append(" cannot be propagated because the friendly URL ");
            sb.append("conflicts with the friendly URL of layout with ");
            sb.append("layout ID ");
            sb.append(mergeFailFriendlyURLLayout.getLayoutId());

            _log.warn(sb.toString());

            return;
        }
    } else {

        // The default behavior of import mode is
        // PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_UUID

        existingLayout = _layoutLocalService.fetchLayoutByUuidAndGroupId(layout.getUuid(), groupId,
                privateLayout);

        if (existingLayout == null) {
            existingLayout = _layoutLocalService.fetchLayoutByFriendlyURL(groupId, privateLayout, friendlyURL);
        }

        if (existingLayout == null) {
            layoutId = _layoutLocalService.getNextLayoutId(groupId, privateLayout);
        }
    }

    if (_log.isDebugEnabled()) {
        StringBundler sb = new StringBundler(7);

        sb.append("Layout with {groupId=");
        sb.append(groupId);
        sb.append(",privateLayout=");
        sb.append(privateLayout);
        sb.append(",layoutId=");
        sb.append(layoutId);

        if (existingLayout == null) {
            sb.append("} does not exist");

            _log.debug(sb.toString());
        } else {
            sb.append("} exists");

            _log.debug(sb.toString());
        }
    }

    if (existingLayout == null) {
        long plid = _counterLocalService.increment();

        importedLayout = _layoutLocalService.createLayout(plid);

        if (layoutsImportMode.equals(PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {

            importedLayout.setSourcePrototypeLayoutUuid(layout.getUuid());

            layoutId = _layoutLocalService.getNextLayoutId(groupId, privateLayout);
        } else {
            importedLayout.setCreateDate(layout.getCreateDate());
            importedLayout.setModifiedDate(layout.getModifiedDate());
            importedLayout.setLayoutPrototypeUuid(layout.getLayoutPrototypeUuid());
            importedLayout.setLayoutPrototypeLinkEnabled(layout.isLayoutPrototypeLinkEnabled());
            importedLayout.setSourcePrototypeLayoutUuid(layout.getSourcePrototypeLayoutUuid());
        }

        importedLayout.setUuid(layout.getUuid());
        importedLayout.setGroupId(groupId);
        importedLayout.setUserId(userId);
        importedLayout.setPrivateLayout(privateLayout);
        importedLayout.setLayoutId(layoutId);

        initNewLayoutPermissions(portletDataContext.getCompanyId(), groupId, userId, layout, importedLayout,
                privateLayout);

        LayoutSet layoutSet = _layoutSetLocalService.getLayoutSet(groupId, privateLayout);

        importedLayout.setLayoutSet(layoutSet);
    } else {
        importedLayout = existingLayout;
    }

    portletDataContext.setPlid(importedLayout.getPlid());
    portletDataContext.setOldPlid(layout.getPlid());

    long parentLayoutId = layout.getParentLayoutId();

    String parentLayoutUuid = GetterUtil.getString(layoutElement.attributeValue("parent-layout-uuid"));

    Element parentLayoutElement = portletDataContext.getReferenceDataElement(layout, Layout.class,
            layout.getGroupId(), parentLayoutUuid);

    if ((parentLayoutId != LayoutConstants.DEFAULT_PARENT_LAYOUT_ID) && (parentLayoutElement != null)) {

        StagedModelDataHandlerUtil.importStagedModel(portletDataContext, parentLayoutElement);

        Layout importedParentLayout = layouts.get(parentLayoutId);

        parentLayoutId = importedParentLayout.getLayoutId();
    }

    if (_log.isDebugEnabled()) {
        StringBundler sb = new StringBundler(4);

        sb.append("Importing layout with layout ID ");
        sb.append(layoutId);
        sb.append(" and parent layout ID ");
        sb.append(parentLayoutId);

        _log.debug(sb.toString());
    }

    importedLayout.setCompanyId(portletDataContext.getCompanyId());

    if (layout.getLayoutPrototypeUuid() != null) {
        importedLayout.setModifiedDate(new Date());
    }

    importedLayout.setParentLayoutId(parentLayoutId);
    importedLayout.setName(layout.getName());
    importedLayout.setTitle(layout.getTitle());
    importedLayout.setDescription(layout.getDescription());
    importedLayout.setKeywords(layout.getKeywords());
    importedLayout.setRobots(layout.getRobots());
    importedLayout.setType(layout.getType());

    String portletsMergeMode = MapUtil.getString(portletDataContext.getParameterMap(),
            PortletDataHandlerKeys.PORTLETS_MERGE_MODE, PortletDataHandlerKeys.PORTLETS_MERGE_MODE_REPLACE);

    if (Objects.equals(layout.getType(), LayoutConstants.TYPE_PORTLET)
            && Validator.isNotNull(layout.getTypeSettings())
            && !portletsMergeMode.equals(PortletDataHandlerKeys.PORTLETS_MERGE_MODE_REPLACE)) {

        mergePortlets(importedLayout, layout.getTypeSettings(), portletsMergeMode);
    } else if (Objects.equals(layout.getType(), LayoutConstants.TYPE_LINK_TO_LAYOUT)) {

        importLinkedLayout(portletDataContext, layout, importedLayout, layoutElement);

        updateTypeSettings(importedLayout, layout);
    } else {
        updateTypeSettings(importedLayout, layout);
    }

    importedLayout.setHidden(layout.isHidden());
    importedLayout.setFriendlyURL(getUniqueFriendlyURL(portletDataContext, importedLayout, friendlyURL));

    if (layout.getIconImageId() > 0) {
        importLayoutIconImage(portletDataContext, importedLayout, layoutElement);
    } else if (importedLayout.getIconImageId() > 0) {
        _imageLocalService.deleteImage(importedLayout.getIconImageId());

        importedLayout.setIconImageId(0);
    }

    if (existingLayout == null) {
        try {
            final long finalParentLayoutId = parentLayoutId;

            int priority = TransactionInvokerUtil.invoke(_transactionConfig, new Callable<Integer>() {

                @Override
                public Integer call() throws Exception {
                    return _layoutLocalServiceHelper.getNextPriority(groupId, privateLayout,
                            finalParentLayoutId, null, -1);
                }

            });

            importedLayout.setPriority(priority);
        } catch (Throwable t) {
            ReflectionUtil.throwException(t);
        }
    }

    importedLayout.setLayoutPrototypeUuid(layout.getLayoutPrototypeUuid());
    importedLayout.setLayoutPrototypeLinkEnabled(layout.isLayoutPrototypeLinkEnabled());

    ServiceContext serviceContext = portletDataContext.createServiceContext(layout);

    importedLayout.setExpandoBridgeAttributes(serviceContext);

    _staging.updateLastImportSettings(layoutElement, importedLayout, portletDataContext);

    fixImportTypeSettings(importedLayout);

    importTheme(portletDataContext, layout, importedLayout);

    _layoutLocalService.updateLayout(importedLayout);

    _layoutSetLocalService.updatePageCount(groupId, privateLayout);

    Map<Long, Long> layoutPlids = (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(Layout.class);

    layoutPlids.put(layout.getPlid(), importedLayout.getPlid());

    layouts.put(oldLayoutId, importedLayout);

    if (Objects.equals(layout.getType(), LayoutConstants.TYPE_PORTLET)
            && Validator.isNotNull(layout.getTypeSettings())) {

        importLayoutPortlets(portletDataContext, importedLayout, layoutElement);
    }

    importAssets(portletDataContext, layout, importedLayout);

    importLayoutFriendlyURLs(portletDataContext, layout, importedLayout);

    portletDataContext.importClassedModel(layout, importedLayout);
}

From source file:com.liferay.site.admin.web.internal.portlet.SiteAdminPortlet.java

License:Open Source License

public void editGroup(ActionRequest actionRequest, ActionResponse actionResponse) throws Throwable {

    Callable<Group> groupCallable = new GroupCallable(actionRequest);

    Group group = TransactionInvokerUtil.invoke(_transactionConfig, groupCallable);

    long liveGroupId = ParamUtil.getLong(actionRequest, "liveGroupId");

    if (liveGroupId <= 0) {
        hideDefaultSuccessMessage(actionRequest);

        MultiSessionMessages.add(actionRequest, SiteAdminPortletKeys.SITE_SETTINGS + "requestProcessed");
    }/*from  ww w  . jav  a  2 s .c  om*/

    PortletURL siteAdministrationURL = getSiteAdministrationURL(actionRequest, group);

    siteAdministrationURL.setParameter("historyKey", getHistoryKey(actionRequest, actionResponse));
    siteAdministrationURL.setParameter("redirect", siteAdministrationURL.toString());

    actionRequest.setAttribute(WebKeys.REDIRECT, siteAdministrationURL.toString());

    sendRedirect(actionRequest, actionResponse);
}