Улучшить код Java для LDAP

Я нашел этот код Java для подключения LDAP.

package javaapplication2;

import java.util.Properties;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class SearchLDAP {

    public static void main(String[] args) {
        // The search base is the level in the hierarchy
        // that our search will start at. Here was use ""
        // which indicates the very root of the directory.
        String base = "";
        // LDAP filters are sort of like a WHERE clause. It
        // is constructed in a standard way based on LDAP
        // standards. The search here is a simple one that
        // says to return any entry with an objectclass value.
        // Since all entries must contain an objectclass, all
        // entries will be returned.
        String filter = "(objectclass=*)";
        // Here we set some connection properties for JNDI.
        Properties env = new Properties();
        // The Sun provider is the most widely used JNDI
        // provider and comes with Java 1.3+
        env.put(DirContext.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.ldap.LdapCtxFactory");
        // The provider URL is an LDAP URL that tells JNDI
        // where it will need to connect to.
        env.put(DirContext.PROVIDER_URL, "ldap://localhost:389");
        try {
            // Here we create a DirContext object using
            // the environment we setup above. This
            // object will be used to communicate with
            // the server.
            DirContext dc = new InitialDirContext(env);
            // Above we mentioned the filter and base.
            // Another important part of the search criteria
            // is the scope. There are three scopes: base (this
            // entry only), onelevel (the direct children of this
            // entry), and subtree (this entry and all of its
            // decendents in the tree). In JNDI, OBJECT_SCOPE
            // indicates a base search.
            SearchControls sc = new SearchControls();
            sc.setSearchScope(SearchControls.OBJECT_SCOPE);
            NamingEnumeration ne = null;
            // Here we actually perform the search.
            ne = dc.search(base, filter, sc);
            // We cycle through the NamingEnumeration
            // that is returned by the search.
            while (ne.hasMore()) {
                // Retrieve the result as a SearchResult
                // and print it (not very pretty). There are
                // methods for extracting the attributes and
                // values without printing, as well.
                SearchResult sr = (SearchResult) ne.next();
                System.out.println(sr.toString() + "\n");
            }
            // Here we unbind from the LDAP server.
            dc.close();
        } catch (NamingException nex) {
            // A number of exceptions are subclassed from
            // NamingException. In a real application you'd
            // probably want to handle many of them
            // differently.
            System.err.println("Error: " + nex.getMessage());
        }
    }
}

Можете ли вы помочь мне, как я могу улучшить этот код? Могу ли я использовать пул соединений для многих поисковых запросов, используя одно соединение? А также существует ли какой-либо стандартный метод повышения производительности поиска LDAP? Могу ли я открыть бесконечное соединение с сервером LDAP и оставить его открытым?


person Peter Penzov    schedule 09.01.2014    source источник
comment
Лучший сайт для такого рода вопросов: codereview.stackexchange.com.   -  person Taylor Hx    schedule 10.01.2014
comment
Попробуйте использовать код, который уже широко протестирован и используется как в весеннем ldap: projects.spring.io/spring -ldap   -  person Stephan L    schedule 23.07.2015


Ответы (1)


Можете ли вы помочь мне, как я могу улучшить этот код?

Вы не закрываете NamingEnumeration. Close в блоке finally, чтобы убедиться, что он закрыт. Закройте Context в блоке finally, чтобы убедиться, что он закрыт. К сожалению, эти классы не реализуют AutoCloseable, поэтому вы не можете использовать try()..

Могу ли я использовать пул соединений для многих поисковых запросов, используя одно соединение?

Да. Поставщик JNDI LDAP может сделать это за вас. Просто установите для системного свойства com.sun.jndi.ldap.connect.pool значение true. Существуют связанные свойства: см. документацию JNDI LDAP Provider.

А также существует ли какой-либо стандартный метод повышения производительности поиска LDAP?

Убедитесь, что атрибуты, по которым вы ищете, проиндексированы на сервере LDAP.

Могу ли я открыть бесконечное соединение с сервером LDAP и оставить его открытым?

Не хорошая идея. Лучше использовать пул соединений. См. выше.

person user207421    schedule 09.01.2014
comment
@jeemster Ваш комментарий не имеет ничего общего с моим ответом. Я предлагаю вам указать его как свой собственный ответ, чтобы его можно было прокомментировать, проголосовать и т. д. - person user207421; 02.02.2014