import java.util.Hashtable;
import java.util.Enumeration;
import java.util.Properties;
import javax.naming.*;
import javax.naming.directory.*;
import com.sun.jndi.ldap.*;
class Search {
/*
* 実行環境に合わせて以下のパラメタを変更してください。
*/
public static final String ldapurl = "ldap://localhost:636";
public static final String binddn = "cn=admin";
public static final String password = "admin";
public static final String sslenvfile = "c:\\ssl_env\\sslconfig.cfg";
public static final String ssllogdir = "c:\\ssl_env\\";
public static final String s_base = "c=jp";
public static final String filter = "cn=taro";
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, ldapurl );
env.put(Context.SECURITY_AUTHENTICATION, "simple" );
env.put(Context.SECURITY_PRINCIPAL, binddn );
env.put(Context.SECURITY_CREDENTIALS, password );
env.put("java.naming.referral", "follow" );
/* SSL用の環境プロパティのセット */
env.put("java.naming.ldap.factory.socket", "com.fujitsu.ssl.FjSSLSocketFactory");
env.put(Context.SECURITY_PROTOCOL, "ssl" );
//システムプロパティの取得
Properties prop = System.getProperties();
prop.put("user.sslenvfile", sslenvfile);
prop.put("user.ssllogdir", ssllogdir );
try
{
/* ディレクトリサーバに接続 */
DirContext ctx = new InitialDirContext(env);
/* 検索範囲の指定 */
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
/* 検索開始位置:c=jp、検索フィルタ:cn=taro で検索実行 */
NamingEnumeration results = ctx.search(s_base, filter, constraints);
/* 検索結果の表示 */
while (results != null && results.hasMore()) {
SearchResult si = (SearchResult)results.next();
System.out.println("name: " + si.getName());
Attributes attrs = si.getAttributes();
if (attrs == null) {
System.out.println("No attributes");
} else {
/* print each attribute */
for (NamingEnumeration ae = attrs.getAll();
ae.hasMoreElements(); ) {
Attribute attr = (Attribute)ae.next();
String attrId = attr.getID();
for (Enumeration vals = attr.getAll();
vals.hasMoreElements();
System.out.println(attrId + ": " + vals.nextElement()));
}
}
System.out.println();
}
ctx.close();
}
catch(NamingException ne)
{
Throwable msg = ne.getRootCause();
String msgStr = null;
int ssl_error = -1;
if ( msg != null ) {
/* エラーメッセージの取得 */
msgStr = msg.toString();
/* エラーを取得するキー検索 */
ssl_error = msgStr.indexOf("FjSSLSocket");
}
/* SSLのときの処理 */
if ( ssl_error != -1 ) {
int index1 = msgStr.indexOf("errtype=") + "errtype=".length();
if ( index1 != -1 ) {
/* エラータイプの取得 */
String error = msgStr.substring(index1, index1 + 2);
/* エラータイプの表示 */
System.out.println("SSL Error code : " + error);
}
}
System.out.println("Search example failed.");
ne.printStackTrace();
}
catch(Exception e)
{
System.out.println(e.getMessage());
System.out.println(e.getLocalizedMessage());
e.printStackTrace();
}
}
}
|