Example usage for com.liferay.portal.kernel.service ServiceContextThreadLocal pushServiceContext

List of usage examples for com.liferay.portal.kernel.service ServiceContextThreadLocal pushServiceContext

Introduction

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

Prototype

public static void pushServiceContext(ServiceContext serviceContext) 

Source Link

Usage

From source file:com.liferay.adaptive.media.document.library.thumbnails.internal.commands.test.AdaptiveMediaThumbnailsOSGiCommandsTest.java

License:Open Source License

@Before
public void setUp() throws Exception {
    ServiceTestUtil.setUser(TestPropsValues.getUser());

    _company = CompanyTestUtil.addCompany();

    _user = UserTestUtil.addCompanyAdminUser(_company);

    _group = GroupTestUtil.addGroup(_company.getCompanyId(), _user.getUserId(),
            GroupConstants.DEFAULT_PARENT_GROUP_ID);

    _addConfiguration(100, 100);/* w  w  w  .jav  a  2 s  . c o  m*/
    _addConfiguration(300, 300);

    _serviceContext = ServiceContextTestUtil.getServiceContext(_group, _user.getUserId());

    ServiceContextThreadLocal.pushServiceContext(_serviceContext);
}

From source file:com.liferay.asset.search.test.AssetTagsSearchTest.java

License:Open Source License

@Before
public void setUp() throws Exception {
    _group = GroupTestUtil.addGroup();/*w w  w .  ja va2  s  . c  o  m*/

    _serviceContext = ServiceContextTestUtil.getServiceContext(_group.getGroupId(),
            TestPropsValues.getUserId());

    _serviceContext.setCompanyId(TestPropsValues.getCompanyId());

    ServiceContextThreadLocal.pushServiceContext(_serviceContext);
}

From source file:com.liferay.exportimport.controller.LayoutExportController.java

License:Open Source License

protected File doExport(PortletDataContext portletDataContext) throws Exception {

    Map<String, String[]> parameterMap = portletDataContext.getParameterMap();

    boolean ignoreLastPublishDate = MapUtil.getBoolean(parameterMap,
            PortletDataHandlerKeys.IGNORE_LAST_PUBLISH_DATE);
    boolean permissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);

    if (_log.isDebugEnabled()) {
        _log.debug("Export permissions " + permissions);
    }/*from  ww w . ja v a2  s .  co  m*/

    long companyId = portletDataContext.getCompanyId();

    long defaultUserId = _userLocalService.getDefaultUserId(companyId);

    ServiceContext serviceContext = ServiceContextThreadLocal.popServiceContext();

    if (serviceContext == null) {
        serviceContext = new ServiceContext();
    }

    serviceContext.setCompanyId(companyId);
    serviceContext.setSignedIn(true);

    if (BackgroundTaskThreadLocal.hasBackgroundTask()) {
        BackgroundTask backgroundTask = _backgroundTaskLocalService
                .getBackgroundTask(BackgroundTaskThreadLocal.getBackgroundTaskId());

        serviceContext.setUserId(backgroundTask.getUserId());
    } else {
        serviceContext.setUserId(defaultUserId);
    }

    serviceContext.setAttribute("exporting", Boolean.TRUE);

    long layoutSetBranchId = MapUtil.getLong(parameterMap, "layoutSetBranchId");

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    ServiceContextThreadLocal.pushServiceContext(serviceContext);

    if (ignoreLastPublishDate) {
        portletDataContext.setEndDate(null);
        portletDataContext.setStartDate(null);
    }

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("root");

    portletDataContext.setExportDataRootElement(rootElement);

    Element headerElement = rootElement.addElement("header");

    headerElement.addAttribute("available-locales",
            StringUtil.merge(LanguageUtil.getAvailableLocales(portletDataContext.getScopeGroupId())));

    headerElement.addAttribute("build-number", String.valueOf(ReleaseInfo.getBuildNumber()));

    headerElement.addAttribute("schema-version", ExportImportConstants.EXPORT_IMPORT_SCHEMA_VERSION);

    headerElement.addAttribute("export-date", Time.getRFC822());

    if (portletDataContext.hasDateRange()) {
        headerElement.addAttribute("start-date", String.valueOf(portletDataContext.getStartDate()));
        headerElement.addAttribute("end-date", String.valueOf(portletDataContext.getEndDate()));
    }

    headerElement.addAttribute("company-id", String.valueOf(portletDataContext.getCompanyId()));
    headerElement.addAttribute("company-group-id", String.valueOf(portletDataContext.getCompanyGroupId()));
    headerElement.addAttribute("group-id", String.valueOf(portletDataContext.getGroupId()));
    headerElement.addAttribute("user-personal-site-group-id",
            String.valueOf(portletDataContext.getUserPersonalSiteGroupId()));
    headerElement.addAttribute("private-layout", String.valueOf(portletDataContext.isPrivateLayout()));

    Group group = _groupLocalService.fetchGroup(portletDataContext.getGroupId());

    String type = "layout-set";

    if (group.isLayoutPrototype()) {
        type = "layout-prototype";

        LayoutPrototype layoutPrototype = _layoutPrototypeLocalService.getLayoutPrototype(group.getClassPK());

        headerElement.addAttribute("type-uuid", layoutPrototype.getUuid());
    } else if (group.isLayoutSetPrototype()) {
        type = "layout-set-prototype";

        LayoutSetPrototype layoutSetPrototype = _layoutSetPrototypeLocalService
                .getLayoutSetPrototype(group.getClassPK());

        headerElement.addAttribute("type-uuid", layoutSetPrototype.getUuid());
    }

    headerElement.addAttribute("type", type);
    portletDataContext.setType(type);

    Element missingReferencesElement = rootElement.addElement("missing-references");

    portletDataContext.setMissingReferencesElement(missingReferencesElement);

    rootElement.addElement("site-portlets");
    rootElement.addElement("site-services");

    // Export the group

    LayoutSet layoutSet = _layoutSetLocalService.getLayoutSet(portletDataContext.getGroupId(),
            portletDataContext.isPrivateLayout());

    String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid();

    boolean layoutSetPrototypeSettings = MapUtil.getBoolean(portletDataContext.getParameterMap(),
            PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_SETTINGS);

    if (!group.isStaged() && Validator.isNotNull(layoutSetPrototypeUuid) && layoutSetPrototypeSettings) {

        LayoutSetPrototype layoutSetPrototype = _layoutSetPrototypeLocalService
                .getLayoutSetPrototypeByUuidAndCompanyId(layoutSetPrototypeUuid, companyId);

        headerElement.addAttribute("layout-set-prototype-uuid", layoutSetPrototypeUuid);

        headerElement.addAttribute("layout-set-prototype-name",
                layoutSetPrototype.getName(LocaleUtil.getDefault()));
    }

    StagedGroup stagedGroup = ModelAdapterUtil.adapt(group, Group.class, StagedGroup.class);

    StagedModelDataHandlerUtil.exportStagedModel(portletDataContext, stagedGroup);

    // Export other models

    _portletExportController.exportAssetLinks(portletDataContext);
    _portletExportController.exportExpandoTables(portletDataContext);
    _portletExportController.exportLocks(portletDataContext);

    portletDataContext.addDeletionSystemEventStagedModelTypes(new StagedModelType(StagedAssetLink.class));

    _deletionSystemEventExporter.exportDeletionSystemEvents(portletDataContext);

    if (permissions) {
        _permissionExporter.exportPortletDataPermissions(portletDataContext);
    }

    _exportImportHelper.writeManifestSummary(document, portletDataContext.getManifestSummary());

    if (_log.isInfoEnabled()) {
        _log.info("Exporting layouts takes " + stopWatch.getTime() + " ms");
    }

    portletDataContext.addZipEntry("/manifest.xml", document.formattedString());

    ZipWriter zipWriter = portletDataContext.getZipWriter();

    return zipWriter.getFile();
}

From source file:com.liferay.exportimport.controller.LayoutImportController.java

License:Open Source License

protected void doImportFile(PortletDataContext portletDataContext, long userId) throws Exception {

    Map<String, String[]> parameterMap = portletDataContext.getParameterMap();

    Group group = _groupLocalService.getGroup(portletDataContext.getGroupId());

    String layoutsImportMode = MapUtil.getString(parameterMap, PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE,
            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_UUID);
    boolean permissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);

    if (group.isLayoutSetPrototype()) {
        parameterMap.put(PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_LINK_ENABLED,
                new String[] { Boolean.FALSE.toString() });
    }/*from  www .  j a  v a2s.com*/

    if (_log.isDebugEnabled()) {
        _log.debug("Import permissions " + permissions);
    }

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    LayoutCache layoutCache = new LayoutCache();

    long companyId = portletDataContext.getCompanyId();

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (serviceContext == null) {
        serviceContext = new ServiceContext();
    }

    serviceContext.setCompanyId(companyId);
    serviceContext.setSignedIn(false);
    serviceContext.setUserId(userId);

    ServiceContextThreadLocal.pushServiceContext(serviceContext);

    // LAR validation

    validateFile(companyId, portletDataContext.getGroupId(), parameterMap, portletDataContext.getZipReader());

    // Source and target group id

    Map<Long, Long> groupIds = (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(Group.class);

    groupIds.put(portletDataContext.getSourceGroupId(), portletDataContext.getGroupId());

    // Manifest

    ManifestSummary manifestSummary = _exportImportHelper.getManifestSummary(portletDataContext);

    portletDataContext.setManifestSummary(manifestSummary);

    // Layout and layout set prototype

    Element rootElement = portletDataContext.getImportDataRootElement();

    Element headerElement = rootElement.element("header");

    String layoutSetPrototypeUuid = headerElement.attributeValue("layout-set-prototype-uuid");

    String larType = headerElement.attributeValue("type");

    portletDataContext.setType(larType);

    if (group.isLayoutPrototype() && larType.equals("layout-prototype")) {
        parameterMap.put(PortletDataHandlerKeys.DELETE_MISSING_LAYOUTS,
                new String[] { Boolean.FALSE.toString() });

        LayoutPrototype layoutPrototype = _layoutPrototypeLocalService.getLayoutPrototype(group.getClassPK());

        String layoutPrototypeUuid = GetterUtil.getString(headerElement.attributeValue("type-uuid"));

        LayoutPrototype existingLayoutPrototype = null;

        if (Validator.isNotNull(layoutPrototypeUuid)) {
            try {
                existingLayoutPrototype = _layoutPrototypeLocalService
                        .getLayoutPrototypeByUuidAndCompanyId(layoutPrototypeUuid, companyId);
            } catch (NoSuchLayoutPrototypeException nslpe) {

                // LPS-52675

                if (_log.isDebugEnabled()) {
                    _log.debug(nslpe, nslpe);
                }
            }
        }

        if (existingLayoutPrototype == null) {
            List<Layout> layouts = _layoutLocalService
                    .getLayoutsByLayoutPrototypeUuid(layoutPrototype.getUuid());

            layoutPrototype.setUuid(layoutPrototypeUuid);

            _layoutPrototypeLocalService.updateLayoutPrototype(layoutPrototype);

            for (Layout layout : layouts) {
                layout.setLayoutPrototypeUuid(layoutPrototypeUuid);

                _layoutLocalService.updateLayout(layout);
            }
        }
    } else if (group.isLayoutSetPrototype() && larType.equals("layout-set-prototype")) {

        parameterMap.put(PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_SETTINGS,
                new String[] { Boolean.TRUE.toString() });

        LayoutSetPrototype layoutSetPrototype = _layoutSetPrototypeLocalService
                .getLayoutSetPrototype(group.getClassPK());

        String importedLayoutSetPrototypeUuid = GetterUtil.getString(headerElement.attributeValue("type-uuid"));

        LayoutSetPrototype existingLayoutSetPrototype = null;

        if (Validator.isNotNull(importedLayoutSetPrototypeUuid)) {
            try {
                existingLayoutSetPrototype = _layoutSetPrototypeLocalService
                        .getLayoutSetPrototypeByUuidAndCompanyId(importedLayoutSetPrototypeUuid, companyId);
            } catch (NoSuchLayoutSetPrototypeException nslspe) {

                // LPS-52675

                if (_log.isDebugEnabled()) {
                    _log.debug(nslspe, nslspe);
                }
            }
        }

        if (existingLayoutSetPrototype == null) {
            List<LayoutSet> layoutSets = _layoutSetLocalService
                    .getLayoutSetsByLayoutSetPrototypeUuid(layoutSetPrototype.getUuid());

            layoutSetPrototype.setUuid(importedLayoutSetPrototypeUuid);

            _layoutSetPrototypeLocalService.updateLayoutSetPrototype(layoutSetPrototype);

            for (LayoutSet curLayoutSet : layoutSets) {
                curLayoutSet.setLayoutSetPrototypeUuid(importedLayoutSetPrototypeUuid);

                _layoutSetLocalService.updateLayoutSet(curLayoutSet);
            }
        }
    } else if (larType.equals("layout-set-prototype")) {
        parameterMap.put(PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_SETTINGS,
                new String[] { Boolean.TRUE.toString() });

        layoutSetPrototypeUuid = GetterUtil.getString(headerElement.attributeValue("type-uuid"));
    }

    if (Validator.isNotNull(layoutSetPrototypeUuid)) {
        portletDataContext.setLayoutSetPrototypeUuid(layoutSetPrototypeUuid);
    }

    List<Element> portletElements = fetchPortletElements(rootElement);

    if (permissions) {
        for (Element portletElement : portletElements) {
            String portletPath = portletElement.attributeValue("path");

            Document portletDocument = SAXReaderUtil.read(portletDataContext.getZipEntryAsString(portletPath));

            _permissionImporter.checkRoles(layoutCache, companyId, portletDataContext.getGroupId(), userId,
                    portletDocument.getRootElement());
        }

        _permissionImporter.readPortletDataPermissions(portletDataContext);
    }

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

        _portletImportController.readExpandoTables(portletDataContext);
    }

    _portletImportController.readLocks(portletDataContext);

    // Import the group

    Element groupsElement = portletDataContext.getImportDataGroupElement(StagedGroup.class);

    for (Element groupElement : groupsElement.elements()) {
        StagedModelDataHandlerUtil.importStagedModel(portletDataContext, groupElement);
    }

    // Asset links

    _portletImportController.importAssetLinks(portletDataContext);

    // Site

    _groupLocalService.updateSite(portletDataContext.getGroupId(), true);

    if (_log.isInfoEnabled()) {
        _log.info("Importing layouts takes " + stopWatch.getTime() + " ms");
    }

    ZipReader zipReader = portletDataContext.getZipReader();

    zipReader.close();
}

From source file:com.liferay.exportimport.controller.PortletExportController.java

License:Open Source License

protected File doExport(PortletDataContext portletDataContext) throws Exception {

    boolean exportPermissions = MapUtil.getBoolean(portletDataContext.getParameterMap(),
            PortletDataHandlerKeys.PERMISSIONS);

    if (_log.isDebugEnabled()) {
        _log.debug("Export permissions " + exportPermissions);
    }//from  www  . j av  a2 s  . com

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    Layout layout = _layoutLocalService.getLayout(portletDataContext.getPlid());

    if (!layout.isTypeControlPanel() && !layout.isTypePanel() && !layout.isTypePortlet()) {

        StringBundler sb = new StringBundler(4);

        sb.append("Unable to export layout ");
        sb.append(layout.getPlid());
        sb.append(" because it has an invalid type: ");
        sb.append(layout.getType());

        throw new LayoutImportException(sb.toString());
    }

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (serviceContext == null) {
        serviceContext = new ServiceContext();

        serviceContext.setCompanyId(layout.getCompanyId());
        serviceContext.setSignedIn(false);

        long defaultUserId = _userLocalService.getDefaultUserId(layout.getCompanyId());

        serviceContext.setUserId(defaultUserId);

        ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

    long layoutSetBranchId = MapUtil.getLong(portletDataContext.getParameterMap(), "layoutSetBranchId");

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    long scopeGroupId = portletDataContext.getGroupId();

    javax.portlet.PortletPreferences jxPortletPreferences = PortletPreferencesFactoryUtil
            .getLayoutPortletSetup(layout, portletDataContext.getPortletId());

    String scopeType = GetterUtil.getString(jxPortletPreferences.getValue("lfrScopeType", null));
    String scopeLayoutUuid = GetterUtil.getString(jxPortletPreferences.getValue("lfrScopeLayoutUuid", null));

    if (Validator.isNotNull(scopeType)) {
        Group scopeGroup = null;

        if (scopeType.equals("company")) {
            scopeGroup = _groupLocalService.getCompanyGroup(layout.getCompanyId());
        } else if (Validator.isNotNull(scopeLayoutUuid)) {
            scopeGroup = layout.getScopeGroup();
        }

        if (scopeGroup != null) {
            scopeGroupId = scopeGroup.getGroupId();
        }
    }

    portletDataContext.setScopeType(scopeType);
    portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("root");

    portletDataContext.setExportDataRootElement(rootElement);

    Element headerElement = rootElement.addElement("header");

    headerElement.addAttribute("available-locales", StringUtil.merge(
            LanguageUtil.getAvailableLocales(_portal.getSiteGroupId(portletDataContext.getScopeGroupId()))));
    headerElement.addAttribute("build-number", String.valueOf(ReleaseInfo.getBuildNumber()));
    headerElement.addAttribute("export-date", Time.getRFC822());

    if (portletDataContext.hasDateRange()) {
        headerElement.addAttribute("start-date", String.valueOf(portletDataContext.getStartDate()));
        headerElement.addAttribute("end-date", String.valueOf(portletDataContext.getEndDate()));
    }

    headerElement.addAttribute("type", portletDataContext.getType());
    headerElement.addAttribute("company-id", String.valueOf(portletDataContext.getCompanyId()));
    headerElement.addAttribute("company-group-id", String.valueOf(portletDataContext.getCompanyGroupId()));
    headerElement.addAttribute("group-id", String.valueOf(scopeGroupId));
    headerElement.addAttribute("user-personal-site-group-id",
            String.valueOf(portletDataContext.getUserPersonalSiteGroupId()));
    headerElement.addAttribute("private-layout", String.valueOf(layout.isPrivateLayout()));
    headerElement.addAttribute("root-portlet-id", portletDataContext.getRootPortletId());
    headerElement.addAttribute("schema-version", ExportImportConstants.EXPORT_IMPORT_SCHEMA_VERSION);

    Element missingReferencesElement = rootElement.addElement("missing-references");

    portletDataContext.setMissingReferencesElement(missingReferencesElement);

    Map<String, Boolean> exportPortletControlsMap = _exportImportHelper.getExportPortletControlsMap(
            layout.getCompanyId(), portletDataContext.getPortletId(), portletDataContext.getParameterMap());

    exportPortlet(portletDataContext, layout.getPlid(), rootElement, exportPermissions,
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_USER_PREFERENCES));
    exportService(portletDataContext, rootElement,
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP));

    exportAssetLinks(portletDataContext);
    exportExpandoTables(portletDataContext);
    exportLocks(portletDataContext);

    portletDataContext.addDeletionSystemEventStagedModelTypes(new StagedModelType(StagedAssetLink.class));

    _deletionSystemEventExporter.exportDeletionSystemEvents(portletDataContext);

    if (exportPermissions) {
        _permissionExporter.exportPortletDataPermissions(portletDataContext);
    }

    _exportImportHelper.writeManifestSummary(document, portletDataContext.getManifestSummary());

    if (_log.isInfoEnabled()) {
        _log.info("Exporting portlet took " + stopWatch.getTime() + " ms");
    }

    try {
        portletDataContext.addZipEntry("/manifest.xml", document.formattedString());
    } catch (IOException ioe) {
        throw new SystemException("Unable to create the export LAR manifest file for portlet "
                + portletDataContext.getPortletId(), ioe);
    }

    ZipWriter zipWriter = portletDataContext.getZipWriter();

    return zipWriter.getFile();
}

From source file:com.liferay.exportimport.controller.PortletImportController.java

License:Open Source License

protected void doImportPortletInfo(PortletDataContext portletDataContext, long userId) throws Exception {

    Map<String, String[]> parameterMap = portletDataContext.getParameterMap();

    boolean importPermissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();//from   www .  j  a  va  2  s  .  c  o m

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (serviceContext == null) {
        serviceContext = new ServiceContext();

        serviceContext.setCompanyId(portletDataContext.getCompanyId());
        serviceContext.setSignedIn(false);
        serviceContext.setUserId(userId);

        ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

    // LAR validation

    validateFile(portletDataContext.getCompanyId(), portletDataContext.getGroupId(),
            portletDataContext.getPortletId(), portletDataContext.getZipReader());

    // Source and target group id

    Map<Long, Long> groupIds = (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(Group.class);

    groupIds.put(portletDataContext.getSourceGroupId(), portletDataContext.getGroupId());

    // Manifest

    ManifestSummary manifestSummary = _exportImportHelper.getManifestSummary(portletDataContext);

    if (BackgroundTaskThreadLocal.hasBackgroundTask()) {
        _portletDataHandlerStatusMessageSender.sendStatusMessage("portlet", portletDataContext.getPortletId(),
                manifestSummary);
    }

    portletDataContext.setManifestSummary(manifestSummary);

    // Read expando tables, locks and permissions to make them
    // available to the data handlers through the portlet data context

    Element rootElement = portletDataContext.getImportDataRootElement();

    Element portletElement = null;

    try {
        portletElement = rootElement.element("portlet");

        Document portletDocument = SAXReaderUtil
                .read(portletDataContext.getZipEntryAsString(portletElement.attributeValue("path")));

        portletElement = portletDocument.getRootElement();
    } catch (DocumentException de) {
        throw new SystemException("Unable to parse XML document for portlet "
                + portletDataContext.getPortletId() + " during import", de);
    }

    LayoutCache layoutCache = new LayoutCache();

    if (importPermissions) {
        _permissionImporter.checkRoles(layoutCache, portletDataContext.getCompanyId(),
                portletDataContext.getGroupId(), userId, portletElement);

        _permissionImporter.readPortletDataPermissions(portletDataContext);
    }

    String layoutsImportMode = MapUtil.getString(parameterMap, PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE);

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

        readExpandoTables(portletDataContext);
    }

    readLocks(portletDataContext);

    Element portletDataElement = portletElement.element("portlet-data");

    Map<String, Boolean> importPortletControlsMap = _exportImportHelper.getImportPortletControlsMap(
            portletDataContext.getCompanyId(), portletDataContext.getPortletId(), parameterMap,
            portletDataElement, manifestSummary);

    Layout layout = _layoutLocalService.getLayout(portletDataContext.getPlid());

    try {

        // Portlet preferences

        importPortletPreferences(portletDataContext, layout.getCompanyId(), portletDataContext.getGroupId(),
                layout, portletElement, true,
                importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS),
                importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA),
                importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP),
                importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_USER_PREFERENCES));

        // Portlet data

        if (importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA)) {

            if (_log.isDebugEnabled()) {
                _log.debug("Importing portlet data");
            }

            importPortletData(portletDataContext, portletDataElement);
        }
    } finally {
        resetPortletScope(portletDataContext, portletDataContext.getGroupId());
    }

    // Portlet permissions

    if (importPermissions) {
        if (_log.isDebugEnabled()) {
            _log.debug("Importing portlet permissions");
        }

        _permissionImporter.importPortletPermissions(layoutCache, portletDataContext.getCompanyId(),
                portletDataContext.getGroupId(), userId, layout, portletElement,
                portletDataContext.getPortletId());

        if (userId > 0) {
            Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);

            User user = _userLocalService.fetchUser(userId);

            indexer.reindex(user);
        }
    }

    // Asset links

    if (_log.isDebugEnabled()) {
        _log.debug("Importing asset links");
    }

    importAssetLinks(portletDataContext);

    // Deletion system events

    _deletionSystemEventImporter.importDeletionSystemEvents(portletDataContext);

    if (_log.isInfoEnabled()) {
        _log.info("Importing portlet takes " + stopWatch.getTime() + " ms");
    }

    // Service portlet preferences

    boolean importPortletSetup = importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP);

    if (importPortletSetup) {
        try {
            List<Element> serviceElements = rootElement.elements("service");

            for (Element serviceElement : serviceElements) {
                Document serviceDocument = SAXReaderUtil
                        .read(portletDataContext.getZipEntryAsString(serviceElement.attributeValue("path")));

                importServicePortletPreferences(portletDataContext, serviceDocument.getRootElement());
            }
        } catch (DocumentException de) {
            throw new SystemException("Unable to parse XML service information for portlet "
                    + portletDataContext.getPortletId() + " during import", de);
        } catch (PortalException pe) {
            throw new PortletDataException(
                    "Unable to import service preferences for portlet " + portletDataContext.getPortletId(),
                    pe);
        }
    }

    ZipReader zipReader = portletDataContext.getZipReader();

    zipReader.close();
}

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

License:Open Source License

protected void initThreadLocals(long groupId, boolean privateLayout) throws PortalException {

    ServiceContext serviceContext = ServiceContextThreadLocal.popServiceContext();

    if (serviceContext == null) {
        serviceContext = new ServiceContext();
    }/*from w ww.j  a  v a  2s  .  c  om*/

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

    serviceContext.setCompanyId(layoutSet.getCompanyId());

    serviceContext.setSignedIn(false);

    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(layoutSet.getCompanyId());

    serviceContext.setUserId(defaultUserId);

    ServiceContextThreadLocal.pushServiceContext(serviceContext);
}

From source file:com.liferay.exportimport.messaging.BasePublisherMessageListener.java

License:Open Source License

protected void initThreadLocals(long userId, Map<String, String[]> parameterMap) throws PortalException {

    User user = UserLocalServiceUtil.getUserById(userId);

    CompanyThreadLocal.setCompanyId(user.getCompanyId());

    PrincipalThreadLocal.setName(userId);

    PermissionChecker permissionChecker = null;

    try {/*from ww  w  . ja v a 2 s  . com*/
        permissionChecker = PermissionCheckerFactoryUtil.create(user);
    } catch (Exception e) {
        throw new SystemException("Unable to initialize thread locals because an error occured "
                + "when creating a permission checker for user " + userId, e);
    }

    PermissionThreadLocal.setPermissionChecker(permissionChecker);

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setCompanyId(user.getCompanyId());
    serviceContext.setPathMain(PortalUtil.getPathMain());
    serviceContext.setSignedIn(!user.isDefaultUser());
    serviceContext.setUserId(user.getUserId());

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

    for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
        String param = entry.getKey();
        String[] values = entry.getValue();

        if (ArrayUtil.isNotEmpty(values)) {
            if (values.length == 1) {
                attributes.put(param, values[0]);
            } else {
                attributes.put(param, values);
            }
        }
    }

    serviceContext.setAttributes(attributes);

    ServiceContextThreadLocal.pushServiceContext(serviceContext);
}

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

License:Open Source License

protected void addLayout(boolean privateLayout, long parentLayoutId, JSONObject layoutJSONObject)
        throws Exception {

    if (targetClassName.equals(LayoutSetPrototype.class.getName())) {
        privateLayout = true;// w  w  w  . j  a va  2s.  c  o m
    }

    Map<Locale, String> nameMap = getMap(layoutJSONObject, "name");
    Map<Locale, String> titleMap = getMap(layoutJSONObject, "title");

    String type = layoutJSONObject.getString("type");

    if (Validator.isNull(type)) {
        type = LayoutConstants.TYPE_PORTLET;
    }

    String typeSettings = layoutJSONObject.getString("typeSettings");

    boolean hidden = layoutJSONObject.getBoolean("hidden");

    String themeId = layoutJSONObject.getString("themeId");

    String layoutCss = layoutJSONObject.getString("layoutCss");

    String colorSchemeId = layoutJSONObject.getString("colorSchemeId");

    Map<Locale, String> friendlyURLMap = new HashMap<>();

    String friendlyURL = layoutJSONObject.getString("friendlyURL");

    if (Validator.isNotNull(friendlyURL) && !friendlyURL.startsWith(StringPool.SLASH)) {

        friendlyURL = StringPool.SLASH + friendlyURL;
    }

    friendlyURLMap.put(LocaleUtil.getDefault(), friendlyURL);

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setCompanyId(companyId);
    serviceContext.setScopeGroupId(groupId);
    serviceContext.setUserId(userId);

    ServiceContextThreadLocal.pushServiceContext(serviceContext);

    try {
        String layoutPrototypeName = layoutJSONObject.getString("layoutPrototypeName");

        String layoutPrototypeUuid = null;

        if (Validator.isNotNull(layoutPrototypeName)) {
            LayoutPrototype layoutPrototype = getLayoutPrototype(companyId, layoutPrototypeName);

            layoutPrototypeUuid = layoutPrototype.getUuid();
        } else {
            layoutPrototypeUuid = layoutJSONObject.getString("layoutPrototypeUuid");
        }

        if (Validator.isNotNull(layoutPrototypeUuid)) {
            boolean layoutPrototypeLinkEnabled = GetterUtil
                    .getBoolean(layoutJSONObject.getString("layoutPrototypeLinkEnabled"));

            serviceContext.setAttribute("layoutPrototypeLinkEnabled", layoutPrototypeLinkEnabled);

            serviceContext.setAttribute("layoutPrototypeUuid", layoutPrototypeUuid);
        }

        Layout layout = layoutLocalService.fetchLayoutByFriendlyURL(groupId, privateLayout, friendlyURL);

        if (layout != null) {
            if (!developerModeEnabled) {
                if (_log.isInfoEnabled()) {
                    _log.info("Layout with friendly URL " + friendlyURL + " already exists");
                }

                return;
            }

            if (!updateModeEnabled) {
                layoutLocalService.deleteLayout(layout);
            }
        }

        if (!updateModeEnabled || (layout == null)) {
            layout = layoutLocalService.addLayout(userId, groupId, privateLayout, parentLayoutId, nameMap,
                    titleMap, null, null, null, type, typeSettings, hidden, friendlyURLMap, serviceContext);
        } else {
            resetLayoutColumns(layout);

            layout = layoutLocalService.updateLayout(groupId, privateLayout, layout.getLayoutId(),
                    parentLayoutId, nameMap, titleMap, layout.getDescriptionMap(), layout.getKeywordsMap(),
                    layout.getRobotsMap(), type, hidden, friendlyURLMap, layout.getIconImage(), null,
                    serviceContext);
        }

        if (Validator.isNotNull(themeId) || Validator.isNotNull(colorSchemeId)) {

            // If the theme ID or the color scheme ID are not null, then the
            // layout has a custom look and feel and should be updated in
            // the database

            layoutLocalService.updateLookAndFeel(groupId, privateLayout, layout.getLayoutId(), themeId,
                    colorSchemeId, layoutCss);
        }

        LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

        String layoutTemplateId = layoutJSONObject.getString("layoutTemplateId", _defaultLayoutTemplateId);

        if (Validator.isNotNull(layoutTemplateId)) {
            layoutTypePortlet.setLayoutTemplateId(userId, layoutTemplateId, false);
        }

        JSONArray columnsJSONArray = layoutJSONObject.getJSONArray("columns");

        addLayoutColumns(layout, LayoutTypePortletConstants.COLUMN_PREFIX, columnsJSONArray);

        layoutLocalService.updateLayout(groupId, layout.isPrivateLayout(), layout.getLayoutId(),
                layout.getTypeSettings());

        JSONArray layoutsJSONArray = layoutJSONObject.getJSONArray("layouts");

        addLayouts(privateLayout, layout.getLayoutId(), layoutsJSONArray);
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn("Unable to import layout " + layoutJSONObject, e);
        }

        throw e;
    } finally {
        ServiceContextThreadLocal.popServiceContext();
    }
}

From source file:com.liferay.exportimport.test.BasePrototypePropagationTestCase.java

License:Open Source License

@Before
public void setUp() throws Exception {
    ServiceContextThreadLocal.pushServiceContext(ServiceContextTestUtil.getServiceContext());

    ServiceTestUtil.setUser(TestPropsValues.getUser());

    // Group//from www .j  av a 2  s.  co  m

    group = GroupTestUtil.addGroup();

    // Global scope article

    Company company = CompanyLocalServiceUtil.fetchCompany(group.getCompanyId());

    globalGroupId = company.getGroupId();

    globalJournalArticle = JournalTestUtil.addArticle(globalGroupId, "Global Article", "Global Content");

    // Layout prototype

    layoutPrototype = LayoutTestUtil.addLayoutPrototype(RandomTestUtil.randomString());

    layoutPrototypeLayout = layoutPrototype.getLayout();

    LayoutTestUtil.updateLayoutTemplateId(layoutPrototypeLayout, initialLayoutTemplateId);

    doSetUp();
}