@Override
  public void importDataDeletions(ExportImportConfiguration exportImportConfiguration, File file)
      throws Exception {

    ZipReader zipReader = null;

    try {

      // LAR validation

      ExportImportThreadLocal.setPortletDataDeletionImportInProcess(true);

      Map<String, Serializable> settingsMap = exportImportConfiguration.getSettingsMap();

      Map<String, String[]> parameterMap = (Map<String, String[]>) settingsMap.get("parameterMap");
      String portletId = MapUtil.getString(settingsMap, "portletId");
      long targetPlid = MapUtil.getLong(settingsMap, "targetPlid");
      long targetGroupId = MapUtil.getLong(settingsMap, "targetGroupId");

      Layout layout = LayoutLocalServiceUtil.getLayout(targetPlid);

      zipReader = ZipReaderFactoryUtil.getZipReader(file);

      validateFile(layout.getCompanyId(), targetGroupId, portletId, zipReader);

      PortletDataContext portletDataContext =
          getPortletDataContext(exportImportConfiguration, file);

      boolean deletePortletData =
          MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.DELETE_PORTLET_DATA);

      // Portlet data deletion

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

        deletePortletData(portletDataContext);
      }

      // Deletion system events

      populateDeletionStagedModelTypes(portletDataContext);

      _deletionSystemEventImporter.importDeletionSystemEvents(portletDataContext);
    } finally {
      ExportImportThreadLocal.setPortletDataDeletionImportInProcess(false);

      if (zipReader != null) {
        zipReader.close();
      }
    }
  }
  /**
   * Records an activity in the database, using a time based on the current time in an attempt to
   * make the activity's time unique.
   *
   * @param userId the primary key of the acting user
   * @param groupId the primary key of the group
   * @param className the target asset's class name
   * @param classPK the primary key of the target asset
   * @param type the activity's type
   * @param extraData any extra data regarding the activity
   * @param receiverUserId the primary key of the receiving user
   * @throws PortalException if the user or group could not be found
   */
  @Override
  public void addActivity(
      long userId,
      long groupId,
      String className,
      long classPK,
      int type,
      String extraData,
      long receiverUserId)
      throws PortalException {

    if (ExportImportThreadLocal.isImportInProcess()) {
      return;
    }

    Date createDate = new Date();

    long classNameId = classNameLocalService.getClassNameId(className);

    while (true) {
      SocialActivity socialActivity =
          socialActivityPersistence.fetchByG_U_CD_C_C_T_R(
              groupId, userId, createDate.getTime(), classNameId, classPK, type, receiverUserId);

      if (socialActivity != null) {
        createDate = new Date(createDate.getTime() + 1);
      } else {
        break;
      }
    }

    addActivity(userId, groupId, createDate, className, classPK, type, extraData, receiverUserId);
  }
  protected int getProcessFlag() {
    if (ExportImportThreadLocal.isPortletStagingInProcess()) {
      return PROCESS_FLAG_PORTLET_STAGING_IN_PROCESS;
    }

    return PROCESS_FLAG_PORTLET_IMPORT_IN_PROCESS;
  }
  @Override
  public MissingReferences validateFile(
      ExportImportConfiguration exportImportConfiguration, File file) throws Exception {

    ZipReader zipReader = null;

    try {
      ExportImportThreadLocal.setPortletValidationInProcess(true);

      Map<String, Serializable> settingsMap = exportImportConfiguration.getSettingsMap();

      String portletId = MapUtil.getString(settingsMap, "portletId");
      long targetGroupId = MapUtil.getLong(settingsMap, "targetGroupId");
      long targetPlid = MapUtil.getLong(settingsMap, "targetPlid");

      Layout layout = LayoutLocalServiceUtil.getLayout(targetPlid);

      zipReader = ZipReaderFactoryUtil.getZipReader(file);

      validateFile(layout.getCompanyId(), targetGroupId, portletId, zipReader);

      PortletDataContext portletDataContext =
          getPortletDataContext(exportImportConfiguration, file);

      MissingReferences missingReferences =
          ExportImportHelperUtil.validateMissingReferences(portletDataContext);

      Map<String, MissingReference> dependencyMissingReferences =
          missingReferences.getDependencyMissingReferences();

      if (!dependencyMissingReferences.isEmpty()) {
        throw new MissingReferenceException(missingReferences);
      }

      return missingReferences;
    } finally {
      ExportImportThreadLocal.setPortletValidationInProcess(false);

      if (zipReader != null) {
        zipReader.close();
      }
    }
  }
  public static void clearResourceBlockCache(long companyId, long groupId, String name) {

    if (ExportImportThreadLocal.isImportInProcess()
        || !PermissionThreadLocal.isFlushResourceBlockEnabled(companyId, groupId, name)) {

      return;
    }

    _resourceBlockIdsBagCacheIndexer.removeKeys(
        ResourceBlockIdsBagKeyIndexEncoder.encode(companyId, groupId, name));
  }
  public static void clearCache() {
    if (ExportImportThreadLocal.isImportInProcess()) {
      return;
    }

    _userRolePortalCache.removeAll();
    _permissionCheckerBagPortalCache.removeAll();
    _permissionPortalCache.removeAll();
    _resourceBlockIdsBagCache.removeAll();
    _userPermissionCheckerBagPortalCache.removeAll();
  }
  @Override
  public void importFile(ExportImportConfiguration exportImportConfiguration, File file)
      throws Exception {

    PortletDataContext portletDataContext = null;

    try {
      ExportImportThreadLocal.setPortletImportInProcess(true);

      portletDataContext = getPortletDataContext(exportImportConfiguration, file);

      _exportImportLifecycleManager.fireExportImportLifecycleEvent(
          EVENT_PORTLET_IMPORT_STARTED,
          getProcessFlag(),
          PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext));

      Map<String, Serializable> settingsMap = exportImportConfiguration.getSettingsMap();

      long userId = MapUtil.getLong(settingsMap, "userId");

      doImportPortletInfo(portletDataContext, userId);

      ExportImportThreadLocal.setPortletImportInProcess(false);

      _exportImportLifecycleManager.fireExportImportLifecycleEvent(
          EVENT_PORTLET_IMPORT_SUCCEEDED,
          getProcessFlag(),
          PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext),
          userId);
    } catch (Throwable t) {
      ExportImportThreadLocal.setPortletImportInProcess(false);

      _exportImportLifecycleManager.fireExportImportLifecycleEvent(
          EVENT_PORTLET_IMPORT_FAILED,
          getProcessFlag(),
          PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext),
          t);

      throw t;
    }
  }
  public static void clearCache(long... userIds) {
    if (ExportImportThreadLocal.isImportInProcess()) {
      return;
    }

    for (long userId : userIds) {
      _userPermissionCheckerBagPortalCache.remove(userId);

      _permissionCheckerBagPortalCacheIndexer.removeKeys(userId);
      _userRolePortalCacheIndexer.removeKeys(userId);
    }

    _permissionPortalCache.removeAll();
    _resourceBlockIdsBagCache.removeAll();
  }
  @BufferedIncrement(configuration = "MBThread", incrementClass = NumberIncrement.class)
  @Override
  public void incrementViewCounter(long threadId, int increment) throws PortalException {

    if (ExportImportThreadLocal.isImportInProcess()) {
      return;
    }

    MBThread thread = mbThreadPersistence.findByPrimaryKey(threadId);

    thread.setModifiedDate(thread.getModifiedDate());
    thread.setViewCount(thread.getViewCount() + increment);

    mbThreadPersistence.update(thread);
  }
  public static void clearResourcePermissionCache(int scope, String name, String primKey) {

    if (ExportImportThreadLocal.isImportInProcess()
        || !PermissionThreadLocal.isFlushResourcePermissionEnabled(name, primKey)) {

      return;
    }

    if (scope == ResourceConstants.SCOPE_INDIVIDUAL) {
      _permissionPortalCacheNamePrimKeyIndexer.removeKeys(
          PermissionKeyNamePrimKeyIndexEncoder.encode(name, primKey));
    } else if (scope == ResourceConstants.SCOPE_GROUP) {
      _permissionPortalCacheGroupIdIndexer.removeKeys(Long.valueOf(primKey));
    } else {
      _permissionPortalCache.removeAll();
    }
  }
  @Async
  @Override
  public void addActivity(SocialActivity activity, SocialActivity mirrorActivity)
      throws PortalException {

    if (ExportImportThreadLocal.isImportInProcess()) {
      return;
    }

    if ((activity.getActivityId() > 0)
        || ((mirrorActivity != null) && (mirrorActivity.getActivityId() > 0))) {

      throw new PortalException("Activity and mirror activity must not have primary keys set");
    }

    if (isLogActivity(activity)) {
      long activityId = counterLocalService.increment(SocialActivity.class.getName());

      activity.setActivityId(activityId);

      socialActivityPersistence.update(activity);

      if (mirrorActivity != null) {
        long mirrorActivityId = counterLocalService.increment(SocialActivity.class.getName());

        mirrorActivity.setActivityId(mirrorActivityId);
        mirrorActivity.setMirrorActivityId(activity.getPrimaryKey());

        socialActivityPersistence.update(mirrorActivity);
      }

      if (PropsValues.SOCIAL_ACTIVITY_SETS_ENABLED) {
        socialActivityInterpreterLocalService.updateActivitySet(activity.getActivityId());
      }
    }

    socialActivityCounterLocalService.addActivityCounters(activity);
  }
 public static void clearResourceCache() {
   if (!ExportImportThreadLocal.isImportInProcess()) {
     _resourceBlockIdsBagCache.removeAll();
     _permissionPortalCache.removeAll();
   }
 }
  /**
   * Records an activity with the given time in the database.
   *
   * <p>This method records a social activity done on an asset, identified by its class name and
   * class primary key, in the database. Additional information (such as the original message ID for
   * a reply to a forum post) is passed in via the <code>extraData</code> in JSON format. For
   * activities affecting another user, a mirror activity is generated that describes the action
   * from the user's point of view. The target user's ID is passed in via the <code>receiverUserId
   * </code>.
   *
   * <p>Example for a mirrored activity:<br>
   * When a user replies to a message boards post, the reply action is stored in the database with
   * the <code>receiverUserId</code> being the ID of the author of the original message. The <code>
   * extraData</code> contains the ID of the original message in JSON format. A mirror activity is
   * generated with the values of the <code>userId</code> and the <code>receiverUserId</code>
   * swapped. This mirror activity basically describes a "replied to" event.
   *
   * <p>Mirror activities are most often used in relation to friend requests and activities.
   *
   * @param userId the primary key of the acting user
   * @param groupId the primary key of the group
   * @param createDate the activity's date
   * @param className the target asset's class name
   * @param classPK the primary key of the target asset
   * @param type the activity's type
   * @param extraData any extra data regarding the activity
   * @param receiverUserId the primary key of the receiving user
   * @throws PortalException if the user or group could not be found
   */
  @Override
  public void addActivity(
      long userId,
      long groupId,
      Date createDate,
      String className,
      long classPK,
      int type,
      String extraData,
      long receiverUserId)
      throws PortalException {

    if (ExportImportThreadLocal.isImportInProcess()) {
      return;
    }

    User user = userPersistence.findByPrimaryKey(userId);
    long classNameId = classNameLocalService.getClassNameId(className);

    if (groupId > 0) {
      Group group = groupLocalService.getGroup(groupId);

      if (group.isLayout()) {
        Layout layout = layoutLocalService.getLayout(group.getClassPK());

        groupId = layout.getGroupId();
      }
    }

    final SocialActivity activity = socialActivityPersistence.create(0);

    activity.setGroupId(groupId);
    activity.setCompanyId(user.getCompanyId());
    activity.setUserId(user.getUserId());
    activity.setCreateDate(createDate.getTime());
    activity.setMirrorActivityId(0);
    activity.setClassNameId(classNameId);
    activity.setClassPK(classPK);

    SocialActivityHierarchyEntry activityHierarchyEntry =
        SocialActivityHierarchyEntryThreadLocal.peek();

    if (activityHierarchyEntry != null) {
      activity.setParentClassNameId(activityHierarchyEntry.getClassNameId());
      activity.setParentClassPK(activityHierarchyEntry.getClassPK());
    }

    activity.setType(type);
    activity.setExtraData(extraData);
    activity.setReceiverUserId(receiverUserId);

    AssetEntry assetEntry = assetEntryPersistence.fetchByC_C(classNameId, classPK);

    activity.setAssetEntry(assetEntry);

    SocialActivity mirrorActivity = null;

    if ((receiverUserId > 0) && (userId != receiverUserId)) {
      mirrorActivity = socialActivityPersistence.create(0);

      mirrorActivity.setGroupId(groupId);
      mirrorActivity.setCompanyId(user.getCompanyId());
      mirrorActivity.setUserId(receiverUserId);
      mirrorActivity.setCreateDate(createDate.getTime());
      mirrorActivity.setClassNameId(classNameId);
      mirrorActivity.setClassPK(classPK);

      if (activityHierarchyEntry != null) {
        mirrorActivity.setParentClassNameId(activityHierarchyEntry.getClassNameId());
        mirrorActivity.setParentClassPK(activityHierarchyEntry.getClassPK());
      }

      mirrorActivity.setType(type);
      mirrorActivity.setExtraData(extraData);
      mirrorActivity.setReceiverUserId(user.getUserId());
      mirrorActivity.setAssetEntry(assetEntry);
    }

    final SocialActivity finalMirrorActivity = mirrorActivity;

    Callable<Void> callable =
        new Callable<Void>() {

          @Override
          public Void call() throws Exception {
            socialActivityLocalService.addActivity(activity, finalMirrorActivity);

            return null;
          }
        };

    TransactionCommitCallbackUtil.registerCallback(callable);
  }
  @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());
  }