Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.event.EventContext;
import javax.naming.event.NamespaceChangeListener;
import javax.naming.event.NamingEvent;
import javax.naming.event.NamingExceptionEvent;
import javax.naming.event.NamingListener;

public class Main {
    public static void main(String[] argv) throws Exception {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "YourURL");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "userDN");
        env.put(Context.SECURITY_CREDENTIALS, "secret");
        EventContext ctx = (EventContext) (new InitialContext(env).lookup("ou=People"));

        NamingListener listener = new SampleNCListener();

        ctx.addNamingListener("cn=John", EventContext.ONELEVEL_SCOPE, listener);
    }
}

class SampleNCListener implements NamespaceChangeListener {
    public SampleNCListener() {
    }

    public void objectAdded(NamingEvent evt) {
        System.out.println(evt.getNewBinding().getName());
    }

    public void objectRemoved(NamingEvent evt) {
        System.out.println(evt.getOldBinding().getName());
    }

    public void objectRenamed(NamingEvent evt) {
        System.out.println(evt.getOldBinding().getName());
    }

    public void namingExceptionThrown(NamingExceptionEvent evt) {
        System.out.println(evt.getException().getExplanation());
    }
}