2016年11月11日 星期五

apacheDS API search, add, modify and delete ( 1.0.0-RC2 )

再來就是寫 client 的部份,嗯~因為懶惰,所以我也順便用同一套的http://directory.apache.org/api/
在此使用的版本是  API 1.0.0-RC2...

看起來都也是剛 release,不過以官網文件程度來說的話,有比 ds 好T_T...雖然也是有點差異,但相比之下,真的是算好的~只是,這文件妙的是,他連之後的功能都先寫上去了!?(不過實際上我都拿最新版的了,還點不出那個 method,或關鍵字眼XD...)
https://directory.apache.org/api/user-guide/2-basic-ldap-api-usage.html

先測一下最常用的查詢,新增,和修改。基本上沒啥太大的問題。
用法原則上就是 建 client,開 connect, 然後操作(操作時會用到一些 cursor,這個用完記得要關),最後就是 close。
大概有些會很常用到的,檢查是否存在(connection.exists),等於是一個 ldap 的search...然後下filiter指定單一項目,不過可以一行就寫出來是很方便的~

建 Entry 時,要加進去的 attribute 跟內容時,可以多利用 studio 防呆做出結構來看,就比憑空想像來的簡單~dn name的一行內容,也可以從studio 的介面看到,較不容易少key層級~

在新增 Entry 時,透過 request, response。就要看response 是否成功,還是得用官方寫法: response.getLdapResult().getResultCode().equals(ResultCodeEnum.SUCCESS)
那個isDefaultSuccess()...目前還不行XD...
是說,目前碰到有出錯之類(建到重覆,改到不存在的...)的,其實都直接是出 Exception...所以,實做去接 exception 做錯誤處理是比較好的~

另外關於要驗證新增後是否成功的那個method,應該就還沒做好(文件上也有寫是 feature啦,不過目前我看不到在那),所以替代方案就是,先 sleep 一下,或是另起 thread 晚一點去確認那個 entry 是否存在了~

修改密碼的話,目前寫進去後,會被default用 ssha hash,

maven dependency
        <dependency>
            <groupId>org.apache.directory.api</groupId>
            <artifactId>api-all</artifactId>
            <version>1.0.0-RC2</version>
        </dependency>

import 使用到的部份
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.cursor.SearchCursor;
import org.apache.directory.api.ldap.model.entry.DefaultEntry;
import org.apache.directory.api.ldap.model.entry.DefaultModification;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.entry.Modification;
import org.apache.directory.api.ldap.model.entry.ModificationOperation;
import org.apache.directory.api.ldap.model.message.AddRequest;
import org.apache.directory.api.ldap.model.message.AddRequestImpl;
import org.apache.directory.api.ldap.model.message.AddResponse;
import org.apache.directory.api.ldap.model.message.Control;
import org.apache.directory.api.ldap.model.message.DeleteRequest;
import org.apache.directory.api.ldap.model.message.DeleteRequestImpl;
import org.apache.directory.api.ldap.model.message.DeleteResponse;
import org.apache.directory.api.ldap.model.message.Response;
import org.apache.directory.api.ldap.model.message.ResultCodeEnum;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
import org.apache.directory.api.ldap.model.message.SearchResultEntry;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.message.controls.OpaqueControl;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;


code 的部份(標一下建 connection 和 close 的地方)
        LdapConnection connection = new LdapNetworkConnection( "127.0.0.1", 10389 );
        connection.connect();
        System.out.println("connection="+connection);
       
        //Simple search
        System.out.println("====Simple search");
        EntryCursor cursor = connection.search( "ou=system", "(objectclass=*)", SearchScope.ONELEVEL );

        while ( cursor.next() )  {
            Entry entry = cursor.get();
            System.out.println( entry );
        }
        cursor.close();
       
        //Searching using a DN
        System.out.println("====Dn search");
        Dn systemDn = new Dn( "ou=system" );
        EntryCursor cursor2 = connection.search( systemDn, "(objectclass=*)", SearchScope.ONELEVEL );

        while ( cursor2.next() )  {
            Entry entry = cursor2.get();
            System.out.println( entry );
        }

        cursor2.close();
       
        // Create the SearchRequest object
        System.out.println("====SearchRequest object");
        SearchRequest req = new SearchRequestImpl();
        req.setScope( SearchScope.SUBTREE );
        req.addAttributes( "*" );
        req.setTimeLimit( 0 );
        req.setBase( new Dn( "dc=example,dc=com" ) );
        //req.setFilter( "(objectClass=*)" );  //search all
        req.setFilter( "(ou=users)" );  //assign some

        // Process the request
        SearchCursor searchCursor = connection.search( req );

        while ( searchCursor.next() )  {
            Response response = searchCursor.get();

            // process the SearchResultEntry
            if ( response instanceof SearchResultEntry )  {
                Entry resultEntry = ( ( SearchResultEntry ) response ).getEntry();
                System.out.println(resultEntry);
            }
        }
        searchCursor.close();
       
        System.out.println("======Test Search End========");
        System.out.println("======START to UPDATE");
        String uname1="AddTest11";
        Entry entry1 = new DefaultEntry(
                "cn="+uname1+",ou=users,dc=example,dc=com",
                "ObjectClass: top",
                "ObjectClass: inetOrgPerson",
                "ObjectClass: person",
                "ObjectClass: organizationalPerson",
                "cn: "+uname1,
                "sn: "+uname1 );
        if(!connection.exists("cn="+uname1+",ou=users,dc=example,dc=com"))  {
            AddRequest addRequest = new AddRequestImpl();
            addRequest.setEntry( entry1 );
            AddResponse response = connection.add( addRequest );
            System.out.println(response.getLdapResult().isDefaultSuccess());  //why this is false ?_?a...bug?
            if( response.getLdapResult().isDefaultSuccess()
                    || response.getLdapResult().getResultCode().equals(ResultCodeEnum.SUCCESS))  {
                System.out.println("Add OK");
            }  else  {
                System.out.println("not default success["+response.getLdapResult().getResultCode()+"]:"+response.getLdapResult().getDiagnosticMessage());
            }
        }
        //check exist? check it after wait some while
        Thread.currentThread().sleep(1000);
        if(connection.exists("cn="+uname1+",ou=users,dc=example,dc=com"))  {
            System.out.println("re check add OK");
        }
       
        //https://directory.apache.org/api/user-guide/2.6-modifying.html
        //modify
        Modification modify1 = new DefaultModification( ModificationOperation.ADD_ATTRIBUTE, "uid", "testuser" );
        Modification modify2 = new DefaultModification( ModificationOperation.ADD_ATTRIBUTE, "givenName", "Well", "Smile" );
        Modification modify3 = new DefaultModification( ModificationOperation.ADD_ATTRIBUTE, "userPassword", "t123456" );
        connection.modify( "cn="+uname1+",ou=users,dc=example,dc=com", modify1,  modify2, modify3);
       
        System.out.println("======START to Delete");
        //delete easy
        connection.delete( "cn=AddTest2,ou=users,dc=example,dc=com" );
       
        //delete by repsonse
        DeleteRequest deleteRequest = new DeleteRequestImpl();
        deleteRequest.setName( new Dn( "cn=AddTest3,ou=users,dc=example,dc=com" ) );
        Control deleteTreeControl = new OpaqueControl( "1.2.840.113556.1.4.805" );
        deleteRequest.addControl( deleteTreeControl );
        DeleteResponse deleteResponse = connection.delete( deleteRequest );
        if( deleteResponse.getLdapResult().isDefaultSuccess()
                || deleteResponse.getLdapResult().getResultCode().equals(ResultCodeEnum.SUCCESS))  {
            System.out.println("Delete OK");
        }  else  {
            System.out.println("delete fail["+deleteResponse.getLdapResult().getResultCode()+"]:"+deleteResponse.getLdapResult().getDiagnosticMessage());
        }
       
        connection.close();

沒有留言: