Ejemplo n.º 1
0
  /**
   * Search the Database Server using the provided search request.
   *
   * @param request The search request.
   * @param handler A search result handler which can be used to asynchronously process the search
   *     result entries and references as they are received, may be null.
   * @return The result of the operation.
   * @throws ErrorResultException If the result code indicates that the request failed for some
   *     reason.
   * @throws SQLException If the SQL query has an invalid format.
   * @throws NullPointerException If {@code request} was {@code null}, or if a corresponding mapping
   *     value could not be found in the mapping component.
   */
  @Override
  public Result search(SearchRequest request, SearchResultHandler handler)
      throws ErrorResultException {
    Result r;
    try {
      // Split up the DN the of the request.
      final DN DN = request.getName();
      final int DNSize = DN.size();
      final String baseDN = DN.parent(DNSize - 2).toString();
      RDN OU = null;
      RDN rDN = null;
      String OUName = "";
      String rDNAttributeName = "";
      String rDNAttributeValue = "";

      if (DNSize > 3) {
        OU = DN.parent(1).rdn();
        OUName = OU.getFirstAVA().getAttributeValue().toString();
        rDN = DN.parent(0).rdn();
        rDNAttributeName = rDN.getFirstAVA().getAttributeType().getNameOrOID();
        rDNAttributeValue = rDN.getFirstAVA().getAttributeValue().toString();
      } else if (DNSize > 2) {
        OU = DN.parent(0).rdn();
        OUName = OU.getFirstAVA().getAttributeValue().toString();
      }
      List<String> returnAttributeNames = request.getAttributes();
      final List<String> removeAttributesList = new ArrayList<String>();

      // Get all column names to be returned to return full records.
      if (returnAttributeNames == null) {
        if (OU != null) {
          returnAttributeNames = jdbcm.getOrganizationalUnitAttributes(baseDN, OUName);

          if (returnAttributeNames == null)
            throw new NullPointerException(
                "JDBC Error: Could not find any matching attributes in OU: '" + OUName + "'.");
          final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);

          for (Iterator<String> iterAttributes = returnAttributeNames.iterator();
              iterAttributes.hasNext(); ) {
            String returnAttributeName = iterAttributes.next();
            final String returnColumnName =
                jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, returnAttributeName);

            if (returnColumnName == null) removeAttributesList.add(returnAttributeName);
          }
          returnAttributeNames.removeAll(removeAttributesList);
        } else {
          final List<String> OUList = jdbcm.getOrganizationalUnits(baseDN);

          if (OUList == null)
            throw new NullPointerException(
                "JDBC Error: Could not find any matching organizational units in DN: '"
                    + baseDN
                    + "'.");

          for (Iterator<String> iterOU = OUList.iterator(); iterOU.hasNext(); ) {
            OUName = iterOU.next();
            final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);
            returnAttributeNames = jdbcm.getOrganizationalUnitAttributes(baseDN, OUName);

            for (Iterator<String> iterAttributes = returnAttributeNames.iterator();
                iterAttributes.hasNext(); ) {
              String returnAttributeName = iterAttributes.next();
              final String returnColumnName =
                  jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, returnAttributeName);

              if (returnColumnName == null) removeAttributesList.add(returnAttributeName);
            }
            returnAttributeNames.removeAll(removeAttributesList);
          }
        }
      }
      // Convert the search filter.
      final Filter searchFilter = request.getFilter();
      final String convertedFilterString = convertSearchFilter(searchFilter, baseDN, OUName);

      if (convertedFilterString.startsWith("Err:")) {
        String[] errorStringSplitter = convertedFilterString.split("Err:");
        throw new NullPointerException(errorStringSplitter[1]);
      }
      final List<String> returnColumnNames = new ArrayList<String>();

      // Search mapping for the corresponding column name for each return attribute.
      for (Iterator<String> iter = returnAttributeNames.iterator(); iter.hasNext(); ) {

        if (OU == null) {
          final String returnAttributeName = iter.next();
          final List<String> OUList = jdbcm.getOrganizationalUnits(baseDN);

          if (OUList == null)
            throw new NullPointerException(
                "JDBC Error: Could not find any matching organizational units in DN: '"
                    + baseDN
                    + "'.");

          for (Iterator<String> iterOU = OUList.iterator(); iterOU.hasNext(); ) {
            OUName = iterOU.next();
            final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);
            final String returnColumnName =
                jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, returnAttributeName);

            if (returnColumnName == null) continue;
            else returnColumnNames.add(returnColumnName);
            break;
          }
        } else {
          final String returnAttributeName = iter.next();
          final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);

          if (tableName == null)
            throw new NullPointerException(
                "JDBC Error: Could not find matching table name for OU: '"
                    + OUName
                    + "' in DN: '"
                    + baseDN
                    + "'. Please check if mapping was succesful.");
          final String returnColumnName =
              jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, returnAttributeName);

          if (returnColumnName == null)
            throw new NullPointerException(
                "JDBC Error: Could not find matching column name for attribute: '"
                    + returnAttributeName
                    + "'. Please check if mapping was succesful.");
          returnColumnNames.add(returnColumnName);
        }
      }

      String selectString = "";
      String fromString = "";
      String whereString = convertedFilterString;

      if (returnAttributeNames.isEmpty()) selectString = "*";

      // Build the SQL SELECT string.
      if (OU == null) {
        final List<String> OUList = jdbcm.getOrganizationalUnits(baseDN);

        if (OUList == null)
          throw new NullPointerException(
              "JDBC Error: Could not find any matching organizational units in DN: '"
                  + baseDN
                  + "'.");

        for (int i = 0; i < OUList.size(); i++) {
          final String currentOU = OUList.get(i);
          final String currentTable = jdbcm.getTableNameFromMapping(baseDN, currentOU);

          if (currentTable == null) continue;
          final List<String> currentTableColumnNames = jdbcm.getTableColumns(currentTable);

          if (!fromString.isEmpty()) fromString = fromString.concat(",");
          fromString = fromString.concat(currentTable);

          for (int j = 0; j < returnColumnNames.size(); j++) {
            final String returnColumnName = returnColumnNames.get(j);

            if (currentTableColumnNames.contains(returnColumnName)) {

              if (!selectString.isEmpty()) selectString = selectString.concat(",");
              selectString = selectString.concat(currentTable + "." + returnColumnName);
            }
          }
        }
      } else {
        final String selectTable = jdbcm.getTableNameFromMapping(baseDN, OUName);
        if (selectTable == null)
          throw new NullPointerException(
              "JDBC Error: Could not find matching table name for OU: '"
                  + OUName
                  + "' in DN: '"
                  + baseDN
                  + "'. Please check if mapping was succesful.");

        fromString = fromString.concat(selectTable);

        for (int j = 0; j < returnColumnNames.size(); j++) {
          final String returnColumnName = returnColumnNames.get(j);

          if (returnColumnName == null) continue;

          if (!selectString.isEmpty()) selectString = selectString.concat(",");
          selectString = selectString.concat(returnColumnName);
        }

        if (rDN != null) {
          final String columnName =
              jdbcm.getColumnNameFromMapping(selectTable, baseDN, OUName, rDNAttributeName);

          if (columnName == null)
            throw new NullPointerException(
                "JDBC Error: Could not find matching column name for attribute: '"
                    + rDNAttributeName
                    + "'. Please check if mapping was succesful.");
          whereString = columnName + "='" + rDNAttributeValue + "'";
        }
      }

      // Build the SQL query.
      final Statement st = connection.createStatement();
      String sql = "SELECT " + selectString + " FROM " + fromString;

      if (!whereString.isEmpty()) sql = sql.concat(" WHERE " + whereString);
      ResultSet rs = st.executeQuery(sql);
      ResultSetMetaData rsmd = rs.getMetaData();

      // Fill the entries result for this query.
      searchEntries.clear();
      while (rs.next()) {
        Entry e = new LinkedHashMapEntry();

        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
          e.addAttribute(rsmd.getTableName(i) + "_" + rsmd.getColumnName(i), rs.getObject(i));
        }
        searchEntries.add(e);
      }
      r = Responses.newResult(ResultCode.SUCCESS);
    } catch (SQLException e) {
      System.out.println(e.toString());
      r = Responses.newResult(ResultCode.OPERATIONS_ERROR);
      r.setCause(e);
    } catch (NullPointerException e) {
      System.out.println(e.toString());
      r = Responses.newCompareResult(ResultCode.OPERATIONS_ERROR);
      r.setCause(e);
    }
    return r;
  }
Ejemplo n.º 2
0
  /**
   * Converts the LDAP filter to an SQL filter.
   *
   * @param filter The filter of the search request.
   * @param baseDN The top domain name.
   * @param OUName The name of the organizational unit.
   * @return The converted SQL filter.
   * @throws NullPointerException If the result code indicates that the request failed for some
   *     reason.
   * @throws SQLException If the SQL query has an invalid format.
   * @throws NullPointerException If {@code filter}, {@code baseDN} or {@code OUName} was {@code
   *     null}, or if a corresponding mapping value could not be found in the mapping component.
   */
  private String convertSearchFilter(final Filter filter, final String baseDN, String OUName) {
    try {
      String filterString = filter.toString();
      String convertedFilterString = "";

      if (filterString.isEmpty() || filterString.contains("objectClass=*")) return "";
      int stringIndex = 0;
      int subStringCount = 0;

      // Set the amount of subfilters if operators are present.
      while (filterString.charAt(stringIndex) == '(') {
        if (filterString.charAt(stringIndex + 2) == '(') {
          subStringCount++;
        }
        stringIndex += 2;
      }

      if (subStringCount == 0) {
        // Replace escape characters.
        String subString = filterString.substring(1, filterString.length() - 1);
        subString = subString.replace("\\02a", "*");
        subString = subString.replace("\\028", "(");
        subString = subString.replace("\\029", ")");

        String[] subStringSplitter;

        if (subString.contains("<=")) subStringSplitter = subString.split("<=");
        else if (subString.contains(">=")) subStringSplitter = subString.split(">=");
        else subStringSplitter = subString.split("=");

        final String filterAttributeName = subStringSplitter[0];
        String filterColumnName = null;
        ;
        Object columnDataType = null;

        // Search mapping for the corresponding table and column names.
        if (OUName.isEmpty()) {
          final List<String> OUList = jdbcm.getOrganizationalUnits(baseDN);

          for (Iterator<String> iter = OUList.iterator(); iter.hasNext(); ) {
            OUName = iter.next();
            final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);

            if (tableName == null) continue;
            filterColumnName =
                jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, filterAttributeName);

            if (filterColumnName == null) continue;
            else columnDataType = jdbcm.getTableColumnDataType(tableName, filterColumnName);
            break;
          }

          if (filterColumnName == null)
            throw new NullPointerException(
                "JDBC Error: Could not find matching column name for attribute: '"
                    + filterAttributeName
                    + "'. Please check if mapping was succesful.");
        } else {
          final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);

          if (tableName == null)
            throw new NullPointerException(
                "JDBC Error: Could not find matching table name for OU: '"
                    + OUName
                    + "' in DN: '"
                    + baseDN
                    + "'. Please check if mapping was succesful.");
          filterColumnName =
              jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, filterAttributeName);

          if (filterColumnName == null)
            throw new NullPointerException(
                "JDBC Error: Could not find matching column name for attribute: '"
                    + filterAttributeName
                    + "'. Please check if mapping was succesful.");
          columnDataType = jdbcm.getTableColumnDataType(tableName, filterColumnName);
        }

        // Set values to right format.
        if (columnDataType != Integer.class) {
          String filterAttributeValue = subStringSplitter[1];
          String filterColumnValue = "'" + filterAttributeValue + "'";
          filterAttributeValue = filterAttributeValue.replace("*", "\\*");
          filterAttributeValue = filterAttributeValue.replace("(", "\\(");
          filterAttributeValue = filterAttributeValue.replace(")", "\\)");

          if (filterColumnValue.length() > 3 && filterColumnValue.contains("*")) {
            filterColumnValue = filterColumnValue.replace("*", "%");

            subString = subString.replace("=", " like ");
          }
          subString = subString.replaceFirst(filterAttributeValue, filterColumnValue);
        }
        subString = subString.replaceFirst(filterAttributeName, filterColumnName);
        convertedFilterString = convertedFilterString.concat(subString);
      } else {
        int subStringStartIndex = 2 * subStringCount;
        int subStringEndIndex = 0;
        final String[] subStrings = new String[subStringCount];
        final char[] operationChars = new char[subStringCount];

        // Separate operation characters and subfilters.
        while (subStringStartIndex > 0) {
          final char operationChar = filterString.charAt(subStringStartIndex - 1);
          subStringEndIndex = filterString.indexOf("))") + 1;
          String subString = filterString.substring(subStringStartIndex, subStringEndIndex);
          subString = subString.replace("()", "");

          operationChars[subStringCount - subStringStartIndex / 2] = operationChar;
          subStrings[subStringCount - subStringStartIndex / 2] = subString;

          final String replaceString =
              filterString.substring(subStringStartIndex - 1, subStringEndIndex);
          filterString = filterString.replace(replaceString, "");

          subStringStartIndex -= 2;
        }

        // Handle the not operator.
        for (int i = 0; i < subStringCount; i++) {
          final char operationChar = operationChars[i];

          if (operationChar == '!') {
            String subString = subStrings[i];

            if (subString.isEmpty()) {
              subString = subStrings[i - 1];
              subString = subString.replace(">=", ">");
              subString = subString.replace("<=", "<");
              subString = subString.replace("=", "!=");
              subString = subString.replace(">", ">=");
              subString = subString.replace("<", "<=");
              subStrings[i - 1] = subString;
            } else {
              subString = subString.replace(">=", ">");
              subString = subString.replace("<=", "<");
              subString = subString.replace("=", "!=");
              subString = subString.replace(">", ">=");
              subString = subString.replace("<", "<=");
              subStrings[i] = subString;
            }
          }
        }
        boolean multipleSubStrings = false;

        if (subStringCount > 1) multipleSubStrings = true;

        // Convert each subfilter with corresponding operator.
        for (int i = 0; i < subStringCount; i++) {
          final char operationChar = operationChars[i];
          String operationString = "";

          if (operationChar == '&') {
            operationString = " AND ";
          } else if (operationChar == '|') {
            operationString = " OR ";
          }

          String subString = subStrings[i];
          if (subString.isEmpty()) continue;

          subString = subString.substring(1, subString.length() - 1);
          String[] subStringSplitter = subString.split("\\)\\(");

          for (int j = 0; j < subStringSplitter.length; j++) {
            String subStringFilter = subStringSplitter[j];
            final String[] subStringFilterSplitter;

            subStringFilter = subStringFilter.replace("\\02a", "*");
            subStringFilter = subStringFilter.replace("\\028", "(");
            subStringFilter = subStringFilter.replace("\\029", ")");

            if (subStringFilter.contains("!="))
              subStringFilterSplitter = subStringFilter.split("!=");
            else if (subStringFilter.contains("<="))
              subStringFilterSplitter = subStringFilter.split("<=");
            else if (subStringFilter.contains(">="))
              subStringFilterSplitter = subStringFilter.split(">=");
            else subStringFilterSplitter = subStringFilter.split("=");

            final String filterAttributeName = subStringFilterSplitter[0];
            String filterColumnName = null;
            ;
            Object columnDataType = null;

            // Search mapping for the corresponding column name for each filter attribute.
            if (OUName.isEmpty()) {
              final List<String> OUList = jdbcm.getOrganizationalUnits(baseDN);

              for (Iterator<String> iter = OUList.iterator(); iter.hasNext(); ) {
                OUName = iter.next();
                final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);

                if (tableName == null) continue;
                filterColumnName =
                    jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, filterAttributeName);

                if (filterColumnName == null) continue;
                else columnDataType = jdbcm.getTableColumnDataType(tableName, filterColumnName);
                break;
              }
              if (filterColumnName == null)
                throw new NullPointerException(
                    "JDBC Error: Could not find matching column name for attribute: '"
                        + filterAttributeName
                        + "'. Please check if mapping was succesful.");
            } else {
              final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);

              if (tableName == null)
                throw new NullPointerException(
                    "JDBC Error: Could not find matching table name for OU: '"
                        + OUName
                        + "' in DN: '"
                        + baseDN
                        + "'. Please check if mapping was succesful.");
              filterColumnName =
                  jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, filterAttributeName);

              if (filterColumnName == null)
                throw new NullPointerException(
                    "JDBC Error: Could not find matching column name for attribute: '"
                        + filterAttributeName
                        + "'. Please check if mapping was succesful.");
              columnDataType = jdbcm.getTableColumnDataType(tableName, filterColumnName);
            }

            // Handle the like operator.
            if (columnDataType != Integer.class) {
              String filterAttributeValue = subStringFilterSplitter[1];
              String filterColumnValue = "'" + filterAttributeValue + "'";
              filterAttributeValue = filterAttributeValue.replace("*", "\\*");
              filterAttributeValue = filterAttributeValue.replace("(", "\\(");
              filterAttributeValue = filterAttributeValue.replace(")", "\\)");

              if (filterColumnValue.length() > 3 && filterColumnValue.contains("*")) {
                filterColumnValue = filterColumnValue.replace("*", "%");

                if (subStringFilter.contains("!="))
                  subStringFilter = subStringFilter.replace("!=", " not like ");
                else subStringFilter = subStringFilter.replace("=", " like ");
              }
              subStringFilter =
                  subStringFilter.replaceFirst(filterAttributeValue, filterColumnValue);
            }
            subStringFilter = subStringFilter.replaceFirst(filterAttributeName, filterColumnName);

            if (j != 0 || i != 0)
              convertedFilterString = convertedFilterString.concat(operationString);
            convertedFilterString = convertedFilterString.concat(subStringFilter);
          }

          if (multipleSubStrings && i < subStringCount - 1)
            convertedFilterString = "(" + convertedFilterString + ")";
        }
      }
      return convertedFilterString;
    } catch (NullPointerException e) {
      return "Err:" + e.getMessage();
    }
  }