Java Code Examples for javax.naming.NamingEnumeration

The following examples show how to use javax.naming.NamingEnumeration. These examples are extracted from open source projects. 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 Project: activemq-artemis   Author: apache   File: LegacyLDAPSecuritySettingPluginTest.java    License: 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 #2
Source Project: iaf   Author: ibissource   File: LdapSender.java    License: 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 #3
Source Project: MaxKey   Author: shimingxy   File: UserInfo2Activedirectory.java    License: 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 #4
Source Project: spring-ldap   Author: spring-projects   File: LdapTemplateSortedSearchITest.java    License: 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 #5
Source Project: oodt   Author: apache   File: HTTPContext.java    License: 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 #6
Source Project: jdk8u_jdk   Author: JetBrains   File: LDAPCertStore.java    License: 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 #7
Source Project: library   Author: arthurgregorio   File: LdapRepository.java    License: 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 #8
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: Rdn.java    License: 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 #9
Source Project: seppb   Author: purang-fintech   File: UserServiceImpl.java    License: 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 #10
Source Project: uavstack   Author: uavorg   File: GUISSOLdapClient.java    License: 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 #11
Source Project: cloudstack   Author: apache   File: OpenLdapUserManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context, Long domainId) throws NamingException {
    String attributeName = _ldapConfiguration.getGroupUniqueMemberAttribute(domainId);
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(new String[] {attributeName});

    NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(domainId), generateGroupSearchFilter(groupName, domainId), controls);

    final List<LdapUser> users = new ArrayList<LdapUser>();
    //Expecting only one result which has all the users
    if (result.hasMoreElements()) {
        Attribute attribute = result.nextElement().getAttributes().get(attributeName);
        NamingEnumeration<?> values = attribute.getAll();

        while (values.hasMoreElements()) {
            String userdn = String.valueOf(values.nextElement());
            try{
                users.add(getUserForDn(userdn, context, domainId));
            } catch (NamingException e){
                LOGGER.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage());
            }
        }
    }

    Collections.sort(users);

    return users;
}
 
Example #12
Source Project: hadoop   Author: naver   File: LdapGroupsMapping.java    License: Apache License 2.0 5 votes vote down vote up
List<String> doGetGroups(String user) throws NamingException {
  List<String> groups = new ArrayList<String>();

  DirContext ctx = getDirContext();

  // Search for the user. We'll only ever need to look at the first result
  NamingEnumeration<SearchResult> results = ctx.search(baseDN,
      userSearchFilter,
      new Object[]{user},
      SEARCH_CONTROLS);
  if (results.hasMoreElements()) {
    SearchResult result = results.nextElement();
    String userDn = result.getNameInNamespace();

    NamingEnumeration<SearchResult> groupResults =
        ctx.search(baseDN,
            "(&" + groupSearchFilter + "(" + groupMemberAttr + "={0}))",
            new Object[]{userDn},
            SEARCH_CONTROLS);
    while (groupResults.hasMoreElements()) {
      SearchResult groupResult = groupResults.nextElement();
      Attribute groupName = groupResult.getAttributes().get(groupNameAttr);
      groups.add(groupName.get().toString());
    }
  }

  return groups;
}
 
Example #13
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: SelectorContext.java    License: MIT License 5 votes vote down vote up
/**
 * Enumerates the names bound in the named context, along with the class
 * names of objects bound to them.
 *
 * @param name the name of the context to list
 * @return an enumeration of the names and class names of the bindings in
 * this context. Each element of the enumeration is of type NameClassPair.
 * @throws NamingException if a naming exception is encountered
 */
@Override
public NamingEnumeration<NameClassPair> list(String name)
    throws NamingException {

    if (log.isDebugEnabled()) {
        log.debug(sm.getString("selectorContext.methodUsingString", "list",
                name));
    }

    return getBoundContext().list(parseName(name));
}
 
Example #14
Source Project: CodeDefenders   Author: CodeDefenders   File: ParallelizeTest.java    License: 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 #15
Source Project: activiti6-boot2   Author: dingziyang   File: LDAPQueryBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public String buildQueryGroupsForUser(final LDAPConfigurator ldapConfigurator, final String userId) {
  String searchExpression = null;
  if (ldapConfigurator.getQueryGroupsForUser() != null) {

    // Fetch the dn of the user
    LDAPTemplate ldapTemplate = new LDAPTemplate(ldapConfigurator);
    String userDn = ldapTemplate.execute(new LDAPCallBack<String>() {

      public String executeInContext(InitialDirContext initialDirContext) {

        String userDnSearch = buildQueryByUserId(ldapConfigurator, userId);
        try {
          String baseDn = ldapConfigurator.getUserBaseDn() != null ? ldapConfigurator.getUserBaseDn() : ldapConfigurator.getBaseDn();
          NamingEnumeration<?> namingEnum = initialDirContext.search(baseDn, userDnSearch, createSearchControls(ldapConfigurator));
          while (namingEnum.hasMore()) { // Should be only one
            SearchResult result = (SearchResult) namingEnum.next();
            return result.getNameInNamespace();
          }
          namingEnum.close();
        } catch (NamingException e) {
          LOGGER.debug("Could not find user dn : " + e.getMessage(), e);
        }
        return null;
      }

    });

    searchExpression = MessageFormat.format(ldapConfigurator.getQueryGroupsForUser(), Rdn.escapeValue(userDn));

  } else {
    searchExpression = userId;
  }
  return searchExpression;
}
 
Example #16
Source Project: spring-ldap   Author: spring-projects   File: NameAwareAttributes.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance, populated with the data from the supplied instance.
 * @param attributes the instance to copy.
 */
public NameAwareAttributes(Attributes attributes) {
    NamingEnumeration<? extends Attribute> allAttributes = attributes.getAll();
    while(allAttributes.hasMoreElements()) {
        Attribute attribute = allAttributes.nextElement();
        put(new NameAwareAttribute(attribute));
    }
}
 
Example #17
Source Project: flowable-engine   Author: flowable   File: LDAPQueryBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public String buildQueryGroupsForUser(final LDAPConfiguration ldapConfigurator, final String userId) {
    String searchExpression = null;
    if (ldapConfigurator.getQueryGroupsForUser() != null) {

        // Fetch the dn of the user
        LDAPTemplate ldapTemplate = new LDAPTemplate(ldapConfigurator);
        String userDn = ldapTemplate.execute(new LDAPCallBack<String>() {

            @Override
            public String executeInContext(InitialDirContext initialDirContext) {

                String userDnSearch = buildQueryByUserId(ldapConfigurator, userId);
                try {
                    String baseDn = ldapConfigurator.getUserBaseDn() != null ? ldapConfigurator.getUserBaseDn() : ldapConfigurator.getBaseDn();
                    NamingEnumeration<?> namingEnum = initialDirContext.search(baseDn, userDnSearch, createSearchControls(ldapConfigurator));
                    while (namingEnum.hasMore()) { // Should be only one
                        SearchResult result = (SearchResult) namingEnum.next();
                        return result.getNameInNamespace();
                    }
                    namingEnum.close();
                } catch (NamingException e) {
                    LOGGER.debug("Could not find user dn : {}", e.getMessage(), e);
                }
                return null;
            }

        });

        searchExpression = MessageFormat.format(ldapConfigurator.getQueryGroupsForUser(), Rdn.escapeValue(userDn));

    } else {
        searchExpression = userId;
    }
    return searchExpression;
}
 
Example #18
Source Project: flowable-engine   Author: flowable   File: LDAPUserQueryImpl.java    License: 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 #19
Source Project: tomcatsrc   Author: wangyingjie   File: ResourceAttributes.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get all attribute IDs.
 */
@Override
public NamingEnumeration<String> getIDs() {
    if (attributes == null) {
        Vector<String> attributeIDs = new Vector<String>();
        Date creationDate = getCreationDate();
        if (creationDate != null) {
            attributeIDs.addElement(CREATION_DATE);
            attributeIDs.addElement(ALTERNATE_CREATION_DATE);
        }
        Date lastModifiedDate = getLastModifiedDate();
        if (lastModifiedDate != null) {
            attributeIDs.addElement(LAST_MODIFIED);
            attributeIDs.addElement(ALTERNATE_LAST_MODIFIED);
        }
        if (getName() != null) {
            attributeIDs.addElement(NAME);
        }
        String resourceType = getResourceType();
        if (resourceType != null) {
            attributeIDs.addElement(TYPE);
            attributeIDs.addElement(ALTERNATE_TYPE);
        }
        long contentLength = getContentLength();
        if (contentLength >= 0) {
            attributeIDs.addElement(CONTENT_LENGTH);
            attributeIDs.addElement(ALTERNATE_CONTENT_LENGTH);
        }
        String etag = getETag();
        if (etag != null) {
            attributeIDs.addElement(ETAG);
            attributeIDs.addElement(ALTERNATE_ETAG);
        }
        return new RecyclableNamingEnumeration<String>(attributeIDs);
    } else {
        return attributes.getIDs();
    }
}
 
Example #20
Source Project: JDKSourceCode1.8   Author: wupeixuan   File: ContinuationDirContext.java    License: MIT License 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 #21
Source Project: james-project   Author: apache   File: RetryingContext.java    License: 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 #22
Source Project: openjdk-8-source   Author: keerath   File: ContinuationDirContext.java    License: 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 #23
Source Project: tomee   Author: apache   File: IvmContextTest.java    License: 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 #24
Source Project: spring-ldap   Author: spring-projects   File: LdapTemplate.java    License: 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 #25
Source Project: centraldogma   Author: line   File: SearchFirstActiveDirectoryRealm.java    License: 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 #26
Source Project: hottub   Author: dsrg-uoft   File: ContinuationDirContext.java    License: 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 #27
Source Project: hottub   Author: dsrg-uoft   File: ContinuationDirContext.java    License: 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 #28
Source Project: james-project   Author: apache   File: RetryingDirContext.java    License: 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();
}
 
Example #29
Source Project: activemq-artemis   Author: apache   File: SaslKrb5LDAPSecurityTest.java    License: 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 Project: hottub   Author: dsrg-uoft   File: ContinuationDirContext.java    License: 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);
}