Example usage for javax.naming NamingEnumeration hasMore

List of usage examples for javax.naming NamingEnumeration hasMore

Introduction

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

Prototype

public boolean hasMore() throws NamingException;

Source Link

Document

Determines whether there are any more elements in the enumeration.

Usage

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

public static LDAPUser findUserByMail(String mail) {
    NamingEnumeration results = null;
    DirContext ctx = null;/*  www . ja va 2 s  .  c o  m*/
    LDAPUser user = null;
    try {
        ctx = getContext();
        SearchControls controls = new SearchControls();
        String retAttrs[] = { "cn" };
        controls.setReturningAttributes(retAttrs);
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search(rb.getString("peopleRoot"), "(mail=" + mail + ")", controls);
        if (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            user = new LDAPUser();

            if (attributes.get("cn") != null)
                user = getUser((String) attributes.get("cn").get());
        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } 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 user;

}

From source file:org.springframework.ldap.pool.validation.DefaultDirContextValidator.java

/**
 * @see DirContextValidator#validateDirContext(DirContextType, javax.naming.directory.DirContext)
 *//*from   w w w.  jav  a  2 s  .c o  m*/
public boolean validateDirContext(DirContextType contextType, DirContext dirContext) {
    Validate.notNull(contextType, "contextType may not be null");
    Validate.notNull(dirContext, "dirContext may not be null");

    try {
        final NamingEnumeration searchResults = dirContext.search(this.base, this.filter, this.searchControls);

        if (searchResults.hasMore()) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("DirContext '" + dirContext + "' passed validation.");
            }

            return true;
        }
    } catch (Exception e) {
        this.logger.warn("DirContext '" + dirContext + "' failed validation with an exception.", e);
    }

    if (this.logger.isInfoEnabled()) {
        this.logger.info("DirContext '" + dirContext + "' failed validation.");
    }
    return false;
}

From source file:org.beangle.security.ldap.connect.SimpleLdapUserStore.java

public String getUserDN(String uid) {
    DirContext ctx = getContext();
    if (ctx == null)
        return null;
    String result = null;/*  w  w w.  j a v a  2 s  .  c  om*/
    String condition = StrUtils.concat(uidName, "=", uid);
    try {
        String attrList[] = { uidName };
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(2);
        constraints.setReturningAttributes(attrList);
        NamingEnumeration<SearchResult> results = ctx.search(base, condition, constraints);
        if (results.hasMore()) {
            SearchResult si = results.next();
            result = StrUtils.concat(si.getName(), ",", base);
        }
        results.close();
        results = null;
    } catch (Throwable e) {
        logger.error("Ldap search error,uid=" + uid, e);
    }
    return result;
}

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

boolean searchForResult(InitialLdapContext context, String searchBase, String filter) throws NamingException {
    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration<SearchResult> results = context.search(searchBase, filter, constraints);
    return results.hasMore();
}

From source file:org.jasig.schedassist.impl.oraclecalendar.OracleCalendarResourceAccountAttributesMapper.java

@Override
public Object mapFromAttributes(Attributes attributes) throws NamingException {
    OracleCalendarResourceAccount user = new OracleCalendarResourceAccount(owner);

    NamingEnumeration<String> attributeNames = attributes.getIDs();
    Map<String, String> attributesMap = new HashMap<String, String>();
    while (attributeNames.hasMore()) {
        String attributeName = attributeNames.next();
        Attribute attribute = attributes.get(attributeName);
        String value = (String) attribute.get();
        if (null != value) {
            value = value.trim();/*from   w w w.j av  a 2  s  .c o m*/
        }
        final String lcAttributeName = attributeName.toLowerCase();
        attributesMap.put(lcAttributeName, value);

        if (RESOURCE_OWNER_USERNAME.equals(lcAttributeName)) {
            user.setAccountOwnerUsername(value);
        } else if (AbstractOracleCalendarAccount.CTCALXITEMID.equals(lcAttributeName)) {
            user.setCtcalxitemid(value);
        } else if (OracleLdapCalendarResourceAccountDaoImpl.CN.equals(lcAttributeName)) {
            user.setResourceName(value);
        } else if (OracleLdapCalendarResourceAccountDaoImpl.POSTALADDRESS.equals(lcAttributeName)) {
            user.setLocation(value);
        } else if (AbstractOracleCalendarAccount.WISCEDUCALEMAIL.equals(lcAttributeName)) {
            user.setEmailAddress(value);
        }

    }
    user.setAttributes(attributesMap);

    String contactInfo = buildContactInformation(
            getAttributeValue(attributes, OracleLdapCalendarResourceAccountDaoImpl.GIVENNAME),
            getAttributeValue(attributes, OracleLdapCalendarResourceAccountDaoImpl.SN),
            getAttributeValue(attributes, OracleLdapCalendarResourceAccountDaoImpl.TELEPHONENUMBER));
    user.setContactInformation(contactInfo);

    String oracleGuid = this.oracleGUIDSource.getOracleGUID(user);
    user.setOracleGuid(oracleGuid);
    user.getAttributes().put(AbstractOracleCalendarAccount.ORACLE_GUID_ATTRIBUTE, oracleGuid);
    return user;
}

From source file:org.jamwiki.ldap.LdapUserHandler.java

/**
 *
 *///from w  w w . j a  va2 s  . co m
public WikiUserInfo lookupWikiUserInfo(String username) throws Exception {
    InitialDirContext ctx = null;
    try {
        ctx = getContext(Environment.getValue(Environment.PROP_LDAP_LOGIN),
                Encryption.getEncryptedProperty(Environment.PROP_LDAP_PASSWORD, null));
        BasicAttributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute(Environment.getValue(Environment.PROP_LDAP_FIELD_USERID), username));
        NamingEnumeration answer = ctx.search(Environment.getValue(Environment.PROP_LDAP_CONTEXT), matchAttrs,
                SEARCH_ATTRIBUTES);
        return (!answer.hasMore()) ? null : this.initWikiUserInfo(answer);
    } finally {
        try {
            ctx.close();
        } catch (Exception e) {
        }
    }
}

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 a v a2s .  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:com.surevine.ldap2alfresco.ProfileFieldTextConverter.java

/**
 * Encode some attributes as JSON.//  ww w  . ja  v  a2 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 {
                json.put(jsonLabel, "");
            }
        } 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();
                if (value != null && value.length() > MAX_STRING_LENGTH) {
                    value = value.substring(0, MAX_STRING_LENGTH - 1);
                }
                values.put(value);
            }

            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();
            if (value != null && value.length() > MAX_STRING_LENGTH) {
                value = value.substring(0, MAX_STRING_LENGTH - 1);
            }

            json.put(jsonLabel, value);
        }
    } catch (NamingException e) {
        logException(Level.ERROR, e);
        return;
    } catch (JSONException e) {
        logException(Level.ERROR, e);
        return;
    }
}

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

@Test
public void testOkResultSearchQueryLDAP() throws NamingException, IOException {
    PowerMockito.mockStatic(LDAPConnectionUtility.class);
    try {//from   ww w.  ja v  a  2 s. c  om
        when(LDAPConnectionUtility.connect(ldapUrl, ldapDnBase, ldapUsername, ldapPassword))
                .thenReturn(ldapConnection);
    } catch (NamingException e) {
        e.printStackTrace();
    }
    ldapClient = getLdapClient();

    NamingEnumeration results = mock(NamingEnumeration.class);
    when(ldapConnection.search(anyString(), anyString(), any(SearchControls.class))).thenReturn(results);
    when(results.hasMore()).thenReturn(false);

    String jsonResponse = ldapClient.searchQueryLDAP();
    PowerMockito.verifyStatic(Mockito.times(1));
    Response response = mapper.readValue(jsonResponse, LDAPResponse.class);
    assertThat(response.getStatus(), is("Ok"));
}

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

private void mapResults(PagedResultMapper mapper, NamingEnumeration<SearchResult> results)
        throws NamingException {
    while (results != null && results.hasMore()) {
        SearchResult searchResult = results.next();
        String dn = searchResult.getNameInNamespace();

        try {//from w  ww  . j  av a2 s.c  o  m
            if (isDnValid(dn)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Included result " + dn);
                }
                mapper.mapSearchResult(searchResult);
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Excluding result " + dn);
                }
            }
        } catch (Exception e) {
            mapper.processSearchResultException(searchResult, e);
        }
    }
}