@Override
  public Entity add(
      PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper)
      throws ServiceException {
    adminRemoteSecurityService.securityCheck(persistencePackage, EntityOperationType.ADD);
    Entity entity = persistencePackage.getEntity();
    try {
      PersistencePerspective persistencePerspective =
          persistencePackage.getPersistencePerspective();
      AdminUser adminInstance = (AdminUser) Class.forName(entity.getType()[0]).newInstance();
      Map<String, FieldMetadata> adminProperties =
          helper.getSimpleMergedProperties(AdminUser.class.getName(), persistencePerspective);
      adminInstance =
          (AdminUser) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);

      Entity errorEntity = validateLegalUsernameAndEmail(entity, adminInstance, true);
      if (errorEntity != null) {
        return errorEntity;
      }

      adminInstance.setUnencodedPassword(adminInstance.getPassword());
      adminInstance.setPassword(null);

      adminInstance = adminSecurityService.saveAdminUser(adminInstance);

      Entity adminEntity = helper.getRecord(adminProperties, adminInstance, null, null);

      return adminEntity;
    } catch (Exception e) {
      throw new ServiceException("Unable to add entity for " + entity.getType()[0], e);
    }
  }
 @Override
 public PersistenceManagerEventHandlerResponse preFetch(
     PersistenceManager persistenceManager,
     PersistencePackage persistencePackage,
     CriteriaTransferObject cto)
     throws ServiceException {
   try {
     Class<?>[] entityClasses =
         persistenceManager
             .getDynamicEntityDao()
             .getAllPolymorphicEntitiesFromCeiling(
                 Class.forName(persistencePackage.getCeilingEntityFullyQualifiedClassname()));
     boolean isArchivable = false;
     for (Class<?> entity : entityClasses) {
       if (Status.class.isAssignableFrom(entity)) {
         isArchivable = true;
         break;
       }
     }
     if (isArchivable && !persistencePackage.getPersistencePerspective().getShowArchivedFields()) {
       FilterMapping filterMapping =
           new FilterMapping()
               .withFieldPath(new FieldPath().withTargetProperty("archiveStatus.archived"))
               .withDirectFilterValues(new EmptyFilterValues())
               .withRestriction(
                   new Restriction()
                       .withPredicateProvider(
                           new PredicateProvider<Character, Character>() {
                             @Override
                             public Predicate buildPredicate(
                                 CriteriaBuilder builder,
                                 FieldPathBuilder fieldPathBuilder,
                                 From root,
                                 String ceilingEntity,
                                 String fullPropertyName,
                                 Path<Character> explicitPath,
                                 List<Character> directValues) {
                               return builder.or(
                                   builder.equal(explicitPath, 'N'), builder.isNull(explicitPath));
                             }
                           }));
       cto.getAdditionalFilterMappings().add(filterMapping);
     }
     return new PersistenceManagerEventHandlerResponse()
         .withStatus(
             PersistenceManagerEventHandlerResponse.PersistenceManagerEventHandlerResponseStatus
                 .HANDLED);
   } catch (ClassNotFoundException e) {
     LOG.error(
         "Could not find the class "
             + persistencePackage.getCeilingEntityFullyQualifiedClassname()
             + " to "
             + "compute polymorphic entity types for. Assuming that the entity is not archivable");
     return new PersistenceManagerEventHandlerResponse()
         .withStatus(
             PersistenceManagerEventHandlerResponse.PersistenceManagerEventHandlerResponseStatus
                 .NOT_HANDLED);
   }
 }
 @Override
 public Boolean canHandleAdd(PersistencePackage persistencePackage) {
   try {
     return persistencePackage.getCeilingEntityFullyQualifiedClassname() != null
         && AdminUser.class.isAssignableFrom(
             Class.forName(persistencePackage.getCeilingEntityFullyQualifiedClassname()))
         && persistencePackage.getPersistencePerspectiveItems().isEmpty();
   } catch (ClassNotFoundException e) {
     throw new RuntimeException(e);
   }
 }
  @Override
  public Entity update(
      PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper)
      throws ServiceException {
    Entity entity = persistencePackage.getEntity();
    try {
      PersistencePerspective persistencePerspective =
          persistencePackage.getPersistencePerspective();
      Map<String, FieldMetadata> adminProperties =
          helper.getSimpleMergedProperties(AdminUser.class.getName(), persistencePerspective);
      Object primaryKey = helper.getPrimaryKey(entity, adminProperties);
      AdminUser adminInstance =
          (AdminUser) dynamicEntityDao.retrieve(Class.forName(entity.getType()[0]), primaryKey);

      Entity errorEntity = validateLegalUsernameAndEmail(entity, adminInstance, false);
      if (errorEntity != null) {
        return errorEntity;
      }

      String passwordBefore = adminInstance.getPassword();
      adminInstance.setPassword(null);
      adminInstance =
          (AdminUser) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);
      Property passwordProperty = entity.getPMap().get("password");
      if (passwordProperty != null) {
        if (StringUtils.isNotEmpty(passwordProperty.getValue())) {
          adminInstance.setUnencodedPassword(passwordProperty.getValue());
          adminInstance.setPassword(null);
        } else {
          adminInstance.setPassword(passwordBefore);
        }
      }

      validateUserUpdateSecurity(persistencePackage, adminInstance);

      adminInstance = adminSecurityService.saveAdminUser(adminInstance);
      Entity adminEntity = helper.getRecord(adminProperties, adminInstance, null, null);

      return adminEntity;

    } catch (Exception e) {
      throw new ServiceException("Unable to update entity for " + entity.getType()[0], e);
    }
  }
  @Override
  public void remove(
      PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper)
      throws ServiceException {
    Entity entity = persistencePackage.getEntity();
    String userLoginToRemove = entity.findProperty("login").getValue();

    AdminUser persistentAdminUser = adminRemoteSecurityService.getPersistentAdminUser();

    if (persistentAdminUser != null && persistentAdminUser.getLogin() != null) {
      if (persistentAdminUser.getLogin().equals(userLoginToRemove)) {
        throw new ValidationException(entity, "admin.cantDeleteCurrentUserError");
      }
    }

    OperationType removeType =
        persistencePackage.getPersistencePerspective().getOperationTypes().getRemoveType();
    helper.getCompatibleModule(removeType).remove(persistencePackage);
  }