protected void deletePortletData(PortletDataContext portletDataContext) throws Exception {

    long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT;
    int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT;

    PortletPreferences portletPreferences =
        PortletPreferencesUtil.fetchByO_O_P_P(
            ownerId, ownerType, portletDataContext.getPlid(), portletDataContext.getPortletId());

    if (portletPreferences == null) {
      portletPreferences = new com.liferay.portal.model.impl.PortletPreferencesImpl();
    }

    String xml = deletePortletData(portletDataContext, portletPreferences);

    if (xml != null) {
      PortletPreferencesLocalServiceUtil.updatePreferences(
          ownerId, ownerType, portletDataContext.getPlid(), portletDataContext.getPortletId(), xml);
    }
  }
  @Override
  public PortletPreferences processExportPortletPreferences(
      PortletDataContext portletDataContext, PortletPreferences portletPreferences)
      throws PortletDataException {

    try {
      return updateExportPortletPreferences(
          portletDataContext, portletDataContext.getPortletId(), portletPreferences);
    } catch (Exception e) {
      throw new PortletDataException("Unable to update portlet preferences during export", e);
    }
  }
  protected void populateDeletionStagedModelTypes(PortletDataContext portletDataContext)
      throws Exception {

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

    if ((portlet == null) || !portlet.isActive() || portlet.isUndeployedPortlet()) {

      return;
    }

    PortletDataHandler portletDataHandler = portlet.getPortletDataHandlerInstance();

    if (portletDataHandler == null) {
      return;
    }

    portletDataContext.addDeletionSystemEventStagedModelTypes(
        portletDataHandler.getDeletionSystemEventStagedModelTypes());
  }
  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);
      }
    }
  }
  protected void doImportPortletInfo(PortletDataContext portletDataContext, long userId)
      throws Exception {

    Map<String, String[]> parameterMap = portletDataContext.getParameterMap();

    boolean importPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (serviceContext == null) {
      serviceContext = new ServiceContext();

      serviceContext.setCompanyId(portletDataContext.getCompanyId());
      serviceContext.setSignedIn(false);
      serviceContext.setUserId(userId);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

    // LAR validation

    validateFile(
        portletDataContext.getCompanyId(),
        portletDataContext.getGroupId(),
        portletDataContext.getPortletId(),
        portletDataContext.getZipReader());

    // Source and target group id

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

    groupIds.put(portletDataContext.getSourceGroupId(), portletDataContext.getGroupId());

    // Manifest

    ManifestSummary manifestSummary = ExportImportHelperUtil.getManifestSummary(portletDataContext);

    if (BackgroundTaskThreadLocal.hasBackgroundTask()) {
      PortletDataHandlerStatusMessageSenderUtil.sendStatusMessage(
          "portlet", portletDataContext.getPortletId(), manifestSummary);
    }

    portletDataContext.setManifestSummary(manifestSummary);

    // Read expando tables, locks and permissions to make them
    // available to the data handlers through the portlet data context

    Element rootElement = portletDataContext.getImportDataRootElement();

    Element portletElement = null;

    try {
      portletElement = rootElement.element("portlet");

      Document portletDocument =
          SAXReaderUtil.read(
              portletDataContext.getZipEntryAsString(portletElement.attributeValue("path")));

      portletElement = portletDocument.getRootElement();
    } catch (DocumentException de) {
      throw new SystemException(de);
    }

    LayoutCache layoutCache = new LayoutCache();

    if (importPermissions) {
      _permissionImporter.checkRoles(
          layoutCache,
          portletDataContext.getCompanyId(),
          portletDataContext.getGroupId(),
          userId,
          portletElement);

      _permissionImporter.readPortletDataPermissions(portletDataContext);
    }

    readExpandoTables(portletDataContext);
    readLocks(portletDataContext);

    Element portletDataElement = portletElement.element("portlet-data");

    Map<String, Boolean> importPortletControlsMap =
        ExportImportHelperUtil.getImportPortletControlsMap(
            portletDataContext.getCompanyId(),
            portletDataContext.getPortletId(),
            parameterMap,
            portletDataElement,
            manifestSummary);

    Layout layout = LayoutLocalServiceUtil.getLayout(portletDataContext.getPlid());

    try {

      // Portlet preferences

      importPortletPreferences(
          portletDataContext,
          layout.getCompanyId(),
          portletDataContext.getGroupId(),
          layout,
          portletElement,
          true,
          importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS),
          importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA),
          importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP),
          importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_USER_PREFERENCES));

      // Portlet data

      if (importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA)) {

        if (_log.isDebugEnabled()) {
          _log.debug("Importing portlet data");
        }

        importPortletData(portletDataContext, portletDataElement);
      }
    } finally {
      resetPortletScope(portletDataContext, portletDataContext.getGroupId());
    }

    // Portlet permissions

    if (importPermissions) {
      if (_log.isDebugEnabled()) {
        _log.debug("Importing portlet permissions");
      }

      _permissionImporter.importPortletPermissions(
          layoutCache,
          portletDataContext.getCompanyId(),
          portletDataContext.getGroupId(),
          userId,
          layout,
          portletElement,
          portletDataContext.getPortletId());

      if (userId > 0) {
        Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);

        User user = UserLocalServiceUtil.fetchUser(userId);

        indexer.reindex(user);
      }
    }

    // Asset links

    if (_log.isDebugEnabled()) {
      _log.debug("Importing asset links");
    }

    readAssetLinks(portletDataContext);

    // Deletion system events

    _deletionSystemEventImporter.importDeletionSystemEvents(portletDataContext);

    if (_log.isInfoEnabled()) {
      _log.info("Importing portlet takes " + stopWatch.getTime() + " ms");
    }

    // Service portlet preferences

    boolean importPortletSetup = importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP);

    if (importPortletSetup) {
      try {
        List<Element> serviceElements = rootElement.elements("service");

        for (Element serviceElement : serviceElements) {
          Document serviceDocument =
              SAXReaderUtil.read(
                  portletDataContext.getZipEntryAsString(serviceElement.attributeValue("path")));

          importServicePortletPreferences(portletDataContext, serviceDocument.getRootElement());
        }
      } catch (DocumentException de) {
        throw new SystemException(de);
      }
    }

    ZipReader zipReader = portletDataContext.getZipReader();

    zipReader.close();
  }
  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);
  }
  public String importPortletData(
      PortletDataContext portletDataContext,
      PortletPreferences portletPreferences,
      Element portletDataElement)
      throws Exception {

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

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

      return null;
    }

    PortletDataHandler portletDataHandler = portlet.getPortletDataHandlerInstance();

    if ((portletDataHandler == null) || portletDataHandler.isDataPortletInstanceLevel()) {

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

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

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

      return null;
    }

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

    PortletPreferencesImpl portletPreferencesImpl = null;

    if (portletPreferences != null) {
      portletPreferencesImpl =
          (PortletPreferencesImpl)
              PortletPreferencesFactoryUtil.fromDefaultXML(portletPreferences.getPreferences());
    }

    String portletData =
        portletDataContext.getZipEntryAsString(portletDataElement.attributeValue("path"));

    if (Validator.isNull(portletData)) {
      return null;
    }

    portletPreferencesImpl =
        (PortletPreferencesImpl)
            portletDataHandler.importData(
                portletDataContext,
                portletDataContext.getPortletId(),
                portletPreferencesImpl,
                portletData);

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

    return PortletPreferencesFactoryUtil.toXML(portletPreferencesImpl);
  }