@Transactional
  private User getUser(LDAPUser user, boolean importPrivilegesFromLdap, String userName) {
    UserRepository userRepo = ApplicationContextHolder.get().getBean(UserRepository.class);

    User loadedUser = userRepo.findOneByUsername(userName);
    User toSave;
    if (loadedUser != null) {
      // If we don't import privileges from LDAP
      // Set the LDAP user profile to be the one set
      // in the local database. If not, the db profile
      // would be always reset by merge.
      if (!importPrivilegesFromLdap) {
        user.getUser().setProfile(loadedUser.getProfile());
      }
      loadedUser.mergeUser(user.getUser(), false);
      if (Log.isDebugEnabled(Geonet.LDAP)) {
        Log.debug(
            Geonet.LDAP,
            "  - Update LDAP user "
                + user.getUsername()
                + " ("
                + loadedUser.getId()
                + ") in local database.");
      }
      toSave = loadedUser;

    } else {
      if (Log.isDebugEnabled(Geonet.LDAP)) {
        Log.debug(Geonet.LDAP, "  - Saving new LDAP user " + user.getUsername() + " to database.");
      }
      toSave = user.getUser();
    }
    toSave.getSecurity().setAuthType(LDAPConstants.LDAP_FLAG);
    toSave = userRepo.save(toSave);
    user.setUser(toSave);
    return toSave;
  }
  /**
   * Save or update an LDAP user to the local GeoNetwork database.
   *
   * @param user
   * @throws Exception
   */
  @Transactional
  public synchronized void saveUser(
      LDAPUser user, boolean importPrivilegesFromLdap, boolean createNonExistingLdapGroup)
      throws Exception {
    String userName = user.getUsername();
    if (Log.isDebugEnabled(Geonet.LDAP)) {
      Log.debug(Geonet.LDAP, "LDAP user sync for " + userName + " ...");
    }
    User toSave = getUser(user, importPrivilegesFromLdap, userName);

    // Add user groups
    if (importPrivilegesFromLdap) {
      entityManager.flush();
      entityManager.clear();
      List<UserGroup> ug = getPrivilegesAndCreateGroups(user, createNonExistingLdapGroup, toSave);
      entityManager.flush();
      setUserGroups(toSave, ug);
    }
  }