Search in sources :

Example 6 with SearchResult

use of javax.naming.directory.SearchResult in project Openfire by igniterealtime.

the class LdapManager method retrieveListCount.

/**
     * Generic routine for retrieving the number of available results from the LDAP server that
     * match the passed search filter.  This routine also accounts for paging settings and
     * alternate DNs.
     *
     * The passed in filter string needs to be pre-prepared!  In other words, nothing will be changed
     * in the string before it is used as a string.
     *
     * @param attribute LDAP attribute to be pulled from each result and used in the query.
     *     Typically pulled from this manager.
     * @param searchFilter Filter to use to perform the search.  Typically pulled from this manager.
     * @return The number of entries that match the filter.
     */
public Integer retrieveListCount(String attribute, String searchFilter) {
    int pageSize = -1;
    String pageSizeStr = properties.get("ldap.pagedResultsSize");
    if (pageSizeStr != null) {
        try {
            pageSize = Integer.parseInt(pageSizeStr);
        /* radix -1 is invalid */
        } catch (NumberFormatException e) {
        // poorly formatted number, ignoring
        }
    }
    LdapContext ctx = null;
    LdapContext ctx2 = null;
    Integer count = 0;
    try {
        ctx = getContext(baseDN);
        // Set up request controls, if appropriate.
        List<Control> baseTmpRequestControls = new ArrayList<>();
        if (pageSize > 0) {
            // Server side paging.
            baseTmpRequestControls.add(new PagedResultsControl(pageSize, Control.NONCRITICAL));
        }
        Control[] baseRequestControls = baseTmpRequestControls.toArray(new Control[baseTmpRequestControls.size()]);
        ctx.setRequestControls(baseRequestControls);
        SearchControls searchControls = new SearchControls();
        // See if recursive searching is enabled. Otherwise, only search one level.
        if (isSubTreeSearch()) {
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }
        searchControls.setReturningAttributes(new String[] { attribute });
        byte[] cookie;
        // Run through all pages of results (one page is also possible  ;)  )
        do {
            cookie = null;
            NamingEnumeration<SearchResult> answer = ctx.search("", searchFilter, searchControls);
            // Examine all of the results on this page
            while (answer.hasMoreElements()) {
                answer.next();
                count++;
            }
            // Examine the paged results control response
            Control[] controls = ctx.getResponseControls();
            if (controls != null) {
                for (Control control : controls) {
                    if (control instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                        cookie = prrc.getCookie();
                    }
                }
            }
            // Close the enumeration.
            answer.close();
            // Re-activate paged results; affects nothing if no paging support
            List<Control> tmpRequestControls = new ArrayList<>();
            if (pageSize > 0) {
                // Server side paging.
                tmpRequestControls.add(new PagedResultsControl(pageSize, cookie, Control.CRITICAL));
            }
            Control[] requestControls = tmpRequestControls.toArray(new Control[tmpRequestControls.size()]);
            ctx.setRequestControls(requestControls);
        } while (cookie != null);
        // Add groups found in alternate DN
        if (alternateBaseDN != null) {
            ctx2 = getContext(alternateBaseDN);
            ctx2.setRequestControls(baseRequestControls);
            // Run through all pages of results (one page is also possible  ;)  )
            do {
                cookie = null;
                NamingEnumeration<SearchResult> answer = ctx2.search("", searchFilter, searchControls);
                // Examine all of the results on this page
                while (answer.hasMoreElements()) {
                    answer.next();
                    count++;
                }
                // Examine the paged results control response
                Control[] controls = ctx2.getResponseControls();
                if (controls != null) {
                    for (Control control : controls) {
                        if (control instanceof PagedResultsResponseControl) {
                            PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                            cookie = prrc.getCookie();
                        }
                    }
                }
                // Close the enumeration.
                answer.close();
                // Re-activate paged results; affects nothing if no paging support
                List<Control> tmpRequestControls = new ArrayList<>();
                if (pageSize > 0) {
                    // Server side paging.
                    tmpRequestControls.add(new PagedResultsControl(pageSize, cookie, Control.CRITICAL));
                }
                Control[] requestControls = tmpRequestControls.toArray(new Control[tmpRequestControls.size()]);
                ctx2.setRequestControls(requestControls);
            } while (cookie != null);
        }
    } catch (Exception e) {
        Log.error(e.getMessage(), e);
    } finally {
        try {
            if (ctx != null) {
                ctx.setRequestControls(null);
                ctx.close();
            }
            if (ctx2 != null) {
                ctx2.setRequestControls(null);
                ctx2.close();
            }
        } catch (Exception ignored) {
        // Ignore.
        }
    }
    return count;
}
Also used : PagedResultsResponseControl(javax.naming.ldap.PagedResultsResponseControl) ArrayList(java.util.ArrayList) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) GroupNotFoundException(org.jivesoftware.openfire.group.GroupNotFoundException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) Control(javax.naming.ldap.Control) SortControl(javax.naming.ldap.SortControl) PagedResultsControl(javax.naming.ldap.PagedResultsControl) PagedResultsResponseControl(javax.naming.ldap.PagedResultsResponseControl) SearchControls(javax.naming.directory.SearchControls) JiveInitialLdapContext(org.jivesoftware.util.JiveInitialLdapContext) LdapContext(javax.naming.ldap.LdapContext) PagedResultsControl(javax.naming.ldap.PagedResultsControl)

Example 7 with SearchResult

use of javax.naming.directory.SearchResult in project camel by apache.

the class LdapProducer method process.

public void process(Exchange exchange) throws Exception {
    String filter = exchange.getIn().getBody(String.class);
    DirContext dirContext = getDirContext();
    try {
        // could throw NamingException
        List<SearchResult> data;
        if (pageSize == null) {
            data = simpleSearch(dirContext, filter);
        } else {
            if (!(dirContext instanceof LdapContext)) {
                throw new IllegalArgumentException("When using attribute 'pageSize' for a ldap endpoint, you must provide a LdapContext (subclass of DirContext)");
            }
            data = pagedSearch((LdapContext) dirContext, filter);
        }
        exchange.getOut().setBody(data);
        exchange.getOut().setHeaders(exchange.getIn().getHeaders());
        exchange.getOut().setAttachments(exchange.getIn().getAttachments());
    } finally {
        if (dirContext != null) {
            dirContext.close();
        }
    }
}
Also used : SearchResult(javax.naming.directory.SearchResult) DirContext(javax.naming.directory.DirContext) LdapContext(javax.naming.ldap.LdapContext)

Example 8 with SearchResult

use of javax.naming.directory.SearchResult in project camel by apache.

the class LdapRouteTest method testLdapRouteWithPaging.

@Test
public void testLdapRouteWithPaging() throws Exception {
    camel.addRoutes(createRouteBuilder("ldap:localhost:" + port + "?base=ou=system&pageSize=5"));
    camel.start();
    Endpoint endpoint = camel.getEndpoint("direct:start");
    Exchange exchange = endpoint.createExchange();
    // then we set the LDAP filter on the in body
    exchange.getIn().setBody("(objectClass=*)");
    // now we send the exchange to the endpoint, and receives the response from Camel
    Exchange out = template.send(endpoint, exchange);
    Collection<SearchResult> searchResults = defaultLdapModuleOutAssertions(out);
    assertEquals(16, searchResults.size());
}
Also used : Exchange(org.apache.camel.Exchange) Endpoint(org.apache.camel.Endpoint) SearchResult(javax.naming.directory.SearchResult) Test(org.junit.Test)

Example 9 with SearchResult

use of javax.naming.directory.SearchResult in project camel by apache.

the class LdapRouteTest method testLdapRouteStandard.

@Test
public void testLdapRouteStandard() throws Exception {
    camel.addRoutes(createRouteBuilder("ldap:localhost:" + port + "?base=ou=system"));
    camel.start();
    // START SNIPPET: invoke
    Endpoint endpoint = camel.getEndpoint("direct:start");
    Exchange exchange = endpoint.createExchange();
    // then we set the LDAP filter on the in body
    exchange.getIn().setBody("(!(ou=test1))");
    // now we send the exchange to the endpoint, and receives the response from Camel
    Exchange out = template.send(endpoint, exchange);
    Collection<SearchResult> searchResults = defaultLdapModuleOutAssertions(out);
    assertFalse(contains("uid=test1,ou=test,ou=system", searchResults));
    assertTrue(contains("uid=test2,ou=test,ou=system", searchResults));
    assertTrue(contains("uid=testNoOU,ou=test,ou=system", searchResults));
    assertTrue(contains("uid=tcruise,ou=actors,ou=system", searchResults));
// START SNIPPET: invoke
}
Also used : Exchange(org.apache.camel.Exchange) Endpoint(org.apache.camel.Endpoint) SearchResult(javax.naming.directory.SearchResult) Test(org.junit.Test)

Example 10 with SearchResult

use of javax.naming.directory.SearchResult in project camel by apache.

the class LdapRouteTest method testLdapRoutePreserveHeaderAndAttachments.

@Test
public void testLdapRoutePreserveHeaderAndAttachments() throws Exception {
    camel.addRoutes(createRouteBuilder("ldap:localhost:" + port + "?base=ou=system"));
    camel.start();
    final DataHandler dataHandler = new DataHandler("test", "text");
    Exchange out = template.request("direct:start", new Processor() {

        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setBody("(!(ou=test1))");
            exchange.getIn().setHeader("ldapTest", "Camel");
            exchange.getIn().addAttachment("ldapAttachment", dataHandler);
        }
    });
    Collection<SearchResult> searchResults = defaultLdapModuleOutAssertions(out);
    assertFalse(contains("uid=test1,ou=test,ou=system", searchResults));
    assertTrue(contains("uid=test2,ou=test,ou=system", searchResults));
    assertTrue(contains("uid=testNoOU,ou=test,ou=system", searchResults));
    assertTrue(contains("uid=tcruise,ou=actors,ou=system", searchResults));
    assertEquals("Camel", out.getOut().getHeader("ldapTest"));
    assertSame(dataHandler, out.getOut().getAttachment("ldapAttachment"));
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) SearchResult(javax.naming.directory.SearchResult) DataHandler(javax.activation.DataHandler) Test(org.junit.Test)

Aggregations

SearchResult (javax.naming.directory.SearchResult)248 SearchControls (javax.naming.directory.SearchControls)146 NamingException (javax.naming.NamingException)113 Attributes (javax.naming.directory.Attributes)96 Attribute (javax.naming.directory.Attribute)86 ArrayList (java.util.ArrayList)75 LdapContext (javax.naming.ldap.LdapContext)39 NamingEnumeration (javax.naming.NamingEnumeration)36 DirContext (javax.naming.directory.DirContext)35 Test (org.junit.Test)32 BasicAttributes (javax.naming.directory.BasicAttributes)30 HashSet (java.util.HashSet)28 InitialDirContext (javax.naming.directory.InitialDirContext)27 InitialLdapContext (javax.naming.ldap.InitialLdapContext)23 PagedResultsControl (javax.naming.ldap.PagedResultsControl)22 HashMap (java.util.HashMap)20 IOException (java.io.IOException)19 BasicAttribute (javax.naming.directory.BasicAttribute)19 Control (javax.naming.ldap.Control)16 PagedResultsResponseControl (javax.naming.ldap.PagedResultsResponseControl)15