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.codehaus.plexus.redback.authentication.ldap.LdapBindAuthenticator.java

public AuthenticationResult authenticate(AuthenticationDataSource s) throws AuthenticationException {
    PasswordBasedAuthenticationDataSource source = (PasswordBasedAuthenticationDataSource) s;

    if (!config.getBoolean("ldap.bind.authenticator.enabled")
            || (!config.getBoolean("ldap.bind.authenticator.allowEmptyPasswords", false)
                    && StringUtils.isEmpty(source.getPassword()))) {
        return new AuthenticationResult(false, source.getPrincipal(), null);
    }//from   w  w w  .  j  a v  a2 s  . c  om

    SearchControls ctls = new SearchControls();

    ctls.setCountLimit(1);

    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = "(&(objectClass=" + mapper.getUserObjectClass() + ")"
            + (mapper.getUserFilter() != null ? mapper.getUserFilter() : "") + "(" + mapper.getUserIdAttribute()
            + "=" + source.getPrincipal() + "))";

    log.info("Searching for users with filter: \'{}\'" + " from base dn: {}", filter, mapper.getUserBaseDn());

    LdapConnection ldapConnection = getLdapConnection();
    LdapConnection authLdapConnection = null;
    NamingEnumeration<SearchResult> results = null;
    try {
        // check the cache for user's userDn in the ldap server
        String userDn = ldapCacheService.getLdapUserDn(source.getPrincipal());

        if (userDn == null) {
            log.debug("userDn for user {} not found in cache. Retrieving from ldap server..",
                    source.getPrincipal());

            DirContext context = ldapConnection.getDirContext();

            results = context.search(mapper.getUserBaseDn(), filter, ctls);

            log.info("Found user?: {}", results.hasMoreElements());

            if (results.hasMoreElements()) {
                SearchResult result = results.nextElement();

                userDn = result.getNameInNamespace();

                log.debug("Adding userDn {} for user {} to the cache..", userDn, source.getPrincipal());

                // REDBACK-289/MRM-1488 cache the ldap user's userDn to lessen calls to ldap server
                ldapCacheService.addLdapUserDn(source.getPrincipal(), userDn);
            } else {
                return new AuthenticationResult(false, source.getPrincipal(), null);
            }
        }

        log.info("Attempting Authenication: + {}", userDn);

        authLdapConnection = connectionFactory.getConnection(userDn, source.getPassword());

        return new AuthenticationResult(true, source.getPrincipal(), null);
    } catch (LdapException e) {
        return new AuthenticationResult(false, source.getPrincipal(), e);
    } catch (NamingException e) {
        return new AuthenticationResult(false, source.getPrincipal(), e);
    } finally {
        closeNamingEnumeration(results);
        closeLdapConnection(ldapConnection);
        if (authLdapConnection != null) {
            closeLdapConnection(authLdapConnection);
        }
    }
}

From source file:org.efaps.db.store.VFSStoreResource.java

/**
 * Method called to initialize this StoreResource.
 * @param _instance     Instance of the object this StoreResource is wanted
 *                      for/*from w w w .j  a  v a2s. co m*/
 * @param _store        Store this resource belongs to
 * @throws EFapsException on error
 * @see Resource#initialize(Instance, Map, Compress)
 */
@Override
public void initialize(final Instance _instance, final Store _store) throws EFapsException {
    super.initialize(_instance, _store);

    final StringBuilder fileNameTmp = new StringBuilder();

    final String useTypeIdStr = getStore().getResourceProperties().get(VFSStoreResource.PROPERTY_USE_TYPE);
    if ("true".equalsIgnoreCase(useTypeIdStr)) {
        fileNameTmp.append(getInstance().getType().getId()).append("/");
    }

    final String numberSubDirsStr = getStore().getResourceProperties()
            .get(VFSStoreResource.PROPERTY_NUMBER_SUBDIRS);
    if (numberSubDirsStr != null) {
        final long numberSubDirs = Long.parseLong(numberSubDirsStr);
        final String pathFormat = "%0" + Math.round(Math.log10(numberSubDirs) + 0.5d) + "d";
        fileNameTmp.append(String.format(pathFormat, getInstance().getId() % numberSubDirs)).append("/");
    }
    fileNameTmp.append(getInstance().getType().getId()).append(".").append(getInstance().getId());
    this.storeFileName = fileNameTmp.toString();

    final String numberBackupStr = getStore().getResourceProperties()
            .get(VFSStoreResource.PROPERTY_NUMBER_BACKUP);
    if (numberBackupStr != null) {
        this.numberBackup = Integer.parseInt(numberBackupStr);
    }

    if (this.manager == null) {
        try {
            DefaultFileSystemManager tmpMan = null;
            if (getStore().getResourceProperties().containsKey(Store.PROPERTY_JNDINAME)) {
                final InitialContext initialContext = new InitialContext();
                final Context context = (Context) initialContext.lookup("java:comp/env");
                final NamingEnumeration<NameClassPair> nameEnum = context.list("");
                while (nameEnum.hasMoreElements()) {
                    final NameClassPair namePair = nameEnum.next();
                    if (namePair.getName()
                            .equals(getStore().getResourceProperties().get(Store.PROPERTY_JNDINAME))) {
                        tmpMan = (DefaultFileSystemManager) context
                                .lookup(getStore().getResourceProperties().get(Store.PROPERTY_JNDINAME));
                        break;
                    }
                }
            }
            if (tmpMan == null && this.manager == null) {
                this.manager = evaluateFileSystemManager();
            }
        } catch (final NamingException e) {
            throw new EFapsException(VFSStoreResource.class, "initialize.NamingException", e);
        }
    }
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private void setGroup(DirContext context, LDAPAccount user) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    //create the filter of group
    Map filters = new HashMap();
    String uniqueMemberAttrName = "uniquemember";
    if (this.propAttrMap.containsKey("org_member"))
        uniqueMemberAttrName = (String) this.propAttrMap.get("org_member");

    filters.put(uniqueMemberAttrName, user.getDn());
    String grpFilter = buildGroupFilterByDN(filters);

    NamingEnumeration grpRes = context.search(groupBase, grpFilter, searchControls);

    List grpList = new ArrayList();

    while (grpRes.hasMoreElements()) {
        SearchResult findGrpEntry = (SearchResult) grpRes.next();
        if (log.isDebugEnabled())
            log.debug("Found Groups: " + findGrpEntry.getAttributes().toString());
        String grpdn = findGrpEntry.getName() + "," + groupBase;

        grpList.add(createLDAPGroup(grpdn, findGrpEntry.getAttributes()));
    }//w w w  .j a v  a2 s.co m

    IGroup[] igroup = new IGroup[grpList.size()];

    for (int i = 0; i < igroup.length; i++) {
        igroup[i] = (IGroup) grpList.get(i);
    }
    user.setGroups(igroup);

}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private List searchGroupMember(DirContext context, Map filters) throws NamingException {

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

    Set userList = new HashSet();
    String filter = buildFilter(filters);
    if (log.isInfoEnabled())
        log.info("Search User from " + userBase + " by " + filter);
    NamingEnumeration searchResultEnum = context.search(this.groupBase, filter, searchControls);

    while (searchResultEnum.hasMore()) {
        SearchResult searchResult = (SearchResult) searchResultEnum.next();
        Attributes attrs = searchResult.getAttributes();
        String dn = searchResult.getName() + "," + groupBase;
        String uniquememberAttrName = "uniqueMember";
        if (this.propAttrMap.containsKey("org_member")) {
            try {
                uniquememberAttrName = (String) this.propAttrMap.get("org_member");
            } catch (Exception ex) {
                //ignore
            }/*from w  w  w.java  2s  . c  o  m*/
        }
        Attribute uniquememberAttr = attrs.get(uniquememberAttrName);
        if (uniquememberAttr == null)
            continue;
        NamingEnumeration memberDNs = uniquememberAttr.getAll();
        while (memberDNs.hasMoreElements()) {
            //System.out.println(memberDNs[j]);
            userList.add(memberDNs.next());//DN of user
        }
    }

    List members = new ArrayList();

    for (Iterator userDns = userList.iterator(); userDns.hasNext();) {

        /* Next directory entry */
        String userDn = (String) userDns.next();
        Attributes userEntry = null;
        try {
            userEntry = context.getAttributes(userDn);//DN of user
        } catch (Exception e) {
            log.error(userDn + ": " + e.getMessage());
        }
        if (userEntry == null)
            continue;

        LDAPAccount user = createLDAPUser(userDn, userEntry);
        if (user.getUid() == null)
            continue;

        members.add(user);

    }

    return members;

}

From source file:org.jasig.portal.security.provider.SimpleLdapSecurityContext.java

/**
 * <p>Return a single value of an attribute from possibly multiple values,
 * grossly ignoring anything else.  If there are no values, then
 * return an empty string.</p>//from  www .j  a va2s  .co m
 *
 * @param attrs LDAP query results
 * @param attribute LDAP attribute we are interested in
 * @return a single value of the attribute
 */
private String getAttributeValue(Attributes attrs, int attribute) throws NamingException {
    NamingEnumeration values = null;
    String aValue = "";
    if (!isAttribute(attribute))
        return aValue;
    Attribute attrib = attrs.get(attributes[attribute]);
    if (attrib != null) {
        for (values = attrib.getAll(); values.hasMoreElements();) {
            aValue = (String) values.nextElement();
            break; // take only the first attribute value
        }
    }
    return aValue;
}

From source file:org.jboss.web.tomcat.tc4.SingleSignOnContextConfig.java

/**
 * Accumulate and return a Set of resource paths to be analyzed for
 * tag library descriptors.  Each element of the returned set will be
 * the context-relative path to either a tag library descriptor file,
 * or to a JAR file that may contain tag library descriptors in its
 * <code>META-INF</code> subdirectory.
 *
 * @exception IOException if an input/output error occurs while
 *  accumulating the list of resource paths
 *///www  .  ja  va 2s.c om
private Set tldScanResourcePaths() throws IOException {

    if (debug >= 1) {
        log(" Accumulating TLD resource paths");
    }
    Set resourcePaths = new HashSet();

    // Accumulate resource paths explicitly listed in the web application
    // deployment descriptor
    if (debug >= 2) {
        log("  Scanning <taglib> elements in web.xml");
    }
    String taglibs[] = context.findTaglibs();
    for (int i = 0; i < taglibs.length; i++) {
        String resourcePath = context.findTaglib(taglibs[i]);
        // FIXME - Servlet 2.3 DTD implies that the location MUST be
        // a context-relative path starting with '/'?
        if (!resourcePath.startsWith("/")) {
            resourcePath = "/WEB-INF/" + resourcePath;
        }
        if (debug >= 3) {
            log("   Adding path '" + resourcePath + "' for URI '" + taglibs[i] + "'");
        }
        resourcePaths.add(resourcePath);
    }

    // Scan TLDs in the /WEB-INF subdirectory of the web application
    if (debug >= 2) {
        log("  Scanning TLDs in /WEB-INF subdirectory");
    }
    DirContext resources = context.getResources();
    try {
        NamingEnumeration items = resources.list("/WEB-INF");
        while (items.hasMoreElements()) {
            NameClassPair item = (NameClassPair) items.nextElement();
            String resourcePath = "/WEB-INF/" + item.getName();
            // FIXME - JSP 1.2 is not explicit about whether we should
            // scan subdirectories of /WEB-INF for TLDs also
            if (!resourcePath.endsWith(".tld")) {
                continue;
            }
            if (debug >= 3) {
                log("   Adding path '" + resourcePath + "'");
            }
            resourcePaths.add(resourcePath);
        }
    } catch (NamingException e) {
        ; // Silent catch: it's valid that no /WEB-INF directory exists
    }

    // Scan JARs in the /WEB-INF/lib subdirectory of the web application
    if (debug >= 2) {
        log("  Scanning JARs in /WEB-INF/lib subdirectory");
    }
    try {
        NamingEnumeration items = resources.list("/WEB-INF/lib");
        while (items.hasMoreElements()) {
            NameClassPair item = (NameClassPair) items.nextElement();
            String resourcePath = "/WEB-INF/lib/" + item.getName();
            if (!resourcePath.endsWith(".jar")) {
                continue;
            }
            if (debug >= 3) {
                log("   Adding path '" + resourcePath + "'");
            }
            resourcePaths.add(resourcePath);
        }
    } catch (NamingException e) {
        ; // Silent catch: it's valid that no /WEB-INF/lib directory exists
    }

    // Return the completed set
    return (resourcePaths);

}

From source file:org.jsecurity.realm.activedirectory.ActiveDirectoryRealm.java

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

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

    String userPrincipalName = username;
    if (principalSuffix != null) {
        userPrincipalName += principalSuffix;
    }/*from w  w w  .j ava 2 s  .c o  m*/

    String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, 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.kitodo.production.services.data.LdapServerService.java

/**
 * Check if User already exists on system.
 *
 * @param user/*from  w w  w  .  java 2s  .  c  o  m*/
 *            The User.
 * @return result as boolean
 */
public boolean isUserAlreadyExists(User user) {
    Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(
            user.getLdapGroup().getLdapServer());
    DirContext ctx;
    boolean result = false;
    try {
        ctx = new InitialDirContext(ldapEnvironment);
        Attributes matchAttrs = new BasicAttributes(true);
        NamingEnumeration<SearchResult> answer = ctx.search(buildUserDN(user), matchAttrs);
        result = answer.hasMoreElements();

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            logger.debug(">>>{}", sr.getName());
            Attributes attrs = sr.getAttributes();
            String givenName = getStringForAttribute(attrs, "givenName");
            String surName = getStringForAttribute(attrs, "sn");
            String mail = getStringForAttribute(attrs, "mail");
            String cn = getStringForAttribute(attrs, "cn");
            String homeDirectory = getStringForAttribute(attrs, "homeDirectory");

            logger.debug(givenName);
            logger.debug(surName);
            logger.debug(mail);
            logger.debug(cn);
            logger.debug(homeDirectory);
        }

        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }
    return result;
}

From source file:org.lsc.jndi.JndiServices.java

private SearchResult doGetEntry(final String base, final String filter, final SearchControls sc,
        final int scope) throws NamingException {
    //sanity checks
    String searchBase = base == null ? "" : base;
    String searchFilter = filter == null ? DEFAULT_FILTER : filter;

    NamingEnumeration<SearchResult> ne = null;
    try {/*from w w w .  jav  a2  s.  c  om*/
        sc.setSearchScope(scope);
        String rewrittenBase = null;
        if (contextDn != null && searchBase.toLowerCase().endsWith(contextDn.toString().toLowerCase())) {
            if (!searchBase.equalsIgnoreCase(contextDn.toString())) {
                rewrittenBase = searchBase.substring(0,
                        searchBase.toLowerCase().lastIndexOf(contextDn.toString().toLowerCase()) - 1);
            } else {
                rewrittenBase = "";
            }
        } else {
            rewrittenBase = searchBase;
        }
        ne = ctx.search(rewrittenBase, searchFilter, sc);

    } catch (NamingException nex) {
        LOGGER.error("Error while looking for {} in {}: {}", new Object[] { searchFilter, searchBase, nex });
        throw nex;
    }

    SearchResult sr = null;
    if (ne.hasMoreElements()) {
        sr = (SearchResult) ne.nextElement();
        if (ne.hasMoreElements()) {
            LOGGER.error("Too many entries returned (base: \"{}\", filter: \"{}\")", searchBase, searchFilter);
            throw new SizeLimitExceededException("Too many entries returned (base: \"" + searchBase
                    + "\", filter: \"" + searchFilter + "\")");
        } else {
            return sr;
        }
    } else {
        // try hasMore method to throw exceptions if there are any and we didn't get our entry
        ne.hasMore();
    }
    return sr;
}

From source file:org.lsc.jndi.JndiServices.java

private List<String> doGetDnList(final String base, final String filter, final int scope)
        throws NamingException {
    NamingEnumeration<SearchResult> ne = null;
    List<String> iist = new ArrayList<String>();
    try {//w  w w.  j  a va 2 s  .  co  m
        SearchControls sc = new SearchControls();
        sc.setDerefLinkFlag(false);
        sc.setReturningAttributes(new String[] { "1.1" });
        sc.setSearchScope(scope);
        sc.setReturningObjFlag(true);
        ne = ctx.search(base, filter, sc);

        String completedBaseDn = "";
        if (base.length() > 0) {
            completedBaseDn = "," + base;
        }
        while (ne.hasMoreElements()) {
            iist.add(((SearchResult) ne.next()).getName() + completedBaseDn);
        }
    } catch (NamingException e) {
        LOGGER.error(e.toString());
        LOGGER.debug(e.toString(), e);
        throw e;
    }
    return iist;
}