/**
   * 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 {
    }
  }
  /**
   * 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");
  }
  /**
   * Adds a summary message and a list of errors for each processed record that failed.
   *
   * @param context the processing context
   * @param msgBroker the message broker
   * @param resourceKey the resource key associated with the status type
   * @param statusType the sstatus type
   * @param count the count associated with the status type
   */
  private void addErrorMessages(
      ProcessingContext context,
      MessageBroker msgBroker,
      String resourceKey,
      ProcessedRecord.StatusType statusType,
      int count) {

    Object[] parameters = new Integer[] {count};
    String msg = msgBroker.retrieveMessage(resourceKey);
    msg = MessageFormat.format(msg, parameters);
    FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, null);
    msgBroker.addMessage(fm);
    for (ProcessedRecord processedRecord : context.getProcessedRecords()) {
      if (processedRecord.getStatusType().equals(statusType)
          && (processedRecord.getExceptions() != null)) {
        StringBuilder sb = new StringBuilder();
        sb.append(processedRecord.getSourceUri());
        if (processedRecord.getExceptions() != null) {
          for (String error : processedRecord.getExceptions()) {
            sb.append("<br />").append(error);
          }
        }
        fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, sb.toString(), null);
        msgBroker.addMessage(fm);
      }
    }
  }
 @Override
 public OpenSearchProperties getOpenSearchProperties() {
   OpenSearchProperties osProps = new OpenSearchProperties();
   osProps.setShortName(msgBroker.retrieveMessage("catalog.openSearch.shortName"));
   osProps.setNumberOfHits(query.getResult().getNumberOfHits());
   osProps.setStartRecord(query.getFilter().getStartRecord());
   osProps.setRecordsPerPage(query.getResult().getNumberOfHits());
   return osProps;
 }
  /**
   * 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 {
    }
  }
 /**
  * Adds a summary message and a list processed records for a processd status type.
  *
  * @param context the processing context
  * @param msgBroker the message broker
  * @param resourceKey the resource key associated with the status type
  * @param statusType the sstatus type
  * @param count the count associated with the status type
  */
 private void addSummaryMessage(
     ProcessingContext context,
     MessageBroker msgBroker,
     String resourceKey,
     ProcessedRecord.StatusType statusType,
     int count) {
   Object[] parameters = new Integer[] {count};
   String msg = msgBroker.retrieveMessage(resourceKey);
   msg = MessageFormat.format(msg, parameters);
   StringBuilder sb = new StringBuilder(msg);
   for (ProcessedRecord processedRecord : context.getProcessedRecords()) {
     if (processedRecord.getStatusType().equals(statusType)) {
       sb.append("<br />").append(processedRecord.getSourceUri());
     }
   }
   if (sb.length() > 0) {
     FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_INFO, sb.toString(), null);
     msgBroker.addMessage(fm);
   }
 }
  /**
   * 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;
  }
  /**
   * Performs search operation.
   *
   * @param request HTTP servlet request
   * @param response HTTP servlet response
   * @param context request context
   * @param query query
   * @return records
   * @throws Exception if searching fails
   */
  @Override
  public IFeedRecords doSearch(
      HttpServletRequest request,
      HttpServletResponse response,
      RequestContext context,
      RestQuery query)
      throws Exception {
    MessageBroker msgBroker = new FacesContextBroker(request, response).extractMessageBroker();
    final Map<DiscoveredRecord, Map<String, List<String>>> mapping =
        new HashMap<DiscoveredRecord, Map<String, List<String>>>();

    List<IFeedRecords.FieldMeta> fields = new ArrayList<IFeedRecords.FieldMeta>();
    loadStdFieldMeta(fields);

    int startRecord = query.getFilter().getStartRecord();
    boolean returnIdsOnly = Val.chkBool(Val.chkStr(request.getParameter("returnIdsOnly")), false);
    if (returnIdsOnly) {
      startRecord = 1;
      query.getFilter().setMaxRecords(1);
      LuceneQueryAdapter tmp = new LuceneQueryAdapter();
      tmp.execute(context, query);
      query.getFilter().setMaxRecords(query.getResult().getNumberOfHits());
    }

    query.getFilter().setStartRecord(startRecord);
    LuceneQueryAdapter lqa =
        new LuceneQueryAdapter() {
          @Override
          protected void onRecord(DiscoveredRecord record, Document document) {
            Map<String, List<String>> fieldMap = new HashMap<String, List<String>>();
            for (Fieldable field : document.getFields()) {
              String name = field.name();
              List<String> fieldValues = fieldMap.get(name);
              if (fieldValues == null) {
                fieldValues = new ArrayList<String>();
                fieldMap.put(name, fieldValues);
              }
              fieldValues.add(field.stringValue());
            }
            mapping.put(record, fieldMap);
          }
        };
    lqa.execute(context, query);
    startRecord += query.getFilter().getMaxRecords();

    loadLuceneMeta(context, fields);

    OpenSearchProperties osProps = new OpenSearchProperties();
    osProps.setShortName(msgBroker.retrieveMessage("catalog.openSearch.shortName"));
    osProps.setNumberOfHits(query.getResult().getNumberOfHits());
    osProps.setStartRecord(query.getFilter().getStartRecord());
    osProps.setRecordsPerPage(query.getFilter().getMaxRecords());

    ResourceIdentifier resourceIdentifier = ResourceIdentifier.newIdentifier(context);
    DiscoveredRecordsAdapter discoveredRecordsAdapter =
        new DiscoveredRecordsAdapter(
            resourceIdentifier, osProps, fields, query.getResult().getRecords(), mapping);

    FeedLinkBuilder linkBuilder =
        new FeedLinkBuilder(context, RequestContext.resolveBaseContextPath(request), msgBroker);
    for (IFeedRecord record : discoveredRecordsAdapter) {
      linkBuilder.build(record);
    }

    return discoveredRecordsAdapter;
    /*
    MessageBroker msgBroker = new FacesContextBroker(request, response).extractMessageBroker();
    FeedLinkBuilder linkBuilder = new FeedLinkBuilder(RequestContext.resolveBaseContextPath(request), msgBroker);

    DcatRecordsAdapter discoveredRecordsAdapter = new DcatRecordsAdapter(msgBroker, linkBuilder, context, query);

    return discoveredRecordsAdapter;
    */
  }