Example usage for javax.naming.ldap LdapContext close

List of usage examples for javax.naming.ldap LdapContext close

Introduction

In this page you can find the example usage for javax.naming.ldap LdapContext close.

Prototype

public void close() throws NamingException;

Source Link

Document

Closes this context.

Usage

From source file:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * This will create the supplied dn in the LDAP namespace with the supplied
 * attributes. See {@link javax.naming.DirContext#createSubcontext(String,
 * Attributes)}. Note that the context created by this operation is
 * immediately closed.//  www.  j a  v  a2s  .  com
 *
 * @param  dn  <code>String</code> named object in the LDAP
 * @param  attrs  <code>Attributes</code> attributes to be added to this entry
 *
 * @throws  NamingException  if the LDAP returns an error
 */
protected void create(final String dn, final Attributes attrs) throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Create name with the following parameters:");
        this.logger.debug("  dn = " + dn);
        this.logger.debug("  attrs = " + attrs);
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    LdapContext ctx = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                ctx = this.getContext();
                ctx.createSubcontext(dn, attrs).close();
                break;
            } catch (NamingException e) {
                this.operationRetry(ctx, e, i);
            }
        }
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
}

From source file:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * This will modify the supplied attributes for the supplied value given by
 * the modification operation. modOp must be one of: ADD_ATTRIBUTE,
 * REPLACE_ATTRIBUTE, REMOVE_ATTRIBUTE. The order of the modifications is not
 * specified. Where possible, the modifications are performed atomically. See
 * {@link javax.naming.DirContext#modifyAttributes( String, int, Attributes)}.
 *
 * @param  dn  <code>String</code> named object in the LDAP
 * @param  modOp  <code>int</code> modification operation
 * @param  attrs  <code>Attributes</code> attributes to be used for the
 * operation, may be null//  w w  w . j av  a 2  s  .co m
 *
 * @throws  NamingException  if the LDAP returns an error
 */
protected void modifyAttributes(final String dn, final int modOp, final Attributes attrs)
        throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Modify attributes with the following parameters:");
        this.logger.debug("  dn = " + dn);
        this.logger.debug("  modOp = " + modOp);
        this.logger.debug("  attrs = " + attrs);
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    LdapContext ctx = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                ctx = this.getContext();
                ctx.modifyAttributes(dn, modOp, attrs);
                break;
            } catch (NamingException e) {
                this.operationRetry(ctx, e, i);
            }
        }
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
}

From source file:com.wfp.utils.LDAPUtils.java

/**
 * Used to search the LDAP based on the follwoing argumets
 * @param ldapCtx//from   w w  w. j  av a2  s .  com
 * @param searchCtls
 * @param searchFilter
 * @param searchBase
 * @return
 * @throws NamingException
 */
@SuppressWarnings("unchecked")
public static NamingEnumeration getSearchResults(LdapContext ldapCtx, SearchControls searchCtls,
        String searchFilter, String searchBase) {
    try {
        // Search for objects using the filter
        try {
            return ldapCtx.search(searchBase, searchFilter, searchCtls);
        } catch (NamingException e) {
            Logger.error(
                    "Error occured while searching results : 249: getSearchResults(LdapContext ldapCtx, SearchControls searchCtls, String searchFilter, String searchBase)["
                            + e.getLocalizedMessage() + "]",
                    LDAPUtils.class);
        }
    } finally {
        if (ldapCtx != null) {
            try {
                ldapCtx.close();
            } catch (NamingException e) {
                Logger.error(
                        "Error occured while closing the connection to LDAP [" + e.getLocalizedMessage() + "]",
                        LDAPUtils.class);
            }
        }
    }
    return null;
}

From source file:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * This will enumerate the names bounds to the specified context, along with
 * the class names of objects bound to them. The resulting <code>
 * Iterator</code> is a deep copy of the original search results. See {@link
 * javax.naming.Context#list(String)}./*from  ww  w .  j  a  v  a2s  .co m*/
 *
 * @param  dn  <code>String</code> LDAP context to list
 *
 * @return  <code>Iterator</code> - LDAP search result
 *
 * @throws  NamingException  if the LDAP returns an error
 */
protected Iterator<NameClassPair> list(final String dn) throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("list with the following parameters:");
        this.logger.debug("  dn = " + dn);
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    List<NameClassPair> results = null;
    LdapContext ctx = null;
    NamingEnumeration<NameClassPair> en = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                ctx = this.getContext();
                en = ctx.list(dn);

                results = NCP_COPY_RESULT_HANDLER.process(null, en, this.config.getHandlerIgnoreExceptions());

                break;
            } catch (NamingException e) {
                this.operationRetry(ctx, e, i);
            }
        }
    } finally {
        if (en != null) {
            en.close();
        }
        if (ctx != null) {
            ctx.close();
        }
    }
    return results.iterator();
}

From source file:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * This will enumerate the names bounds to the specified context, along with
 * the objects bound to them. The resulting <code>Iterator</code> is a deep
 * copy of the original search results. See {@link
 * javax.naming.Context#listBindings(String)}.
 *
 * @param  dn  <code>String</code> LDAP context to list
 *
 * @return  <code>Iterator</code> - LDAP search result
 *
 * @throws  NamingException  if the LDAP returns an error
 *//*from w  w w .j av a 2s .  c  o  m*/
protected Iterator<Binding> listBindings(final String dn) throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("listBindings with the following parameters:");
        this.logger.debug("  dn = " + dn);
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    List<Binding> results = null;
    LdapContext ctx = null;
    NamingEnumeration<Binding> en = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                ctx = this.getContext();
                en = ctx.listBindings(dn);

                results = BINDING_COPY_RESULT_HANDLER.process(null, en,
                        this.config.getHandlerIgnoreExceptions());

                break;
            } catch (NamingException e) {
                this.operationRetry(ctx, e, i);
            }
        }
    } finally {
        if (en != null) {
            en.close();
        }
        if (ctx != null) {
            ctx.close();
        }
    }
    return results.iterator();
}

From source file:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * This will perform an LDAP compare operation with the supplied filter and
 * dn. Note that to perform a <b>real</b> LDAP compare operation, your filter
 * must be of the form '(name=value)'. Any other filter expression will result
 * in a regular object level search operation. In either case the desired
 * result is achieved, but the underlying LDAP invocation is different.
 *
 * @param  dn  <code>String</code> name to compare
 * @param  filter  <code>String</code> expression to use for compare
 * @param  filterArgs  <code>Object[]</code> to substitute for variables in
 * the filter/*from www. j a  v  a 2 s.co m*/
 *
 * @return  <code>boolean</code> - result of compare operation
 *
 * @throws  NamingException  if the LDAP returns an error
 */
protected boolean compare(final String dn, final String filter, final Object[] filterArgs)
        throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Compare with the following parameters:");
        this.logger.debug("  dn = " + dn);
        this.logger.debug("  filter = " + filter);
        this.logger.debug("  filterArgs = " + Arrays.toString(filterArgs));
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    boolean success = false;
    LdapContext ctx = null;
    NamingEnumeration<SearchResult> en = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                ctx = this.getContext();
                en = ctx.search(dn, filter, filterArgs, LdapConfig.getCompareSearchControls());

                if (en.hasMore()) {
                    success = true;
                }

                break;
            } catch (NamingException e) {
                this.operationRetry(ctx, e, i);
            }
        }
    } finally {
        if (en != null) {
            en.close();
        }
        if (ctx != null) {
            ctx.close();
        }
    }
    return success;
}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java

@Override
public User importUserByScreenName(long companyId, String screenName) throws Exception {

    long ldapServerId = _portalLDAP.getLdapServerId(companyId, screenName, StringPool.BLANK);

    SearchResult result = (SearchResult) _portalLDAP.getUser(ldapServerId, companyId, screenName,
            StringPool.BLANK);/*from w  w w. j  a va  2 s . c  o m*/

    if (result == null) {
        if (_log.isWarnEnabled()) {
            _log.warn("No user was found in LDAP with screenName " + screenName);
        }

        return null;
    }

    LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId);

    String fullUserDN = result.getNameInNamespace();

    Attributes attributes = _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext, fullUserDN);

    User user = importUser(ldapServerId, companyId, ldapContext, attributes, null);

    ldapContext.close();

    return user;
}

From source file:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * Confirms whether the supplied exception matches an exception from {@link
 * LdapConfig#getOperationRetryExceptions()} and the supplied count is less
 * than {@link LdapConfig#getOperationRetry()}. {@link
 * LdapConfig#getOperationRetryWait()} is used in conjunction with {@link
 * LdapConfig#getOperationRetryBackoff()} to delay retries. Calls {@link
 * #close()} if no exception is thrown, which allows the client to reconnect
 * when the operation is performed again.
 *
 * @param  ctx  <code>LdapContext</code> that performed the operation
 * @param  e  <code>NamingException</code> that was thrown
 * @param  count  <code>int</code> operation attempts
 *
 * @throws  NamingException  if the operation won't be retried
 *//*from   www. ja  va  2s  . c o m*/
protected void operationRetry(final LdapContext ctx, final NamingException e, final int count)
        throws NamingException {
    boolean ignoreException = false;
    final Class<?>[] ignore = this.config.getOperationRetryExceptions();
    if (ignore != null && ignore.length > 0) {
        for (Class<?> ne : ignore) {
            if (ne.isInstance(e)) {
                ignoreException = true;
                break;
            }
        }
    }
    if (ignoreException && (count < this.config.getOperationRetry() || this.config.getOperationRetry() == -1)) {
        if (this.logger.isWarnEnabled()) {
            this.logger.warn("Error performing LDAP operation, " + "retrying (attempt " + count + ")", e);
        }
        if (ctx != null) {
            ctx.close();
        }
        this.close();
        if (this.config.getOperationRetryWait() > 0) {
            long sleepTime = this.config.getOperationRetryWait();
            if (this.config.getOperationRetryBackoff() > 0 && count > 0) {
                sleepTime = sleepTime * this.config.getOperationRetryBackoff() * count;
            }
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException ie) {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Operation retry wait interrupted", e);
                }
            }
        }
    } else {
        throw e;
    }
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Gets the ldap persons for ldap groups based on the person DNs
 * //from  ww  w  .ja  v  a  2 s  .co  m
 * @param siteBean
 * @param groups
 * @param groupToMemberReferencesMap
 * @return
 */
public static Map<String, List<TPersonBean>> getGroupToPersonMaps1(String baseURL, TSiteBean siteBean,
        Map<String, TPersonBean> groups, Map<String, List<String>> groupToMemberReferencesMap) {
    String loginAttributeName = siteBean.getLdapAttributeLoginName();
    String bindDN = siteBean.getLdapBindDN();
    String bindPassword = siteBean.getLdapBindPassword();
    Map<String, String> ldapMap = getLdapMap();
    String personFilter = ldapMap.get(LdapUtil.LDAP_CONFIG.LDAP_FILTER_PERSONS);
    boolean hasPersonFilter = false;
    if (personFilter != null && !"".equals(personFilter) && !"*".equals(personFilter)) {
        hasPersonFilter = true;
        if (!(personFilter.startsWith("(") && personFilter.endsWith(")"))) {
            personFilter = "(" + personFilter + ")";
        }
        LOGGER.debug("General user filter expression " + personFilter);
    }
    Map<String, List<TPersonBean>> groupToPersons = new HashMap<String, List<TPersonBean>>();
    if (groupToMemberReferencesMap != null) {
        for (Map.Entry<String, List<String>> groupPersons : groupToMemberReferencesMap.entrySet()) {
            String groupName = groupPersons.getKey();
            List<String> personDNs = groupPersons.getValue();
            Map<String, List<String>> parentDNPartToPersonSearchStrings = new HashMap<String, List<String>>();
            if (personDNs != null) {
                LOGGER.debug("Getting the persons for group " + groupName);
                for (String personDN : personDNs) {
                    int index = personDN.indexOf(",");
                    if (index != -1) {
                        String searchPart = personDN.substring(0, index);
                        String searchStr = "(" + searchPart + ")";
                        if (hasPersonFilter) {
                            searchStr = "(&" + personFilter + searchStr + ")";
                        }
                        String parentDNPart = personDN.substring(index + 1);
                        List<String> personSearchStrings = parentDNPartToPersonSearchStrings.get(parentDNPart);
                        if (personSearchStrings == null) {
                            personSearchStrings = new LinkedList<String>();
                            parentDNPartToPersonSearchStrings.put(parentDNPart, personSearchStrings);
                        }
                        personSearchStrings.add(searchStr);
                    }
                }
            }
            List<TPersonBean> personsInGroup = new LinkedList<TPersonBean>();
            LdapContext baseContext = getInitialContext(baseURL, bindDN, bindPassword);
            if (baseContext == null) {
                LOGGER.warn("Context is null for base url " + baseURL);
                continue;
            }
            for (Map.Entry<String, List<String>> parentDnToPersonSearchStrings : parentDNPartToPersonSearchStrings
                    .entrySet()) {
                String parentDn = parentDnToPersonSearchStrings.getKey();
                List<String> searchStrs = parentDnToPersonSearchStrings.getValue();
                if (searchStrs == null || searchStrs.isEmpty()) {
                    continue;
                }
                LdapContext ldapContext = null;
                try {
                    LOGGER.debug(
                            "Number of persons searched for parentDn " + parentDn + ": " + searchStrs.size());
                    ldapContext = (LdapContext) baseContext.lookup(parentDn);
                    if (ldapContext == null) {
                        LOGGER.warn("Lookup context is null for " + parentDn);
                        continue;
                    }
                    List<TPersonBean> personsInParentDN = getLdapUsers(ldapContext, loginAttributeName,
                            searchStrs);
                    if (personsInParentDN != null) {
                        LOGGER.debug("Number of persons found for parentDn " + parentDn + ": "
                                + personsInParentDN.size());
                        personsInGroup.addAll(personsInParentDN);
                    }
                } catch (Exception e) {
                    LOGGER.warn("Getting the persons with parentDn  " + parentDn + " for group " + groupName
                            + " failed with " + e.getMessage());
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                } finally {
                    try {
                        if (ldapContext != null) {
                            ldapContext.close();
                        }
                    } catch (NamingException e) {
                        LOGGER.warn("Closing the context with " + parentDn + " for group " + groupName
                                + " failed with " + e.getMessage());
                        LOGGER.debug(ExceptionUtils.getStackTrace(e));
                    }
                }
            }
            groupToPersons.put(groupName, personsInGroup);
            if (baseContext != null) {
                try {
                    baseContext.close();
                } catch (NamingException e) {
                    LOGGER.warn("Closing the base context with failed with " + e.getMessage());
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                }
            }
        }
    }
    return groupToPersons;
}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserExporterImpl.java

@Override
public void exportUser(Contact contact, Map<String, Serializable> contactExpandoAttributes) throws Exception {

    long companyId = contact.getCompanyId();

    StopWatch stopWatch = new StopWatch();

    if (_log.isDebugEnabled()) {
        stopWatch.start();/*w  ww.j a va2s.  co  m*/

        _log.debug("Exporting contact " + contact);
    }

    if (!_ldapSettings.isExportEnabled(companyId)) {
        return;
    }

    User user = _userLocalService.getUserByContactId(contact.getContactId());

    if (user.isDefaultUser() || (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {

        return;
    }

    long ldapServerId = _portalLDAP.getLdapServerId(companyId, user.getScreenName(), user.getEmailAddress());

    LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId);

    try {
        if (ldapContext == null) {
            return;
        }

        Properties contactMappings = _ldapSettings.getContactMappings(ldapServerId, companyId);
        Properties contactExpandoMappings = _ldapSettings.getContactExpandoMappings(ldapServerId, companyId);

        Binding binding = _portalLDAP.getUser(ldapServerId, contact.getCompanyId(), user.getScreenName(),
                user.getEmailAddress());

        if (binding == null) {
            Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId);

            binding = addUser(ldapServerId, ldapContext, user, userMappings);
        }

        Name name = new CompositeName();

        name.add(binding.getNameInNamespace());

        Modifications modifications = _portalToLDAPConverter.getLDAPContactModifications(contact,
                contactExpandoAttributes, contactMappings, contactExpandoMappings);

        if (modifications == null) {
            return;
        }

        ModificationItem[] modificationItems = modifications.getItems();

        ldapContext.modifyAttributes(name, modificationItems);
    } finally {
        if (ldapContext != null) {
            ldapContext.close();
        }

        if (_log.isDebugEnabled()) {
            _log.debug(StringBundler.concat("Finished exporting contact ", String.valueOf(contact), " in ",
                    String.valueOf(stopWatch.getTime()), "ms"));
        }
    }
}