@Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, PollsVote vote)
      throws Exception {

    Map<Long, Long> questionIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(PollsQuestion.class);

    long questionId = MapUtil.getLong(questionIds, vote.getQuestionId(), vote.getQuestionId());

    Map<Long, Long> choiceIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(PollsChoice.class);

    long choiceId = MapUtil.getLong(choiceIds, vote.getChoiceId(), vote.getChoiceId());

    ServiceContext serviceContext = portletDataContext.createServiceContext(vote);

    serviceContext.setCreateDate(vote.getVoteDate());

    if (portletDataContext.isDataStrategyMirror()) {
      PollsVote existingVote =
          fetchStagedModelByUuidAndGroupId(vote.getUuid(), portletDataContext.getScopeGroupId());

      if (existingVote == null) {
        serviceContext.setUuid(vote.getUuid());
      }
    }

    try {
      PollsVoteLocalServiceUtil.addVote(vote.getUserId(), questionId, choiceId, serviceContext);
    } catch (DuplicateVoteException dve) {
    }
  }
  protected boolean prepareLayoutStagingHandler(
      PortletDataContext portletDataContext, Layout layout) {

    boolean exportLAR = MapUtil.getBoolean(portletDataContext.getParameterMap(), "exportLAR");

    if (exportLAR || !LayoutStagingUtil.isBranchingLayout(layout)) {
      return true;
    }

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

    if (layoutSetBranchId <= 0) {
      return false;
    }

    LayoutRevision layoutRevision =
        _layoutRevisionLocalService.fetchLayoutRevision(layoutSetBranchId, true, layout.getPlid());

    if (layoutRevision == null) {
      return false;
    }

    LayoutStagingHandler layoutStagingHandler = LayoutStagingUtil.getLayoutStagingHandler(layout);

    layoutStagingHandler.setLayoutRevision(layoutRevision);

    return true;
  }
  protected PortletDataContext getPortletDataContext(
      ExportImportConfiguration exportImportConfiguration) throws Exception {

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

    long sourceGroupId = MapUtil.getLong(settingsMap, "sourceGroupId");
    boolean privateLayout = MapUtil.getBoolean(settingsMap, "privateLayout");
    Map<String, String[]> parameterMap = (Map<String, String[]>) settingsMap.get("parameterMap");
    DateRange dateRange = ExportImportDateUtil.getDateRange(exportImportConfiguration);

    Group group = _groupLocalService.getGroup(sourceGroupId);
    ZipWriter zipWriter = ExportImportHelperUtil.getLayoutSetZipWriter(sourceGroupId);

    PortletDataContext portletDataContext =
        PortletDataContextFactoryUtil.createExportPortletDataContext(
            group.getCompanyId(),
            sourceGroupId,
            parameterMap,
            dateRange.getStartDate(),
            dateRange.getEndDate(),
            zipWriter);

    portletDataContext.setPrivateLayout(privateLayout);

    return portletDataContext;
  }
  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 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 void populateSiteInformation(Document document, Map<String, Serializable> settingsMap) {

    document.addKeyword(
        _PREFIX_SETTING + "privateLayout", MapUtil.getBoolean(settingsMap, "privateLayout"));
    document.addKeyword(
        _PREFIX_SETTING + "sourceGroupId", MapUtil.getLong(settingsMap, "sourceGroupId"));
    document.addKeyword(
        _PREFIX_SETTING + "targetGroupId", MapUtil.getLong(settingsMap, "targetGroupId"));
  }
  public boolean getBooleanParameter(String namespace, String name) {
    boolean defaultValue =
        MapUtil.getBoolean(
            getParameterMap(), PortletDataHandlerKeys.PORTLET_DATA_CONTROL_DEFAULT, true);

    return MapUtil.getBoolean(
        getParameterMap(),
        PortletDataHandlerControl.getNamespacedControlName(namespace, name),
        defaultValue);
  }
  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();
  }
  @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
  public BackgroundTaskResult execute(BackgroundTask backgroundTask) throws PortalException {

    ExportImportConfiguration exportImportConfiguration =
        getExportImportConfiguration(backgroundTask);

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

    long userId = MapUtil.getLong(settingsMap, "userId");
    long groupId = MapUtil.getLong(settingsMap, "sourceGroupId");
    boolean privateLayout = MapUtil.getBoolean(settingsMap, "privateLayout");
    long[] layoutIds = GetterUtil.getLongValues(settingsMap.get("layoutIds"));
    Map<String, String[]> parameterMap = (Map<String, String[]>) settingsMap.get("parameterMap");
    DateRange dateRange =
        ExportImportDateUtil.getDateRange(
            exportImportConfiguration, ExportImportDateUtil.RANGE_ALL);

    StringBundler sb = new StringBundler(4);

    sb.append(
        StringUtil.replace(
            exportImportConfiguration.getName(), StringPool.SPACE, StringPool.UNDERLINE));
    sb.append(StringPool.DASH);
    sb.append(Time.getShortTimestamp());
    sb.append(".lar");

    File larFile =
        LayoutLocalServiceUtil.exportLayoutsAsFile(
            groupId,
            privateLayout,
            layoutIds,
            parameterMap,
            dateRange.getStartDate(),
            dateRange.getEndDate());

    BackgroundTaskLocalServiceUtil.addBackgroundTaskAttachment(
        userId, backgroundTask.getBackgroundTaskId(), sb.toString(), larFile);

    boolean updateLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.UPDATE_LAST_PUBLISH_DATE);

    if (updateLastPublishDate) {
      ExportImportDateUtil.updateLastPublishDate(
          groupId, privateLayout, dateRange, dateRange.getEndDate());
    }

    return BackgroundTaskResult.SUCCESS;
  }
  protected JSONArray getPortletURLsJSONArray(Map<String, PortletURL> portletURLs) {

    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

    if (MapUtil.isEmpty(portletURLs)) {
      return jsonArray;
    }

    for (Map.Entry<String, PortletURL> entry : portletURLs.entrySet()) {
      JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

      jsonObject.put("name", entry.getKey());

      PortletURL portletURL = entry.getValue();

      portletURL.setParameter("selPlid", "{selPlid}");

      jsonObject.put(
          "value",
          StringUtil.replace(portletURL.toString(), HttpUtil.encodePath("{selPlid}"), "{selPlid}"));

      jsonArray.put(jsonObject);
    }

    return jsonArray;
  }
  @Override
  public boolean validateReference(
      PortletDataContext portletDataContext, Element referenceElement) {

    validateMissingGroupReference(portletDataContext, referenceElement);

    String uuid = referenceElement.attributeValue("uuid");

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

    long groupId = GetterUtil.getLong(referenceElement.attributeValue("group-id"));

    groupId = MapUtil.getLong(groupIds, groupId);

    String fileEntryTypeKey = referenceElement.attributeValue("file-entry-type-key");
    boolean preloaded = GetterUtil.getBoolean(referenceElement.attributeValue("preloaded"));

    DLFileEntryType existingFileEntryType =
        fetchExistingFileEntryType(uuid, groupId, fileEntryTypeKey, preloaded);

    if (existingFileEntryType == null) {
      return false;
    }

    return true;
  }
  @Override
  public void importMissingReference(
      PortletDataContext portletDataContext, Element referenceElement) throws PortletDataException {

    importMissingGroupReference(portletDataContext, referenceElement);

    String uuid = referenceElement.attributeValue("uuid");

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

    long groupId = GetterUtil.getLong(referenceElement.attributeValue("group-id"));

    groupId = MapUtil.getLong(groupIds, groupId);

    String fileEntryTypeKey = referenceElement.attributeValue("file-entry-type-key");
    boolean preloaded = GetterUtil.getBoolean(referenceElement.attributeValue("preloaded"));

    DLFileEntryType existingFileEntryType = null;

    existingFileEntryType = fetchExistingFileEntryType(uuid, groupId, fileEntryTypeKey, preloaded);

    Map<Long, Long> fileEntryTypeIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(DLFileEntryType.class);

    long fileEntryTypeId = GetterUtil.getLong(referenceElement.attributeValue("class-pk"));

    fileEntryTypeIds.put(fileEntryTypeId, existingFileEntryType.getFileEntryTypeId());
  }
  @Override
  protected Long getImportPortletPreferencesNewPrimaryKey(
      PortletDataContext portletDataContext,
      Class<?> clazz,
      long companyGroupId,
      Map<Long, Long> primaryKeys,
      String uuid)
      throws Exception {

    if (Validator.isNumber(uuid)) {
      long oldPrimaryKey = GetterUtil.getLong(uuid);

      return MapUtil.getLong(primaryKeys, oldPrimaryKey, oldPrimaryKey);
    }

    String className = clazz.getName();

    if (className.equals(Organization.class.getName())) {
      Organization organization =
          OrganizationUtil.fetchByUuid_C_First(uuid, portletDataContext.getCompanyId(), null);

      if (organization != null) {
        return organization.getOrganizationId();
      }
    }

    return null;
  }
  @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;
  }
  protected void setRequestParameters(
      PortletRequest portletRequest, PortletResponse portletResponse, OAuthRequest oAuthRequest) {

    setBaseRequestParameters(portletRequest, portletResponse, oAuthRequest);

    Map<String, String[]> parameterMap = new HashMap<>();

    MapUtil.copy(portletRequest.getParameterMap(), parameterMap);

    processPortletParameterMap(portletRequest, portletResponse, parameterMap);

    String serverNamespace = getServerNamespace();

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

      if (key.equals("remoteWindowState")) {
        key = "p_p_state";
      } else {
        key = serverNamespace.concat(key);
      }

      if (ArrayUtil.isEmpty(values) || Validator.isNull(values[0])) {
        continue;
      }

      addOAuthParameter(oAuthRequest, key, values[0]);
    }
  }
  @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 boolean isUseCustomSQL(LinkedHashMap<String, Object> params) {
    if (MapUtil.isEmpty(params)) {
      return false;
    }

    return true;
  }
  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
  protected PortletPreferences doProcessImportPortletPreferences(
      PortletDataContext portletDataContext,
      String portletId,
      PortletPreferences portletPreferences)
      throws Exception {

    portletDataContext.importPortletPermissions(WikiPermission.RESOURCE_NAME);

    StagedModelDataHandlerUtil.importReferenceStagedModels(portletDataContext, WikiNode.class);

    StagedModelDataHandlerUtil.importReferenceStagedModels(portletDataContext, WikiPage.class);

    long nodeId = GetterUtil.getLong(portletPreferences.getValue("nodeId", StringPool.BLANK));

    if (nodeId > 0) {
      Map<Long, Long> nodeIds =
          (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(WikiNode.class);

      nodeId = MapUtil.getLong(nodeIds, nodeId, nodeId);

      portletPreferences.setValue("nodeId", String.valueOf(nodeId));
    }

    return portletPreferences;
  }
  protected void importTheme(
      PortletDataContext portletDataContext, Layout layout, Layout importedLayout)
      throws Exception {

    boolean importThemeSettings =
        MapUtil.getBoolean(
            portletDataContext.getParameterMap(), PortletDataHandlerKeys.THEME_REFERENCE);

    if (_log.isDebugEnabled()) {
      _log.debug("Import theme settings " + importThemeSettings);
    }

    if (importThemeSettings) {
      importedLayout.setColorSchemeId(layout.getColorSchemeId());
      importedLayout.setCss(layout.getCss());
      importedLayout.setThemeId(layout.getThemeId());
      importedLayout.setWapColorSchemeId(layout.getWapColorSchemeId());
      importedLayout.setWapThemeId(layout.getWapThemeId());
    } else {
      importedLayout.setColorSchemeId(StringPool.BLANK);
      importedLayout.setCss(StringPool.BLANK);
      importedLayout.setThemeId(StringPool.BLANK);
      importedLayout.setWapColorSchemeId(StringPool.BLANK);
      importedLayout.setWapThemeId(StringPool.BLANK);
    }
  }
  @Override
  public boolean validateReference(
      PortletDataContext portletDataContext, Element referenceElement) {

    validateMissingGroupReference(portletDataContext, referenceElement);

    String uuid = referenceElement.attributeValue("uuid");

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

    long groupId = GetterUtil.getLong(referenceElement.attributeValue("group-id"));

    groupId = MapUtil.getLong(groupIds, groupId);

    boolean privateLayout =
        GetterUtil.getBoolean(referenceElement.attributeValue("private-layout"));

    Layout existingLayout = fetchMissingReference(uuid, groupId, privateLayout);

    if (existingLayout == null) {
      return false;
    }

    return true;
  }
  protected void updateCalendars(
      PortletDataContext portletDataContext,
      CalendarResource calendarResource,
      CalendarResource importedCalendarResource)
      throws SystemException {

    Map<Long, Long> calendarIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(Calendar.class);

    List<Element> referenceElements =
        portletDataContext.getReferenceElements(calendarResource, Calendar.class);

    for (Element referenceElement : referenceElements) {
      long calendarId = GetterUtil.getLong(referenceElement.attributeValue("class-pk"));

      Calendar calendar =
          CalendarLocalServiceUtil.fetchCalendar(MapUtil.getLong(calendarIds, calendarId));

      if (calendar != null) {
        calendar.setCalendarResourceId(importedCalendarResource.getCalendarResourceId());

        CalendarLocalServiceUtil.updateCalendar(calendar);
      }
    }
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext, WSRPConsumerPortlet wsrpConsumerPortlet)
      throws Exception {

    StagedModelDataHandlerUtil.importReferenceStagedModel(
        portletDataContext,
        wsrpConsumerPortlet,
        WSRPConsumer.class,
        wsrpConsumerPortlet.getWsrpConsumerId());

    Map<Long, Long> wsrpConsumerIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(WSRPConsumer.class);

    long wsrpConsumerId =
        MapUtil.getLong(
            wsrpConsumerIds,
            wsrpConsumerPortlet.getWsrpConsumerId(),
            wsrpConsumerPortlet.getWsrpConsumerId());

    ServiceContext serviceContext = portletDataContext.createServiceContext(wsrpConsumerPortlet);

    WSRPConsumerPortlet importedWSRPConsumerPortlet = null;

    if (portletDataContext.isDataStrategyMirror()) {
      WSRPConsumerPortlet existingWSRPConsumerPortlet =
          WSRPConsumerPortletLocalServiceUtil.fetchWSRPConsumerPortletByUuidAndCompanyId(
              wsrpConsumerPortlet.getUuid(), portletDataContext.getCompanyId());

      if (existingWSRPConsumerPortlet == null) {
        serviceContext.setUuid(wsrpConsumerPortlet.getUuid());

        importedWSRPConsumerPortlet =
            WSRPConsumerPortletLocalServiceUtil.addWSRPConsumerPortlet(
                wsrpConsumerId,
                wsrpConsumerPortlet.getName(),
                wsrpConsumerPortlet.getPortletHandle(),
                serviceContext);
      } else {
        existingWSRPConsumerPortlet.setWsrpConsumerId(wsrpConsumerId);
        existingWSRPConsumerPortlet.setName(wsrpConsumerPortlet.getName());
        existingWSRPConsumerPortlet.setPortletHandle(wsrpConsumerPortlet.getPortletHandle());

        importedWSRPConsumerPortlet =
            WSRPConsumerPortletLocalServiceUtil.updateWSRPConsumerPortlet(
                existingWSRPConsumerPortlet);
      }
    } else {
      importedWSRPConsumerPortlet =
          WSRPConsumerPortletLocalServiceUtil.addWSRPConsumerPortlet(
              wsrpConsumerId,
              wsrpConsumerPortlet.getName(),
              wsrpConsumerPortlet.getPortletHandle(),
              serviceContext);
    }

    portletDataContext.importClassedModel(wsrpConsumerPortlet, importedWSRPConsumerPortlet);
  }
  @Override
  public void deleteStagedModels(PortletDataContext portletDataContext) throws PortalException {

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

    long classNameId = MapUtil.getLong(parameterMap, "parentStagedModelClassNameId");

    _friendlyURLLocalService.deleteGroupFriendlyURLs(portletDataContext.getGroupId(), classNameId);
  }
  @Override
  protected void doReceive(Message message, MessageStatus messageStatus) throws PortalException {

    long exportImportConfigurationId = GetterUtil.getLong(message.getPayload());

    ExportImportConfiguration exportImportConfiguration =
        _exportImportConfigurationLocalService.fetchExportImportConfiguration(
            exportImportConfigurationId);

    if (exportImportConfiguration == null) {
      if (_log.isWarnEnabled()) {
        _log.warn(
            "Unable to find export import configuration with ID " + exportImportConfigurationId);
      }

      return;
    }

    messageStatus.setPayload(exportImportConfiguration);

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

    long userId = MapUtil.getLong(settingsMap, "userId");
    long sourceGroupId = MapUtil.getLong(settingsMap, "sourceGroupId");
    long targetGroupId = MapUtil.getLong(settingsMap, "targetGroupId");
    boolean privateLayout = MapUtil.getBoolean(settingsMap, "privateLayout");
    long[] layoutIds = GetterUtil.getLongValues(settingsMap.get("layoutIds"));
    Map<String, String[]> parameterMap = (Map<String, String[]>) settingsMap.get("parameterMap");

    initThreadLocals(userId, parameterMap);

    try {
      StagingUtil.publishLayouts(
          userId,
          sourceGroupId,
          targetGroupId,
          privateLayout,
          layoutIds,
          exportImportConfiguration.getName(),
          parameterMap);
    } finally {
      resetThreadLocals();
    }
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, MDRAction action)
      throws Exception {

    Map<Long, Long> ruleGroupInstanceIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(MDRRuleGroupInstance.class);

    long ruleGroupInstanceId =
        MapUtil.getLong(
            ruleGroupInstanceIds, action.getRuleGroupInstanceId(), action.getRuleGroupInstanceId());

    ServiceContext serviceContext = portletDataContext.createServiceContext(action);

    serviceContext.setUserId(portletDataContext.getUserId(action.getUserUuid()));

    Element element = portletDataContext.getImportDataStagedModelElement(action);

    validateLayout(element, action);

    MDRAction importedAction = null;

    if (portletDataContext.isDataStrategyMirror()) {
      MDRAction existingAction =
          fetchStagedModelByUuidAndGroupId(action.getUuid(), portletDataContext.getScopeGroupId());

      if (existingAction == null) {
        serviceContext.setUuid(action.getUuid());

        importedAction =
            _mdrActionLocalService.addAction(
                ruleGroupInstanceId,
                action.getNameMap(),
                action.getDescriptionMap(),
                action.getType(),
                action.getTypeSettingsProperties(),
                serviceContext);
      } else {
        importedAction =
            _mdrActionLocalService.updateAction(
                existingAction.getActionId(), action.getNameMap(),
                action.getDescriptionMap(), action.getType(),
                action.getTypeSettingsProperties(), serviceContext);
      }
    } else {
      importedAction =
          _mdrActionLocalService.addAction(
              ruleGroupInstanceId,
              action.getNameMap(),
              action.getDescriptionMap(),
              action.getType(),
              action.getTypeSettingsProperties(),
              serviceContext);
    }

    portletDataContext.importClassedModel(action, importedAction);
  }
  @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 unsetSearchEngine(SearchEngine searchEngine, Map<String, Object> properties) {

    String searchEngineId = MapUtil.getString(properties, "search.engine.id");

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

    _searchEngines.remove(searchEngineId);
  }
  /**
   * Returns the number of groups and organization groups that match the name and description,
   * optionally including the user's inherited organizations and user groups. System and staged
   * groups are not included.
   *
   * @param companyId the primary key of the company
   * @param name the group's name (optionally <code>null</code>)
   * @param description the group's description (optionally <code>null</code>)
   * @param params the finder params (optionally <code>null</code>). To include the user's inherited
   *     organizations and user groups in the search, add entries having &quot;usersGroups&quot; and
   *     &quot;inherit&quot; as keys mapped to the the user's ID. For more information see {@link
   *     com.liferay.portal.service.persistence.GroupFinder}.
   * @return the number of matching groups
   */
  @Override
  public int searchCount(long companyId, String name, String description, String[] params) {

    if (params == null) {
      params = new String[0];
    }

    LinkedHashMap<String, Object> paramsObj = MapUtil.toLinkedHashMap(params);

    return groupLocalService.searchCount(companyId, name, description, paramsObj, true);
  }