Example usage for javax.naming.directory SearchControls SUBTREE_SCOPE

List of usage examples for javax.naming.directory SearchControls SUBTREE_SCOPE

Introduction

In this page you can find the example usage for javax.naming.directory SearchControls SUBTREE_SCOPE.

Prototype

int SUBTREE_SCOPE

To view the source code for javax.naming.directory SearchControls SUBTREE_SCOPE.

Click Source Link

Document

Search the entire subtree rooted at the named object.

Usage

From source file:org.ow2.proactive.addons.ldap_query.LDAPClient.java

public String searchQueryLDAP() {
    NamingEnumeration results = null;
    ObjectMapper mapper = new ObjectMapper();
    Response response;//w  w  w. j a  v  a2  s  .  c o m
    String resultOutput = new String();
    List<Map<String, String>> attributesList = new LinkedList<>();

    String[] attributesToReturn = splitAttributes(allLDAPClientParameters.get(ARG_SELECTED_ATTRIBUTES));
    try {
        ldapConnection = LDAPConnectionUtility.connect(allLDAPClientParameters.get(ARG_URL),
                allLDAPClientParameters.get(ARG_DN_BASE), allLDAPClientParameters.get(ARG_USERNAME),
                allLDAPClientParameters.get(ARG_PASSWORD));
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (attributesToReturn.length > 0) {
            controls.setReturningAttributes(attributesToReturn);
        }
        results = ldapConnection.search(
                getFullLdapSearchBase(allLDAPClientParameters.get(ARG_DN_BASE),
                        allLDAPClientParameters.get(ARG_SEARCH_BASE)),
                allLDAPClientParameters.get(ARG_SEARCH_FILTER), controls);

        // Iterate through all attributes in the result of search query
        while (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();

            if (attributes != null && attributes.size() > 0) {
                NamingEnumeration ae = attributes.getAll();
                Map<String, String> attributesMap = new HashMap<>();
                while (ae.hasMore()) {
                    Attribute attribute = (Attribute) ae.next();
                    attributesMap.put(attribute.getID(), attribute.get().toString());
                }
                attributesList.add(attributesMap);
            }
        }
        response = new LDAPResponse("Ok", attributesList);
    } catch (Exception e) {
        response = new ErrorResponse("Error", e.toString());
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (ldapConnection != null) {
            try {
                ldapConnection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    try {
        resultOutput = mapper.writeValueAsString(response);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return resultOutput;
}

From source file:org.ballerinalang.stdlib.ldap.nativeimpl.GetLdapScopesOfUser.java

private static String[] getLDAPGroupsListOfUser(String userName, List<String> searchBase,
        CommonLdapConfiguration ldapAuthConfig, DirContext ldapConnectionContext)
        throws UserStoreException, NamingException {
    if (userName == null) {
        throw new BallerinaException("userName value is null.");
    }//from w  w  w .  j  a va  2s.  c  o m

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    // Load normal roles with the user
    String searchFilter = ldapAuthConfig.getGroupNameListFilter();
    String roleNameProperty = ldapAuthConfig.getGroupNameAttribute();
    String membershipProperty = ldapAuthConfig.getMembershipAttribute();
    String nameInSpace = getNameInSpaceForUserName(userName, ldapAuthConfig, ldapConnectionContext);

    if (membershipProperty == null || membershipProperty.length() < 1) {
        throw new BallerinaException("membershipAttribute not set in configuration");
    }

    String membershipValue;
    if (nameInSpace != null) {
        LdapName ldn = new LdapName(nameInSpace);
        if (LdapConstants.MEMBER_UID.equals(ldapAuthConfig.getMembershipAttribute())) {
            // membership value of posixGroup is not DN of the user
            List rdns = ldn.getRdns();
            membershipValue = ((Rdn) rdns.get(rdns.size() - 1)).getValue().toString();
        } else {
            membershipValue = escapeLdapNameForFilter(ldn);
        }
    } else {
        return new String[0];
    }

    searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))";
    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Reading roles with the membershipProperty Property: " + membershipProperty);
    }

    List<String> list = getListOfNames(searchBase, searchFilter, searchCtls, roleNameProperty,
            ldapConnectionContext);
    return list.toArray(new String[list.size()]);
}

From source file:org.iplantc.persondir.support.ldap.LdapMultirecordAttributeDao.java

public LdapMultirecordAttributeDao() {
    this.searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    this.searchControls.setReturningObjFlag(false);
}

From source file:com.adito.activedirectory.PagedResultTemplate.java

private void doPagedSearch(InitialLdapContext context, String filter, String[] attributes,
        PagedResultMapper mapper) throws NamingException {
    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    applyControls(context, pageSize);//  w  ww.  j a va2  s .  com

    for (String searchBase : ouSearchBase) {
        if (logger.isDebugEnabled()) {
            logger.debug("Looking for items starting at " + searchBase + " (filter = " + filter + ")");
        }

        try {
            int currentPage = 1;
            int startPosition = 0;
            int endPosition = pageSize - 1;
            byte[] cookie = null;

            do {
                String range = startPosition + "-" + endPosition;

                if (logger.isDebugEnabled()) {
                    logger.debug("Starting search on page " + currentPage + " " + range);
                }

                constraints.setReturningAttributes(attributes);
                NamingEnumeration<SearchResult> results = context.search(searchBase, filter, constraints);

                try {
                    mapResults(mapper, results);
                } catch (PartialResultException pre) {
                    // We're paging so we dont care and don't log anymore
                }

                // Examine the paged results control response
                Control[] controls = context.getResponseControls();
                if (controls != null) {
                    for (int index = 0; index < controls.length; index++) {
                        if (controls[index] instanceof PagedResultsResponseControl) {
                            PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[index];
                            cookie = prrc.getCookie();
                        }
                    }
                }

                applyControls(context, pageSize, cookie);
                startPosition = startPosition + pageSize;
                endPosition = endPosition + pageSize;
                currentPage++;
            } while ((cookie != null) && (cookie.length != 0));
        } catch (NamingException e) {
            mapper.processException(e);
            logger.error("Possible configuration error! Did you enter your OUs correctly? [" + searchBase + "]",
                    e);
        }
    }
}

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

public static boolean isMailUsed(String mail) {
    boolean registered = false;
    NamingEnumeration results = null;
    DirContext ctx = null;/*w w  w.j a  v a 2s. c  o  m*/
    try {
        ctx = getContext();
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search(rb.getString("peopleRoot"), "(mail=" + mail + ")", controls);
        if (results.hasMore()) {
            registered = true;
        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        registered = true;
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }
    return registered;
}

From source file:org.archone.ad.authentication.ShoadRealm.java

private String getUserDn(String username) throws javax.naming.NamingException {
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    DirContext dirContext = contextSource.getReadOnlyContext();
    NamingEnumeration<SearchResult> searchResults = dirContext.search("",
            adConfiguration.getUserDnSearchFilter(), new String[] { username }, controls);

    SearchResult sr = searchResults.next();

    if (sr == null || searchResults.hasMore()) {
        throw new AuthenticationException();
    }/*from  ww w  . ja  v  a2  s . co m*/

    return sr.getNameInNamespace();
}

From source file:org.springframework.ldap.config.LdapTemplateNamespaceHandlerTest.java

@Test
public void verifyParseWithDefaultValues() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
            "/ldap-namespace-config-defaults.xml");
    ContextSource outerContextSource = ctx.getBean(ContextSource.class);
    LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class);

    assertThat(outerContextSource).isNotNull();
    assertThat(ldapTemplate).isNotNull();

    assertThat(outerContextSource instanceof TransactionAwareContextSourceProxy).isTrue();
    ContextSource contextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget();

    assertThat(LdapUtils.emptyLdapName()).isEqualTo(getInternalState(contextSource, "base"));
    assertThat("uid=admin").isEqualTo(getInternalState(contextSource, "userDn"));
    assertThat("apassword").isEqualTo(getInternalState(contextSource, "password"));
    assertThat(new String[] { "ldap://localhost:389" })
            .isEqualTo((Object[]) getInternalState(contextSource, "urls"));
    assertThat(Boolean.FALSE).isEqualTo(getInternalState(contextSource, "pooled"));
    assertThat(Boolean.FALSE).isEqualTo(getInternalState(contextSource, "anonymousReadOnly"));
    assertThat(getInternalState(contextSource, "referral")).isNull();

    assertThat(outerContextSource).isSameAs(getInternalState(ldapTemplate, "contextSource"));
    assertThat(Boolean.FALSE).isEqualTo(getInternalState(ldapTemplate, "ignorePartialResultException"));
    assertThat(Boolean.FALSE).isEqualTo(getInternalState(ldapTemplate, "ignoreNameNotFoundException"));
    assertThat(0).isEqualTo(getInternalState(ldapTemplate, "defaultCountLimit"));
    assertThat(0).isEqualTo(getInternalState(ldapTemplate, "defaultTimeLimit"));
    assertThat(SearchControls.SUBTREE_SCOPE).isEqualTo(getInternalState(ldapTemplate, "defaultSearchScope"));
}

From source file:io.apiman.gateway.engine.policies.BasicAuthLDAPTest.java

@Test
@Ignore// ww  w .  j av  a 2  s.c  om
public void testLdap() throws Exception {
    DirContext ctx = createContext();
    Assert.assertNotNull(ctx);

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration<SearchResult> result = ctx.search("o=apiman", "(ObjectClass=*)", controls);

    System.out.println(" ==== Search Results ====");
    while (result.hasMore()) {
        SearchResult entry = result.next();
        System.out.println(" ===> " + entry.getName());
    }

}

From source file:org.wso2.carbon.appfactory.userstore.OTAppFactoryUserStore.java

@Override
public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException {
    String[] userNames = new String[0];

    if (maxItemLimit == 0) {
        return userNames;
    }// w w w.  ja  v  a2  s .  co  m

    int givenMax = Integer
            .parseInt(realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST));

    if (maxItemLimit < 0 || maxItemLimit > givenMax) {
        maxItemLimit = givenMax;
    }

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setCountLimit(maxItemLimit);

    if (filter.contains("?") || filter.contains("**")) {
        throw new UserStoreException(
                "Invalid character sequence entered for user serch. Please enter valid sequence.");
    }

    StringBuffer searchFilter = null;
    searchFilter = new StringBuffer(realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER));
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
    StringBuffer buff = new StringBuffer();
    buff.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=").append(filter)
            .append("))");

    String serviceNameAttribute = "sn";
    String mailAttribute = "mail";
    String returnedAtts[] = { userNameProperty, serviceNameAttribute, mailAttribute };

    searchCtls.setReturningAttributes(returnedAtts);
    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;
    String[] allUserNames = null;
    try {
        dirContext = connectionSource.getContext();
        answer = dirContext.search(searchBase, buff.toString(), searchCtls);
        List<String> list = new ArrayList<String>();
        int i = 0;
        while (answer.hasMoreElements() && i < maxItemLimit) {
            SearchResult sr = (SearchResult) answer.next();
            if (sr.getAttributes() != null) {
                Attribute attr = sr.getAttributes().get(mailAttribute);

                /*
                 * If this is a service principle, just ignore and iterate rest of the array.
                 * The entity is a service if value of surname is Service
                 */
                Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute);

                if (attrSurname != null) {
                    String serviceName = (String) attrSurname.get();
                    if (serviceName != null
                            && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) {
                        continue;
                    }
                }

                if (attr != null) {
                    String name = (String) attr.get();
                    //append the domain if exist
                    String domain = userRealm.getRealmConfiguration()
                            .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
                    if (domain != null) {
                        domain = domain + "/";
                        name = domain + name;
                    }
                    list.add(name);
                    i++;
                }
            }
        }
        userNames = list.toArray(new String[list.size()]);
        //get secondary user lists
        UserStoreManager secUserManager = this.getSecondaryUserStoreManager();
        if (secUserManager != null) {
            String[] secUserNames = secUserManager.listUsers(filter, maxItemLimit);
            allUserNames = UserCoreUtil.combineArrays(userNames, secUserNames);
        } else {
            allUserNames = userNames;
        }
        Arrays.sort(allUserNames);
    } catch (NamingException e) {
        log.error(e.getMessage(), e);
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return allUserNames;
}