protected PortletDataContext getPortletDataContext( ExportImportConfiguration exportImportConfiguration, File file) throws PortalException { Map<String, Serializable> settingsMap = exportImportConfiguration.getSettingsMap(); Map<String, String[]> parameterMap = (Map<String, String[]>) settingsMap.get("parameterMap"); String portletId = MapUtil.getString(settingsMap, "portletId"); long targetPlid = MapUtil.getLong(settingsMap, "targetPlid"); long targetGroupId = MapUtil.getLong(settingsMap, "targetGroupId"); long userId = MapUtil.getLong(settingsMap, "userId"); Layout layout = _layoutLocalService.getLayout(targetPlid); String userIdStrategyString = MapUtil.getString(parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY); UserIdStrategy userIdStrategy = ExportImportHelperUtil.getUserIdStrategy(userId, userIdStrategyString); ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file); PortletDataContext portletDataContext = PortletDataContextFactoryUtil.createImportPortletDataContext( layout.getCompanyId(), targetGroupId, parameterMap, userIdStrategy, zipReader); portletDataContext.setOldPlid(targetPlid); portletDataContext.setPlid(targetPlid); portletDataContext.setPortletId(portletId); portletDataContext.setPrivateLayout(layout.isPrivateLayout()); return portletDataContext; }
protected String getKey(Map<String, Object> env) { StringBundler sb = new StringBundler(5); sb.append(MapUtil.getString(env, Context.PROVIDER_URL)); sb.append(StringPool.POUND); sb.append(MapUtil.getString(env, Context.SECURITY_PRINCIPAL)); sb.append(StringPool.POUND); sb.append(MapUtil.getString(env, Context.SECURITY_CREDENTIALS)); return sb.toString(); }
protected PortletDataContext getPortletDataContext( ExportImportConfiguration exportImportConfiguration) throws PortalException { Map<String, Serializable> settingsMap = exportImportConfiguration.getSettingsMap(); long sourcePlid = MapUtil.getLong(settingsMap, "sourcePlid"); long sourceGroupId = MapUtil.getLong(settingsMap, "sourceGroupId"); String portletId = MapUtil.getString(settingsMap, "portletId"); Map<String, String[]> parameterMap = (Map<String, String[]>) settingsMap.get("parameterMap"); DateRange dateRange = ExportImportDateUtil.getDateRange(exportImportConfiguration); Layout layout = _layoutLocalService.getLayout(sourcePlid); ZipWriter zipWriter = ExportImportHelperUtil.getPortletZipWriter(portletId); PortletDataContext portletDataContext = PortletDataContextFactoryUtil.createExportPortletDataContext( layout.getCompanyId(), sourceGroupId, parameterMap, dateRange.getStartDate(), dateRange.getEndDate(), zipWriter); portletDataContext.setOldPlid(sourcePlid); portletDataContext.setPlid(sourcePlid); portletDataContext.setPortletId(portletId); return portletDataContext; }
protected static String getAddTemplateActionId( ServiceWrapper<DDMTemplatePermissionSupport> templatePermissionSupportServiceWrapper) { Map<String, Object> properties = templatePermissionSupportServiceWrapper.getProperties(); return MapUtil.getString(properties, "add.template.action.id", DDMActionKeys.ADD_TEMPLATE); }
@Override public PortletDataContext createImportPortletDataContext( long companyId, long groupId, Map<String, String[]> parameterMap, UserIdStrategy userIdStrategy, ZipReader zipReader) { PortletDataContext portletDataContext = createPortletDataContext(companyId, groupId); String dataStrategy = MapUtil.getString( parameterMap, PortletDataHandlerKeys.DATA_STRATEGY, PortletDataHandlerKeys.DATA_STRATEGY_MIRROR); portletDataContext.setDataStrategy(dataStrategy); portletDataContext.setNewLayouts(new ArrayList<Layout>()); portletDataContext.setParameterMap(parameterMap); portletDataContext.setUserIdStrategy(userIdStrategy); portletDataContext.setZipReader(zipReader); return portletDataContext; }
@Reference(target = "(&(search.engine.id=SYSTEM_ENGINE)(search.engine.impl=Solr))") protected void setSearchEngine(SearchEngine searchEngine, Map<String, Object> properties) { String searchEngineId = MapUtil.getString(properties, "search.engine.id"); _searchEngines.put(searchEngineId, searchEngine); }
protected void unsetSearchEngine(SearchEngine searchEngine, Map<String, Object> properties) { String searchEngineId = MapUtil.getString(properties, "search.engine.id"); if (Validator.isNull(searchEngineId)) { return; } _searchEngines.remove(searchEngineId); }
@Override public void importDataDeletions(ExportImportConfiguration exportImportConfiguration, File file) throws Exception { ZipReader zipReader = null; try { // LAR validation ExportImportThreadLocal.setPortletDataDeletionImportInProcess(true); Map<String, Serializable> settingsMap = exportImportConfiguration.getSettingsMap(); Map<String, String[]> parameterMap = (Map<String, String[]>) settingsMap.get("parameterMap"); String portletId = MapUtil.getString(settingsMap, "portletId"); long targetPlid = MapUtil.getLong(settingsMap, "targetPlid"); long targetGroupId = MapUtil.getLong(settingsMap, "targetGroupId"); Layout layout = _layoutLocalService.getLayout(targetPlid); zipReader = ZipReaderFactoryUtil.getZipReader(file); validateFile(layout.getCompanyId(), targetGroupId, portletId, zipReader); PortletDataContext portletDataContext = getPortletDataContext(exportImportConfiguration, file); boolean deletePortletData = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.DELETE_PORTLET_DATA); // Portlet data deletion if (deletePortletData) { if (_log.isDebugEnabled()) { _log.debug("Deleting portlet data"); } deletePortletData(portletDataContext); } // Deletion system events populateDeletionStagedModelTypes(portletDataContext); _deletionSystemEventImporter.importDeletionSystemEvents(portletDataContext); } finally { ExportImportThreadLocal.setPortletDataDeletionImportInProcess(false); if (zipReader != null) { zipReader.close(); } } }
@Override @Transactional(enabled = false) public Map<String, Object> updateFileEntries(File zipFile) throws PortalException { Map<String, Object> responseMap = new HashMap<>(); ZipReader zipReader = null; try { zipReader = ZipReaderFactoryUtil.getZipReader(zipFile); String manifest = zipReader.getEntryAsString("/manifest.json"); JSONArray jsonArray = JSONFactoryUtil.createJSONArray(manifest); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); JSONWebServiceActionParametersMap jsonWebServiceActionParametersMap = JSONFactoryUtil.looseDeserialize( jsonObject.toString(), JSONWebServiceActionParametersMap.class); String zipFileId = MapUtil.getString(jsonWebServiceActionParametersMap, "zipFileId"); try { responseMap.put( zipFileId, updateFileEntries(zipReader, zipFileId, jsonWebServiceActionParametersMap)); } catch (Exception e) { String message = e.getMessage(); if (!message.startsWith(StringPool.QUOTE) && !message.endsWith(StringPool.QUOTE)) { message = StringUtil.quote(message, StringPool.QUOTE); } String json = "{\"exception\": " + message + "}"; responseMap.put(zipFileId, json); } } } finally { if (zipReader != null) { zipReader.close(); } } return responseMap; }
protected void importJournalArticle( PortletDataContext portletDataContext, Layout layout, Element layoutElement) throws Exception { UnicodeProperties typeSettingsProperties = layout.getTypeSettingsProperties(); String articleId = typeSettingsProperties.getProperty("article-id", StringPool.BLANK); if (Validator.isNull(articleId)) { return; } JournalPortletDataHandlerImpl.importReferencedData(portletDataContext, layoutElement); Element structureElement = layoutElement.element("structure"); if (structureElement != null) { JournalPortletDataHandlerImpl.importStructure(portletDataContext, structureElement); } Element templateElement = layoutElement.element("template"); if (templateElement != null) { JournalPortletDataHandlerImpl.importTemplate(portletDataContext, templateElement); } Element articleElement = layoutElement.element("article"); if (articleElement != null) { JournalPortletDataHandlerImpl.importArticle(portletDataContext, articleElement); } Map<String, String> articleIds = (Map<String, String>) portletDataContext.getNewPrimaryKeysMap(JournalArticle.class + ".articleId"); articleId = MapUtil.getString(articleIds, articleId, articleId); typeSettingsProperties.setProperty("article-id", articleId); JournalContentSearchLocalServiceUtil.updateContentSearch( portletDataContext.getScopeGroupId(), layout.isPrivateLayout(), layout.getLayoutId(), StringPool.BLANK, articleId, true); }
@Override public MissingReferences call() throws PortalException { Map<String, Serializable> settingsMap = _exportImportConfiguration.getSettingsMap(); long userId = MapUtil.getLong(settingsMap, "userId"); long targetPlid = MapUtil.getLong(settingsMap, "targetPlid"); long targetGroupId = MapUtil.getLong(settingsMap, "targetGroupId"); String portletId = MapUtil.getString(settingsMap, "portletId"); Map<String, String[]> parameterMap = (Map<String, String[]>) settingsMap.get("parameterMap"); long sourcePlid = MapUtil.getLong(settingsMap, "sourcePlid"); long sourceGroupId = MapUtil.getLong(settingsMap, "sourceGroupId"); DateRange dateRange = ExportImportDateUtil.getDateRange( _exportImportConfiguration, ExportImportDateUtil.RANGE_FROM_LAST_PUBLISH_DATE); File larFile = null; MissingReferences missingReferences = null; try { larFile = LayoutLocalServiceUtil.exportPortletInfoAsFile( sourcePlid, sourceGroupId, portletId, parameterMap, dateRange.getStartDate(), dateRange.getEndDate()); markBackgroundTask(_backgroundTaskId, "exported"); missingReferences = LayoutLocalServiceUtil.validateImportPortletInfo( userId, targetPlid, targetGroupId, portletId, parameterMap, larFile); markBackgroundTask(_backgroundTaskId, "validated"); LayoutLocalServiceUtil.importPortletInfo( userId, targetPlid, targetGroupId, portletId, parameterMap, larFile); } finally { larFile.delete(); } return missingReferences; }
@Override public MissingReferences validateFile( ExportImportConfiguration exportImportConfiguration, File file) throws Exception { ZipReader zipReader = null; try { ExportImportThreadLocal.setPortletValidationInProcess(true); Map<String, Serializable> settingsMap = exportImportConfiguration.getSettingsMap(); String portletId = MapUtil.getString(settingsMap, "portletId"); long targetGroupId = MapUtil.getLong(settingsMap, "targetGroupId"); long targetPlid = MapUtil.getLong(settingsMap, "targetPlid"); Layout layout = _layoutLocalService.getLayout(targetPlid); zipReader = ZipReaderFactoryUtil.getZipReader(file); validateFile(layout.getCompanyId(), targetGroupId, portletId, zipReader); PortletDataContext portletDataContext = getPortletDataContext(exportImportConfiguration, file); MissingReferences missingReferences = ExportImportHelperUtil.validateMissingReferences(portletDataContext); Map<String, MissingReference> dependencyMissingReferences = missingReferences.getDependencyMissingReferences(); if (!dependencyMissingReferences.isEmpty()) { throw new MissingReferenceException(missingReferences); } return missingReferences; } finally { ExportImportThreadLocal.setPortletValidationInProcess(false); if (zipReader != null) { zipReader.close(); } } }
protected void moveFrontPage(long userId, WikiNode node, Map<String, String[]> options) { String frontPageTitle = MapUtil.getString(options, WikiImporterKeys.OPTIONS_FRONT_PAGE); if (Validator.isNotNull(frontPageTitle)) { frontPageTitle = normalizeTitle(frontPageTitle); try { if (WikiPageLocalServiceUtil.getPagesCount(node.getNodeId(), frontPageTitle, true) > 0) { ServiceContext serviceContext = new ServiceContext(); serviceContext.setAddGroupPermissions(true); serviceContext.setAddGuestPermissions(true); WikiPageLocalServiceUtil.movePage( userId, node.getNodeId(), frontPageTitle, WikiPageConstants.FRONT_PAGE, false, serviceContext); } } catch (Exception e) { if (_log.isWarnEnabled()) { StringBundler sb = new StringBundler(4); sb.append("Could not move "); sb.append(WikiPageConstants.FRONT_PAGE); sb.append(" to the title provided: "); sb.append(frontPageTitle); _log.warn(sb.toString(), e); } } } }
public PortletDataContextImpl( long companyId, long groupId, Map<String, String[]> parameterMap, Set<String> primaryKeys, UserIdStrategy userIdStrategy, ZipReader zipReader) { _companyId = companyId; _groupId = groupId; _scopeGroupId = groupId; _parameterMap = parameterMap; _primaryKeys = primaryKeys; _dataStrategy = MapUtil.getString( parameterMap, PortletDataHandlerKeys.DATA_STRATEGY, PortletDataHandlerKeys.DATA_STRATEGY_MIRROR); _userIdStrategy = userIdStrategy; _zipReader = zipReader; _zipWriter = null; initXStream(); }
protected SyncDLObject updateFileEntries( ZipReader zipReader, String zipFileId, JSONWebServiceActionParametersMap jsonWebServiceActionParametersMap) throws Exception { ServiceContext serviceContext = new ServiceContext(); List<NameValue<String, Object>> innerParameters = jsonWebServiceActionParametersMap.getInnerParameters("serviceContext"); if (innerParameters != null) { for (NameValue<String, Object> innerParameter : innerParameters) { try { BeanUtil.setProperty(serviceContext, innerParameter.getName(), innerParameter.getValue()); } catch (Exception e) { if (_log.isDebugEnabled()) { _log.debug(e.getMessage(), e); } } } } String urlPath = MapUtil.getString(jsonWebServiceActionParametersMap, "urlPath"); if (urlPath.endsWith("/add-file-entry")) { long repositoryId = MapUtil.getLong(jsonWebServiceActionParametersMap, "repositoryId"); long folderId = MapUtil.getLong(jsonWebServiceActionParametersMap, "folderId"); String sourceFileName = MapUtil.getString(jsonWebServiceActionParametersMap, "sourceFileName"); String mimeType = MapUtil.getString(jsonWebServiceActionParametersMap, "mimeType"); String title = MapUtil.getString(jsonWebServiceActionParametersMap, "title"); String description = MapUtil.getString(jsonWebServiceActionParametersMap, "description"); String changeLog = MapUtil.getString(jsonWebServiceActionParametersMap, "changeLog"); InputStream inputStream = zipReader.getEntryAsInputStream(zipFileId); File tempFile = null; try { tempFile = FileUtil.createTempFile(inputStream); String checksum = MapUtil.getString(jsonWebServiceActionParametersMap, "checksum"); return addFileEntry( repositoryId, folderId, sourceFileName, mimeType, title, description, changeLog, tempFile, checksum, serviceContext); } finally { FileUtil.delete(tempFile); } } else if (urlPath.endsWith("/add-folder")) { long repositoryId = MapUtil.getLong(jsonWebServiceActionParametersMap, "repositoryId"); long parentFolderId = MapUtil.getLong(jsonWebServiceActionParametersMap, "parentFolderId"); String name = MapUtil.getString(jsonWebServiceActionParametersMap, "name"); String description = MapUtil.getString(jsonWebServiceActionParametersMap, "description"); return addFolder(repositoryId, parentFolderId, name, description, serviceContext); } else if (urlPath.endsWith("/move-file-entry")) { long fileEntryId = MapUtil.getLong(jsonWebServiceActionParametersMap, "fileEntryId"); long newFolderId = MapUtil.getLong(jsonWebServiceActionParametersMap, "newFolderId"); return moveFileEntry(fileEntryId, newFolderId, serviceContext); } else if (urlPath.endsWith("/move-file-entry-to-trash")) { long fileEntryId = MapUtil.getLong(jsonWebServiceActionParametersMap, "fileEntryId"); return moveFileEntryToTrash(fileEntryId); } else if (urlPath.endsWith("/move-folder")) { long folderId = MapUtil.getLong(jsonWebServiceActionParametersMap, "folderId"); long parentFolderId = MapUtil.getLong(jsonWebServiceActionParametersMap, "parentFolderId"); return moveFolder(folderId, parentFolderId, serviceContext); } else if (urlPath.endsWith("/move-folder-to-trash")) { long folderId = MapUtil.getLong(jsonWebServiceActionParametersMap, "folderId"); return moveFolderToTrash(folderId); } else if (urlPath.endsWith("/patch-file-entry")) { long fileEntryId = MapUtil.getLong(jsonWebServiceActionParametersMap, "fileEntryId"); long sourceVersionId = MapUtil.getLong(jsonWebServiceActionParametersMap, "sourceVersionId"); String sourceFileName = MapUtil.getString(jsonWebServiceActionParametersMap, "sourceFileName"); String mimeType = MapUtil.getString(jsonWebServiceActionParametersMap, "mimeType"); String title = MapUtil.getString(jsonWebServiceActionParametersMap, "title"); String description = MapUtil.getString(jsonWebServiceActionParametersMap, "description"); String changeLog = MapUtil.getString(jsonWebServiceActionParametersMap, "changeLog"); boolean majorVersion = MapUtil.getBoolean(jsonWebServiceActionParametersMap, "majorVersion"); InputStream inputStream = zipReader.getEntryAsInputStream(zipFileId); File tempFile = null; try { tempFile = FileUtil.createTempFile(inputStream); String checksum = MapUtil.getString(jsonWebServiceActionParametersMap, "checksum"); return patchFileEntry( fileEntryId, sourceVersionId, sourceFileName, mimeType, title, description, changeLog, majorVersion, tempFile, checksum, serviceContext); } finally { FileUtil.delete(tempFile); } } else if (urlPath.endsWith("/update-file-entry")) { long fileEntryId = MapUtil.getLong(jsonWebServiceActionParametersMap, "fileEntryId"); String sourceFileName = MapUtil.getString(jsonWebServiceActionParametersMap, "sourceFileName"); String mimeType = MapUtil.getString(jsonWebServiceActionParametersMap, "mimeType"); String title = MapUtil.getString(jsonWebServiceActionParametersMap, "title"); String description = MapUtil.getString(jsonWebServiceActionParametersMap, "description"); String changeLog = MapUtil.getString(jsonWebServiceActionParametersMap, "changeLog"); boolean majorVersion = MapUtil.getBoolean(jsonWebServiceActionParametersMap, "majorVersion"); File tempFile = null; try { InputStream inputStream = zipReader.getEntryAsInputStream(zipFileId); if (inputStream != null) { tempFile = FileUtil.createTempFile(inputStream); } String checksum = MapUtil.getString(jsonWebServiceActionParametersMap, "checksum"); return updateFileEntry( fileEntryId, sourceFileName, mimeType, title, description, changeLog, majorVersion, tempFile, checksum, serviceContext); } finally { FileUtil.delete(tempFile); } } else if (urlPath.endsWith("/update-folder")) { long folderId = MapUtil.getLong(jsonWebServiceActionParametersMap, "folderId"); String name = MapUtil.getString(jsonWebServiceActionParametersMap, "name"); String description = MapUtil.getString(jsonWebServiceActionParametersMap, "description"); return updateFolder(folderId, name, description, serviceContext); } return null; }
@Override protected void doImportStagedModel(PortletDataContext portletDataContext, Layout layout) throws Exception { long groupId = portletDataContext.getGroupId(); long userId = portletDataContext.getUserId(layout.getUserUuid()); Element layoutElement = portletDataContext.getImportDataStagedModelElement(layout); String layoutUuid = GetterUtil.getString(layoutElement.attributeValue("layout-uuid")); long layoutId = GetterUtil.getInteger(layoutElement.attributeValue("layout-id")); long oldLayoutId = layoutId; boolean privateLayout = portletDataContext.isPrivateLayout(); String action = layoutElement.attributeValue(Constants.ACTION); if (action.equals(Constants.DELETE)) { Layout deletingLayout = _layoutLocalService.fetchLayoutByUuidAndGroupId(layoutUuid, groupId, privateLayout); _layoutLocalService.deleteLayout( deletingLayout, false, ServiceContextThreadLocal.getServiceContext()); return; } Map<Long, Layout> layouts = (Map<Long, Layout>) portletDataContext.getNewPrimaryKeysMap(Layout.class + ".layout"); Layout existingLayout = null; 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); friendlyURL = getFriendlyURL(friendlyURL, layoutId); } } 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); friendlyURL = getFriendlyURL(friendlyURL, layoutId); } } 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); friendlyURL = getFriendlyURL(friendlyURL, layoutId); } 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 (layout.isTypePortlet() && Validator.isNotNull(layout.getTypeSettings()) && !portletsMergeMode.equals(PortletDataHandlerKeys.PORTLETS_MERGE_MODE_REPLACE)) { mergePortlets(importedLayout, layout.getTypeSettings(), portletsMergeMode); } else if (layout.isTypeLinkToLayout()) { importLinkedLayout(portletDataContext, layout, importedLayout, layoutElement, layouts); } 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()); } if (existingLayout == null) { int priority = _layoutLocalServiceHelper.getNextPriority( groupId, privateLayout, parentLayoutId, null, -1); importedLayout.setPriority(priority); } importedLayout.setLayoutPrototypeUuid(layout.getLayoutPrototypeUuid()); importedLayout.setLayoutPrototypeLinkEnabled(layout.isLayoutPrototypeLinkEnabled()); ServiceContext serviceContext = portletDataContext.createServiceContext(layout); importedLayout.setExpandoBridgeAttributes(serviceContext); StagingUtil.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); importAssets(portletDataContext, layout, importedLayout); importLayoutFriendlyURLs(portletDataContext, layout, importedLayout); portletDataContext.importClassedModel(layout, importedLayout); }
protected void doImportLayouts( long userId, long groupId, boolean privateLayout, Map<String, String[]> parameterMap, File file) throws Exception { boolean deleteMissingLayouts = MapUtil.getBoolean( parameterMap, PortletDataHandlerKeys.DELETE_MISSING_LAYOUTS, Boolean.TRUE.booleanValue()); boolean deletePortletData = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.DELETE_PORTLET_DATA); boolean importCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES); boolean importPermissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS); boolean importPublicLayoutPermissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PUBLIC_LAYOUT_PERMISSIONS); boolean importUserPermissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.USER_PERMISSIONS); boolean importPortletData = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA); boolean importPortletSetup = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_SETUP); boolean importPortletArchivedSetups = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS); boolean importPortletUserPreferences = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES); boolean importTheme = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME); boolean importThemeSettings = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME_REFERENCE); boolean importLogo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO); boolean importLayoutSetSettings = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS); boolean layoutSetPrototypeLinkEnabled = MapUtil.getBoolean( parameterMap, PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_LINK_ENABLED, true); Group group = GroupLocalServiceUtil.getGroup(groupId); if (group.isLayoutSetPrototype()) { layoutSetPrototypeLinkEnabled = false; } boolean publishToRemote = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PUBLISH_TO_REMOTE); String layoutsImportMode = MapUtil.getString( parameterMap, PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE, PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_UUID); String portletsMergeMode = MapUtil.getString( parameterMap, PortletDataHandlerKeys.PORTLETS_MERGE_MODE, PortletDataHandlerKeys.PORTLETS_MERGE_MODE_REPLACE); String userIdStrategy = MapUtil.getString(parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY); if (_log.isDebugEnabled()) { _log.debug("Delete portlet data " + deletePortletData); _log.debug("Import categories " + importCategories); _log.debug("Import permissions " + importPermissions); _log.debug("Import user permissions " + importUserPermissions); _log.debug("Import portlet data " + importPortletData); _log.debug("Import portlet setup " + importPortletSetup); _log.debug("Import portlet archived setups " + importPortletArchivedSetups); _log.debug("Import portlet user preferences " + importPortletUserPreferences); _log.debug("Import theme " + importTheme); } StopWatch stopWatch = null; if (_log.isInfoEnabled()) { stopWatch = new StopWatch(); stopWatch.start(); } LayoutCache layoutCache = new LayoutCache(); LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout); long companyId = layoutSet.getCompanyId(); User user = UserUtil.findByPrimaryKey(userId); UserIdStrategy strategy = _portletImporter.getUserIdStrategy(user, userIdStrategy); ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file); PortletDataContext portletDataContext = new PortletDataContextImpl( companyId, groupId, parameterMap, new HashSet<String>(), strategy, zipReader); portletDataContext.setPortetDataContextListener( new PortletDataContextListenerImpl(portletDataContext)); portletDataContext.setPrivateLayout(privateLayout); // Zip Element rootElement = null; InputStream themeZip = null; // Manifest String xml = portletDataContext.getZipEntryAsString("/manifest.xml"); if (xml == null) { throw new LARFileException("manifest.xml not found in the LAR"); } try { Document document = SAXReaderUtil.read(xml); rootElement = document.getRootElement(); } catch (Exception e) { throw new LARFileException(e); } // Build compatibility Element headerElement = rootElement.element("header"); int buildNumber = ReleaseInfo.getBuildNumber(); int importBuildNumber = GetterUtil.getInteger(headerElement.attributeValue("build-number")); if (buildNumber != importBuildNumber) { throw new LayoutImportException( "LAR build number " + importBuildNumber + " does not match " + "portal build number " + buildNumber); } // Type compatibility String larType = headerElement.attributeValue("type"); if (!larType.equals("layout-set") && !larType.equals("layout-set-prototype")) { throw new LARTypeException("Invalid type of LAR file (" + larType + ")"); } // Group id long sourceGroupId = GetterUtil.getLong(headerElement.attributeValue("group-id")); portletDataContext.setSourceGroupId(sourceGroupId); // Layout set prototype if (group.isLayoutSetPrototype() && larType.equals("layout-set-prototype")) { LayoutSetPrototype layoutSetPrototype = LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(group.getClassPK()); String layoutSetPrototypeUuid = GetterUtil.getString(headerElement.attributeValue("type-uuid")); LayoutSetPrototype existingLayoutSetPrototype = null; if (Validator.isNotNull(layoutSetPrototypeUuid)) { try { existingLayoutSetPrototype = LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuid( layoutSetPrototypeUuid); } catch (NoSuchLayoutSetPrototypeException nslspe) { } } if (existingLayoutSetPrototype == null) { layoutSetPrototype.setUuid(layoutSetPrototypeUuid); LayoutSetPrototypeLocalServiceUtil.updateLayoutSetPrototype(layoutSetPrototype); } } Element layoutsElement = rootElement.element("layouts"); String layoutSetPrototypeUuid = layoutsElement.attributeValue("layout-set-prototype-uuid"); ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext(); if (Validator.isNotNull(layoutSetPrototypeUuid)) { if (layoutSetPrototypeLinkEnabled) { if (publishToRemote) { importLayoutSetPrototype( portletDataContext, user, layoutSetPrototypeUuid, serviceContext); } } layoutSet.setLayoutSetPrototypeUuid(layoutSetPrototypeUuid); layoutSet.setLayoutSetPrototypeLinkEnabled(layoutSetPrototypeLinkEnabled); LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet); } // Look and feel if (importTheme) { themeZip = portletDataContext.getZipEntryAsInputStream("theme.zip"); } // Look and feel String themeId = layoutSet.getThemeId(); String colorSchemeId = layoutSet.getColorSchemeId(); if (importThemeSettings) { Attribute themeIdAttribute = headerElement.attribute("theme-id"); if (themeIdAttribute != null) { themeId = themeIdAttribute.getValue(); } Attribute colorSchemeIdAttribute = headerElement.attribute("color-scheme-id"); if (colorSchemeIdAttribute != null) { colorSchemeId = colorSchemeIdAttribute.getValue(); } } if (importLogo) { String logoPath = headerElement.attributeValue("logo-path"); byte[] iconBytes = portletDataContext.getZipEntryAsByteArray(logoPath); if ((iconBytes != null) && (iconBytes.length > 0)) { File logo = FileUtil.createTempFile(iconBytes); LayoutSetLocalServiceUtil.updateLogo(groupId, privateLayout, true, logo); } else { LayoutSetLocalServiceUtil.updateLogo(groupId, privateLayout, false, (File) null); } } if (importLayoutSetSettings) { String settings = GetterUtil.getString(headerElement.elementText("settings")); LayoutSetLocalServiceUtil.updateSettings(groupId, privateLayout, settings); } String css = GetterUtil.getString(headerElement.elementText("css")); if (themeZip != null) { String importThemeId = importTheme(layoutSet, themeZip); if (importThemeId != null) { themeId = importThemeId; colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId(); } if (_log.isDebugEnabled()) { _log.debug("Importing theme takes " + stopWatch.getTime() + " ms"); } } boolean wapTheme = false; LayoutSetLocalServiceUtil.updateLookAndFeel( groupId, privateLayout, themeId, colorSchemeId, css, wapTheme); // Read asset categories, asset tags, comments, locks, permissions, and // ratings entries to make them available to the data handlers through // the context if (importPermissions) { _permissionImporter.readPortletDataPermissions(portletDataContext); } if (importCategories) { _portletImporter.readAssetCategories(portletDataContext); } _portletImporter.readAssetTags(portletDataContext); _portletImporter.readComments(portletDataContext); _portletImporter.readExpandoTables(portletDataContext); _portletImporter.readLocks(portletDataContext); _portletImporter.readRatingsEntries(portletDataContext); // Layouts List<Layout> previousLayouts = LayoutUtil.findByG_P(groupId, privateLayout); // Remove layouts that were deleted from the layout set prototype if (Validator.isNotNull(layoutSetPrototypeUuid) && layoutSetPrototypeLinkEnabled) { LayoutSetPrototype layoutSetPrototype = LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuid(layoutSetPrototypeUuid); Group layoutSetPrototypeGroup = layoutSetPrototype.getGroup(); for (Layout layout : previousLayouts) { String sourcePrototypeLayoutUuid = layout.getSourcePrototypeLayoutUuid(); if (Validator.isNull(layout.getSourcePrototypeLayoutUuid())) { continue; } Layout sourcePrototypeLayout = LayoutUtil.fetchByUUID_G( sourcePrototypeLayoutUuid, layoutSetPrototypeGroup.getGroupId()); if (sourcePrototypeLayout == null) { LayoutLocalServiceUtil.deleteLayout(layout, false, serviceContext); } } } List<Layout> newLayouts = new ArrayList<Layout>(); Set<Long> newLayoutIds = new HashSet<Long>(); Map<Long, Layout> newLayoutsMap = (Map<Long, Layout>) portletDataContext.getNewPrimaryKeysMap(Layout.class); List<Element> layoutElements = layoutsElement.elements("layout"); if (_log.isDebugEnabled()) { if (layoutElements.size() > 0) { _log.debug("Importing layouts"); } } for (Element layoutElement : layoutElements) { importLayout( portletDataContext, user, layoutCache, previousLayouts, newLayouts, newLayoutsMap, newLayoutIds, portletsMergeMode, themeId, colorSchemeId, layoutsImportMode, privateLayout, importPermissions, importPublicLayoutPermissions, importUserPermissions, importThemeSettings, rootElement, layoutElement); } Element portletsElement = rootElement.element("portlets"); List<Element> portletElements = portletsElement.elements("portlet"); // Delete portlet data if (deletePortletData) { if (_log.isDebugEnabled()) { if (portletElements.size() > 0) { _log.debug("Deleting portlet data"); } } for (Element portletElement : portletElements) { String portletId = portletElement.attributeValue("portlet-id"); long layoutId = GetterUtil.getLong(portletElement.attributeValue("layout-id")); long plid = newLayoutsMap.get(layoutId).getPlid(); portletDataContext.setPlid(plid); _portletImporter.deletePortletData(portletDataContext, portletId, plid); } } // Import portlets if (_log.isDebugEnabled()) { if (portletElements.size() > 0) { _log.debug("Importing portlets"); } } for (Element portletElement : portletElements) { String portletPath = portletElement.attributeValue("path"); String portletId = portletElement.attributeValue("portlet-id"); long layoutId = GetterUtil.getLong(portletElement.attributeValue("layout-id")); long plid = newLayoutsMap.get(layoutId).getPlid(); long oldPlid = GetterUtil.getLong(portletElement.attributeValue("old-plid")); Portlet portlet = PortletLocalServiceUtil.getPortletById(portletDataContext.getCompanyId(), portletId); if (!portlet.isActive() || portlet.isUndeployedPortlet()) { continue; } Layout layout = null; try { layout = LayoutUtil.findByPrimaryKey(plid); } catch (NoSuchLayoutException nsle) { continue; } portletDataContext.setPlid(plid); portletDataContext.setOldPlid(oldPlid); Document portletDocument = SAXReaderUtil.read(portletDataContext.getZipEntryAsString(portletPath)); portletElement = portletDocument.getRootElement(); // The order of the import is important. You must always import // the portlet preferences first, then the portlet data, then // the portlet permissions. The import of the portlet data // assumes that portlet preferences already exist. _portletImporter.setPortletScope(portletDataContext, portletElement); try { // Portlet preferences _portletImporter.importPortletPreferences( portletDataContext, layoutSet.getCompanyId(), layout.getGroupId(), layout, null, portletElement, importPortletSetup, importPortletArchivedSetups, importPortletUserPreferences, false); // Portlet data Element portletDataElement = portletElement.element("portlet-data"); if (importPortletData && (portletDataElement != null)) { _portletImporter.importPortletData( portletDataContext, portletId, plid, portletDataElement); } } finally { _portletImporter.resetPortletScope(portletDataContext, layout.getGroupId()); } // Portlet permissions if (importPermissions) { _permissionImporter.importPortletPermissions( layoutCache, companyId, groupId, userId, layout, portletElement, portletId, importUserPermissions); } // Archived setups _portletImporter.importPortletPreferences( portletDataContext, layoutSet.getCompanyId(), groupId, null, null, portletElement, importPortletSetup, importPortletArchivedSetups, importPortletUserPreferences, false); } if (importPermissions) { if ((userId > 0) && ((PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) || (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6))) { Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class); indexer.reindex(userId); } } // Asset links _portletImporter.readAssetLinks(portletDataContext); // Delete missing layouts if (deleteMissingLayouts) { deleteMissingLayouts(groupId, privateLayout, newLayoutIds, previousLayouts, serviceContext); } // Page count LayoutSetLocalServiceUtil.updatePageCount(groupId, privateLayout); if (_log.isInfoEnabled()) { _log.info("Importing layouts takes " + stopWatch.getTime() + " ms"); } // Site GroupLocalServiceUtil.updateSite(groupId, true); // Web content layout type for (Layout layout : newLayouts) { UnicodeProperties typeSettingsProperties = layout.getTypeSettingsProperties(); String articleId = typeSettingsProperties.getProperty("article-id"); if (Validator.isNotNull(articleId)) { Map<String, String> articleIds = (Map<String, String>) portletDataContext.getNewPrimaryKeysMap(JournalArticle.class + ".articleId"); typeSettingsProperties.setProperty( "article-id", MapUtil.getString(articleIds, articleId, articleId)); LayoutUtil.update(layout, false); } } zipReader.close(); }
protected PortletPreferences doImportData( PortletDataContext context, String portletId, PortletPreferences preferences, String data) throws Exception { context.importPermissions( "com.liferay.portlet.journal", context.getSourceGroupId(), context.getScopeGroupId()); if (Validator.isNull(data)) { return null; } Document document = SAXReaderUtil.read(data); Element rootElement = document.getRootElement(); Element dlFoldersElement = rootElement.element("dl-folders"); List<Element> dlFolderElements = Collections.EMPTY_LIST; if (dlFoldersElement != null) { dlFolderElements = dlFoldersElement.elements("folder"); } for (Element folderElement : dlFolderElements) { DLPortletDataHandlerImpl.importFolder(context, folderElement); } Element dlFileEntriesElement = rootElement.element("dl-file-entries"); List<Element> dlFileEntryElements = Collections.EMPTY_LIST; if (dlFileEntriesElement != null) { dlFileEntryElements = dlFileEntriesElement.elements("file-entry"); } for (Element fileEntryElement : dlFileEntryElements) { DLPortletDataHandlerImpl.importFileEntry(context, fileEntryElement); } Element dlFileRanksElement = rootElement.element("dl-file-ranks"); List<Element> dlFileRankElements = Collections.EMPTY_LIST; if (dlFileRanksElement != null) { dlFileRankElements = dlFileRanksElement.elements("file-rank"); } for (Element fileRankElement : dlFileRankElements) { DLPortletDataHandlerImpl.importFileRank(context, fileRankElement); } Element igFoldersElement = rootElement.element("ig-folders"); List<Element> igFolderElements = Collections.EMPTY_LIST; if (igFoldersElement != null) { igFolderElements = igFoldersElement.elements("folder"); } for (Element folderElement : igFolderElements) { IGPortletDataHandlerImpl.importFolder(context, folderElement); } Element igImagesElement = rootElement.element("ig-images"); List<Element> igImageElements = Collections.EMPTY_LIST; if (igImagesElement != null) { igImageElements = igImagesElement.elements("image"); } for (Element imageElement : igImageElements) { IGPortletDataHandlerImpl.importImage(context, imageElement); } Element structureElement = rootElement.element("structure"); if (structureElement != null) { JournalPortletDataHandlerImpl.importStructure(context, structureElement); } Element templateElement = rootElement.element("template"); if (templateElement != null) { JournalPortletDataHandlerImpl.importTemplate(context, templateElement); } Element articleElement = rootElement.element("article"); if (articleElement != null) { JournalPortletDataHandlerImpl.importArticle(context, articleElement); } String articleId = preferences.getValue("article-id", StringPool.BLANK); if (Validator.isNotNull(articleId)) { Map<String, String> articleIds = (Map<String, String>) context.getNewPrimaryKeysMap(JournalArticle.class); articleId = MapUtil.getString(articleIds, articleId, articleId); preferences.setValue("group-id", String.valueOf(context.getScopeGroupId())); preferences.setValue("article-id", articleId); Layout layout = LayoutLocalServiceUtil.getLayout(context.getPlid()); JournalContentSearchLocalServiceUtil.updateContentSearch( context.getScopeGroupId(), layout.isPrivateLayout(), layout.getLayoutId(), portletId, articleId, true); } return preferences; }
protected void readAssetCategories(PortletDataContext portletDataContext) throws Exception { String xml = portletDataContext.getZipEntryAsString( portletDataContext.getSourceRootPath() + "/categories-hierarchy.xml"); if (xml == null) { return; } Document document = SAXReaderUtil.read(xml); Element rootElement = document.getRootElement(); Element assetVocabulariesElement = rootElement.element("vocabularies"); List<Element> assetVocabularyElements = assetVocabulariesElement.elements("vocabulary"); Map<Long, Long> assetVocabularyPKs = (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(AssetVocabulary.class); for (Element assetVocabularyElement : assetVocabularyElements) { String path = assetVocabularyElement.attributeValue("path"); if (!portletDataContext.isPathNotProcessed(path)) { continue; } AssetVocabulary assetVocabulary = (AssetVocabulary) portletDataContext.getZipEntryAsObject(path); importAssetVocabulary( portletDataContext, assetVocabularyPKs, assetVocabularyElement, assetVocabulary); } Element assetCategoriesElement = rootElement.element("categories"); List<Element> assetCategoryElements = assetCategoriesElement.elements("category"); Map<Long, Long> assetCategoryPKs = (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(AssetCategory.class); Map<String, String> assetCategoryUuids = (Map<String, String>) portletDataContext.getNewPrimaryKeysMap(AssetCategory.class.getName() + "uuid"); for (Element assetCategoryElement : assetCategoryElements) { String path = assetCategoryElement.attributeValue("path"); if (!portletDataContext.isPathNotProcessed(path)) { continue; } AssetCategory assetCategory = (AssetCategory) portletDataContext.getZipEntryAsObject(path); importAssetCategory( portletDataContext, assetVocabularyPKs, assetCategoryPKs, assetCategoryUuids, assetCategoryElement, assetCategory); } Element assetsElement = rootElement.element("assets"); List<Element> assetElements = assetsElement.elements("asset"); for (Element assetElement : assetElements) { String className = GetterUtil.getString(assetElement.attributeValue("class-name")); long classPK = GetterUtil.getLong(assetElement.attributeValue("class-pk")); String[] assetCategoryUuidArray = StringUtil.split(GetterUtil.getString(assetElement.attributeValue("category-uuids"))); long[] assetCategoryIds = new long[0]; for (String assetCategoryUuid : assetCategoryUuidArray) { assetCategoryUuid = MapUtil.getString(assetCategoryUuids, assetCategoryUuid, assetCategoryUuid); AssetCategory assetCategory = AssetCategoryUtil.fetchByUUID_G( assetCategoryUuid, portletDataContext.getScopeGroupId()); if (assetCategory == null) { Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId()); assetCategory = AssetCategoryUtil.fetchByUUID_G(assetCategoryUuid, companyGroup.getGroupId()); } if (assetCategory != null) { assetCategoryIds = ArrayUtil.append(assetCategoryIds, assetCategory.getCategoryId()); } } portletDataContext.addAssetCategories(className, classPK, assetCategoryIds); } }
public void importPortletInfo( long userId, long plid, long groupId, String portletId, Map<String, String[]> parameterMap, File file) throws Exception { boolean deletePortletData = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.DELETE_PORTLET_DATA); boolean importPermissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS); boolean importUserPermissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS); boolean importPortletData = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA); boolean importPortletArchivedSetups = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS); boolean importPortletSetup = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_SETUP); boolean importPortletUserPreferences = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES); String userIdStrategyString = MapUtil.getString(parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY); StopWatch stopWatch = null; if (_log.isInfoEnabled()) { stopWatch = new StopWatch(); stopWatch.start(); } Layout layout = LayoutLocalServiceUtil.getLayout(plid); User user = UserUtil.findByPrimaryKey(userId); UserIdStrategy userIdStrategy = getUserIdStrategy(user, userIdStrategyString); ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file); PortletDataContext portletDataContext = new PortletDataContextImpl( layout.getCompanyId(), groupId, parameterMap, new HashSet<String>(), userIdStrategy, zipReader); portletDataContext.setPortetDataContextListener( new PortletDataContextListenerImpl(portletDataContext)); portletDataContext.setPlid(plid); portletDataContext.setPrivateLayout(layout.isPrivateLayout()); // Manifest String xml = portletDataContext.getZipEntryAsString("/manifest.xml"); Element rootElement = null; try { Document document = SAXReaderUtil.read(xml); rootElement = document.getRootElement(); } catch (Exception e) { throw new LARFileException("Unable to read /manifest.xml"); } // Build compatibility Element headerElement = rootElement.element("header"); int buildNumber = ReleaseInfo.getBuildNumber(); int importBuildNumber = GetterUtil.getInteger(headerElement.attributeValue("build-number")); if (buildNumber != importBuildNumber) { throw new LayoutImportException( "LAR build number " + importBuildNumber + " does not match " + "portal build number " + buildNumber); } // Type compatibility String type = headerElement.attributeValue("type"); if (!type.equals("portlet")) { throw new LARTypeException("Invalid type of LAR file (" + type + ")"); } // Portlet compatibility String rootPortletId = headerElement.attributeValue("root-portlet-id"); if (!PortletConstants.getRootPortletId(portletId).equals(rootPortletId)) { throw new PortletIdException("Invalid portlet id " + rootPortletId); } // Import group id long sourceGroupId = GetterUtil.getLong(headerElement.attributeValue("group-id")); portletDataContext.setSourceGroupId(sourceGroupId); // Read asset categories, asset tags, comments, locks, and ratings // entries to make them available to the data handlers through the // context if (importPermissions) { _permissionImporter.readPortletDataPermissions(portletDataContext); } readAssetCategories(portletDataContext); readAssetTags(portletDataContext); readComments(portletDataContext); readExpandoTables(portletDataContext); readLocks(portletDataContext); readRatingsEntries(portletDataContext); // Delete portlet data if (_log.isDebugEnabled()) { _log.debug("Deleting portlet data"); } if (deletePortletData) { deletePortletData(portletDataContext, portletId, plid); } 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(de); } setPortletScope(portletDataContext, portletElement); try { // Portlet preferences importPortletPreferences( portletDataContext, layout.getCompanyId(), groupId, layout, portletId, portletElement, importPortletSetup, importPortletArchivedSetups, importPortletUserPreferences, true); // Portlet data Element portletDataElement = portletElement.element("portlet-data"); if (importPortletData && (portletDataElement != null)) { if (_log.isDebugEnabled()) { _log.debug("Importing portlet data"); } importPortletData(portletDataContext, portletId, plid, portletDataElement); } } finally { resetPortletScope(portletDataContext, groupId); } // Portlet permissions if (importPermissions) { if (_log.isDebugEnabled()) { _log.debug("Importing portlet permissions"); } LayoutCache layoutCache = new LayoutCache(); _permissionImporter.importPortletPermissions( layoutCache, layout.getCompanyId(), groupId, userId, layout, portletElement, portletId, importUserPermissions); } // Asset links if (_log.isDebugEnabled()) { _log.debug("Importing asset links"); } readAssetLinks(portletDataContext); if (_log.isInfoEnabled()) { _log.info("Importing portlet takes " + stopWatch.getTime() + " ms"); } zipReader.close(); }
protected static String exportDLFileEntries( PortletDataContext portletDataContext, Element dlFileEntryTypesElement, Element dlFoldersElement, Element dlFileEntriesElement, Element dlFileRanksElement, Element dlRepositoriesElement, Element dlRepositoryEntriesElement, Element entityElement, String content, boolean checkDateRange) throws Exception { Group group = GroupLocalServiceUtil.getGroup(portletDataContext.getGroupId()); if (group.isStagingGroup()) { group = group.getLiveGroup(); } if (group.isStaged() && !group.isStagedRemotely() && !group.isStagedPortlet(PortletKeys.DOCUMENT_LIBRARY)) { return content; } StringBuilder sb = new StringBuilder(content); int beginPos = content.length(); int currentLocation = -1; boolean legacyURL = true; while (true) { String contextPath = PortalUtil.getPathContext(); currentLocation = content.lastIndexOf(contextPath.concat("/c/document_library/get_file?"), beginPos); if (currentLocation == -1) { currentLocation = content.lastIndexOf(contextPath.concat("/image/image_gallery?"), beginPos); } if (currentLocation == -1) { currentLocation = content.lastIndexOf(contextPath.concat("/documents/"), beginPos); legacyURL = false; } if (currentLocation == -1) { return sb.toString(); } beginPos = currentLocation + contextPath.length(); int endPos1 = content.indexOf(CharPool.APOSTROPHE, beginPos); int endPos2 = content.indexOf(CharPool.CLOSE_BRACKET, beginPos); int endPos3 = content.indexOf(CharPool.CLOSE_CURLY_BRACE, beginPos); int endPos4 = content.indexOf(CharPool.CLOSE_PARENTHESIS, beginPos); int endPos5 = content.indexOf(CharPool.LESS_THAN, beginPos); int endPos6 = content.indexOf(CharPool.QUESTION, beginPos); int endPos7 = content.indexOf(CharPool.QUOTE, beginPos); int endPos8 = content.indexOf(CharPool.SPACE, beginPos); int endPos = endPos1; if ((endPos == -1) || ((endPos2 != -1) && (endPos2 < endPos))) { endPos = endPos2; } if ((endPos == -1) || ((endPos3 != -1) && (endPos3 < endPos))) { endPos = endPos3; } if ((endPos == -1) || ((endPos4 != -1) && (endPos4 < endPos))) { endPos = endPos4; } if ((endPos == -1) || ((endPos5 != -1) && (endPos5 < endPos))) { endPos = endPos5; } if ((endPos == -1) || ((endPos6 != -1) && (endPos6 < endPos) && !legacyURL)) { endPos = endPos6; } if ((endPos == -1) || ((endPos7 != -1) && (endPos7 < endPos))) { endPos = endPos7; } if ((endPos == -1) || ((endPos8 != -1) && (endPos8 < endPos))) { endPos = endPos8; } if ((beginPos == -1) || (endPos == -1)) { break; } try { String oldParameters = content.substring(beginPos, endPos); while (oldParameters.contains(StringPool.AMPERSAND_ENCODED)) { oldParameters = oldParameters.replace(StringPool.AMPERSAND_ENCODED, StringPool.AMPERSAND); } Map<String, String[]> map = new HashMap<String, String[]>(); if (oldParameters.startsWith("/documents/")) { String[] pathArray = oldParameters.split(StringPool.SLASH); map.put("groupId", new String[] {pathArray[2]}); if (pathArray.length == 4) { map.put("uuid", new String[] {pathArray[3]}); } else if (pathArray.length == 5) { map.put("folderId", new String[] {pathArray[3]}); String title = HttpUtil.decodeURL(pathArray[4]); int pos = title.indexOf(StringPool.QUESTION); if (pos != -1) { title = title.substring(0, pos); } map.put("title", new String[] {title}); } else if (pathArray.length > 5) { String uuid = pathArray[5]; int pos = uuid.indexOf(StringPool.QUESTION); if (pos != -1) { uuid = uuid.substring(0, pos); } map.put("uuid", new String[] {uuid}); } } else { oldParameters = oldParameters.substring(oldParameters.indexOf(CharPool.QUESTION) + 1); map = HttpUtil.parameterMapFromString(oldParameters); } FileEntry fileEntry = null; String uuid = MapUtil.getString(map, "uuid"); if (Validator.isNotNull(uuid)) { String groupIdString = MapUtil.getString(map, "groupId"); long groupId = GetterUtil.getLong(groupIdString); if (groupIdString.equals("@group_id@")) { groupId = portletDataContext.getScopeGroupId(); } fileEntry = DLAppLocalServiceUtil.getFileEntryByUuidAndGroupId(uuid, groupId); } else { String folderIdString = MapUtil.getString(map, "folderId"); if (Validator.isNotNull(folderIdString)) { long folderId = GetterUtil.getLong(folderIdString); String name = MapUtil.getString(map, "name"); String title = MapUtil.getString(map, "title"); String groupIdString = MapUtil.getString(map, "groupId"); long groupId = GetterUtil.getLong(groupIdString); if (groupIdString.equals("@group_id@")) { groupId = portletDataContext.getScopeGroupId(); } if (Validator.isNotNull(title)) { fileEntry = DLAppLocalServiceUtil.getFileEntry(groupId, folderId, title); } else { DLFileEntry dlFileEntry = DLFileEntryLocalServiceUtil.getFileEntryByName(groupId, folderId, name); fileEntry = new LiferayFileEntry(dlFileEntry); } } else if (map.containsKey("image_id") || map.containsKey("img_id") || map.containsKey("i_id")) { long imageId = MapUtil.getLong(map, "image_id"); if (imageId <= 0) { imageId = MapUtil.getLong(map, "img_id"); if (imageId <= 0) { imageId = MapUtil.getLong(map, "i_id"); } } DLFileEntry dlFileEntry = DLFileEntryLocalServiceUtil.fetchFileEntryByAnyImageId(imageId); if (dlFileEntry != null) { fileEntry = new LiferayFileEntry(dlFileEntry); } } } if (fileEntry == null) { beginPos--; continue; } beginPos = currentLocation; DLPortletDataHandler.exportFileEntry( portletDataContext, dlFileEntryTypesElement, dlFoldersElement, dlFileEntriesElement, dlFileRanksElement, dlRepositoriesElement, dlRepositoryEntriesElement, fileEntry, checkDateRange); Element dlReferenceElement = entityElement.addElement("dl-reference"); dlReferenceElement.addAttribute( "default-repository", String.valueOf(fileEntry.isDefaultRepository())); String path = null; if (fileEntry.isDefaultRepository()) { path = DLPortletDataHandler.getFileEntryPath(portletDataContext, fileEntry); } else { path = DLPortletDataHandler.getRepositoryEntryPath( portletDataContext, fileEntry.getFileEntryId()); } dlReferenceElement.addAttribute("path", path); String dlReference = "[$dl-reference=" + path + "$]"; sb.replace(beginPos, endPos, dlReference); } catch (Exception e) { if (_log.isDebugEnabled()) { _log.debug(e, e); } else if (_log.isWarnEnabled()) { _log.warn(e.getMessage()); } } beginPos--; } return sb.toString(); }
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(); 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 = ExportImportHelperUtil.getManifestSummary(portletDataContext); if (BackgroundTaskThreadLocal.hasBackgroundTask()) { PortletDataHandlerStatusMessageSenderUtil.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(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 = ExportImportHelperUtil.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(de); } } ZipReader zipReader = portletDataContext.getZipReader(); zipReader.close(); }