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:ca.tnt.ldaputils.impl.LdapEntry.java

/**
 * Runs the batch modifications requested through the {@link
 * ILdapEntry#modifyBatchAttribute(int, String, Object)}
 *//*from ww  w. ja va2  s .co  m*/
public void modifyBatchAttributes(final String bindDN, final String bindPassword) { // BEGIN modifyBatchAttributes()
    DirContext ldapContext = null;

    if (modificationItems.size() == 0) {
        throw new IllegalStateException("No modification items for batch");
    }
    try {
        final Object[] tempModItems;
        final ModificationItem[] modItems;
        tempModItems = modificationItems.values().toArray();
        modItems = new ModificationItem[tempModItems.length];
        for (int index = 0; index < tempModItems.length; index++) { // convert to ModificationItem array
            modItems[index] = (ModificationItem) tempModItems[index];
        }

        ldapContext = manager.getConnection(bindDN, bindPassword);
        ldapContext.modifyAttributes(getDn(), modItems);

        /**
         * Update the attributes in memory
         */
        for (final ModificationItem modItem : modItems) {
            final Attribute attribute;
            attribute = modItem.getAttribute();
            updateAttribute(attribute.getID());
        }
        //            manager.reloadAttributes(this);
    } catch (NamingException namingException) {
        throw new LdapNamingException(namingException);
    } catch (Exception exception) {
        throw new LdapNamingException("error modifying attributes", exception);
    } finally {
        try {
            if (ldapContext != null) {
                ldapContext.close();
            }
        } catch (NamingException namingException) {
            manager.logNamingException(namingException);
        }

        // recreate empty batch list
        modificationItems = new LinkedHashMap();
    }
}

From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java

/**
 * @see com.alfaariss.oa.api.idmapper.IIDMapper#remap(java.lang.String)
 *//*from   w w  w.  ja  v  a 2 s . com*/
public String remap(String id) throws OAException {
    if (id == null)
        throw new IllegalArgumentException("Could not remap: NULL");

    String sReturn = null;
    DirContext oDirContext = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment, e);
            throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
        }

        try {
            if (_sMapperAttribute == null) {//must be null, otherwise you can't do the inverse
                Name nameLdap = new LdapName(id);
                if (_sIDAttribute != null)
                    return getAttributes(oDirContext, _sIDAttribute, nameLdap);

                _logger.error("Can't remap: no id attribute name configured");
                throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
            }

            sReturn = searchAttributes(oDirContext, _sMapperAttribute, _sIDAttribute, id);
        } catch (InvalidNameException e) {
            _logger.debug("Supplied id isn't a valid LdapName: " + id);
        }

    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not remap id: " + id, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for mapped id: " + id, e);
            }
        }
    }
    return sReturn;
}

From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java

/**
 * @see com.alfaariss.oa.api.idmapper.IIDMapper#map(java.lang.String)
 *//* ww  w .j av a2s  .  c  o  m*/
public String map(String id) throws OAException {
    if (id == null)
        throw new IllegalArgumentException("Could not map: NULL");

    String sReturn = null;
    DirContext oDirContext = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment, e);
            throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
        }

        try {
            if (_sIDAttribute == null) {//must be null, otherwise you can't do the inverse
                Name nameLdap = new LdapName(id);
                if (_sMapperAttribute != null)
                    return getAttributes(oDirContext, _sMapperAttribute, nameLdap);

                _logger.error("Can't map: no mapper attribute name configured");
                throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
            }

            sReturn = searchAttributes(oDirContext, _sIDAttribute, _sMapperAttribute, id);
        } catch (InvalidNameException e) {
            _logger.debug("Supplied id isn't a valid LdapName: " + id);
        }

    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not map id: " + id, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after mapping id: " + id, e);
            }
        }
    }
    return sReturn;
}

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

public static List<Organization> getOrgList(String country) {
    List<Organization> OrgList = new ArrayList<Organization>();
    NamingEnumeration resultCountries = null;
    DirContext ctx = null;
    try {//from  ww w.  j a v  a 2  s  .com
        ctx = getContext();
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        String filter;
        if (country == null) {
            filter = "(objectclass=country)";
        } else {
            filter = "(&(objectclass=country)(c=" + country + "))";
        }
        resultCountries = ctx.search(rb.getString("organisationsRoot"), filter, controls);

        while (resultCountries.hasMore()) {
            SearchResult searchResult = (SearchResult) resultCountries.next();
            Attributes attributes = searchResult.getAttributes();
            String countryCode = (String) attributes.get("c").get();
            String countryName = (String) attributes.get("co").get();

            NamingEnumeration resultsOrgs = ctx.search(
                    "c=" + countryCode + "," + rb.getString("organisationsRoot"), "(objectclass=organization)",
                    controls);
            while (resultsOrgs.hasMore()) {
                SearchResult srOrg = (SearchResult) resultsOrgs.next();
                Attributes orgAttrs = srOrg.getAttributes();
                String description = "";
                if ((orgAttrs.get("description")) != null) {
                    description = (String) orgAttrs.get("description").get();
                }

                OrgList.add(new Organization((String) orgAttrs.get("o").get(), countryName, countryCode,
                        description, srOrg.getNameInNamespace()));
            }
            resultsOrgs.close();

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

    Collections.sort(OrgList, new Comparator<Organization>() {

        public int compare(Organization o1, Organization o2) {
            return o1.getKey().compareTo(o2.getKey());
        }

    });

    return OrgList;

}

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

/**
 * return the user dn of an ldap entry//  ww  w .  j  av a 2s .  c om
 * 
 * search: base, filter, attrs, user, pass
 * @return
 */
protected SearchResult ldapSearch(String bindUser, String bindPass, String base, String filter,
        String[] attributes) {
    SearchResult ret = null;
    Hashtable<String, Object> bindEnv = new Hashtable<String, Object>(11);
    bindEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    bindEnv.put(Context.PROVIDER_URL, getLdapUrl());

    // remove null attributes
    List<String> goodAttributes = new ArrayList<String>();
    for (String s : attributes) {
        if (s != null) {
            goodAttributes.add(s);
        }
    }

    // get the DN 
    DirContext authenticationContext;
    try {
        SearchControls ctls = new SearchControls();
        ctls.setCountLimit(1);
        ctls.setReturningObjFlag(true);
        ctls.setReturningAttributes(goodAttributes.toArray(new String[0]));
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // Authenticate as  User and password  
        if (bindUser != null && bindPass != null) {
            log.debug("NBinding with credential as user: " + bindUser);
            bindEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
            bindEnv.put(Context.SECURITY_PRINCIPAL, bindUser);
            bindEnv.put(Context.SECURITY_CREDENTIALS, bindPass);
        }
        authenticationContext = new InitialDirContext(bindEnv);
        // %u, %d in baseDN are still expanded 
        NamingEnumeration<SearchResult> answer;
        try {
            answer = authenticationContext.search(base, filter, ctls);

            if (answer.hasMore()) {
                ret = (SearchResult) answer.next();
            }
        } catch (NamingException e) {
            log.warn("Error while searching user with filter [" + filter + "]: " + e.getMessage());
        }
        authenticationContext.close();
        return ret;

    } catch (NamingException e) {
        log.error("Error while creating context: " + e.getMessage());
        if (e.getCause() != null) {
            log.error("Error is: " + e.getCause().getMessage());
        }
        return null;
    }
}

From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * /* w  w  w .  ja v a  2s.c om*/
 * @param search
 * @param searchValue
 * @param attributeNames
 * @return naming enumeration
 */
protected NamingEnumeration getLdapResults(Search search, String searchValue, String[] attributeNames) {
    DirContext context = null;
    NamingEnumeration results = null;
    String filter = search.getParam("filter");
    if (filter == null) {
        log.error("Search filter not found for search type:  " + search.getSearchType());
        return results;
    }
    filter = filter.replaceAll("%TERM%", escapeSearchFilter(searchValue));
    String base = search.getParam("base");
    if (base == null) {
        base = "";
        log.error("Search base not found for:  " + search.getSearchType() + ". Using base \"\" ");

    }
    int scopeNum = -1;
    String scope = search.getParam("scope");
    if (scope != null) {
        scopeNum = getScope(scope);
    }
    if (scopeNum == -1) {
        scopeNum = SearchControls.SUBTREE_SCOPE;
        log.error("Search scope not found for: " + search.getSearchType() + ". Using scope SUBTREE_SCOPE.");
    }
    log.debug("searchType: " + search.getSearchType() + " filter: " + filter + " base: " + base + " scope: "
            + scope);
    try {
        context = new InitialDirContext(this.environment);
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(scopeNum);
        constraints.setReturningAttributes(attributeNames);
        results = context.search(base, filter, constraints);
    } catch (AuthenticationException ex) {
        log.error("Ldap Authentication Exception: " + ex.getMessage(), ex);
    } catch (NamingException ex) {
        log.error("Ldap NamingException: " + ex.getMessage(), ex);

    } finally {
        if (context != null) {
            try {
                context.close();
            } catch (NamingException ne) {
                // squelch, since it is already closed
            }
        }
    }
    return results;

}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Returns <code>true</code> if the supplied id is found in the JNDI storage.
 * @see IStorage#exists(java.lang.String)
 *///from w ww. j  av  a 2s .c  o  m
public boolean exists(String id) throws UserException {
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;

    boolean bReturn = false;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = resolveSearchQuery(id);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
            bReturn = oNamingEnumeration.hasMore();
        } catch (InvalidSearchFilterException e) {
            _logger.error("Wrong filter: " + searchFilter);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.debug("User unknown, naming exception. query: " + searchFilter, e);
            return false; //user unknown
        }
    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not verify if user exists: " + id, e);
        throw new UserException(SystemErrors.ERROR_INTERNAL, e);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + id, e);
            }
        }
    }
    return bReturn;
}

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

/**
 * check if User already exists on system.
 *
 * @param inLogin/* w  w  w .jav a2  s.c o  m*/
 *            String
 * @return path as string
 */
public boolean isUserAlreadyExists(String inLogin) {
    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;
    boolean rueckgabe = false;
    try {
        ctx = new InitialDirContext(env);
        Attributes matchAttrs = new BasicAttributes(true);
        NamingEnumeration<SearchResult> answer = ctx.search("ou=users,dc=gdz,dc=sub,dc=uni-goettingen,dc=de",
                matchAttrs);
        rueckgabe = answer.hasMoreElements();

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            if (logger.isDebugEnabled()) {
                logger.debug(">>>" + sr.getName());
            }
            Attributes attrs = sr.getAttributes();
            String givenName = " ";
            String surName = " ";
            String mail = " ";
            String cn = " ";
            String hd = " ";
            try {
                givenName = attrs.get("givenName").toString();
            } catch (Exception err) {
                givenName = " ";
            }
            try {
                surName = attrs.get("sn").toString();
            } catch (Exception e2) {
                surName = " ";
            }
            try {
                mail = attrs.get("mail").toString();
            } catch (Exception e3) {
                mail = " ";
            }
            try {
                cn = attrs.get("cn").toString();
            } catch (Exception e4) {
                cn = " ";
            }
            try {
                hd = attrs.get("homeDirectory").toString();
            } catch (Exception e4) {
                hd = " ";
            }
            logger.debug(givenName);
            logger.debug(surName);
            logger.debug(mail);
            logger.debug(cn);
            logger.debug(hd);

        }

        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
    }
    return rueckgabe;
}

From source file:com.alfaariss.oa.authentication.password.jndi.JNDIProtocolResource.java

private boolean doBind(String sUserID, String sPassword) throws OAException, UserException {
    StringBuffer sbTemp = null;//from  www.j  a va2s  . c o m
    DirContext oDirContext = null;
    String sQuery = null;
    String sRelUserDn = null;
    boolean bResult = false;
    NamingEnumeration enumSearchResults = null;

    Hashtable<String, String> htEnvironment = new Hashtable<String, String>();

    htEnvironment.put(Context.PROVIDER_URL, _sJNDIUrl);
    htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, _sDriver);
    htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (_bSSL) {
        htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    if (_sPrincipalDn.length() <= 0)
    // If no principal dn is known, we do a simple binding
    {
        String sEscUserID = JNDIUtil.escapeDN(sUserID);
        _logger.debug("Escaped user: " + sEscUserID);
        sbTemp = new StringBuffer(_sUserDn);
        sbTemp.append('=');
        sbTemp.append(sEscUserID);
        sbTemp.append(", ");
        sbTemp.append(_sBaseDn);
        htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString());

        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
            bResult = true;
        } catch (AuthenticationException e) {
            // If supplied credentials are invalid or when authentication fails
            // while accessing the directory or naming service.
            _logger.debug("Could not authenticate user (invalid password): " + sUserID, e);
        } catch (CommunicationException eC) {
            // If communication with the directory or naming service fails.
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            // The initial dir context could not be created.
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } finally {

            try {
                if (oDirContext != null) {
                    oDirContext.close();
                }
            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + '\'', e);
            }
        }
    } else //search through the subtree
    {
        // 1 - Try to bind to LDAP using the security principal's DN and its password
        htEnvironment.put(Context.SECURITY_PRINCIPAL, _sPrincipalDn);
        htEnvironment.put(Context.SECURITY_CREDENTIALS, _sPrincipalPwd);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
        } catch (AuthenticationException eA) {
            _logger.warn("Could not bind to LDAP server", eA);
            throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
        } catch (CommunicationException eC) {
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        // 2 - Search through the context for user's DN relative to the base DN
        sQuery = resolveSearchQuery(sUserID);

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);

        try {
            enumSearchResults = oDirContext.search(_sBaseDn, sQuery, oScope);
        } catch (NamingException eN) {
            _logger.warn("User id not found in password backend for user: " + sUserID, eN);
            throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
        } finally {
            try {

                oDirContext.close();
                oDirContext = null;

            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + "'", e);
            }
        }

        try {
            if (!enumSearchResults.hasMoreElements()) {
                StringBuffer sb = new StringBuffer("User '");
                sb.append(sUserID);
                sb.append("' not found during LDAP search. The filter was: '");
                sb.append(sQuery);
                sb.append("'");
                _logger.warn(sb.toString());
                throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
            }

            SearchResult searchResult = (SearchResult) enumSearchResults.next();
            sRelUserDn = searchResult.getName();
            if (sRelUserDn == null) {
                _logger.warn("no user dn was returned for '" + sUserID + "'.");
                throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
            }
        } catch (NamingException eN) {

            _logger.warn("failed to fetch profile of user '" + sUserID + "'.", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        // 3 - Bind user using supplied credentials
        sbTemp = new StringBuffer(sRelUserDn);
        sbTemp.append(",");
        sbTemp.append(_sBaseDn);

        htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString());
        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
            bResult = true;
        } catch (AuthenticationException e) {
            _logger.debug("Could not authenticate user (invalid password): " + sUserID, e);
        } catch (CommunicationException eC) {
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } finally {
            try {
                if (oDirContext != null) {
                    oDirContext.close();
                }
            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + "'.", e);
            }
        }
    }
    return bResult;
}

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

public static boolean registerUser(LDAPUser lus, UserRequest userReq, String OrgDN, String OrgUDN) {
    boolean registration = false;
    DirContext ctx = null;
    try {/*from w w  w  . j ava  2 s.c om*/
        ctx = getAuthContext(lus.getUsername(), lus.getPassword());

        Attributes attrsBag = new BasicAttributes();

        Attribute oc = new BasicAttribute("objectClass");
        oc.add("inetOrgPerson");
        oc.add("organizationalPerson");
        oc.add("person");
        oc.add("top");
        attrsBag.put(oc);

        Attribute sn = new BasicAttribute("sn", userReq.getSurname());
        attrsBag.put(sn);

        Attribute cn = new BasicAttribute("cn", userReq.getUsername());
        attrsBag.put(cn);

        Attribute dispName = new BasicAttribute("displayName", userReq.getUsername());
        attrsBag.put(dispName);

        Attribute uPass = new BasicAttribute("userPassword", userReq.getPassword());
        attrsBag.put(uPass);

        Attribute regAdd = new BasicAttribute("registeredAddress", userReq.getPreferredMail());
        attrsBag.put(regAdd);

        if (userReq.getTitle() != null && !userReq.getTitle().isEmpty()) {
            Attribute title = new BasicAttribute("title", userReq.getTitle());
            attrsBag.put(title);
        }

        Attribute gName = new BasicAttribute("givenName", userReq.getGivenname());
        attrsBag.put(gName);

        Attribute inits = new BasicAttribute("initials", userReq.getGivenname().substring(0, 1).toUpperCase()
                + userReq.getSurname().substring(0, 1).toUpperCase());
        attrsBag.put(inits);

        Attribute mails = new BasicAttribute("mail");
        mails.add(userReq.getPreferredMail());
        for (String adMail : userReq.getAdditionalMails().split("[,\\s;]"))
            if (!adMail.isEmpty())
                mails.add(adMail.trim());
        attrsBag.put(mails);

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

        if (OrgUDN != null && !OrgUDN.isEmpty()) {
            Attribute orgU = new BasicAttribute("ou", OrgUDN);
            attrsBag.put(orgU);
        }

        ResourceBundle rb = ResourceBundle.getBundle("ldap");
        ctx.createSubcontext("cn=" + userReq.getUsername() + "," + rb.getString("peopleRoot"), attrsBag);

        ModificationItem[] modItems = new ModificationItem[1];
        modItems[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("uniqueMember",
                "cn=" + userReq.getUsername() + "," + rb.getString("peopleRoot")));

        ctx.modifyAttributes(rb.getString("usersGroup"), modItems);

        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;
}