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:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java

private void closeQuietly(DirContext context) {
    try {/*from w  w w  .  j a  va  2 s.  c  o m*/
        if (context != null)
            context.close();
    } catch (NamingException e) {
        LOGGER.log(Level.INFO, "Failed to close DirContext: " + context, e);
    }
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * Get next free uidNumber./*  ww  w. j  a v  a 2 s  .co m*/
 *
 * @return next free uidNumber
 */
private String getNextUidNumber() {
    Hashtable<String, String> env = getLdapConnectionSettings();
    env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
    env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));
    DirContext ctx;
    String rueckgabe = "";
    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(ConfigCore.getParameter("ldap_nextFreeUnixId"));
        Attribute la = attrs.get("uidNumber");
        rueckgabe = (String) la.get(0);
        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
        Helper.setFehlerMeldung(e.getMessage());
    }
    return rueckgabe;
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

/**
* Tries to find the value of the given attribute. Note that this method
* only uses the first search result./* w w  w.j a  v  a  2 s  . c  om*/
* 
* @param username
*            a username
* @param attrName
*            the name of the attribute to find
* @return the value of the attribute, or an empty string
*/
public String getAttr(String username, String attrName) {
    String val = "";
    try {
        DirContext dc = new InitialDirContext(env);
        NamingEnumeration<SearchResult> ne = performLdapSearch(username, dc);

        if (ne.hasMore()) {
            val = getAttrValue(attrName, ne.next());
        }

        ne.close();
        dc.close();
    } catch (NamingException ne) {
        log.warn("Failed LDAP lookup getAttr", ne);
        log.warn("username:", username);
        log.warn("attrName:", attrName);
    }

    log.trace(String.format("getAttr search result: %s", val));
    return val;
}

From source file:fr.iphc.grid.jobmonitor.CeList.java

static public ArrayList<URL> AvailableLdapCe() throws Exception {
    ArrayList<URL> CeList = new ArrayList<URL>();
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://cclcgtopbdii01.in2p3.fr:2170");
    env.put("java.naming.ldap.attributes.binary", "objectSID");
    try {/*from w w  w .  j  a  v  a2 s .  c o m*/
        // Create initial context
        DirContext ctx = new InitialDirContext(env);
        SearchControls contraints = new SearchControls();
        contraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attributIDs = { "GlueCEUniqueID" };
        contraints.setReturningAttributes(attributIDs);
        String BASE_SEARCH = "Mds-Vo-name=local,o=grid";
        String filter = "(&(objectClass=GlueCE)(GlueCEImplementationName=CREAM)(GlueCEAccessControlBaseRule=VO:biomed))";
        NamingEnumeration<SearchResult> answer = ctx.search(BASE_SEARCH, filter, contraints);
        //         int index = 0;
        Random rand = new Random();
        while (answer.hasMore()) {
            //            index++;
            SearchResult result = answer.next();
            //            Attributes attrs = result.getAttributes();
            //            NamingEnumeration f = attrs.getAll();
            //            Attribute attr = (Attribute) f.next();
            String line = "cream://" + result.getAttributes().get("GlueCEUniqueID").get() + "?delegationId="
                    + rand.nextLong();
            URL serviceURL = URLFactory.createURL(line);
            CeList.add(serviceURL);
        }
        // Close the context when we're done
        ctx.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    ;
    return CeList;
}

From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java

/**
 * return false if user or password is wrong
 *    /*from   w w w . j a  va2  s .  co m*/
 * here we expand attributes: %u, %d, %s
 *    if defined userSearch, retrieve user's DN  and try to bind with it
 * @param username
 * @param password
 * @return
 */
private boolean ldapBind(String username, String password) {
    String userDN = null;
    try {
        TempParams t = new TempParams();
        // if username  is an email substitute %u e %d in baseDn:  
        expandSearchAndBaseDn(username, t);

        // setup the default LdapInterface configured with bean data
        ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapInterface.init(getLdapUrl(), getBaseDn(), getSearchBindDn(), getSearchBindPassword(),
                isFollowReferral(), isConnectionPooling(), null);

        // set the userDN when custom user search
        if (!StringUtils.isEmpty(getUserSearch())) {
            // customize the field used to search the user.

            SearchResult sr = ldapInterface.searchOneEntry(getUserSearch(), new String[] { "dn" },
                    SearchControls.SUBTREE_SCOPE);

            if (sr == null) {
                log.info("Username " + username + " not found");
                return false;
            }

            userDN = sr.getNameInNamespace().trim();
            log.info("binding with dn:" + userDN);

        }
        // on failure, set the user DN with append
        if (userDN == null) {
            userDN = "uid=" + username + "," + baseDn;
        }
    } catch (Exception e) {
        log.error("Can't instantiate LdapInterface: " + e.getMessage());
        return false;
    }
    // Set up environment for creating initial context
    Hashtable<String, String> env = new Hashtable<String, String>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, getLdapUrl());

    // Authenticate as  User and password  
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, password);

    try {
        DirContext ctx = new InitialDirContext(env);
        log.debug(ctx.lookup(userDN));
        ctx.close();
    } catch (AuthenticationException e) {
        log.info("User not authenticated: " + e.getMessage());
        return false;
    } catch (NamingException e) {
        log.warn("User not authenticated: problem while accessing ldap " + e.getMessage());
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

/**
 * Tries to find the value(s) of the given attribute. Note that this method
 * uses all search results./* w  w  w . j av a 2 s.  c  om*/
 * 
 * @param username
 *            a username
 * @param attrName
 *            the name of the attribute to find
 * @return a list of values for the attribute, or an empty list
 */
public List<String> getAllAttrs(String username, String attrName) {
    List<String> resultList = new ArrayList<String>();

    try {
        DirContext dc = new InitialDirContext(env);
        NamingEnumeration<SearchResult> ne = performLdapSearch(username, dc);

        while (ne.hasMore()) {
            resultList.add(getAttrValue(attrName, ne.next()));
        }

        ne.close();
        dc.close();
    } catch (NamingException ne) {
        log.warn("Failed LDAP lookup getAllAttrs" + username, ne);
    }

    log.trace("getAllAttrs search result: " + resultList);
    if (log.isTraceEnabled()) {
        log.trace("getAllAttrs search result: " + resultList);
    }

    return resultList;
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static String getOrgDN(String organisation, String countryCode) {
    NamingEnumeration results = null;
    DirContext ctx = null;
    String dn = null;//from   w ww. j  ava 2s . c  o  m
    try {
        ctx = getContext();
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String retAttrs[] = { "dn" };
        controls.setReturningAttributes(retAttrs);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search("c=" + countryCode + "," + rb.getString("organisationsRoot"),
                "(&(objectclass=organization)(o=" + organisation + "))", controls);

        if (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            dn = searchResult.getNameInNamespace();
        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    return dn;
}

From source file:ru.efo.security.ADUserDetailsService.java

@Override
public ADUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    DirContext context = null;
    try {//from  w  w  w  .  ja v a 2 s  . c om
        context = getDirContext(ldapAccount + userSuffix, ldapPassword);
        logger.log(Level.FINE, "Successfully logged on " + ldapUrl);
        return loadUserByUsername(context, username, null);
    } catch (NamingException ex) {
        logger.log(Level.SEVERE, "Could not login to " + ldapUrl, ex);
        throw new UsernameNotFoundException(ex.getMessage());
    } finally {
        if (context != null) {
            try {
                context.close();
            } catch (NamingException ex) {
                logger.log(Level.WARNING, "Could not close DirContext", ex);
            }
        }
    }
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static LDAPUser findUserByMail(String mail) {
    NamingEnumeration results = null;
    DirContext ctx = null;
    LDAPUser user = null;/*from ww w.  j  a va2  s.  c om*/
    try {
        ctx = getContext();
        SearchControls controls = new SearchControls();
        String retAttrs[] = { "cn" };
        controls.setReturningAttributes(retAttrs);
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search(rb.getString("peopleRoot"), "(mail=" + mail + ")", controls);
        if (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            user = new LDAPUser();

            if (attributes.get("cn") != null)
                user = getUser((String) attributes.get("cn").get());
        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }
    return user;

}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static boolean addOrganisation(LDAPUser lus, Organization org) {
    boolean registration = false;
    DirContext ctx = null;
    try {/*from w w  w . j  a v a  2s. c  o  m*/
        ctx = getAuthContext(lus.getUsername(), lus.getPassword());

        Attributes attrsBag = new BasicAttributes();

        Attribute oc = new BasicAttribute("objectClass");
        oc.add("organization");
        oc.add("top");
        attrsBag.put(oc);

        Attribute o = new BasicAttribute("o", org.getKey());
        attrsBag.put(o);

        Attribute description = new BasicAttribute("description", org.getDescription());
        attrsBag.put(description);

        if (org.getReference() != null && !org.getReference().isEmpty()) {
            Attribute registeredAddr = new BasicAttribute("registeredAddress", org.getReference());
            attrsBag.put(registeredAddr);
        }

        ResourceBundle rb = ResourceBundle.getBundle("ldap");
        ctx.createSubcontext(
                "o=" + org.getKey() + ",c=" + org.getCountryCode() + "," + rb.getString("organisationsRoot"),
                attrsBag);

        registration = true;
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    return registration;

}