Example usage for javax.naming NamingEnumeration close

List of usage examples for javax.naming NamingEnumeration close

Introduction

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

Prototype

public void close() throws NamingException;

Source Link

Document

Closes this enumeration.

Usage

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  w  w  w .  j  ava 2s  .c  o  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:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * This will return the LDAP schema associated with the supplied dn. The
 * resulting <code>Iterator</code> is a deep copy of the original search
 * results. See {@link javax.naming.DirContext#getSchema(String)}.
 *
 * @param  dn  <code>String</code> named object in the LDAP
 *
 * @return  <code>Iterator</code> - LDAP search result
 *
 * @throws  NamingException  if the LDAP returns an error
 *//*from w ww . ja  va 2s .  c  o m*/
protected Iterator<SearchResult> getSchema(final String dn) throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Schema search with the following parameters:");
        this.logger.debug("  dn = " + dn);
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    List<SearchResult> results = null;
    LdapContext ctx = null;
    DirContext schema = null;
    NamingEnumeration<SearchResult> en = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                ctx = this.getContext();
                schema = ctx.getSchema(dn);
                en = schema.search("", null);

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

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

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java

protected Set<PrivilegeEnum> convertLdapGroupsToOrganizationPrivileges(
        NamingEnumeration<SearchResult> pPrivilegesResult) {
    Set<PrivilegeEnum> vResult = EnumSet.noneOf(PrivilegeEnum.class);
    NamingEnumeration<SearchResult> vSearchResults = pPrivilegesResult;
    try {//from ww w .  jav a  2  s.co m
        if (pPrivilegesResult != null) {
            PrivilegeEnum p;
            SearchResult sr;
            String vCnPrivileg;
            // construct privileges
            while (vSearchResults.hasMore()) {
                sr = vSearchResults.next();
                vCnPrivileg = (String) sr.getAttributes().get(Constants.ldap_ddbPrivilege_Cn).get();
                p = this.mapToPrivilege(sr.getAttributes(), Constants.ldap_ddbPrivilege_Cn);
                if (p != null) {
                    vResult.add(p);
                } else {
                    LOG.log(Level.WARNING,
                            "Es ist ein nicht existierende Privileg: ''{0}'' im LDAP gespeichert!",
                            new Object[] { vCnPrivileg });
                }
            }
            // -- releases this context's resources immediately, instead of
            // waiting for the garbage collector
            vSearchResults.close();
        }
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, null, ne);
    } finally {
        // -- releases this context's resources immediately, instead of
        // waiting for the garbage collector
        if (vSearchResults != null) {
            try {
                vSearchResults.close();
            } catch (NamingException ex) {
            }
        }
    }
    return vResult;
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

protected void commonAfterQueryCleanup(final NamingEnumeration<SearchResult> searchResults,
        final SearchResult result, final InitialDirContext ctx) {
    if (result != null) {
        try {/*  www.java 2s. c  o m*/
            this.commonCloseSearchResult(result);
        } catch (final NamingException e) {
            LOGGER.debug("Error when closing result block context", e);
        }
    }
    if (searchResults != null) {
        try {
            searchResults.close();
        } catch (final NamingException e) {
            LOGGER.debug("Error when closing searchResults context", e);
        }
    }
    if (ctx != null) {
        try {
            ctx.close();
        } catch (final NamingException e) {
            LOGGER.debug("Error when closing ldap context", e);
        }
    }
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_ACCOUNT_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aUserBag Active Directory user fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *//*w  w  w  .ja v  a  2  s. c o  m*/
public void loadUserByAccountName(DataBag aUserBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

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

    int field = 0;
    String accountName = null;
    int attrCount = aUserBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField dataField : aUserBag.getFields()) {
        fieldName = dataField.getName();
        if (fieldName.equals(LDAP_ACCOUNT_NAME))
            accountName = dataField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (accountName == null) {
        String msgStr = String.format("LDAP account name '%s' is unassigned.", LDAP_ACCOUNT_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String userSearchBaseDN = getPropertyValue("user_searchbasedn", null);
    String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_ACCOUNT_NAME, accountName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aUserBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_COMMON_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aUserBag Active Directory user fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *//*from w  w w  . j a v a 2  s .co m*/
public void loadUserByCommonName(DataBag aUserBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserByCommonName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

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

    int field = 0;
    String commonName = null;
    int attrCount = aUserBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField complexField : aUserBag.getFields()) {
        fieldName = complexField.getName();
        if (fieldName.equals(LDAP_COMMON_NAME))
            commonName = complexField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (commonName == null) {
        String msgStr = String.format("LDAP common name '%s' is unassigned.", LDAP_COMMON_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String userSearchBaseDN = getPropertyValue("user_searchbasedn", null);
    String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_COMMON_NAME, commonName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aUserBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_ACCOUNT_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aGroupBag Active Directory group fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *//*from   w ww.  j av a 2  s . co  m*/
public void loadGroupByAccountName(DataBag aGroupBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadGroupByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

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

    int field = 0;
    String accountName = null;
    int attrCount = aGroupBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField complexField : aGroupBag.getFields()) {
        fieldName = complexField.getName();
        if (fieldName.equals(LDAP_ACCOUNT_NAME))
            accountName = complexField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (accountName == null) {
        String msgStr = String.format("LDAP account name '%s' is unassigned.", LDAP_ACCOUNT_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null);
    String groupSearchFilter = String.format("(&(objectClass=group)(%s=%s))", LDAP_ACCOUNT_NAME, accountName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(groupSearchBaseDN, groupSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aGroupBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", groupSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

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)
 *//*  www  .  j av  a 2s .  co  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.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

protected Organisation convertLdapOrganizationToOrganisation(
        NamingEnumeration<SearchResult> pOrganizationResult, NamingEnumeration<SearchResult> pPrivilegesResult)
        throws ExecutionException, NameNotFoundException {
    Organisation vOrganisation = null;/*w w w  .j a v a  2 s  .  c o m*/
    try {
        if ((pOrganizationResult != null) && pOrganizationResult.hasMore()) {

            SearchResult sr = pOrganizationResult.next();
            vOrganisation = convertSearchResultToOrganization(sr);
            // -- Organization privileges:
            vOrganisation = this.convertLdapGroupsToOrganizationPrivileges(vOrganisation, pPrivilegesResult);
        }
    } catch (NameNotFoundException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw ex;
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, null, ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        // -- releases this context's resources immediately, instead of waiting for the garbage collector
        if (pOrganizationResult != null) {
            try {
                pOrganizationResult.close();
            } catch (NamingException ex) {
            }
        }
    }
    return vOrganisation;
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

protected boolean organizationExists(String orgId) throws ExecutionException {
    NamingEnumeration<SearchResult> searchResults = null;
    try {//from   ww  w.  j  ava2s .  c  om
        searchResults = this.query(LDAPConnector.getSingletonInstance().getInstitutionBaseDN(),
                new StringBuilder("(& (objectclass=").append(Constants.ldap_ddbOrg_ObjectClass).append(") (")
                        .append(Constants.ldap_ddbOrg_Id).append("=").append(orgId).append("))").toString(),
                new String[] { Constants.ldap_ddbOrg_Id, "+" }, SearchControls.SUBTREE_SCOPE);
        if (searchResults.hasMore()) {
            return true;
        } else {
            return false;
        }
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, "Connection-Error", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, "something went wrong while checking if userId exists", ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (NamingException e) {
            }
        }
    }
}