@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 doImportMissingReference(
      PortletDataContext portletDataContext, String uuid, long groupId, long pageId)
      throws Exception {

    WikiPage existingPage = fetchMissingReference(uuid, groupId);

    if (existingPage == null) {
      return;
    }

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

    pageIds.put(pageId, existingPage.getPageId());
  }
  @Override
  protected void doImportMissingReference(
      PortletDataContext portletDataContext, String uuid, long groupId, long calendarId)
      throws Exception {

    Calendar existingCalendar = fetchMissingReference(uuid, groupId);

    if (existingCalendar == null) {
      return;
    }

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

    calendarIds.put(calendarId, existingCalendar.getCalendarId());
  }
    protected Layout fetchImportedLayout(
        PortletDataContext portletDataContext, JSONObject jsonObject) {

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

      long layoutId = jsonObject.getLong("layoutId");

      Layout layout = layouts.get(layoutId);

      if (layout == null) {
        if (_log.isWarnEnabled()) {
          _log.warn("Unable to find layout with ID " + layoutId);
        }
      }

      return layout;
    }
    protected FileEntry fetchImportedFileEntry(
        PortletDataContext portletDataContext, JSONObject jsonObject) throws PortalException {

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

      long groupId = jsonObject.getLong("groupId");
      String uuid = jsonObject.getString("uuid");

      groupId = MapUtil.getLong(groupIds, groupId, groupId);

      if ((groupId > 0) && Validator.isNotNull(uuid)) {
        try {
          return _dlAppService.getFileEntryByUuidAndGroupId(uuid, groupId);
        } catch (NoSuchFileEntryException nsfee) {
          if (_log.isWarnEnabled()) {
            _log.warn(
                "Unable to find file entry with uuid " + uuid + " and groupId " + groupId, nsfee);
          }
        }
      }

      return null;
    }
  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);
    }

    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();
  }
  @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);
  }