List of usage examples for javax.naming.directory SearchControls SearchControls
public SearchControls()
From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTest.java
@Test public void testGetAllAuthorities1ForTenant() { ITenant defaultTenant = new Tenant("/pentaho/tenant0", true); login("suzy", defaultTenant); SearchControls con1 = new SearchControls(); con1.setReturningAttributes(new String[] { "cn" }); //$NON-NLS-1$ LdapSearchParamsFactory paramsFactory = new LdapSearchParamsFactoryImpl("ou=roles", //$NON-NLS-1$ "(objectClass=organizationalRole)", con1); //$NON-NLS-1$ Transformer one = new SearchResultToAttrValueList("cn"); //$NON-NLS-1$ Transformer two = new StringToGrantedAuthority(); Transformer[] transformers = { one, two }; Transformer transformer = new ChainedTransformer(transformers); LdapSearch rolesSearch = new GenericLdapSearch(getContextSource(), paramsFactory, transformer); DefaultLdapUserRoleListService userRoleListService = getDefaultLdapUserRoleListService(); userRoleListService.setAllAuthoritiesSearch(rolesSearch); List res = userRoleListService.getAllRoles(defaultTenant); assertTrue(res.contains("ROLE_CTO")); //$NON-NLS-1$ assertTrue(res.contains("ROLE_CEO")); //$NON-NLS-1$ if (logger.isDebugEnabled()) { logger.debug("results of getAllAuthorities1(): " + res); //$NON-NLS-1$ }// w w w. j a v a2 s . c o m try { userRoleListService.getAllRoles(new Tenant("/pentaho", true)); } catch (UnsupportedOperationException uoe) { assertNotNull(uoe); } }
From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTests.java
/** * Same as above except sorted.// w ww . ja va2s. co m */ @Test public void testGetAllAuthorities1Sorted() { SearchControls con1 = new SearchControls(); con1.setReturningAttributes(new String[] { "cn" }); //$NON-NLS-1$ LdapSearchParamsFactory paramsFactory = new LdapSearchParamsFactoryImpl("ou=roles", //$NON-NLS-1$ "(objectClass=organizationalRole)", con1); //$NON-NLS-1$ Transformer one = new SearchResultToAttrValueList("cn"); //$NON-NLS-1$ Transformer two = new StringToGrantedAuthority(); Transformer[] transformers = { one, two }; Transformer transformer = new ChainedTransformer(transformers); LdapSearch rolesSearch = new GenericLdapSearch(getContextSource(), paramsFactory, transformer); DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService(); userRoleListService.setAllAuthoritiesSearch(rolesSearch); userRoleListService.setRoleComparator(new DefaultRoleComparator()); List res = userRoleListService.getAllRoles(); assertTrue(res.contains("ROLE_CTO")); //$NON-NLS-1$ assertTrue(res.contains("ROLE_CEO")); //$NON-NLS-1$ assertTrue(res.indexOf("ROLE_ADMINISTRATOR") < res.indexOf("ROLE_DEV")); if (logger.isDebugEnabled()) { logger.debug("results of getAllAuthorities1Sorted(): " + res); //$NON-NLS-1$ } }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
@SuppressWarnings("unchecked") private SearchResult findUser(String username) throws NamingException, LoginException { SearchControls ctls = new SearchControls(); ctls.setCountLimit(1);//from w ww . j a va2 s. c o m ctls.setDerefLinkFlag(true); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = OBJECT_CLASS_FILTER; debug("Searching for users with filter: \'" + filter + "\'" + " from base dn: " + _userBaseDn); Object[] filterArguments = new Object[] { _userObjectClass, _userIdAttribute, username }; NamingEnumeration results = _rootContext.search(_userBaseDn, filter, filterArguments, ctls); debug("Found user?: " + results.hasMoreElements()); if (!results.hasMoreElements()) { throw new LoginException("User not found."); } return (SearchResult) results.nextElement(); }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
private void searchInLdap(final LdapVisitor visitor, final String filter, final String[] returningAttrs, final LdapContext ctx) { final SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setReturningAttributes(returningAttrs); ctls.setCountLimit(0); // set no limits final boolean paging = isPagedResultControlSupported(ctx); for (final String ldapBase : LDAPLoginModule.getLdapBases()) { int counter = 0; try {/*w w w .jav a 2 s. c o m*/ if (paging) { byte[] cookie = null; ctx.setRequestControls( new Control[] { new PagedResultsControl(PAGE_SIZE, Control.NONCRITICAL) }); do { final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls); while (enm.hasMore()) { visitor.visit(enm.next()); } cookie = getCookie(ctx); } while (cookie != null); } else { final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls); while (enm.hasMore()) { visitor.visit(enm.next()); } counter++; } } catch (final SizeLimitExceededException e) { logError("SizeLimitExceededException after " + counter + " records when getting all users from LDAP, reconfigure your LDAP server, hints: http://www.ldapbrowser.com/forum/viewtopic.php?t=14", null); } catch (final NamingException e) { logError("NamingException when trying to fetch deleted users from LDAP using ldapBase::" + ldapBase + " on row::" + counter, e); } catch (final Exception e) { logError("Exception when trying to fetch deleted users from LDAP using ldapBase::" + ldapBase + " on row::" + counter, e); } } }
From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTest.java
/** * Same as above except sorted./* w w w .j a v a2s . c o m*/ */ @Test public void testGetAllAuthorities1Sorted() { SearchControls con1 = new SearchControls(); con1.setReturningAttributes(new String[] { "cn" }); //$NON-NLS-1$ LdapSearchParamsFactory paramsFactory = new LdapSearchParamsFactoryImpl("ou=roles", //$NON-NLS-1$ "(objectClass=organizationalRole)", con1); //$NON-NLS-1$ Transformer one = new SearchResultToAttrValueList("cn"); //$NON-NLS-1$ Transformer two = new StringToGrantedAuthority(); Transformer[] transformers = { one, two }; Transformer transformer = new ChainedTransformer(transformers); LdapSearch rolesSearch = new GenericLdapSearch(getContextSource(), paramsFactory, transformer); DefaultLdapUserRoleListService userRoleListService = getDefaultLdapUserRoleListService(); userRoleListService.setAllAuthoritiesSearch(rolesSearch); userRoleListService.setRoleComparator(new DefaultRoleComparator()); List res = userRoleListService.getAllRoles(); assertTrue(res.contains("ROLE_CTO")); //$NON-NLS-1$ assertTrue(res.contains("ROLE_CEO")); //$NON-NLS-1$ assertTrue(res.indexOf("ROLE_ADMINISTRATOR") < res.indexOf("ROLE_DEV")); if (logger.isDebugEnabled()) { logger.debug("results of getAllAuthorities1Sorted(): " + res); //$NON-NLS-1$ } }
From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java
/** Obtain the DistinguishedName for a given user logon name. *@param ctx is the ldap context to use.// w ww. ja va 2s .co m *@param userName (Domain Logon Name) is the user name or identifier. *@param searchBase (Full Domain Name for the search ie: DC=qa-ad-76,DC=metacarta,DC=com) *@return DistinguishedName for given domain user logon name. * (Should throws an exception if user is not found.) */ protected String getDistinguishedName(LdapContext ctx, String userName, String searchBase, String userACLsUsername) throws ManifoldCFException { String returnedAtts[] = { "distinguishedName" }; String searchFilter = "(&(objectClass=user)(" + userACLsUsername + "=" + userName + "))"; SearchControls searchCtls = new SearchControls(); searchCtls.setReturningAttributes(returnedAtts); //Specify the search scope searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(returnedAtts); try { NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); if (attrs != null) { String dn = attrs.get("distinguishedName").get().toString(); return dn; } } return null; } catch (NamingException e) { throw new ManifoldCFException(e.getMessage(), e); } }
From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTests.java
/** * Search for all roles (aka authorities) starting at <code>ou=groups</code>, looking for objects with * <code>objectClass=groupOfUniqueNames</code>, and returning the <code>cn</code> attribute. *///from w w w. j a va 2 s.c o m @Test public void testGetAllAuthorities2() { SearchControls con1 = new SearchControls(); con1.setReturningAttributes(new String[] { "cn" }); //$NON-NLS-1$ LdapSearchParamsFactory paramsFactory = new LdapSearchParamsFactoryImpl("ou=groups", //$NON-NLS-1$ "(objectClass=groupOfUniqueNames)", con1); //$NON-NLS-1$ Transformer one = new SearchResultToAttrValueList("cn"); //$NON-NLS-1$ Transformer two = new StringToGrantedAuthority(); Transformer[] transformers = { one, two }; Transformer transformer = new ChainedTransformer(transformers); LdapSearch rolesSearch = new GenericLdapSearch(getContextSource(), paramsFactory, transformer); DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService(); userRoleListService.setAllAuthoritiesSearch(rolesSearch); List res = userRoleListService.getAllRoles(); assertTrue(res.contains("ROLE_SALES")); //$NON-NLS-1$ assertTrue(res.contains("ROLE_MARKETING")); //$NON-NLS-1$ if (logger.isDebugEnabled()) { logger.debug("results of getAllAuthorities2(): " + res); //$NON-NLS-1$ } }
From source file:org.apache.syncope.fit.core.reference.RoleITCase.java
@Test public void issueSYNCOPE632() { RoleTO roleTO = null;/*from w w w . j av a2 s. co m*/ try { // 1. create new LDAP resource having account id mapped to a derived attribute ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP); newLDAP.setKey("new-ldap"); newLDAP.setPropagationPrimary(true); MappingItemTO accountId = newLDAP.getRmapping().getAccountIdItem(); accountId.setIntMappingType(IntMappingType.RoleDerivedSchema); accountId.setIntAttrName("displayProperty"); newLDAP.getRmapping().setAccountIdItem(accountId); newLDAP.getRmapping().setAccountLink("'cn=' + displayProperty + ',ou=groups,o=isp'"); MappingItemTO description = new MappingItemTO(); description.setIntMappingType(IntMappingType.RoleId); description.setExtAttrName("description"); description.setPurpose(MappingPurpose.BOTH); newLDAP.getRmapping().addItem(description); newLDAP = createResource(newLDAP); assertNotNull(newLDAP); // 2. create a role and give the resource created above roleTO = buildRoleTO("lastRole"); roleTO.getRPlainAttrTemplates().add("icon"); roleTO.getPlainAttrs().add(attrTO("icon", "anIcon")); roleTO.getRPlainAttrTemplates().add("show"); roleTO.getPlainAttrs().add(attrTO("show", "true")); roleTO.getRDerAttrTemplates().add("displayProperty"); roleTO.getDerAttrs().add(attrTO("displayProperty", null)); roleTO.getResources().clear(); roleTO.getResources().add("new-ldap"); roleTO = createRole(roleTO); assertNotNull(roleTO); // 3. update the role RoleMod roleMod = new RoleMod(); roleMod.setKey(roleTO.getKey()); roleMod.getPlainAttrsToRemove().add("icon"); roleMod.getPlainAttrsToUpdate().add(attrMod("icon", "anotherIcon")); roleTO = updateRole(roleMod); assertNotNull(roleTO); // 4. check that a single group exists in LDAP for the role created and updated above int entries = 0; DirContext ctx = null; try { ctx = getLdapResourceDirContext(null, null); SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(new String[] { "*", "+" }); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp", "(description=" + roleTO.getKey() + ")", ctls); while (result.hasMore()) { result.next(); entries++; } } catch (Exception e) { // ignore } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { // ignore } } } assertEquals(1, entries); } finally { if (roleTO != null) { roleService.delete(roleTO.getKey()); } resourceService.delete("new-ldap"); } }
From source file:org.lsc.jndi.JndiServices.java
private List<String> doGetDnList(final String base, final String filter, final int scope) throws NamingException { NamingEnumeration<SearchResult> ne = null; List<String> iist = new ArrayList<String>(); try {/* w w w . ja va 2s. c o m*/ SearchControls sc = new SearchControls(); sc.setDerefLinkFlag(false); sc.setReturningAttributes(new String[] { "1.1" }); sc.setSearchScope(scope); sc.setReturningObjFlag(true); ne = ctx.search(base, filter, sc); String completedBaseDn = ""; if (base.length() > 0) { completedBaseDn = "," + base; } while (ne.hasMoreElements()) { iist.add(((SearchResult) ne.next()).getName() + completedBaseDn); } } catch (NamingException e) { LOGGER.error(e.toString()); LOGGER.debug(e.toString(), e); throw e; } return iist; }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
/** * This method overwrites the method in LDAPUserStoreManager. This implements the functionality * of updating user's profile information in LDAP user store. * * @param userName//from w ww . ja v a2 s . c om * @param claims * @param profileName * @throws UserStoreException */ @Override public void doSetUserClaimValues(String userName, Map<String, String> claims, String profileName) throws UserStoreException { // get the LDAP Directory context DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // search the relevant user entry by user name String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); // if user name contains domain name, remove domain name String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR); if (userNames.length > 1) { userName = userNames[1]; } userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(null); NamingEnumeration<SearchResult> returnedResultList = null; String returnedUserEntry = null; try { returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter, searchControls); // assume only one user is returned from the search // TODO:what if more than one user is returned if (returnedResultList.hasMore()) { returnedUserEntry = returnedResultList.next().getName(); } } catch (NamingException e) { String errorMessage = "Results could not be retrieved from the directory context for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(returnedResultList); } if (profileName == null) { profileName = UserCoreConstants.DEFAULT_PROFILE; } if (claims.get(UserCoreConstants.PROFILE_CONFIGURATION) == null) { claims.put(UserCoreConstants.PROFILE_CONFIGURATION, UserCoreConstants.DEFAULT_PROFILE_CONFIGURATION); } try { Attributes updatedAttributes = new BasicAttributes(true); for (Map.Entry<String, String> claimEntry : claims.entrySet()) { String claimURI = claimEntry.getKey(); // if there is no attribute for profile configuration in LDAP, // skip updating it. if (claimURI.equals(UserCoreConstants.PROFILE_CONFIGURATION)) { continue; } // get the claimMapping related to this claimURI String attributeName = getClaimAtrribute(claimURI, userName, null); //remove user DN from cache if changing username attribute if (realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE).equals(attributeName)) { userCache.remove(userName); } // if uid attribute value contains domain name, remove domain // name if (attributeName.equals("uid")) { // if user name contains domain name, remove domain name String uidName = claimEntry.getValue(); String[] uidNames = uidName.split(CarbonConstants.DOMAIN_SEPARATOR); if (uidNames.length > 1) { uidName = uidNames[1]; claimEntry.setValue(uidName); } // claimEntry.setValue(escapeISSpecialCharacters(uidName)); } Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); /* if updated attribute value is null, remove its values. */ if (EMPTY_ATTRIBUTE_STRING.equals(claimEntry.getValue())) { currentUpdatedAttribute.clear(); } else { String userAttributeSeparator = ","; if (claimEntry.getValue() != null && !attributeName.equals("uid") && !attributeName.equals("sn")) { String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR); if (claimSeparator != null && !claimSeparator.trim().isEmpty()) { userAttributeSeparator = claimSeparator; } if (claimEntry.getValue().contains(userAttributeSeparator)) { StringTokenizer st = new StringTokenizer(claimEntry.getValue(), userAttributeSeparator); while (st.hasMoreElements()) { String newVal = st.nextElement().toString(); if (newVal != null && newVal.trim().length() > 0) { currentUpdatedAttribute.add(newVal.trim()); } } } else { currentUpdatedAttribute.add(claimEntry.getValue()); } } else { currentUpdatedAttribute.add(claimEntry.getValue()); } } updatedAttributes.put(currentUpdatedAttribute); } // update the attributes in the relevant entry of the directory // store subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.modifyAttributes(returnedUserEntry, DirContext.REPLACE_ATTRIBUTE, updatedAttributes); } catch (Exception e) { handleException(e, userName); } finally { JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }