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:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

public Set<OIDs> getAllSubOrgIds(boolean pLicensedOrgs, OIDs pOIDs, int pScopy, AasPrincipal pPerformer)
        throws ExecutionException {
    Set<OIDs> vSetOIDs = new HashSet<OIDs>();
    NamingEnumeration<SearchResult> searchResults = null;
    try {//from  w w w. jav  a 2s.  co  m
        searchResults = getAllSubOrgs(pLicensedOrgs, pOIDs, pScopy,
                new String[] { Constants.ldap_ddbOrg_Id, Constants.ldap_ddbOrg_PID, "+" }, pPerformer);
        SearchResult sr;
        Attribute attr;
        while (searchResults.hasMore()) {
            sr = searchResults.next();
            if ((attr = sr.getAttributes().get(Constants.ldap_ddb_EntryDN)) != null) {
                vSetOIDs.add(new OIDs(String.valueOf(attr.get()),
                        (attr = sr.getAttributes().get(Constants.ldap_ddbOrg_PID)) != null
                                ? String.valueOf(attr.get())
                                : null));
            } else {
                throw new ExecutionException("entryDN = null : OIDs = " + pOIDs, null);
            }
        }
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, "Connection-Error", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, "NamingException", ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        if (searchResults != null) {
            try {
                searchResults.close();
                searchResults = null;
            } catch (NamingException ex) {
            }
        }
    }
    return vSetOIDs;
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java

@SuppressWarnings("unchecked")
protected Object getFieldValue(Attribute attribute, String fieldName, String entryId, boolean fetchReferences)
        throws DirectoryException {

    Field field = schemaFieldMap.get(fieldName);
    Type type = field.getType();//w  w  w. j  a  v a 2 s. c om
    Object defaultValue = field.getDefaultValue();
    String typeName = type.getName();
    if (attribute == null) {
        return defaultValue;
    }
    Object value;
    try {
        value = attribute.get();
    } catch (NamingException e) {
        throw new DirectoryException("Could not fetch value for " + attribute, e);
    }
    if (value == null) {
        return defaultValue;
    }
    String trimmedValue = value.toString().trim();
    if ("string".equals(typeName)) {
        return trimmedValue;
    } else if ("integer".equals(typeName) || "long".equals(typeName)) {
        if ("".equals(trimmedValue)) {
            return defaultValue;
        }
        try {
            return Long.valueOf(trimmedValue);
        } catch (NumberFormatException e) {
            log.error(String.format(
                    "field %s of type %s has non-numeric value found on server: '%s' (ignoring and using default value instead)",
                    fieldName, typeName, trimmedValue));
            return defaultValue;
        }
    } else if (type.isListType()) {
        List<String> parsedItems = new LinkedList<String>();
        NamingEnumeration<Object> values = null;
        try {
            values = (NamingEnumeration<Object>) attribute.getAll();
            while (values.hasMore()) {
                parsedItems.add(values.next().toString().trim());
            }
            return parsedItems;
        } catch (NamingException e) {
            log.error(String.format(
                    "field %s of type %s has non list value found on server: '%s' (ignoring and using default value instead)",
                    fieldName, typeName, values != null ? values.toString() : trimmedValue));
            return defaultValue;
        } finally {
            if (values != null) {
                try {
                    values.close();
                } catch (NamingException e) {
                    log.error(e, e);
                }
            }
        }
    } else if ("date".equals(typeName)) {
        if ("".equals(trimmedValue)) {
            return defaultValue;
        }
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
            dateFormat.setTimeZone(new SimpleTimeZone(0, "Z"));
            Date date = dateFormat.parse(trimmedValue);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            return cal;
        } catch (ParseException e) {
            log.error(String.format(
                    "field %s of type %s has invalid value found on server: '%s' (ignoring and using default value instead)",
                    fieldName, typeName, trimmedValue));
            return defaultValue;
        }
    } else if ("content".equals(typeName)) {
        return Blobs.createBlob((byte[]) value);
    } else {
        throw new DirectoryException("Field type not supported in directories: " + typeName);
    }
}

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

/**
 * Authenticates the user.//from  ww  w . java 2 s.co m
 */
public synchronized void authenticate() throws PortalSecurityException {
    this.isauth = false;
    ILdapServer ldapConn;

    String propFile = ctxProperties.getProperty(LDAP_PROPERTIES_CONNECTION_NAME);
    if (propFile != null && propFile.length() > 0)
        ldapConn = LdapServices.getLdapServer(propFile);
    else
        ldapConn = LdapServices.getDefaultLdapServer();

    String creds = new String(this.myOpaqueCredentials.credentialstring);
    if (this.myPrincipal.UID != null && !this.myPrincipal.UID.trim().equals("")
            && this.myOpaqueCredentials.credentialstring != null && !creds.trim().equals("")) {
        DirContext conn = null;
        NamingEnumeration results = null;
        StringBuffer user = new StringBuffer("(");
        String first_name = null;
        String last_name = null;

        user.append(ldapConn.getUidAttribute()).append("=");
        user.append(this.myPrincipal.UID).append(")");
        if (log.isDebugEnabled())
            log.debug("SimpleLdapSecurityContext: Looking for " + user.toString());

        try {
            conn = ldapConn.getConnection();

            // set up search controls
            SearchControls searchCtls = new SearchControls();
            searchCtls.setReturningAttributes(attributes);
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            // do lookup
            if (conn != null) {
                try {
                    results = conn.search(ldapConn.getBaseDN(), user.toString(), searchCtls);
                    if (results != null) {
                        if (!results.hasMore())
                            log.error("SimpleLdapSecurityContext: user not found , " + this.myPrincipal.UID);
                        while (results != null && results.hasMore()) {
                            SearchResult entry = (SearchResult) results.next();
                            StringBuffer dnBuffer = new StringBuffer();
                            dnBuffer.append(entry.getName()).append(", ");
                            dnBuffer.append(ldapConn.getBaseDN());
                            Attributes attrs = entry.getAttributes();
                            first_name = getAttributeValue(attrs, ATTR_FIRSTNAME);
                            last_name = getAttributeValue(attrs, ATTR_LASTNAME);
                            // re-bind as user
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_PRINCIPAL);
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_CREDENTIALS);
                            conn.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, dnBuffer.toString());
                            conn.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS,
                                    this.myOpaqueCredentials.credentialstring);
                            searchCtls = new SearchControls();
                            searchCtls.setReturningAttributes(new String[0]);
                            searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

                            String attrSearch = "(" + ldapConn.getUidAttribute() + "=*)";
                            log.debug("SimpleLdapSecurityContext: Looking in " + dnBuffer.toString() + " for "
                                    + attrSearch);
                            conn.search(dnBuffer.toString(), attrSearch, searchCtls);

                            this.isauth = true;
                            this.myPrincipal.FullName = first_name + " " + last_name;
                            log.debug("SimpleLdapSecurityContext: User " + this.myPrincipal.UID + " ("
                                    + this.myPrincipal.FullName + ") is authenticated");

                            // Since LDAP is case-insensitive with respect to uid, force
                            // user name to lower case for use by the portal
                            this.myPrincipal.UID = this.myPrincipal.UID.toLowerCase();
                        } // while (results != null && results.hasMore())
                    } else {
                        log.error("SimpleLdapSecurityContext: No such user: " + this.myPrincipal.UID);
                    }
                } catch (AuthenticationException ae) {
                    log.info("SimpleLdapSecurityContext: Password invalid for user: " + this.myPrincipal.UID);
                } catch (Exception e) {
                    log.error("SimpleLdapSecurityContext: LDAP Error with user: " + this.myPrincipal.UID + "; ",
                            e);
                    throw new PortalSecurityException("SimpleLdapSecurityContext: LDAP Error" + e
                            + " with user: " + this.myPrincipal.UID);
                } finally {
                    ldapConn.releaseConnection(conn);
                }
            } else {
                log.error("LDAP Server Connection unavalable");
            }
        } catch (final NamingException ne) {
            log.error("Error geting connection to LDAP server.", ne);
        }
    } else {
        log.error("Principal or OpaqueCredentials not initialized prior to authenticate");
    }
    // Ok...we are now ready to authenticate all of our subcontexts.
    super.authenticate();
    return;
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java

protected DocumentModelList ldapResultsToDocumentModels(NamingEnumeration<SearchResult> results,
        boolean fetchReferences) throws DirectoryException, NamingException {
    DocumentModelListImpl list = new DocumentModelListImpl();
    try {//from  ww w .j  ava  2s . c o  m
        while (results.hasMore()) {
            SearchResult result = results.next();
            DocumentModel entry = ldapResultToDocumentModel(result, null, fetchReferences);
            if (entry != null) {
                list.add(entry);
            }
        }
    } catch (SizeLimitExceededException e) {
        if (list.isEmpty()) {
            // the server did no send back the truncated results set,
            // re-throw the exception to that the user interface can display
            // the error message
            throw e;
        }
        // mark the collect results as a truncated result list
        log.debug("SizeLimitExceededException caught," + " return truncated results. Original message: "
                + e.getMessage() + " explanation: " + e.getExplanation());
        list.setTotalSize(-2);
    } finally {
        results.close();
    }
    log.debug("LDAP search returned " + list.size() + " results");
    return list;
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

private ConcurrentHashMap<String, List<String>> buildRoleMemberOfMap(DirContext dirContext) {
    Object[] filterArguments = { _roleObjectClass };
    SearchControls ctls = new SearchControls();
    ctls.setDerefLinkFlag(true);//from   w ww.  j av  a2s .c  om
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    ConcurrentHashMap<String, List<String>> roleMemberOfMap = new ConcurrentHashMap<String, List<String>>();

    try {
        NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, _roleMemberFilter, ctls);
        while (results.hasMoreElements()) {
            SearchResult result = results.nextElement();
            Attributes attributes = result.getAttributes();

            if (attributes == null) {
                continue;
            }

            Attribute roleAttribute = attributes.get(_roleNameAttribute);
            Attribute memberAttribute = attributes.get(_roleMemberAttribute);

            if (roleAttribute == null || memberAttribute == null) {
                continue;
            }

            NamingEnumeration role = roleAttribute.getAll();
            NamingEnumeration members = memberAttribute.getAll();

            if (!role.hasMore() || !members.hasMore()) {
                continue;
            }

            String roleName = (String) role.next();
            if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
                roleName = roleName.replace(_rolePrefix, "");
            }

            while (members.hasMore()) {
                String member = (String) members.next();
                Matcher roleMatcher = rolePattern.matcher(member);
                if (!roleMatcher.find()) {
                    continue;
                }
                String roleMember = roleMatcher.group(1);
                List<String> memberOf;
                if (roleMemberOfMap.containsKey(roleMember)) {
                    memberOf = roleMemberOfMap.get(roleMember);
                } else {
                    memberOf = new ArrayList<String>();
                }

                memberOf.add(roleName);

                roleMemberOfMap.put(roleMember, memberOf);
            }

        }
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return roleMemberOfMap;
}

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

/**
 * get attribute values of given resource and attributes.
 * //from  ww  w.  j  a v a 2s  .com
 * @param scope
 *            scope
 * @param id
 *            id of resource
 * @param attributeName
 *            attribute-name to retrieve
 * 
 * @return String attribute value
 * @throws NamingException
 * @throws IllegalAccessException
 */
public Map<String, String> getResourceAttributes(Scope scope, String id, String[] attributeNames)
        throws NamingException, IllegalAccessException {
    Map<String, String> returnMap = new HashMap<String, String>();
    String baseDn = null;
    String filter = getIdFilter(scope, id);
    int levelScope = 0;
    InitialLdapContext ctx = null;
    NamingEnumeration<SearchResult> results = null;
    if (scope == Scope.ORGANIZATION) {
        baseDn = LDAPConnector.getSingletonInstance().getInstitutionBaseDN();
        levelScope = SearchControls.SUBTREE_SCOPE;
    } else if (scope == Scope.PERSON) {
        baseDn = LDAPConnector.getSingletonInstance().getPersonBaseDN();
        levelScope = SearchControls.ONELEVEL_SCOPE;
    }
    try {
        ctx = LDAPConnector.getSingletonInstance().takeCtx();
        results = query(ctx, baseDn, filter, attributeNames, levelScope);
        if (results.hasMore()) {
            SearchResult searchResult = results.next();
            if (results.hasMore()) {
                throw new IllegalAccessException("found more than one object with id=" + id);
            }
            Attributes attributes = searchResult.getAttributes();
            for (int i = 0; i < attributeNames.length; i++) {
                Attribute attribute = attributes.get(attributeNames[i]);
                if (attribute == null) {
                    returnMap.put(attributeNames[i], (String) null);
                } else {
                    returnMap.put(attributeNames[i], (String) attribute.get());
                }
            }
            return returnMap;
        } else {
            throw new NameNotFoundException("id not found");
        }

    } finally {
        if (ctx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(ctx);
            } catch (IllegalAccessException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }
        if (results != null) {
            try {
                results.close();
            } catch (NamingException e) {
                LOG.log(Level.WARNING, null, e);
            }
        }
    }
}

From source file:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * This will perform an LDAP compare operation with the supplied filter and
 * dn. Note that to perform a <b>real</b> LDAP compare operation, your filter
 * must be of the form '(name=value)'. Any other filter expression will result
 * in a regular object level search operation. In either case the desired
 * result is achieved, but the underlying LDAP invocation is different.
 *
 * @param  dn  <code>String</code> name to compare
 * @param  filter  <code>String</code> expression to use for compare
 * @param  filterArgs  <code>Object[]</code> to substitute for variables in
 * the filter//w w  w .  ja v  a 2 s.  co m
 *
 * @return  <code>boolean</code> - result of compare operation
 *
 * @throws  NamingException  if the LDAP returns an error
 */
protected boolean compare(final String dn, final String filter, final Object[] filterArgs)
        throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Compare with the following parameters:");
        this.logger.debug("  dn = " + dn);
        this.logger.debug("  filter = " + filter);
        this.logger.debug("  filterArgs = " + Arrays.toString(filterArgs));
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    boolean success = false;
    LdapContext ctx = null;
    NamingEnumeration<SearchResult> en = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                ctx = this.getContext();
                en = ctx.search(dn, filter, filterArgs, LdapConfig.getCompareSearchControls());

                if (en.hasMore()) {
                    success = true;
                }

                break;
            } catch (NamingException e) {
                this.operationRetry(ctx, e, i);
            }
        }
    } finally {
        if (en != null) {
            en.close();
        }
        if (ctx != null) {
            ctx.close();
        }
    }
    return success;
}

From source file:org.apache.syncope.fit.core.GroupITCase.java

@Test
public void issueSYNCOPE632() {
    DerSchemaTO orig = schemaService.read(SchemaType.DERIVED, "displayProperty");
    DerSchemaTO modified = SerializationUtils.clone(orig);
    modified.setExpression("icon + '_' + show");

    GroupTO groupTO = GroupITCase.getSampleTO("lastGroup");
    try {/*from  w  w  w .  ja  v  a  2s.  c  o m*/
        schemaService.update(SchemaType.DERIVED, modified);

        // 0. create group
        groupTO.getPlainAttrs().add(attrTO("icon", "anIcon"));
        groupTO.getPlainAttrs().add(attrTO("show", "true"));
        groupTO.getResources().clear();

        groupTO = createGroup(groupTO).getEntity();
        assertNotNull(groupTO);

        // 1. create new LDAP resource having ConnObjectKey mapped to a derived attribute
        ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP);
        newLDAP.setKey("new-ldap");
        newLDAP.setPropagationPriority(0);

        for (ProvisionTO provision : newLDAP.getProvisions()) {
            provision.getVirSchemas().clear();
        }

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

        ItemTO connObjectKey = mapping.getConnObjectKeyItem();
        connObjectKey.setIntAttrName("displayProperty");
        connObjectKey.setPurpose(MappingPurpose.PROPAGATION);
        mapping.setConnObjectKeyItem(connObjectKey);
        mapping.setConnObjectLink("'cn=' + displayProperty + ',ou=groups,o=isp'");

        ItemTO description = new ItemTO();
        description.setIntAttrName("key");
        description.setExtAttrName("description");
        description.setPurpose(MappingPurpose.PROPAGATION);
        mapping.add(description);

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

        // 2. update group and give the resource created above
        GroupPatch patch = new GroupPatch();
        patch.setKey(groupTO.getKey());
        patch.getResources().add(
                new StringPatchItem.Builder().operation(PatchOperation.ADD_REPLACE).value("new-ldap").build());

        groupTO = updateGroup(patch).getEntity();
        assertNotNull(groupTO);

        // 3. update the group
        GroupPatch groupPatch = new GroupPatch();
        groupPatch.setKey(groupTO.getKey());
        groupPatch.getPlainAttrs().add(attrAddReplacePatch("icon", "anotherIcon"));

        groupTO = updateGroup(groupPatch).getEntity();
        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 {
        schemaService.update(SchemaType.DERIVED, orig);
        if (groupTO.getKey() != null) {
            groupService.delete(groupTO.getKey());
        }
        resourceService.delete("new-ldap");
    }
}

From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public List<String> getAllGroups(DirContext context) throws MappingException {

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {/*  www  . j  av a2s  . co  m*/

        SearchControls searchControls = new SearchControls();

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

        String filter = "objectClass=" + getLdapGroupClass();

        if (!StringUtils.isEmpty(this.groupFilter)) {
            filter = "(&(" + filter + ")(" + this.groupFilter + "))";
        }

        namingEnumeration = context.search(getGroupsDn(), filter, searchControls);

        List<String> allGroups = new ArrayList<String>();

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();

            String groupName = searchResult.getName();
            // cn=blabla we only want bla bla
            groupName = StringUtils.substringAfter(groupName, "=");

            log.debug("found groupName: '{}", groupName);

            allGroups.add(groupName);

        }

        return allGroups;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    }

    finally {
        close(namingEnumeration);
    }
}

From source file:org.apache.zeppelin.realm.LdapRealm.java

private void addRoleIfMember(final String userDn, final SearchResult group, final Set<String> roleNames,
        final Set<String> groupNames, final LdapContextFactory ldapContextFactory) throws NamingException {
    NamingEnumeration<? extends Attribute> attributeEnum = null;
    NamingEnumeration<?> ne = null;
    try {/*from  w ww  . java2s .  c  om*/
        LdapName userLdapDn = new LdapName(userDn);
        Attribute attribute = group.getAttributes().get(getGroupIdAttribute());
        String groupName = attribute.get().toString();

        attributeEnum = group.getAttributes().getAll();
        while (attributeEnum.hasMore()) {
            final Attribute attr = attributeEnum.next();
            if (!memberAttribute.equalsIgnoreCase(attr.getID())) {
                continue;
            }
            ne = attr.getAll();
            while (ne.hasMore()) {
                String attrValue = ne.next().toString();
                if (memberAttribute.equalsIgnoreCase(MEMBER_URL)) {
                    boolean dynamicGroupMember = isUserMemberOfDynamicGroup(userLdapDn, attrValue,
                            ldapContextFactory);
                    if (dynamicGroupMember) {
                        groupNames.add(groupName);
                        String roleName = roleNameFor(groupName);
                        if (roleName != null) {
                            roleNames.add(roleName);
                        } else {
                            roleNames.add(groupName);
                        }
                    }
                } else {
                    // posix groups' members don' include the entire dn
                    if (groupObjectClass.equalsIgnoreCase(POSIX_GROUP)) {
                        attrValue = memberDn(attrValue);
                    }
                    if (userLdapDn.equals(new LdapName(attrValue))) {
                        groupNames.add(groupName);
                        String roleName = roleNameFor(groupName);
                        if (roleName != null) {
                            roleNames.add(roleName);
                        } else {
                            roleNames.add(groupName);
                        }
                        break;
                    }
                }
            }
        }
    } finally {
        try {
            if (attributeEnum != null) {
                attributeEnum.close();
            }
        } finally {
            if (ne != null) {
                ne.close();
            }
        }
    }
}