List of usage examples for javax.naming.directory SearchResult getAttributes
public Attributes getAttributes()
From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java
private String searchAttributes(DirContext oDirContext, String sIDAttribute, String sMapperAttribute, String id) throws OAException { String sReturn = null;// w ww .jav a2 s . c o m NamingEnumeration oNamingEnumeration = null; try { if (sIDAttribute == null) { _logger.error("No attribute name to map from supplied"); throw new OAException(SystemErrors.ERROR_INTERNAL); } StringBuffer sbQuery = new StringBuffer("("); sbQuery.append(sIDAttribute); sbQuery.append("="); sbQuery.append(JNDIUtil.escapeLDAPSearchFilter(id)); sbQuery.append(")"); String sSearchQuery = sbQuery.toString(); String sSearchFor = sMapperAttribute; if (sSearchFor == null) sSearchFor = "*"; SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); oScope.setReturningAttributes(new String[] { sSearchFor }); try { oNamingEnumeration = oDirContext.search(_sDNBase, sSearchQuery, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(sSearchQuery); sbFailed.append(" while searching for attributes for id: "); sbFailed.append(id); _logger.error(sbFailed.toString(), e); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } if (!oNamingEnumeration.hasMore()) { _logger.debug("No result when searching for: " + sSearchQuery); } else { SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); if (sMapperAttribute == null) { sReturn = oSearchResult.getName(); sReturn += "," + _sDNBase; } else { Attributes oSearchedAttributes = oSearchResult.getAttributes(); Attribute attrMapping = oSearchedAttributes.get(sMapperAttribute); if (attrMapping == null) { _logger.debug("Mapping attribute not found: " + sMapperAttribute); } else { Object oValue = attrMapping.get(); if (!(oValue instanceof String)) { StringBuffer sbError = new StringBuffer("Returned value for mapping attribute '"); sbError.append(_sMapperAttribute); sbError.append("' has a value which is not of type 'String'"); _logger.error(sbError.toString()); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } sReturn = (String) oValue; } } } } catch (OAException e) { throw e; } catch (NamingException e) { _logger.debug("Failed to fetch mapping attribute for id: " + id, e); } catch (Exception e) { _logger.fatal("Could not retrieve fields for id: " + id, e); throw new OAException(SystemErrors.ERROR_INTERNAL); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for id: " + id, e); } } } return sReturn; }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * check if User already exists on system. * * @param inLogin// w w w . j a v a 2 s . com * String * @return path as string */ public boolean isUserAlreadyExists(String inLogin) { Hashtable<String, String> env = getLdapConnectionSettings(); env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin")); env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword")); DirContext ctx; boolean rueckgabe = false; try { ctx = new InitialDirContext(env); Attributes matchAttrs = new BasicAttributes(true); NamingEnumeration<SearchResult> answer = ctx.search("ou=users,dc=gdz,dc=sub,dc=uni-goettingen,dc=de", matchAttrs); rueckgabe = answer.hasMoreElements(); while (answer.hasMore()) { SearchResult sr = answer.next(); if (logger.isDebugEnabled()) { logger.debug(">>>" + sr.getName()); } Attributes attrs = sr.getAttributes(); String givenName = " "; String surName = " "; String mail = " "; String cn = " "; String hd = " "; try { givenName = attrs.get("givenName").toString(); } catch (Exception err) { givenName = " "; } try { surName = attrs.get("sn").toString(); } catch (Exception e2) { surName = " "; } try { mail = attrs.get("mail").toString(); } catch (Exception e3) { mail = " "; } try { cn = attrs.get("cn").toString(); } catch (Exception e4) { cn = " "; } try { hd = attrs.get("homeDirectory").toString(); } catch (Exception e4) { hd = " "; } logger.debug(givenName); logger.debug(surName); logger.debug(mail); logger.debug(cn); logger.debug(hd); } ctx.close(); } catch (NamingException e) { logger.error(e); } return rueckgabe; }
From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java
/** * For a given name, this method makes ldap search in userBase with filter {@link #userIdAttribute}=name and objectClass={@link #userObjectClass} * and builds {@link User} based on search result. * * @param name/*from w w w.jav a 2s. c o m*/ * The userId which should be value of the field {@link #userIdAttribute} * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the * userId of this user and ldap connection information with which * the user was searched. Return null if such a user was not found. * @throws NamingException * Propagated by the underlying LDAP communication layer. */ private ReadOnlyLDAPUser searchAndBuildUser(String name) throws NamingException { SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(new String[] { userIdAttribute }); sc.setCountLimit(1); StringBuilder builderFilter = new StringBuilder("(&("); builderFilter.append(userIdAttribute).append("=").append(name).append(")").append("(objectClass=") .append(userObjectClass).append(")"); if (StringUtils.isNotEmpty(filter)) { builderFilter.append(filter).append(")"); } else { builderFilter.append(")"); } NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, builderFilter.toString(), sc); if (!sr.hasMore()) return null; SearchResult r = sr.next(); Attribute userName = r.getAttributes().get(userIdAttribute); if (!restriction.isActivated() || userInGroupsMembershipList(r.getNameInNamespace(), restriction.getGroupMembershipLists(ldapContext))) return new ReadOnlyLDAPUser(userName.get().toString(), r.getNameInNamespace(), ldapContext); return null; }
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public boolean removeUserRole(String roleName, String username, DirContext context) throws MappingException { String groupName = findGroupName(roleName); if (groupName == null) { log.warn("no group found for role '{}", roleName); return false; }// w w w. j av a 2 s. c om NamingEnumeration<SearchResult> namingEnumeration = null; try { SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attribute attribute = searchResult.getAttributes().get(getLdapGroupMember()); if (attribute != null) { BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember()); basicAttribute.add(this.userIdAttribute + "=" + username + "," + getGroupsDn()); context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] { new ModificationItem(DirContext.REMOVE_ATTRIBUTE, basicAttribute) }); } return true; } return false; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } finally { if (namingEnumeration != null) { try { namingEnumeration.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public boolean saveUserRole(String roleName, String username, DirContext context) throws MappingException { String groupName = findGroupName(roleName); if (groupName == null) { log.warn("no group found for role '{}", roleName); groupName = roleName;/* w ww .j a v a 2 s . c o m*/ } NamingEnumeration<SearchResult> namingEnumeration = null; try { SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attribute attribute = searchResult.getAttributes().get(getLdapGroupMember()); if (attribute == null) { BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember()); basicAttribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn()); context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] { new ModificationItem(DirContext.ADD_ATTRIBUTE, basicAttribute) }); } else { attribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn()); context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] { new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute) }); } return true; } return false; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } finally { if (namingEnumeration != null) { try { namingEnumeration.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public List<String> getGroupsMember(String group, DirContext context) throws MappingException { NamingEnumeration<SearchResult> namingEnumeration = null; try {/*www. j av a 2s. c o m*/ SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = context.search("cn=" + group + "," + getGroupsDn(), filter, searchControls); List<String> allMembers = new ArrayList<String>(); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attribute uniqueMemberAttr = searchResult.getAttributes().get(getLdapGroupMember()); if (uniqueMemberAttr != null) { NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr .getAll(); while (allMembersEnum.hasMore()) { String userName = allMembersEnum.next(); // uid=blabla we only want bla bla userName = StringUtils.substringAfter(userName, "="); userName = StringUtils.substringBefore(userName, ","); log.debug("found userName for group {}: '{}", group, userName); allMembers.add(userName); } close(allMembersEnum); } } return allMembers; } 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.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
public ServerPrinciple[] listServicePrinciples(String filter) throws DirectoryServerManagerException { ServerPrinciple[] serverNames = null; int maxItemLimit = Integer.parseInt( this.realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST)); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(maxItemLimit); if (filter.contains("?") || filter.contains("**")) { log.error("Invalid search character " + filter); throw new DirectoryServerManagerException( "Invalid character sequence entered for service principle search. Please enter valid sequence."); }//from ww w . j av a2 s . com StringBuilder searchFilter; searchFilter = new StringBuilder( this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER)); String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); StringBuilder buff = new StringBuilder(); buff.append("(&").append(searchFilter).append("(") .append(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE).append("=").append(filter) .append(")").append(getServerPrincipleIncludeString()).append(")"); String[] returnedAtts = { LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE, LDAPServerManagerConstants.LDAP_COMMON_NAME }; searchCtls.setReturningAttributes(returnedAtts); DirContext dirContext = null; try { dirContext = connectionSource.getContext(); NamingEnumeration<SearchResult> answer = dirContext.search(searchBase, buff.toString(), searchCtls); List<ServerPrinciple> list = new ArrayList<ServerPrinciple>(); int i = 0; while (answer.hasMoreElements() && i < maxItemLimit) { SearchResult sr = answer.next(); if (sr.getAttributes() != null) { Attribute serverNameAttribute = sr.getAttributes() .get(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE); Attribute serverDescription = sr.getAttributes() .get(LDAPServerManagerConstants.LDAP_COMMON_NAME); if (serverNameAttribute != null) { ServerPrinciple principle; String serviceName; String serverPrincipleFullName = (String) serverNameAttribute.get(); if (serverPrincipleFullName.toLowerCase(Locale.ENGLISH) .contains(LDAPServerManagerConstants.KERBEROS_TGT)) { continue; } if (serverPrincipleFullName.contains("@")) { serviceName = serverPrincipleFullName.split("@")[0]; } else { serviceName = serverPrincipleFullName; } if (serverDescription != null) { principle = new ServerPrinciple(serviceName, (String) serverDescription.get()); } else { principle = new ServerPrinciple(serviceName); } list.add(principle); i++; } } } serverNames = list.toArray(new ServerPrinciple[list.size()]); Arrays.sort(serverNames); } catch (NamingException e) { log.error(e.getMessage(), e); throw new DirectoryServerManagerException("Unable to list service principles.", e); } catch (UserStoreException e) { log.error("Unable to retrieve LDAP connection context.", e); throw new DirectoryServerManagerException("Unable to list service principles.", e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } return serverNames; }
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
public void updateServicePrinciplePassword(String serverName, Object oldCredential, Object newCredentials) throws DirectoryServerManagerException { DirContext dirContext;/*w w w .j av a2s .co m*/ try { dirContext = this.connectionSource.getContext(); } catch (UserStoreException e) { throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e); } //first search the existing user entry. String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String searchFilter = getServicePrincipleFilter(serverName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_PASSWORD }); try { NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter, searchControls); // here we assume only one user while (namingEnumeration.hasMore()) { BasicAttributes basicAttributes = new BasicAttributes(true); SearchResult searchResult = namingEnumeration.next(); Attributes attributes = searchResult.getAttributes(); Attribute userPassword = attributes.get(LDAPServerManagerConstants.LDAP_PASSWORD); Attribute newPasswordAttribute = getChangePasswordAttribute(userPassword, oldCredential, newCredentials); basicAttributes.put(newPasswordAttribute); String dnName = searchResult.getName(); dirContext = (DirContext) dirContext.lookup(searchBase); dirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes); } } catch (NamingException e) { log.error("Unable to update server principle password details. Server name - " + serverName); throw new DirectoryServerManagerException("Can not access the directory service", e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } }
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
public boolean isValidPassword(String serverName, Object existingCredentials) throws DirectoryServerManagerException { DirContext dirContext;//from w w w. j a v a 2 s .c o m try { dirContext = this.connectionSource.getContext(); } catch (UserStoreException e) { throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e); } //first search the existing user entry. String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String searchFilter = getServicePrincipleFilter(serverName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_PASSWORD }); try { NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter, searchControls); // here we assume only one user while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attributes attributes = searchResult.getAttributes(); Attribute userPassword = attributes.get(LDAPServerManagerConstants.LDAP_PASSWORD); NamingEnumeration passwords = userPassword.getAll(); String passwordHashMethod = null; if (passwords.hasMore()) { byte[] byteArray = (byte[]) passwords.next(); String password = new String(byteArray, StandardCharsets.UTF_8); if (password.startsWith("{")) { passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}")); } return password.equals(getPasswordToStore((String) existingCredentials, passwordHashMethod)); } } } catch (NamingException e) { log.error("Failed, validating password. Can not access the directory service", e); throw new DirectoryServerManagerException( "Failed, validating password. " + "Can not access the directory service", e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } return false; }
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
private String lookupUserId(String serverName) throws DirectoryServerManagerException { DirContext dirContext;/* w w w. j av a 2s . c o m*/ try { dirContext = this.connectionSource.getContext(); } catch (UserStoreException e) { throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e); } String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); //first search the existing user entry. String searchFilter = getServicePrincipleFilter(serverName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { "uid" }); try { NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter, searchControls); // here we assume only one user if (namingEnumeration.hasMore()) { SearchResult searchResult; searchResult = namingEnumeration.next(); Attributes attributes = searchResult.getAttributes(); Attribute userId = attributes.get("uid"); return (String) userId.get(); } else { return null; } } catch (NamingException e) { log.error("Could not find user id for given server " + serverName, e); throw new DirectoryServerManagerException("Could not find user id for given server " + serverName, e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } }