@Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, AssetTag assetTag)
      throws Exception {

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

    ServiceContext serviceContext = createServiceContext(portletDataContext, assetTag);

    AssetTag existingAssetTag =
        fetchStagedModelByUuidAndGroupId(assetTag.getUuid(), portletDataContext.getScopeGroupId());

    AssetTag importedAssetTag = null;

    if (existingAssetTag == null) {
      serviceContext.setUuid(assetTag.getUuid());

      importedAssetTag =
          AssetTagLocalServiceUtil.addTag(
              userId, portletDataContext.getScopeGroupId(), assetTag.getName(), serviceContext);
    } else {
      importedAssetTag =
          AssetTagLocalServiceUtil.updateTag(
              userId, existingAssetTag.getTagId(), assetTag.getName(), serviceContext);
    }

    portletDataContext.importClassedModel(assetTag, importedAssetTag);
  }
  @Override
  protected PortletPreferences doImportData(
      PortletDataContext portletDataContext,
      String portletId,
      PortletPreferences portletPreferences,
      String data)
      throws Exception {

    portletDataContext.importPermissions(
        CalendarPermission.RESOURCE_NAME,
        portletDataContext.getSourceGroupId(),
        portletDataContext.getScopeGroupId());

    Element rootElement = portletDataContext.getImportDataRootElement();

    for (Element eventElement : rootElement.elements("event")) {
      String path = eventElement.attributeValue("path");

      if (!portletDataContext.isPathNotProcessed(path)) {
        continue;
      }

      CalEvent event = (CalEvent) portletDataContext.getZipEntryAsObject(path);

      importEvent(portletDataContext, eventElement, event);
    }

    return null;
  }
  protected void importKBArticleAttachments(
      PortletDataContext portletDataContext, KBArticle kbArticle, KBArticle importedKBArticle)
      throws Exception {

    List<Element> dlFileEntryElements =
        portletDataContext.getReferenceDataElements(kbArticle, DLFileEntry.class);

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setCompanyId(portletDataContext.getCompanyId());
    serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId());

    InputStream inputStream = null;

    for (Element dlFileEntryElement : dlFileEntryElements) {
      try {
        byte[] bytes =
            portletDataContext.getZipEntryAsByteArray(dlFileEntryElement.attributeValue("path"));

        inputStream = new UnsyncByteArrayInputStream(bytes);

        String fileName = dlFileEntryElement.attributeValue("file-name");

        String mimeType = KnowledgeBaseUtil.getMimeType(bytes, fileName);

        PortletFileRepositoryUtil.addPortletFileEntry(
            portletDataContext.getScopeGroupId(),
            portletDataContext.getUserId(importedKBArticle.getUserUuid()),
            KBArticle.class.getName(),
            importedKBArticle.getClassPK(),
            PortletKeys.KNOWLEDGE_BASE_ADMIN,
            importedKBArticle.getAttachmentsFolderId(),
            inputStream,
            fileName,
            mimeType,
            true);
      } catch (DuplicateFileException dfe) {
        continue;
      } finally {
        StreamUtil.cleanUp(inputStream);
      }
    }
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext, StagedAssetLink stagedAssetLink) throws Exception {

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

    StagedAssetLink existingStagedAssetLink =
        fetchExistingAssetLink(
            portletDataContext.getScopeGroupId(),
            stagedAssetLink.getEntry1Uuid(),
            stagedAssetLink.getEntry2Uuid());

    if (existingStagedAssetLink != null) {
      _assetLinkLocalService.updateLink(
          userId,
          existingStagedAssetLink.getEntryId1(),
          existingStagedAssetLink.getEntryId2(),
          stagedAssetLink.getType(),
          stagedAssetLink.getWeight());

      return;
    }

    AssetEntry assetEntry1 =
        _assetEntryLocalService.fetchEntry(
            portletDataContext.getScopeGroupId(), stagedAssetLink.getEntry1Uuid());
    AssetEntry assetEntry2 =
        _assetEntryLocalService.fetchEntry(
            portletDataContext.getScopeGroupId(), stagedAssetLink.getEntry2Uuid());

    if ((assetEntry1 == null) || (assetEntry2 == null)) {
      return;
    }

    _assetLinkLocalService.addLink(
        userId,
        assetEntry1.getEntryId(),
        assetEntry2.getEntryId(),
        stagedAssetLink.getType(),
        stagedAssetLink.getWeight());
  }
  @Override
  public ExportActionableDynamicQuery getExportActionableDynamicQuery(
      final PortletDataContext portletDataContext) {
    final ExportActionableDynamicQuery exportActionableDynamicQuery =
        new ExportActionableDynamicQuery() {
          @Override
          public long performCount() throws PortalException {
            ManifestSummary manifestSummary = portletDataContext.getManifestSummary();

            StagedModelType stagedModelType = getStagedModelType();

            long modelAdditionCount = super.performCount();

            manifestSummary.addModelAdditionCount(stagedModelType.toString(), modelAdditionCount);

            long modelDeletionCount =
                ExportImportHelperUtil.getModelDeletionCount(portletDataContext, stagedModelType);

            manifestSummary.addModelDeletionCount(stagedModelType.toString(), modelDeletionCount);

            return modelAdditionCount;
          }
        };

    initActionableDynamicQuery(exportActionableDynamicQuery);

    exportActionableDynamicQuery.setAddCriteriaMethod(
        new ActionableDynamicQuery.AddCriteriaMethod() {
          @Override
          public void addCriteria(DynamicQuery dynamicQuery) {
            portletDataContext.addDateRangeCriteria(dynamicQuery, "modifiedDate");
          }
        });

    exportActionableDynamicQuery.setCompanyId(portletDataContext.getCompanyId());

    exportActionableDynamicQuery.setGroupId(portletDataContext.getScopeGroupId());

    exportActionableDynamicQuery.setPerformActionMethod(
        new ActionableDynamicQuery.PerformActionMethod() {
          @Override
          public void performAction(Object object) throws PortalException {
            CalendarNotificationTemplate stagedModel = (CalendarNotificationTemplate) object;

            StagedModelDataHandlerUtil.exportStagedModel(portletDataContext, stagedModel);
          }
        });
    exportActionableDynamicQuery.setStagedModelType(
        new StagedModelType(
            PortalUtil.getClassNameId(CalendarNotificationTemplate.class.getName())));

    return exportActionableDynamicQuery;
  }
  @Override
  protected String doExportData(
      PortletDataContext portletDataContext,
      String portletId,
      PortletPreferences portletPreferences)
      throws Exception {

    portletDataContext.addPermissions(
        CalendarPermission.RESOURCE_NAME, portletDataContext.getScopeGroupId());

    Element rootElement = addExportDataRootElement(portletDataContext);

    rootElement.addAttribute("group-id", String.valueOf(portletDataContext.getScopeGroupId()));

    List<CalEvent> events = CalEventUtil.findByGroupId(portletDataContext.getScopeGroupId());

    for (CalEvent event : events) {
      exportEvent(portletDataContext, rootElement, event);
    }

    return getExportDataRootElementString(rootElement);
  }
  protected ServiceContext createServiceContext(
      PortletDataContext portletDataContext, AssetTag assetTag) {

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);
    serviceContext.setCreateDate(assetTag.getCreateDate());
    serviceContext.setModifiedDate(assetTag.getModifiedDate());
    serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId());

    return serviceContext;
  }
  @Override
  protected PortletPreferences doDeleteData(
      PortletDataContext portletDataContext,
      String portletId,
      PortletPreferences portletPreferences)
      throws Exception {

    if (portletDataContext.addPrimaryKey(CalendarPortletDataHandler.class, "deleteData")) {

      return portletPreferences;
    }

    CalEventLocalServiceUtil.deleteEvents(portletDataContext.getScopeGroupId());

    return portletPreferences;
  }
  protected void exportLayoutIconImage(
      PortletDataContext portletDataContext, Layout layout, Element layoutElement)
      throws Exception {

    Image image = _imageLocalService.getImage(layout.getIconImageId());

    if (image != null) {
      String iconPath =
          ExportImportPathUtil.getModelPath(
              portletDataContext.getScopeGroupId(), Image.class.getName(), image.getImageId());

      Element iconImagePathElement = layoutElement.addElement("icon-image-path");

      iconImagePathElement.addText(iconPath);

      portletDataContext.addZipEntry(iconPath, image.getTextObj());
    }
  }
  @Override
  protected void doRestoreStagedModel(PortletDataContext portletDataContext, BlogsEntry entry)
      throws Exception {

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

    BlogsEntry existingEntry =
        fetchStagedModelByUuidAndGroupId(entry.getUuid(), portletDataContext.getScopeGroupId());

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

    TrashHandler trashHandler = existingEntry.getTrashHandler();

    if (trashHandler.isRestorable(existingEntry.getEntryId())) {
      trashHandler.restoreTrashEntry(userId, existingEntry.getEntryId());
    }
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext, StagedAssetLink stagedAssetLink) throws Exception {

    StagedAssetLink existingStagedAssetLink =
        _stagedAssetLinkStagedModelRepository.fetchExistingAssetLink(
            portletDataContext.getScopeGroupId(),
            stagedAssetLink.getEntry1Uuid(),
            stagedAssetLink.getEntry2Uuid());

    if (existingStagedAssetLink != null) {
      _stagedAssetLinkStagedModelRepository.updateStagedModel(
          portletDataContext, existingStagedAssetLink);

      return;
    }

    _stagedAssetLinkStagedModelRepository.addStagedModel(portletDataContext, stagedAssetLink);
  }
  protected Map<Locale, String> getCalendarNameMap(
      PortletDataContext portletDataContext, Calendar calendar) throws Exception {

    String calendarName = calendar.getName(LocaleUtil.getDefault());

    Group sourceGroup = GroupLocalServiceUtil.fetchGroup(portletDataContext.getSourceGroupId());

    if ((sourceGroup == null) || !calendarName.equals(sourceGroup.getDescriptiveName())) {

      return calendar.getNameMap();
    }

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

    Group scopeGroup = GroupLocalServiceUtil.getGroup(portletDataContext.getScopeGroupId());

    calendarNameMap.put(LocaleUtil.getDefault(), scopeGroup.getName());

    return calendarNameMap;
  }
  @Override
  protected void doRestoreStagedModel(PortletDataContext portletDataContext, FileEntry fileEntry)
      throws Exception {

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

    FileEntry existingFileEntry =
        fetchStagedModelByUuidAndGroupId(fileEntry.getUuid(), portletDataContext.getScopeGroupId());

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

    TrashHandler trashHandler =
        TrashHandlerRegistryUtil.getTrashHandler(DLFileEntry.class.getName());

    if (trashHandler.isRestorable(existingFileEntry.getFileEntryId())) {
      trashHandler.restoreTrashEntry(userId, existingFileEntry.getFileEntryId());
    }
  }
  @Override
  protected String doExportData(
      final PortletDataContext portletDataContext,
      String portletId,
      PortletPreferences portletPreferences)
      throws Exception {

    Element rootElement = addExportDataRootElement(portletDataContext);

    portletDataContext.addPortletPermissions(GadgetPermission.RESOURCE_NAME);

    rootElement.addAttribute("group-id", String.valueOf(portletDataContext.getScopeGroupId()));

    ActionableDynamicQuery actionableDynamicQuery =
        GadgetLocalServiceUtil.getExportActionableDynamicQuery(portletDataContext);

    actionableDynamicQuery.performActions();

    return getExportDataRootElementString(rootElement);
  }
  @Override
  protected void validateExport(PortletDataContext portletDataContext, FileEntry fileEntry)
      throws PortletDataException {

    if ((fileEntry.getGroupId() != portletDataContext.getGroupId())
        && (fileEntry.getGroupId() != portletDataContext.getScopeGroupId())) {

      PortletDataException pde = new PortletDataException(PortletDataException.INVALID_GROUP);

      pde.setStagedModel(fileEntry);

      throw pde;
    }

    try {
      FileVersion fileVersion = fileEntry.getFileVersion();

      if (!portletDataContext.isInitialPublication()
          && !ArrayUtil.contains(getExportableStatuses(), fileVersion.getStatus())) {

        throw new PortletDataException(PortletDataException.STATUS_UNAVAILABLE);
      }
    } catch (PortletDataException pde) {
      throw pde;
    } catch (Exception e) {
      if (_log.isDebugEnabled()) {
        _log.debug(e, e);
      } else if (_log.isWarnEnabled()) {
        _log.warn("Unable to check workflow status for file entry " + fileEntry.getFileEntryId());
      }
    }

    if (fileEntry.isInTrash() || fileEntry.isInTrashContainer()) {
      PortletDataException pde = new PortletDataException(PortletDataException.STATUS_IN_TRASH);

      pde.setStagedModel(fileEntry);

      throw pde;
    }
  }
  protected void exportLinkedLayout(
      PortletDataContext portletDataContext, Layout layout, Element layoutElement)
      throws Exception {

    UnicodeProperties typeSettingsProperties = layout.getTypeSettingsProperties();

    long linkToLayoutId =
        GetterUtil.getLong(typeSettingsProperties.getProperty("linkToLayoutId", StringPool.BLANK));

    if (linkToLayoutId > 0) {
      try {
        Layout linkedToLayout =
            _layoutLocalService.getLayout(
                portletDataContext.getScopeGroupId(), layout.isPrivateLayout(), linkToLayoutId);

        StagedModelDataHandlerUtil.exportReferenceStagedModel(
            portletDataContext, layout, linkedToLayout, PortletDataContext.REFERENCE_TYPE_STRONG);

        layoutElement.addAttribute("linked-to-layout-uuid", linkedToLayout.getUuid());
      } catch (NoSuchLayoutException nsle) {
      }
    }
  }
  @Override
  public ExportActionableDynamicQuery getExportActionableDynamicQuery(
      final PortletDataContext portletDataContext) {
    final ExportActionableDynamicQuery exportActionableDynamicQuery =
        new ExportActionableDynamicQuery() {
          @Override
          public long performCount() throws PortalException {
            ManifestSummary manifestSummary = portletDataContext.getManifestSummary();

            StagedModelType stagedModelType = getStagedModelType();

            long modelAdditionCount = super.performCount();

            manifestSummary.addModelAdditionCount(stagedModelType, modelAdditionCount);

            long modelDeletionCount =
                ExportImportHelperUtil.getModelDeletionCount(portletDataContext, stagedModelType);

            manifestSummary.addModelDeletionCount(stagedModelType, modelDeletionCount);

            return modelAdditionCount;
          }
        };

    initActionableDynamicQuery(exportActionableDynamicQuery);

    exportActionableDynamicQuery.setAddCriteriaMethod(
        new ActionableDynamicQuery.AddCriteriaMethod() {
          @Override
          public void addCriteria(DynamicQuery dynamicQuery) {
            portletDataContext.addDateRangeCriteria(dynamicQuery, "modifiedDate");

            StagedModelType stagedModelType = exportActionableDynamicQuery.getStagedModelType();

            long referrerClassNameId = stagedModelType.getReferrerClassNameId();

            Property classNameIdProperty = PropertyFactoryUtil.forName("classNameId");

            if ((referrerClassNameId != StagedModelType.REFERRER_CLASS_NAME_ID_ALL)
                && (referrerClassNameId != StagedModelType.REFERRER_CLASS_NAME_ID_ANY)) {
              dynamicQuery.add(classNameIdProperty.eq(stagedModelType.getReferrerClassNameId()));
            } else if (referrerClassNameId == StagedModelType.REFERRER_CLASS_NAME_ID_ANY) {
              dynamicQuery.add(classNameIdProperty.isNotNull());
            }
          }
        });

    exportActionableDynamicQuery.setCompanyId(portletDataContext.getCompanyId());

    exportActionableDynamicQuery.setGroupId(portletDataContext.getScopeGroupId());

    exportActionableDynamicQuery.setPerformActionMethod(
        new ActionableDynamicQuery.PerformActionMethod<DDMStructure>() {
          @Override
          public void performAction(DDMStructure ddmStructure) throws PortalException {
            StagedModelDataHandlerUtil.exportStagedModel(portletDataContext, ddmStructure);
          }
        });
    exportActionableDynamicQuery.setStagedModelType(
        new StagedModelType(
            PortalUtil.getClassNameId(DDMStructure.class.getName()),
            StagedModelType.REFERRER_CLASS_NAME_ID_ALL));

    return exportActionableDynamicQuery;
  }
  protected String deletePortletData(
      PortletDataContext portletDataContext, PortletPreferences portletPreferences)
      throws Exception {

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

    if (!group.isStagedPortlet(portletDataContext.getPortletId())) {
      if (_log.isDebugEnabled()) {
        _log.debug(
            "Do not delete portlet data for "
                + portletDataContext.getPortletId()
                + " because the portlet is not staged");
      }

      return null;
    }

    Portlet portlet =
        PortletLocalServiceUtil.getPortletById(
            portletDataContext.getCompanyId(), portletDataContext.getPortletId());

    if (portlet == null) {
      if (_log.isDebugEnabled()) {
        _log.debug(
            "Do not delete portlet data for "
                + portletDataContext.getPortletId()
                + " because the portlet does not exist");
      }

      return null;
    }

    PortletDataHandler portletDataHandler = portlet.getPortletDataHandlerInstance();

    if (portletDataHandler == null) {
      if (_log.isDebugEnabled()) {
        StringBundler sb = new StringBundler(4);

        sb.append("Do not delete portlet data for ");
        sb.append(portletDataContext.getPortletId());
        sb.append(" because the portlet does not have a ");
        sb.append("PortletDataHandler");

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

      return null;
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Deleting data for " + portletDataContext.getPortletId());
    }

    PortletPreferencesImpl portletPreferencesImpl =
        (PortletPreferencesImpl)
            PortletPreferencesFactoryUtil.fromDefaultXML(portletPreferences.getPreferences());

    try {
      portletPreferencesImpl =
          (PortletPreferencesImpl)
              portletDataHandler.deleteData(
                  portletDataContext, portletDataContext.getPortletId(), portletPreferencesImpl);
    } finally {
      portletDataContext.setGroupId(portletDataContext.getScopeGroupId());
    }

    if (portletPreferencesImpl == null) {
      return null;
    }

    return PortletPreferencesFactoryUtil.toXML(portletPreferencesImpl);
  }
  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 =
              PortletItemLocalServiceUtil.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 = UserLocalServiceUtil.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 =
              PortletLocalServiceUtil.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, BlogsEntry entry)
      throws Exception {

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

    Element entryElement = portletDataContext.getImportDataStagedModelElement(entry);

    String content =
        _blogsEntryExportImportContentProcessor.replaceImportContentReferences(
            portletDataContext, entry, entry.getContent());

    entry.setContent(content);

    Calendar displayDateCal = CalendarFactoryUtil.getCalendar();

    displayDateCal.setTime(entry.getDisplayDate());

    int displayDateMonth = displayDateCal.get(Calendar.MONTH);
    int displayDateDay = displayDateCal.get(Calendar.DATE);
    int displayDateYear = displayDateCal.get(Calendar.YEAR);
    int displayDateHour = displayDateCal.get(Calendar.HOUR);
    int displayDateMinute = displayDateCal.get(Calendar.MINUTE);

    if (displayDateCal.get(Calendar.AM_PM) == Calendar.PM) {
      displayDateHour += 12;
    }

    boolean allowPingbacks = entry.isAllowPingbacks();
    boolean allowTrackbacks = entry.isAllowTrackbacks();
    String[] trackbacks = StringUtil.split(entry.getTrackbacks());

    ServiceContext serviceContext = portletDataContext.createServiceContext(entry);

    BlogsEntry importedEntry = null;

    if (portletDataContext.isDataStrategyMirror()) {
      serviceContext.setAttribute("urlTitle", entry.getUrlTitle());

      BlogsEntry existingEntry =
          fetchStagedModelByUuidAndGroupId(entry.getUuid(), portletDataContext.getScopeGroupId());

      if (existingEntry == null) {
        serviceContext.setUuid(entry.getUuid());

        importedEntry =
            _blogsEntryLocalService.addEntry(
                userId,
                entry.getTitle(),
                entry.getSubtitle(),
                entry.getDescription(),
                entry.getContent(),
                displayDateMonth,
                displayDateDay,
                displayDateYear,
                displayDateHour,
                displayDateMinute,
                allowPingbacks,
                allowTrackbacks,
                trackbacks,
                entry.getCoverImageCaption(),
                null,
                null,
                serviceContext);
      } else {
        importedEntry =
            _blogsEntryLocalService.updateEntry(
                userId,
                existingEntry.getEntryId(),
                entry.getTitle(),
                entry.getSubtitle(),
                entry.getDescription(),
                entry.getContent(),
                displayDateMonth,
                displayDateDay,
                displayDateYear,
                displayDateHour,
                displayDateMinute,
                allowPingbacks,
                allowTrackbacks,
                trackbacks,
                entry.getCoverImageCaption(),
                new ImageSelector(),
                new ImageSelector(),
                serviceContext);
      }
    } else {
      importedEntry =
          _blogsEntryLocalService.addEntry(
              userId,
              entry.getTitle(),
              entry.getSubtitle(),
              entry.getDescription(),
              entry.getContent(),
              displayDateMonth,
              displayDateDay,
              displayDateYear,
              displayDateHour,
              displayDateMinute,
              allowPingbacks,
              allowTrackbacks,
              trackbacks,
              entry.getCoverImageCaption(),
              null,
              null,
              serviceContext);
    }

    if ((entry.getCoverImageFileEntryId() == 0)
        && Validator.isNull(entry.getCoverImageURL())
        && (entry.getSmallImageFileEntryId() == 0)
        && Validator.isNull(entry.getSmallImageURL())
        && !entry.isSmallImage()) {

      portletDataContext.importClassedModel(entry, importedEntry);

      return;
    }

    // Cover image

    ImageSelector coverImageSelector = null;

    List<Element> attachmentElements =
        portletDataContext.getReferenceDataElements(
            entry, DLFileEntry.class, PortletDataContext.REFERENCE_TYPE_WEAK);

    if (Validator.isNotNull(entry.getCoverImageURL())) {
      coverImageSelector = new ImageSelector(entry.getCoverImageURL());
    } else if (entry.getCoverImageFileEntryId() != 0) {
      coverImageSelector =
          _getImageSelector(
              portletDataContext, entry.getCoverImageFileEntryId(), attachmentElements);
    }

    if (coverImageSelector != null) {
      _blogsEntryLocalService.addCoverImage(importedEntry.getEntryId(), coverImageSelector);
    }

    // Small image

    ImageSelector smallImageSelector = null;

    if (entry.isSmallImage()) {
      String smallImagePath = entryElement.attributeValue("small-image-path");

      if (Validator.isNotNull(entry.getSmallImageURL())) {
        smallImageSelector = new ImageSelector(entry.getSmallImageURL());
      } else if (Validator.isNotNull(smallImagePath)) {
        String smallImageFileName =
            entry.getSmallImageId() + StringPool.PERIOD + entry.getSmallImageType();

        InputStream inputStream = null;

        try {
          inputStream = portletDataContext.getZipEntryAsInputStream(smallImagePath);

          smallImageSelector =
              new ImageSelector(
                  FileUtil.getBytes(inputStream),
                  smallImageFileName,
                  MimeTypesUtil.getContentType(smallImageFileName),
                  null);
        } finally {
          StreamUtil.cleanUp(inputStream);
        }
      } else if (entry.getSmallImageFileEntryId() != 0) {
        smallImageSelector =
            _getImageSelector(
                portletDataContext, entry.getSmallImageFileEntryId(), attachmentElements);
      }
    }

    if (smallImageSelector != null) {
      _blogsEntryLocalService.addSmallImage(importedEntry.getEntryId(), smallImageSelector);
    }

    if ((coverImageSelector != null) || (smallImageSelector != null)) {
      importedEntry = _blogsEntryLocalService.getBlogsEntry(importedEntry.getEntryId());
    }

    portletDataContext.importClassedModel(entry, importedEntry);
  }
  protected void readAssetLinks(PortletDataContext portletDataContext) throws Exception {

    String xml =
        portletDataContext.getZipEntryAsString(
            ExportImportPathUtil.getSourceRootPath(portletDataContext) + "/links.xml");

    if (xml == null) {
      return;
    }

    Document document = SAXReaderUtil.read(xml);

    Element rootElement = document.getRootElement();

    List<Element> assetLinkGroupElements = rootElement.elements("asset-link-group");

    for (Element assetLinkGroupElement : assetLinkGroupElements) {
      String sourceUuid = assetLinkGroupElement.attributeValue("source-uuid");

      AssetEntry sourceAssetEntry =
          AssetEntryLocalServiceUtil.fetchEntry(portletDataContext.getScopeGroupId(), sourceUuid);

      if (sourceAssetEntry == null) {
        sourceAssetEntry =
            AssetEntryLocalServiceUtil.fetchEntry(
                portletDataContext.getCompanyGroupId(), sourceUuid);
      }

      if (sourceAssetEntry == null) {
        if (_log.isWarnEnabled()) {
          _log.warn("Unable to find asset entry with uuid " + sourceUuid);
        }

        continue;
      }

      List<Element> assetLinksElements = assetLinkGroupElement.elements("asset-link");

      for (Element assetLinkElement : assetLinksElements) {
        String path = assetLinkElement.attributeValue("path");

        if (!portletDataContext.isPathNotProcessed(path)) {
          continue;
        }

        String targetUuid = assetLinkElement.attributeValue("target-uuid");

        AssetEntry targetAssetEntry =
            AssetEntryLocalServiceUtil.fetchEntry(portletDataContext.getScopeGroupId(), targetUuid);

        if (targetAssetEntry == null) {
          targetAssetEntry =
              AssetEntryLocalServiceUtil.fetchEntry(
                  portletDataContext.getCompanyGroupId(), targetUuid);
        }

        if (targetAssetEntry == null) {
          if (_log.isWarnEnabled()) {
            _log.warn("Unable to find asset entry with uuid " + targetUuid);
          }

          continue;
        }

        AssetLink assetLink = (AssetLink) portletDataContext.getZipEntryAsObject(path);

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

        AssetLinkLocalServiceUtil.updateLink(
            userId,
            sourceAssetEntry.getEntryId(),
            targetAssetEntry.getEntryId(),
            assetLink.getType(),
            assetLink.getWeight());
      }
    }
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, KBArticle kbArticle)
      throws Exception {

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

    if (kbArticle.getParentResourcePrimKey() != KBFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

      if (kbArticle.getClassNameId() == kbArticle.getParentResourceClassNameId()) {

        StagedModelDataHandlerUtil.importReferenceStagedModels(
            portletDataContext, kbArticle, KBArticle.class);
      } else {
        StagedModelDataHandlerUtil.importReferenceStagedModels(
            portletDataContext, kbArticle, KBFolder.class);
      }
    }

    Map<Long, Long> kbArticleResourcePrimKeys =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(KBArticle.class);

    long parentResourcePrimKey =
        MapUtil.getLong(
            kbArticleResourcePrimKeys,
            kbArticle.getParentResourcePrimKey(),
            KBFolderConstants.DEFAULT_PARENT_FOLDER_ID);

    long resourcePrimaryKey =
        MapUtil.getLong(kbArticleResourcePrimKeys, kbArticle.getResourcePrimKey(), 0);

    if (parentResourcePrimKey == KBFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

      Map<Long, Long> kbFolderResourcePrimKeys =
          (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(KBFolder.class);

      parentResourcePrimKey =
          MapUtil.getLong(
              kbFolderResourcePrimKeys,
              kbArticle.getParentResourcePrimKey(),
              KBFolderConstants.DEFAULT_PARENT_FOLDER_ID);
    }

    String[] sections = AdminUtil.unescapeSections(kbArticle.getSections());

    ServiceContext serviceContext = portletDataContext.createServiceContext(kbArticle);

    KBArticle importedKBArticle = null;

    if (portletDataContext.isDataStrategyMirror()) {
      KBArticle existingKBArticle =
          KBArticleUtil.fetchByR_V(resourcePrimaryKey, kbArticle.getVersion());

      if (existingKBArticle == null) {
        existingKBArticle =
            fetchStagedModelByUuidAndGroupId(
                kbArticle.getUuid(), portletDataContext.getScopeGroupId());
      }

      if (existingKBArticle == null) {
        serviceContext.setUuid(kbArticle.getUuid());

        existingKBArticle =
            KBArticleLocalServiceUtil.fetchLatestKBArticle(
                resourcePrimaryKey, WorkflowConstants.STATUS_ANY);

        if (existingKBArticle == null) {
          importedKBArticle =
              KBArticleLocalServiceUtil.addKBArticle(
                  userId,
                  kbArticle.getParentResourceClassNameId(),
                  parentResourcePrimKey,
                  kbArticle.getTitle(),
                  kbArticle.getUrlTitle(),
                  kbArticle.getContent(),
                  kbArticle.getDescription(),
                  kbArticle.getSourceURL(),
                  sections,
                  null,
                  serviceContext);

          KBArticleLocalServiceUtil.updatePriority(
              importedKBArticle.getResourcePrimKey(), kbArticle.getPriority());
        } else {
          KBArticleLocalServiceUtil.updateKBArticle(
              userId,
              existingKBArticle.getResourcePrimKey(),
              kbArticle.getTitle(),
              kbArticle.getContent(),
              kbArticle.getDescription(),
              kbArticle.getSourceURL(),
              sections,
              null,
              null,
              serviceContext);

          KBArticleLocalServiceUtil.moveKBArticle(
              userId,
              existingKBArticle.getResourcePrimKey(),
              existingKBArticle.getParentResourceClassNameId(),
              parentResourcePrimKey,
              kbArticle.getPriority());

          importedKBArticle =
              KBArticleLocalServiceUtil.getLatestKBArticle(
                  existingKBArticle.getResourcePrimKey(), WorkflowConstants.STATUS_APPROVED);
        }
      } else {
        importedKBArticle = existingKBArticle;
      }
    } else {
      importedKBArticle =
          KBArticleLocalServiceUtil.addKBArticle(
              userId,
              kbArticle.getParentResourceClassNameId(),
              parentResourcePrimKey,
              kbArticle.getTitle(),
              kbArticle.getUrlTitle(),
              kbArticle.getContent(),
              kbArticle.getDescription(),
              kbArticle.getSourceURL(),
              sections,
              null,
              serviceContext);

      KBArticleLocalServiceUtil.updatePriority(
          importedKBArticle.getResourcePrimKey(), kbArticle.getPriority());
    }

    importKBArticleAttachments(portletDataContext, kbArticle, importedKBArticle);

    portletDataContext.importClassedModel(kbArticle, importedKBArticle);

    if (!kbArticle.isMain()) {
      kbArticleResourcePrimKeys.put(
          kbArticle.getResourcePrimKey(), importedKBArticle.getResourcePrimKey());
    }
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext,
      CalendarNotificationTemplate calendarNotificationTemplate)
      throws Exception {

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

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

    long calendarId =
        MapUtil.getLong(
            calendarIds,
            calendarNotificationTemplate.getCalendarId(),
            calendarNotificationTemplate.getCalendarId());

    NotificationType notificationType =
        NotificationType.parse(calendarNotificationTemplate.getNotificationType());
    NotificationTemplateType notificationTemplateType =
        NotificationTemplateType.parse(calendarNotificationTemplate.getNotificationTemplateType());

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(calendarNotificationTemplate);

    CalendarNotificationTemplate importedCalendarNotificationTemplate = null;

    String body =
        ExportImportHelperUtil.replaceImportContentReferences(
            portletDataContext,
            calendarNotificationTemplate,
            calendarNotificationTemplate.getBody());

    if (portletDataContext.isDataStrategyMirror()) {
      CalendarNotificationTemplate existingCalendarNotificationTemplate =
          fetchStagedModelByUuidAndGroupId(
              calendarNotificationTemplate.getUuid(), portletDataContext.getScopeGroupId());

      if (existingCalendarNotificationTemplate == null) {
        serviceContext.setUuid(calendarNotificationTemplate.getUuid());

        importedCalendarNotificationTemplate =
            CalendarNotificationTemplateLocalServiceUtil.addCalendarNotificationTemplate(
                userId,
                calendarId,
                notificationType,
                calendarNotificationTemplate.getNotificationTypeSettings(),
                notificationTemplateType,
                calendarNotificationTemplate.getSubject(),
                body,
                serviceContext);
      } else {
        importedCalendarNotificationTemplate =
            CalendarNotificationTemplateLocalServiceUtil.updateCalendarNotificationTemplate(
                existingCalendarNotificationTemplate.getCalendarNotificationTemplateId(),
                calendarNotificationTemplate.getNotificationTypeSettings(),
                calendarNotificationTemplate.getSubject(),
                body,
                serviceContext);
      }
    } else {
      importedCalendarNotificationTemplate =
          CalendarNotificationTemplateLocalServiceUtil.addCalendarNotificationTemplate(
              userId,
              calendarId,
              notificationType,
              calendarNotificationTemplate.getNotificationTypeSettings(),
              notificationTemplateType,
              calendarNotificationTemplate.getSubject(),
              body,
              serviceContext);
    }

    portletDataContext.importClassedModel(
        calendarNotificationTemplate, importedCalendarNotificationTemplate);
  }
  @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 =
            CalendarLocalServiceUtil.addCalendar(
                userId,
                portletDataContext.getScopeGroupId(),
                calendarResourceId,
                calendarNameMap,
                calendar.getDescriptionMap(),
                calendar.getTimeZoneId(),
                calendar.getColor(),
                calendar.isDefaultCalendar(),
                calendar.isEnableComments(),
                calendar.isEnableRatings(),
                serviceContext);
      } else {
        importedCalendar =
            CalendarLocalServiceUtil.updateCalendar(
                existingCalendar.getCalendarId(),
                calendar.getNameMap(),
                calendar.getDescriptionMap(),
                calendar.getTimeZoneId(),
                calendar.getColor(),
                calendar.isDefaultCalendar(),
                calendar.isEnableComments(),
                calendar.isEnableRatings(),
                serviceContext);
      }
    } else {
      importedCalendar =
          CalendarLocalServiceUtil.addCalendar(
              userId,
              portletDataContext.getScopeGroupId(),
              calendarResourceId,
              calendarNameMap,
              calendar.getDescriptionMap(),
              calendar.getTimeZoneId(),
              calendar.getColor(),
              calendar.isDefaultCalendar(),
              calendar.isEnableComments(),
              calendar.isEnableRatings(),
              serviceContext);
    }

    portletDataContext.importClassedModel(calendar, importedCalendar);
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext, DLFileEntryType fileEntryType) throws Exception {

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

    List<Element> ddmStructureReferenceElements =
        portletDataContext.getReferenceElements(
            fileEntryType, com.liferay.dynamic.data.mapping.model.DDMStructure.class);

    long[] ddmStructureIdsArray = new long[ddmStructureReferenceElements.size()];

    Map<Long, Long> ddmStructureIds =
        (Map<Long, Long>)
            portletDataContext.getNewPrimaryKeysMap(
                com.liferay.dynamic.data.mapping.model.DDMStructure.class);

    for (int i = 0; i < ddmStructureReferenceElements.size(); i++) {
      Element ddmStructureReferenceElement = ddmStructureReferenceElements.get(i);

      long ddmStructureId =
          GetterUtil.getLong(ddmStructureReferenceElement.attributeValue("class-pk"));

      ddmStructureIdsArray[i] = MapUtil.getLong(ddmStructureIds, ddmStructureId);
    }

    ServiceContext serviceContext = portletDataContext.createServiceContext(fileEntryType);

    DLFileEntryType importedDLFileEntryType = null;

    Element element = portletDataContext.getImportDataStagedModelElement(fileEntryType);

    boolean preloaded = GetterUtil.getBoolean(element.attributeValue("preloaded"));

    if (portletDataContext.isDataStrategyMirror()) {
      DLFileEntryType existingDLFileEntryType =
          fetchExistingFileEntryType(
              fileEntryType.getUuid(),
              portletDataContext.getScopeGroupId(),
              fileEntryType.getFileEntryTypeKey(),
              preloaded);

      if (existingDLFileEntryType == null) {
        serviceContext.setUuid(fileEntryType.getUuid());

        importedDLFileEntryType =
            DLFileEntryTypeLocalServiceUtil.addFileEntryType(
                userId,
                portletDataContext.getScopeGroupId(),
                fileEntryType.getFileEntryTypeKey(),
                fileEntryType.getNameMap(),
                fileEntryType.getDescriptionMap(),
                ddmStructureIdsArray,
                serviceContext);
      } else {
        DLFileEntryTypeLocalServiceUtil.updateFileEntryType(
            userId,
            existingDLFileEntryType.getFileEntryTypeId(),
            fileEntryType.getNameMap(),
            fileEntryType.getDescriptionMap(),
            ddmStructureIdsArray,
            serviceContext);

        importedDLFileEntryType =
            DLFileEntryTypeLocalServiceUtil.fetchDLFileEntryType(
                existingDLFileEntryType.getFileEntryTypeId());
      }
    } else {
      importedDLFileEntryType =
          DLFileEntryTypeLocalServiceUtil.addFileEntryType(
              userId,
              portletDataContext.getScopeGroupId(),
              fileEntryType.getFileEntryTypeKey(),
              fileEntryType.getNameMap(),
              fileEntryType.getDescriptionMap(),
              ddmStructureIdsArray,
              serviceContext);
    }

    portletDataContext.importClassedModel(fileEntryType, importedDLFileEntryType);

    if (preloaded) {
      return;
    }

    String importedDLFileEntryDDMStructureKey = DLUtil.getDDMStructureKey(importedDLFileEntryType);

    List<DDMStructure> importedDDMStructures = importedDLFileEntryType.getDDMStructures();

    for (DDMStructure importedDDMStructure : importedDDMStructures) {
      String ddmStructureKey = importedDDMStructure.getStructureKey();

      if (!DLUtil.isAutoGeneratedDLFileEntryTypeDDMStructureKey(ddmStructureKey)) {

        continue;
      }

      if (ddmStructureKey.equals(importedDLFileEntryDDMStructureKey)) {
        continue;
      }

      com.liferay.dynamic.data.mapping.model.DDMStructure ddmStructure =
          _ddmStructureLocalService.getDDMStructure(importedDDMStructure.getStructureId());

      ddmStructure.setStructureKey(importedDLFileEntryDDMStructureKey);

      _ddmStructureLocalService.updateDDMStructure(ddmStructure);
    }
  }
  protected void importEvent(
      PortletDataContext portletDataContext, Element eventElement, CalEvent event)
      throws Exception {

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

    Date startDate = event.getStartDate();

    int startDateMonth = 0;
    int startDateDay = 0;
    int startDateYear = 0;
    int startDateHour = 0;
    int startDateMinute = 0;

    if (startDate != null) {
      Locale locale = null;
      TimeZone timeZone = null;

      if (event.getTimeZoneSensitive()) {
        User user = UserLocalServiceUtil.getUser(userId);

        locale = user.getLocale();
        timeZone = user.getTimeZone();
      } else {
        locale = LocaleUtil.getSiteDefault();
        timeZone = TimeZoneUtil.getTimeZone(StringPool.UTC);
      }

      Calendar startCal = CalendarFactoryUtil.getCalendar(timeZone, locale);

      startCal.setTime(startDate);

      startDateMonth = startCal.get(Calendar.MONTH);
      startDateDay = startCal.get(Calendar.DATE);
      startDateYear = startCal.get(Calendar.YEAR);
      startDateHour = startCal.get(Calendar.HOUR);
      startDateMinute = startCal.get(Calendar.MINUTE);

      if (startCal.get(Calendar.AM_PM) == Calendar.PM) {
        startDateHour += 12;
      }
    }

    ServiceContext serviceContext = portletDataContext.createServiceContext(eventElement, event);

    CalEvent importedEvent = null;

    if (portletDataContext.isDataStrategyMirror()) {
      CalEvent existingEvent =
          CalEventUtil.fetchByUUID_G(event.getUuid(), portletDataContext.getScopeGroupId());

      if (existingEvent == null) {
        serviceContext.setUuid(event.getUuid());

        importedEvent =
            CalEventLocalServiceUtil.addEvent(
                userId,
                event.getTitle(),
                event.getDescription(),
                event.getLocation(),
                startDateMonth,
                startDateDay,
                startDateYear,
                startDateHour,
                startDateMinute,
                event.getDurationHour(),
                event.getDurationMinute(),
                event.isAllDay(),
                event.isTimeZoneSensitive(),
                event.getType(),
                event.getRepeating(),
                event.getRecurrenceObj(),
                event.getRemindBy(),
                event.getFirstReminder(),
                event.getSecondReminder(),
                serviceContext);
      } else {
        importedEvent =
            CalEventLocalServiceUtil.updateEvent(
                userId,
                existingEvent.getEventId(),
                event.getTitle(),
                event.getDescription(),
                event.getLocation(),
                startDateMonth,
                startDateDay,
                startDateYear,
                startDateHour,
                startDateMinute,
                event.getDurationHour(),
                event.getDurationMinute(),
                event.isAllDay(),
                event.isTimeZoneSensitive(),
                event.getType(),
                event.getRepeating(),
                event.getRecurrenceObj(),
                event.getRemindBy(),
                event.getFirstReminder(),
                event.getSecondReminder(),
                serviceContext);
      }
    } else {
      importedEvent =
          CalEventLocalServiceUtil.addEvent(
              userId,
              event.getTitle(),
              event.getDescription(),
              event.getLocation(),
              startDateMonth,
              startDateDay,
              startDateYear,
              startDateHour,
              startDateMinute,
              event.getDurationHour(),
              event.getDurationMinute(),
              event.isAllDay(),
              event.isTimeZoneSensitive(),
              event.getType(),
              event.getRepeating(),
              event.getRecurrenceObj(),
              event.getRemindBy(),
              event.getFirstReminder(),
              event.getSecondReminder(),
              serviceContext);
    }

    portletDataContext.importClassedModel(event, importedEvent);
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, FileEntry fileEntry)
      throws Exception {

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

    if (!fileEntry.isDefaultRepository()) {

      // References has been automatically imported, nothing to do here

      return;
    }

    Map<Long, Long> folderIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(Folder.class);

    long folderId = MapUtil.getLong(folderIds, fileEntry.getFolderId(), fileEntry.getFolderId());

    long[] assetCategoryIds =
        portletDataContext.getAssetCategoryIds(DLFileEntry.class, fileEntry.getFileEntryId());
    String[] assetTagNames =
        portletDataContext.getAssetTagNames(DLFileEntry.class, fileEntry.getFileEntryId());

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(fileEntry, DLFileEntry.class);

    serviceContext.setAttribute("sourceFileName", "A." + fileEntry.getExtension());
    serviceContext.setUserId(userId);

    Element fileEntryElement = portletDataContext.getImportDataElement(fileEntry);

    String binPath = fileEntryElement.attributeValue("bin-path");

    InputStream is = null;

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

      try {
        is = FileEntryUtil.getContentStream(fileEntry);
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn("Unable to retrieve content for file entry " + fileEntry.getFileEntryId(), e);
        }

        return;
      }
    } else {
      is = portletDataContext.getZipEntryAsInputStream(binPath);
    }

    if (is == null) {
      if (_log.isWarnEnabled()) {
        _log.warn("No file found for file entry " + fileEntry.getFileEntryId());
      }

      return;
    }

    importMetaData(portletDataContext, fileEntryElement, fileEntry, serviceContext);

    FileEntry importedFileEntry = null;

    String titleWithExtension = DLUtil.getTitleWithExtension(fileEntry);
    String extension = fileEntry.getExtension();

    String periodAndExtension = StringPool.PERIOD.concat(extension);

    if (portletDataContext.isDataStrategyMirror()) {
      FileEntry existingFileEntry =
          fetchStagedModelByUuidAndGroupId(
              fileEntry.getUuid(), portletDataContext.getScopeGroupId());

      FileVersion fileVersion = fileEntry.getFileVersion();

      if (existingFileEntry == null) {
        String fileEntryTitle = fileEntry.getTitle();

        FileEntry existingTitleFileEntry =
            FileEntryUtil.fetchByR_F_T(
                portletDataContext.getScopeGroupId(), folderId, fileEntryTitle);

        if (existingTitleFileEntry != null) {
          if ((fileEntry.getGroupId() == portletDataContext.getSourceGroupId())
              && portletDataContext.isDataStrategyMirrorWithOverwriting()) {

            DLAppLocalServiceUtil.deleteFileEntry(existingTitleFileEntry.getFileEntryId());
          } else {
            boolean titleHasExtension = false;

            if (fileEntryTitle.endsWith(periodAndExtension)) {
              fileEntryTitle = FileUtil.stripExtension(fileEntryTitle);

              titleHasExtension = true;
            }

            for (int i = 1; ; i++) {
              fileEntryTitle += StringPool.SPACE + i;

              titleWithExtension = fileEntryTitle + periodAndExtension;

              existingTitleFileEntry =
                  FileEntryUtil.fetchByR_F_T(
                      portletDataContext.getScopeGroupId(), folderId, titleWithExtension);

              if (existingTitleFileEntry == null) {
                if (titleHasExtension) {
                  fileEntryTitle += periodAndExtension;
                }

                break;
              }
            }
          }
        }

        serviceContext.setAttribute("fileVersionUuid", fileVersion.getUuid());
        serviceContext.setUuid(fileEntry.getUuid());

        importedFileEntry =
            DLAppLocalServiceUtil.addFileEntry(
                userId,
                portletDataContext.getScopeGroupId(),
                folderId,
                titleWithExtension,
                fileEntry.getMimeType(),
                fileEntryTitle,
                fileEntry.getDescription(),
                null,
                is,
                fileEntry.getSize(),
                serviceContext);

        if (fileEntry.isInTrash()) {
          importedFileEntry =
              DLAppServiceUtil.moveFileEntryToTrash(importedFileEntry.getFileEntryId());
        }
      } else {
        FileVersion latestExistingFileVersion = existingFileEntry.getLatestFileVersion(true);

        boolean indexEnabled = serviceContext.isIndexingEnabled();

        boolean deleteFileEntry = false;
        boolean updateFileEntry = false;

        if (!Validator.equals(fileVersion.getUuid(), latestExistingFileVersion.getUuid())) {

          deleteFileEntry = true;
          updateFileEntry = true;
        } else {
          InputStream existingFileVersionInputStream = null;

          try {
            existingFileVersionInputStream = latestExistingFileVersion.getContentStream(false);
          } catch (Exception e) {
            if (_log.isDebugEnabled()) {
              _log.debug(e, e);
            }
          } finally {
            if (existingFileVersionInputStream != null) {
              existingFileVersionInputStream.close();
            }
          }

          if (existingFileVersionInputStream == null) {
            updateFileEntry = true;
          }
        }

        try {
          serviceContext.setIndexingEnabled(false);

          if (updateFileEntry) {
            DLFileVersion alreadyExistingFileVersion =
                DLFileVersionLocalServiceUtil.getFileVersionByUuidAndGroupId(
                    fileVersion.getUuid(), existingFileEntry.getGroupId());

            if (alreadyExistingFileVersion != null) {
              serviceContext.setAttribute(
                  "existingDLFileVersionId", alreadyExistingFileVersion.getFileVersionId());
            }

            serviceContext.setUuid(fileVersion.getUuid());

            importedFileEntry =
                DLAppLocalServiceUtil.updateFileEntry(
                    userId,
                    existingFileEntry.getFileEntryId(),
                    titleWithExtension,
                    fileEntry.getMimeType(),
                    fileEntry.getTitle(),
                    fileEntry.getDescription(),
                    null,
                    false,
                    is,
                    fileEntry.getSize(),
                    serviceContext);
          } else {
            DLAppLocalServiceUtil.updateAsset(
                userId, existingFileEntry,
                latestExistingFileVersion, assetCategoryIds,
                assetTagNames, null);

            importedFileEntry = existingFileEntry;
          }

          if (importedFileEntry.getFolderId() != folderId) {
            importedFileEntry =
                DLAppLocalServiceUtil.moveFileEntry(
                    userId, importedFileEntry.getFileEntryId(), folderId, serviceContext);
          }

          if (importedFileEntry instanceof LiferayFileEntry) {
            LiferayFileEntry liferayFileEntry = (LiferayFileEntry) importedFileEntry;

            Indexer<DLFileEntry> indexer =
                IndexerRegistryUtil.nullSafeGetIndexer(DLFileEntry.class);

            indexer.reindex((DLFileEntry) liferayFileEntry.getModel());
          }

          if (deleteFileEntry && ExportImportThreadLocal.isStagingInProcess()) {

            DLAppServiceUtil.deleteFileVersion(
                latestExistingFileVersion.getFileEntryId(), latestExistingFileVersion.getVersion());
          }
        } finally {
          serviceContext.setIndexingEnabled(indexEnabled);
        }
      }
    } else {
      try {
        importedFileEntry =
            DLAppLocalServiceUtil.addFileEntry(
                userId,
                portletDataContext.getScopeGroupId(),
                folderId,
                titleWithExtension,
                fileEntry.getMimeType(),
                fileEntry.getTitle(),
                fileEntry.getDescription(),
                null,
                is,
                fileEntry.getSize(),
                serviceContext);
      } catch (DuplicateFileException dfe) {
        String title = fileEntry.getTitle();

        String[] titleParts = title.split("\\.", 2);

        title = titleParts[0] + StringUtil.randomString();

        if (titleParts.length > 1) {
          title += StringPool.PERIOD + titleParts[1];
        }

        if (!title.endsWith(periodAndExtension)) {
          title += periodAndExtension;
        }

        importedFileEntry =
            DLAppLocalServiceUtil.addFileEntry(
                userId,
                portletDataContext.getScopeGroupId(),
                folderId,
                title,
                fileEntry.getMimeType(),
                title,
                fileEntry.getDescription(),
                null,
                is,
                fileEntry.getSize(),
                serviceContext);
      }
    }

    if (portletDataContext.getBooleanParameter(
        DLPortletDataHandler.NAMESPACE, "previews-and-thumbnails")) {

      DLProcessorRegistryUtil.importGeneratedFiles(
          portletDataContext, fileEntry, importedFileEntry, fileEntryElement);
    }

    portletDataContext.importClassedModel(fileEntry, importedFileEntry, DLFileEntry.class);

    Map<Long, Long> fileEntryIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(FileEntry.class);

    fileEntryIds.put(fileEntry.getFileEntryId(), importedFileEntry.getFileEntryId());
  }