Search code examples
javaldapunboundid-ldap-sdk

Java question (calling methods with parameters) using UnboundID LDAP SDK api


I'm using UnboundID LDAP SDK for my LDAP server. I made a method for connecting.

public static LDAPConnection connectSDK(String ip, Integer port, String id, String pw) throws LDAPException    {

    LDAPConnection ldap = new LDAPConnection(ip,port,id,pw);
    System.out.println("success");  
    return ldap;

}

In my main method, I call this methods with parameters, and it works fine.

public static void main(String[] args) throws LDAPException {

    connectSDK("192.168.0.60",389,"******","*****");

}   

I wanted to go further. I made a method to search data using a filter.

public static void searchSDK(String filter) throws LDAPException {

    LDAPConnection ldap = connectSDK(); 

/* Before calling a method with parameter, I used to connect with this,
 and use 'ldap' variable to put search results. 
Now, I am using a method with parameters. 
I don't know what to do with 'ldap' variable. 
If I delete it, 'SearchRequest' doesn't run.  
Also how can I continue to use the connection from connectSDK method? */

    SearchRequest searchRequest = new SearchRequest("c=kr",SearchScope.SUB,filter);
    SearchResult searchResult = ldap.search(searchRequest);
    System.out.println(searchResult);

}

Ultimately, I want to call two of these methods in my main like below.

public static void main(String[] args) throws LDAPException {
    //connect
    connectSDK("192.168.0.60",389,"*****","******");
    //search using a filter 
    searchSDK("hotdog");
}  

I want advice in my searchSDK() methods.
*1) how to use the session connectSDK method created
*2) how to handle 'ldap' variable.
*3) ldap.close() I want to close a session after, but this method wouldn't work. Is there any other way?


Solution

  • There is no such method in your code LDAPConnection ldap = connectSDK(); As connectSDK(String ip, Integer port, String id, String pw) returns a LDAPConnection then pass this as a parameter into searchSDK and remove connectSDK() from it.

    Modify the code as

    public static void searchSDK(String filter, LDAPConnection ldap) throws LDAPException {
    
        // LDAPConnection ldap = connectSDK(); 
    ....
    }
    

    So your main would look like

    LDAPConnection ldap = connectSDK("192.168.0.60",389,"*****","******");
    //search using a filter 
    searchSDK("hotdog", ldap);