List of usage examples for javax.naming.directory DirContext search
public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException;
From source file:org.wso2.carbon.appfactory.userstore.internal.OTLDAPUtil.java
public static NamingEnumeration<SearchResult> searchForUser(String searchFilter, String[] returnedAtts, DirContext dirContext, String userSearchBase) throws UserStoreException { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (returnedAtts != null && returnedAtts.length > 0) { searchCtls.setReturningAttributes(returnedAtts); }//from ww w . j a v a 2 s . c om try { return dirContext.search(userSearchBase, searchFilter, searchCtls); } catch (NamingException e) { log.error("Search failed.", e); throw new UserStoreException(e.getMessage()); } }
From source file:org.wso2.carbon.appfactory.userstore.OTAppFactoryUserStore.java
@Override public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException { String[] userNames = new String[0]; if (maxItemLimit == 0) { return userNames; }//from ww w.j a v a 2 s . c om int givenMax = Integer .parseInt(realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST)); if (maxItemLimit < 0 || maxItemLimit > givenMax) { maxItemLimit = givenMax; } SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(maxItemLimit); if (filter.contains("?") || filter.contains("**")) { throw new UserStoreException( "Invalid character sequence entered for user serch. Please enter valid sequence."); } StringBuffer searchFilter = null; searchFilter = new StringBuffer(realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER)); String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); StringBuffer buff = new StringBuffer(); buff.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=").append(filter) .append("))"); String serviceNameAttribute = "sn"; String mailAttribute = "mail"; String returnedAtts[] = { userNameProperty, serviceNameAttribute, mailAttribute }; searchCtls.setReturningAttributes(returnedAtts); DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; String[] allUserNames = null; try { dirContext = connectionSource.getContext(); answer = dirContext.search(searchBase, buff.toString(), searchCtls); List<String> list = new ArrayList<String>(); int i = 0; while (answer.hasMoreElements() && i < maxItemLimit) { SearchResult sr = (SearchResult) answer.next(); if (sr.getAttributes() != null) { Attribute attr = sr.getAttributes().get(mailAttribute); /* * If this is a service principle, just ignore and iterate rest of the array. * The entity is a service if value of surname is Service */ Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute); if (attrSurname != null) { String serviceName = (String) attrSurname.get(); if (serviceName != null && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) { continue; } } if (attr != null) { String name = (String) attr.get(); //append the domain if exist String domain = userRealm.getRealmConfiguration() .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); if (domain != null) { domain = domain + "/"; name = domain + name; } list.add(name); i++; } } } userNames = list.toArray(new String[list.size()]); //get secondary user lists UserStoreManager secUserManager = this.getSecondaryUserStoreManager(); if (secUserManager != null) { String[] secUserNames = secUserManager.listUsers(filter, maxItemLimit); allUserNames = UserCoreUtil.combineArrays(userNames, secUserNames); } else { allUserNames = userNames; } Arrays.sort(allUserNames); } catch (NamingException e) { log.error(e.getMessage(), e); throw new UserStoreException(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return allUserNames; }
From source file:org.wso2.carbon.connector.ldap.SearchEntry.java
private NamingEnumeration<SearchResult> searchInUserBase(String dn, String searchFilter, String[] returningAttributes, int searchScope, DirContext rootContext) throws NamingException { String userBase = dn;/*from www . ja v a 2s . c o m*/ SearchControls userSearchControl = new SearchControls(); userSearchControl.setReturningAttributes(returningAttributes); userSearchControl.setSearchScope(searchScope); NamingEnumeration<SearchResult> userSearchResults; userSearchResults = rootContext.search(userBase, searchFilter, userSearchControl); return userSearchResults; }
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
public boolean isExistingServiceUid(String uid) throws DirectoryServerManagerException { DirContext dirContext; try {/*from w ww . j a va 2 s . c o m*/ dirContext = this.connectionSource.getContext(); } catch (UserStoreException e) { log.error("Unable to retrieve directory context.", e); throw new DirectoryServerManagerException("Unable to retrieve directory context.", e); } //first search the existing user entry. String searchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String filter = "(&(" + LDAPServerManagerConstants.LDAP_UID + "=" + uid + ")" + getServerPrincipleIncludeString() + ")"; SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_UID }); try { NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, filter, searchControls); return namingEnumeration.hasMore(); } catch (NamingException e) { log.error("Unable to check whether service exists in directory server. UID - " + uid, e); 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 isExistingServicePrinciple(String servicePrinciple) throws DirectoryServerManagerException { DirContext dirContext; try {/*from w w w . j ava 2 s. co m*/ dirContext = this.connectionSource.getContext(); } catch (UserStoreException e) { log.error("Unable to retrieve directory context.", e); throw new DirectoryServerManagerException("Unable to retrieve directory context.", e); } //first search the existing user entry. String searchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String filter = getServicePrincipleFilter(servicePrinciple); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_UID }); try { NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, filter, searchControls); return namingEnumeration.hasMore(); } catch (NamingException e) { String message = "Unable to search entry with search base " + searchBase + ", filter -" + filter; log.error(message, e); 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 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 w w w . j av a2s.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; try {//from w ww . j av a 2 s. c om 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; try {/*w w w. ja v a 2 s . c om*/ 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; try {//from w w w .ja v a2 s . co m 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); } } }
From source file:org.wso2.carbon.identity.account.suspension.notification.task.ldap.LDAPNotificationReceiversRetrieval.java
@Override public List<NotificationReceiver> getNotificationReceivers(long lookupMin, long lookupMax, long delayForSuspension, String tenantDomain) throws AccountSuspensionNotificationException { List<NotificationReceiver> users = new ArrayList<NotificationReceiver>(); if (realmConfiguration != null) { String ldapSearchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); RealmService realmService = NotificationTaskDataHolder.getInstance().getRealmService(); try {//from www. j a v a2 s. c o m ClaimManager claimManager = (ClaimManager) realmService .getTenantUserRealm(IdentityTenantUtil.getTenantId(tenantDomain)).getClaimManager(); String userStoreDomain = realmConfiguration .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); if (StringUtils.isBlank(userStoreDomain)) { userStoreDomain = IdentityUtil.getPrimaryDomainName(); } String usernameMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.USERNAME_CLAIM); String firstNameMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.FIRST_NAME_CLAIM); String emailMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.EMAIL_CLAIM); String lastLoginTimeAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.LAST_LOGIN_TIME); if (log.isDebugEnabled()) { log.debug( "Retrieving ldap user list for lookupMin: " + lookupMin + " - lookupMax: " + lookupMax); } LDAPConnectionContext ldapConnectionContext = new LDAPConnectionContext(realmConfiguration); DirContext ctx = ldapConnectionContext.getContext(); //carLicense is the mapped LDAP attribute for LastLoginTime claim String searchFilter = "(&(" + lastLoginTimeAttribute + ">=" + lookupMin + ")(" + lastLoginTimeAttribute + "<=" + lookupMax + "))"; SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls); if (log.isDebugEnabled()) { log.debug("LDAP user list retrieved."); } while (results.hasMoreElements()) { SearchResult result = results.nextElement(); NotificationReceiver receiver = new NotificationReceiver(); receiver.setEmail((String) result.getAttributes().get(emailMapAttribute).get()); receiver.setUsername((String) result.getAttributes().get(usernameMapAttribute).get()); receiver.setFirstName((String) result.getAttributes().get(firstNameMapAttribute).get()); receiver.setUserStoreDomain(userStoreDomain); long lastLoginTime = Long .parseLong(result.getAttributes().get(lastLoginTimeAttribute).get().toString()); long expireDate = lastLoginTime + TimeUnit.DAYS.toMillis(delayForSuspension); receiver.setExpireDate(new SimpleDateFormat("dd-MM-yyyy").format(new Date(expireDate))); if (log.isDebugEnabled()) { log.debug("Expire date was set to: " + receiver.getExpireDate()); } users.add(receiver); } } catch (NamingException e) { throw new AccountSuspensionNotificationException("Failed to filter users from LDAP user store.", e); } catch (UserStoreException e) { throw new AccountSuspensionNotificationException("Failed to load LDAP connection context.", e); } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new AccountSuspensionNotificationException( "Error occurred while getting tenant user realm for " + "tenant:" + tenantDomain, e); } } return users; }