/**
  * 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");
 }
  /**
   * 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;
  }
  /**
   * Executes the query request.
   *
   * @throws SQLException if a database exception occurs
   * @throws IOException
   * @throws SAXException
   * @throws ParserConfigurationException
   */
  public void execute()
      throws SQLException, IdentityException, NamingException, ParserConfigurationException,
          SAXException, IOException {

    // intitalize
    PreparedStatement st = null;
    PreparedStatement stCount = null;
    MmdQueryCriteria criteria = getQueryCriteria();
    MmdRecords records = getQueryResult().getRecords();
    PageCursor pageCursor = getQueryResult().getPageCursor();
    criteria.getDateRange().check();
    pageCursor.setTotalRecordCount(0);

    adminDao = new ImsMetadataAdminDao(getRequestContext());
    tblImsUser = getRequestContext().getCatalogConfiguration().getUserTableName();
    Users editablePublishers = Publisher.buildSelectablePublishers(getRequestContext(), false);
    for (User u : editablePublishers.values()) {
      if (u.getName().length() > 0) {
        hmEditablePublishers.put(u.getName().toLowerCase(), u.getKey());
      }
    }
    User tmpUser = new User();
    tmpUser.setDistinguishedName("*");
    getRequestContext().newIdentityAdapter().readUserGroups(tmpUser);
    allGroups = tmpUser.getGroups();

    isGptAdministrator = new RoleMap(getRequestContext().getUser()).get("gptAdministrator");

    // determine if we are in ArcIMS metadata server proxy mode

    try {

      // establish the connection
      ManagedConnection mc = returnConnection();
      Connection con = mc.getJdbcConnection();

      // start the SQL expression
      StringBuilder sbSql = new StringBuilder();
      StringBuilder sbCount = new StringBuilder();
      StringBuilder sbFrom = new StringBuilder();
      StringBuilder sbWhere = new StringBuilder();
      sbSql.append("SELECT A.TITLE,A.DOCUUID,A.SITEUUID,C.USERNAME");
      sbSql.append(",A.APPROVALSTATUS,A.PUBMETHOD,A.UPDATEDATE,A.ACL");
      sbSql.append(",A.ID,A.HOST_URL,A.FREQUENCY,A.SEND_NOTIFICATION,A.PROTOCOL");
      sbSql.append(",A.FINDABLE,A.SEARCHABLE,A.SYNCHRONIZABLE");
      sbCount.append("SELECT COUNT(*)");

      // append from clause
      sbFrom.append(" FROM ").append(tblImsUser).append(" C");
      sbFrom.append(",").append(getResourceTableName()).append(" A");
      sbSql.append(sbFrom);
      sbCount.append(sbFrom);

      // build the where clause
      if (sbWhere.length() > 0) {
        sbWhere.append(" AND");
      }
      sbWhere.append(" (A.OWNER = C.USERID)");

      Map<String, Object> args = criteria.appendWherePhrase("A", sbWhere, getPublisher());

      // append the where clause expressions
      if (sbWhere.length() > 0) {
        sbSql.append(" WHERE ").append(sbWhere.toString());
        sbCount.append(" WHERE ").append(sbWhere.toString());
      }

      // append the order by clause
      String sSortColumn = criteria.getSortOption().getColumnKey();
      String sSortDir = criteria.getSortOption().getDirection().toString();
      if (sSortColumn.equalsIgnoreCase("title")) {
        sSortColumn = "UPPER(A.TITLE)";
      } else if (sSortColumn.equalsIgnoreCase("uuid")) {
        sSortColumn = "A.DOCUUID";
      } else if (sSortColumn.equalsIgnoreCase("owner")) {
        sSortColumn = "UPPER(C.USERNAME)";
      } else if (sSortColumn.equalsIgnoreCase("status")) {
        sSortColumn = "A.APPROVALSTATUS";
      } else if (sSortColumn.equalsIgnoreCase("method")) {
        sSortColumn = "A.PUBMETHOD";
      } else if (sSortColumn.equalsIgnoreCase("acl")) {
        sSortColumn = "A.ACL";
      } else if (sSortColumn.equalsIgnoreCase("updatedate")) {
        sSortColumn = "A.UPDATEDATE";
      } else {
        sSortColumn = "A.UPDATEDATE";
        sSortDir = "DESC";
        criteria.getSortOption().setColumnKey("updatedate");
        criteria.getSortOption().setDirection("desc");
      }
      sbSql.append(" ORDER BY ");
      sbSql.append(sSortColumn).append(" ").append(sSortDir.toUpperCase());
      if (!sSortColumn.equalsIgnoreCase("A.UPDATEDATE")) {
        sbSql.append(", A.UPDATEDATE DESC");
      }

      // prepare the statements
      st = con.prepareStatement(sbSql.toString());
      stCount = con.prepareStatement(sbCount.toString());

      int n = 1;
      criteria.applyArgs(st, n, args);
      criteria.applyArgs(stCount, n, args);

      // query the count
      logExpression(sbCount.toString());
      ResultSet rsCount = stCount.executeQuery();
      if (rsCount.next()) {
        pageCursor.setTotalRecordCount(rsCount.getInt(1));
      }
      stCount.close();
      stCount = null;

      // query records if a count was found
      pageCursor.checkCurrentPage();
      if (pageCursor.getTotalRecordCount() > 0) {

        // set the start record and the number of records to retrieve
        int nCurPage = pageCursor.getCurrentPage();
        int nRecsPerPage = getQueryResult().getPageCursor().getRecordsPerPage();
        int nStartRecord = ((nCurPage - 1) * nRecsPerPage) + 1;
        int nMaxRecsToRetrieve = nCurPage * nRecsPerPage;
        st.setMaxRows(nMaxRecsToRetrieve);

        // determine publisher names associated with editable records

        // execute the query
        logExpression(sbSql.toString());
        ResultSet rs = st.executeQuery();

        // build the record set
        int nCounter = 0;

        while (rs.next()) {
          n = 1;
          nCounter++;
          if (nCounter >= nStartRecord) {
            MmdRecord record = new MmdRecord();
            records.add(record);

            readRecord(rs, record);

            // break if we hit the max value for the cursor
            if (records.size() >= nRecsPerPage) {
              break;
            }
          }
        }

        TreeMap<String, MmdRecord> recordsMap =
            new TreeMap<String, MmdRecord>(String.CASE_INSENSITIVE_ORDER);
        StringBuilder keys = new StringBuilder();

        for (MmdRecord r : records) {
          if (r.getProtocol() == null) continue;
          recordsMap.put(r.getUuid(), r);
          if (keys.length() > 0) {
            keys.append(",");
          }
          keys.append("'").append(r.getUuid().toUpperCase()).append("'");
        }

        readJobStatus(con, recordsMap, keys.toString());
        readLastHarvestDate(con, recordsMap, keys.toString());
      }

    } finally {
      closeStatement(st);
      closeStatement(stCount);
    }
  }