List of usage examples for javax.naming NamingEnumeration hasMore
public boolean hasMore() throws NamingException;
From source file:com.surevine.ldap2alfresco.ProfileFieldTelephoneConverter.java
/** * Encode some attributes as JSON.// w w w .j a v a 2 s .c o m * @param json The JSON object to insert into * @param attributes Collection of attributes */ public void toJson(final JSONObject json, final Attributes attributes) { Attribute attribute = attributes.get(attributeLabel); if (attribute == null) { LOGGER.debug("Missing attribute: " + attributeLabel); // just put an empty entry into the JSON try { if (allowMultiples) { json.put(jsonLabel, new JSONArray()); } else { JSONObject blank = new JSONObject(); blank.put(JSON_LABEL_NETWORK, ""); blank.put(JSON_LABEL_NUMBER, ""); blank.put(JSON_LABEL_EXTENSION, ""); json.put(jsonLabel, blank); } } catch (JSONException e) { logException(Level.ERROR, e); } return; } int numValues = attribute.size(); if (numValues == 0) { LOGGER.error("Attribute " + attributeLabel + " contains no values"); return; } try { if (allowMultiples) { JSONArray values = new JSONArray(); NamingEnumeration<?> valueEnum = attribute.getAll(); while (valueEnum.hasMore()) { String value = valueEnum.next().toString(); JSONObject entry = decodePhoneNumber(value); if (entry == null) { LOGGER.error("Failed to parse telephone number from :" + value); } else { values.put(entry); } } json.put(jsonLabel, values); } else { // expecting only one value if (numValues != 1) { LOGGER.error("Expected single value in attribute " + attributeLabel + ", found " + numValues); return; } String value = attribute.get().toString(); JSONObject entry = decodePhoneNumber(value); if (entry == null) { LOGGER.error("Failed to parse telephone fields from :" + value); } else { json.put(jsonLabel, entry); } } } catch (NamingException e) { logException(Level.ERROR, e); return; } catch (JSONException e) { logException(Level.ERROR, e); return; } }
From source file:org.apache.cxf.sts.claims.LdapClaimsHandler.java
public ProcessedClaimCollection retrieveClaimValues(ClaimCollection claims, ClaimsParameters parameters) { String user = null;/*from w w w . j av a2 s .co m*/ boolean useLdapLookup = false; Principal principal = parameters.getPrincipal(); if (principal instanceof KerberosPrincipal) { KerberosPrincipal kp = (KerberosPrincipal) principal; StringTokenizer st = new StringTokenizer(kp.getName(), "@"); user = st.nextToken(); } else if (principal instanceof X500Principal) { X500Principal x500p = (X500Principal) principal; LOG.warning("Unsupported principal type X500: " + x500p.getName()); return new ProcessedClaimCollection(); } else if (principal != null) { user = principal.getName(); if (user == null) { LOG.warning("User must not be null"); return new ProcessedClaimCollection(); } useLdapLookup = LdapUtils.isDN(user); } else { LOG.warning("Principal is null"); return new ProcessedClaimCollection(); } if (LOG.isLoggable(Level.FINEST)) { LOG.finest("Retrieve claims for user " + user); } Map<String, Attribute> ldapAttributes = null; if (useLdapLookup) { AttributesMapper mapper = new AttributesMapper() { public Object mapFromAttributes(Attributes attrs) throws NamingException { Map<String, Attribute> map = new HashMap<String, Attribute>(); NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll(); while (attrEnum.hasMore()) { Attribute att = attrEnum.next(); map.put(att.getID(), att); } return map; } }; Object result = ldap.lookup(user, mapper); ldapAttributes = CastUtils.cast((Map<?, ?>) result); } else { List<String> searchAttributeList = new ArrayList<String>(); for (Claim claim : claims) { if (getClaimsLdapAttributeMapping().keySet().contains(claim.getClaimType().toString())) { searchAttributeList.add(getClaimsLdapAttributeMapping().get(claim.getClaimType().toString())); } else { if (LOG.isLoggable(Level.FINER)) { LOG.finer("Unsupported claim: " + claim.getClaimType()); } } } String[] searchAttributes = null; searchAttributes = searchAttributeList.toArray(new String[searchAttributeList.size()]); ldapAttributes = LdapUtils.getAttributesOfEntry(ldap, this.userBaseDn, this.getObjectClass(), this.getUserNameAttribute(), user, searchAttributes); } if (ldapAttributes == null || ldapAttributes.size() == 0) { //No result if (LOG.isLoggable(Level.INFO)) { LOG.finest("User '" + user + "' not found"); } return new ProcessedClaimCollection(); } ProcessedClaimCollection claimsColl = new ProcessedClaimCollection(); for (Claim claim : claims) { URI claimType = claim.getClaimType(); String ldapAttribute = getClaimsLdapAttributeMapping().get(claimType.toString()); Attribute attr = ldapAttributes.get(ldapAttribute); if (attr == null) { if (LOG.isLoggable(Level.FINEST)) { LOG.finest("Claim '" + claim.getClaimType() + "' is null"); } } else { ProcessedClaim c = new ProcessedClaim(); c.setClaimType(claimType); c.setPrincipal(principal); StringBuilder claimValue = new StringBuilder(); try { NamingEnumeration<?> list = (NamingEnumeration<?>) attr.getAll(); while (list.hasMore()) { Object obj = list.next(); if (!(obj instanceof String)) { LOG.warning("LDAP attribute '" + ldapAttribute + "' has got an unsupported value type"); break; } String itemValue = (String) obj; if (this.isX500FilterEnabled()) { try { X500Principal x500p = new X500Principal(itemValue); itemValue = x500p.getName(); int index = itemValue.indexOf('='); itemValue = itemValue.substring(index + 1, itemValue.indexOf(',', index)); } catch (Exception ex) { //Ignore, not X500 compliant thus use the whole string as the value } } claimValue.append(itemValue); if (list.hasMore()) { claimValue.append(this.getDelimiter()); } } } catch (NamingException ex) { LOG.warning("Failed to read value of LDAP attribute '" + ldapAttribute + "'"); } c.addValue(claimValue.toString()); // c.setIssuer(issuer); // c.setOriginalIssuer(originalIssuer); // c.setNamespace(namespace); claimsColl.add(c); } } return claimsColl; }
From source file:jndi.view.JndiView.java
/** * @param ctx/*w w w .ja va 2 s . c o m*/ * the Context we're examining * @param path * the path to examine * @param bindings * the {@link NamingEnumeration} of {@link Binding}s * @return List of {@link JndiEntry} * @throws NamingException * on exception */ private List<JndiEntry> examineBindings(final Context ctx, final String path, final NamingEnumeration<Binding> bindings) throws NamingException { if (null == bindings) { throw new NullPointerException("bindings is null!"); } final List<JndiEntry> entries = new ArrayList<JndiEntry>(); while (bindings.hasMore()) { final Binding binding = bindings.next(); final String name = binding.getName(); final String className = binding.getClassName(); logger.finest("name: " + name + " [" + className + "]"); final JndiEntry entry = new JndiEntry(name, className); final Object obj = binding.getObject(); if (obj instanceof Context) { entry.setContext(true); String link = name; if (!path.isEmpty()) { link = path + "/" + name; } entry.setLink(link); } else if (obj instanceof Reference) { final Reference ref = (Reference) obj; entry.setTargetClassName(ref.getClassName()); } else if ("org.glassfish.javaee.services.ResourceProxy".equals(className)) { // SUPPRESS CHECKSTYLE AvoidInlineConditionals final Object lookup = ctx.lookup(path.isEmpty() ? name : path + "/" + name); if (lookup != null) { final String lookedUpClassName = lookup.getClass().getName(); logger.finest("lookup(\"" + name + "\") returned " + lookedUpClassName); entry.setTargetClassName(lookedUpClassName); } } else if ("com.sun.ejb.containers.JavaGlobalJndiNamingObjectProxy".equals(className)) { inspectJndiNamingObjectProxy(entry, obj); } entries.add(entry); } return entries; }
From source file:org.apache.zeppelin.rest.GetUserList.java
/** * function to extract users from Zeppelin LdapRealm */// w w w.ja v a 2 s.c om public List<String> getUserList(LdapRealm r, String searchText) { List<String> userList = new ArrayList<>(); if (LOG.isDebugEnabled()) { LOG.debug("SearchText: " + searchText); } String userAttribute = r.getUserSearchAttributeName(); String userSearchRealm = r.getUserSearchBase(); String userObjectClass = r.getUserObjectClass(); JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory(); try { LdapContext ctx = CF.getSystemLdapContext(); SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); 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()) { LOG.debug("userLowerCase true"); currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase(); } else { LOG.debug("userLowerCase false"); currentUser = (String) attrs.get(userAttribute).get(); } if (LOG.isDebugEnabled()) { LOG.debug("CurrentUser: " + currentUser); } userList.add(currentUser.trim()); } } } catch (Exception e) { LOG.error("Error retrieving User list from Ldap Realm", e); } return userList; }
From source file:org.cloudfoundry.identity.uaa.ldap.extension.SpringSecurityLdapTemplate.java
/** * Performs an LDAP compare operation of the value of an attribute for a particular directory entry. * * @param dn the entry who's attribute is to be used * @param attributeName the attribute who's value we want to compare * @param value the value to be checked against the directory value * * @return true if the supplied value matches that in the directory *//* ww w.j a v a 2 s . c o m*/ public boolean compare(final String dn, final String attributeName, final Object value) { final String comparisonFilter = "(" + attributeName + "={0})"; class LdapCompareCallback implements ContextExecutor { public Object executeWithContext(DirContext ctx) throws NamingException { SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(NO_ATTRS); ctls.setSearchScope(SearchControls.OBJECT_SCOPE); NamingEnumeration<SearchResult> results = ctx.search(dn, comparisonFilter, new Object[] { value }, ctls); Boolean match = Boolean.valueOf(results.hasMore()); LdapUtils.closeEnumeration(results); return match; } } Boolean matches = (Boolean) executeReadOnly(new LdapCompareCallback()); return matches.booleanValue(); }
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
/** * Test to make sure anonymous binds are allowed on the RootDSE even when disabled * in general when going through the wire protocol. * * @throws Exception if anything goes wrong *///from w w w .ja v a 2s.c o m @Test public void testEnableAnonymousBindsOnRootDse() throws Exception { getLdapServer().getDirectoryService().setAllowAnonymousAccess(true); // Use the SUN JNDI provider to hit server port and bind as anonymous Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort())); env.put(Context.SECURITY_AUTHENTICATION, "none"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); InitialDirContext ctx = new InitialDirContext(env); SearchControls cons = new SearchControls(); cons.setSearchScope(SearchControls.OBJECT_SCOPE); NamingEnumeration<SearchResult> list = ctx.search("", "(objectClass=*)", cons); SearchResult result = null; if (list.hasMore()) { result = list.next(); } assertFalse(list.hasMore()); list.close(); assertNotNull(result); assertEquals("", result.getName().trim()); }
From source file:io.apiman.gateway.engine.policies.BasicAuthLDAPTest.java
@Test @Ignore// www. j a v a 2s . c o m public void testLdap() throws Exception { DirContext ctx = createContext(); Assert.assertNotNull(ctx); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> result = ctx.search("o=apiman", "(ObjectClass=*)", controls); System.out.println(" ==== Search Results ===="); while (result.hasMore()) { SearchResult entry = result.next(); System.out.println(" ===> " + entry.getName()); } }
From source file:org.talend.dataquality.email.checkerImpl.CallbackMailServerCheckerImpl.java
private List<String> getMX(String hostName) throws NamingException { // Perform a DNS lookup for MX records in the domain Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" }); //$NON-NLS-1$ Attribute attr = attrs.get("MX"); //$NON-NLS-1$ List<String> res = new ArrayList<String>(); // if we don't have an MX record, try the machine itself if ((attr == null) || (attr.size() == 0)) { attrs = ictx.getAttributes(hostName, new String[] { "A" }); //$NON-NLS-1$ attr = attrs.get("A"); //$NON-NLS-1$ if (attr == null) { if (LOG.isInfoEnabled()) { LOG.info(HEADER + "No match for hostname '" + hostName + "'"); //$NON-NLS-1$ //$NON-NLS-2$ }//from w w w . j a v a2 s. c o m return res; } } // we have machines to try. Return them as an array list NamingEnumeration<?> en = attr.getAll(); Map<Integer, String> map = new TreeMap<Integer, String>(); while (en.hasMore()) { String mailhost; String x = (String) en.next(); String f[] = x.split(" "); //$NON-NLS-1$ Integer key = 0; if (f.length == 1) { mailhost = f[0]; } else if (f[1].endsWith(".")) { //$NON-NLS-1$ mailhost = f[1].substring(0, f[1].length() - 1); key = Integer.valueOf(f[0]); } else { mailhost = f[1]; key = Integer.valueOf(f[0]); } map.put(key, mailhost); } // NOTE: We SHOULD take the preference into account to be absolutely // correct. Iterator<Integer> keyInterator = map.keySet().iterator(); while (keyInterator.hasNext()) { res.add(map.get(keyInterator.next())); } return res; }
From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java
private ArrayList<String> addAttributeValues(String attrId, Attributes attrs, ArrayList<String> values) throws NamingException { if (attrId == null || attrs == null) { return values; }/*from w w w . ja v a 2 s .c o m*/ if (values == null) { values = new ArrayList<String>(); } Attribute attr = attrs.get(attrId); if (attr == null) { return (values); } NamingEnumeration e = attr.getAll(); while (e.hasMore()) { String value = (String) e.next(); values.add(value); } return values; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets all persons for a group/*from w ww. j a v a 2 s . com*/ * * @param groups * @param siteBean * @param filter * @return * @throws Exception */ static List<TPersonBean> getAllLdapUsersDescendants(String providerUrl, String bindDN, String bindPassword, String loginAttributeName, String filter) throws Exception { List<TPersonBean> personBeans = new ArrayList<TPersonBean>(); if (filter == null || "".equals(filter) || "*".equals(filter)) { filter = loginAttributeName + "=*"; } int recordCount = 0; SearchControls ctls = null; LdapContext ctx = null; try { ctx = getInitialContext(providerUrl, bindDN, bindPassword); if (ctx == null) { return personBeans; } // Activate paged results int pageSize = 5; // TODO replace for GROOVY ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; String searchStr = "(" + filter + ")"; // Control the search ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers() + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle // anyways if (ldapMap == null || ldapMap.isEmpty()) { LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!"); return personBeans; } String firstNameAttributeName = ldapMap.get("firstName"); String lastNameAttributName = ldapMap.get("lastName"); String emailAttributeName = ldapMap.get("email"); String phoneAttributName = ldapMap.get("phone"); byte[] cookie = null; // TODO replace for GROOVY cookie = new byte[] {}; // cookie = [] as byte[]; while (cookie != null) { NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls); while (results != null && results.hasMore()) { SearchResult sr = (SearchResult) results.next(); TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName, emailAttributeName, phoneAttributName); if (personBean != null) { personBeans.add(personBean); ++recordCount; } } // Examine the paged results control response Control[] controls = ctx.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total + ") *****************\n"); } else { LOGGER.debug( "***************** END-OF-PAGE " + "(total: unknown) ***************\n"); } cookie = prrc.getCookie(); } } } else { LOGGER.debug("No controls were sent from the server"); } // Re-activate paged results // TODO replace for GROOVY ctx.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } } catch (SizeLimitExceededException sle) { if (recordCount < ctls.getCountLimit()) { LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server."); LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with " + sle.getMessage()); LOGGER.error( "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter."); } else { LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server (" + recordCount + ")."); LOGGER.error( "You have to get more user licenses for Genji or specify a more suitable search base or filter."); } LOGGER.error("The LDAP synchronization is most likely incomplete."); } catch (NamingException e) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException ie) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(ie)); } finally { if (ctx != null) { ctx.close(); } } return personBeans; }