Example usage for javax.naming.directory SearchResult getAttributes

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

Introduction

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

Prototype

public Attributes getAttributes() 

Source Link

Document

Retrieves the attributes in this search result.

Usage

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

public static Map<String, String> parseAsMap(NamingEnumeration searchResults, String keyAttribute,
        String valueAttribute) {//from w  w  w .  j  a  v  a  2  s. c  om
    Logger.debug("# START parseAsMap : Formatting the data as MAP", LDAPUtils.class);
    //System.out.println("# START parseAsMap : Formatting the data as MAP: "+searchResults );
    Map<String, String> resultMap = new HashMap<String, String>();
    if (searchResults == null) {
        return null;
    }
    // Loop through the search results
    while (searchResults.hasMoreElements()) {
        SearchResult sr = null;
        List<String> strList = new ArrayList<String>();
        try {
            sr = (SearchResult) searchResults.next();

        } catch (NamingException e1) {
            Logger.error("No Search results on LDAP ", LDAPUtils.class);
        }
        if (sr == null) {
            Logger.error("No Search results on LDAP ", LDAPUtils.class);
            return null;
        }
        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            try {
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();

                    for (NamingEnumeration e = attr.getAll(); e.hasMore(); e.next())
                        ;

                    //System.out.println(" attrs : "+attrs.get(keyAttribute) + ": "+ attrs.get(valueAttribute));
                    //if(attrs.get(keyAttribute)!=null && attrs.get(keyAttribute)!=null)
                    resultMap.put(attrs.get(keyAttribute).toString(), attrs.get(valueAttribute).toString());
                }
            } catch (NamingException ne) {
                ne.printStackTrace();
            }

        } else {
            Logger.info("No attributes found on LDAP", LDAPUtils.class);
        }
    }
    //Logger.debug("# END parseAsMap : Formatting the data as MAP", LDAPUtils.class );
    return resultMap;
}

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

protected DocumentModel ldapResultToDocumentModel(SearchResult result, String entryId, boolean fetchReferences)
        throws DirectoryException, NamingException {
    Attributes attributes = result.getAttributes();
    String passwordFieldId = getPasswordField();
    Map<String, Object> fieldMap = new HashMap<String, Object>();

    Attribute attribute = attributes.get(idAttribute);
    // NXP-2461: check that id field is filled + NXP-2730: make sure that
    // entry id is the one returned from LDAP
    if (attribute != null) {
        Object entry = attribute.get();
        if (entry != null) {
            entryId = entry.toString();/*from   ww w. j  a v  a  2  s. c o  m*/
        }
    }
    // NXP-7136 handle id case
    entryId = changeEntryIdCase(entryId, idCase);

    if (entryId == null) {
        // don't bother
        return null;
    }
    for (String fieldName : schemaFieldMap.keySet()) {
        List<Reference> references = directory.getReferences(fieldName);
        if (references != null && references.size() > 0) {
            if (fetchReferences) {
                Map<String, List<String>> referencedIdsMap = new HashMap<>();
                for (Reference reference : references) {
                    // reference resolution
                    List<String> referencedIds;
                    if (reference instanceof LDAPReference) {
                        // optim: use the current LDAPSession directly to
                        // provide the LDAP reference with the needed backend entries
                        LDAPReference ldapReference = (LDAPReference) reference;
                        referencedIds = ldapReference.getLdapTargetIds(attributes);
                    } else if (reference instanceof LDAPTreeReference) {
                        // TODO: optimize using the current LDAPSession
                        // directly to provide the LDAP reference with the
                        // needed backend entries (needs to implement getLdapTargetIds)
                        LDAPTreeReference ldapReference = (LDAPTreeReference) reference;
                        referencedIds = ldapReference.getTargetIdsForSource(entryId);
                    } else {
                        referencedIds = reference.getTargetIdsForSource(entryId);
                    }
                    referencedIds = new ArrayList<>(referencedIds);
                    Collections.sort(referencedIds);
                    if (referencedIdsMap.containsKey(fieldName)) {
                        referencedIdsMap.get(fieldName).addAll(referencedIds);
                    } else {
                        referencedIdsMap.put(fieldName, referencedIds);
                    }
                }
                fieldMap.put(fieldName, referencedIdsMap.get(fieldName));
            }
        } else {
            // manage directly stored fields
            String attributeId = getDirectory().getFieldMapper().getBackendField(fieldName);
            if (attributeId.equals(LDAPDirectory.DN_SPECIAL_ATTRIBUTE_KEY)) {
                // this is the special DN readonly attribute
                try {
                    fieldMap.put(fieldName, result.getNameInNamespace());
                } catch (UnsupportedOperationException e) {
                    // ignore ApacheDS partial implementation when running
                    // in embedded mode
                }
            } else {
                // this is a regular attribute
                attribute = attributes.get(attributeId);
                if (fieldName.equals(passwordFieldId)) {
                    // do not try to fetch the password attribute
                    continue;
                } else {
                    fieldMap.put(fieldName, getFieldValue(attribute, fieldName, entryId, fetchReferences));
                }
            }
        }
    }
    // check if the idAttribute was returned from the search. If not
    // set it anyway, maybe changing its case if it's a String instance
    String fieldId = getDirectory().getFieldMapper().getDirectoryField(idAttribute);
    Object obj = fieldMap.get(fieldId);
    if (obj == null) {
        fieldMap.put(fieldId,
                changeEntryIdCase(entryId, getDirectory().getDescriptor().getMissingIdFieldCase()));
    } else if (obj instanceof String) {
        fieldMap.put(fieldId, changeEntryIdCase((String) obj, idCase));
    }
    return fieldMapToDocumentModel(fieldMap);
}

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

/**
 *
 *///from w w  w . ja  v  a  2 s  .  c  o m
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:de.fiz.ddb.aas.utils.LDAPEngineUtility.java

private Privilege convertLdapGroupToOrgPriv(SearchResult sr) throws NamingException, IllegalAccessException {
    Privilege vOrgPrivilege = null;/*w  w  w. java  2 s .co m*/
    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.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java

public Map<String, String> findLdapUserDetails(String userName) {
    Properties systemConfig = systemManager.getSystemConfiguration(subjectManager.getOverlord());
    HashMap<String, String> userDetails = new HashMap<String, String>();
    // Load our LDAP specific properties
    Properties env = getProperties(systemConfig);

    // Load the BaseDN
    String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN);

    // Load the LoginProperty
    String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty);
    if (loginProperty == null) {
        // Use the default
        loginProperty = "cn";
    }//ww  w.  j  a v a 2  s.co m
    // Load any information we may need to bind
    String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN);
    String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW);

    // Load any search filter
    String searchFilter = (String) systemConfig.get(RHQConstants.LDAPFilter);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }

    try {
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        SearchControls searchControls = getSearchControls();

        // Add the search filter if specified.  This only allows for a single search filter.. i.e. foo=bar.
        String filter;
        if ((searchFilter != null) && (searchFilter.length() != 0)) {
            filter = "(&(" + loginProperty + "=" + userName + ")" + "(" + searchFilter + "))";
        } else {
            filter = "(" + loginProperty + "=" + userName + ")";
        }

        log.debug("Using LDAP filter [" + filter + "] to locate user details for " + userName);

        // Loop through each configured base DN.  It may be useful
        // in the future to allow for a filter to be configured for
        // each BaseDN, but for now the filter will apply to all.
        String[] baseDNs = baseDN.split(BASEDN_DELIMITER);
        for (int x = 0; x < baseDNs.length; x++) {
            NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls);
            if (!answer.hasMoreElements()) { //BZ:582471- ldap api bug change
                log.debug("User " + userName + " not found for BaseDN " + baseDNs[x]);
                // Nothing found for this DN, move to the next one if we have one.
                continue;
            }

            // We use the first match
            SearchResult si = answer.next();
            //generate the DN
            String userDN = null;
            try {
                userDN = si.getNameInNamespace();
            } catch (UnsupportedOperationException use) {
                userDN = si.getName();
                if (userDN.startsWith("\"")) {
                    userDN = userDN.substring(1, userDN.length());
                }
                if (userDN.endsWith("\"")) {
                    userDN = userDN.substring(0, userDN.length() - 1);
                }
                userDN = userDN + "," + baseDNs[x];
            }
            userDetails.put("dn", userDN);

            // Construct the UserDN
            NamingEnumeration<String> keys = si.getAttributes().getIDs();
            while (keys.hasMore()) {
                String key = keys.next();
                Attribute value = si.getAttributes().get(key);
                if ((value != null) && (value.get() != null)) {
                    userDetails.put(key, value.get().toString());
                }
            }
            return userDetails;
        }
        return userDetails;
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.nuxeo.wizard.RouterServlet.java

public void handleUserPOST(Page currentPage, HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    Context ctx = Context.instance(req);
    ParamCollector collector = ctx.getCollector();

    String refreshParam = req.getParameter("refresh");
    String directoryType = collector.getConfigurationParam("nuxeo.directory.type");

    if ("true".equals(refreshParam)) {
        currentPage.dispatchToJSP(req, resp);
        return;//from   ww w  .  j  a v a2 s.c om
    }

    if ("checkNetwork".equals(refreshParam) || "checkAuth".equals(refreshParam)
            || "checkUserLdapParam".equals(refreshParam) || "checkGroupLdapParam".equals(refreshParam)) {
        try {
            if ("checkNetwork".equals(refreshParam)) {
                bindLdapConnection(collector, false);
                ctx.trackInfo("nuxeo.ldap.url", "info.host.found");
            } else if ("checkAuth".equals(refreshParam)) {
                bindLdapConnection(collector, true);
                ctx.trackInfo("nuxeo.ldap.auth", "info.auth.success");
            } else {
                DirContext dirContext = new InitialDirContext(getContextEnv(collector, true));
                String searchScope;
                String searchBaseDn;
                String searchClass;
                String searchFilter;
                if ("checkUserLdapParam".equals(refreshParam)) {
                    searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn");
                    searchScope = collector.getConfigurationParam("nuxeo.ldap.user.searchScope");
                    searchClass = collector.getConfigurationParam("nuxeo.ldap.user.searchClass");
                    searchFilter = collector.getConfigurationParam("nuxeo.ldap.user.searchFilter");
                } else {
                    searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn");
                    searchScope = collector.getConfigurationParam("nuxeo.ldap.group.searchScope");
                    searchFilter = collector.getConfigurationParam("nuxeo.ldap.group.searchFilter");
                    searchClass = "";
                }

                SearchControls scts = new SearchControls();
                if ("onelevel".equals(searchScope)) {
                    scts.setSearchScope(SearchControls.ONELEVEL_SCOPE);
                } else {
                    scts.setSearchScope(SearchControls.SUBTREE_SCOPE);
                }
                String filter = String.format("(&(%s)(objectClass=%s))",
                        searchFilter.isEmpty() ? "objectClass=*" : searchFilter,
                        searchClass.isEmpty() ? "*" : searchClass);
                NamingEnumeration<SearchResult> results;
                try {
                    results = dirContext.search(searchBaseDn, filter, scts);
                    if (!results.hasMore()) {
                        ctx.trackError("nuxeo.ldap.search", "error.ldap.noresult");
                    } else {
                        SearchResult result = results.next();
                        if (searchBaseDn.equalsIgnoreCase(result.getNameInNamespace()) && results.hasMore()) {
                            // try not to display the root of the search
                            // base DN
                            result = results.next();
                        }
                        ctx.trackInfo("dn", result.getNameInNamespace());
                        Attributes attributes = result.getAttributes();
                        NamingEnumeration<String> ids = attributes.getIDs();
                        String id;
                        StringBuilder sb;
                        while (ids.hasMore()) {
                            id = ids.next();
                            NamingEnumeration<?> values = attributes.get(id).getAll();
                            sb = new StringBuilder();
                            while (values.hasMore()) {
                                sb.append(values.next()).append(" , ");
                            }
                            ctx.trackInfo(id, sb.substring(0, sb.length() - 3));
                        }
                    }
                } catch (NameNotFoundException e) {
                    ctx.trackError("nuxeo.ldap.search", "error.ldap.searchBaseDn");
                    log.warn(e);
                }
                dirContext.close();
            }
        } catch (AuthenticationException e) {
            ctx.trackError("nuxeo.ldap.auth", "error.auth.failed");
            log.warn(e);
        } catch (NamingException e) {
            ctx.trackError("nuxeo.ldap.url", "error.host.not.found");
            log.warn(e);
        }
    }

    // Form submit
    if (!"default".equals(directoryType) && refreshParam.isEmpty()) {
        // first check bind to LDAP server
        try {
            bindLdapConnection(collector, true);
        } catch (NamingException e) {
            ctx.trackError("nuxeo.ldap.auth", "error.ldap.bind.failed");
            log.warn(e);
        }

        // then check mandatory fields
        if (collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.searchBaseDn", "error.user.searchBaseDn.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.rdn").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.rdn", "error.user.rdn.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.username").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.username", "error.user.username.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.password").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.password", "error.user.password.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.firstname").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.firstname", "error.user.firstname.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.lastname").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.lastname", "error.user.lastname.required");
        }
        String userGroupStorage = collector.getConfigurationParam("nuxeo.user.group.storage");
        if (!"userLdapOnly".equals(userGroupStorage) && !"multiUserSqlGroup".equals(userGroupStorage)) {
            if (collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.searchBaseDn", "error.group.searchBaseDn.required");
            }
            if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.rdn").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.mapping.rdn", "error.group.rdn.required");
            }
            if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.name").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.mapping.name", "error.group.name.required");
            }
        }
        if ("true".equals(collector.getConfigurationParam("nuxeo.user.emergency.enable"))) {
            if (collector.getConfigurationParam("nuxeo.user.emergency.username").isEmpty()) {
                ctx.trackError("nuxeo.user.emergency.username", "error.emergency.username.required");
            }
            if (collector.getConfigurationParam("nuxeo.user.emergency.password").isEmpty()) {
                ctx.trackError("nuxeo.user.emergency.password", "error.emergency.password.required");
            }
        }
    }

    if (ctx.hasErrors() || ctx.hasInfos()) {
        currentPage.dispatchToJSP(req, resp);
    } else {
        currentPage.next().dispatchToJSP(req, resp, true);
    }
}

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 {/*  ww  w. j  av  a2s . co m*/
        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.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 a va  2s . com*/
        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.olat.ldap.manager.LDAPLoginManagerImpl.java

@Override
public void doSyncSingleUser(Identity ident) {
    LdapContext ctx = bindSystem();
    if (ctx == null) {
        log.error("could not bind to ldap", null);
    }//from w  w w.  j a va  2  s .c o  m
    String userDN = ldapDao.searchUserDN(ident.getName(), ctx);

    final List<Attributes> ldapUserList = new ArrayList<Attributes>();
    // TODO: use userDN instead of filter to get users attribs
    ldapDao.searchInLdap(new LDAPVisitor() {
        @Override
        public void visit(SearchResult result) {
            Attributes resAttribs = result.getAttributes();
            log.debug("        found : " + resAttribs.size() + " attributes in result " + result.getName());
            ldapUserList.add(resAttribs);
        }
    }, userDN, syncConfiguration.getUserAttributes(), ctx);

    Attributes attrs = ldapUserList.get(0);
    Map<String, String> olatProToSync = prepareUserPropertyForSync(attrs, ident);
    if (olatProToSync != null) {
        syncUser(olatProToSync, ident);
    }
}

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

/**
 * Remove existing statically defined links for the given target id (dynamic references remain unaltered)
 *
 * @see org.nuxeo.ecm.directory.Reference#removeLinksForTarget(String)
 *///from  w w  w.  j a v  a  2  s .c  o  m
@Override
public void removeLinksForTarget(String targetId) throws DirectoryException {
    if (!isStatic()) {
        // nothing to do: dynamic references cannot be updated
        return;
    }
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        if (!sourceSession.isReadOnly()) {
            // get the dn of the target that matches targetId
            String targetAttributeValue;

            if (staticAttributeIdIsDn) {
                SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId);
                if (targetLdapEntry == null) {
                    String rdnAttribute = ldapTargetDirectory.getDescriptor().getRdnAttribute();
                    if (!rdnAttribute.equals(targetSession.idAttribute)) {
                        log.warn(String.format(
                                "cannot remove links to missing entry %s in directory %s for reference %s",
                                targetId, ldapTargetDirectory.getName(), this));
                        return;
                    }
                    // the entry might have already been deleted, try to
                    // re-forge it if possible (might not work if scope is
                    // subtree)
                    targetAttributeValue = String.format("%s=%s,%s", rdnAttribute, targetId,
                            ldapTargetDirectory.getDescriptor().getSearchBaseDn());
                } else {
                    targetAttributeValue = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace());
                }
            } else {
                targetAttributeValue = targetId;
            }

            // build a LDAP query to find entries that point to the target
            String searchFilter = String.format("(%s=%s)", attributeId, targetAttributeValue);
            String sourceFilter = ldapSourceDirectory.getBaseFilter();

            if (sourceFilter != null && !"".equals(sourceFilter)) {
                searchFilter = String.format("(&(%s)(%s))", searchFilter, sourceFilter);
            }

            SearchControls scts = new SearchControls();
            scts.setSearchScope(ldapSourceDirectory.getDescriptor().getSearchScope());
            scts.setReturningAttributes(new String[] { attributeId });

            // find all source entries that point to the target key and
            // clean
            // those references
            if (log.isDebugEnabled()) {
                log.debug(String.format(
                        "LDAPReference.removeLinksForTarget(%s): LDAP search baseDn='%s' "
                                + " filter='%s' scope='%s' [%s]",
                        targetId, sourceSession.searchBaseDn, searchFilter, scts.getSearchScope(), this));
            }
            NamingEnumeration<SearchResult> results = sourceSession.dirContext
                    .search(sourceSession.searchBaseDn, searchFilter, scts);
            String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
            Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker);

            try {
                while (results.hasMore()) {
                    SearchResult result = results.next();
                    Attributes attrs = result.getAttributes();
                    Attribute attr = attrs.get(attributeId);
                    try {
                        if (attr.size() == 1) {
                            // the attribute holds the last reference, put
                            // the
                            // empty ref. marker before removing the
                            // attribute
                            // since empty attribute are often not allowed
                            // by
                            // the server schema
                            if (log.isDebugEnabled()) {
                                log.debug(String.format(
                                        "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' "
                                                + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                        targetId, result.getNameInNamespace(), attrs, this));
                            }
                            sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(),
                                    DirContext.ADD_ATTRIBUTE, emptyAttribute);
                        }
                        // remove the reference to the target key
                        attrs = new BasicAttributes();
                        attr = new BasicAttribute(attributeId);
                        attr.add(targetAttributeValue);
                        attrs.put(attr);
                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' "
                                            + "mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    targetId, result.getNameInNamespace(), attrs, this));
                        }
                        sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(),
                                DirContext.REMOVE_ATTRIBUTE, attrs);
                    } catch (SchemaViolationException e) {
                        if (isDynamic()) {
                            // we are editing an entry that has no static
                            // part
                            log.warn(String.format("cannot remove dynamic reference in field %s for target %s",
                                    getFieldName(), targetId));
                        } else {
                            // this is a real schema configuration problem,
                            // wrapup the exception
                            throw new DirectoryException(e);
                        }
                    }
                }
            } finally {
                results.close();
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("removeLinksForTarget failed: " + e.getMessage(), e);
    }
}