Example usage for javax.naming.directory DirContext close

List of usage examples for javax.naming.directory DirContext close

Introduction

In this page you can find the example usage for javax.naming.directory DirContext close.

Prototype

public void close() throws NamingException;

Source Link

Document

Closes this context.

Usage

From source file:Compare.java

public static void main(String[] args) {

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {//  w w  w. j  ava  2s .  com
        // Create initial context
        DirContext ctx = new InitialDirContext(env);

        // Value of attribute
        byte[] key = { (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66,
                (byte) 0x67 };

        // Set up search controls
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(new String[0]); // return no attrs
        ctls.setSearchScope(SearchControls.OBJECT_SCOPE); // search object only

        // Invoke search method that will use the LDAP "compare" operation
        NamingEnumeration answer = ctx.search("cn=S. User, ou=NewHires", "(mySpecialKey={0})",
                new Object[] { key }, ctls);

        // Print the answer
        // FilterArgs.printSearchEnumeration(answer);

        // Close the context when we're done
        ctx.close();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:SearchObject.java

public static void main(String[] args) {

    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {//from w  w w  .j a v  a  2  s.  com
        // Create initial context
        DirContext ctx = new InitialDirContext(env);

        // Specify the ids of the attributes to return
        String[] attrIDs = { "sn", "telephonenumber", "golfhandicap", "mail" };
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(attrIDs);
        ctls.setSearchScope(SearchControls.OBJECT_SCOPE);

        // Specify the search filter to match
        // Ask for objects with attribute sn == Geisel and which have
        // the "mail" attribute.
        String filter = "(&(sn=Geisel)(mail=*))";

        // Search subtree for objects using filter
        NamingEnumeration answer = ctx.search("cn=Ted Geisel, ou=People", filter, ctls);

        // Print the answer
        // Search.printSearchEnumeration(answer);

        // Close the context when we're done
        ctx.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Create.java

public static void main(String[] args) {

    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {//from  w  w w.ja va  2 s.  com
        // Create the initial context
        DirContext ctx = new InitialDirContext(env);

        // Create attributes to be associated with the new context
        Attributes attrs = new BasicAttributes(true); // case-ignore
        Attribute objclass = new BasicAttribute("objectclass");
        objclass.add("top");
        objclass.add("organizationalUnit");
        attrs.put(objclass);

        // Create the context
        Context result = ctx.createSubcontext("ou=NewOu", attrs);

        // Check that it was created by listing its parent
        NamingEnumeration list = ctx.list("");

        // Go through each item in list
        while (list.hasMore()) {
            NameClassPair nc = (NameClassPair) list.next();
            System.out.println(nc);
        }

        // Close the contexts when we're done
        result.close();
        ctx.close();
    } catch (NamingException e) {
        System.out.println("Create failed: " + e);
    }
}

From source file:ModAttrs.java

public static void main(String[] args) {

    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {/*www  .  j a v  a 2s .  co m*/
        // Create the initial context
        DirContext ctx = new InitialDirContext(env);
        String name = "cn=Ted Geisel, ou=People";

        // Save original attributes
        Attributes orig = ctx.getAttributes(name, new String[] { "mail", "telephonenumber", "jpegphoto" });

        // Specify the changes to make
        ModificationItem[] mods = new ModificationItem[3];

        // Replace the "mail" attribute with a new value
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                new BasicAttribute("mail", "geisel@wizards.com"));

        // Add additional value to "telephonenumber"
        mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE,
                new BasicAttribute("telephonenumber", "+1 555 555 5555"));

        // Remove the "jpegphoto" attribute
        mods[2] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("jpegphoto"));

        // Perform the requested modifications on the named object
        ctx.modifyAttributes(name, mods);

        // Check attributes
        System.out.println("**** new attributes *****");
        printAttrs(ctx.getAttributes(name));

        // Revert changes
        ctx.modifyAttributes(name, DirContext.REPLACE_ATTRIBUTE, orig);

        // Check that the attributes got restored
        System.out.println("**** reverted to original attributes *****");
        printAttrs(ctx.getAttributes(name));

        // Close the context when we're done
        ctx.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:LdapUtils.java

/**
 * Close the given context and ignore any thrown exception. This is useful
 * for typical finally blocks in manual Ldap statements.
 * /*from ww w. j av  a  2  s.com*/
 * @param context the Ldap context to close
 */
public static void closeContext(final DirContext context) {
    if (context != null) {
        try {
            context.close();
        } catch (NamingException ex) {

        }
    }
}

From source file:com.ktds.ldap.populator.LdapTestUtils.java

/**
 * Load an Ldif file into an LDAP server.
 *
 * @param contextSource ContextSource to use for getting a DirContext to
 *                      interact with the LDAP server.
 * @param ldifFile      a Resource representing a valid LDIF file.
 * @throws IOException if the Resource cannot be read.
 */// w  w  w  . j a  v  a 2 s.  c om
public static void loadLdif(ContextSource contextSource, Resource ldifFile) throws IOException {
    DirContext context = contextSource.getReadWriteContext();
    try {
        loadLdif(context, ldifFile);
    } finally {
        try {
            context.close();
        } catch (Exception e) {
            // This is not the exception we are interested in.
        }
    }
}

From source file:com.ktds.ldap.populator.LdapTestUtils.java

/**
 * Clear the directory sub-tree starting with the node represented by the
 * supplied distinguished name.//from   w  w  w  . j  a  v  a  2  s.  c  o m
 *
 * @param contextSource the ContextSource to use for getting a DirContext.
 * @param name          the distinguished name of the root node.
 * @throws NamingException if anything goes wrong removing the sub-tree.
 */
public static void clearSubContexts(ContextSource contextSource, Name name) throws NamingException {
    DirContext ctx = null;
    try {
        ctx = contextSource.getReadWriteContext();
        clearSubContexts(ctx, name);
    } finally {
        try {
            ctx.close();
        } catch (Exception e) {
            // Never mind this
        }
    }
}

From source file:com.ery.ertc.estorm.util.DNS.java

/**
 * Returns the hostname associated with the specified IP address by the provided nameserver.
 * /*from ww  w.  j  ava2s  . c  o m*/
 * @param hostIp
 *            The address to reverse lookup
 * @param ns
 *            The host name of a reachable DNS server
 * @return The host name associated with the provided IP
 * @throws NamingException
 *             If a NamingException is encountered
 */
public static String reverseDns(InetAddress hostIp, String ns) throws NamingException {
    //
    // Builds the reverse IP lookup form
    // This is formed by reversing the IP numbers and appending in-addr.arpa
    //
    String[] parts = hostIp.getHostAddress().split("\\.");
    String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "." + parts[0] + ".in-addr.arpa";

    DirContext ictx = new InitialDirContext();
    Attributes attribute = ictx.getAttributes("dns://" // Use "dns:///" if the default
            + ((ns == null) ? "" : ns) +
            // nameserver is to be used
            "/" + reverseIP, new String[] { "PTR" });
    ictx.close();

    String hostname = attribute.get("PTR").get().toString();
    int hostnameLength = hostname.length();
    if (hostname.charAt(hostnameLength - 1) == '.') {
        hostname = hostname.substring(0, hostnameLength - 1);
    }
    return hostname;
}

From source file:no.smint.anthropos.ldap.LDAP.java

public static PersonList retrieve() throws NamingException {
    Hashtable<String, Object> env = config();

    DirContext ctx = new InitialDirContext(env);

    //Search controller
    SearchControls ctls = new SearchControls();

    //The actual search
    NamingEnumeration answer = ctx.search("ou=Users,dc=studentmediene,dc=no", "(&(memberOf=*))", ctls);

    ctx.close();
    return SearchProcessing.getPersons(answer);
}

From source file:com.buaa.cfs.net.DNS.java

/**
 * Returns the hostname associated with the specified IP address by the provided nameserver.
 * <p>//www .  ja  v  a 2  s.  co  m
 * Loopback addresses
 *
 * @param hostIp The address to reverse lookup
 * @param ns     The host name of a reachable DNS server
 *
 * @return The host name associated with the provided IP
 *
 * @throws NamingException If a NamingException is encountered
 */
public static String reverseDns(InetAddress hostIp, String ns) throws NamingException {
    //
    // Builds the reverse IP lookup form
    // This is formed by reversing the IP numbers and appending in-addr.arpa
    //
    String[] parts = hostIp.getHostAddress().split("\\.");
    String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "." + parts[0] + ".in-addr.arpa";

    DirContext ictx = new InitialDirContext();
    Attributes attribute;
    try {
        attribute = ictx.getAttributes("dns://" // Use "dns:///" if the default
                + ((ns == null) ? "" : ns) +
                // nameserver is to be used
                "/" + reverseIP, new String[] { "PTR" });
    } finally {
        ictx.close();
    }

    String hostname = attribute.get("PTR").get().toString();
    int hostnameLength = hostname.length();
    if (hostname.charAt(hostnameLength - 1) == '.') {
        hostname = hostname.substring(0, hostnameLength - 1);
    }
    return hostname;
}