@Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, Website website)
      throws Exception {

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

    ServiceContext serviceContext = portletDataContext.createServiceContext(website);

    Website existingWebsite =
        _websiteLocalService.fetchWebsiteByUuidAndCompanyId(
            website.getUuid(), portletDataContext.getCompanyGroupId());

    Website importedWebsite = null;

    if (existingWebsite == null) {
      serviceContext.setUuid(website.getUuid());

      importedWebsite =
          _websiteLocalService.addWebsite(
              userId,
              website.getClassName(),
              website.getClassPK(),
              website.getUrl(),
              website.getTypeId(),
              website.isPrimary(),
              serviceContext);
    } else {
      importedWebsite =
          _websiteLocalService.updateWebsite(
              existingWebsite.getWebsiteId(), website.getUrl(),
              website.getTypeId(), website.isPrimary());
    }

    portletDataContext.importClassedModel(website, importedWebsite);
  }
  @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 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, 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,
      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, Layout layout)
      throws Exception {

    long groupId = portletDataContext.getGroupId();
    long userId = portletDataContext.getUserId(layout.getUserUuid());

    Element layoutElement = portletDataContext.getImportDataStagedModelElement(layout);

    String layoutUuid = GetterUtil.getString(layoutElement.attributeValue("layout-uuid"));

    long layoutId = GetterUtil.getInteger(layoutElement.attributeValue("layout-id"));

    long oldLayoutId = layoutId;

    boolean privateLayout = portletDataContext.isPrivateLayout();

    String action = layoutElement.attributeValue(Constants.ACTION);

    if (action.equals(Constants.DELETE)) {
      Layout deletingLayout =
          _layoutLocalService.fetchLayoutByUuidAndGroupId(layoutUuid, groupId, privateLayout);

      _layoutLocalService.deleteLayout(
          deletingLayout, false, ServiceContextThreadLocal.getServiceContext());

      return;
    }

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

    Layout existingLayout = null;
    Layout importedLayout = null;

    String friendlyURL = layout.getFriendlyURL();

    String layoutsImportMode =
        MapUtil.getString(
            portletDataContext.getParameterMap(),
            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE,
            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_UUID);

    if (layoutsImportMode.equals(PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_ADD_AS_NEW)) {

      layoutId = _layoutLocalService.getNextLayoutId(groupId, privateLayout);
      friendlyURL = StringPool.SLASH + layoutId;
    } else if (layoutsImportMode.equals(
        PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_NAME)) {

      Locale locale = LocaleUtil.getSiteDefault();

      String localizedName = layout.getName(locale);

      List<Layout> previousLayouts = _layoutLocalService.getLayouts(groupId, privateLayout);

      for (Layout curLayout : previousLayouts) {
        if (localizedName.equals(curLayout.getName(locale))
            || friendlyURL.equals(curLayout.getFriendlyURL())) {

          existingLayout = curLayout;

          break;
        }
      }

      if (existingLayout == null) {
        layoutId = _layoutLocalService.getNextLayoutId(groupId, privateLayout);

        friendlyURL = getFriendlyURL(friendlyURL, layoutId);
      }
    } else if (layoutsImportMode.equals(
        PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {

      existingLayout =
          _layoutLocalService.fetchLayoutByUuidAndGroupId(layout.getUuid(), groupId, privateLayout);

      if (SitesUtil.isLayoutModifiedSinceLastMerge(existingLayout)) {
        layouts.put(oldLayoutId, existingLayout);

        return;
      }

      LayoutFriendlyURL layoutFriendlyURL =
          _layoutFriendlyURLLocalService.fetchFirstLayoutFriendlyURL(
              groupId, privateLayout, friendlyURL);

      if ((layoutFriendlyURL != null) && (existingLayout == null)) {
        Layout mergeFailFriendlyURLLayout =
            _layoutLocalService.getLayout(layoutFriendlyURL.getPlid());

        SitesUtil.addMergeFailFriendlyURLLayout(mergeFailFriendlyURLLayout);

        if (!_log.isWarnEnabled()) {
          return;
        }

        StringBundler sb = new StringBundler(6);

        sb.append("Layout with layout ID ");
        sb.append(layout.getLayoutId());
        sb.append(" cannot be propagated because the friendly URL ");
        sb.append("conflicts with the friendly URL of layout with ");
        sb.append("layout ID ");
        sb.append(mergeFailFriendlyURLLayout.getLayoutId());

        _log.warn(sb.toString());

        return;
      }
    } else {

      // The default behavior of import mode is
      // PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_UUID

      existingLayout =
          _layoutLocalService.fetchLayoutByUuidAndGroupId(layout.getUuid(), groupId, privateLayout);

      if (existingLayout == null) {
        existingLayout =
            _layoutLocalService.fetchLayoutByFriendlyURL(groupId, privateLayout, friendlyURL);
      }

      if (existingLayout == null) {
        layoutId = _layoutLocalService.getNextLayoutId(groupId, privateLayout);

        friendlyURL = getFriendlyURL(friendlyURL, layoutId);
      }
    }

    if (_log.isDebugEnabled()) {
      StringBundler sb = new StringBundler(7);

      sb.append("Layout with {groupId=");
      sb.append(groupId);
      sb.append(",privateLayout=");
      sb.append(privateLayout);
      sb.append(",layoutId=");
      sb.append(layoutId);

      if (existingLayout == null) {
        sb.append("} does not exist");

        _log.debug(sb.toString());
      } else {
        sb.append("} exists");

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

    if (existingLayout == null) {
      long plid = _counterLocalService.increment();

      importedLayout = _layoutLocalService.createLayout(plid);

      if (layoutsImportMode.equals(
          PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {

        importedLayout.setSourcePrototypeLayoutUuid(layout.getUuid());

        layoutId = _layoutLocalService.getNextLayoutId(groupId, privateLayout);

        friendlyURL = getFriendlyURL(friendlyURL, layoutId);
      } else {
        importedLayout.setCreateDate(layout.getCreateDate());
        importedLayout.setModifiedDate(layout.getModifiedDate());
        importedLayout.setLayoutPrototypeUuid(layout.getLayoutPrototypeUuid());
        importedLayout.setLayoutPrototypeLinkEnabled(layout.isLayoutPrototypeLinkEnabled());
        importedLayout.setSourcePrototypeLayoutUuid(layout.getSourcePrototypeLayoutUuid());
      }

      importedLayout.setUuid(layout.getUuid());
      importedLayout.setGroupId(groupId);
      importedLayout.setUserId(userId);
      importedLayout.setPrivateLayout(privateLayout);
      importedLayout.setLayoutId(layoutId);

      initNewLayoutPermissions(
          portletDataContext.getCompanyId(),
          groupId,
          userId,
          layout,
          importedLayout,
          privateLayout);

      LayoutSet layoutSet = _layoutSetLocalService.getLayoutSet(groupId, privateLayout);

      importedLayout.setLayoutSet(layoutSet);
    } else {
      importedLayout = existingLayout;
    }

    portletDataContext.setPlid(importedLayout.getPlid());
    portletDataContext.setOldPlid(layout.getPlid());

    long parentLayoutId = layout.getParentLayoutId();

    String parentLayoutUuid =
        GetterUtil.getString(layoutElement.attributeValue("parent-layout-uuid"));

    Element parentLayoutElement =
        portletDataContext.getReferenceDataElement(
            layout, Layout.class, layout.getGroupId(), parentLayoutUuid);

    if ((parentLayoutId != LayoutConstants.DEFAULT_PARENT_LAYOUT_ID)
        && (parentLayoutElement != null)) {

      StagedModelDataHandlerUtil.importStagedModel(portletDataContext, parentLayoutElement);

      Layout importedParentLayout = layouts.get(parentLayoutId);

      parentLayoutId = importedParentLayout.getLayoutId();
    }

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

      sb.append("Importing layout with layout id ");
      sb.append(layoutId);
      sb.append(" and parent layout id ");
      sb.append(parentLayoutId);

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

    importedLayout.setCompanyId(portletDataContext.getCompanyId());

    if (layout.getLayoutPrototypeUuid() != null) {
      importedLayout.setModifiedDate(new Date());
    }

    importedLayout.setParentLayoutId(parentLayoutId);
    importedLayout.setName(layout.getName());
    importedLayout.setTitle(layout.getTitle());
    importedLayout.setDescription(layout.getDescription());
    importedLayout.setKeywords(layout.getKeywords());
    importedLayout.setRobots(layout.getRobots());
    importedLayout.setType(layout.getType());

    String portletsMergeMode =
        MapUtil.getString(
            portletDataContext.getParameterMap(),
            PortletDataHandlerKeys.PORTLETS_MERGE_MODE,
            PortletDataHandlerKeys.PORTLETS_MERGE_MODE_REPLACE);

    if (layout.isTypePortlet()
        && Validator.isNotNull(layout.getTypeSettings())
        && !portletsMergeMode.equals(PortletDataHandlerKeys.PORTLETS_MERGE_MODE_REPLACE)) {

      mergePortlets(importedLayout, layout.getTypeSettings(), portletsMergeMode);
    } else if (layout.isTypeLinkToLayout()) {
      importLinkedLayout(portletDataContext, layout, importedLayout, layoutElement, layouts);
    } else {
      updateTypeSettings(importedLayout, layout);
    }

    importedLayout.setHidden(layout.isHidden());
    importedLayout.setFriendlyURL(
        getUniqueFriendlyURL(portletDataContext, importedLayout, friendlyURL));

    if (layout.getIconImageId() > 0) {
      importLayoutIconImage(portletDataContext, importedLayout, layoutElement);
    } else if (importedLayout.getIconImageId() > 0) {
      _imageLocalService.deleteImage(importedLayout.getIconImageId());
    }

    if (existingLayout == null) {
      int priority =
          _layoutLocalServiceHelper.getNextPriority(
              groupId, privateLayout, parentLayoutId, null, -1);

      importedLayout.setPriority(priority);
    }

    importedLayout.setLayoutPrototypeUuid(layout.getLayoutPrototypeUuid());
    importedLayout.setLayoutPrototypeLinkEnabled(layout.isLayoutPrototypeLinkEnabled());

    ServiceContext serviceContext = portletDataContext.createServiceContext(layout);

    importedLayout.setExpandoBridgeAttributes(serviceContext);

    StagingUtil.updateLastImportSettings(layoutElement, importedLayout, portletDataContext);

    fixImportTypeSettings(importedLayout);

    importTheme(portletDataContext, layout, importedLayout);

    _layoutLocalService.updateLayout(importedLayout);

    _layoutSetLocalService.updatePageCount(groupId, privateLayout);

    Map<Long, Long> layoutPlids =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(Layout.class);

    layoutPlids.put(layout.getPlid(), importedLayout.getPlid());

    layouts.put(oldLayoutId, importedLayout);

    importAssets(portletDataContext, layout, importedLayout);

    importLayoutFriendlyURLs(portletDataContext, layout, importedLayout);

    portletDataContext.importClassedModel(layout, importedLayout);
  }
  @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 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, 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);
    }
  }
  @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, 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());
  }