Mozilla LDAP SDK Programmer's Guide/Using Filter Configuration Files With LDAP Java SDK

From MozillaWiki
Jump to: navigation, search

This section explains how to use API function to work with filter configuration files. Filter configuration files can help simplify the process of selecting the appropriate search filter for a search request.

Understanding Filter Configuration Files

Suppose that you are writing a client that allows users to search the directory. You might want to use different search filters tailored for specific types of search criteria. For example, suppose the user wants to search for this:

bjensen@example.com

You might want to use this search filter:

(mail=bjensen@example.com)

Similarly, suppose the search term entered by the user contains numbers, like this:

555-1212

In this case, you might want to use this search filter:

(telephoneNumber=555-1212)

Rather than write code to construct the search filter explicitly, you can generate filters using a filter configuration file. A filter configuration file specifies a list of filters that you can load and use in your searches.

Understanding the Configuration File Syntax

A filter configuration file has the following format:

''tag''
    ''pattern1''    ''delimiters''    ''filter1-1''    ''desc1-1''    [''scope1'']
                                      ''filter1-2''    ''desc1-2''    [''scope2'']
    ''pattern2''    ''delimiters''    ''filter2-1''    ''desc2-1''    [''scope3'']
...

Each element in the file is a string, surrounded by quotes (").

Comments consist of lines starting with #.

The format supports these elements:

  • tag: Identifies a group of filters.
    You can use different tags to distinguish filters for different types of objects.
    For example, you can use a "person" tag to identify filters for person entries, a "organization" tag to represent filters for organization entries, and so forth.
    You can specify multiple tags for the same group of filters in the configuration file using the keyword and, such as "people and organization".
    You can specify a tag, or part of a tag, as a parameter. The tag narrows the list of filters that the function retrieves.
  • pattern: Specifies a regular expression used to determine which filter is selected based on the search criteria.
    For example, if you specify ^[0-9] as the pattern for a filter, the filter is selected for all search criteria beginning with a number.
  • delimiters: Specify what characters separate one field from another within search criteria.
    For example, if the search criteria consists of a city name and state abbreviation separated by a comma, specify "," as the delimiter.
  • filter: Specifies an LDAP filter including %v to represent the search criteria.
    For example, to search email addresses, use the filter (mail=%v). During runtime, if the search criteria bjensen@example.com is entered, the filter becomes (mail=bjensen@example.com).
    If the search criteria consists of a number of delimited fields such as a surname, first name format like Jensen, Barbara, use %v1, %v2, ..., %vn to represent the fields within the search criteria. For example:
"people"
    "^[A-Z]*,"    ","    "(&(sn=%v1)(givenName=%v2))"

In the example, the delimiter is a comma. The word before the delimiter replaces %v1 in the filter, and the word after the delimiter replaces%v1. A search for: Jensen, Barbara results in a filter:

(&(sn=Jensen)(givenName=Barbara))

You can also specify ranges of fields. For example, to specify the values in the first three fields, use %v1-3. To specify values from the third field to the last field, use %v3-. To specify the value in the last field, use %v$.

  • desc: Specify short text descriptions of the filters.
  • scope: Specify the scope of each search.
    This field is optional. It can take the values "base", "onelevel", or "subtree". For example, the following section of a filter configuration file specifies a filter for telephone numbers and two filters for email addresses. The telephone number filter is used if the search criteria contains one or more numbers. The email filters are used if the search criteria contains an at sign (@).
"people"
    "^[0-9][0-9-]*$"    " "    "(telephoneNumber=*%v)"    "phone number ends with"
    "@"                 " "    "(mail=%v)"                "email address is"
                               "(mail=%v*)"               "email address starts with"

Specify the filters in the order that you want them to be used. For example, if you want to apply the (mail=%v) filter before the (mail=%v*) filter, make sure that the filters appear in that order.

Understanding Filter Parameters

Configuration file filter specifications support the following parameters:

  • %v: Insert the search criterion verbatim in place of %v.
    For example, if the filter specification is (mail=%v), entering bjensen results in the filter (mail=bjensen).
  • %v$: Insert the last word of search criterion verbatim in place of %v.
    For example, if the filter specification is (sn=%v$), entering Barbara Jensen results in the filter (sn=Jensen).
  • %vN: Insert the Nth word of the criteria in place of %v, where N is a single digit between 1 and 9.
    For example, if the filter specification is (sn=%v2), entering Barbara Jensen results in the filter (sn=Jensen).
  • %vM-N: Insert the sequence of the Mth through Nth words of the criteria in place of %v, where M and N are single digits between 1 and 9.
    For example, if the filter specification is (cn=%v1-2), entering Barbara Jensen results in the filter (cn=Barbara Jensen).
  • %vN-: Insert the sequence of th eNth through last words of the criteria in place of %v, where N is a single digit between 1 and 9.
    For example, if the filter specification is (cn=%v2-), entering Ms. Barbara Jensen results in the filter (cn=Barbara Jensen).

Loading Filter Configuration Files

To use a filter configuration file, you need to create an LDAPFilterDescriptor object. The LDAPFilterDescriptor constructor allows you to read in the filter configuration file from one of the following:

  • A file in the local file system to which you specify the path
  • A file served by a web server to which you specify the URL
  • A location in memory where you specify a StringBuffer object containing the configuration information

The following section of code reads in a filter configuration file named in the current directory.

import netscape.ldap.util.*;
...
LDAPFilterDescriptor filtdesc = null;
try {
    /* Read in the filter configuration file. */
    filtdesc = new LDAPFilterDescriptor("ldapfilter.conf");
} catch ( Exception e ) {
    System.out.println( "Error: " + e.toString() );
}

Retrieving Filters

After loading a filter configuration file into memory, you can retrieve filters based on the search criteria. For example, if the search criteria is an email address such as bjensen@example.com, you can have your client automatically search for this value in the mail attribute.

Retrieving Filters Using A Filter Configuration File

  1. Invoke the LDAPFilterDescriptor constructor to read in the filter configuration file.
  2. Invoke the getFilters method of the LDAPFilterDescriptor object.
    Specify the tag of the section that you want to use in the filter configuration file.
    You do not need to invoke the setupFilter of the LDAPFilter object to generate the filter. The getFilters method of the LDAPFilterDescriptor object does this already. You just need to invoke the getFilter method of the LDAPFilter object to get the generated filter.
    This method returns an LDAPFilterList object, which is an enumeration of LDAPFilter objects containing the filters for the specified search term.
  3. Invoke the next method of the LDAPFilterList object to iterate through the LDAPFilter objects.
  4. For each LDAPFilter object, get the filter by invoking the getFilter method, passing no arguments.
    To get the total number of filter configuration lines that match the specified search term, invoke the numFilters method of the LDAPFilterList object.
    This number decrements each time you invoke the next or nextElement method.

Retrieving Telephone Number and Mail Filters

This example uses a filter configuration file, , with the following specifications:

"people"
    "^[0-9][0-9-]*$"    " "    "(telephoneNumber=*%v)"    "phone number ends with"
    "@"                 " "    "(mail=%v)"                "email address is"
                               "(mail=%v*)"               "email address starts with"

The following code retrieves, generates, and prints filters matching the criteria:

String searchTerm = "bjensen@example.com";
LDAPFilterDescriptor filtdesc = null;
try {
    /* Read in the filter configuration file. */
    filtdesc = new LDAPFilterDescriptor("ldapfilt.conf");

    /* Get filters from the section "people" */
    LDAPFilterList filtlist = null;
    try {
        filtlist = filtdesc.getFilters("people", searchTerm);
    } catch ( Exception e ) {
        System.out.println("No matching tag section or filter");
        System.exit(0);
    }

    int totalFilters = filtlist.numFilters();
    System.out.println("Found " + totalFilters + " applicable filters.\n");

    /* Iterate through the lines in the list. */
    while ( filtlist.hasMoreElements() ) {
        LDAPFilter filtline = filtlist.next();
        System.out.println("Filter #" +
            (totalFilters - filtlist.numFilters()));

        /* Get and print information about the selected line
            of filter configuration information. */
        System.out.println("  Description: " + filtline.getDescription());
        System.out.println("  Line #: " + filtline.getLineNumber());
        System.out.println("  Matches pattern: " +
            filtline.getMatchPattern());
        System.out.println("  Filter template: " +
            filtline.getFilterTemplate());
        System.out.println("  Delimiter: " + filtline.getDelimeter());
        System.out.println("  Scope: " + filtline.getScope());

        /* Get the generated filter. */
        String filterString = filtline.getFilter();
        System.out.println("  Generated filter string: " +
            filterString + "\n");
    }
} catch ( Exception e ) {
    System.out.println("Error: " + e.toString());
}

When built into a program, compiled, and run, this code produces the following output:

Found 2 applicable filters.

Filter #1
  Description: email address is
  Line #: 3
  Matches pattern: @
  Filter template: (mail=%v)
  Delimiter: 
  Scope: subtree
  Generated filter string: (mail=bjensen@example.com)

Filter #2
  Description: email address starts with
  Line #: 4
  Matches pattern: @
  Filter template: (mail=%v*)
  Delimiter: 
  Scope: subtree
  Generated filter string: (mail=bjensen@example.com*)

Adding Filter Prefixes and Suffixes

If you need to apply a filter to all searches, you can add a filter prefix and suffix to all filters rather than adding the criteria to all filters. For example, if your client searches only for person entries, you can add the following filter prefix to restrict the search:

(&(l=Sunnyvale)

The filter prefix now requires the following suffix to balance the number of parentheses:

)

For example, given the following filter:

(sn=Jensen)

You can use the filter prefix (&(l=Sunnyvale and the filter suffix ) to narrow down the search to only the entries matching l=Sunnyvale:

(&(l=Sunnyvale)(sn=Jensen))

You can set up the filter prefix and suffix in several ways:

  • To set these for all filters generated from the filter configuration file, invoke the setFilterAffixes method of the LDAPFilterDescriptor object.
  • To set the prefix or suffix for a specific filter, do one of the following:
    • Invoke the setFilterAffixes method of the LDAPFilter object, then invoke the getFilter method, passing in the search term again. This builds the filter again, using the specified search term with the prefix and suffix.
    • Invoke the getFilter method, passing in the search term, the prefix, and the suffix.
    • Invoke the setupFilter method, passing the search term, the prefix, and the suffix.
      Setting the prefix and suffix for an individual filter overrides any prefix or suffix set for the entire filter configuration file.

Adding Affixes for All Filters

The following code loads a filter configuration file into memory, and adds the prefix (&(l=Sunnyvale and suffix ) to each filter retrieved from the file:

LDAPFilterDescriptor filtdesc = null;
try {
    /* Read in the filter configuration file. */
    filtdesc = new LDAPFilterDescriptor("ldapfilter.conf");

    /* Add the specified prefix and suffix to all filters. */
    String prefix = "((l=Sunnyvale)";
    String suffix = ")";
    filtdesc.setFilterAffixes(prefix, suffix);

    /* Get filters from the section "people" */
    LDAPFilterList filtlist = null;
    try {
        filtlist = filtdesc.getFilters("people", searchTerm);
    } catch (Exception e) {
        System.out.println("No matching tag section or filter");
        System.exit(0);
    }

    /* Iterate through the lines in the list. */
    while (filtlist.hasMoreElements()) {
        LDAPFilter filtline = filtlist.next();

        /* Get and print each filter. */
        String filterString = filtline.getFilter();
        System.out.println("  Generated filter string: " +
            filterString + "\n");
    }
} catch (Exception e) {
    System.out.println("Error: " + e.toString());
}

For example, if the following search term is passed to the LDAPFilterDescriptor.getFilters method:

bjensen@example.com

and the corresponding filter, not including the prefix or suffix, is:

(mail=bjensen@example.com)

the entire filter string retrieved by the LDAPFilter.getFilter method is:

(&(l=Sunnyvale)(mail=bjensen@example.com))

Adding Affixes Using setFilterAffixes

The following code loads a filter configuration file <filename>ldapfilter.conf </filename> into memory, and uses the LDAPFilter.setFilterAffixes method to add the prefix (&(l=Sunnyvale and suffix ) to a generated filter:

LDAPFilterDescriptor filtdesc = null;
try {
    /* Read in the filter configuration file. */
    filtdesc = new LDAPFilterDescriptor("ldapfilter.conf");

    /* Get filters from the section "people" */
    LDAPFilterList filtlist = null;
    try {
        filtlist = filtdesc.getFilters("people", searchTerm);
    } catch (Exception e) {
        System.out.println("No matching tag section or filter");
        System.exit(0);
    }

    /* Iterate through the lines in the list. */
    while (filtlist.hasMoreElements()) {
        LDAPFilter filtline = filtlist.next();

        /* Add the prefix and suffix, and generate the filter. */
        String prefix = "((l=Sunnyvale)";
        String suffix = ")";
        filtline.setFilterAffixes(prefix, suffix);
        String filterString = filtline.getFilter(searchTerm);
        System.out.println("  Generated filter string: " +
            filterString + "\n");
    }
} catch ( Exception e ) {
    System.out.println( "Error: " + e.toString() );
}

For example, if the following search term is passed to the LDAPFilterDescriptor.getFilters method:

bjensen@example.com

and the corresponding filter, not including the prefix or suffix, is:

(mail=bjensen@example.com)

the entire filter string retrieved by the LDAPFilter.getFilter method is:

(&(l=Sunnyvale)(mail=bjensen@example.com))

Adding Affixes Using getFilter

The following code loads a filter configuration file into memory, and uses the LDAPFilter.getFilter method to add the prefix (&(l=Sunnyvale and suffix ) to a generated filter:

LDAPFilterDescriptor filtdesc = null;
try {
    /* Read in the filter configuration file. */
    filtdesc = new LDAPFilterDescriptor("ldapfilter.conf");

    /* Get filters from the section "people" */
    LDAPFilterList filtlist = null;
    try {
        filtlist = filtdesc.getFilters("people", searchTerm);
    } catch (Exception e) {
        System.out.println("No matching tag section or filter");
        System.exit(0);
    }

    /* Iterate through the lines in the list. */
    while (filtlist.hasMoreElements()) {
        LDAPFilter filtline = filtlist.next();

        /* Add the prefix and suffix, and generate the filter. */
        String prefix = "((l=Sunnyvale)";
        String suffix = ")";
        String filterString =
            filtline.getFilter(searchTerm, prefix, suffix);
        System.out.println("  Generated filter string: " +
            filterString + "\n");
    }
} catch ( Exception e ) {
    System.out.println( "Error: " + e.toString() );
}

For example, if the following search term is passed to the LDAPFilterDescriptor.getFilters method:

bjensen@example.com

and the corresponding filter, not including the prefix or suffix, is:

(mail=bjensen@example.com)

the entire filter string retrieved by the LDAPFilter.getFilter method is:

(&(l=Sunnyvale)(mail=bjensen@example.com))

Adding Affixes Using setupFilter

The following code loads a filter configuration file <filename>ldapfilter.conf </filename> into memory, and uses the LDAPFilter.setupFilter method to add the prefix (&(l=Sunnyvale and suffix ) to a generated filter:

LDAPFilterDescriptor filtdesc = null;
try {
    /* Read in the filter configuration file. */
    filtdesc = new LDAPFilterDescriptor("ldapfilter.conf");

    /* Get filters from the section "people" */
    LDAPFilterList filtlist = null;
    try {
        filtlist = filtdesc.getFilters("people", searchTerm);
    } catch (Exception e) {
        System.out.println("No matching tag section or filter");
        System.exit(0);
    }

    /* Iterate through the lines in the list. */
    while (filtlist.hasMoreElements()) {
        LDAPFilter filtline = filtlist.next();

        /* Add the prefix and suffix, and generate the filter. */
        String prefix = "((l=Sunnyvale)";
        String suffix = ")";
        filtline.setupFilter(searchTerm, prefix, suffix);
        String filterString = filtline.getFilter();
        System.out.println("  Generated filter string: "
            + filterString + "\n");
    }
} catch ( Exception e ) {
    System.out.println( "Error: " + e.toString() );
}

For example, if the following search term is passed to the LDAPFilterDescriptor.getFilters method:

bjensen@example.com

and the corresponding filter, not including the prefix or suffix, is:

(mail=bjensen@example.com)

the entire filter string retrieved by the LDAPFilter.getFilter method is:

(&(l=Sunnyvale)(mail=bjensen@example.com))