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: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() + "]");
        }/*www .  j  a  va 2 s.co  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:com.surevine.ldap2alfresco.ProfileFieldTelephoneConverter.java

/**
 * Encode some attributes as JSON.//w w w .ja va 2  s.co  m
 * @param json The JSON object to insert into
 * @param attributes Collection of attributes
 */
public void toJson(final JSONObject json, final Attributes attributes) {

    Attribute attribute = attributes.get(attributeLabel);

    if (attribute == null) {
        LOGGER.debug("Missing attribute: " + attributeLabel);

        // just put an empty entry into the JSON
        try {
            if (allowMultiples) {
                json.put(jsonLabel, new JSONArray());
            } else {
                JSONObject blank = new JSONObject();
                blank.put(JSON_LABEL_NETWORK, "");
                blank.put(JSON_LABEL_NUMBER, "");
                blank.put(JSON_LABEL_EXTENSION, "");
                json.put(jsonLabel, blank);
            }
        } catch (JSONException e) {
            logException(Level.ERROR, e);
        }

        return;
    }

    int numValues = attribute.size();

    if (numValues == 0) {
        LOGGER.error("Attribute " + attributeLabel + " contains no values");
        return;
    }

    try {
        if (allowMultiples) {

            JSONArray values = new JSONArray();

            NamingEnumeration<?> valueEnum = attribute.getAll();

            while (valueEnum.hasMore()) {
                String value = valueEnum.next().toString();
                JSONObject entry = decodePhoneNumber(value);

                if (entry == null) {
                    LOGGER.error("Failed to parse telephone number from :" + value);
                } else {
                    values.put(entry);
                }
            }

            json.put(jsonLabel, values);
        } else {
            // expecting only one value
            if (numValues != 1) {
                LOGGER.error("Expected single value in attribute " + attributeLabel + ", found " + numValues);
                return;
            }

            String value = attribute.get().toString();
            JSONObject entry = decodePhoneNumber(value);

            if (entry == null) {
                LOGGER.error("Failed to parse telephone fields from :" + value);
            } else {
                json.put(jsonLabel, entry);
            }
        }
    } catch (NamingException e) {
        logException(Level.ERROR, e);
        return;
    } catch (JSONException e) {
        logException(Level.ERROR, e);
        return;
    }
}

From source file:org.pepstock.jem.gwt.server.security.ExtendedJndiLdapRealm.java

/**
 * Extract from LDAP all configured attributes.
 * /*w  w  w  . j  a  v  a2s  .co m*/
 * @param id user id
 * @param environment LDAP environment 
 * @return list of principal attributes
 */
public List<PrincipalAttribute> search(String id, Hashtable<String, String> environment) {
    // checks if attributes are set
    if (attributes != null && attributes.length > 0) {
        ctls.setReturningAttributes(attributes);
    }
    // if no attributes, uses UID by default
    if (ctls.getReturningAttributes() == null) {
        ctls.setReturningAttributes(new String[] { UID });
    }

    // uses useDN for searching
    String userDn = super.getUserDnTemplate();
    String ldapUserContext = StringUtils.substringAfter(userDn, ",");
    try {
        // gets initial context
        InitialDirContext ctx = new InitialDirContext(environment);

        // creates search string
        String filter = MessageFormat.format("(uid={0})", new Object[] { id });
        // searchs!
        Object obj = ctx.search(ldapUserContext, filter, ctls);
        // scans all attributes and load into a Principal Attribute
        @SuppressWarnings("rawtypes")
        NamingEnumeration userEnum = (NamingEnumeration) obj;
        if (userEnum != null && userEnum.hasMore()) {
            SearchResult result = (SearchResult) userEnum.next();
            return loadAttributes(id, result.getAttributes());
        }
    } catch (NamingException ne) {
        LogAppl.getInstance().emit(UserInterfaceMessage.JEMG031E, ne, id);
    }
    return new ArrayList<PrincipalAttribute>();
}

From source file:org.craftercms.studio.impl.v1.service.security.DbWithLdapExtensionSecurityProvider.java

private void extractGroupsFromAttribute(User user, String groupNameAttribName, Attribute groupNameAttrib,
        SiteFeed siteFeed) throws NamingException {
    if (groupNameAttrib != null && groupNameAttrib.size() > 0) {
        NamingEnumeration groupAttribValues = groupNameAttrib.getAll();
        while (groupAttribValues.hasMore()) {
            Object groupNameObj = groupAttribValues.next();
            if (groupNameObj != null) {
                String groupName = extractGroupNameFromAttributeValue(groupNameObj.toString());
                if (StringUtils.isNotEmpty(groupName)) {
                    addGroupToUser(user, groupName, siteFeed);
                }/*w  ww  .ja v a2s  . c  om*/
            }
        }
    } else {
        logger.debug("No LDAP attribute " + groupNameAttribName + " found for username " + user.getUsername());
    }
}

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

public static List<Organization> getOrgList(String country) {
    List<Organization> OrgList = new ArrayList<Organization>();
    NamingEnumeration resultCountries = null;
    DirContext ctx = null;//from  w ww  . j  a v a2  s .c  o m
    try {
        ctx = getContext();
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        String filter;
        if (country == null) {
            filter = "(objectclass=country)";
        } else {
            filter = "(&(objectclass=country)(c=" + country + "))";
        }
        resultCountries = ctx.search(rb.getString("organisationsRoot"), filter, controls);

        while (resultCountries.hasMore()) {
            SearchResult searchResult = (SearchResult) resultCountries.next();
            Attributes attributes = searchResult.getAttributes();
            String countryCode = (String) attributes.get("c").get();
            String countryName = (String) attributes.get("co").get();

            NamingEnumeration resultsOrgs = ctx.search(
                    "c=" + countryCode + "," + rb.getString("organisationsRoot"), "(objectclass=organization)",
                    controls);
            while (resultsOrgs.hasMore()) {
                SearchResult srOrg = (SearchResult) resultsOrgs.next();
                Attributes orgAttrs = srOrg.getAttributes();
                String description = "";
                if ((orgAttrs.get("description")) != null) {
                    description = (String) orgAttrs.get("description").get();
                }

                OrgList.add(new Organization((String) orgAttrs.get("o").get(), countryName, countryCode,
                        description, srOrg.getNameInNamespace()));
            }
            resultsOrgs.close();

        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (resultCountries != null) {
            try {
                resultCountries.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    Collections.sort(OrgList, new Comparator<Organization>() {

        public int compare(Organization o1, Organization o2) {
            return o1.getKey().compareTo(o2.getKey());
        }

    });

    return OrgList;

}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Test to make sure anonymous binds are allowed on the RootDSE even when disabled
 * in general when going through the wire protocol.
 *
 * @throws Exception if anything goes wrong
 *//*  w ww  .  j  a va  2 s  .co m*/
@Test
public void testEnableAnonymousBindsOnRootDse() 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("", "(objectClass=*)", cons);

    SearchResult result = null;

    if (list.hasMore()) {
        result = list.next();
    }

    assertFalse(list.hasMore());
    list.close();

    assertNotNull(result);
    assertEquals("", result.getName().trim());
}

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

private LdapUser getUserByDN(final String userDN) throws NamingException {
    NamingEnumeration<SearchResult> answer = getContext().search(settings.getUserFilterBaseDN(),
            "(distinguishedName=" + userDN + ")", getDefaultSearchControls());
    while (answer.hasMoreElements()) {
        Attributes attr = answer.next().getAttributes();
        if (hasRequiredUserAttributesFilled(attr, settings)) {
            return new LdapUser(attr, settings);
        }//from   ww  w . jav  a  2  s . c  om
    }
    return null;
}

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;
    }/*  www .  j av  a 2 s.c om*/

    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;
    }//  ww w  . j ava 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:jndi.view.JndiView.java

/**
 * @param ctx/*from  w  ww  .  j  a va2 s .  c o m*/
 *        the Context we're examining
 * @param path
 *        the path to examine
 * @param bindings
 *        the {@link NamingEnumeration} of {@link Binding}s
 * @return List of {@link JndiEntry}
 * @throws NamingException
 *         on exception
 */
private List<JndiEntry> examineBindings(final Context ctx, final String path,
        final NamingEnumeration<Binding> bindings) throws NamingException {
    if (null == bindings) {
        throw new NullPointerException("bindings is null!");
    }
    final List<JndiEntry> entries = new ArrayList<JndiEntry>();
    while (bindings.hasMore()) {
        final Binding binding = bindings.next();
        final String name = binding.getName();
        final String className = binding.getClassName();

        logger.finest("name: " + name + " [" + className + "]");
        final JndiEntry entry = new JndiEntry(name, className);
        final Object obj = binding.getObject();
        if (obj instanceof Context) {
            entry.setContext(true);
            String link = name;
            if (!path.isEmpty()) {
                link = path + "/" + name;
            }
            entry.setLink(link);
        } else if (obj instanceof Reference) {
            final Reference ref = (Reference) obj;
            entry.setTargetClassName(ref.getClassName());
        } else if ("org.glassfish.javaee.services.ResourceProxy".equals(className)) {
            // SUPPRESS CHECKSTYLE AvoidInlineConditionals
            final Object lookup = ctx.lookup(path.isEmpty() ? name : path + "/" + name);
            if (lookup != null) {
                final String lookedUpClassName = lookup.getClass().getName();
                logger.finest("lookup(\"" + name + "\") returned " + lookedUpClassName);
                entry.setTargetClassName(lookedUpClassName);
            }
        } else if ("com.sun.ejb.containers.JavaGlobalJndiNamingObjectProxy".equals(className)) {
            inspectJndiNamingObjectProxy(entry, obj);
        }
        entries.add(entry);
    }
    return entries;
}