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:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

@SuppressWarnings("unchecked")
private List getUserRolesByDn(DirContext dirContext, String userDn, String username)
        throws LoginException, NamingException {
    List<String> roleList = new ArrayList<String>();

    if (dirContext == null || _roleBaseDn == null
            || (_roleMemberAttribute == null && _roleUsernameMemberAttribute == null)
            || _roleObjectClass == null) {
        LOG.warn(/*from w  w w . ja  v a2s.  c o m*/
                "JettyCachingLdapLoginModule: No user roles found: roleBaseDn, roleObjectClass and roleMemberAttribute or roleUsernameMemberAttribute must be specified.");
        addSupplementalRoles(roleList);
        return roleList;
    }

    String[] attrIDs = { _roleNameAttribute };
    SearchControls ctls = new SearchControls();
    ctls.setReturningAttributes(attrIDs);
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = OBJECT_CLASS_FILTER;
    final NamingEnumeration results;

    if (null != _roleUsernameMemberAttribute) {
        Object[] filterArguments = { _roleObjectClass, _roleUsernameMemberAttribute, username };
        results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    } else {
        Object[] filterArguments = { _roleObjectClass, _roleMemberAttribute, userDn };
        results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    }

    while (results.hasMoreElements()) {
        SearchResult result = (SearchResult) results.nextElement();

        Attributes attributes = result.getAttributes();

        if (attributes == null) {
            continue;
        }

        Attribute roleAttribute = attributes.get(_roleNameAttribute);

        if (roleAttribute == null) {
            continue;
        }

        NamingEnumeration roles = roleAttribute.getAll();
        while (roles.hasMore()) {
            if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
                String role = (String) roles.next();
                roleList.add(role.replace(_rolePrefix, ""));
            } else {
                roleList.add((String) roles.next());
            }
        }
    }

    addSupplementalRoles(roleList);

    if (_nestedGroups) {
        roleList = getNestedRoles(dirContext, roleList);
    }

    if (roleList.size() < 1) {
        LOG.warn("JettyCachingLdapLoginModule: User '" + username
                + "' has no role membership; role query configuration may be incorrect");
    } else {
        debug("JettyCachingLdapLoginModule: User '" + username + "' has roles: " + roleList);
    }

    return roleList;
}

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  ww .  j av  a  2 s .c om*/
        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:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

protected Organisation convertSearchResultToOrganization(final SearchResult sr)
        throws ExecutionException, NameNotFoundException {
    if (sr == null) {
        throw new ExecutionException("SearchResult sr == NULL", new NullPointerException());
    }// w ww .  j a  va  2  s .  c o m
    Organisation vOrganisation = null;
    try {
        Attributes attributes = sr.getAttributes();

        Attribute attr;
        String vStr;
        String vOrgName = ((attr = attributes.get(Constants.ldap_ddbOrg_Id)) != null
                ? String.valueOf(attr.get())
                : null);
        String vName = sr.getName();
        String vNameInNamespace = sr.getNameInNamespace();
        // --- EntryDN
        String vEntryDN = ((attr = attributes.get(Constants.ldap_ddb_EntryDN)) != null
                ? String.valueOf(attr.get())
                : "");

        int idx;
        // -- Parent node detections:
        String vParent = null;
        //vParent = sr.getName();
        //LOG.log(Level.INFO, "getNameInNamespace() = '" + sr.getNameInNamespace() + "'");
        //LOG.log(Level.INFO, "getName() = '" + sr.getName() + "'");
        // -- getNameInNamespace() = 'o=99900711,o=00008125,o=00050350,ou=Organizations,dc=de'
        // -- getName() = 'o=99900711,o=00008125,o=00050350'

        //sr.getName(): 'o=00000116', 
        //sr.getNameInNamespace(): 'o=00000116,o=00050350,ou=Organizations,dc=de', 
        //vOrgEntryDN: 'o=00000116,o=00050350,ou=Organizations,dc=de'            
        vParent = sr.getNameInNamespace();
        if ((idx = vParent.indexOf(",ou=")) >= 0) {
            vParent = vParent.substring(0, idx);
        }
        vParent = vParent.replaceAll(Constants.ldap_ddbOrg_Id + "=", "");
        // -- 99900711,00008125,00050350'
        String[] vParents = vParent.split(",");

        if (vParents.length >= 2) {
            vParent = vParents[1];
        } else {
            vParent = null;
        }

        LOG.log(Level.INFO,
                "convertLdapOrganizationToOrganisation: o: '" + vOrgName + "', vParent: '" + vParent
                        + "', sr.getName(): '" + vName + "', sr.getNameInNamespace(): '" + vNameInNamespace
                        + "', vOrgEntryDN: '" + vEntryDN + "', sr.isRelative(): '" + sr.isRelative() + "'");
        /*
         * if ( (vOrgName != null)&&(!vOrgName.isEmpty()) ) { vOrganisation = new Organisation(vOrgName,
         * vDescription, vParent);
         */
        if ((vEntryDN != null) && (!vEntryDN.isEmpty())) {
            vOrganisation = new Organisation(vEntryDN,
                    (attr = sr.getAttributes().get(Constants.ldap_ddbOrg_PID)) != null
                            ? String.valueOf(attr.get())
                            : null);
            // Public-ID: (s.o.)
            // vOrganisation.setOrgPID( (attr = attributes.get(ddbOrg_PID)) != null ? String.valueOf(attr.get()) :
            // "");
            // Parent (s.o.)
            vOrganisation.setOrgParent(vParent);

            // Kurzbeschreibung der Einrichtung
            vOrganisation.setDescription((attr = attributes.get(Constants.ldap_ddbOrg_Description)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // -- Rechtsform
            try {
                vOrganisation.setBusinessCategory(
                        (attr = attributes.get(Constants.ldap_ddbOrg_BusinessCategory)) != null
                                ? ConstEnumOrgSector.valueOf(String.valueOf(attr.get()))
                                : null);
            } catch (IllegalArgumentException ex) {
                LOG.log(Level.WARNING, "Organisation-Sector-Error: {0}", ex.getMessage());
                vOrganisation.setStatus(null);
            }

            // -- Sub-Sectors:
            if ((attr = attributes.get(Constants.ldap_ddbOrg_SubBusinessCategory)) != null) {
                ConstEnumOrgSubSector vSubSector;
                NamingEnumeration<?> allSubSectors = attr.getAll();
                while (allSubSectors.hasMore()) {
                    try {
                        vSubSector = ConstEnumOrgSubSector.valueOf((String) allSubSectors.next());
                        vOrganisation.addSubSectors(vSubSector);
                    } catch (IllegalArgumentException ex) {
                        LOG.log(Level.WARNING, "Organisation-SubSector-Error: {0}", ex.getMessage());
                    }
                }
            }

            // -- Funding Agency
            vOrganisation.setFundingAgency((attr = attributes.get(Constants.ldap_ddbOrg_FundingAgency)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // Name der Einrichtung
            vOrganisation.setDisplayName((attr = attributes.get(Constants.ldap_ddbOrg_DisplayName)) != null
                    ? String.valueOf(attr.get())
                    : "");

            // E-Mail
            vOrganisation.setEmail(
                    (attr = attributes.get(Constants.ldap_ddbOrg_Email)) != null ? String.valueOf(attr.get())
                            : null);
            // Telefonnummer
            vOrganisation.setTel((attr = attributes.get(Constants.ldap_ddbOrg_TelephoneNumber)) != null
                    ? String.valueOf(attr.get())
                    : null);
            // -- FAX
            vOrganisation.setFax((attr = attributes.get(Constants.ldap_ddbOrg_FaxNumber)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // -- PLZ
            vOrganisation.getAddress()
                    .setPostalCode((attr = attributes.get(Constants.ldap_ddbOrg_PostalCode)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- City/Ortsname [l, localityName]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_LocalityName)) != null) {
                vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get()));
            } else if ((attr = attributes.get("l")) != null) {
                vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get()));
            }

            // -- HouseIdentifier
            vOrganisation.getAddress()
                    .setHouseIdentifier((attr = attributes.get(Constants.ldap_ddbOrg_HouseIdentifier)) != null
                            ? String.valueOf(attr.get())
                            : "");
            // -- Strasse
            vOrganisation.getAddress()
                    .setStreet((attr = attributes.get(Constants.ldap_ddbOrg_Street)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- Bundesland [stateOrProvinceName, st]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_StateOrProvinceName)) != null) {
                vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get()));
            } else if ((attr = attributes.get("st")) != null) {
                vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get()));
            }

            // -- Land [countryName, c]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_CountryName)) != null) {
                vOrganisation.getAddress().setCountryName(String.valueOf(attr.get()));
            }
            // -- AddressSuplement
            vOrganisation.getAddress()
                    .setAddressSuplement((attr = attributes.get(Constants.ldap_ddbOrg_AddressSuplement)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- Geokoordinaten
            try {
                vOrganisation.getAddress()
                        .setLatitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLatitude)) != null
                                ? Double.valueOf(String.valueOf(attr.get()))
                                : 0.0);
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "GeoLatitude-Error: {0}", ex.getMessage());
            }
            try {
                vOrganisation.getAddress()
                        .setLongitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLongitude)) != null
                                ? Double.valueOf(String.valueOf(attr.get()))
                                : 0.0);
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "GeoLongitude-Error: {0}", ex.getMessage());
            }
            vOrganisation.getAddress().setLocationDisplayName(
                    (attr = attributes.get(Constants.ldap_ddbOrg_LocationDisplayName)) != null
                            ? String.valueOf(attr.get())
                            : null);

            vOrganisation.setAbbreviation((attr = attributes.get(Constants.ldap_ddbOrg_Abbreviation)) != null
                    ? String.valueOf(attr.get())
                    : null);

            vOrganisation.setLegalStatus((attr = attributes.get(Constants.ldap_ddbOrg_LegalStatus)) != null
                    ? String.valueOf(attr.get())
                    : null);

            if ((attr = attributes.get(Constants.ldap_ddbOrg_URL)) != null) {
                NamingEnumeration<?> allURLs = attr.getAll();
                while (allURLs.hasMore()) {
                    vOrganisation.addURLs((String) allURLs.next());
                }
            }

            vOrganisation.setLogo(
                    (attr = attributes.get(Constants.ldap_ddbOrg_Logo)) != null ? String.valueOf(attr.get())
                            : null);

            // -- org-Status:
            //vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null ? String
            //  .valueOf(attr.get()) : "");
            try {
                vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null
                        ? ConstEnumOrgStatus.valueOf(String.valueOf(attr.get()))
                        : ConstEnumOrgStatus.pending);
            } catch (IllegalArgumentException ex) {
                LOG.log(Level.WARNING, "Organisation-Status-Error: {0}", ex.getMessage());
                vOrganisation.setStatus(null);
            }

            vOrganisation.setCreatedBy((attr = attributes.get(Constants.ldap_ddb_CreatorsName)) != null
                    ? String.valueOf(attr.get())
                    : "");

            try { // createTimestamp-Error: For input string: "20120620142810Z"
                  // 1340205676692 - 20120620152116Z - 2012-06-20-15-21-16Z
                  // vOrganisation.setCreated( (attr = attributes.get(ddbOrg_CreateTimestamp)) != null ?
                  // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1));
                if ((attr = attributes.get(Constants.ldap_ddb_CreateTimestamp)) != null) {
                    vStr = String.valueOf(attr.get());
                    vOrganisation.setCreated(convertLdapDateToLong(vStr));
                }
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "createTimestamp-Error: {0}", ex.getMessage());
            }

            vOrganisation.setModifiedBy((attr = attributes.get(Constants.ldap_ddb_ModifiersName)) != null
                    ? String.valueOf(attr.get())
                    : "");
            try { // modifyTimestamp-Error: For input string: "20120620142810Z"
                  // vOrganisation.setModified( (attr = attributes.get(ddbOrg_ModifyTimestamp)) != null ?
                  // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1));
                if ((attr = attributes.get(Constants.ldap_ddb_ModifyTimestamp)) != null) {
                    vStr = String.valueOf(attr.get());
                    vOrganisation.setModified(convertLdapDateToLong(vStr));
                }
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "modifyTimestamp-Error: {0}", ex.getMessage());
            }

            if ((attr = attributes.get(Constants.ldap_ddbOrg_Properties)) != null
                    && attributes.get(Constants.ldap_ddbOrg_Properties).get() != null) {
                vOrganisation.setProperties(serializer.deserialize((String) attr.get()));
            }

        } else {
            throw new NameNotFoundException();
        }
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NameNotFoundException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw ex;
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, null, ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    }
    return vOrganisation;
}

From source file:org.lsc.jndi.JndiServices.java

/**
 * Retrieve a specific attribute from an object
 * /*from   ww w  .  j  a  v a 2 s .  co m*/
 * @param objectDn
 * @param attribute
 * @return
 * @throws LscServiceException
 */
public List<String> getAttributeValues(String objectDn, String attribute) throws LscServiceException {
    List<String> values = null;
    try {
        // Setup search
        SearchControls sc = new SearchControls();
        sc.setDerefLinkFlag(false);
        sc.setReturningAttributes(new String[] { attribute });
        sc.setSearchScope(SearchControls.OBJECT_SCOPE);
        sc.setReturningObjFlag(true);

        // Retrieve attribute values
        SearchResult res = getEntry(objectDn, "objectClass=*", sc, SearchControls.OBJECT_SCOPE);
        Attribute attr = res.getAttributes().get(attribute);
        if (attr != null) {
            values = new ArrayList<String>();
            NamingEnumeration<?> enu = attr.getAll();
            while (enu.hasMoreElements()) {
                Object val = enu.next();
                values.add(val.toString());
            }
        }
    } catch (NamingException e) {
        throw new LscServiceException(e);
    }
    return values;
}

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);// w w w.  j av a 2  s  . c o  m
    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:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java

@Override
public void doUpdateCredentialByAdmin(String userName, Object newCredential) throws UserStoreException {

    if (!isSSLConnection) {
        logger.warn("Unsecured connection is being used. Password operations will fail");
    }/*w ww.  ja va  2 s.com*/

    DirContext dirContext = this.connectionSource.getContext();
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userListFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER);
    String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
    String searchFilter = "(&" + userListFilter + "(" + userNameAttribute + "="
            + escapeSpecialCharactersForFilter(userName) + "))";
    SearchControls searchControl = new SearchControls();
    String[] returningAttributes = { "CN" };
    searchControl.setReturningAttributes(returningAttributes);
    searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE);

    DirContext subDirContext = null;
    NamingEnumeration<SearchResult> searchResults = null;
    try {
        // search the user with UserNameAttribute and obtain its CN attribute
        searchResults = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControl);
        SearchResult user = null;
        int count = 0;
        while (searchResults.hasMore()) {
            if (count > 0) {
                throw new UserStoreException(
                        "There are more than one result in the user store " + "for user: " + userName);
            }
            user = searchResults.next();
            count++;
        }
        String userCNValue = null;
        if (user.getAttributes() != null) {
            Attribute cnAttribute = user.getAttributes().get("CN");
            if (cnAttribute != null) {
                userCNValue = (String) cnAttribute.get();
            } else {
                throw new UserStoreException("Can not update credential: CN attribute is null");
            }
        }

        ModificationItem[] mods = null;

        if (newCredential != null) {
            mods = new ModificationItem[1];
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE,
                            createUnicodePassword((String) newCredential)));

            subDirContext = (DirContext) dirContext.lookup(searchBase);
            subDirContext.modifyAttributes("CN" + "=" + escapeSpecialCharactersForDN(userCNValue), mods);
        }

    } catch (NamingException e) {
        String error = "Can not access the directory service for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(error, e);
        }
        throw new UserStoreException(error, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(searchResults);
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

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.  ja  v  a  2 s  .  c  o 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   www . j  a v  a 2  s.  com*/
        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();
            }
        }
    }
}

From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java

/**
 *
 *//*from   w  w  w.j  a v a  2 s  . c  om*/
public void doUpdateCredential(String userName, Object newCredential, Object oldCredential)
        throws UserStoreException {

    if (!isSSLConnection) {
        logger.warn("Unsecured connection is being used. Password operations will fail");
    }

    DirContext dirContext = this.connectionSource.getContext();
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userListFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER);
    String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
    // String searchFilter =
    // realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    String searchFilter = "(&" + userListFilter + "(" + userNameAttribute + "="
            + escapeSpecialCharactersForFilter(userName) + "))";

    SearchControls searchControl = new SearchControls();
    String[] returningAttributes = { "CN" };
    searchControl.setReturningAttributes(returningAttributes);
    searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    DirContext subDirContext = null;
    NamingEnumeration<SearchResult> searchResults = null;
    try {
        // search the user with UserNameAttribute and obtain its CN attribute
        searchResults = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControl);
        SearchResult user = null;
        int count = 0;
        while (searchResults.hasMore()) {
            if (count > 0) {
                throw new UserStoreException(
                        "There are more than one result in the user store " + "for user: " + userName);
            }
            user = searchResults.next();
            count++;
        }
        String userCNValue = null;
        if (user.getAttributes() != null) {
            Attribute cnAttribute = user.getAttributes().get("CN");
            if (cnAttribute != null) {
                userCNValue = (String) cnAttribute.get();
            } else {
                throw new UserStoreException("Can not update credential: CN attribute is null");
            }
        }

        ModificationItem[] mods = null;

        // The user tries to change his own password
        if (oldCredential != null && newCredential != null) {
            mods = new ModificationItem[1];
            /*
            * byte[] oldUnicodePassword = createUnicodePassword((String) oldCredential); byte[]
            * newUnicodePassword = createUnicodePassword((String) newCredential);
            */
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE,
                            createUnicodePassword((String) newCredential)));
            /*
             * mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(
             * LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, newUnicodePassword));
             */
        }
        subDirContext = (DirContext) dirContext.lookup(searchBase);
        subDirContext.modifyAttributes("CN" + "=" + escapeSpecialCharactersForDN(userCNValue), mods);

    } catch (NamingException e) {
        String error = "Can not access the directory service for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(error, e);
        }
        throw new UserStoreException(error, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(searchResults);
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }

}

From source file:org.lsc.jndi.JndiServices.java

private void doDeleteChildrenRecursively(String distinguishName) throws NamingException {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    NamingEnumeration<SearchResult> ne = ctx.search(distinguishName, DEFAULT_FILTER, sc);
    while (ne.hasMore()) {
        SearchResult sr = (SearchResult) ne.next();
        String childrenDn = rewriteBase(sr.getName() + "," + distinguishName);
        deleteChildrenRecursively(childrenDn);
    }/*  www  .  ja va2s . c o m*/
    ctx.destroySubcontext(new LdapName(distinguishName));
}