List of usage examples for javax.naming NamingEnumeration hasMore
public boolean hasMore() throws NamingException;
From source file:py.una.pol.karaku.util.LDAPUtil.java
/** * Recupera los usuarios de LDAP//from ww w.ja v a 2 s. c om * * @return Una lista con los usuarios de LDAP */ public List<User> getUsers() { List<User> users = new ArrayList<User>(); try { DirContext ctx = createInitialDirContext(); Attributes matchAttrs = new BasicAttributes(true); matchAttrs.put(new BasicAttribute("uid")); NamingEnumeration<SearchResult> answer = ctx.search("ou=users", matchAttrs); while (answer.hasMore()) { SearchResult sr = answer.next(); String uid = sr.getName().substring(4); // No se retornan los usuarios especiales if (!uid.startsWith(LDAP_SPECIAL_USER_PREFIX) && !ListHelper.contains(EXCLUDED_USERS, uid)) { User user = new User(); user.setUid(uid); Attributes atributos = sr.getAttributes(); String cn = atributos.get("cn").toString().substring(4); user.setCn(cn); users.add(user); } } } catch (NamingException e) { throw new KarakuRuntimeException(e.getMessage(), e); } return users; }
From source file:org.jasig.schedassist.impl.oraclecalendar.OracleCalendarUserAccountAttributesMapper.java
public Object mapFromAttributes(Attributes attributes) throws NamingException { OracleCalendarUserAccount user = new OracleCalendarUserAccount(); NamingEnumeration<String> attributeNames = attributes.getIDs(); Map<String, String> attributesMap = new HashMap<String, String>(); while (attributeNames.hasMore()) { String attributeName = attributeNames.next(); Attribute attribute = attributes.get(attributeName); String value = (String) attribute.get(); if (null != value) { value = value.trim();/*from www .ja va 2 s.co m*/ } final String lcAttributeName = attributeName.toLowerCase(); attributesMap.put(lcAttributeName, value); if (USERNAME_ATTRIBUTE.equals(lcAttributeName)) { user.setUsername(value); } else if (CALENDAR_UNIQUEID_ATTRIBUTE.equals(lcAttributeName)) { user.setCtcalxitemid(value); } else if (EMAIL_ATTRIBUTE.equals(lcAttributeName)) { user.setEmailAddress(value); } else if (DISPLAYNAME_ATTRIBUTE.equals(lcAttributeName)) { user.setDisplayName(value); } else if (GIVENNAME_ATTRIBUTE.equals(lcAttributeName)) { user.setGivenName(value); } else if (SURNAME_ATTRIBUTE.equals(lcAttributeName)) { user.setSurname(value); } } user.setAttributes(attributesMap); if (user.getCalendarUniqueId() != null) { String oracleGuid = this.oracleGUIDSource.getOracleGUID(user); user.setOracleGuid(oracleGuid); user.getAttributes().put(AbstractOracleCalendarAccount.ORACLE_GUID_ATTRIBUTE, oracleGuid); } return user; }
From source file:sk.lazyman.gizmo.security.SimpleBindAunthenticator.java
@Override public DirContextOperations authenticate(Authentication authentication) { DirContextOperations user = null;// w ww .jav a 2 s. c o m Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects"); String username = authentication.getName(); String password = (String) authentication.getCredentials(); if (StringUtils.isEmpty(password)) { LOG.debug("Rejecting empty password for user " + username); throw new BadCredentialsException( messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password")); } // If DN patterns are configured, try authenticating with them directly for (String dn : getUserDns(username)) { user = bindWithDn(dn, username, password); if (user != null) { break; } } // Otherwise use the configured search object to find the user and authenticate with the returned DN. if (user == null && getUserSearch() != null) { DirContextOperations userFromSearch = getUserSearch().searchForUser(username); user = bindWithDn(userFromSearch.getDn().toString(), username, password); } try { if (user != null && StringUtils.isNotEmpty(gizmoGroup)) { BaseLdapPathContextSource ctxSource = (BaseLdapPathContextSource) getContextSource(); DirContext ctx = ctxSource.getReadOnlyContext(); DistinguishedName userDn = new DistinguishedName(user.getDn()); userDn.prepend(ctxSource.getBaseLdapPath()); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = String.format(GROUP_SEARCH_QUERY, gizmoGroup, userDn.toCompactString()); NamingEnumeration en = ctx.search("", filter, controls); if (!en.hasMore()) { throw new BadCredentialsException( messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials")); } } } catch (javax.naming.NamingException ex) { throw new BadCredentialsException("Couldn't check group membership"); } if (user == null) { throw new BadCredentialsException( messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials")); } return user; }
From source file:org.pentaho.platform.plugin.services.security.userrole.ldap.transform.SearchResultToAttrValueList.java
public Object transform(final Object obj) { Object transformed = obj;/*from w ww. ja va 2 s .c o m*/ if (obj instanceof SearchResult) { transformed = new HashSet(); Set valueSet = (Set) transformed; SearchResult res = (SearchResult) obj; if (SearchResultToAttrValueList.logger.isDebugEnabled()) { SearchResultToAttrValueList.logger.debug(Messages.getInstance().getString( "SearchResultToAttrValueList.DEBUG_ATTRIBUTES_FROM_SEARCHRESULT", (null != res.getAttributes()) ? res.getAttributes().toString() : "null")); //$NON-NLS-1$ //$NON-NLS-2$ } Attribute attr = res.getAttributes().get(attributeName); if (SearchResultToAttrValueList.logger.isDebugEnabled()) { SearchResultToAttrValueList.logger .debug(Messages.getInstance().getString("SearchResultToAttrValueList.DEBUG_ATTRIBUTE_VALUE", attributeName, (null != attr) ? attr.toString() : "null")); //$NON-NLS-1$ //$NON-NLS-2$ } if (attr != null) { // check for null as node might not have attribute we're looking for try { NamingEnumeration values = attr.getAll(); while (values.hasMore()) { // if tokenName was specified, extract from value; otherwise // store value unchanged Object value = values.next(); if (StringUtils.hasLength(tokenName)) { if ((null != value) && (value instanceof String)) { String tokenValue = extract((String) value, tokenName); if (null != tokenValue) { valueSet.add(tokenValue); } } else { if (SearchResultToAttrValueList.logger.isWarnEnabled()) { SearchResultToAttrValueList.logger.warn(Messages.getInstance() .getString("SearchResultToAttrValueList.WARN_ATTRIBUTE_NOT_A_STRING")); //$NON-NLS-1$ } } } else { if (null != value) { valueSet.add(value.toString()); } } } } catch (NamingException e) { if (SearchResultToAttrValueList.logger.isErrorEnabled()) { SearchResultToAttrValueList.logger.error(Messages.getInstance() .getErrorString("SearchResultToAttrValueList.ERROR_0001_NAMING_EXCEPTION"), e); //$NON-NLS-1$ } } } return transformed; } return transformed; }
From source file:egovframework.com.ext.ldapumt.service.impl.DeptManageLdapDAO.java
/** * ?./*from w w w. j a v a 2 s . c o m*/ * @param vo vo */ public boolean hasChildren(String dn) throws NamingException { ContextSource contextSource = ldapTemplate.getContextSource(); DirContext ctx = contextSource.getReadOnlyContext(); String filter = "objectclass=*"; SearchControls control = new SearchControls(); control.setSearchScope(SearchControls.ONELEVEL_SCOPE); NamingEnumeration<SearchResult> n = ctx.search(dn, filter, control); if (n != null && n.hasMore()) { return true; } return false; }
From source file:org.sonar.plugins.ldap.LdapAutodiscovery.java
List<LdapSrvRecord> getLdapServers(DirContext context, String domain) throws NamingException { Attributes lSrvAttrs = context.getAttributes("dns:/_ldap._tcp." + domain, new String[] { "srv" }); Attribute serversAttribute = lSrvAttrs.get("srv"); NamingEnumeration<?> lEnum = serversAttribute.getAll(); SortedSet<LdapSrvRecord> result = new TreeSet<>(); while (lEnum.hasMore()) { String srvRecord = (String) lEnum.next(); // priority weight port target String[] srvData = srvRecord.split(" "); int priority = NumberUtils.toInt(srvData[0]); int weight = NumberUtils.toInt(srvData[1]); String port = srvData[2]; String target = srvData[3]; if (target.endsWith(".")) { target = target.substring(0, target.length() - 1); }/* w w w . j ava 2 s .com*/ String server = "ldap://" + target + ":" + port; result.add(new LdapSrvRecord(server, priority, weight)); } return new ArrayList<>(result); }
From source file:se.vgregion.service.innovationsslussen.ldap.LdapService.java
AttributesMapper newAttributesMapper(final Class type) { return new AttributesMapper() { @Override//from ww w . jav a 2s . co m public Object mapFromAttributes(Attributes attributes) throws NamingException { try { return mapFromAttributesImpl(attributes); } catch (Exception e) { throw new RuntimeException(e); } } public Object mapFromAttributesImpl(Attributes attributes) throws NamingException, IllegalAccessException, InstantiationException { Object result = type.newInstance(); BeanMap bm = new BeanMap(result); NamingEnumeration<? extends Attribute> all = attributes.getAll(); while (all.hasMore()) { Attribute attribute = all.next(); String name = toBeanPropertyName(attribute.getID()); if (bm.containsKey(name) && bm.getWriteMethod(name) != null) { bm.put(name, attribute.get()); } } return result; } }; }
From source file:com.hs.mail.security.login.JndiLoginModule.java
@SuppressWarnings("unchecked") protected boolean authenticate(String username, String password) throws Exception { DirContext context = null;/*from w w w.ja va 2 s. c o m*/ try { context = open(); searchFilterFormat.format(new String[] { username }); SearchControls constraints = new SearchControls(); constraints.setSearchScope(subtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE); if (returnAttribute != null) { String[] attribs = StringUtils.split(returnAttribute, ","); constraints.setReturningAttributes(attribs); } NamingEnumeration ne = context.search(base, searchFilter, constraints); if (ne == null || !ne.hasMore()) { return false; } SearchResult sr = (SearchResult) ne.next(); if (ne.hasMore()) { // Ignore for now } // Check the credentials by binding to server if (bindUser(context, sr.getNameInNamespace(), password)) { return true; } else { return true; } } catch (NamingException e) { close(context); return false; } }
From source file:org.springframework.ldap.core.LdapAttributes.java
/** * Returns a string representation of the object in LDIF format. * /*from w w w. j av a 2s .c o m*/ * @return {@link java.lang.String} formated to RFC2849 LDIF specifications. */ public String toString() { StringBuilder sb = new StringBuilder(); try { DistinguishedName dn = getDN(); if (!dn.toString().matches(SAFE_INIT_CHAR + SAFE_CHAR + "*")) { sb.append("dn:: " + new BASE64Encoder().encode(dn.toString().getBytes()) + "\n"); } else { sb.append("dn: " + getDN() + "\n"); } NamingEnumeration<Attribute> attributes = getAll(); while (attributes.hasMore()) { Attribute attribute = attributes.next(); NamingEnumeration<?> values = attribute.getAll(); while (values.hasMore()) { Object value = values.next(); if (value instanceof String) sb.append(attribute.getID() + ": " + (String) value + "\n"); else if (value instanceof byte[]) sb.append(attribute.getID() + ":: " + new BASE64Encoder().encode((byte[]) value) + "\n"); else if (value instanceof URI) sb.append(attribute.getID() + ":< " + (URI) value + "\n"); else { sb.append(attribute.getID() + ": " + value + "\n"); } } } } catch (NamingException e) { log.error("Error formating attributes for output.", e); sb = new StringBuilder(); } return sb.toString(); }
From source file:org.archone.ad.domain.UserHelper.java
public List<String> lookupMembershipGroups(DirContext dirContext, String userDn) throws javax.naming.NamingException { SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> searchResults = dirContext.search("", adConfiguration.getMembershipSearchFilter(), new String[] { userDn }, controls); List<String> roles = new LinkedList<String>(); while (searchResults.hasMore()) { GroupDn groupDn = new GroupDn(searchResults.next().getNameInNamespace(), adConfiguration.getGroupsRdn()); roles.add(groupDn.getAsGroupId()); }//from w w w. j a va 2 s . c o m return roles; }