/**
   * Reads configured roles.
   *
   * @param request HTTP request.
   * @param response HTTP response.
   * @param context request context
   * @throws IdentityException if a system error occurs
   */
  private void executeReadConfigureRoles(
      HttpServletRequest request, HttpServletResponse response, RequestContext context)
      throws Exception {
    String mimeType = "application/json";
    String rolesJson = " { \"configuredRoles\" : [";
    Roles roles = buildSelectableRoles(context);
    ArrayList<String> sortedKeys = new ArrayList<String>(roles.keySet());
    Collections.sort(sortedKeys);
    boolean firstRole = true;
    for (int i = 0; i < sortedKeys.size(); i++) {
      Role role = roles.get(sortedKeys.get(i));
      String roleDn = Val.chkStr(role.getDistinguishedName());
      String roleKey = Val.chkStr(role.getKey());
      String roleName = msgBroker.retrieveMessage(Val.chkStr(role.getResKey()));
      if (!role.isManage()) continue;
      if (!firstRole) {
        rolesJson += ",";
      } else {
        firstRole = false;
      }
      rolesJson +=
          " { \"roleName\" : \""
              + Val.escapeStrForJson(roleName)
              + "\" , \"roleDn\" : \""
              + Val.escapeStrForJson(roleDn)
              + "\" , \"roleKey\" : \""
              + Val.escapeStrForJson(roleKey)
              + "\" }";
    }
    rolesJson += " ] } ";

    writeCharacterResponse(response, rolesJson, "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;
  }
  /**
   * Serializes user information from ldap to json string.
   *
   * @param context request context
   * @param user the user to be serialized
   * @return the user profile information serialized as json string.
   * @throws IdentityException if a system error occurs preventing the action
   * @throws NamingException if an LDAP naming exception occurs
   */
  protected String serializeUserAsJson(RequestContext context, User user)
      throws IdentityException, NamingException {
    String usersJson = "{ \"attributes\": [";
    UserAttributeMap attributes = user.getProfile();
    boolean first = true;
    List<String> sortedKeys = new ArrayList<String>(attributes.keySet());
    // Collections.sort(sortedKeys); TODO to sort or not ?
    for (int i = 0; i < sortedKeys.size(); i++) {
      UserAttribute attr = attributes.get(sortedKeys.get(i));
      String key =
          Val.chkStr(msgBroker.retrieveMessage("catalog.identity.profile.label." + attr.getKey()));
      String value = "";
      value = Val.chkStr(attr.getValue());
      if (attr.getKey().equalsIgnoreCase("password")) continue;
      if (!first) {
        usersJson += ",";
      } else {
        first = false;
      }
      usersJson +=
          " { \"key\" : \""
              + Val.escapeStrForJson(key)
              + "\" , \"value\" : \""
              + Val.escapeStrForJson(value)
              + "\" }";
    }
    usersJson += " ] , ";

    usersJson += " \"userDn\" : \"" + user.getDistinguishedName() + " \" , ";

    String groupsJson = " \"groups\" : [";
    Groups groups = user.getGroups();
    groups.sort();
    boolean firstGroup = true;
    for (Group group : groups.values()) {
      String gkey = Val.chkStr(group.getKey());
      String name = Val.chkStr(group.getName());
      String dn = Val.chkStr(group.getDistinguishedName());
      if (!firstGroup) {
        groupsJson += ",";
      } else {
        firstGroup = false;
      }
      groupsJson +=
          " { \"key\" : \""
              + Val.escapeStrForJson(gkey)
              + "\" , \"name\" : \""
              + Val.escapeStrForJson(name)
              + "\" , \"dn\" : \""
              + Val.escapeStrForJson(dn)
              + "\" }";
    }
    groupsJson += " ] , ";

    String rolesJson = " \"selectableRoles\" : [";
    Roles roles = buildSelectableRoles(context);
    sortedKeys = new ArrayList<String>(roles.keySet());
    Collections.sort(sortedKeys);
    boolean firstRole = true;
    for (int i = 0; i < sortedKeys.size(); i++) {
      Role role = roles.get(sortedKeys.get(i));
      String roleDn = Val.chkStr(role.getDistinguishedName());
      String roleKey = Val.chkStr(role.getKey());
      String roleName = msgBroker.retrieveMessage(Val.chkStr(role.getResKey()));
      if (!role.isManage()) continue;
      boolean hasRole = false;
      for (Group group : groups.values()) {
        String groupDn = Val.chkStr(group.getDistinguishedName());
        if (roleDn.equals(groupDn)) {
          hasRole = true;
          break;
        }
      }
      if (!firstRole) {
        rolesJson += ",";
      } else {
        firstRole = false;
      }
      rolesJson +=
          " { \"roleName\" : \""
              + Val.escapeStrForJson(roleName)
              + "\" , \"roleDn\" : \""
              + Val.escapeStrForJson(roleDn)
              + "\" , \"roleKey\" : \""
              + Val.escapeStrForJson(roleKey)
              + "\" , \"hasRole\" : \""
              + hasRole
              + "\" }";
    }
    rolesJson += " ] } ";
    String json = usersJson + groupsJson + rolesJson;
    return json;
  }