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:org.apache.syncope.fit.core.reference.GroupITCase.java

@Test
public void issueSYNCOPE632() {
    GroupTO groupTO = null;/*from ww w  .  j  a  va 2  s .c  om*/
    try {
        // 1. create new LDAP resource having ConnObjectKey mapped to a derived attribute
        ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP);
        newLDAP.setKey("new-ldap");
        newLDAP.setPropagationPrimary(true);

        MappingTO mapping = newLDAP.getProvision(AnyTypeKind.GROUP.name()).getMapping();

        MappingItemTO connObjectKey = mapping.getConnObjectKeyItem();
        connObjectKey.setIntMappingType(IntMappingType.GroupDerivedSchema);
        connObjectKey.setIntAttrName("displayProperty");
        mapping.setConnObjectKeyItem(connObjectKey);
        mapping.setConnObjectLink("'cn=' + displayProperty + ',ou=groups,o=isp'");

        MappingItemTO description = new MappingItemTO();
        description.setIntMappingType(IntMappingType.GroupKey);
        description.setExtAttrName("description");
        description.setPurpose(MappingPurpose.BOTH);
        mapping.add(description);

        newLDAP = createResource(newLDAP);
        assertNotNull(newLDAP);

        // 2. create a group and give the resource created above
        groupTO = getSampleTO("lastGroup" + getUUIDString());
        groupTO.getPlainAttrs().add(attrTO("icon", "anIcon"));
        groupTO.getPlainAttrs().add(attrTO("show", "true"));
        groupTO.getDerAttrs().add(attrTO("displayProperty", null));
        groupTO.getResources().clear();
        groupTO.getResources().add("new-ldap");

        groupTO = createGroup(groupTO);
        assertNotNull(groupTO);

        // 3. update the group
        GroupMod groupMod = new GroupMod();
        groupMod.setKey(groupTO.getKey());
        groupMod.getPlainAttrsToRemove().add("icon");
        groupMod.getPlainAttrsToUpdate().add(attrMod("icon", "anotherIcon"));

        groupTO = updateGroup(groupMod);
        assertNotNull(groupTO);

        // 4. check that a single group exists in LDAP for the group created and updated above
        int entries = 0;
        DirContext ctx = null;
        try {
            ctx = getLdapResourceDirContext(null, null);

            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(new String[] { "*", "+" });
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp",
                    "(description=" + groupTO.getKey() + ")", ctls);
            while (result.hasMore()) {
                result.next();
                entries++;
            }
        } catch (Exception e) {
            // ignore
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {
                    // ignore
                }
            }
        }

        assertEquals(1, entries);
    } finally {
        if (groupTO != null) {
            groupService.delete(groupTO.getKey());
        }
        resourceService.delete("new-ldap");
    }
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

private String lookupUserId(String serverName) throws DirectoryServerManagerException {

    DirContext dirContext;//from  ww  w. j  a  v  a2 s  .c o m
    try {
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e);
    }

    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    //first search the existing user entry.
    String searchFilter = getServicePrincipleFilter(serverName);

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { "uid" });
    try {
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter,
                searchControls);

        // here we assume only one user
        if (namingEnumeration.hasMore()) {

            SearchResult searchResult;

            searchResult = namingEnumeration.next();

            Attributes attributes = searchResult.getAttributes();

            Attribute userId = attributes.get("uid");
            return (String) userId.get();
        } else {
            return null;
        }

    } catch (NamingException e) {
        log.error("Could not find user id for given server " + serverName, e);
        throw new DirectoryServerManagerException("Could not find user id for given server " + serverName, e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }

}

From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java

/**
 * Resolves all the groups that the user is in.
 *
 * We now use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms680275(v=vs.85).aspx">tokenGroups</a>
 * attribute, which is a computed attribute that lists all the SIDs of the groups that the user is directly/indirectly in.
 * We then use that to retrieve all the groups in one query and resolve their canonical names.
 *
 * @param userDN/*from   w w w.  j  a  v  a  2  s  .c  o  m*/
 *      User's distinguished name.
 * @param context Used for making queries.
 */
private Set<GrantedAuthority> resolveGroups(String domainDN, String userDN, DirContext context)
        throws NamingException {
    if (userDN.contains("/")) {
        userDN = userDN.replace("/", "\\/");
    }
    Set<GrantedAuthority> groups = new HashSet<GrantedAuthority>();

    LOGGER.log(Level.FINER, "Looking up group of {0}", userDN);
    Attributes id = context.getAttributes(userDN, new String[] { "tokenGroups", "memberOf", "CN" });
    Attribute tga = id.get("tokenGroups");

    if (tga == null) {
        // tga will be null if you are not using a global catalogue
        // or if the user is not actually a member of any security groups.
        LOGGER.log(Level.FINE, "Failed to retrieve tokenGroups for {0}", userDN);
        // keep on trucking as we can still use memberOf for Distribution Groups.
    } else {
        // build up the query to retrieve all the groups
        StringBuilder query = new StringBuilder("(|");
        List<byte[]> sids = new ArrayList<byte[]>();

        NamingEnumeration<?> tokenGroups = tga.getAll();
        while (tokenGroups.hasMore()) {
            byte[] gsid = (byte[]) tokenGroups.next();
            query.append("(objectSid={" + sids.size() + "})");
            sids.add(gsid);
        }
        tokenGroups.close();

        query.append(")");

        NamingEnumeration<SearchResult> renum = new LDAPSearchBuilder(context, domainDN).subTreeScope()
                .returns("cn").search(query.toString(), sids.toArray());
        parseMembers(userDN, groups, renum);
        renum.close();
    }

    {/*
     stage 2: use memberOf to find groups that aren't picked up by tokenGroups.
     This includes distribution groups
        */
        LOGGER.fine("Stage 2: looking up via memberOf");

        while (true) {
            switch (groupLookupStrategy) {
            case TOKENGROUPS:
                // no extra lookup - ever.
                return groups;
            case AUTO:
                // try the accurate one first, and if it's too slow fall back to recursive in the hope that it's faster
                long start = System.nanoTime();
                boolean found = false;
                long duration = 0;
                try {
                    found = chainGroupLookup(domainDN, userDN, context, groups);
                    duration = TimeUnit2.NANOSECONDS.toSeconds(System.nanoTime() - start);
                } catch (TimeLimitExceededException e) {
                    LOGGER.log(Level.WARNING,
                            "The LDAP request did not terminate within the specified time limit. AD will fall back to recursive lookup",
                            e);
                } catch (NamingException e) {
                    if (e.getMessage().contains("LDAP response read timed out")) {
                        LOGGER.log(Level.WARNING,
                                "LDAP response read time out. AD will fall back to recursive lookup", e);
                    } else {
                        throw e;
                    }
                }
                if (!found && duration >= 10) {
                    LOGGER.log(Level.WARNING,
                            "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension timed out after {0} seconds. Falling back to recursive group lookup strategy for this and future queries",
                            duration);
                    groupLookupStrategy = GroupLookupStrategy.RECURSIVE;
                    continue;
                } else if (found && duration >= 10) {
                    LOGGER.log(Level.WARNING,
                            "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension matched user's groups but took {0} seconds to run. Switching to recursive lookup for future group lookup queries",
                            duration);
                    groupLookupStrategy = GroupLookupStrategy.RECURSIVE;
                    return groups;
                } else if (!found) {
                    LOGGER.log(Level.WARNING,
                            "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension failed. Falling back to recursive group lookup strategy for this and future queries");
                    groupLookupStrategy = GroupLookupStrategy.RECURSIVE;
                    continue;
                } else {
                    // it run fast enough, so let's stick to it
                    groupLookupStrategy = GroupLookupStrategy.CHAIN;
                    return groups;
                }
            case RECURSIVE:
                recursiveGroupLookup(context, id, groups);
                return groups;
            case CHAIN:
                chainGroupLookup(domainDN, userDN, context, groups);
                return groups;
            }
        }
    }
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public void updateServicePrinciplePassword(String serverName, Object oldCredential, Object newCredentials)
        throws DirectoryServerManagerException {

    DirContext dirContext;// www.ja  v a 2 s  . c o  m

    try {
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e);
    }

    //first search the existing user entry.
    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String searchFilter = getServicePrincipleFilter(serverName);

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_PASSWORD });

    try {
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter,
                searchControls);
        // here we assume only one user
        while (namingEnumeration.hasMore()) {

            BasicAttributes basicAttributes = new BasicAttributes(true);

            SearchResult searchResult = namingEnumeration.next();
            Attributes attributes = searchResult.getAttributes();

            Attribute userPassword = attributes.get(LDAPServerManagerConstants.LDAP_PASSWORD);
            Attribute newPasswordAttribute = getChangePasswordAttribute(userPassword, oldCredential,
                    newCredentials);
            basicAttributes.put(newPasswordAttribute);

            String dnName = searchResult.getName();
            dirContext = (DirContext) dirContext.lookup(searchBase);

            dirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes);
        }

    } catch (NamingException e) {
        log.error("Unable to update server principle password details. Server name - " + serverName);
        throw new DirectoryServerManagerException("Can not access the directory service", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }
}

From source file:com.wfp.utils.LDAPUtils.java

public static String getUserImageAsString(String uid) {
    String base64String = null;
    if (uid != null && uid != "") {
        // Specify the attributes to return
        String searchFilter = "(&" + FILTER_LDAP_USERS + "((uid=" + uid + ")))";
        String searchBase = LDAP_FILTER_URL + "uid=" + uid + "," + LDAP_BASE;

        String returnedAtts[] = { "" + PROPERTY_IMAGE };
        // Specify the search scope
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchCtls.setReturningAttributes(returnedAtts);
        // Search for objects using the filter
        try {//from   w w  w.  j av  a2s .c om
            NamingEnumeration results = getSearchResults(getLDAPContext(), searchCtls, searchFilter,
                    searchBase);
            while (results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();
                Attributes attributes = searchResult.getAttributes();
                Attribute attr = attributes.get(PROPERTY_IMAGE);
                if (attr != null)
                    base64String = new String(
                            org.apache.commons.codec.binary.Base64.encodeBase64((byte[]) attr.get()));

            }
        } catch (NamingException e) {
            Logger.error(" Error occured while fetching user image 1334: getUserImageBytes(String uid):["
                    + e.getLocalizedMessage() + "]", LDAPUtils.class);
        }
    }
    return base64String;
}

From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java

protected void processLdapResults(NamingEnumeration results, ArrayList keys) {
    //long time1 = System.currentTimeMillis();
    //long casting=0;
    //long getting=0;
    //long setting=0;
    //long looping=0;
    //long loop1=System.currentTimeMillis();
    try {/*from  www. j a  v  a2 s.  co m*/
        while (results.hasMore()) {
            //long loop2 = System.currentTimeMillis();
            //long cast1=System.currentTimeMillis();
            //looping=looping+loop2-loop1;
            SearchResult result = (SearchResult) results.next();
            //long cast2 = System.currentTimeMillis();
            //long get1 = System.currentTimeMillis();
            Attributes ldapattribs = result.getAttributes();
            //long get2 = System.currentTimeMillis();
            //long set1 = System.currentTimeMillis();
            Attribute attrib = ldapattribs.get(keyfield);
            if (attrib != null) {
                keys.add(String.valueOf(attrib.get()).toLowerCase());
            }
            //long set2 = System.currentTimeMillis();
            //loop1=System.currentTimeMillis();
            //casting=casting+cast2-cast1;
            //setting=setting+set2-set1;
            //getting=getting+get2-get1;
        }
    } catch (NamingException nex) {
        log.error("LDAPGroupStore: error processing results", nex);
    } finally {
        try {
            results.close();
        } catch (Exception e) {
        }
    }
    //long time5 = System.currentTimeMillis();
    //System.out.println("Result processing took "+(time5-time1)+": "+getting+" for getting, "
    //  +setting+" for setting, "+casting+" for casting, "+looping+" for looping,"
    //  +(time5-loop1)+" for closing");
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public boolean isValidPassword(String serverName, Object existingCredentials)
        throws DirectoryServerManagerException {

    DirContext dirContext;/*from   ww  w  . j  av  a2 s .c o  m*/
    try {
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e);
    }

    //first search the existing user entry.
    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String searchFilter = getServicePrincipleFilter(serverName);

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_PASSWORD });

    try {
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter,
                searchControls);
        // here we assume only one user
        while (namingEnumeration.hasMore()) {

            SearchResult searchResult = namingEnumeration.next();
            Attributes attributes = searchResult.getAttributes();

            Attribute userPassword = attributes.get(LDAPServerManagerConstants.LDAP_PASSWORD);

            NamingEnumeration passwords = userPassword.getAll();

            String passwordHashMethod = null;
            if (passwords.hasMore()) {
                byte[] byteArray = (byte[]) passwords.next();
                String password = new String(byteArray, StandardCharsets.UTF_8);

                if (password.startsWith("{")) {
                    passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}"));
                }

                return password.equals(getPasswordToStore((String) existingCredentials, passwordHashMethod));
            }
        }

    } catch (NamingException e) {
        log.error("Failed, validating password. Can not access the directory service", e);
        throw new DirectoryServerManagerException(
                "Failed, validating password. " + "Can not access the directory service", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }

    return false;
}

From source file:org.projectforge.business.ldap.LdapDao.java

public T findById(final DirContext ctx, final Object id, final String... organizationalUnits)
        throws NamingException {
    NamingEnumeration<?> results = null;
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final String searchBase = getSearchBase(organizationalUnits);
    final String args = "(&(objectClass=" + getObjectClass() + ")(" + getIdAttrId() + "=" + buildId(id) + "))";
    results = ctx.search(searchBase, args, controls);
    if (results.hasMore() == false) {
        return null;
    }/*from ww  w.  j a  v a  2 s .c  o  m*/
    final SearchResult searchResult = (SearchResult) results.next();
    final String dn = searchResult.getName();
    final Attributes attributes = searchResult.getAttributes();
    if (results.hasMore() == true) {
        log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + id);
    }
    return mapToObject(dn, searchBase, attributes);
}

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

/**
 * Ensure correct credentials.//from w  ww .ja v a 2 s  .c  o m
 */
@SuppressWarnings("unchecked")
public void testCredentials() throws Exception {

    // Create the expected credentials
    final String expectedRaw = "daniel:officefloor:password";
    MessageDigest digest = MessageDigest.getInstance("MD5");
    digest.update(expectedRaw.getBytes(US_ASCII));
    final byte[] expectedCredentials = digest.digest();

    // Obtain the encoded credentials
    final String encodedCredentials = Base64.encodeBase64String(expectedCredentials).trim();
    assertEquals("Incorrect encoded credentials", "msu723GSLovbwuaPnaLcnQ==", encodedCredentials);

    // Mocks
    final NamingEnumeration<SearchResult> searchResults = this.createMock(NamingEnumeration.class);
    final Attributes attributes = this.createMock(Attributes.class);
    final Attribute attribute = this.createMock(Attribute.class);
    final NamingEnumeration<?> userPasswords = this.createMock(NamingEnumeration.class);

    // Objects
    final SearchResult searchResult = new SearchResult("uid=daniel", null, attributes);
    searchResult.setNameInNamespace("uid=daniel,ou=People,dc=officefloor,dc=net");

    // Record
    this.recordReturn(this.context, this.context.search("ou=People,dc=officefloor,dc=net",
            "(&(objectClass=inetOrgPerson)(uid=daniel))", null), searchResults);
    this.recordReturn(searchResults, searchResults.hasMore(), true);
    this.recordReturn(searchResults, searchResults.next(), searchResult);
    this.recordReturn(this.context, this.context.getAttributes("uid=daniel,ou=People,dc=officefloor,dc=net"),
            attributes);
    this.recordReturn(attributes, attributes.get("userPassword"), attribute);
    this.recordReturn(attribute, attribute.getAll(), userPasswords);
    this.recordReturn(userPasswords, userPasswords.hasMore(), true);
    this.recordReturn(userPasswords, userPasswords.next(), "Plain Text Password".getBytes(US_ASCII));
    this.recordReturn(userPasswords, userPasswords.hasMore(), true);
    this.recordReturn(userPasswords, userPasswords.next(), ("{MD5}" + encodedCredentials).getBytes(US_ASCII));

    // Test
    this.replayMockObjects();
    CredentialEntry entry = this.store.retrieveCredentialEntry("daniel", "REALM");
    byte[] actualCredentials = entry.retrieveCredentials();
    this.verifyMockObjects();

    // Validate correct value
    assertEquals("Incorrect credential byte length", expectedCredentials.length, actualCredentials.length);
    for (int i = 0; i < expectedCredentials.length; i++) {
        assertEquals("Incorrect credential byte " + i, expectedCredentials[i], actualCredentials[i]);
    }
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java

protected Set<Privilege> convertLdapGroupsToOrganizationPrivilegesWithUsers(
        NamingEnumeration<SearchResult> pPrivilegesSearchResults)
        throws NamingException, IllegalAccessException {
    Set<Privilege> vResult = new HashSet<Privilege>();
    try {//from w ww.  j av a 2  s .co m
        Privilege vOrgPrivilege;
        // construct privileges
        while (pPrivilegesSearchResults.hasMore()) {
            if ((vOrgPrivilege = this.convertLdapGroupToOrgPriv(pPrivilegesSearchResults.next())) != null) {
                vResult.add(vOrgPrivilege);
            }
        }
    } finally {
        // -- releases this context's resources immediately, instead of
        // waiting for the garbage collector
        if (pPrivilegesSearchResults != null) {
            try {
                pPrivilegesSearchResults.close();
            } catch (NamingException ex) {
            }
        }
    }
    return vResult;
}