javax.naming.NamingEnumeration Java Examples

The following examples show how to use javax.naming.NamingEnumeration. 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: UserInfo2Activedirectory.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public boolean delete(UserInfo userInfo) throws Exception{
	try {
		String dn=null;
		SearchControls searchControls = new SearchControls();
		searchControls.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(sAMAccountName="+userInfo.getUsername()+")", searchControls);
		if (results == null || !results.hasMore()) {
			
		}else{
			SearchResult sr = (SearchResult) results.next();
			dn =sr.getNameInNamespace();
			logger.debug("delete dn : "+dn);
			ldapUtils.getCtx().destroySubcontext(dn);
		}
		
		ldapUtils.close();
		super.delete(userInfo);
	} catch (NamingException e) {
		e.printStackTrace();
	} 
	return true;
}
 
Example #2
Source File: LdapRepository.java    From library with Apache License 2.0 6 votes vote down vote up
/**
 * Simple version of {@link #listBy(LdapSearchOption, String, Object...)}  but this one will not map the return
 * attributes and let you do that and will not take an {@link LdapSearchOption} as template for search
 *
 * @param filter to be applied
 * @param parameters to be applied to the filter
 * @return a {@link List} of {@link Attributes} found
 */
public List<Attributes> listBy(String filter, Object... parameters) {

    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    final List<Attributes> attributes = new ArrayList<>();

    try {
        final LdapContext context = this.factory.getSystemLdapContext();

        final NamingEnumeration<SearchResult> answer = context.search(this.baseDN, filter, parameters, searchControls);

        while (answer.hasMoreElements()) {
            final SearchResult searchResult = answer.nextElement();
            attributes.add(searchResult.getAttributes());
        }
    } catch (NamingException ex) {
        throw new BusinessLogicException("error.ldap.cant-search-for-users", ex);
    }
    return attributes;
}
 
Example #3
Source File: Rdn.java    From openjdk-jdk9 with GNU General Public License v2.0 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 {@code attrSet} 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 #4
Source File: UserServiceImpl.java    From seppb with MIT License 6 votes vote down vote up
/**
 * 获取对应账户的用户名 (通过account获取userName)
 * 该方法在用户名密码验证失败后会抛出异常,根据异常判断用户名密码是否正确,用户是否存在
 *
 * @param account
 * @param ctx
 * @return
 * @throws NamingException
 */
private String applyUserName(String account, LdapContext ctx) throws NamingException {
	String userName = null;
	SearchControls searchControls = new SearchControls();
	searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
	searchControls.setReturningAttributes(new String[]{"uid", "userPassword", "displayName", "cn", "sn", "mail", "description"});
	String searchFilter = String.format(SEARCH_FILTER, account, account, account);
	NamingEnumeration<SearchResult> answer = ctx.search("DC=purang,DC=com", searchFilter, searchControls);
	while (answer.hasMoreElements()) {
		SearchResult sr = answer.next();
		String[] qResult = sr.getName().split(",");
		if (qResult.length > 1) {
			userName = qResult[0].split("=")[1];
		}
	}
	return userName;
}
 
Example #5
Source File: LdapTemplateSortedSearchITest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
public void testSearch_SortControl() {
    SearchExecutor searchExecutor = new SearchExecutor() {
        public NamingEnumeration executeSearch(DirContext ctx)
                throws NamingException {
            return ctx.search(BASE, FILTER_STRING, searchControls);
        }
    };
    SortControlDirContextProcessor requestControl;

    // Prepare for first search
    requestControl = new SortControlDirContextProcessor("cn");
    tested.search(searchExecutor, callbackHandler, requestControl);
    int resultCode = requestControl.getResultCode();
    boolean sorted = requestControl.isSorted();
    assertThat("Search result should have been sorted: " + resultCode, sorted).isTrue();
    List list = callbackHandler.getList();
    assertSortedList(list);
}
 
Example #6
Source File: GUISSOLdapClient.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private List<String> formatUserEnName(SearchResult sResult) {

    if (null == sResult) {
        return Collections.emptyList();
    }

    List<String> result = new ArrayList<String>();
    try {
        String memberKey = ldapConfig.get("memberKey");
        NamingEnumeration namingEnumeration = sResult.getAttributes().getAll();
        while (namingEnumeration.hasMoreElements()) {
            Attribute attr = (Attribute) namingEnumeration.next();
            String attrId = attr.getID();
            if (memberKey.equals(attrId)) {
                List<String> userEnNames = formatUserEnName(attr);
                result.addAll(userEnNames);
            }
        }

    }
    catch (Exception e) {
        loggerError("formatUserEnName 619", "", e);
    }
    return result;
}
 
Example #7
Source File: LDAPCertStore.java    From jdk8u_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 #8
Source File: LdapSender.java    From iaf with Apache License 2.0 6 votes vote down vote up
private XmlBuilder searchResultsToXml(NamingEnumeration entries)
	throws NamingException {
	
	XmlBuilder entriesElem = new XmlBuilder("entries");
	int row=0;
	while ((getMaxEntriesReturned()==0 || row<getMaxEntriesReturned()) && entries.hasMore()) {
		SearchResult searchResult = (SearchResult) entries.next();
		XmlBuilder entryElem = new XmlBuilder("entry");
		 
		entryElem.addAttribute("name", searchResult.getName());
		entryElem.addSubElement(attributesToXml(searchResult.getAttributes()));
		
		entriesElem.addSubElement(entryElem);
		row++;
	}
	return entriesElem;
}
 
Example #9
Source File: HTTPContext.java    From oodt with Apache License 2.0 6 votes vote down vote up
public NamingEnumeration listBindings(String name) throws NamingException {
	if (name.length() > 0) {
	  throw new NotContextException("Subcontexts not supported");
	}
	return new NamingEnumeration() {
		public void close() {}
		public boolean hasMore() {
			return false;
		}
		public Object next() {
			throw new NoSuchElementException();
		}
		public boolean hasMoreElements() {
			return hasMore();
		}
		public Object nextElement() {
			return next();
		}
	};
}
 
Example #10
Source File: LegacyLDAPSecuritySettingPluginTest.java    From activemq-artemis with Apache License 2.0 6 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"));
}
 
Example #11
Source File: RetryingContext.java    From james-project with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public NamingEnumeration<Binding> listBindings(final Name name) throws NamingException {
    return (NamingEnumeration<Binding>) new LoggingRetryHandler(DEFAULT_EXCEPTION_CLASSES,
            this, schedule, maxRetries) {

        @Override
        public Object operation() throws NamingException {
            return getDelegate().listBindings(name);
        }
    }.perform();
}
 
Example #12
Source File: ParallelizeTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
    System.out.println("ParallelizeAntRunnerTest.MyContextFactory.getInitialContext()");
    InitialContext mockedInitialContext = PowerMockito.mock(InitialContext.class);
    NamingEnumeration<NameClassPair> mockedEnumeration = PowerMockito.mock(NamingEnumeration.class);
    // Look at this again ...
    PowerMockito.mockStatic(NamingEnumeration.class);
    //
    PowerMockito.when(mockedEnumeration.hasMore()).thenReturn(true, true, true, true, false);
    PowerMockito.when(mockedEnumeration.next()).thenReturn(
            new NameClassPair("data.dir", String.class.getName()),
            new NameClassPair("parallelize", String.class.getName()),
            new NameClassPair("mutant.coverage", String.class.getName()),
            new NameClassPair("ant.home", String.class.getName())//
    );

    PowerMockito.when(mockedInitialContext.toString()).thenReturn("Mocked Initial Context");
    PowerMockito.when(mockedInitialContext.list("java:/comp/env")).thenReturn(mockedEnumeration);

    Context mockedEnvironmentContext = PowerMockito.mock(Context.class);
    PowerMockito.when(mockedInitialContext.lookup("java:/comp/env")).thenReturn(mockedEnvironmentContext);

    PowerMockito.when(mockedEnvironmentContext.lookup("mutant.coverage")).thenReturn("enabled");
    // FIXME
    PowerMockito.when(mockedEnvironmentContext.lookup("parallelize")).thenReturn("enabled");

    PowerMockito.when(mockedEnvironmentContext.lookup("data.dir"))
            .thenReturn(codedefendersHome.getAbsolutePath());

    PowerMockito.when(mockedEnvironmentContext.lookup("ant.home")).thenReturn("/usr/local");

    return mockedInitialContext;
}
 
Example #13
Source File: JNDIRealm.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Add values of a specified attribute to a list
 *
 * @param attrId Attribute name
 * @param attrs Attributes containing the new values
 * @param values ArrayList containing values found so far
 *
 * @exception NamingException if a directory server error occurs
 */
private ArrayList<String> addAttributeValues(String attrId,
                                     Attributes attrs,
                                     ArrayList<String> values)
    throws NamingException{

    if (containerLog.isTraceEnabled())
        containerLog.trace("  retrieving values for attribute " + attrId);
    if (attrId == null || attrs == null)
        return values;
    if (values == null)
        values = new ArrayList<String>();
    Attribute attr = attrs.get(attrId);
    if (attr == null)
        return values;
    NamingEnumeration<?> e = attr.getAll();
    try {
        while(e.hasMore()) {
            String value = (String)e.next();
            values.add(value);
        }
    } catch (PartialResultException ex) {
        if (!adCompat)
            throw ex;
    } finally {
        e.close();
    }
    return values;
}
 
Example #14
Source File: ContinuationDirContext.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(Name name,
                            String filterExpr,
                            Object[] args,
                            SearchControls cons)
throws NamingException {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().search(res.getName(), filterExpr, args,
                                     cons);
}
 
Example #15
Source File: ContinuationDirContext.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            Attributes matchingAttributes,
                            String[] attributesToReturn)
throws NamingException  {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(),
                                     matchingAttributes,
                                     attributesToReturn);
}
 
Example #16
Source File: LDAPUserQueryImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected List<User> executeUsersQuery(final String searchExpression) {
    LDAPTemplate ldapTemplate = new LDAPTemplate(ldapConfigurator);
    return ldapTemplate.execute(new LDAPCallBack<List<User>>() {

        @Override
        public List<User> executeInContext(InitialDirContext initialDirContext) {
            List<User> result = new ArrayList<>();
            try {
                String baseDn = ldapConfigurator.getUserBaseDn() != null ? ldapConfigurator.getUserBaseDn() : ldapConfigurator.getBaseDn();
                NamingEnumeration<?> namingEnum = initialDirContext.search(baseDn, searchExpression, createSearchControls());

                while (namingEnum.hasMore()) {
                    SearchResult searchResult = (SearchResult) namingEnum.next();

                    UserEntity user = new UserEntityImpl();
                    mapSearchResultToUser(searchResult, user);
                    result.add(user);

                }
                namingEnum.close();

            } catch (NamingException ne) {
                LOGGER.debug("Could not execute LDAP query: {}", ne.getMessage(), ne);
                return null;
            }
            return result;
        }

    });
}
 
Example #17
Source File: IvmContextTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void testListContextListsAllFederatedContextBindings() throws SystemException, NamingException {
//mimic logic from EnterpriseBeanBuilder.build, create compJndiContext and bind in it module, app, global 
Context compContext = new IvmContext();
    compContext.bind("java:comp/env/dummy", "dummy");

    Context moduleContext = new IvmContext();
    moduleContext.bind("module/env/test", String.class);
    moduleContext.bind("module/env/sub/test2", String.class);
    Context originalModuleSubContext = (IvmContext)moduleContext.lookup("module");
    compContext.bind("module", originalModuleSubContext);

    Context referencedModuleEnvSubContext = (IvmContext)compContext.lookup("module/env");
    NamingEnumeration<NameClassPair> referencedEnvLookupResult = referencedModuleEnvSubContext.list("");

    boolean testFound= false;
    boolean subFound = false;
    while(referencedEnvLookupResult.hasMore()) {
        String currentName = referencedEnvLookupResult.next().getName();
        if("test".equals(currentName)) {
            testFound = true;
        } else if("sub".equals(currentName)) {
            subFound = true;
        } else {
            fail();
        }
    }
    assertTrue(testFound);
    assertTrue(subFound);
 }
 
Example #18
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 #19
Source File: ContinuationDirContext.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(Name name,
                            Attributes matchingAttributes,
                            String[] attributesToReturn)
throws NamingException  {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().search(res.getName(), matchingAttributes,
                                     attributesToReturn);
}
 
Example #20
Source File: LDAPIdentityStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Set<LDAPCapabilityRepresentation> queryServerCapabilities() {
    Set<LDAPCapabilityRepresentation> result = new LinkedHashSet<>();
    try {
        List<String> attrs = new ArrayList<>();
        attrs.add("supportedControl");
        attrs.add("supportedExtension");
        attrs.add("supportedFeatures");
        List<SearchResult> searchResults = operationManager
            .search("", "(objectClass=*)", Collections.unmodifiableCollection(attrs), SearchControls.OBJECT_SCOPE);
        if (searchResults.size() != 1) {
            throw new ModelException("Could not query root DSE: unexpected result size");
        }
        SearchResult rootDse = searchResults.get(0);
        Attributes attributes = rootDse.getAttributes();
        for (String attr: attrs) {
            Attribute attribute = attributes.get(attr);
            if (null != attribute) {
                CapabilityType capabilityType = CapabilityType.fromRootDseAttributeName(attr);
                NamingEnumeration<?> values = attribute.getAll();
                while (values.hasMoreElements()) {
                    Object o = values.nextElement();
                    LDAPCapabilityRepresentation capability = new LDAPCapabilityRepresentation(o, capabilityType);
                    logger.info("rootDSE query: " + capability);
                    result.add(capability);
                }
            }
        }
        return result;
    } catch (NamingException e) {
        throw new ModelException("Failed to query root DSE: " + e.getMessage(), e);
    }
}
 
Example #21
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * Close the supplied NamingEnumeration if it is not null. Swallow any
 * exceptions, as this is only for cleanup.
 * 
 * @param results the NamingEnumeration to close.
 */
private void closeNamingEnumeration(NamingEnumeration results) {
	if (results != null) {
		try {
			results.close();
		}
		catch (Exception e) {
			// Never mind this.
		}
	}
}
 
Example #22
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
public void list(final Name base, NameClassPairCallbackHandler handler) {
	SearchExecutor searchExecutor = new SearchExecutor() {
		public NamingEnumeration executeSearch(DirContext ctx) throws javax.naming.NamingException {
			return ctx.list(base);
		}
	};

	search(searchExecutor, handler);
}
 
Example #23
Source File: LDAPDataDao.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * LDAP查询
 * </p>
 * @param ctx
 * @param searchBase
 * @param filterString
 * @return
 */
private NamingEnumeration<SearchResult> ldapSearch(DirContext ctx, String searchBase, String filterString) {
    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    try {
        return ctx.search(searchBase, filterString, constraints);
    } catch (Exception e) {
        throw new BusinessException("ldap search failed, please check parameters!", e);
    } 
}
 
Example #24
Source File: SearchFirstActiveDirectoryRealm.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
/**
 * Finds a distinguished name(DN) of a user by querying the active directory LDAP context for the
 * specified username.
 *
 * @return the DN of the user, or {@code null} if there's no such user
 */
@Nullable
protected String findUserDn(LdapContextFactory ldapContextFactory, String username) throws NamingException {
    LdapContext ctx = null;
    try {
        // Binds using the system username and password.
        ctx = ldapContextFactory.getSystemLdapContext();

        final SearchControls ctrl = new SearchControls();
        ctrl.setCountLimit(1);
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctrl.setTimeLimit(searchTimeoutMillis);

        final String filter =
                searchFilter != null ? USERNAME_PLACEHOLDER.matcher(searchFilter)
                                                           .replaceAll(username)
                                     : username;
        final NamingEnumeration<SearchResult> result = ctx.search(searchBase, filter, ctrl);
        try {
            if (!result.hasMore()) {
                return null;
            }
            return result.next().getNameInNamespace();
        } finally {
            result.close();
        }
    } finally {
        LdapUtils.closeContext(ctx);
    }
}
 
Example #25
Source File: LdapSearch.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Attributes findAttributes(String rootDN, String filter) throws NamingException {
    NamingEnumeration<SearchResult> answer = searchSubTree(rootDN, filter);
    if (answer.hasMore()) {
        SearchResult sr = answer.next();
        return sr.getAttributes();
    }
    return null;
}
 
Example #26
Source File: ContinuationDirContext.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            String filter,
                            SearchControls cons)
throws NamingException {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(), filter, cons);
}
 
Example #27
Source File: ContinuationDirContext.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            String filterExpr,
                            Object[] args,
                            SearchControls cons)
throws NamingException {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(), filterExpr, args,
                                     cons);
}
 
Example #28
Source File: ContinuationDirContext.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public NamingEnumeration<SearchResult> search(String name,
                            Attributes matchingAttributes,
                            String[] attributesToReturn)
throws NamingException  {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().search(res.getString(),
                                     matchingAttributes,
                                     attributesToReturn);
}
 
Example #29
Source File: SaslKrb5LDAPSecurityTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaslGssapiLdapAuth() throws Exception {

   final 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, "GSSAPI");

   LoginContext loginContext = new LoginContext("broker-sasl-gssapi");
   loginContext.login();
   try {
      Subject.doAs(loginContext.getSubject(), (PrivilegedExceptionAction<Object>) () -> {

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

         DirContext ctx = new InitialDirContext(env);
         NamingEnumeration<NameClassPair> list = ctx.list("ou=system");

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

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

         ctx.close();
         return null;

      });
   } catch (PrivilegedActionException e) {
      throw e.getException();
   }
}
 
Example #30
Source File: RetryingDirContext.java    From james-project with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public NamingEnumeration<SearchResult> search(final String name, final String filter,
        final SearchControls cons)
        throws NamingException {
    return (NamingEnumeration<SearchResult>) new LoggingRetryHandler(
            DEFAULT_EXCEPTION_CLASSES, this, getSchedule(), getMaxRetries()) {

        @Override
        public Object operation() throws NamingException {
            return ((DirContext) getDelegate()).search(name, filter, cons);
        }
    }.perform();
}