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 query the LDAP with the supplied dn, filter, filter arguments,
 * and search controls. See {@link #search(String, String, Object[],
 * SearchControls, SearchResultHandler...)}. The PagedResultsControl is used
 * in conjunction with {@link LdapConfig#getPagedResultsSize()} to produce the
 * results.//from   www  .j a  va  2s  . c  o m
 *
 * @param  dn  <code>String</code> name to begin search at
 * @param  filter  <code>String</code> expression to use for the search
 * @param  filterArgs  <code>Object[]</code> to substitute for variables in
 * the filter
 * @param  searchControls  <code>SearchControls</code> to perform search with
 * @param  handler  <code>SearchResultHandler[]</code> to post process results
 *
 * @return  <code>Iterator</code> - of LDAP search results
 *
 * @throws  NamingException  if the LDAP returns an error
 */
protected Iterator<SearchResult> pagedSearch(final String dn, final String filter, final Object[] filterArgs,
        final SearchControls searchControls, final SearchResultHandler... handler) throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Paginated search with the following parameters:");
        this.logger.debug("  dn = " + dn);
        this.logger.debug("  filter = " + filter);
        this.logger.debug("  filterArgs = " + Arrays.toString(filterArgs));
        this.logger.debug("  searchControls = " + searchControls);
        this.logger.debug("  handler = " + Arrays.toString(handler));
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    final List<SearchResult> results = new ArrayList<SearchResult>();
    LdapContext ctx = null;
    NamingEnumeration<SearchResult> en = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                byte[] cookie = null;
                ctx = this.getContext();
                ctx.setRequestControls(new Control[] {
                        new PagedResultsControl(this.config.getPagedResultsSize(), Control.CRITICAL), });
                do {
                    List<SearchResult> pagedResults = null;
                    en = ctx.search(dn, filter, filterArgs, searchControls);

                    if (handler != null && handler.length > 0) {
                        final SearchCriteria sc = new SearchCriteria();
                        if (ctx != null && !"".equals(ctx.getNameInNamespace())) {
                            sc.setDn(ctx.getNameInNamespace());
                        } else {
                            sc.setDn(dn);
                        }
                        sc.setFilter(filter);
                        sc.setFilterArgs(filterArgs);
                        if (searchControls != null) {
                            sc.setReturnAttrs(searchControls.getReturningAttributes());
                        }
                        for (int j = 0; j < handler.length; j++) {
                            if (j == 0) {
                                pagedResults = handler[j].process(sc, en,
                                        this.config.getHandlerIgnoreExceptions());
                            } else {
                                pagedResults = handler[j].process(sc, pagedResults);
                            }
                        }
                    } else {
                        pagedResults = SR_COPY_RESULT_HANDLER.process(null, en,
                                this.config.getHandlerIgnoreExceptions());
                    }

                    results.addAll(pagedResults);

                    final Control[] controls = ctx.getResponseControls();
                    if (controls != null) {
                        for (int j = 0; j < controls.length; j++) {
                            if (controls[j] instanceof PagedResultsResponseControl) {
                                final PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[j];
                                cookie = prrc.getCookie();
                            }
                        }
                    }

                    // re-activate paged results
                    ctx.setRequestControls(
                            new Control[] { new PagedResultsControl(this.config.getPagedResultsSize(), cookie,
                                    Control.CRITICAL), });

                } while (cookie != null);

                break;
            } catch (NamingException e) {
                this.operationRetry(ctx, e, i);
            } catch (IOException e) {
                if (this.logger.isErrorEnabled()) {
                    this.logger.error("Could not encode page size into control", e);
                }
                throw new NamingException(e.getMessage());
            }
        }
    } finally {
        if (en != null) {
            en.close();
        }
        if (ctx != null) {
            ctx.close();
        }
    }
    return results.iterator();
}

From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    if (logger.isDebugEnabled()) {
        logger.debug("resolveDistinguishedName userId:" + userId);
    }/*from ww w.  j  a  v  a2  s.  c o m*/
    SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868
    userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName });

    InitialDirContext ctx = null;

    for (String userSearchBase : this.userSearchBases) {

        String query = userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))";

        NamingEnumeration<SearchResult> searchResults = null;
        SearchResult result = null;

        try {
            ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic);

            // Execute the user query with an additional condition that ensures only the user with the required ID is
            // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation

            searchResults = ctx.search(userSearchBase,
                    "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))",
                    new Object[] { userId }, userSearchCtls);

            if (searchResults.hasMore()) {
                result = searchResults.next();
                Attributes attributes = result.getAttributes();
                Attribute uidAttribute = attributes.get(this.userIdAttributeName);
                if (uidAttribute == null) {
                    if (this.errorOnMissingUID) {
                        throw new AlfrescoRuntimeException(
                                "User returned by user search does not have mandatory user id attribute "
                                        + attributes);
                    } else {
                        LDAPMultiBaseUserRegistry.logger
                                .warn("User returned by user search does not have mandatory user id attribute "
                                        + attributes);
                    }
                }
                // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will
                // only resolve this user if the user ID matches
                else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) {
                    String name = result.getNameInNamespace();

                    // Close the contexts, see ALF-20682
                    Context context = (Context) result.getObject();
                    if (context != null) {
                        context.close();
                    }
                    result = null;
                    return name;
                }

                // Close the contexts, see ALF-20682
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
                result = null;
            }
        } catch (NamingException e) {
            // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory

            Object[] args1 = { userId, query };
            diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1);
        }

        if (result != null) {
            try {
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
            } catch (Exception e) {
                logger.debug("error when closing result block context", e);
            }
        }
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (Exception e) {
                logger.debug("error when closing searchResults context", e);
            }
        }
    }

    if (ctx != null) {
        try {
            ctx.close();
        } catch (NamingException e) {
            logger.debug("error when closing ldap context", e);
        }
    }

    // failed to search
    //        Object[] args = {e.getLocalizedMessage()};
    throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic);
}

From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java

public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    if (logger.isDebugEnabled()) {
        logger.debug("resolveDistinguishedName userId:" + userId);
    }//from  www .  ja  va 2  s .  c om
    SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868
    userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName });

    String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName
            + "= userId))";

    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;

    InitialDirContext ctx = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic);

        // Execute the user query with an additional condition that ensures only the user with the required ID is
        // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation            

        searchResults = ctx.search(this.userSearchBase,
                "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId },
                userSearchCtls);

        if (searchResults.hasMore()) {
            result = searchResults.next();
            Attributes attributes = result.getAttributes();
            Attribute uidAttribute = attributes.get(this.userIdAttributeName);
            if (uidAttribute == null) {
                if (this.errorOnMissingUID) {
                    throw new AlfrescoRuntimeException(
                            "User returned by user search does not have mandatory user id attribute "
                                    + attributes);
                } else {
                    LDAPUserRegistry.logger
                            .warn("User returned by user search does not have mandatory user id attribute "
                                    + attributes);
                }
            }
            // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will
            // only resolve this user if the user ID matches
            else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) {
                String name = result.getNameInNamespace();

                // Close the contexts, see ALF-20682
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
                result = null;
                return name;
            }

            // Close the contexts, see ALF-20682
            Context context = (Context) result.getObject();
            if (context != null) {
                context.close();
            }
            result = null;
        }

        Object[] args = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args);

        throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic);
    } catch (NamingException e) {
        // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory

        Object[] args1 = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1);

        // failed to search
        Object[] args = { e.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e);
    } finally {
        if (result != null) {
            try {
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
            } catch (Exception e) {
                logger.debug("error when closing result block context", e);
            }
        }
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (Exception e) {
                logger.debug("error when closing searchResults context", e);
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                logger.debug("error when closing ldap context", e);
            }
        }
    }
}

From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java

/**
 * Invokes the given callback on each entry returned by the given query.
 * /*  w  ww .ja v a  2  s .  c om*/
 * @param callback
 *            the callback
 * @param searchBase
 *            the base DN for the search
 * @param query
 *            the query
 * @param returningAttributes
 *            the attributes to include in search results
 * @throws AlfrescoRuntimeException           
 */
private void processQuery(SearchCallback callback, String searchBase, String query,
        String[] returningAttributes) {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(returningAttributes);
    if (LDAPUserRegistry.logger.isDebugEnabled()) {
        LDAPUserRegistry.logger.debug("Processing query");
        LDAPUserRegistry.logger.debug("Search base: " + searchBase);
        LDAPUserRegistry.logger.debug("    Return result limit: " + searchControls.getCountLimit());
        LDAPUserRegistry.logger.debug("    DerefLink: " + searchControls.getDerefLinkFlag());
        LDAPUserRegistry.logger.debug("    Return named object: " + searchControls.getReturningObjFlag());
        LDAPUserRegistry.logger.debug("    Time limit for search: " + searchControls.getTimeLimit());
        LDAPUserRegistry.logger.debug("    Attributes to return: " + returningAttributes.length + " items.");
        for (String ra : returningAttributes) {
            LDAPUserRegistry.logger.debug("        Attribute: " + ra);
        }
    }
    InitialDirContext ctx = null;
    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(this.queryBatchSize);
        do {
            searchResults = ctx.search(searchBase, query, searchControls);

            while (searchResults.hasMore()) {
                result = searchResults.next();
                callback.process(result);

                // Close the contexts, see ALF-20682
                Context resultCtx = (Context) result.getObject();
                if (resultCtx != null) {
                    resultCtx.close();
                }
                result = null;
            }
        } while (this.ldapInitialContextFactory.hasNextPage(ctx, this.queryBatchSize));
    } catch (NamingException e) {
        Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } catch (ParseException e) {
        Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } finally {
        if (result != null) {
            try {
                Context resultCtx = (Context) result.getObject();
                if (resultCtx != null) {
                    resultCtx.close();
                }
            } catch (Exception e) {
                logger.debug("error when closing result block context", e);
            }
        }
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (Exception e) {
                logger.debug("error when closing searchResults context", e);
            }
            searchResults = null;
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            }
        }
        try {
            callback.close();
        } catch (NamingException e) {
        }
    }
}

From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java

private String findPrincipalDN(String normalizedPrincipal) throws NamingException, KerberosOperationException {
    String dn = null;/*from   w  w w.j a  v  a  2 s . c o  m*/

    if (normalizedPrincipal != null) {
        NamingEnumeration<SearchResult> results = null;

        try {
            results = ldapContext.search(principalContainerDn,
                    String.format("(userPrincipalName=%s)", normalizedPrincipal), searchControls);

            if ((results != null) && results.hasMore()) {
                SearchResult result = results.next();
                dn = result.getNameInNamespace();
            }
        } finally {
            try {
                if (results != null) {
                    results.close();
                }
            } catch (NamingException ne) {
                // ignore, we can not do anything about it
            }
        }
    }

    return dn;
}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Test to make sure anonymous binds are allowed on the RootDSE even when disabled
 * in general when going through the wire protocol.
 *
 * @throws Exception if anything goes wrong
 *//*from w w  w .  j a v  a2s . co  m*/
@Test
public void testEnableAnonymousBindsOnRootDse() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous
    Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put(Context.SECURITY_AUTHENTICATION, "none");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    InitialDirContext ctx = new InitialDirContext(env);
    SearchControls cons = new SearchControls();
    cons.setSearchScope(SearchControls.OBJECT_SCOPE);
    NamingEnumeration<SearchResult> list = ctx.search("", "(objectClass=*)", cons);

    SearchResult result = null;

    if (list.hasMore()) {
        result = list.next();
    }

    assertFalse(list.hasMore());
    list.close();

    assertNotNull(result);
    assertEquals("", result.getName().trim());
}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Test to make sure that if anonymous binds are allowed a user may search
 * within a a partition./*from  w ww .  j a  v a2 s. com*/
 *
 * @throws Exception if anything goes wrong
 */
@Test
public void testAnonymousBindsEnabledBaseSearch() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous
    Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put(Context.SECURITY_AUTHENTICATION, "none");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    InitialDirContext ctx = new InitialDirContext(env);
    SearchControls cons = new SearchControls();
    cons.setSearchScope(SearchControls.OBJECT_SCOPE);
    NamingEnumeration<SearchResult> list = ctx.search("dc=apache,dc=org", "(objectClass=*)", cons);
    SearchResult result = null;

    if (list.hasMore()) {
        result = list.next();
    }

    assertFalse(list.hasMore());
    list.close();

    assertNotNull(result);
    assertNotNull(result.getAttributes().get("dc"));
}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Reproduces the problem with//from  w w w  .j a  v a 2s  .c om
 * <a href="http://issues.apache.org/jira/browse/DIREVE-239">DIREVE-239</a>.
 *
 * @throws Exception if anything goes wrong
 */
@Test
public void testAdminAccessBug() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous

    final Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    Attributes attributes = new BasicAttributes(true);
    Attribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("organizationalUnit");
    attributes.put(objectClass);
    attributes.put("ou", "blah");
    InitialDirContext ctx = new InitialDirContext(env);
    ctx.createSubcontext("ou=blah,ou=system", attributes);
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.OBJECT_SCOPE);
    controls.setReturningAttributes(new String[] { "+" });
    NamingEnumeration<SearchResult> list = ctx.search("ou=blah,ou=system", "(objectClass=*)", controls);
    SearchResult result = list.next();
    list.close();
    Attribute creatorsName = result.getAttributes().get("creatorsName");
    assertEquals("", creatorsName.get());
    ctx.destroySubcontext("ou=blah,ou=system");
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

@Override
public SampleResult sample(Entry e) {
    XMLBuffer xmlBuffer = new XMLBuffer();
    xmlBuffer.openTag("ldapanswer"); // $NON-NLS-1$
    SampleResult res = new SampleResult();
    res.setResponseData("successfull", null);
    res.setResponseMessage("Success"); // $NON-NLS-1$
    res.setResponseCode("0"); // $NON-NLS-1$
    res.setContentType("text/xml");// $NON-NLS-1$
    boolean isSuccessful = true;
    res.setSampleLabel(getName());//from  w  ww .j av  a 2s  . co  m
    DirContext dirContext = ldapContexts.get(getThreadName());

    try {
        xmlBuffer.openTag("operation"); // $NON-NLS-1$
        final String testType = getTest();
        xmlBuffer.tag("opertype", testType); // $NON-NLS-1$
        log.debug("performing test: " + testType);
        if (testType.equals(UNBIND)) {
            res.setSamplerData("Unbind");
            xmlBuffer.tag("baseobj", getRootdn()); // $NON-NLS-1$
            xmlBuffer.tag("binddn", getUserDN()); // $NON-NLS-1$
            unbindOp(dirContext, res);
        } else if (testType.equals(BIND)) {
            res.setSamplerData("Bind as " + getUserDN());
            xmlBuffer.tag("baseobj", getRootdn()); // $NON-NLS-1$
            xmlBuffer.tag("binddn", getUserDN()); // $NON-NLS-1$
            xmlBuffer.tag("connectionTO", getConnTimeOut()); // $NON-NLS-1$
            bindOp(res);
        } else if (testType.equals(SBIND)) {
            res.setSamplerData("SingleBind as " + getUserDN());
            xmlBuffer.tag("baseobj", getRootdn()); // $NON-NLS-1$
            xmlBuffer.tag("binddn", getUserDN()); // $NON-NLS-1$
            xmlBuffer.tag("connectionTO", getConnTimeOut()); // $NON-NLS-1$
            singleBindOp(res);
        } else if (testType.equals(COMPARE)) {
            res.setSamplerData(
                    "Compare " + getPropertyAsString(COMPAREFILT) + " " + getPropertyAsString(COMPAREDN));
            xmlBuffer.tag("comparedn", getPropertyAsString(COMPAREDN)); // $NON-NLS-1$
            xmlBuffer.tag("comparefilter", getPropertyAsString(COMPAREFILT)); // $NON-NLS-1$
            NamingEnumeration<SearchResult> cmp = null;
            try {
                res.sampleStart();
                cmp = LdapExtClient.compare(dirContext, getPropertyAsString(COMPAREFILT),
                        getPropertyAsString(COMPAREDN));
                if (!cmp.hasMore()) {
                    res.setResponseCode("5"); // $NON-NLS-1$
                    res.setResponseMessage("compareFalse");
                    isSuccessful = false;
                }
            } finally {
                res.sampleEnd();
                if (cmp != null) {
                    cmp.close();
                }
            }
        } else if (testType.equals(ADD)) {
            res.setSamplerData("Add object " + getBaseEntryDN());
            xmlBuffer.tag("attributes", getArguments().toString()); // $NON-NLS-1$
            xmlBuffer.tag("dn", getBaseEntryDN()); // $NON-NLS-1$
            addTest(dirContext, res);
        } else if (testType.equals(DELETE)) {
            res.setSamplerData("Delete object " + getBaseEntryDN());
            xmlBuffer.tag("dn", getBaseEntryDN()); // $NON-NLS-1$
            deleteTest(dirContext, res);
        } else if (testType.equals(MODIFY)) {
            res.setSamplerData("Modify object " + getBaseEntryDN());
            xmlBuffer.tag("dn", getBaseEntryDN()); // $NON-NLS-1$
            xmlBuffer.tag("attributes", getLDAPArguments().toString()); // $NON-NLS-1$
            modifyTest(dirContext, res);
        } else if (testType.equals(RENAME)) {
            res.setSamplerData(
                    "ModDN object " + getPropertyAsString(MODDDN) + " to " + getPropertyAsString(NEWDN));
            xmlBuffer.tag("dn", getPropertyAsString(MODDDN)); // $NON-NLS-1$
            xmlBuffer.tag("newdn", getPropertyAsString(NEWDN)); // $NON-NLS-1$
            renameTest(dirContext, res);
        } else if (testType.equals(SEARCH)) {
            final String scopeStr = getScope();
            final int scope = getScopeAsInt();
            final String searchFilter = getPropertyAsString(SEARCHFILTER);
            final String searchBase = getPropertyAsString(SEARCHBASE);
            final String timeLimit = getTimelim();
            final String countLimit = getCountlim();

            res.setSamplerData("Search with filter " + searchFilter);
            xmlBuffer.tag("searchfilter", StringEscapeUtils.escapeXml10(searchFilter)); // $NON-NLS-1$
            xmlBuffer.tag("baseobj", getRootdn()); // $NON-NLS-1$
            xmlBuffer.tag("searchbase", searchBase);// $NON-NLS-1$
            xmlBuffer.tag("scope", scopeStr); // $NON-NLS-1$
            xmlBuffer.tag("countlimit", countLimit); // $NON-NLS-1$
            xmlBuffer.tag("timelimit", timeLimit); // $NON-NLS-1$

            NamingEnumeration<SearchResult> srch = null;
            try {
                res.sampleStart();
                srch = LdapExtClient.searchTest(dirContext, searchBase, searchFilter, scope,
                        getCountlimAsLong(), getTimelimAsInt(), getRequestAttributes(getAttrs()), isRetobj(),
                        isDeref());
                if (isParseFlag()) {
                    try {
                        xmlBuffer.openTag("searchresults"); // $NON-NLS-1$
                        writeSearchResults(xmlBuffer, srch);
                    } finally {
                        xmlBuffer.closeTag("searchresults"); // $NON-NLS-1$
                    }
                } else {
                    xmlBuffer.tag("searchresults", // $NON-NLS-1$
                            "hasElements=" + srch.hasMoreElements()); // $NON-NLS-1$
                }
            } finally {
                if (srch != null) {
                    srch.close();
                }
                res.sampleEnd();
            }

        }

    } catch (NamingException ex) {
        // TODO: tidy this up
        String returnData = ex.toString();
        final int indexOfLDAPErrCode = returnData.indexOf("LDAP: error code");
        if (indexOfLDAPErrCode >= 0) {
            res.setResponseMessage(returnData.substring(indexOfLDAPErrCode + 21, returnData.indexOf(']'))); // $NON-NLS-1$
            res.setResponseCode(returnData.substring(indexOfLDAPErrCode + 17, indexOfLDAPErrCode + 19));
        } else {
            res.setResponseMessage(returnData);
            res.setResponseCode("800"); // $NON-NLS-1$
        }
        isSuccessful = false;
    } finally {
        xmlBuffer.closeTag("operation"); // $NON-NLS-1$
        xmlBuffer.tag("responsecode", res.getResponseCode()); // $NON-NLS-1$
        xmlBuffer.tag("responsemessage", res.getResponseMessage()); // $NON-NLS-1$
        res.setResponseData(xmlBuffer.toString(), null);
        res.setDataType(SampleResult.TEXT);
        res.setSuccessful(isSuccessful);
    }
    return res;
}

From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java

private void getUsers(UserGroupSink sink) throws Throwable {
    NamingEnumeration<SearchResult> userSearchResultEnum = null;
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    try {//from   www.  j a  v  a  2  s .c  o  m
        createLdapContext();
        int total;
        // Activate paged results
        if (pagedResultsEnabled) {
            ldapContext.setRequestControls(
                    new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) });
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        extendedUserSearchFilter = "(objectclass=" + userObjectClass + ")(|(uSNChanged>=" + deltaSyncUserTime
                + ")(modifyTimestamp>=" + deltaSyncUserTimeStamp + "Z))";

        if (userSearchFilter != null && !userSearchFilter.trim().isEmpty()) {
            String customFilter = userSearchFilter.trim();
            if (!customFilter.startsWith("(")) {
                customFilter = "(" + customFilter + ")";
            }

            extendedUserSearchFilter = "(&" + extendedUserSearchFilter + customFilter + ")";
        } else {
            extendedUserSearchFilter = "(&" + extendedUserSearchFilter + ")";
        }
        LOG.info("extendedUserSearchFilter = " + extendedUserSearchFilter);

        long highestdeltaSyncUserTime = deltaSyncUserTime;

        // When multiple OUs are configured, go through each OU as the user search base to search for users.
        for (int ou = 0; ou < userSearchBase.length; ou++) {
            byte[] cookie = null;
            int counter = 0;
            try {
                int paged = 0;
                do {
                    userSearchResultEnum = ldapContext.search(userSearchBase[ou], extendedUserSearchFilter,
                            userSearchControls);

                    while (userSearchResultEnum.hasMore()) {
                        // searchResults contains all the user entries
                        final SearchResult userEntry = userSearchResultEnum.next();

                        if (userEntry == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("userEntry null, skipping sync for the entry");
                            }
                            continue;
                        }
                        //System.out.println("userEntry = " + userEntry);

                        Attributes attributes = userEntry.getAttributes();
                        if (attributes == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("attributes  missing for entry " + userEntry.getNameInNamespace()
                                        + ", skipping sync");
                            }
                            continue;
                        }

                        Attribute userNameAttr = attributes.get(userNameAttribute);
                        if (userNameAttr == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(userNameAttribute + " missing for entry "
                                        + userEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }

                        String userFullName = (userEntry.getNameInNamespace()).toLowerCase();
                        String userName = (String) userNameAttr.get();

                        if (userName == null || userName.trim().isEmpty()) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(userNameAttribute + " empty for entry "
                                        + userEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }

                        Attribute timeStampAttr = attributes.get("uSNChanged");
                        if (timeStampAttr != null) {
                            String uSNChangedVal = (String) timeStampAttr.get();
                            long currentDeltaSyncTime = Long.parseLong(uSNChangedVal);
                            LOG.info("uSNChangedVal = " + uSNChangedVal + "and currentDeltaSyncTime = "
                                    + currentDeltaSyncTime);
                            if (currentDeltaSyncTime > highestdeltaSyncUserTime) {
                                highestdeltaSyncUserTime = currentDeltaSyncTime;
                            }
                        } else {
                            timeStampAttr = attributes.get("modifytimestamp");
                            if (timeStampAttr != null) {
                                String timeStampVal = (String) timeStampAttr.get();
                                Date parseDate = dateFormat.parse(timeStampVal);
                                long currentDeltaSyncTime = parseDate.getTime();
                                LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = "
                                        + currentDeltaSyncTime);
                                if (currentDeltaSyncTime > highestdeltaSyncUserTime) {
                                    highestdeltaSyncUserTime = currentDeltaSyncTime;
                                    deltaSyncUserTimeStamp = timeStampVal;
                                }
                            }
                        }

                        if (!groupSearchFirstEnabled) {
                            String transformUserName = userNameTransform(userName);
                            try {
                                sink.addOrUpdateUser(transformUserName);
                            } catch (Throwable t) {
                                LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage()
                                        + ", for user: " + transformUserName);
                            }
                            //System.out.println("Adding user fullname = " + userFullName + " username = " + transformUserName);
                            userNameMap.put(userFullName, transformUserName);
                            Set<String> groups = new HashSet<String>();

                            // Get all the groups from the group name attribute of the user only when group search is not enabled.
                            if (!groupSearchEnabled) {
                                for (String useGroupNameAttribute : userGroupNameAttributeSet) {
                                    Attribute userGroupfAttribute = userEntry.getAttributes()
                                            .get(useGroupNameAttribute);
                                    if (userGroupfAttribute != null) {
                                        NamingEnumeration<?> groupEnum = userGroupfAttribute.getAll();
                                        while (groupEnum.hasMore()) {
                                            String gName = getShortGroupName((String) groupEnum.next());
                                            String transformGroupName = groupNameTransform(gName);
                                            groups.add(transformGroupName);
                                        }
                                    }
                                }
                            }

                            List<String> groupList = new ArrayList<String>(groups);
                            try {
                                sink.addOrUpdateUser(transformUserName, groupList);

                            } catch (Throwable t) {
                                LOG.error("sink.addOrUpdateUserGroups failed with exception: " + t.getMessage()
                                        + ", for user: " + transformUserName + " and groups: " + groupList);
                            }
                            counter++;
                            if (counter <= 2000) {
                                if (LOG.isInfoEnabled()) {
                                    LOG.info("Updating user count: " + counter + ", userName: " + userName
                                            + ", groupList: " + groupList);
                                }
                                if (counter == 2000) {
                                    LOG.info(
                                            "===> 2000 user records have been synchronized so far. From now on, only a summary progress log will be written for every 100 users. To continue to see detailed log for every user, please enable Trace level logging. <===");
                                }
                            } else {
                                if (LOG.isTraceEnabled()) {
                                    LOG.trace("Updating user count: " + counter + ", userName: " + userName
                                            + ", groupList: " + groupList);
                                } else {
                                    if (counter % 100 == 0) {
                                        LOG.info("Synced " + counter + " users till now");
                                    }
                                }
                            }
                        } else {
                            // If the user from the search result is present in the group user table,
                            // then addorupdate user to ranger admin.
                            LOG.debug("Chekcing if the user " + userFullName
                                    + " is part of the retrieved groups");
                            if (groupUserTable.containsColumn(userFullName)
                                    || groupUserTable.containsColumn(userName)) {
                                String transformUserName = userNameTransform(userName);
                                try {
                                    sink.addOrUpdateUser(transformUserName);
                                } catch (Throwable t) {
                                    LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage()
                                            + ", for user: " + transformUserName);
                                }
                                userNameMap.put(userFullName, transformUserName);
                                //Also update the username in the groupUserTable with the one from username attribute.
                                Map<String, String> userMap = groupUserTable.column(userFullName);
                                for (Map.Entry<String, String> entry : userMap.entrySet()) {
                                    LOG.debug("Updating groupUserTable " + entry.getValue() + " with: "
                                            + transformUserName + " for " + entry.getKey());
                                    groupUserTable.put(entry.getKey(), userFullName, transformUserName);
                                }
                            }
                        }

                    }

                    // Examine the paged results control response
                    Control[] controls = ldapContext.getResponseControls();
                    if (controls != null) {
                        for (int i = 0; i < controls.length; i++) {
                            if (controls[i] instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                                total = prrc.getResultSize();
                                if (total != 0) {
                                    LOG.debug("END-OF-PAGE total : " + total);
                                } else {
                                    LOG.debug("END-OF-PAGE total : unknown");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOG.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    if (pagedResultsEnabled) {
                        LOG.debug(String.format("Fetched paged results round: %s", ++paged));
                        ldapContext.setRequestControls(new Control[] {
                                new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) });
                    }
                } while (cookie != null);
                LOG.info("LdapDeltaUserGroupBuilder.getUsers() completed with user count: " + counter);
            } catch (Exception t) {
                LOG.error("LdapDeltaUserGroupBuilder.getUsers() failed with exception: " + t);
                LOG.info("LdapDeltaUserGroupBuilder.getUsers() user count: " + counter);
            }
        }
        if (deltaSyncUserTime < highestdeltaSyncUserTime) {
            // Incrementing highestdeltaSyncUserTime (for AD) in order to avoid search record repetition for next sync cycle.
            deltaSyncUserTime = highestdeltaSyncUserTime + 1;
            // Incrementing the highest timestamp value (for Openldap) with 1sec in order to avoid search record repetition for next sync cycle.
            deltaSyncUserTimeStamp = dateFormat.format(new Date(highestdeltaSyncUserTime + 60l));
        }
    } finally {
        if (userSearchResultEnum != null) {
            userSearchResultEnum.close();
        }
        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
        closeLdapContext();
    }
}