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