Java Code Examples for javax.naming.NamingEnumeration#hasMore()

The following examples show how to use javax.naming.NamingEnumeration#hasMore() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EntityService.java    From cukes with Apache License 2.0 8 votes vote down vote up
public List<Attributes> searchByFilter(String dn, String filter){
    try {
        LdapContext context = connectionService.getContext();
        NamingEnumeration<SearchResult> searchResults = context.search(dn, filter, new SearchControls());
        List<Attributes> attributesList = new ArrayList<>();
        while (searchResults.hasMore()) {
            SearchResult searchResult = searchResults.next();
            attributesList.add(searchResult.getAttributes());
        }
        return attributesList;
    } catch (NamingException ex) {
        throw new CukesRuntimeException(ex);
    } finally {
        connectionService.close();
    }
}
 
Example 2
Source File: LDAPCertStore.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the values for the given attribute. If the attribute is null
 * or does not contain any values, a zero length byte array is
 * returned. NOTE that it is assumed that all values are byte arrays.
 */
private byte[][] getAttributeValues(Attribute attr)
        throws NamingException {
    byte[][] values;
    if (attr == null) {
        values = BB0;
    } else {
        values = new byte[attr.size()][];
        int i = 0;
        NamingEnumeration<?> enum_ = attr.getAll();
        while (enum_.hasMore()) {
            Object obj = enum_.next();
            if (debug != null) {
                if (obj instanceof String) {
                    debug.println("LDAPCertStore.getAttrValues() "
                        + "enum.next is a string!: " + obj);
                }
            }
            byte[] value = (byte[])obj;
            values[i++] = value;
        }
    }
    return values;
}
 
Example 3
Source File: LDAPCertStore.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the values for the given attribute. If the attribute is null
 * or does not contain any values, a zero length byte array is
 * returned. NOTE that it is assumed that all values are byte arrays.
 */
private byte[][] getAttributeValues(Attribute attr)
        throws NamingException {
    byte[][] values;
    if (attr == null) {
        values = BB0;
    } else {
        values = new byte[attr.size()][];
        int i = 0;
        NamingEnumeration<?> enum_ = attr.getAll();
        while (enum_.hasMore()) {
            Object obj = enum_.next();
            if (debug != null) {
                if (obj instanceof String) {
                    debug.println("LDAPCertStore.getAttrValues() "
                        + "enum.next is a string!: " + obj);
                }
            }
            byte[] value = (byte[])obj;
            values[i++] = value;
        }
    }
    return values;
}
 
Example 4
Source File: LdapAuthenticator.java    From dropwizard-auth-ldap with Apache License 2.0 6 votes vote down vote up
private Set<String> getGroupMembershipsIntersectingWithRestrictedGroups(AutoclosingLdapContext context, String userName) throws NamingException {

        userName = userNameBaseOnGroupClass(userName);

        final String filter = String.format("(&(%s=%s)(objectClass=%s))", configuration.getGroupMembershipAttribute(), userName, configuration.getGroupClassName());
        final NamingEnumeration<SearchResult> result = context.search(configuration.getGroupFilter(), filter, new SearchControls());

        ImmutableSet.Builder<String> overlappingGroups = ImmutableSet.builder();
        try {
            while (result.hasMore()) {
                SearchResult next = result.next();
                if (next.getAttributes() != null && next.getAttributes().get(configuration.getGroupNameAttribute()) != null) {
                    String group = (String) next.getAttributes().get(configuration.getGroupNameAttribute()).get(0);
                    if (configuration.getRestrictToGroups().isEmpty() ||
                            configuration.getRestrictToGroups().contains(group)) {
                        overlappingGroups.add(group);
                    }
                }
            }
            return overlappingGroups.build();
        } finally {
            result.close();
        }
    }
 
Example 5
Source File: Rdn.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
/**
 * Constructs an Rdn from the given attribute set. See
 * {@link javax.naming.directory.Attributes Attributes}.
 * <p>
 * The string attribute values are not interpreted as
 * <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>
 * formatted RDN strings. That is, the values are used
 * literally (not parsed) and assumed to be unescaped.
 *
 * @param attrSet The non-null and non-empty attributes containing
 * type/value mappings.
 * @throws InvalidNameException If contents of <tt>attrSet</tt> cannot
 *          be used to construct a valid RDN.
 */
public Rdn(Attributes attrSet) throws InvalidNameException {
    if (attrSet.size() == 0) {
        throw new InvalidNameException("Attributes cannot be empty");
    }
    entries = new ArrayList<>(attrSet.size());
    NamingEnumeration<? extends Attribute> attrs = attrSet.getAll();
    try {
        for (int nEntries = 0; attrs.hasMore(); nEntries++) {
            RdnEntry entry = new RdnEntry();
            Attribute attr = attrs.next();
            entry.type = attr.getID();
            entry.value = attr.get();
            entries.add(nEntries, entry);
        }
    } catch (NamingException e) {
        InvalidNameException e2 = new InvalidNameException(
                                    e.getMessage());
        e2.initCause(e);
        throw e2;
    }
    sort(); // arrange entries for comparison
}
 
Example 6
Source File: LdapBackend.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
public List<String> getAttributes(Entry entry, String attName) {
    List<String> values = new ArrayList<>();
    javax.naming.directory.Attribute att = AttributeUtils.toAttributes(entry).get(attName);
    if (att == null) {
        return values;
    }

    try {
        NamingEnumeration<?> list = att.getAll();
        while (list.hasMore()) {
            values.add(list.next().toString());
        }
    } catch (NamingException e) {
        log.warn("Error while processing LDAP attribute {}, result could be incomplete!", attName, e);
    }
    return values;
}
 
Example 7
Source File: TestNamingContext.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain;UTF-8");
    PrintWriter out = resp.getWriter();

    try {
        Context ctx = new InitialContext();
        NamingEnumeration<Binding> enm =
            ctx.listBindings("java:comp/env/list");
        while (enm.hasMore()) {
            Binding b = enm.next();
            out.print(b.getObject().getClass().getName());
        }
    } catch (NamingException ne) {
        ne.printStackTrace(out);
    }
}
 
Example 8
Source File: EmbeddedLdapRuleTest.java    From submarine with Apache License 2.0 6 votes vote down vote up
@Test
public void testList() throws Exception {
  final Context context = embeddedLdapRule.context();
  NamingEnumeration list = context.list("ou=semi-people,dc=zapodot,dc=org");

  while (list.hasMore()){
    NameClassPair nc = (NameClassPair) list.next();
    String user, group = null;
    ArrayList user_sp = new ArrayList();
    StringTokenizer user_info = new StringTokenizer(nc.getNameInNamespace(), ",");

    while (user_info.hasMoreTokens()){
      user_sp.add(user_info.nextToken());
    }
    user = user_sp.get(0).toString().substring(3, user_sp.get(0).toString().length());
    group = user_sp.get(1).toString().substring(3, user_sp.get(1).toString().length());

    LOG.info(user);

    assertEquals((user + "," + group) , "Fake-Eros,semi-people");
  }

  context.close();
}
 
Example 9
Source File: TestNamingContext.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain;UTF-8");
    PrintWriter out = resp.getWriter();

    try {
        Context ctx = new InitialContext();
        NamingEnumeration<Binding> enm =
            ctx.listBindings("java:comp/env/list");
        while (enm.hasMore()) {
            Binding b = enm.next();
            out.print(b.getObject().getClass().getName());
        }
    } catch (NamingException ne) {
        ne.printStackTrace(out);
    }
}
 
Example 10
Source File: LDAPSecurityTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testRunning() throws Exception {
   Hashtable<String, String> env = new Hashtable<>();
   env.put(Context.PROVIDER_URL, "ldap://localhost:1024");
   env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
   env.put(Context.SECURITY_AUTHENTICATION, "simple");
   env.put(Context.SECURITY_PRINCIPAL, PRINCIPAL);
   env.put(Context.SECURITY_CREDENTIALS, CREDENTIALS);
   DirContext ctx = new InitialDirContext(env);

   HashSet<String> set = new HashSet<>();

   NamingEnumeration<NameClassPair> list = ctx.list("ou=system");

   while (list.hasMore()) {
      NameClassPair ncp = list.next();
      set.add(ncp.getName());
   }

   Assert.assertTrue(set.contains("uid=admin"));
   Assert.assertTrue(set.contains("ou=users"));
   Assert.assertTrue(set.contains("ou=groups"));
   Assert.assertTrue(set.contains("ou=configuration"));
   Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot"));

   ctx.close();
}
 
Example 11
Source File: LdapService.java    From eagle with Apache License 2.0 5 votes vote down vote up
public Map<String, String> getUserInfo(int id, String userName) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Ldap get user information for id:" + id + ", username:" + userName);
    }
    DirContext ctx = getDirContext(id);
    Map<String, String> infos = new HashMap<String, String>();

    if (ctx != null) {
        try {
            SearchControls sc = getSearchControl();
            String filter = "(&(objectClass=user)(sAMAccountName=" + userName + "))";
            NamingEnumeration<?> results = ctx.search("OU=Accounts_User,DC=corp,DC=company1,DC=com", filter, sc);

            while (results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                Attributes attrs = sr.getAttributes();

                for (NamingEnumeration<?> ae = attrs.getAll(); ae.hasMoreElements(); ) {
                    Attribute attr = (Attribute) ae.next();
                    String attrId = attr.getID();
                    for (NamingEnumeration<?> vals = attr.getAll(); vals.hasMore(); ) {
                        String thing = vals.next().toString();
                        infos.put(attrId, thing);
                    }
                }
            }
        } catch (NamingException e) {
            LOG.error("LDAP authentication failed with exception: " + e.getMessage(), e);
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug(infos.toString());
    }
    return infos;
}
 
Example 12
Source File: ActiveDirectoryGroupRealm.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public List<String> searchForUserName(String containString, LdapContext ldapContext,
    int numUsersToFetch)
        throws NamingException {
  List<String> userNameList = new ArrayList<>();

  SearchControls searchCtls = new SearchControls();
  searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  searchCtls.setCountLimit(numUsersToFetch);

  String searchFilter = String.format("(&(objectClass=*)(%s=*%s*))", this.getUserSearchAttributeName(), containString);

  Object[] searchArguments = new Object[]{containString};

  NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments,
      searchCtls);

  while (answer.hasMoreElements()) {
    SearchResult sr = (SearchResult) answer.next();

    if (log.isDebugEnabled()) {
      log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]");
    }

    Attributes attrs = sr.getAttributes();
    if (attrs != null) {
      NamingEnumeration ae = attrs.getAll();
      while (ae.hasMore()) {
        Attribute attr = (Attribute) ae.next();
        if (attr.getID().toLowerCase().equals(this.getUserSearchAttributeName().toLowerCase())) {
          userNameList.addAll(LdapUtils.getAllAttributeValues(attr));
        }
      }
    }
  }
  return userNameList;
}
 
Example 13
Source File: JNDIProviderImpl.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Map<String, List<String>> parseAttributeValues(
        final NamingEnumeration attributeEnum,
        final boolean returnAllValues
)
        throws NamingException
{
    final Map<String, List<String>> attrValues = new HashMap<String, List<String>>();
    if ( attributeEnum != null && attributeEnum.hasMore() )
    {
        while ( attributeEnum.hasMore() )
        {
            final Attribute loopAttribute = ( Attribute ) attributeEnum.next();
            final String attrName = loopAttribute.getID();
            final List<String> valueList = new ArrayList<String>();
            for ( NamingEnumeration attrValueEnum = loopAttribute.getAll(); attrValueEnum.hasMore(); )
            {
                final Object value = attrValueEnum.next();
                valueList.add( value.toString() );
                if ( !returnAllValues )
                {
                    attrValueEnum.close();
                    break;
                }
            }
            attrValues.put( attrName, Collections.unmodifiableList( valueList ) );
        }
    }
    return Collections.unmodifiableMap( attrValues );
}
 
Example 14
Source File: LdapService.java    From Eagle with Apache License 2.0 5 votes vote down vote up
public Map<String, String> getUserInfo(int id, String userName) {
    if(LOG.isDebugEnabled()) LOG.debug("Ldap get user information for id:"+id+", username:"+userName);
    DirContext ctx = getDirContext(id);
    Map<String, String> infos = new HashMap<String, String>();

    if (ctx != null) {
        try {
            SearchControls sc = getSearchControl();
            String filter = "(&(objectClass=user)(sAMAccountName=" + userName + "))";
            NamingEnumeration<?> results = ctx.search("OU=Accounts_User,DC=corp,DC=company1,DC=com", filter, sc);

            while (results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                Attributes attrs = sr.getAttributes();

                for (NamingEnumeration<?> ae = attrs.getAll(); ae.hasMoreElements();) {
                    Attribute attr = (Attribute) ae.next();
                    String attrId = attr.getID();
                    for (NamingEnumeration<?> vals = attr.getAll(); vals.hasMore();) {
                        String thing = vals.next().toString();
                        infos.put(attrId, thing);
                    }
                }
            }
        } catch (NamingException e) {
            LOG.error("LDAP authentication failed with exception: "+e.getMessage(),e);
        }
    }

    if(LOG.isDebugEnabled()) LOG.debug(infos.toString());
    return infos;
}
 
Example 15
Source File: Group2Ldap.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public boolean update(Groups group)  throws Exception{
	logger.info("update");
	try {
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(cn="+group.getName()+")", constraints);
		String oldDn="";
		String rdn="";
		if (results == null || !results.hasMore()) {
			return create(group);
		}else{
			SearchResult sr = (SearchResult) results.next();
			oldDn =sr.getNameInNamespace();
			String[] dnSplit=oldDn.split(",");
			rdn=oldDn.substring(oldDn.indexOf(","), oldDn.length());
			
			String groupName=dnSplit[0].split("=")[1];
			if(group.getName()!=groupName){
				String newDn="cn="+group.getName()+","+rdn;
				ldapUtils.getCtx().rename(oldDn, newDn);
				ModificationItem[] modificationItems = new ModificationItem[1];
				modificationItems[0]=new ModificationItem(DirContext.REMOVE_ATTRIBUTE,new BasicAttribute("cn",groupName));
				ldapUtils.getCtx().modifyAttributes(newDn, modificationItems);
			}
		}
		
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return true;
}
 
Example 16
Source File: JndiBinding.java    From javamelody with Apache License 2.0 5 votes vote down vote up
public static List<JndiBinding> listBindings(Context context, String path)
		throws NamingException {
	final String normalizedPath = normalizePath(path);
	final String jndiName;
	if (Parameters.getServletContext().getServerInfo().contains("WebLogic")) {
		// path + '/' nécessaire pour WebLogic 10.3.1.0 mais pas supporté dans JBoss
		jndiName = JNDI_PREFIX + normalizedPath + '/';
	} else {
		jndiName = JNDI_PREFIX + normalizedPath;
	}
	final List<JndiBinding> result = new ArrayList<JndiBinding>();
	final NamingEnumeration<Binding> enumeration = context.listBindings(jndiName);
	try {
		while (enumeration.hasMore()) {
			try {
				final Binding binding = enumeration.next();
				final JndiBinding jndiBinding = createJndiBinding(normalizedPath, binding);
				// si on veux corriger http://java.net/jira/browse/GLASSFISH-12831
				// sous glassfish 3.0.1 et non 3.1, les bindings d'un contexte contienne le contexte lui-même
				//		if (jndiBinding.getName().isEmpty()) {
				//			return;
				//		}
				result.add(jndiBinding);
			} catch (final Exception e) {
				// catch Exception et non catch NamingException car glassfish 3.1 par exemple
				// lance parfois des RuntimeException encapsulant des NamingException lors du next()
				continue;
			}
		}
	} finally {
		// Comme indiqué dans la javadoc enumeration.close() n'est pas nécessaire après que hasMore()
		// a retourné false. De plus, cela provoquerait une exception dans glassfish 3.0.1
		// "javax.naming.OperationNotSupportedException: close() not implemented"
		// enumeration.close();

		context.close();
	}
	return result;
}
 
Example 17
Source File: BasicAttributes.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determines whether this <tt>BasicAttributes</tt> is equal to another
 * <tt>Attributes</tt>
 * Two <tt>Attributes</tt> are equal if they are both instances of
 * <tt>Attributes</tt>,
 * treat the case of attribute IDs the same way, and contain the
 * same attributes. Each <tt>Attribute</tt> in this <tt>BasicAttributes</tt>
 * is checked for equality using <tt>Object.equals()</tt>, which may have
 * be overridden by implementations of <tt>Attribute</tt>).
 * If a subclass overrides <tt>equals()</tt>,
 * it should override <tt>hashCode()</tt>
 * as well so that two <tt>Attributes</tt> instances that are equal
 * have the same hash code.
 * @param obj the possibly null object to compare against.
 *
 * @return true If obj is equal to this BasicAttributes.
 * @see #hashCode
 */
public boolean equals(Object obj) {
    if ((obj != null) && (obj instanceof Attributes)) {
        Attributes target = (Attributes)obj;

        // Check case first
        if (ignoreCase != target.isCaseIgnored()) {
            return false;
        }

        if (size() == target.size()) {
            Attribute their, mine;
            try {
                NamingEnumeration<?> theirs = target.getAll();
                while (theirs.hasMore()) {
                    their = (Attribute)theirs.next();
                    mine = get(their.getID());
                    if (!their.equals(mine)) {
                        return false;
                    }
                }
            } catch (NamingException e) {
                return false;
            }
            return true;
        }
    }
    return false;
}
 
Example 18
Source File: SchemaViewer.java    From spring-ldap with Apache License 2.0 4 votes vote down vote up
private static void printSchema(String contextName, DirContext schemaContext) throws NameNotFoundException,
        NamingException {

    outstream.println();

    NamingEnumeration<NameClassPair> schemaList = schemaContext.list(contextName);

    while (schemaList.hasMore()) {
        NameClassPair ncp = schemaList.nextElement();

        printObject(contextName, ncp.getName(), schemaContext);
        outstream.println();
    }

    outstream.println();
}
 
Example 19
Source File: UserSync.java    From ranger with Apache License 2.0 4 votes vote down vote up
public void getAllGroups(LdapContext ldapContext) throws Throwable {
    int noOfGroups = 0;
    Attribute groupNameAttr;
    Attribute groupMemberAttr;
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    SearchControls groupSearchControls = new SearchControls();
    groupSearchControls.setSearchScope(config.getGroupSearchScope());
    Set<String> groupSearchAttributes = new HashSet<>();
    groupSearchAttributes.add(groupNameAttrName);
    groupSearchAttributes.add(groupMemberName);
    groupSearchAttributes.add("distinguishedName");
    groupSearchControls.setReturningAttributes(groupSearchAttributes.toArray(
            new String[groupSearchAttributes.size()]));

    String extendedGroupSearchFilter= "(objectclass=" + groupObjClassName + ")";
    if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) {
        String customFilter = groupSearchFilter.trim();
        if (!customFilter.startsWith("(")) {
            customFilter = "(" + customFilter + ")";
        }
        extendedGroupSearchFilter = "(&" + extendedGroupSearchFilter + customFilter + ")";
    }

    try {

        groupSearchResultEnum = ldapContext.search(groupSearchBase, extendedGroupSearchFilter,
                groupSearchControls);

        logFile.println("\nINFO: First 20 Groups and associated Users are:");

        while (groupSearchResultEnum.hasMore()) {
            final SearchResult groupEntry = groupSearchResultEnum.next();
            if (groupEntry == null) {
                continue;
            }
            Attributes groupAttributes = groupEntry.getAttributes();
            if (groupAttributes == null) {
                logFile.println("WARN: Attributes missing for entry " + groupEntry.getNameInNamespace());
                continue;
            }

            groupMemberAttr = groupAttributes.get(groupMemberName);

            Set<String> users = new HashSet<>();
            if (groupMemberAttr != null) {
                NamingEnumeration<?> userEnum = groupMemberAttr.getAll();
                while (userEnum.hasMore()) {
                    String userRes = userEnum.next().toString();
                    users.add(userRes);
                }
            }

            groupNameAttr = groupAttributes.get(groupNameAttrName);
            if (noOfGroups < 20) {
                logFile.println("Group name: " + groupNameAttr.get().toString() + ", Users: " + users);
            }
            noOfGroups++;
        }

        logFile.println("\nINFO: Total no. of groups = " + noOfGroups);

    } catch (NamingException ne) {
        String msg = "Exception occured while retreiving groups\n";
        if ((config.getGroupNameAttribute() != null && !config.getGroupNameAttribute().isEmpty()) ||
                (config.getGroupObjectClass() != null && !config.getGroupObjectClass().isEmpty()) ||
                (config.getUserGroupMemberAttributeName() != null && !config.getUserGroupMemberAttributeName().isEmpty()) ||
                (config.getGroupSearchBase() != null && !config.getGroupSearchBase().isEmpty()) ||
                (config.getGroupSearchFilter() != null && !config.getGroupSearchFilter().isEmpty())) {
            throw new Exception("Please verify values for:\n ranger.usersync.group.memberattributename\n " +
                    "ranger.usersync.group.nameattribute\n" +
                    "ranger.usersync.group.objectclass\n" +
                    "ranger.usersync.group.searchbase\n" +
                    "ranger.usersync.group.searchfilter\n");
        } else {
            throw new Exception(msg + ne);
        }
    } finally {

        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
    }
}
 
Example 20
Source File: BasicAttributes.java    From jdk8u-jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Calculates the hash code of this BasicAttributes.
 *<p>
 * The hash code is computed by adding the hash code of
 * the attributes of this object. If this BasicAttributes
 * ignores case of its attribute IDs, one is added to the hash code.
 * If a subclass overrides <tt>hashCode()</tt>,
 * it should override <tt>equals()</tt>
 * as well so that two <tt>Attributes</tt> instances that are equal
 * have the same hash code.
 *
 * @return an int representing the hash code of this BasicAttributes instance.
 * @see #equals
 */
public int hashCode() {
    int hash = (ignoreCase ? 1 : 0);
    try {
        NamingEnumeration<?> all = getAll();
        while (all.hasMore()) {
            hash += all.next().hashCode();
        }
    } catch (NamingException e) {}
    return hash;
}