go to  ForumEasy.com   
LdapPro  
 
 
   Home  |  MyForum  |  FAQ  |  Archive    You are not logged in. [Login] or [Register]  
Forum Home » LDAP Operations & Controls » LDAP Sort Control -- RFC 2891
Email To Friend  |   Set Alert To This Topic Rewarding Points Availabe: 0 (What's this) New Topic  |   Post Reply
Author Topic: LDAP Sort Control -- RFC 2891
SteveHB
member
offline   
 
posts: 113
joined: 05/31/2006
from: Mountain View, CA
  posted on: 06/07/2007 12:43:20 PM    Edit  |   Quote  |   Report 
LDAP Sort Control -- RFC 2891
Request Control

This control is included in the searchRequest message as part of the
controls field of the LDAPMessage, as defined in Section 4.1.12 of
[LDAPv3].

The controlType is set to 1.2.840.113556.1.4.473. The criticality
MAY be either TRUE or FALSE (where absent is also equivalent to
FALSE) at the client's option. The controlValue is an OCTET STRING,
whose value is the BER encoding of a value of the following SEQUENCE:
      SortKeyList ::= SEQUENCE OF SEQUENCE {
                 attributeType   AttributeDescription,
                 orderingRule    [0] MatchingRuleId OPTIONAL,
                 reverseOrder    [1] BOOLEAN DEFAULT FALSE }

The SortKeyList sequence is in order of highest to lowest sort key
precedence.

The MatchingRuleId, as defined in section 4.1.9 of [LDAPv3], SHOULD
be one that is valid for the attribute type it applies to. If it is
not, the server will return inappropriateMatching.

Each attributeType should only occur in the SortKeyList once. If an
attributeType is included in the sort key list multiple times, the
server should return an error in the sortResult of
unwillingToPerform.

If the orderingRule is omitted, the ordering MatchingRule defined for
use with this attribute MUST be used.

Any conformant implementation of this control MUST allow a sort key
list with at least one key.
 Profile | Reply Points Earned: 0
SteveHB
member
offline   
 
posts: 113
joined: 05/31/2006
from: Mountain View, CA
  posted on: 06/07/2007 12:47:50 PM    Edit  |   Quote  |   Report 
Response Control

This control is included in the searchResultDone message as part of
the controls field of the LDAPMessage, as defined in Section 4.1.12
of [LDAPv3].

The controlType is set to 1.2.840.113556.1.4.474. The criticality
is FALSE (MAY be absent). The controlValue is an OCTET STRING, whose
value is the BER encoding of a value of the following SEQUENCE:
      SortResult ::= SEQUENCE {
         sortResult  ENUMERATED {
             success                   (0), -- results are sorted
             operationsError           (1), -- server internal failure
             timeLimitExceeded         (3), -- timelimit reached before
                                            -- sorting was completed
             strongAuthRequired        (8), -- refused to return sorted
                                            -- results via insecure
                                            -- protocol
             adminLimitExceeded       (11), -- too many matching entries
                                            -- for the server to sort
             noSuchAttribute          (16), -- unrecognized attribute
                                            -- type in sort key
             inappropriateMatching    (18), -- unrecognized or
                                            -- inappropriate matching
                                            -- rule in sort key
             insufficientAccessRights (50), -- refused to return sorted
                                            -- results to this client
             busy                     (51), -- too busy to process
             unwillingToPerform       (53), -- unable to sort
             other                    (80)
             },
       attributeType [0] AttributeDescription OPTIONAL }

 Profile | Reply Points Earned: 0
SteveHB
member
offline   
 
posts: 113
joined: 05/31/2006
from: Mountain View, CA
  posted on: 06/07/2007 12:57:43 PM    Edit  |   Quote  |   Report 
Client-Server Interaction

The sortKeyRequestControl specifies one or more attribute types and
matching rules for the results returned by a search request. The
server SHOULD return all results for the search request in the order
specified by the sort keys. If the reverseOrder field is set to TRUE,
then the entries will be presented in reverse sorted order for the
specified key.

There are six possible scenarios that may occur as a result of the
sort control being included on the search request:

1 - If the server does not support this sorting control and the
client specified TRUE for the control's criticality field, then
the server MUST return unavailableCriticalExtension as a return
code in the searchResultDone message and not send back any other
results. This behavior is specified in section 4.1.12 of
[LDAPv3].

2 - If the server does not support this sorting control and the
client specified FALSE for the control's criticality field, then
the server MUST ignore the sort control and process the search
request as if it were not present. This behavior is specified in
section 4.1.12 of [LDAPv3].

3 - If the server supports this sorting control but for some reason
cannot sort the search results using the specified sort keys and
the client specified TRUE for the control's criticality field,
then the server SHOULD do the following: return
unavailableCriticalExtension as a return code in the
searchResultDone message; include the sortKeyResponseControl in
the searchResultDone message, and not send back any search result
entries.

4 - If the server supports this sorting control but for some reason
cannot sort the search results using the specified sort keys and
the client specified FALSE for the control's criticality field,
then the server should return all search results unsorted and
include the sortKeyResponseControl in the searchResultDone
message.

5 - If the server supports this sorting control and can sort the
search results using the specified sort keys, then it should
include the sortKeyResponseControl in the searchResultDone
message with a sortResult of success.

6 - If the search request failed for any reason and/or there are no
searchResultEntry messages returned for the search response, then
the server SHOULD omit the sortKeyResponseControl from the
searchResultDone message.

The client application is assured that the results are sorted in the
specified key order if and only if the result code in the
sortKeyResponseControl is success. If the server omits the
sortKeyResponseControl from the searchResultDone message, the client
SHOULD assume that the sort control was ignored by the server.

The sortKeyResponseControl, if included by the server in the
searchResultDone message, should have the sortResult set to either
success if the results were sorted in accordance with the keys
specified in the sortKeyRequestControl or set to the appropriate
error code as to why it could not sort the data (such as
noSuchAttribute or inappropriateMatching). Optionally, the server MAY
set the attributeType to the first attribute type specified in the
SortKeyList that was in error. The client SHOULD ignore the
attributeType field if the sortResult is success.

The server may not be able to sort the results using the specified
sort keys because it may not recognize one of the attribute types,
the matching rule associated with an attribute type is not
applicable, or none of the attributes in the search response are of
these types. Servers may also restrict the number of keys allowed in
the control, such as only supporting a single key.

Servers that chain requests to other LDAP servers should ensure that
the server satisfying the client's request sort the entire result set
prior to sending back the results.

 Profile | Reply Points Earned: 0
SteveHB
member
offline   
 
posts: 113
joined: 05/31/2006
from: Mountain View, CA
  posted on: 06/07/2007 01:22:21 PM    Edit  |   Quote  |   Report 
Code Example
/**
 * 
 * SortControlJndiClient.java
 * Sample code to demonstrate how Sort Control works.
 * 
 */
 
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;

import java.util.Hashtable;

public class SortControlJndiClient 
{
	
  static final String  SORT_CONTROL_OID = "1.2.840.113556.1.4.473";
    
  public static void main(String[] args)
  {
    Hashtable env = new Hashtable();
        
    env.put(Context.INITIAL_CONTEXT_FACTORY, 
                    "com.sun.jndi.ldap.LdapCtxFactory");
        
    env.put(Context.PROVIDER_URL, "ldap://myAD.mydomain.com:389");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "administrator@mydomain.com");
    env.put(Context.SECURITY_CREDENTIALS, "mypassword");
        
    try{
    	
      /* Open an LDAP connection for the provided principal and credentials */
      LdapContext ctx = new InitialLdapContext(env, null);
      System.out.println("Initial binding done!");
            
      /* Query the server to see if the sort control is supported */ 
      if(!isSortControlSupported(ctx)){
         System.out.println("The server does not support Sort Control.");
         System.exit(1);
      }

      
      // Activate Sorting: A list of people sorted by: 
      //     ascending family name and descending given name
      SortKey[] sk = new SortKey[2];
      sk[0] = new SortKey("sn"); // ascending 
      sk[1] = new SortKey("givenName", false, null); // descending
	        
      ctx.setRequestControls(
              new Control[]{new SortControl(sk, Control.CRITICAL)});

      SearchControls ctls = new SearchControls();
      ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
      ctls.setCountLimit(0);

      // Perform the search
      NamingEnumeration results = ctx.search("ou=people,dc=mydomain,dc=com", 
                                           "(objectclass=*)", ctls);
      // Iterate over the search results
      while (results != null && results.hasMore()) {
          // Display an entry
          SearchResult entry = (SearchResult)results.next();
          System.out.println("entryDN=" + entry.getName());
          /* other output here */
      }
	            
      // Examine the sort control response 
      Control[] controls = ctx.getResponseControls();
      if(controls!=null){
        for(int k = 0; k<controls.length; k++){
          if(controls[k] instanceof SortResponseControl){
            SortResponseControl src = 
                     (SortResponseControl)controls[k];
            if(!src.isSorted()){
              throw src.getException();
            }
          }else{
            // Handle other response controls (if any)
          }
        }
      }
	
      // Close the LDAP association
      ctx.close();

    }catch (Exception e){
      e.printStackTrace();
    }
  }

  /**
   * Is Sort control supported?
   *
   * Query the rootDSE object to find out if the sort control
   * is supported.
   */
  static boolean isSortControlSupported(LdapContext ctx) 
				throws NamingException
  {
    SearchControls ctl = new SearchControls();
    ctl.setReturningAttributes(new String[]{"supportedControl"});
    ctl.setSearchScope(SearchControls.OBJECT_SCOPE);

    /* search for the rootDSE object */
    NamingEnumeration results = ctx.search("", "(objectClass=*)", ctl);

    while(results.hasMore()){
      SearchResult entry = (SearchResult)results.next();
      NamingEnumeration attrs = entry.getAttributes().getAll();
      while (attrs.hasMore()){
      	Attribute attr = (Attribute)attrs.next();
       	NamingEnumeration vals = attr.getAll();
        while (vals.hasMore()){
        String value = (String) vals.next();
        if(value.equals(SORT_CONTROL_OID))
           return true;
        }
      }
    }
    return false;
  }

}
 Profile | Reply Points Earned: 0
SteveHB
member
offline   
 
posts: 113
joined: 05/31/2006
from: Mountain View, CA
  posted on: 06/07/2007 01:26:58 PM    Edit  |   Quote  |   Report 
Who Support Sort Control?
Most enterprise LDAP servers support Sort Control. Among them are Active Directory and SunONE Directory Server.

The above code has been tested against AD and SunOne. It works for both server but exceptions may be different when things went wrong.
 Profile | Reply Points Earned: 0
SteveHB
member
offline   
 
posts: 113
joined: 05/31/2006
from: Mountain View, CA
  posted on: 06/07/2007 03:29:40 PM    Edit  |   Quote  |   Report 
AD--javax.naming.OperationNotSupportedException
If some thing goes wrong, e.g. unrecognized attribute sorting key or maching rule, running the above code against Active Directory would bring back the following:


javax.naming.OperationNotSupportedException: [LDAP: error code 12 - 00000057: LdapErr: DSID-0C09068F, comment: Error processing control, data 0, vece]; remaining name 'ou=people,dc=mydomain,dc=com'
at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3065)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2951)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2758)
at com.sun.jndi.ldap.LdapCtx.searchAux(LdapCtx.java:1812)
at com.sun.jndi.ldap.LdapCtx.c_search(LdapCtx.java:1735)
at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(ComponentDirContext.java:368)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContext.java:338)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContext.java:321)
at javax.naming.directory.InitialDirContext.search(InitialDirContext.java:248)

 Profile | Reply Points Earned: 0
SteveHB
member
offline   
 
posts: 113
joined: 05/31/2006
from: Mountain View, CA
  posted on: 06/07/2007 03:34:05 PM    Edit  |   Quote  |   Report 
SunOne--javax.naming.CommunicationException
If some thing goes wrong, e.g. unrecognized attribute sorting key or maching rule, running the above code against SunOne Directory Server would, however, bring back the following:

javax.naming.CommunicationException:[LDAP: error code 2 - Sort Control]; remaining name 'ou=people,dc=mydomain,dc=com'
at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3053)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2951)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2758)
at com.sun.jndi.ldap.LdapCtx.searchAux(LdapCtx.java:1812)
at com.sun.jndi.ldap.LdapCtx.c_search(LdapCtx.java:1735)
at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(ComponentDirContext.java:368)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContext.java:338)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContext.java:321)
at javax.naming.directory.InitialDirContext.search(InitialDirContext.java:248)

 Profile | Reply Points Earned: 0
SteveHB
member
offline   
 
posts: 113
joined: 05/31/2006
from: Mountain View, CA
  posted on: 07/29/2011 01:31:46 PM    Edit  |   Quote  |   Report 
How do I know the returned results are sorted?
By SPEC:

The client application is assured that the results are sorted in the specified key order if and only if the result code in the sortKeyResponseControl (1.2.840.113556.1.4.474) is success. If the server omits the sortKeyResponseControl (1.2.840.113556.1.4.474) from the searchResultDone message, the client SHOULD assume that the sort control was ignored by the server.

 Profile | Reply Points Earned: 0

 
Powered by ForumEasy © 2003-2005, All Rights Reserved. | Privacy Policy | Terms of Use
 
Get your own forum today. It's easy and free.