@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
  protected void doRestoreStagedModel(PortletDataContext portletDataContext, WikiPage page)
      throws Exception {

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

    WikiPage existingPage =
        fetchStagedModelByUuidAndGroupId(page.getUuid(), portletDataContext.getScopeGroupId());

    if ((existingPage == null) || !existingPage.isInTrash()) {
      return;
    }

    TrashHandler trashHandler = existingPage.getTrashHandler();

    if (trashHandler.isRestorable(existingPage.getResourcePrimKey())) {
      trashHandler.restoreTrashEntry(userId, existingPage.getResourcePrimKey());
    }
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, UserGroup userGroup)
      throws Exception {

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

    ServiceContext serviceContext = portletDataContext.createServiceContext(userGroup);

    UserGroup existingUserGroup =
        fetchStagedModelByUuidAndGroupId(userGroup.getUuid(), portletDataContext.getGroupId());

    if (existingUserGroup == null) {
      existingUserGroup =
          _userGroupLocalService.fetchUserGroup(
              portletDataContext.getCompanyId(), userGroup.getName());
    }

    UserGroup importedUserGroup = null;

    if (existingUserGroup == null) {
      serviceContext.setUuid(userGroup.getUuid());

      importedUserGroup =
          _userGroupLocalService.addUserGroup(
              userId,
              portletDataContext.getCompanyId(),
              userGroup.getName(),
              userGroup.getDescription(),
              serviceContext);
    } else {
      importedUserGroup =
          _userGroupLocalService.updateUserGroup(
              portletDataContext.getCompanyId(),
              existingUserGroup.getUserGroupId(),
              userGroup.getName(),
              userGroup.getDescription(),
              serviceContext);
    }

    portletDataContext.importClassedModel(userGroup, importedUserGroup);
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, KBTemplate kbTemplate)
      throws Exception {

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

    ServiceContext serviceContext = portletDataContext.createServiceContext(kbTemplate);

    KBTemplate importedKBTemplate = null;

    if (portletDataContext.isDataStrategyMirror()) {
      KBTemplate existingKBTemplate =
          fetchStagedModelByUuidAndGroupId(
              kbTemplate.getUuid(), portletDataContext.getScopeGroupId());

      if (existingKBTemplate == null) {
        serviceContext.setUuid(kbTemplate.getUuid());

        importedKBTemplate =
            KBTemplateLocalServiceUtil.addKBTemplate(
                userId, kbTemplate.getTitle(), kbTemplate.getContent(), serviceContext);
      } else {
        importedKBTemplate =
            KBTemplateLocalServiceUtil.updateKBTemplate(
                existingKBTemplate.getKbTemplateId(),
                kbTemplate.getTitle(),
                kbTemplate.getContent(),
                serviceContext);
      }
    } else {
      importedKBTemplate =
          KBTemplateLocalServiceUtil.addKBTemplate(
              userId, kbTemplate.getTitle(), kbTemplate.getContent(), serviceContext);
    }

    portletDataContext.importClassedModel(kbTemplate, importedKBTemplate);
  }
  protected void importPortletPreferences(
      PortletDataContext portletDataContext,
      long companyId,
      long groupId,
      Layout layout,
      Element parentElement,
      boolean preserveScopeLayoutId,
      boolean importPortletArchivedSetups,
      boolean importPortletData,
      boolean importPortletSetup,
      boolean importPortletUserPreferences)
      throws Exception {

    long plid = LayoutConstants.DEFAULT_PLID;
    String scopeType = StringPool.BLANK;
    String scopeLayoutUuid = StringPool.BLANK;

    if (layout != null) {
      plid = layout.getPlid();

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

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

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

    List<Element> portletPreferencesElements = parentElement.elements("portlet-preferences");

    for (Element portletPreferencesElement : portletPreferencesElements) {
      String path = portletPreferencesElement.attributeValue("path");

      if (portletDataContext.isPathNotProcessed(path)) {
        String xml = null;

        Element element = null;

        try {
          xml = portletDataContext.getZipEntryAsString(path);

          Document preferencesDocument = SAXReaderUtil.read(xml);

          element = preferencesDocument.getRootElement();
        } catch (DocumentException de) {
          throw new SystemException(de);
        }

        long ownerId = GetterUtil.getLong(element.attributeValue("owner-id"));
        int ownerType = GetterUtil.getInteger(element.attributeValue("owner-type"));

        if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_COMPANY) || !importPortletSetup) {

          continue;
        }

        if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) && !importPortletArchivedSetups) {

          continue;
        }

        if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_USER)
            && (ownerId != PortletKeys.PREFS_OWNER_ID_DEFAULT)
            && !importPortletUserPreferences) {

          continue;
        }

        long curPlid = plid;
        String curPortletId = portletDataContext.getPortletId();

        if (ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) {
          curPlid = PortletKeys.PREFS_PLID_SHARED;
          curPortletId = portletDataContext.getRootPortletId();
          ownerId = portletDataContext.getScopeGroupId();
        }

        if (ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) {
          String userUuid = element.attributeValue("archive-user-uuid");

          long userId = portletDataContext.getUserId(userUuid);

          String name = element.attributeValue("archive-name");

          curPortletId = portletDataContext.getRootPortletId();

          PortletItem portletItem =
              _portletItemLocalService.updatePortletItem(
                  userId, groupId, name, curPortletId, PortletPreferences.class.getName());

          curPlid = LayoutConstants.DEFAULT_PLID;
          ownerId = portletItem.getPortletItemId();
        }

        if (ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) {
          String userUuid = element.attributeValue("user-uuid");

          ownerId = portletDataContext.getUserId(userUuid);
        }

        boolean defaultUser = GetterUtil.getBoolean(element.attributeValue("default-user"));

        if (defaultUser) {
          ownerId = _userLocalService.getDefaultUserId(companyId);
        }

        javax.portlet.PortletPreferences jxPortletPreferences =
            PortletPreferencesFactoryUtil.fromXML(
                companyId, ownerId, ownerType, curPlid, curPortletId, xml);

        Element importDataRootElement = portletDataContext.getImportDataRootElement();

        try {
          Element preferenceDataElement = portletPreferencesElement.element("preference-data");

          if (preferenceDataElement != null) {
            portletDataContext.setImportDataRootElement(preferenceDataElement);
          }

          Portlet portlet =
              _portletLocalService.getPortletById(portletDataContext.getCompanyId(), curPortletId);

          ExportImportPortletPreferencesProcessor exportImportPortletPreferencesProcessor =
              ExportImportPortletPreferencesProcessorRegistryUtil
                  .getExportImportPortletPreferencesProcessor(portlet.getRootPortletId());

          if (exportImportPortletPreferencesProcessor != null) {
            List<Capability> importCapabilities =
                exportImportPortletPreferencesProcessor.getImportCapabilities();

            if (ListUtil.isNotEmpty(importCapabilities)) {
              for (Capability importCapability : importCapabilities) {

                importCapability.process(portletDataContext, jxPortletPreferences);
              }
            }

            exportImportPortletPreferencesProcessor.processImportPortletPreferences(
                portletDataContext, jxPortletPreferences);
          } else {
            PortletDataHandler portletDataHandler = portlet.getPortletDataHandlerInstance();

            jxPortletPreferences =
                portletDataHandler.processImportPortletPreferences(
                    portletDataContext, curPortletId, jxPortletPreferences);
          }
        } finally {
          portletDataContext.setImportDataRootElement(importDataRootElement);
        }

        updatePortletPreferences(
            portletDataContext,
            ownerId,
            ownerType,
            curPlid,
            curPortletId,
            PortletPreferencesFactoryUtil.toXML(jxPortletPreferences),
            importPortletData);
      }
    }

    if (preserveScopeLayoutId && (layout != null)) {
      javax.portlet.PortletPreferences jxPortletPreferences =
          PortletPreferencesFactoryUtil.getLayoutPortletSetup(
              layout, portletDataContext.getPortletId());

      try {
        jxPortletPreferences.setValue("lfrScopeType", scopeType);
        jxPortletPreferences.setValue("lfrScopeLayoutUuid", scopeLayoutUuid);

        jxPortletPreferences.store();
      } finally {
        portletDataContext.setScopeType(scopeType);
        portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
      }
    }
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext, LayoutSetPrototype layoutSetPrototype)
      throws Exception {

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

    UnicodeProperties settingsProperties = layoutSetPrototype.getSettingsProperties();

    boolean layoutsUpdateable =
        GetterUtil.getBoolean(settingsProperties.getProperty("layoutsUpdateable"), true);

    ServiceContext serviceContext = portletDataContext.createServiceContext(layoutSetPrototype);

    serviceContext.setAttribute("addDefaultLayout", Boolean.FALSE);

    LayoutSetPrototype importedLayoutSetPrototype = null;

    if (portletDataContext.isDataStrategyMirror()) {
      LayoutSetPrototype existingLayoutSetPrototype =
          _layoutSetPrototypeLocalService.fetchLayoutSetPrototypeByUuidAndCompanyId(
              layoutSetPrototype.getUuid(), portletDataContext.getCompanyId());

      if (existingLayoutSetPrototype == null) {
        serviceContext.setUuid(layoutSetPrototype.getUuid());

        importedLayoutSetPrototype =
            _layoutSetPrototypeLocalService.addLayoutSetPrototype(
                userId,
                portletDataContext.getCompanyId(),
                layoutSetPrototype.getNameMap(),
                layoutSetPrototype.getDescriptionMap(),
                layoutSetPrototype.isActive(),
                layoutsUpdateable,
                serviceContext);
      } else {
        importedLayoutSetPrototype =
            _layoutSetPrototypeLocalService.updateLayoutSetPrototype(
                existingLayoutSetPrototype.getLayoutSetPrototypeId(),
                layoutSetPrototype.getNameMap(),
                layoutSetPrototype.getDescriptionMap(),
                layoutSetPrototype.isActive(),
                layoutsUpdateable,
                serviceContext);
      }
    } else {
      importedLayoutSetPrototype =
          _layoutSetPrototypeLocalService.addLayoutSetPrototype(
              userId,
              portletDataContext.getCompanyId(),
              layoutSetPrototype.getNameMap(),
              layoutSetPrototype.getDescriptionMap(),
              layoutSetPrototype.isActive(),
              layoutsUpdateable,
              serviceContext);
    }

    importLayoutPrototypes(portletDataContext, layoutSetPrototype);
    importLayouts(
        portletDataContext, layoutSetPrototype, importedLayoutSetPrototype, serviceContext);

    portletDataContext.importClassedModel(layoutSetPrototype, importedLayoutSetPrototype);
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext, MDRRuleGroupInstance ruleGroupInstance)
      throws Exception {

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

    Map<Long, Long> ruleGroupIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(MDRRuleGroup.class);

    Long ruleGroupId =
        MapUtil.getLong(
            ruleGroupIds, ruleGroupInstance.getRuleGroupId(), ruleGroupInstance.getRuleGroupId());

    long classPK = 0;

    Element ruleGroupInstanceElement =
        portletDataContext.getImportDataStagedModelElement(ruleGroupInstance);

    String layoutUuid = ruleGroupInstanceElement.attributeValue("layout-uuid");

    try {
      if (Validator.isNotNull(layoutUuid)) {
        Layout layout =
            _layoutLocalService.getLayoutByUuidAndGroupId(
                layoutUuid,
                portletDataContext.getScopeGroupId(),
                portletDataContext.isPrivateLayout());

        classPK = layout.getPrimaryKey();
      } else {
        LayoutSet layoutSet =
            _layoutSetLocalService.getLayoutSet(
                portletDataContext.getScopeGroupId(), portletDataContext.isPrivateLayout());

        classPK = layoutSet.getLayoutSetId();
      }
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        StringBundler sb = new StringBundler(5);

        sb.append("Layout ");
        sb.append(layoutUuid);
        sb.append(" is missing for rule group instance ");
        sb.append(ruleGroupInstance.getRuleGroupInstanceId());
        sb.append(", skipping this rule group instance.");

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

      return;
    }

    ServiceContext serviceContext = portletDataContext.createServiceContext(ruleGroupInstance);

    serviceContext.setUserId(userId);

    MDRRuleGroupInstance importedRuleGroupInstance = null;

    if (portletDataContext.isDataStrategyMirror()) {
      MDRRuleGroupInstance existingMDRRuleGroupInstance =
          fetchStagedModelByUuidAndGroupId(
              ruleGroupInstance.getUuid(), portletDataContext.getScopeGroupId());

      if (existingMDRRuleGroupInstance == null) {
        serviceContext.setUuid(ruleGroupInstance.getUuid());

        importedRuleGroupInstance =
            _mdrRuleGroupInstanceLocalService.addRuleGroupInstance(
                portletDataContext.getScopeGroupId(),
                ruleGroupInstance.getClassName(),
                classPK,
                ruleGroupId,
                ruleGroupInstance.getPriority(),
                serviceContext);
      } else {
        importedRuleGroupInstance =
            _mdrRuleGroupInstanceLocalService.updateRuleGroupInstance(
                existingMDRRuleGroupInstance.getRuleGroupInstanceId(),
                ruleGroupInstance.getPriority());
      }
    } else {
      importedRuleGroupInstance =
          _mdrRuleGroupInstanceLocalService.addRuleGroupInstance(
              portletDataContext.getScopeGroupId(),
              ruleGroupInstance.getClassName(),
              classPK,
              ruleGroupId,
              ruleGroupInstance.getPriority(),
              serviceContext);
    }

    portletDataContext.importClassedModel(ruleGroupInstance, importedRuleGroupInstance);
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, WikiPage page)
      throws Exception {

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

    Element pageElement = portletDataContext.getImportDataStagedModelElement(page);

    String content =
        _wikiPageExportImportContentProcessor.replaceImportContentReferences(
            portletDataContext, page, page.getContent());

    page.setContent(content);

    ServiceContext serviceContext = portletDataContext.createServiceContext(page);

    serviceContext.setUuid(page.getUuid());

    Map<Long, Long> nodeIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(WikiNode.class);

    long nodeId = MapUtil.getLong(nodeIds, page.getNodeId(), page.getNodeId());

    WikiPage importedPage = null;

    WikiPage existingPage = _wikiPageLocalService.fetchPage(nodeId, page.getTitle());

    if (existingPage == null) {
      importedPage =
          _wikiPageLocalService.addPage(
              userId,
              nodeId,
              page.getTitle(),
              page.getVersion(),
              page.getContent(),
              page.getSummary(),
              page.isMinorEdit(),
              page.getFormat(),
              page.getHead(),
              page.getParentTitle(),
              page.getRedirectTitle(),
              serviceContext);

      WikiPageResource pageResource =
          _wikiPageResourceLocalService.getPageResource(importedPage.getResourcePrimKey());

      String pageResourceUuid =
          GetterUtil.getString(pageElement.attributeValue("page-resource-uuid"));

      if (Validator.isNotNull(pageResourceUuid)) {
        pageResource.setUuid(pageElement.attributeValue("page-resource-uuid"));

        _wikiPageResourceLocalService.updateWikiPageResource(pageResource);
      }
    } else {
      existingPage =
          fetchStagedModelByUuidAndGroupId(page.getUuid(), portletDataContext.getScopeGroupId());

      if (existingPage == null) {
        existingPage = _wikiPageLocalService.fetchPage(nodeId, page.getTitle(), page.getVersion());
      }

      if (existingPage == null) {
        importedPage =
            _wikiPageLocalService.updatePage(
                userId,
                nodeId,
                page.getTitle(),
                0.0,
                page.getContent(),
                page.getSummary(),
                page.isMinorEdit(),
                page.getFormat(),
                page.getParentTitle(),
                page.getRedirectTitle(),
                serviceContext);
      } else {
        importedPage = existingPage;
      }
    }

    if (page.isHead()) {
      List<Element> attachmentElements =
          portletDataContext.getReferenceDataElements(
              pageElement, DLFileEntry.class, PortletDataContext.REFERENCE_TYPE_WEAK);

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

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

        InputStream inputStream = null;

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

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

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

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

            continue;
          }

          _wikiPageLocalService.addPageAttachment(
              userId,
              importedPage.getNodeId(),
              importedPage.getTitle(),
              fileEntry.getTitle(),
              inputStream,
              null);
        } finally {
          StreamUtil.cleanUp(inputStream);
        }
      }
    }

    portletDataContext.importClassedModel(page, importedPage);

    Map<Long, Long> pageIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(WikiPage.class + ".pageId");

    pageIds.put(page.getPageId(), importedPage.getPageId());
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, Calendar calendar)
      throws Exception {

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

    Map<Long, Long> calendarResourceIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(CalendarResource.class);

    long calendarResourceId =
        MapUtil.getLong(
            calendarResourceIds,
            calendar.getCalendarResourceId(),
            calendar.getCalendarResourceId());

    Map<Locale, String> calendarNameMap = getCalendarNameMap(portletDataContext, calendar);

    ServiceContext serviceContext = portletDataContext.createServiceContext(calendar);

    Calendar importedCalendar = null;

    if (portletDataContext.isDataStrategyMirror()) {
      Calendar existingCalendar =
          fetchStagedModelByUuidAndGroupId(
              calendar.getUuid(), portletDataContext.getScopeGroupId());

      if (existingCalendar == null) {
        serviceContext.setUuid(calendar.getUuid());

        importedCalendar =
            _calendarLocalService.addCalendar(
                userId,
                portletDataContext.getScopeGroupId(),
                calendarResourceId,
                calendarNameMap,
                calendar.getDescriptionMap(),
                calendar.getTimeZoneId(),
                calendar.getColor(),
                calendar.isDefaultCalendar(),
                calendar.isEnableComments(),
                calendar.isEnableRatings(),
                serviceContext);
      } else {
        importedCalendar =
            _calendarLocalService.updateCalendar(
                existingCalendar.getCalendarId(),
                calendar.getNameMap(),
                calendar.getDescriptionMap(),
                calendar.getTimeZoneId(),
                calendar.getColor(),
                calendar.isDefaultCalendar(),
                calendar.isEnableComments(),
                calendar.isEnableRatings(),
                serviceContext);
      }
    } else {
      importedCalendar =
          _calendarLocalService.addCalendar(
              userId,
              portletDataContext.getScopeGroupId(),
              calendarResourceId,
              calendarNameMap,
              calendar.getDescriptionMap(),
              calendar.getTimeZoneId(),
              calendar.getColor(),
              calendar.isDefaultCalendar(),
              calendar.isEnableComments(),
              calendar.isEnableRatings(),
              serviceContext);
    }

    portletDataContext.importClassedModel(calendar, importedCalendar);
  }