List of usage examples for javax.naming NamingEnumeration next
public T next() throws NamingException;
From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java
private User searchUserById(LdapContext ldap, String userId) throws NamingException { SearchControls sc = getSearchControls(); NamingEnumeration<SearchResult> results = null; try {/*from ww w . j a va 2 s.c o m*/ results = ldap.search(config.getBaseDN(), MessageFormat.format("(&(objectClass=user)(sAMAccountName={0}))", userId), sc); //$NON-NLS-1$ while (results != null && results.hasMore()) { SearchResult entry = results.next(); User user = processEntry(entry); if (user != null) { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format("Success reading from LDAP: {0}, {1} <{2}>", //$NON-NLS-1$ user.getUserId(), user.getDisplayName(), user.getEmail())); } return user; } } } finally { closeQuietly(results); } return new User(userId); }
From source file:org.orbeon.oxf.processor.LDAPProcessor.java
private List search(DirContext ctx, String rootDN, String scope, String filter, String[] attributes) { try {// w w w.j av a2 s . com List listResults = new ArrayList(); SearchControls constraints = new SearchControls(); constraints.setSearchScope(convertSearchScope(scope)); constraints.setReturningAttributes(attributes); try { if (scope != null && scope.toUpperCase().equals("ALLLEVELS")) { String[] levels = rootDN.split(","); for (int i = 0; i < levels.length; i++) { String[] currentLevels = new String[levels.length - i]; System.arraycopy(levels, i, currentLevels, 0, levels.length - i); String levelRootDN = StringUtils.join(currentLevels, ","); if (logger.isDebugEnabled()) logger.debug("LDAP Search on level " + levelRootDN); NamingEnumeration results = ctx.search(levelRootDN, filter, constraints); for (; results.hasMore();) { SearchResult result = (SearchResult) results.next(); listResults.add(result); } } } else { NamingEnumeration results = ctx.search(rootDN, filter, constraints); for (; results.hasMore();) { SearchResult result = (SearchResult) results.next(); listResults.add(result); } } } catch (NameNotFoundException e) { // for example in case of ALLLEVELS scope, if the LDAP database suffix has more than one component, the last iteration would result in NameNotFoundException } return listResults; } catch (NamingException e) { throw new OXFException("LDAP Search Failed", e); } }
From source file:org.apache.openaz.xacml.std.pip.engines.ldap.LDAPEngine.java
public void getAttributes(PIPRequest pipRequest, PIPFinder pipFinder, StdMutablePIPResponse mutablePIPResponse, LDAPResolver ldapResolver) throws PIPException { /*/* ww w . j a v a 2s . co m*/ * Check with the resolver to get the base string */ String stringBase = ldapResolver.getBase(this, pipRequest, pipFinder); if (stringBase == null) { this.logger.warn(this.getName() + " does not handle " + pipRequest.toString()); return; } /* * Get the filter string */ String stringFilter = ldapResolver.getFilterString(this, pipRequest, pipFinder); /* * Check the cache */ Cache<String, PIPResponse> cache = this.getCache(); String cacheKey = stringBase + "::" + (stringFilter == null ? "" : stringFilter); if (cache != null) { PIPResponse pipResponse = cache.getIfPresent(cacheKey); if (pipResponse != null) { if (this.logger.isDebugEnabled()) { this.logger.debug("Returning cached response: " + pipResponse); } mutablePIPResponse.addAttributes(pipResponse.getAttributes()); return; } } /* * Not in the cache, so set up the LDAP query session */ DirContext dirContext = null; PIPResponse pipResponse = null; try { /* * Create the DirContext */ dirContext = new InitialDirContext(this.ldapEnvironment); /* * Set up the search controls */ SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(this.ldapScope); /* * Do the search */ NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(stringBase, stringFilter, searchControls); if (namingEnumeration != null && namingEnumeration.hasMore()) { while (namingEnumeration.hasMore()) { List<Attribute> listAttributes = ldapResolver.decodeResult(namingEnumeration.next()); if (listAttributes != null && listAttributes.size() > 0) { mutablePIPResponse.addAttributes(listAttributes); } } } /* * Put in the cache */ if (cache != null) { cache.put(cacheKey, pipResponse); } } catch (NamingException ex) { this.logger.error("NamingException creating the DirContext: " + ex.getMessage(), ex); } finally { if (dirContext != null) { try { dirContext.close(); } catch (Exception ex) { this.logger.warn("Exception closing DirContext: " + ex.getMessage(), ex); } } } }
From source file:org.easy.ldap.AdminServiceImpl.java
@Override public List<LdapUser> findAllUsers(LdapUser example) { Preconditions.checkNotNull(example); Preconditions.checkNotNull(example.getTenantId()); List<LdapUser> out = new ArrayList<LdapUser>(0); try {// w w w . j av a 2 s. c o m LdapName rootDn = namingFactory.createUsersDn(example.getTenantId()); NamingEnumeration<SearchResult> result = ldapDao.findAll(rootDn, LdapDao.toAttributes(example)); while (result.hasMore()) { out.add(LdapDao.toModel(example.getTenantId(), result.next().getAttributes())); } } catch (NamingException e) { log.error(e); throw new java.lang.RuntimeException(e); } return out; }
From source file:org.wso2.carbon.appfactory.userstore.AppFactoryTenantManager.java
protected String getNameInSpaceForUserName(String userName) throws UserStoreException { DirContext dirContext;//from w w w . j a v a2s .c o m String usernameSearchFilter = realmConfig.getUserStoreProperty("UserNameListFilter"); String userNameProperty = realmConfig.getUserStoreProperty("UserNameAttribute"); String searchFilter = getSearchFilter(usernameSearchFilter, userNameProperty, userName); if (log.isDebugEnabled()) { log.debug((new StringBuilder()).append("Searching for ").append(searchFilter).toString()); } dirContext = ldapConnectionSource.getContext(); NamingEnumeration answer = null; String userDn; try { String name = null; answer = searchForObject(searchFilter, null, dirContext, realmConfig.getUserStoreProperty("UserSearchBase")); int count = 0; SearchResult userObj; SearchResult sr; for (userObj = null; answer.hasMoreElements(); userObj = sr) { sr = (SearchResult) answer.next(); if (count > 0) { log.error("More than one user exist for the same name"); } count++; } if (userObj != null) { name = userObj.getNameInNamespace(); } userDn = name; } catch (Exception e) { log.error(e.getMessage(), e); throw new UserStoreException(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return userDn; }
From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java
/** * @return true = monitoring is enabled * @return false = monitoring is not enabled * @exception NamingException no conection *//*from ww w. ja v a 2 s.co m*/ private boolean hasMonitoringEnabled(Metric metric) throws NamingException { NamingEnumeration enumer = null, enumerx = null, enumery = null; boolean res = false; try { String[] a = { "monitorContext" }; SearchControls cons = new SearchControls(); cons.setSearchScope(SearchControls.OBJECT_SCOPE); cons.setReturningAttributes(a); enumer = getDirContext(metric.getProperties()).search("", "(&(objectClass=*))", cons); while (enumer.hasMore() && !res) { SearchResult searchresult = (SearchResult) enumer.next(); Attributes attrs = searchresult.getAttributes(); enumerx = attrs.getIDs(); while (enumerx.hasMore()) { String id = (String) enumerx.next(); Attribute attr = attrs.get(id); res = true; } } } finally { if (enumer != null) { enumer.close(); } if (enumerx != null) { enumerx.close(); } if (enumery != null) { enumery.close(); } } log.debug("[hasMonitoringEnabled] res=" + res + " metric:" + metric); return res; }
From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java
/** Function to extract users from Zeppelin LdapRealm. */ private List<String> getUserList(LdapRealm r, String searchText, int numUsersToFetch) { List<String> userList = new ArrayList<>(); LOGGER.debug("SearchText: " + searchText); String userAttribute = r.getUserSearchAttributeName(); String userSearchRealm = r.getUserSearchBase(); String userObjectClass = r.getUserObjectClass(); JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory(); try {//from w ww . j a v a 2 s . c om LdapContext ctx = cf.getSystemLdapContext(); SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); constraints.setCountLimit(numUsersToFetch); String[] attrIDs = { userAttribute }; constraints.setReturningAttributes(attrIDs); NamingEnumeration result = ctx.search(userSearchRealm, "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=*" + searchText + "*))", constraints); while (result.hasMore()) { Attributes attrs = ((SearchResult) result.next()).getAttributes(); if (attrs.get(userAttribute) != null) { String currentUser; if (r.getUserLowerCase()) { LOGGER.debug("userLowerCase true"); currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase(); } else { LOGGER.debug("userLowerCase false"); currentUser = (String) attrs.get(userAttribute).get(); } LOGGER.debug("CurrentUser: " + currentUser); userList.add(currentUser.trim()); } } } catch (Exception e) { LOGGER.error("Error retrieving User list from Ldap Realm", e); } return userList; }
From source file:openscim.restful.server.resources.user.ldap.UserAttributesMapper.java
public Object mapFromAttributes(Attributes attributes) throws NamingException { // create a user resource User user = ResourceUtilities.FACTORY.createUser(); // get the uid attribute name String uidAtttributeName = properties.getProperty(UID_ATTRIBUTE, DEFAULT_UID_ATTRIBUTE); // get the uid //Attribute uidAttribute = attributes.get(uidAtttributeName); //if(uidAttribute != null) user.setId((String)uidAttribute.get()); // get the display name attribute name String displayAtttributeName = properties.getProperty(DISPLAYNAME_ATTRIBUTE, DEFAULT_DISPLAYNAME_ATTRIBUTE); // get the display name Attribute displayNameAttribute = attributes.get(displayAtttributeName); if (displayNameAttribute != null) user.setDisplayName((String) displayNameAttribute.get()); // create a user name resource Name name = ResourceUtilities.FACTORY.createName(); // get the surname attribute name String surnameAtttributeName = properties.getProperty(FAMILYNAME_ATTRIBUTE, DEFAULT_FAMILYNAME_ATTRIBUTE); // get the surname name Attribute surnameAttribute = attributes.get(surnameAtttributeName); if (surnameAttribute != null) name.setFamilyName((String) surnameAttribute.get()); // get the given name attribute name String givenAtttributeName = properties.getProperty(GIVENNAME_ATTRIBUTE, DEFAULT_GIVENNAME_ATTRIBUTE); // get the given name Attribute givenAttribute = attributes.get(givenAtttributeName); if (givenAttribute != null) name.setGivenName((String) givenAttribute.get()); // add the name to the user resource user.setName(name);/* www.ja v a2 s.c o m*/ // get the email attribute name String mailAtttributeName = properties.getProperty(MAIL_ATTRIBUTE, DEFAULT_MAIL_ATTRIBUTE); // get the mails if (attributes.get(mailAtttributeName) != null) { NamingEnumeration mailEnumeration = attributes.get(mailAtttributeName).getAll(); if (mailEnumeration != null) { // create a emails resource Emails emails = ResourceUtilities.FACTORY.createUserEmails(); while (mailEnumeration.hasMoreElements()) { // get the next email String mailAttribute = (String) mailEnumeration.next(); if (mailAttribute != null) { PluralAttribute pluralAttribute = ResourceUtilities.FACTORY.createPluralAttribute(); pluralAttribute.setValue(mailAttribute); if (emails.getEmail().isEmpty()) pluralAttribute.setPrimary(true); else pluralAttribute.setPrimary(false); emails.getEmail().add(pluralAttribute); } } // add the mails to the user resource user.setEmails(emails); } } // get the telephone attribute name String telephoneAtttributeName = properties.getProperty(TELEPHONE_ATTRIBUTE, DEFAULT_TELEPHONE_ATTRIBUTE); // get the telephones if (attributes.get(telephoneAtttributeName) != null) { NamingEnumeration telephoneEnumeration = attributes.get(telephoneAtttributeName).getAll(); if (telephoneEnumeration != null) { // create a telephones resource PhoneNumbers telephones = ResourceUtilities.FACTORY.createUserPhoneNumbers(); while (telephoneEnumeration.hasMoreElements()) { // get the next telephone String telephoneAttribute = (String) telephoneEnumeration.next(); if (telephoneAttribute != null) { PluralAttribute pluralAttribute = ResourceUtilities.FACTORY.createPluralAttribute(); pluralAttribute.setValue(telephoneAttribute); if (telephones.getPhoneNumber().isEmpty()) pluralAttribute.setPrimary(true); else pluralAttribute.setPrimary(false); telephones.getPhoneNumber().add(pluralAttribute); } } // add the telephones to the user resource user.setPhoneNumbers(telephones); } } // get the password attribute name String passwordAtttributeName = properties.getProperty(PASSWORD_ATTRIBUTE, DEFAULT_PASSWORD_ATTRIBUTE); // get the password Attribute passwordAttribute = attributes.get(passwordAtttributeName); if (passwordAttribute != null) user.setPassword(new String((byte[]) passwordAttribute.get())); // get the memberOf attribute name String memberOfAtttributeName = properties.getProperty(MEMBEROF_ATTRIBUTE, DEFAULT_MEMBEROF_ATTRIBUTE); // get the memberOf if (attributes.get(memberOfAtttributeName) != null) { NamingEnumeration memberOfEnumeration = attributes.get(memberOfAtttributeName).getAll(); if (memberOfEnumeration != null) { // create a memberof resource MemberOf memberof = ResourceUtilities.FACTORY.createUserMemberOf(); while (memberOfEnumeration.hasMoreElements()) { // get the next member String memberOfAttribute = (String) memberOfEnumeration.next(); if (memberOfAttribute != null) { PluralAttribute pluralAttribute = ResourceUtilities.FACTORY.createPluralAttribute(); // check if the member dns need to be concealed if (properties .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS, UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS) .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) { Matcher matcher = pattern.matcher(memberOfAttribute); if (matcher.matches()) { memberOfAttribute = matcher.group(1); } } pluralAttribute.setValue(memberOfAttribute); memberof.getGroup().add(pluralAttribute); } } // add the memberOf to the user resource user.setMemberOf(memberof); } } return user; }
From source file:ru.runa.wfe.security.logic.LdapLogic.java
private int synchronizeActors(DirContext dirContext, Map<String, Actor> actorsByDistinguishedName) throws Exception { int changesCount = 0; List<Actor> existingActorsList = executorDao.getAllActors(BatchPresentationFactory.ACTORS.createNonPaged()); Map<String, Actor> existingActorsMap = Maps.newHashMap(); for (Actor actor : existingActorsList) { existingActorsMap.put(actor.getName().toLowerCase(), actor); }/* w w w. ja va 2 s . co m*/ Set<Actor> ldapActorsToDelete = Sets.newHashSet(); if (LdapProperties.isSynchronizationDeleteExecutors()) { ldapActorsToDelete.addAll(executorDao.getGroupActors(importGroup)); } SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); for (String ou : LdapProperties.getSynchronizationOrganizationUnits()) { List<SearchResult> resultList = Lists.newArrayList(); try { NamingEnumeration<SearchResult> list = dirContext.search(ou, OBJECT_CLASS_USER_FILTER, controls); while (list.hasMore()) { SearchResult searchResult = list.next(); resultList.add(searchResult); } list.close(); } catch (SizeLimitExceededException e) { resultList.clear(); for (String y : ALPHABETS) { NamingEnumeration<SearchResult> list = dirContext.search(ou, MessageFormat.format(LOGIN_FIRST_LETTER_FILTER, ATTR_ACCOUNT_NAME, y, y.toLowerCase(), OBJECT_CLASS_USER_FILTER), controls); while (list.hasMore()) { SearchResult searchResult = list.next(); resultList.add(searchResult); } list.close(); } } for (SearchResult searchResult : resultList) { String name = getStringAttribute(searchResult, ATTR_ACCOUNT_NAME); String description = getStringAttribute(searchResult, LdapProperties.getSynchronizationUserDescriptionAttribute()); String fullName = getStringAttribute(searchResult, LdapProperties.getSynchronizationUserFullNameAttribute()); String email = getStringAttribute(searchResult, LdapProperties.getSynchronizationUserEmailAttribute()); String phone = getStringAttribute(searchResult, LdapProperties.getSynchronizationUserPhoneAttribute()); String title = getStringAttribute(searchResult, LdapProperties.getSynchronizationUserTitleAttribute()); String department = getStringAttribute(searchResult, LdapProperties.getSynchronizationUserDepartmentAttribute()); ToStringHelper toStringHelper = MoreObjects.toStringHelper("user info"); toStringHelper.add("name", name).add("description", description).add("fullName", fullName) .add("email", email); toStringHelper.add("phone", phone).add("title", title).add("department", department) .omitNullValues(); log.debug("Read " + toStringHelper.toString()); Actor actor = existingActorsMap.get(name.toLowerCase()); if (actor == null) { if (!LdapProperties.isSynchronizationCreateExecutors()) { continue; } actor = new Actor(name, description, fullName, null, email, phone, title, department); log.info("Creating " + actor); executorDao.create(actor); executorDao.addExecutorsToGroup(Lists.newArrayList(actor), importGroup); permissionDao.setPermissions(importGroup, Lists.newArrayList(Permission.LIST), actor); changesCount++; } else { ldapActorsToDelete.remove(actor); if (LdapProperties.isSynchronizationUpdateExecutors()) { List<IChange> changes = Lists.newArrayList(); if (isAttributeNeedsChange(description, actor.getDescription())) { changes.add(new AttributeChange("description", actor.getDescription(), description)); actor.setDescription(description); } if (isAttributeNeedsChange(fullName, actor.getFullName())) { changes.add(new AttributeChange("fullName", actor.getFullName(), fullName)); actor.setFullName(fullName); } if (isAttributeNeedsChange(email, actor.getEmail())) { changes.add(new AttributeChange("email", actor.getEmail(), email)); actor.setEmail(email); } if (isAttributeNeedsChange(phone, actor.getPhone())) { changes.add(new AttributeChange("phone", actor.getPhone(), phone)); actor.setPhone(phone); } if (isAttributeNeedsChange(title, actor.getTitle())) { changes.add(new AttributeChange("title", actor.getTitle(), title)); actor.setTitle(title); } if (isAttributeNeedsChange(department, actor.getDepartment())) { changes.add(new AttributeChange("department", actor.getDepartment(), department)); actor.setDepartment(department); } if (!actor.isActive()) { if (LdapProperties.isSynchronizationUserStatusEnabled()) { actor.setActive(true); changes.add(new AttributeChange("active", "false", "true")); } if (executorDao.removeExecutorFromGroup(actor, wasteGroup)) { changes.add(new Change("waste group removal")); } if (executorDao.addExecutorToGroup(actor, importGroup)) { changes.add(new Change("import group addition")); } } if (!changes.isEmpty()) { executorDao.update(actor); log.info("Updating " + actor + ": " + changes); changesCount++; } } } actorsByDistinguishedName.put(searchResult.getNameInNamespace(), actor); } } if (LdapProperties.isSynchronizationDeleteExecutors() && ldapActorsToDelete.size() > 0) { if (LdapProperties.isSynchronizationUserStatusEnabled()) { for (Actor actor : ldapActorsToDelete) { actor.setActive(false); executorDao.update(actor); log.info("Inactivating " + actor); changesCount++; } } executorDao.removeExecutorsFromGroup(ldapActorsToDelete, importGroup); executorDao.addExecutorsToGroup(ldapActorsToDelete, wasteGroup); changesCount += ldapActorsToDelete.size(); } return changesCount; }
From source file:org.efaps.db.store.VFSStoreResource.java
/** * Method called to initialize this StoreResource. * @param _instance Instance of the object this StoreResource is wanted * for/* ww w . j ava2 s.c o m*/ * @param _store Store this resource belongs to * @throws EFapsException on error * @see Resource#initialize(Instance, Map, Compress) */ @Override public void initialize(final Instance _instance, final Store _store) throws EFapsException { super.initialize(_instance, _store); final StringBuilder fileNameTmp = new StringBuilder(); final String useTypeIdStr = getStore().getResourceProperties().get(VFSStoreResource.PROPERTY_USE_TYPE); if ("true".equalsIgnoreCase(useTypeIdStr)) { fileNameTmp.append(getInstance().getType().getId()).append("/"); } final String numberSubDirsStr = getStore().getResourceProperties() .get(VFSStoreResource.PROPERTY_NUMBER_SUBDIRS); if (numberSubDirsStr != null) { final long numberSubDirs = Long.parseLong(numberSubDirsStr); final String pathFormat = "%0" + Math.round(Math.log10(numberSubDirs) + 0.5d) + "d"; fileNameTmp.append(String.format(pathFormat, getInstance().getId() % numberSubDirs)).append("/"); } fileNameTmp.append(getInstance().getType().getId()).append(".").append(getInstance().getId()); this.storeFileName = fileNameTmp.toString(); final String numberBackupStr = getStore().getResourceProperties() .get(VFSStoreResource.PROPERTY_NUMBER_BACKUP); if (numberBackupStr != null) { this.numberBackup = Integer.parseInt(numberBackupStr); } if (this.manager == null) { try { DefaultFileSystemManager tmpMan = null; if (getStore().getResourceProperties().containsKey(Store.PROPERTY_JNDINAME)) { final InitialContext initialContext = new InitialContext(); final Context context = (Context) initialContext.lookup("java:comp/env"); final NamingEnumeration<NameClassPair> nameEnum = context.list(""); while (nameEnum.hasMoreElements()) { final NameClassPair namePair = nameEnum.next(); if (namePair.getName() .equals(getStore().getResourceProperties().get(Store.PROPERTY_JNDINAME))) { tmpMan = (DefaultFileSystemManager) context .lookup(getStore().getResourceProperties().get(Store.PROPERTY_JNDINAME)); break; } } } if (tmpMan == null && this.manager == null) { this.manager = evaluateFileSystemManager(); } } catch (final NamingException e) { throw new EFapsException(VFSStoreResource.class, "initialize.NamingException", e); } } }