/**
   * Executes a delete user action.
   *
   * @param request HTTP request.
   * @param response HTTP response.
   * @param context request context
   * @throws Exception if an exception occurs
   */
  private void executeDeleteUser(
      HttpServletRequest request, HttpServletResponse response, RequestContext context)
      throws Exception {
    try {
      String[] parts = request.getRequestURI().toString().split("/");
      if (parts.length > 0) {
        String userIdentifier = URLDecoder.decode(parts[5].trim(), "UTF-8");
        if (userIdentifier.endsWith(userDIT)) {
          String attempt = Val.chkStr(request.getParameter("attempt"));
          IdentityAdapter idAdapter = context.newIdentityAdapter();
          User user = new User();
          user.setDistinguishedName(userIdentifier);
          idAdapter.readUserProfile(user);
          idAdapter.readUserGroups(user);

          boolean isSelf = checkSelf(context, userIdentifier);
          if ((isSelf && attempt.equals("2")) || !isSelf) {
            idAdapter.deleteUser(user);
            response
                .getWriter()
                .write(msgBroker.retrieveMessage("catalog.identity.deleteUser.success"));
          } else {
            response.getWriter().write("prompt");
          }
        }
      }
    } finally {
    }
  }
 /**
  * Add attribute to ldap entry.
  *
  * @param request HTTP request.
  * @param response HTTP response.
  * @param context request context
  * @throws IdentityException if a system error occurs preventing the action
  * @throws IOException if error writing to the buffer
  * @throws NamingException if an LDAP naming exception occurs
  * @throws SQLException
  * @throws CredentialPolicyException
  */
 private void executeModifyUserAttribute(
     HttpServletRequest request,
     HttpServletResponse response,
     RequestContext context,
     boolean isAddAttributeRequest)
     throws IdentityException, IOException, NamingException, SQLException,
         CredentialPolicyException {
   String mimeType = "application/json";
   String filter = Val.chkStr(request.getParameter("q"));
   String attributeName = Val.chkStr(request.getParameter("an"));
   String attributeValue = Val.chkStr(request.getParameter("av"));
   if (filter.length() == 0) {
     response.getWriter().write("{ \"response\" : \"noResults\" }");
     return;
   }
   IdentityAdapter idAdapter = context.newIdentityAdapter();
   Users users = idAdapter.readUsers(filter, null);
   for (User u : users.values()) {
     if (isAddAttributeRequest) {
       try {
         idAdapter.addAttribute(u.getDistinguishedName(), attributeName, attributeValue);
       } catch (AttributeInUseException aiue) {
         // TODO : do nothing if attribute exists ? or overwrite ?
       }
     } else {
       idAdapter.removeAttribute(u.getDistinguishedName(), attributeName, attributeValue);
     }
   }
   writeCharacterResponse(
       response,
       "{ \"response\" : \"User attribute modification was successful.\" }",
       "UTF-8",
       mimeType + ";charset=UTF-8");
 }
  /**
   * Executes a remove member action.
   *
   * @param request HTTP request.
   * @param response HTTP response.
   * @param context request context
   * @throws Exception if an exception occurs
   */
  protected void executeRemoveMember(
      HttpServletRequest request, HttpServletResponse response, RequestContext context)
      throws Exception {
    try {
      String[] parts = request.getRequestURI().toString().split("/");
      String member = Val.chkStr(request.getParameter("member"));
      String attempt = Val.chkStr(request.getParameter("attempt"));
      IdentityAdapter idAdapter = context.newIdentityAdapter();
      User user = new User();
      user.setDistinguishedName(member);
      idAdapter.readUserProfile(user);
      if (parts.length > 0) {
        String groupIdentifier = URLDecoder.decode(parts[5].trim(), "UTF-8");
        if (!groupIdentifier.endsWith(groupDIT)) {
          IdentityConfiguration idConfig = context.getIdentityConfiguration();
          Roles configuredRoles = idConfig.getConfiguredRoles();
          Role roleRegistered = configuredRoles.get(groupIdentifier);
          groupIdentifier = roleRegistered.getDistinguishedName();
        }
        boolean isSelf = checkSelf(context, member);
        if ((isSelf && attempt.equals("2")) || !isSelf) {

          boolean checkGroupConfigured = true;
          if (checkIfAllowConfigured(context)) {
            checkGroupConfigured = checkIfConfigured(context, groupIdentifier);
          }
          boolean isAllowedToManage = true;
          isAllowedToManage = checkIfAllowedToManage(context, groupIdentifier);
          if (checkGroupConfigured) {
            if (isAllowedToManage) {
              idAdapter.removeUserFromGroup(user, groupIdentifier);
              response
                  .getWriter()
                  .write(msgBroker.retrieveMessage("catalog.identity.removeRole.success"));
            } else {
              response.sendError(
                  HttpServletResponse.SC_BAD_REQUEST,
                  "{ \"error\":\""
                      + groupIdentifier
                      + " is not allowed to be managed in geoportal. \"}");
              return;
            }
          } else {
            response.sendError(
                HttpServletResponse.SC_BAD_REQUEST,
                "{ \"error\":\"" + groupIdentifier + " is not configured in geoportal. \"}");
            return;
          }

        } else {
          response.getWriter().write("prompt");
        }
      }
    } finally {
    }
  }
  /**
   * Serializes list of ldap users matching filter.
   *
   * @param context the current request context
   * @param filter the user search filter for ldap
   * @return the list of users as json
   * @throws IdentityException if a system error occurs preventing the action
   * @throws NamingException if an LDAP naming exception occurs
   * @throws SQLException
   */
  protected String serializeUsersAsJson(
      RequestContext context, String filter, String attributeName, boolean isMemberSearch)
      throws IdentityException, NamingException, SQLException {
    Users users = new Users();
    int totalMatches = 0;
    if (!isMemberSearch) {
      HashMap<String, Object> resultsMap = buildUsersList(context, filter, null);
      users = (Users) resultsMap.get("topUserMatches");
      totalMatches = (Integer) resultsMap.get("totalMatches");
    } else if (isMemberSearch && attributeName != null) {
      Roles configuredRoles = context.getIdentityConfiguration().getConfiguredRoles();
      Role role = configuredRoles.get(attributeName);
      String sDn = role.getDistinguishedName();
      IdentityAdapter idAdapter = context.newIdentityAdapter();
      users = idAdapter.readGroupMembers(sDn);
      totalMatches = users.size();
      users.sort();
    } else {
      IdentityAdapter idAdapter = context.newIdentityAdapter();
      Users members = idAdapter.readGroupMembers(filter);
      for (User u : members.values()) {
        users.add(u);
      }
      users.sort();
      totalMatches = users.size();
    }

    String usersJson =
        "{ \"totalUsers\" : \""
            + totalMatches
            + "\" ,\"topUsers\" : \""
            + users.size()
            + "\" , \"users\": [";
    boolean firstUser = true;
    for (User user : users.values()) {
      String userName = user.getName();
      String dn = user.getKey();
      if (!firstUser) {
        usersJson += ",";
      } else {
        firstUser = false;
      }
      usersJson +=
          " { \"dn\" : \""
              + dn
              + "\" , \"userName\" : \""
              + Val.escapeStrForJson(userName)
              + "\" }";
    }
    usersJson += " ] }";
    return usersJson;
  }
  /**
   * Builds list of ldap users matching filter.
   *
   * @param context the current request context (contains the active user)
   * @param filter the user search filter for ldap
   * @return the list of users matching filter
   * @throws IdentityException if a system error occurs preventing the action
   * @throws NamingException if an LDAP naming exception occurs
   */
  protected HashMap<String, Object> buildUsersList(
      RequestContext context, String filter, String attributeName)
      throws IdentityException, NamingException {
    HashMap<String, Object> resultsMap = new HashMap<String, Object>();
    IdentityAdapter idAdapter = context.newIdentityAdapter();
    String searchLimit =
        Val.chkStr(
            context
                .getCatalogConfiguration()
                .getParameters()
                .getValue("ldap.identity.search.maxResults"));
    int srchLimit = -1;
    if (searchLimit.length() > 0) {
      srchLimit = Integer.parseInt(searchLimit);
    }
    Users users = idAdapter.readUsers(filter, attributeName);
    users.sort();
    int totalMatches = users.size();
    resultsMap.put("totalMatches", totalMatches);
    if (srchLimit == -1) {
      resultsMap.put("topUserMatches", users);
      return resultsMap;
    }

    if (attributeName != null) {
      resultsMap.put("topUserMatches", users);
      return resultsMap;
    }
    Users topUserMatches = new Users();
    int count = 0;
    for (User user : users.values()) {
      count++;
      if (count <= srchLimit) {
        topUserMatches.add(user);
      } else {
        break;
      }
    }
    resultsMap.put("topUserMatches", topUserMatches);
    return resultsMap;
  }