Example usage for javax.naming NamingEnumeration next

List of usage examples for javax.naming NamingEnumeration next

Introduction

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

Prototype

public T next() throws NamingException;

Source Link

Document

Retrieves the next element in the enumeration.

Usage

From source file:openscim.restful.server.resources.group.ldap.GroupAttributesMapper.java

public Object mapFromAttributes(Attributes attributes) throws NamingException {
    // create a group resource
    Group group = ResourceUtilities.FACTORY.createGroup();

    // get the gid attribute name
    String gidAtttributeName = properties.getProperty(GID_ATTRIBUTE, DEFAULT_GID_ATTRIBUTE);

    // get the gid      
    Attribute gidAttribute = attributes.get(gidAtttributeName);
    if (gidAttribute != null)
        group.setId((String) gidAttribute.get());

    // get the member attribute name
    String memberAtttributeName = properties.getProperty(MEMBER_ATTRIBUTE, DEFAULT_MEMBER_ATTRIBUTE);

    // get the members
    NamingEnumeration memberEnumeration = attributes.get(memberAtttributeName).getAll();
    if (memberEnumeration != null) {
        // create a members resource
        List<PluralAttribute> members = new ArrayList<PluralAttribute>();

        while (memberEnumeration.hasMoreElements()) {
            // get the next member
            String memberAttribute = (String) memberEnumeration.next();
            if (memberAttribute != null) {
                PluralAttribute pluralAttribute = ResourceUtilities.FACTORY.createPluralAttribute();

                // check if the member dns need to be concealed 
                if (properties
                        .getProperty(GroupAttributesMapper.CONCEAL_GROUP_DNS,
                                GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)
                        .equalsIgnoreCase(GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)) {
                    Matcher matcher = pattern.matcher(memberAttribute);
                    if (matcher.matches()) {
                        memberAttribute = matcher.group(1);
                    }//from  ww  w  .  j  a v  a 2  s.  co m
                }

                pluralAttribute.setValue(memberAttribute);
                members.add(pluralAttribute);
            }
        }

        // add the members to the group resource
        group.setAny(members);
    }

    return group;
}

From source file:org.apache.cxf.sts.claims.LdapClaimsHandler.java

public ProcessedClaimCollection retrieveClaimValues(ClaimCollection claims, ClaimsParameters parameters) {
    String user = null;//from  w  w  w  .  jav a  2s.  com
    boolean useLdapLookup = false;

    Principal principal = parameters.getPrincipal();
    if (principal instanceof KerberosPrincipal) {
        KerberosPrincipal kp = (KerberosPrincipal) principal;
        StringTokenizer st = new StringTokenizer(kp.getName(), "@");
        user = st.nextToken();
    } else if (principal instanceof X500Principal) {
        X500Principal x500p = (X500Principal) principal;
        LOG.warning("Unsupported principal type X500: " + x500p.getName());
        return new ProcessedClaimCollection();
    } else if (principal != null) {
        user = principal.getName();
        if (user == null) {
            LOG.warning("User must not be null");
            return new ProcessedClaimCollection();
        }
        useLdapLookup = LdapUtils.isDN(user);

    } else {
        LOG.warning("Principal is null");
        return new ProcessedClaimCollection();
    }

    if (LOG.isLoggable(Level.FINEST)) {
        LOG.finest("Retrieve claims for user " + user);
    }

    Map<String, Attribute> ldapAttributes = null;
    if (useLdapLookup) {
        AttributesMapper mapper = new AttributesMapper() {
            public Object mapFromAttributes(Attributes attrs) throws NamingException {
                Map<String, Attribute> map = new HashMap<String, Attribute>();
                NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
                while (attrEnum.hasMore()) {
                    Attribute att = attrEnum.next();
                    map.put(att.getID(), att);
                }
                return map;
            }
        };

        Object result = ldap.lookup(user, mapper);
        ldapAttributes = CastUtils.cast((Map<?, ?>) result);
    } else {
        List<String> searchAttributeList = new ArrayList<String>();
        for (Claim claim : claims) {
            if (getClaimsLdapAttributeMapping().keySet().contains(claim.getClaimType().toString())) {
                searchAttributeList.add(getClaimsLdapAttributeMapping().get(claim.getClaimType().toString()));
            } else {
                if (LOG.isLoggable(Level.FINER)) {
                    LOG.finer("Unsupported claim: " + claim.getClaimType());
                }
            }
        }

        String[] searchAttributes = null;
        searchAttributes = searchAttributeList.toArray(new String[searchAttributeList.size()]);

        ldapAttributes = LdapUtils.getAttributesOfEntry(ldap, this.userBaseDn, this.getObjectClass(),
                this.getUserNameAttribute(), user, searchAttributes);
    }

    if (ldapAttributes == null || ldapAttributes.size() == 0) {
        //No result
        if (LOG.isLoggable(Level.INFO)) {
            LOG.finest("User '" + user + "' not found");
        }
        return new ProcessedClaimCollection();
    }

    ProcessedClaimCollection claimsColl = new ProcessedClaimCollection();

    for (Claim claim : claims) {
        URI claimType = claim.getClaimType();
        String ldapAttribute = getClaimsLdapAttributeMapping().get(claimType.toString());
        Attribute attr = ldapAttributes.get(ldapAttribute);
        if (attr == null) {
            if (LOG.isLoggable(Level.FINEST)) {
                LOG.finest("Claim '" + claim.getClaimType() + "' is null");
            }
        } else {
            ProcessedClaim c = new ProcessedClaim();
            c.setClaimType(claimType);
            c.setPrincipal(principal);

            StringBuilder claimValue = new StringBuilder();
            try {
                NamingEnumeration<?> list = (NamingEnumeration<?>) attr.getAll();
                while (list.hasMore()) {
                    Object obj = list.next();
                    if (!(obj instanceof String)) {
                        LOG.warning("LDAP attribute '" + ldapAttribute + "' has got an unsupported value type");
                        break;
                    }
                    String itemValue = (String) obj;
                    if (this.isX500FilterEnabled()) {
                        try {
                            X500Principal x500p = new X500Principal(itemValue);
                            itemValue = x500p.getName();
                            int index = itemValue.indexOf('=');
                            itemValue = itemValue.substring(index + 1, itemValue.indexOf(',', index));
                        } catch (Exception ex) {
                            //Ignore, not X500 compliant thus use the whole string as the value
                        }
                    }
                    claimValue.append(itemValue);
                    if (list.hasMore()) {
                        claimValue.append(this.getDelimiter());
                    }
                }
            } catch (NamingException ex) {
                LOG.warning("Failed to read value of LDAP attribute '" + ldapAttribute + "'");
            }

            c.addValue(claimValue.toString());
            // c.setIssuer(issuer);
            // c.setOriginalIssuer(originalIssuer);
            // c.setNamespace(namespace);
            claimsColl.add(c);
        }
    }

    return claimsColl;
}

From source file:eu.uqasar.util.ldap.LdapManager.java

private LdapUser getUserBySAMAccountName(final String sAMAccountName) throws NamingException {
    NamingEnumeration<SearchResult> answer = getContext().search(settings.getUserFilterBaseDN(),
            "(sAMAccountName=" + sAMAccountName + ")", getDefaultSearchControls());
    while (answer.hasMoreElements()) {
        Attributes attr = answer.next().getAttributes();
        if (hasRequiredUserAttributesFilled(attr, settings)) {
            return new LdapUser(attr, settings);
        }//from   w w  w. java  2 s  . co  m
    }
    return null;
}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

private boolean getUserInf(UserEdit edit, String filter) {

    String id = null;// ww  w.ja  v  a2  s.  c o m
    String firstName = null;
    String lastName = null;
    String employeenumber = null;
    String email = null;
    try {
        DirContext ctx = new InitialDirContext(env);

        // Setup subtree scope to tell LDAP to recursively descend directory structure
        // during searches.
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // We want the user's id, first name and last name ...
        searchControls.setReturningAttributes(new String[] { "uid", "givenName", "sn" });

        // Execute the search, starting at the directory level of Users
        NamingEnumeration results = ctx.search(getBasePath(), filter, searchControls);

        while (results.hasMore()) {
            SearchResult result = (SearchResult) results.next();
            String dn = result.getName().toString() + "," + getBasePath();
            Attributes attrs = ctx.getAttributes(dn);
            id = attrs.get("uid").get().toString();
            String cn = attrs.get("cn").get().toString();
            firstName = cn.substring(0, cn.indexOf(" "));
            lastName = cn.substring(cn.indexOf(" "));
            email = attrs.get("mail").get().toString();
        }

        results.close();
        ctx.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

    edit.setId(id);
    edit.setFirstName(firstName);
    edit.setLastName(lastName);
    edit.setEmail(email);
    return true;
}

From source file:net.officefloor.plugin.web.http.security.store.JndiLdapCredentialStore.java

@Override
public CredentialEntry retrieveCredentialEntry(String userId, String realm) throws IOException {
    try {/* w  w w.j  av a 2 s  . co  m*/
        // Search for the credential entry
        NamingEnumeration<SearchResult> searchResults = this.context.search(this.entrySearchBaseDn,
                "(&(objectClass=inetOrgPerson)(uid=" + userId + "))", null);
        if (!searchResults.hasMore()) {
            return null; // entry not found
        }
        SearchResult result = searchResults.next();

        // Obtain the attributes
        String entryDn = result.getNameInNamespace();

        // Create and return the credential entry
        return new JndiLdapCredentialEntry(entryDn);

    } catch (NamingException ex) {
        throw new IOException(ex);
    }
}

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  w w . jav  a  2  s.c om
 *
 * @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:io.apiman.gateway.engine.policies.BasicAuthLDAPTest.java

@Test
@Ignore/*w  w  w  . jav  a2  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.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

private ArrayList<String> addAttributeValues(String attrId, Attributes attrs, ArrayList<String> values)
        throws NamingException {

    if (attrId == null || attrs == null) {
        return values;
    }/*from   ww  w .  j a  v  a 2 s . co m*/
    if (values == null) {
        values = new ArrayList<String>();
    }
    Attribute attr = attrs.get(attrId);
    if (attr == null) {
        return (values);
    }
    NamingEnumeration e = attr.getAll();
    while (e.hasMore()) {
        String value = (String) e.next();
        values.add(value);
    }
    return values;
}

From source file:org.apache.zeppelin.rest.GetUserList.java

/**
 * function to extract users from Zeppelin LdapRealm
 *//*from  w  w w  .j  av  a2s  .  c  o m*/
public List<String> getUserList(LdapRealm r, String searchText) {
    List<String> userList = new ArrayList<>();
    if (LOG.isDebugEnabled()) {
        LOG.debug("SearchText: " + searchText);
    }
    String userAttribute = r.getUserSearchAttributeName();
    String userSearchRealm = r.getUserSearchBase();
    String userObjectClass = r.getUserObjectClass();
    JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
    try {
        LdapContext ctx = CF.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { userAttribute };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userSearchRealm,
                "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=" + searchText + "))",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userAttribute) != null) {
                String currentUser;
                if (r.getUserLowerCase()) {
                    LOG.debug("userLowerCase true");
                    currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase();
                } else {
                    LOG.debug("userLowerCase false");
                    currentUser = (String) attrs.get(userAttribute).get();
                }
                if (LOG.isDebugEnabled()) {
                    LOG.debug("CurrentUser: " + currentUser);
                }
                userList.add(currentUser.trim());
            }
        }
    } catch (Exception e) {
        LOG.error("Error retrieving User list from Ldap Realm", e);
    }
    return userList;
}

From source file:org.talend.dataquality.email.checkerImpl.CallbackMailServerCheckerImpl.java

private List<String> getMX(String hostName) throws NamingException {
    // Perform a DNS lookup for MX records in the domain
    Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" }); //$NON-NLS-1$
    Attribute attr = attrs.get("MX"); //$NON-NLS-1$
    List<String> res = new ArrayList<String>();

    // if we don't have an MX record, try the machine itself
    if ((attr == null) || (attr.size() == 0)) {
        attrs = ictx.getAttributes(hostName, new String[] { "A" }); //$NON-NLS-1$
        attr = attrs.get("A"); //$NON-NLS-1$
        if (attr == null) {
            if (LOG.isInfoEnabled()) {
                LOG.info(HEADER + "No match for hostname '" + hostName + "'"); //$NON-NLS-1$ //$NON-NLS-2$
            }/*w  w w.  ja  v a  2  s  . c  om*/
            return res;
        }
    }
    // we have machines to try. Return them as an array list
    NamingEnumeration<?> en = attr.getAll();
    Map<Integer, String> map = new TreeMap<Integer, String>();

    while (en.hasMore()) {
        String mailhost;
        String x = (String) en.next();
        String f[] = x.split(" "); //$NON-NLS-1$
        Integer key = 0;
        if (f.length == 1) {
            mailhost = f[0];
        } else if (f[1].endsWith(".")) { //$NON-NLS-1$
            mailhost = f[1].substring(0, f[1].length() - 1);
            key = Integer.valueOf(f[0]);
        } else {
            mailhost = f[1];
            key = Integer.valueOf(f[0]);
        }
        map.put(key, mailhost);
    }
    // NOTE: We SHOULD take the preference into account to be absolutely
    // correct.
    Iterator<Integer> keyInterator = map.keySet().iterator();
    while (keyInterator.hasNext()) {
        res.add(map.get(keyInterator.next()));
    }
    return res;
}