Example usage for javax.naming.directory SearchResult getNameInNamespace

List of usage examples for javax.naming.directory SearchResult getNameInNamespace

Introduction

In this page you can find the example usage for javax.naming.directory SearchResult getNameInNamespace.

Prototype

public String getNameInNamespace() 

Source Link

Document

Retrieves the full name of this binding.

Usage

From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java

private void execute() throws Exception {
    // Connecting to server and retreiving entries
    NamingEnumeration entries = connectToServerAndGetEntries();

    // Creating destination file
    File destionationFile = new File(ldifFileName);

    // Deleting the destination file if it already exists
    if (destionationFile.exists()) {
        destionationFile.delete();/* w ww .j  av a2  s  . co  m*/
    }

    // Creating the writer to generate the LDIF file
    FileWriter fw = new FileWriter(ldifFileName, true);

    BufferedWriter writer = new BufferedWriter(fw);
    OtcLdifComposerImpl composer = new OtcLdifComposerImpl();
    MultiValueMap map = new MultiValueMap();
    //      MultiMap map = new MultiMap() {
    //         // FIXME Stop forking commons-collections.
    //         private final MultiValueMap map = new MultiValueMap();
    //
    //         public Object remove(Object arg0, Object arg1) {
    //            return map.remove(arg0, arg1);
    //         }
    //
    //         public int size() {
    //            return map.size();
    //         }
    //
    //         public Object get(Object arg0) {
    //            return map.get(arg0);
    //         }
    //
    //         public boolean containsValue(Object arg0) {
    //            return map.containsValue(arg0);
    //         }
    //
    //         public Object put(Object arg0, Object arg1) {
    //            return map.put(arg0, arg1);
    //         }
    //
    //         public Object remove(Object arg0) {
    //            return map.remove(arg0);
    //         }
    //
    //         public Collection values() {
    //            return map.values();
    //         }
    //
    //         public boolean isEmpty() {
    //            return map.isEmpty();
    //         }
    //
    //         public boolean containsKey(Object key) {
    //            return map.containsKey(key);
    //         }
    //
    //         public void putAll(Map arg0) {
    //            map.putAll(arg0);
    //         }
    //
    //         public void clear() {
    //            map.clear();
    //         }
    //
    //         public Set keySet() {
    //            return map.keySet();
    //         }
    //
    //         public Set entrySet() {
    //            return map.entrySet();
    //         }
    //      };

    int entriesCounter = 1;
    long t0 = System.currentTimeMillis();

    while (entries.hasMoreElements()) {
        SearchResult sr = (SearchResult) entries.nextElement();
        Attributes attributes = sr.getAttributes();
        NamingEnumeration attributesEnumeration = attributes.getAll();

        map.clear();

        while (attributesEnumeration.hasMoreElements()) {
            Attribute attr = (Attribute) attributesEnumeration.nextElement();
            NamingEnumeration e2 = null;

            e2 = attr.getAll();

            while (e2.hasMoreElements()) {
                Object value = e2.nextElement();
                map.put(attr.getID(), value);
            }
        }

        // Writing entry in the file
        writer.write("dn: " + sr.getNameInNamespace() + "\n");
        writer.write(composer.compose(map) + "\n");

        notifyEntryWrittenListener(sr.getNameInNamespace());
        entriesCounter++;

        if (entriesCounter % 10 == 0) {
            notifyOutputListener(new Character('.'));
        }

        if (entriesCounter % 500 == 0) {
            notifyOutputListener("" + entriesCounter);
        }
    }

    writer.flush();
    writer.close();
    fw.close();

    long t1 = System.currentTimeMillis();

    notifyOutputListener("Done!");
    notifyOutputListener(entriesCounter + " entries exported in " + ((t1 - t0) / 1000) + " seconds");
}

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

@Override
public void deleteEntry(String id) {
    checkPermission(SecurityConstants.WRITE);
    checkDeleteConstraints(id);/*from  w ww .  j  a v  a  2  s  . co  m*/
    try {
        for (String fieldName : schemaFieldMap.keySet()) {
            if (getDirectory().isReference(fieldName)) {
                List<Reference> references = directory.getReferences(fieldName);
                if (references.size() > 1) {
                    // not supported
                } else {
                    Reference reference = references.get(0);
                    reference.removeLinksForSource(id);
                }
            }
        }
        SearchResult result = getLdapEntry(id);

        if (log.isDebugEnabled()) {
            log.debug(String.format("LDAPSession.deleteEntry(%s): LDAP destroySubcontext dn='%s' [%s]", id,
                    result.getNameInNamespace(), this));
        }
        dirContext.destroySubcontext(result.getNameInNamespace());
    } catch (NamingException e) {
        handleException(e, "deleteEntry failed for: " + id);
    }
    getDirectory().invalidateCaches();
}

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

/**
 * Store new links using the LDAP staticAttributeId strategy.
 *
 * @see org.nuxeo.ecm.directory.Reference#addLinks(String, List)
 *//*from ww w  . j a  v a2 s.  c  o m*/
@Override
public void addLinks(String sourceId, List<String> targetIds) throws DirectoryException {

    if (targetIds.isEmpty()) {
        // optim: nothing to do, return silently without further creating
        // session instances
        return;
    }

    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    if (attributeId == null) {
        if (log.isTraceEnabled()) {
            log.trace(String.format("trying to edit a non-static reference from %s in directory %s: ignoring",
                    sourceId, ldapSourceDirectory.getName()));
        }
        return;
    }
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        // fetch the entry to be able to run the security policy
        // implemented in an entry adaptor
        DocumentModel sourceEntry = sourceSession.getEntry(sourceId, false);
        if (sourceEntry == null) {
            throw new DirectoryException(String.format("could not add links from unexisting %s in directory %s",
                    sourceId, ldapSourceDirectory.getName()));
        }
        if (!BaseSession.isReadOnlyEntry(sourceEntry)) {
            SearchResult ldapEntry = sourceSession.getLdapEntry(sourceId);

            String sourceDn = ldapEntry.getNameInNamespace();
            Attribute storedAttr = ldapEntry.getAttributes().get(attributeId);
            String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
            Attribute attrToAdd = new BasicAttribute(attributeId);
            for (String targetId : targetIds) {
                if (staticAttributeIdIsDn) {
                    // TODO optim: avoid LDAP search request when targetDn
                    // can be forged client side (rdnAttribute = idAttribute and scope is onelevel)
                    ldapEntry = targetSession.getLdapEntry(targetId);
                    if (ldapEntry == null) {
                        log.warn(String.format(
                                "entry '%s' in directory '%s' not found: could not add link from '%s' in directory '%s' for '%s'",
                                targetId, ldapTargetDirectory.getName(), sourceId,
                                ldapSourceDirectory.getName(), this));
                        continue;
                    }
                    String dn = ldapEntry.getNameInNamespace();
                    if (storedAttr == null || !storedAttr.contains(dn)) {
                        attrToAdd.add(dn);
                    }
                } else {
                    if (storedAttr == null || !storedAttr.contains(targetId)) {
                        attrToAdd.add(targetId);
                    }
                }
            }
            if (attrToAdd.size() > 0) {
                try {
                    // do the LDAP request to store missing dns
                    Attributes attrsToAdd = new BasicAttributes();
                    attrsToAdd.put(attrToAdd);

                    if (log.isDebugEnabled()) {
                        log.debug(String.format(
                                "LDAPReference.addLinks(%s, [%s]): LDAP modifyAttributes dn='%s' "
                                        + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                sourceId, StringUtils.join(targetIds, ", "), sourceDn, attrsToAdd, this));
                    }
                    sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.ADD_ATTRIBUTE, attrsToAdd);

                    // robustly clean any existing empty marker now that we are sure that the list in not empty
                    if (storedAttr.contains(emptyRefMarker)) {
                        Attributes cleanAttrs = new BasicAttributes(attributeId, emptyRefMarker);

                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.addLinks(%s, [%s]): LDAP modifyAttributes dn='%s'"
                                            + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    sourceId, StringUtils.join(targetIds, ", "), sourceDn, cleanAttrs, this));
                        }
                        sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE,
                                cleanAttrs);
                    }
                } catch (SchemaViolationException e) {
                    if (isDynamic()) {
                        // we are editing an entry that has no static part
                        log.warn(String.format("cannot update dynamic reference in field %s for source %s",
                                getFieldName(), sourceId));
                    } else {
                        // this is a real schema configuration problem,
                        // wrap up the exception
                        throw new DirectoryException(e);
                    }
                }
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("addLinks failed: " + e.getMessage(), e);
    }
}

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

@Override
@SuppressWarnings("unchecked")
public void updateEntry(DocumentModel docModel) {
    checkPermission(SecurityConstants.WRITE);
    List<String> updateList = new ArrayList<String>();
    List<String> referenceFieldList = new LinkedList<String>();

    try {//from w w w  . j av a  2 s .  c o m
        for (String fieldName : schemaFieldMap.keySet()) {
            if (!docModel.getPropertyObject(schemaName, fieldName).isDirty()) {
                continue;
            }
            if (getDirectory().isReference(fieldName)) {
                referenceFieldList.add(fieldName);
            } else {
                updateList.add(fieldName);
            }
        }

        if (!isReadOnlyEntry(docModel) && !updateList.isEmpty()) {
            Attributes attrs = new BasicAttributes();
            SearchResult ldapEntry = getLdapEntry(docModel.getId());
            if (ldapEntry == null) {
                throw new DirectoryException(docModel.getId() + " not found");
            }
            Attributes oldattrs = ldapEntry.getAttributes();
            String dn = ldapEntry.getNameInNamespace();
            Attributes attrsToDel = new BasicAttributes();
            for (String f : updateList) {
                Object value = docModel.getProperty(schemaName, f);
                String backendField = getDirectory().getFieldMapper().getBackendField(f);
                if (LDAPDirectory.DN_SPECIAL_ATTRIBUTE_KEY.equals(backendField)) {
                    // skip special LDAP DN field that is readonly
                    log.warn(String.format("field %s is mapped to read only DN field: ignored", f));
                    continue;
                }
                if (value == null || value.equals("")) {
                    Attribute objectClasses = oldattrs.get("objectClass");
                    Attribute attr;
                    if (getMandatoryAttributes(objectClasses).contains(backendField)) {
                        attr = new BasicAttribute(backendField);
                        // XXX: this might fail if the mandatory attribute
                        // is typed integer for instance
                        attr.add(" ");
                        attrs.put(attr);
                    } else if (oldattrs.get(backendField) != null) {
                        attr = new BasicAttribute(backendField);
                        attr.add(oldattrs.get(backendField).get());
                        attrsToDel.put(attr);
                    }
                } else if (f.equals(getPasswordField())) {
                    // The password has been updated, it has to be encrypted
                    Attribute attr = new BasicAttribute(backendField);
                    attr.add(PasswordHelper.hashPassword((String) value, passwordHashAlgorithm));
                    attrs.put(attr);
                } else {
                    attrs.put(getAttributeValue(f, value));
                }
            }

            if (log.isDebugEnabled()) {
                log.debug(String.format("LDAPSession.updateEntry(%s): LDAP modifyAttributes dn='%s' "
                        + "mod_op='REMOVE_ATTRIBUTE' attr='%s' [%s]", docModel, dn, attrsToDel, this));
            }
            dirContext.modifyAttributes(dn, DirContext.REMOVE_ATTRIBUTE, attrsToDel);

            if (log.isDebugEnabled()) {
                log.debug(String.format("LDAPSession.updateEntry(%s): LDAP modifyAttributes dn='%s' "
                        + "mod_op='REPLACE_ATTRIBUTE' attr='%s' [%s]", docModel, dn, attrs, this));
            }
            dirContext.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, attrs);
        }

        // update reference fields
        for (String referenceFieldName : referenceFieldList) {
            List<Reference> references = directory.getReferences(referenceFieldName);
            if (references.size() > 1) {
                // not supported
            } else {
                Reference reference = references.get(0);
                List<String> targetIds = (List<String>) docModel.getProperty(schemaName, referenceFieldName);
                reference.setTargetIdsForSource(docModel.getId(), targetIds);
            }
        }
    } catch (NamingException e) {
        handleException(e, "updateEntry failed:");
    }
    getDirectory().invalidateCaches();
}

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

@Override
public boolean authenticate(String username, String password) throws DirectoryException {

    if (password == null || "".equals(password.trim())) {
        // never use anonymous bind as a way to authenticate a user in
        // Nuxeo EP
        return false;
    }/*from ww w . j a  v  a  2  s  . c o  m*/

    // lookup the user: fetch its dn
    SearchResult entry;
    try {
        entry = getLdapEntry(username);
    } catch (NamingException e) {
        throw new DirectoryException("failed to fetch the ldap entry for " + username, e);
    }
    if (entry == null) {
        // no such user => authentication failed
        return false;
    }
    String dn = entry.getNameInNamespace();
    Properties env = (Properties) getDirectory().getContextProperties().clone();
    env.put(Context.SECURITY_PRINCIPAL, dn);
    env.put(Context.SECURITY_CREDENTIALS, password);

    InitialLdapContext authenticationDirContext = null;
    try {
        // creating a context does a bind
        log.debug(String.format("LDAP bind dn='%s'", dn));
        // noinspection ResultOfObjectAllocationIgnored
        authenticationDirContext = new InitialLdapContext(env, null);
        // force reconnection to prevent from using a previous connection
        // with an obsolete password (after an user has changed his
        // password)
        authenticationDirContext.reconnect(null);
        log.debug("Bind succeeded, authentication ok");
        return true;
    } catch (NamingException e) {
        log.debug("Bind failed: " + e.getMessage());
        // authentication failed
        return false;
    } finally {
        try {
            if (authenticationDirContext != null) {
                authenticationDirContext.close();
            }
        } catch (NamingException e) {
            log.error("Error closing authentication context when biding dn " + dn, e);
            return false;
        }
    }
}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java

protected void importFromLDAPByUser(LDAPImportContext ldapImportContext) throws Exception {

    byte[] cookie = new byte[0];

    while (cookie != null) {
        List<SearchResult> searchResults = new ArrayList<>();

        Properties userMappings = ldapImportContext.getUserMappings();

        String userMappingsScreenName = GetterUtil.getString(userMappings.getProperty("screenName"));

        userMappingsScreenName = StringUtil.toLowerCase(userMappingsScreenName);

        cookie = _portalLDAP.getUsers(ldapImportContext.getLdapServerId(), ldapImportContext.getCompanyId(),
                ldapImportContext.getLdapContext(), cookie, 0, new String[] { userMappingsScreenName },
                searchResults);//from  w ww .  j  a  va  2 s. co m

        for (SearchResult searchResult : searchResults) {
            try {
                String fullUserDN = searchResult.getNameInNamespace();

                if (ldapImportContext.containsImportedUser(fullUserDN)) {
                    continue;
                }

                Attributes userAttributes = _portalLDAP.getUserAttributes(ldapImportContext.getLdapServerId(),
                        ldapImportContext.getCompanyId(), ldapImportContext.getLdapContext(), fullUserDN);

                User user = importUser(ldapImportContext, fullUserDN, userAttributes, null);

                importGroups(ldapImportContext, userAttributes, user);
            } catch (GroupFriendlyURLException gfurle) {
                int type = gfurle.getType();

                if (type == GroupFriendlyURLException.DUPLICATE) {
                    _log.error("Unable to import user " + searchResult
                            + " because of a duplicate group friendly URL", gfurle);
                } else {
                    _log.error("Unable to import user " + searchResult, gfurle);
                }
            } catch (Exception e) {
                _log.error("Unable to import user " + searchResult, e);
            }
        }
    }
}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java

protected void importGroups(LDAPImportContext ldapImportContext, Attributes userAttributes, User user)
        throws Exception {

    Properties groupMappings = ldapImportContext.getGroupMappings();

    String groupMappingsUser = groupMappings.getProperty("user");

    Set<Long> newUserGroupIds = new LinkedHashSet<>();

    LDAPServerConfiguration ldapServerConfiguration = _ldapServerConfigurationProvider
            .getConfiguration(ldapImportContext.getCompanyId(), ldapImportContext.getLdapServerId());

    if (Validator.isNotNull(groupMappingsUser) && ldapServerConfiguration.groupSearchFilterEnabled()) {

        String baseDN = ldapServerConfiguration.baseDN();

        StringBundler sb = new StringBundler(9);

        sb.append(StringPool.OPEN_PARENTHESIS);
        sb.append(StringPool.AMPERSAND);

        String groupSearchFilter = ldapServerConfiguration.groupSearchFilter();

        LDAPUtil.validateFilter(groupSearchFilter, "LDAPServerConfiguration.groupSearchFilter");

        sb.append(groupSearchFilter);// ww  w. j  av a  2s.c  o  m

        sb.append(StringPool.OPEN_PARENTHESIS);
        sb.append(groupMappingsUser);
        sb.append(StringPool.EQUAL);

        Binding binding = _portalLDAP.getUser(ldapImportContext.getLdapServerId(),
                ldapImportContext.getCompanyId(), user.getScreenName(), user.getEmailAddress());

        String fullUserDN = binding.getNameInNamespace();

        sb.append(escapeValue(fullUserDN));

        sb.append(StringPool.CLOSE_PARENTHESIS);
        sb.append(StringPool.CLOSE_PARENTHESIS);

        byte[] cookie = new byte[0];

        while (cookie != null) {
            List<SearchResult> searchResults = new ArrayList<>();

            String groupMappingsGroupName = GetterUtil.getString(groupMappings.getProperty("groupName"));

            groupMappingsGroupName = StringUtil.toLowerCase(groupMappingsGroupName);

            cookie = _portalLDAP.searchLDAP(ldapImportContext.getCompanyId(),
                    ldapImportContext.getLdapContext(), cookie, 0, baseDN, sb.toString(),
                    new String[] { groupMappingsGroupName }, searchResults);

            for (SearchResult searchResult : searchResults) {
                String fullGroupDN = searchResult.getNameInNamespace();

                newUserGroupIds = importGroup(ldapImportContext, fullGroupDN, user, newUserGroupIds);
            }
        }
    } else {
        Properties userMappings = ldapImportContext.getUserMappings();

        String userMappingsGroup = userMappings.getProperty("group");

        if (Validator.isNull(userMappingsGroup)) {
            if (_log.isInfoEnabled()) {
                _log.info("Skipping group import because no mappings for LDAP "
                        + "groups were specified in user mappings " + userMappings);
            }

            return;
        }

        Attribute userGroupAttribute = userAttributes.get(userMappingsGroup);

        if (userGroupAttribute == null) {
            return;
        }

        for (int i = 0; i < userGroupAttribute.size(); i++) {
            String fullGroupDN = (String) userGroupAttribute.get(i);

            newUserGroupIds = importGroup(ldapImportContext, fullGroupDN, user, newUserGroupIds);
        }
    }

    addUserGroupsNotAddedByLDAPImport(user.getUserId(), newUserGroupIds);

    Set<Long> oldUserGroupIds = new LinkedHashSet<>();

    List<UserGroup> oldUserGroups = _userGroupLocalService.getUserUserGroups(user.getUserId());

    for (UserGroup oldUserGroup : oldUserGroups) {
        oldUserGroupIds.add(oldUserGroup.getUserGroupId());
    }

    if (!oldUserGroupIds.equals(newUserGroupIds)) {
        long[] userGroupIds = ArrayUtil.toLongArray(newUserGroupIds);

        _userGroupLocalService.setUserUserGroups(user.getUserId(), userGroupIds);
    }
}

From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

private NodeDescription mapToNode(Map<String, String> attributeMapping, Map<String, String> attributeDefaults,
        SearchResult result) throws NamingException {
    NodeDescription nodeDescription = new NodeDescription(result.getNameInNamespace());
    Attributes ldapAttributes = result.getAttributes();

    // Parse the timestamp
    Attribute modifyTimestamp = ldapAttributes.get(this.modifyTimestampAttributeName);
    if (modifyTimestamp != null) {
        try {/*  w  w  w .j a va2 s .  c  o m*/
            nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString()));
        } catch (ParseException e) {
            throw new AlfrescoRuntimeException("Failed to parse timestamp.", e);
        }
    }

    // Apply the mapped attributes
    PropertyMap properties = nodeDescription.getProperties();
    for (String key : attributeMapping.keySet()) {
        QName keyQName = QName.createQName(key, this.namespaceService);

        // cater for null
        String attributeName = attributeMapping.get(key);
        if (attributeName != null) {
            Attribute attribute = ldapAttributes.get(attributeName);
            if (attribute != null) {
                String value = (String) attribute.get(0);
                if (value != null) {
                    properties.put(keyQName, value);
                }
            } else {
                String defaultValue = attributeDefaults.get(key);
                if (defaultValue != null) {
                    properties.put(keyQName, defaultValue);
                }
            }
        } else {
            String defaultValue = attributeDefaults.get(key);
            if (defaultValue != null) {
                properties.put(keyQName, defaultValue);
            }
        }
    }
    return nodeDescription;
}

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

private Privilege convertLdapGroupToOrgPriv(SearchResult sr) throws NamingException, IllegalAccessException {
    Privilege vOrgPrivilege = null;//from w w w.j ava2 s  .  com
    String vCnPrivileg = null, vPrivEntryDN = null, vOrgEntryDN = null;
    PrivilegeEnum vPrivilege;
    Attribute vAttr;
    String vMemberRef;
    String[] vStrs;
    if (sr != null) {
        try {
            // -- Beispiel fr entryDN:
            // Organisationeles Privileg:
            // cn=ddb_ingest,o=99900189,o=00001475,dc=ddb,dc=iais,dc=fraunhofer,dc=de
            // construct privileges
            vCnPrivileg = (String) sr.getAttributes().get(Constants.ldap_ddbPrivilege_Cn).get();
            vPrivilege = this.mapToPrivilege(sr.getAttributes(), Constants.ldap_ddbPrivilege_Cn);
            // vPrivEntryDN = (vAttr = sr.getAttributes().get("entryDN")) !=
            // null ? String.valueOf(vAttr.get()) : null; //
            // organizationName
            vPrivEntryDN = sr.getNameInNamespace(); // liefert das gleiche
            // wie oben...
            if ((vPrivilege != null) && (vPrivEntryDN != null)) {
                // vOrgEntryDN =
                // vPrivEntryDN.substring(vPrivEntryDN.indexOf(",") + 1,
                // vPrivEntryDN.indexOf(",dc") );
                vOrgEntryDN = vPrivEntryDN.substring(vPrivEntryDN.indexOf(",") + 1);
                vOrgPrivilege = new Privilege(vPrivilege);
                vAttr = sr.getAttributes().get(Constants.ldap_ddbPrivilege_Member);
                for (int i = 0; i < vAttr.size(); i++) {
                    if (((vMemberRef = String.valueOf(vAttr.get(i))) != null) && (vMemberRef.length() > 0)) {
                        if (((vStrs = vMemberRef.split(",")).length >= 1)
                                && ((vStrs = vStrs[0].split("=")).length == 2)
                                && (vStrs[0].trim().equalsIgnoreCase(Constants.ldap_ddbPerson_Id))) {
                            vOrgPrivilege.add(vStrs[1].trim());
                        }
                    }
                }
            } else {
                LOG.log(Level.WARNING, "Ein fehlerhaftes Privileg: Privileg: ''{0}'', Privileg-Entry: ''{1}''.",
                        new Object[] { vCnPrivileg, vPrivEntryDN });
            }
        } catch (NamingException ex) {
            LOG.log(Level.SEVERE, "CnPrivileg: '" + vCnPrivileg + "', PrivEntryDN: '" + vPrivEntryDN
                    + "', OrgEntryDN: '" + vOrgEntryDN + "'");
            throw ex;
        }
    }
    return vOrgPrivilege;
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Fetch the Ldap user attributes to be used as credentials.
 *
 * @param uid the user id (or lookup value) for whom credentials are required
 * @return the hash map containing user credentials as name/value pairs
 * @throws NamingException LDAP error obtaining user credentials.
 * @throws IOException // w w w .  ja  va 2s .c  o  m
 */
protected HashMap selectCredentials(String uid, CredentialProvider cp) throws NamingException, IOException {
    HashMap credentialResultSet = new HashMap();

    InitialLdapContext ctx = createLdapInitialContext(false);

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    String schemeName = null;
    if (cp instanceof AuthenticationScheme) {
        schemeName = ((AuthenticationScheme) cp).getName();
    }

    String principalLookupAttrName = this.getPrincipalLookupAttributeID();
    if (principalLookupAttrName == null || principalLookupAttrName.trim().equals("")
            || !"strong-authentication".equals(schemeName)) {
        principalLookupAttrName = this.getPrincipalUidAttributeID();
    }

    String usersCtxDN = this.getUsersCtxDN();

    // BasicAttributes matchAttrs = new BasicAttributes(true);
    // matchAttrs.put(principalUidAttrName, uid);

    String credentialQueryString = getCredentialQueryString();
    HashMap credentialQueryMap = parseQueryString(credentialQueryString);

    Iterator i = credentialQueryMap.keySet().iterator();
    List credentialAttrList = new ArrayList();
    while (i.hasNext()) {
        String o = (String) i.next();
        credentialAttrList.add(o);
    }

    String[] credentialAttr = (String[]) credentialAttrList.toArray(new String[credentialAttrList.size()]);

    try {

        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, credentialAttr);

        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalLookupAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();

            String userDN = sr.getNameInNamespace();
            if (logger.isDebugEnabled())
                logger.debug("Processing results for entry '" + userDN + "'");

            for (int j = 0; j < credentialAttr.length; j++) {
                if (attrs.get(credentialAttr[j]) == null)
                    continue;

                //Object credentialObject = attrs.get(credentialAttr[j]).get();
                String credentialName = (String) credentialQueryMap.get(credentialAttr[j]);
                String credentialValue = null;

                Attribute attr = attrs.get(credentialAttr[j]);
                NamingEnumeration attrEnum = attr.getAll();
                while (attrEnum.hasMore()) {
                    Object credentialObject = attrEnum.next();
                    if (credentialObject == null)
                        continue;

                    if (logger.isDebugEnabled())
                        logger.debug("Found user credential '" + credentialName + "' of type '"
                                + credentialObject.getClass().getName() + ""
                                + (credentialObject.getClass().isArray()
                                        ? "[" + Array.getLength(credentialObject) + "]"
                                        : "")
                                + "'");

                    // if the attribute value is an array, cast it to byte[] and then convert to
                    // String using proper encoding
                    if (credentialObject.getClass().isArray()) {

                        try {
                            // Try to create a UTF-8 String, we use java.nio to handle errors in a better way.
                            // If the byte[] cannot be converted to UTF-8, we're using the credentialObject as is.
                            byte[] credentialData = (byte[]) credentialObject;
                            ByteBuffer in = ByteBuffer.allocate(credentialData.length);
                            in.put(credentialData);
                            in.flip();

                            Charset charset = Charset.forName("UTF-8");
                            CharsetDecoder decoder = charset.newDecoder();
                            CharBuffer charBuffer = decoder.decode(in);

                            credentialValue = charBuffer.toString();

                        } catch (CharacterCodingException e) {
                            if (logger.isDebugEnabled())
                                logger.debug("Can't convert credential value to String using UTF-8");
                        }

                    } else if (credentialObject instanceof String) {
                        // The credential value must be a String ...
                        credentialValue = (String) credentialObject;

                    }

                    // Check what do we have ...
                    List credentials = (List) credentialResultSet.get(credentialName);
                    if (credentials == null) {
                        credentials = new ArrayList();
                    }
                    if (credentialValue != null) {
                        // Remove any schema information from the credential value, like the {md5} prefix for passwords.
                        credentialValue = getSchemeFreeValue(credentialValue);
                        credentials.add(credentialValue);
                    } else {
                        // We have a binary credential, leave it as it is ... probably binary value.
                        credentials.add(credentialObject);
                    }
                    credentialResultSet.put(credentialName, credentials);

                    if (logger.isDebugEnabled())
                        logger.debug("Found user credential '" + credentialName + "' with value '"
                                + (credentialValue != null ? credentialValue : credentialObject) + "'");
                }
            }

        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return credentialResultSet;
}