Example usage for javax.naming NamingEnumeration hasMoreElements

List of usage examples for javax.naming NamingEnumeration hasMoreElements

Introduction

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

Prototype

boolean hasMoreElements();

Source Link

Document

Tests if this enumeration contains more elements.

Usage

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());//  w w  w . j av  a 2 s.  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.lens.server.user.LDAPBackedDatabaseUserConfigLoader.java

/**
 * Find account by account name./*from ww  w .j a va2  s  .  c  o  m*/
 *
 * @param accountName the account name
 * @return the search result
 * @throws NamingException the naming exception
 */
protected SearchResult findAccountByAccountName(String accountName) throws NamingException {
    String searchFilter = String.format(searchFilterPattern, accountName);
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    InitialLdapContext ctx = new InitialLdapContext(env, null);
    try {
        NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchControls);
        if (!results.hasMoreElements()) {
            throw new UserConfigLoaderException("LDAP Search returned no accounts");
        }
        SearchResult searchResult = results.nextElement();
        if (results.hasMoreElements()) {
            throw new UserConfigLoaderException("More than one account found in ldap search");
        }
        return searchResult;
    } finally {
        ctx.close();
    }
}

From source file:org.apache.nifi.ldap.tenants.LdapUserGroupProvider.java

/**
 * Reloads the tenants.//from  w ww  .j  av  a2  s.  c  o m
 */
private void load(final ContextSource contextSource) {
    // create the ldapTemplate based on the context source. use a single source context to use the same connection
    // to support paging when configured
    final SingleContextSource singleContextSource = new SingleContextSource(contextSource.getReadOnlyContext());
    final LdapTemplate ldapTemplate = new LdapTemplate(singleContextSource);

    try {
        final List<User> userList = new ArrayList<>();
        final List<Group> groupList = new ArrayList<>();

        // group dn -> user identifiers lookup
        final Map<String, Set<String>> groupToUserIdentifierMappings = new HashMap<>();

        // user dn -> user lookup
        final Map<String, User> userLookup = new HashMap<>();

        if (performUserSearch) {
            // search controls
            final SearchControls userControls = new SearchControls();
            userControls.setSearchScope(userSearchScope.ordinal());

            // consider paging support for users
            final DirContextProcessor userProcessor;
            if (pageSize == null) {
                userProcessor = new NullDirContextProcessor();
            } else {
                userProcessor = new PagedResultsDirContextProcessor(pageSize);
            }

            // looking for objects matching the user object class
            final AndFilter userFilter = new AndFilter();
            userFilter.and(new EqualsFilter("objectClass", userObjectClass));

            // if a filter has been provided by the user, we add it to the filter
            if (StringUtils.isNotBlank(userSearchFilter)) {
                userFilter.and(new HardcodedFilter(userSearchFilter));
            }

            do {
                userList.addAll(ldapTemplate.search(userSearchBase, userFilter.encode(), userControls,
                        new AbstractContextMapper<User>() {
                            @Override
                            protected User doMapFromContext(DirContextOperations ctx) {
                                // get the user identity
                                final String identity = getUserIdentity(ctx);

                                // build the user
                                final User user = new User.Builder().identifierGenerateFromSeed(identity)
                                        .identity(identity).build();

                                // store the user for group member later
                                userLookup.put(getReferencedUserValue(ctx), user);

                                if (StringUtils.isNotBlank(userGroupNameAttribute)) {
                                    final Attribute attributeGroups = ctx.getAttributes()
                                            .get(userGroupNameAttribute);

                                    if (attributeGroups == null) {
                                        logger.warn("User group name attribute [" + userGroupNameAttribute
                                                + "] does not exist. Ignoring group membership.");
                                    } else {
                                        try {
                                            final NamingEnumeration<String> groupValues = (NamingEnumeration<String>) attributeGroups
                                                    .getAll();
                                            while (groupValues.hasMoreElements()) {
                                                // store the group -> user identifier mapping
                                                groupToUserIdentifierMappings
                                                        .computeIfAbsent(groupValues.next(),
                                                                g -> new HashSet<>())
                                                        .add(user.getIdentifier());
                                            }
                                        } catch (NamingException e) {
                                            throw new AuthorizationAccessException(
                                                    "Error while retrieving user group name attribute ["
                                                            + userIdentityAttribute + "].");
                                        }
                                    }
                                }

                                return user;
                            }
                        }, userProcessor));
            } while (hasMorePages(userProcessor));
        }

        if (performGroupSearch) {
            final SearchControls groupControls = new SearchControls();
            groupControls.setSearchScope(groupSearchScope.ordinal());

            // consider paging support for groups
            final DirContextProcessor groupProcessor;
            if (pageSize == null) {
                groupProcessor = new NullDirContextProcessor();
            } else {
                groupProcessor = new PagedResultsDirContextProcessor(pageSize);
            }

            // looking for objects matching the group object class
            AndFilter groupFilter = new AndFilter();
            groupFilter.and(new EqualsFilter("objectClass", groupObjectClass));

            // if a filter has been provided by the user, we add it to the filter
            if (StringUtils.isNotBlank(groupSearchFilter)) {
                groupFilter.and(new HardcodedFilter(groupSearchFilter));
            }

            do {
                groupList.addAll(ldapTemplate.search(groupSearchBase, groupFilter.encode(), groupControls,
                        new AbstractContextMapper<Group>() {
                            @Override
                            protected Group doMapFromContext(DirContextOperations ctx) {
                                final String dn = ctx.getDn().toString();

                                // get the group identity
                                final String name = getGroupName(ctx);

                                // get the value of this group that may associate it to users
                                final String referencedGroupValue = getReferencedGroupValue(ctx);

                                if (!StringUtils.isBlank(groupMemberAttribute)) {
                                    Attribute attributeUsers = ctx.getAttributes().get(groupMemberAttribute);
                                    if (attributeUsers == null) {
                                        logger.warn("Group member attribute [" + groupMemberAttribute
                                                + "] does not exist. Ignoring group membership.");
                                    } else {
                                        try {
                                            final NamingEnumeration<String> userValues = (NamingEnumeration<String>) attributeUsers
                                                    .getAll();
                                            while (userValues.hasMoreElements()) {
                                                final String userValue = userValues.next();

                                                if (performUserSearch) {
                                                    // find the user by it's referenced attribute and add the identifier to this group
                                                    final User user = userLookup.get(userValue);

                                                    // ensure the user is known
                                                    if (user != null) {
                                                        groupToUserIdentifierMappings
                                                                .computeIfAbsent(referencedGroupValue,
                                                                        g -> new HashSet<>())
                                                                .add(user.getIdentifier());
                                                    } else {
                                                        logger.warn(String.format(
                                                                "%s contains member %s but that user was not found while searching users. Ignoring group membership.",
                                                                name, userValue));
                                                    }
                                                } else {
                                                    // since performUserSearch is false, then the referenced group attribute must be blank... the user value must be the dn
                                                    final String userDn = userValue;

                                                    final String userIdentity;
                                                    if (useDnForUserIdentity) {
                                                        // use the user value to avoid the unnecessary look up
                                                        userIdentity = userDn;
                                                    } else {
                                                        // lookup the user to extract the user identity
                                                        userIdentity = getUserIdentity(
                                                                (DirContextAdapter) ldapTemplate
                                                                        .lookup(userDn));
                                                    }

                                                    // build the user
                                                    final User user = new User.Builder()
                                                            .identifierGenerateFromSeed(userIdentity)
                                                            .identity(userIdentity).build();

                                                    // add this user
                                                    userList.add(user);
                                                    groupToUserIdentifierMappings
                                                            .computeIfAbsent(referencedGroupValue,
                                                                    g -> new HashSet<>())
                                                            .add(user.getIdentifier());
                                                }
                                            }
                                        } catch (NamingException e) {
                                            throw new AuthorizationAccessException(
                                                    "Error while retrieving group name attribute ["
                                                            + groupNameAttribute + "].");
                                        }
                                    }
                                }

                                // build this group
                                final Group.Builder groupBuilder = new Group.Builder()
                                        .identifierGenerateFromSeed(name).name(name);

                                // add all users that were associated with this referenced group attribute
                                if (groupToUserIdentifierMappings.containsKey(referencedGroupValue)) {
                                    groupToUserIdentifierMappings.remove(referencedGroupValue)
                                            .forEach(userIdentifier -> groupBuilder.addUser(userIdentifier));
                                }

                                return groupBuilder.build();
                            }
                        }, groupProcessor));
            } while (hasMorePages(groupProcessor));

            // any remaining groupDn's were referenced by a user but not found while searching groups
            groupToUserIdentifierMappings.forEach((referencedGroupValue, userIdentifiers) -> {
                logger.warn(String.format(
                        "[%s] are members of %s but that group was not found while searching users. Ignoring group membership.",
                        StringUtils.join(userIdentifiers, ", "), referencedGroupValue));
            });
        } else {
            // since performGroupSearch is false, then the referenced user attribute must be blank... the group value must be the dn

            // groups are not being searched so lookup any groups identified while searching users
            groupToUserIdentifierMappings.forEach((groupDn, userIdentifiers) -> {
                final String groupName;
                if (useDnForGroupName) {
                    // use the dn to avoid the unnecessary look up
                    groupName = groupDn;
                } else {
                    groupName = getGroupName((DirContextAdapter) ldapTemplate.lookup(groupDn));
                }

                // define the group
                final Group.Builder groupBuilder = new Group.Builder().identifierGenerateFromSeed(groupName)
                        .name(groupName);

                // add each user
                userIdentifiers.forEach(userIdentifier -> groupBuilder.addUser(userIdentifier));

                // build the group
                groupList.add(groupBuilder.build());
            });
        }

        // record the updated tenants
        tenants.set(new TenantHolder(new HashSet<>(userList), new HashSet<>(groupList)));
    } finally {
        singleContextSource.destroy();
    }
}

From source file:org.apache.nifi.processors.enrich.QueryDNS.java

@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    if (!initialized.get()) {
        initializeResolver(context);//w  w w.j  av  a 2s . c o  m
        getLogger().warn("Resolver was initialized at onTrigger instead of onScheduled");

    }

    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }

    final String queryType = context.getProperty(DNS_QUERY_TYPE).getValue();
    final String queryInput = context.getProperty(QUERY_INPUT).evaluateAttributeExpressions(flowFile)
            .getValue();
    final String queryParser = context.getProperty(QUERY_PARSER).getValue();
    final String queryRegex = context.getProperty(QUERY_PARSER_INPUT).getValue();

    boolean found = false;
    try {
        Attributes results = doLookup(queryInput, queryType);
        // NOERROR & NODATA seem to return empty Attributes handled bellow
        // but defaulting to not found in any case
        if (results.size() < 1) {
            found = false;
        } else {
            int recordNumber = 0;
            NamingEnumeration<?> dnsEntryIterator = results.get(queryType).getAll();

            while (dnsEntryIterator.hasMoreElements()) {
                String dnsRecord = dnsEntryIterator.next().toString();
                // While NXDOMAIN is being generated by doLookup catch

                if (dnsRecord != "NXDOMAIN") {
                    // Map<String, String> parsedResults = parseResponse(recordNumber, dnsRecord, queryParser, queryRegex, "dns");
                    Map<String, String> parsedResults = parseResponse(String.valueOf(recordNumber), dnsRecord,
                            queryParser, queryRegex, "dns");
                    flowFile = session.putAllAttributes(flowFile, parsedResults);
                    found = true;
                } else {
                    // Otherwise treat as not found
                    found = false;
                }

                // Increase the counter and iterate over next record....
                recordNumber++;
            }
        }
    } catch (NamingException e) {
        context.yield();
        throw new ProcessException(
                "Unexpected NamingException while processing records. Please review your configuration.", e);

    }

    // Finally prepare to send the data down the pipeline
    if (found) {
        // Sending the resulting flowfile (with attributes) to REL_FOUND
        session.transfer(flowFile, REL_FOUND);
    } else {
        // NXDOMAIN received, accepting the fate but forwarding
        // to REL_NOT_FOUND
        session.transfer(flowFile, REL_NOT_FOUND);
    }
}

From source file:org.apache.openejb.assembler.classic.Assembler.java

public synchronized void destroy() {

    try {//from www  .j  a  va 2s  .c o m
        EjbTimerServiceImpl.shutdown();
    } catch (Exception e) {
        logger.warning("Unable to shutdown scheduler", e);
    }

    logger.debug("Undeploying Applications");
    Assembler assembler = this;
    for (AppInfo appInfo : assembler.getDeployedApplications()) {
        try {
            assembler.destroyApplication(appInfo.path);
        } catch (UndeployException e) {
            logger.error("Undeployment failed: " + appInfo.path, e);
        } catch (NoSuchApplicationException e) {
        }
    }

    NamingEnumeration<Binding> namingEnumeration = null;
    try {
        namingEnumeration = containerSystem.getJNDIContext().listBindings("openejb/Resource");
    } catch (NamingException ignored) {
        // no resource adapters were created
    }
    while (namingEnumeration != null && namingEnumeration.hasMoreElements()) {
        Binding binding = namingEnumeration.nextElement();
        Object object = binding.getObject();
        if (object instanceof ResourceAdapter) {
            ResourceAdapter resourceAdapter = (ResourceAdapter) object;
            try {
                logger.info("Stopping ResourceAdapter: " + binding.getName());

                if (logger.isDebugEnabled()) {
                    logger.debug("Stopping ResourceAdapter: " + binding.getClassName());
                }

                resourceAdapter.stop();
            } catch (Throwable t) {
                logger.fatal("ResourceAdapter Shutdown Failed: " + binding.getName(), t);
            }
        } else if (object instanceof org.apache.commons.dbcp.BasicDataSource) {
            logger.info("Closing DataSource: " + binding.getName());

            try {
                ((org.apache.commons.dbcp.BasicDataSource) object).close();
            } catch (Throwable t) {
                //Ignore
            }

        } else if (logger.isDebugEnabled()) {
            logger.debug("Not processing resource on destroy: " + binding.getClassName());
        }
    }

    SystemInstance.get().removeComponent(OpenEjbConfiguration.class);
    SystemInstance.get().removeComponent(JtaEntityManagerRegistry.class);
    SystemInstance.get().removeComponent(TransactionSynchronizationRegistry.class);
    SystemInstance.get().removeComponent(EjbResolver.class);
    SystemInstance.reset();
}

From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java

public List<String> searchForUserName(String containString, LdapContext ldapContext) throws NamingException {
    List<String> userNameList = new ArrayList<>();

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

    String searchFilter = "(&(objectClass=*)(userPrincipalName=*" + containString + "*))";
    Object[] searchArguments = new Object[] { containString };

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);

    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        if (log.isDebugEnabled()) {
            log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]");
        }/*from  w  w w . ja v  a2  s.  c o  m*/

        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMore()) {
                Attribute attr = (Attribute) ae.next();
                if (attr.getID().toLowerCase().equals("cn")) {
                    userNameList.addAll(LdapUtils.getAllAttributeValues(attr));
                }
            }
        }
    }
    return userNameList;
}

From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java

private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set<String> roleNames = new LinkedHashSet<>();

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String userPrincipalName = username;
    if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) {
        userPrincipalName += principalSuffix;
    }/*from w  ww  .j  a  va  2 s. c  o  m*/

    String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";
    Object[] searchArguments = new Object[] { userPrincipalName };

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);

    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        if (log.isDebugEnabled()) {
            log.debug("Retrieving group names for user [" + sr.getName() + "]");
        }

        Attributes attrs = sr.getAttributes();

        if (attrs != null) {
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMore()) {
                Attribute attr = (Attribute) ae.next();

                if (attr.getID().equals("memberOf")) {

                    Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);

                    if (log.isDebugEnabled()) {
                        log.debug("Groups found for user [" + username + "]: " + groupNames);
                    }

                    Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
                    roleNames.addAll(rolesForGroups);
                }
            }
        }
    }
    return roleNames;
}

From source file:org.apache.zeppelin.server.ActiveDirectoryGroupRealm.java

private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set<String> roleNames = new LinkedHashSet<>();

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String userPrincipalName = username;
    if (principalSuffix != null) {
        userPrincipalName += principalSuffix;
    }//  w  w w .j  av a2  s. co  m

    String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";
    Object[] searchArguments = new Object[] { userPrincipalName };

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);

    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        if (log.isDebugEnabled()) {
            log.debug("Retrieving group names for user [" + sr.getName() + "]");
        }

        Attributes attrs = sr.getAttributes();

        if (attrs != null) {
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMore()) {
                Attribute attr = (Attribute) ae.next();

                if (attr.getID().equals("memberOf")) {

                    Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);

                    if (log.isDebugEnabled()) {
                        log.debug("Groups found for user [" + username + "]: " + groupNames);
                    }

                    Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
                    roleNames.addAll(rolesForGroups);
                }
            }
        }
    }
    return roleNames;
}

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

private List<String> getListOfNames(List<String> searchBases, String searchFilter, SearchControls searchCtls,
        String property, boolean appendDn) throws NamingException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Result for searchBase: " + searchBases + " searchFilter: " + searchFilter + " property:"
                + property + " appendDN: " + appendDn);
    }//from w  w w  . j  a va2  s.c  om

    List<String> names = new ArrayList<String>();
    NamingEnumeration<SearchResult> answer = null;
    try {
        // handle multiple search bases
        for (String searchBase : searchBases) {
            answer = ldapConnectionContext.search(LdapUtils.escapeDNForSearch(searchBase), searchFilter,
                    searchCtls);
            while (answer.hasMoreElements()) {
                SearchResult searchResult = answer.next();
                if (searchResult.getAttributes() == null) {
                    continue;
                }
                Attribute attr = searchResult.getAttributes().get(property);
                if (attr == null) {
                    continue;
                }
                for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) {
                    String name = (String) vals.nextElement();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Found user: " + name);
                    }
                    names.add(name);
                }
            }

            if (LOG.isDebugEnabled()) {
                for (String name : names) {
                    LOG.debug("Result  :  " + name);
                }
            }
        }
    } finally {
        LdapUtils.closeNamingEnumeration(answer);
    }
    return names;
}

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

private static List<String> getListOfNames(List<String> searchBases, String searchFilter,
        SearchControls searchCtls, String property, DirContext ldapConnectionContext) throws NamingException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Result for searchBase: " + searchBases + " searchFilter: " + searchFilter + " property:"
                + property + " appendDN: false");
    }//  w  w  w  .j  a  v a2s.  c  o  m

    List<String> names = new ArrayList<>();
    NamingEnumeration<SearchResult> answer = null;
    try {
        // handle multiple search bases
        for (String searchBase : searchBases) {
            answer = ldapConnectionContext.search(LdapUtils.escapeDNForSearch(searchBase), searchFilter,
                    searchCtls);
            while (answer.hasMoreElements()) {
                SearchResult searchResult = answer.next();
                if (searchResult.getAttributes() == null) {
                    continue;
                }
                Attribute attr = searchResult.getAttributes().get(property);
                if (attr == null) {
                    continue;
                }
                for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) {
                    String name = (String) vals.nextElement();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Found user: " + name);
                    }
                    names.add(name);
                }
            }

            if (LOG.isDebugEnabled()) {
                for (String name : names) {
                    LOG.debug("Result  :  " + name);
                }
            }
        }
    } finally {
        LdapUtils.closeNamingEnumeration(answer);
    }
    return names;
}