Java Code Examples for org.springframework.ldap.query.LdapQuery

The following examples show how to use org.springframework.ldap.query.LdapQuery. 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: metron   Source File: KnoxSSOAuthenticationFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void getAuthenticationShouldProperlyPopulateAuthentication() {
  LdapTemplate ldapTemplate = mock(LdapTemplate.class);
  KnoxSSOAuthenticationFilter knoxSSOAuthenticationFilter = spy(new KnoxSSOAuthenticationFilter("ou=people,dc=hadoop,dc=apache,dc=org",
          mock(Path.class),
          "knoxKeyString",
          "knoxCookie",
          ldapTemplate
  ));

  HttpServletRequest request = mock(HttpServletRequest.class);

  when(ldapTemplate.search(any(LdapQuery.class), any(AttributesMapper.class))).thenReturn(Arrays.asList("USER", "ADMIN"));

  Authentication authentication = knoxSSOAuthenticationFilter.getAuthentication("userName", request);
  Object[] grantedAuthorities = authentication.getAuthorities().toArray();
  assertEquals("ROLE_USER", grantedAuthorities[0].toString());
  assertEquals("ROLE_ADMIN", grantedAuthorities[1].toString());
  assertEquals("userName", authentication.getName());
}
 
Example 2
Source Project: ob1k   Source File: LdapCredentialsAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ComposableFuture<Boolean> authenticate(final Credentials<UserPasswordToken> credentials) {
  final String username = credentials.get().getUsername();
  final LdapQuery query = LdapQueryBuilder.query().filter(new EqualsFilter(UID_ATTRIBUTE, username));
  return ComposableFutures.submit(new Callable<Boolean>() {
    @Override
    public Boolean call() throws Exception {
      try {
        ldapTemplate.authenticate(query, new String(credentials.get().getPassword()));
        return true;
      } catch (final Exception e) {
        return false;
      }
    }
  });
}
 
Example 3
Source Project: spring-ldap   Source File: LdapTemplate.java    License: Apache License 2.0 6 votes vote down vote up
private SearchControls searchControlsForQuery(LdapQuery query, boolean returnObjFlag) {
    SearchControls searchControls = getDefaultSearchControls(
            defaultSearchScope,
            returnObjFlag,
            query.attributes());

    if(query.searchScope() != null) {
        searchControls.setSearchScope(query.searchScope().getId());
    }

    if(query.countLimit() != null) {
        searchControls.setCountLimit(query.countLimit());
    }

    if(query.timeLimit() != null) {
        searchControls.setTimeLimit(query.timeLimit());
    }
    return searchControls;
}
 
Example 4
@Override
protected Set<String> loadUserMemberships(String userName){
    {
        Optional<GatekeeperUserEntry> user = userCache.getUnchecked(userName);
        String userDn = user.get().getDn();

        LdapQuery memberOfApplication = LdapQueryBuilder.query()
                .base(ldapUserGroupsBase)
                .searchScope(SearchScope.SUBTREE)
                .attributes(ldapUserCn, ldapUserDn)
                .filter("(member:" + LDAP_MATCHING_RULE_IN_CHAIN + ":=" + userDn + ")");

        return new HashSet<>(ldapTemplate.search(memberOfApplication, getStringAttributesMapper(ldapUserCn)));
    }
}
 
Example 5
protected GatekeeperUserEntry loadUser(String userName){
    logger.info("Loading info for " + userName);
    LdapQuery query = LdapQueryBuilder.query()
            .base(ldapProperties.getUsersBase()).countLimit(1)
            .searchScope(SearchScope.SUBTREE)
            .attributes(ldapUserId, ldapUserDn, ldapUserEmail, ldapUserName)
            .where("objectClass")
            .is(ldapObjectClass)
            .and(ldapUserId)
            .is(userName);
    List<GatekeeperUserEntry> subjects = ldapTemplate.search(query, getAttributesMapper());

    if (subjects != null && subjects.size() > 0) {
        return subjects.get(0);
        //check to see if account is test account (only if testUsersBase is provided)
    } else if(ldapProperties.getTestUsersBase() != null) {
        query = LdapQueryBuilder.query()
                .base(ldapProperties.getTestUsersBase()).countLimit(1)
                .searchScope(SearchScope.SUBTREE)
                .attributes(ldapUserId, ldapUserDn, ldapUserEmail, ldapUserName)
                .where("objectCategory")
                .is(ldapObjectClass)
                .and(ldapUserId)
                .is(userName);
        subjects = ldapTemplate.search(query, getAttributesMapper());
        //return null;
        if (subjects != null && subjects.size() > 0) {
            return subjects.get(0);
        }
    }
    return null;
}
 
Example 6
@Override
public Collection<User> search(String query) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        String usersSearchFilter = environment.getProperty("lookup.user.filter", LDAP_DEFAULT_LOOKUP_FILTER);
        String hardcodedFilter = usersSearchFilter.replaceAll("\\{0}", LdapUtils.addWhitespaceWildcards(query));

        LdapQuery ldapQuery = LdapQueryBuilder
                .query()
                .base(baseDn)
                .countLimit(20)
                .timeLimit(5000)
                .searchScope(SearchScope.SUBTREE)
                .attributes(
                        LDAP_ATTRIBUTE_GIVENNAME,
                        LDAP_ATTRIBUTE_SURNAME,
                        LDAP_ATTRIBUTE_MAIL,
                        LDAP_ATTRIBUTE_DISPLAYNAME)
                .filter(new HardcodedFilter(hardcodedFilter));

        return ldapTemplate.search(ldapQuery, USER_CONTEXT_MAPPER);
    } catch(LimitExceededException lee) {
        LOGGER.info("Too much results while searching for [{}]. Returns an empty list.", query);
        return Collections.emptyList();
    } catch(CommunicationException ce) {
        LOGGER.error("LDAP server is not reachable.");
        return Collections.emptyList();
    } finally {
        Thread.currentThread().setContextClassLoader(classLoader);
    }
}
 
Example 7
Source Project: herd   Source File: LdapOperationsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSearch()
{
    // Create and initialize an LDAP context source.
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl(LDAP_URL);
    contextSource.setBase(LDAP_BASE);
    contextSource.setUserDn(LDAP_USER_DN);
    contextSource.setPassword(PASSWORD);
    contextSource.afterPropertiesSet();

    // Create an LDAP template.
    LdapTemplate ldapTemplate = new LdapTemplate(contextSource);

    // Create an LDAP query.
    LdapQuery ldapQuery = query().where((String) ConfigurationValue.LDAP_ATTRIBUTE_USER_ID.getDefaultValue()).is(USER_ID);

    // Create a subject matter expert contact details mapper.
    SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper subjectMatterExpertContactDetailsMapper =
        new SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper((String) ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME.getDefaultValue(),
            (String) ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE.getDefaultValue(),
            (String) ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS.getDefaultValue(),
            (String) ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER.getDefaultValue());

    // Gets information for the specified subject matter expert.
    List<SubjectMatterExpertContactDetails> result = ldapOperations.search(ldapTemplate, ldapQuery, subjectMatterExpertContactDetailsMapper);

    // Validate the results.
    assertEquals(
        Collections.singletonList(new SubjectMatterExpertContactDetails(USER_FULL_NAME, USER_JOB_TITLE, USER_EMAIL_ADDRESS, USER_TELEPHONE_NUMBER)),
        result);
}
 
Example 8
Source Project: spring-ldap   Source File: LdapTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> T authenticate(LdapQuery query, String password, AuthenticatedLdapEntryContextMapper<T> mapper) {
    SearchControls searchControls = searchControlsForQuery(query, RETURN_OBJ_FLAG);
    ReturningAuthenticatedLdapEntryContext<T> mapperCallback =
            new ReturningAuthenticatedLdapEntryContext<T>(mapper);
    CollectingAuthenticationErrorCallback errorCallback =
            new CollectingAuthenticationErrorCallback();

    AuthenticationStatus authenticationStatus = authenticate(query.base(),
            query.filter().encode(),
            password,
            searchControls,
            mapperCallback,
            errorCallback);

    if(errorCallback.hasError()) {
        Exception error = errorCallback.getError();

        if (error instanceof NamingException) {
            throw (NamingException) error;
        } else {
            throw new UncategorizedLdapException(error);
        }
    } else if(AuthenticationStatus.EMPTYRESULT == authenticationStatus) {
    	throw new EmptyResultDataAccessException(1);
    } else if(!authenticationStatus.isSuccess()) {
        throw new AuthenticationException();
    }

    return mapperCallback.collectedObject;
}
 
Example 9
Source Project: spring-ldap   Source File: LdapTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void authenticate(LdapQuery query, String password) {
    authenticate(query,
            password,
            new NullAuthenticatedLdapEntryContextCallback());
}
 
Example 10
Source Project: spring-ldap   Source File: LdapTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void search(LdapQuery query, NameClassPairCallbackHandler callbackHandler) {
    SearchControls searchControls = searchControlsForQuery(query, DONT_RETURN_OBJ_FLAG);
    search(query.base(),
            query.filter().encode(),
            searchControls,
            callbackHandler);
}
 
Example 11
Source Project: spring-ldap   Source File: LdapTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> List<T> search(LdapQuery query, ContextMapper<T> mapper) {
    SearchControls searchControls = searchControlsForQuery(query, RETURN_OBJ_FLAG);

    return search(query.base(),
            query.filter().encode(),
            searchControls,
            mapper);

}
 
Example 12
Source Project: spring-ldap   Source File: LdapTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> List<T> search(LdapQuery query, AttributesMapper<T> mapper) {
    SearchControls searchControls = searchControlsForQuery(query, DONT_RETURN_OBJ_FLAG);

    return search(query.base(),
            query.filter().encode(),
            searchControls,
            mapper);
}
 
Example 13
Source Project: spring-ldap   Source File: LdapTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public DirContextOperations searchForContext(LdapQuery query) {
    return searchForObject(query, new ContextMapper<DirContextOperations>() {
        @Override
        public DirContextOperations mapFromContext(Object ctx) throws javax.naming.NamingException {
            return (DirContextOperations) ctx;
        }
    });
}
 
Example 14
Source Project: spring-ldap   Source File: LdapTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> T searchForObject(LdapQuery query, ContextMapper<T> mapper) {
    SearchControls searchControls = searchControlsForQuery(query, DONT_RETURN_OBJ_FLAG);

    return searchForObject(query.base(),
            query.filter().encode(),
            searchControls,
            mapper);
}
 
Example 15
Source Project: spring-ldap   Source File: LdapTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> T findOne(LdapQuery query, Class<T> clazz) {
    List<T> result = find(query, clazz);

    if (result.size() == 0) {
        throw new EmptyResultDataAccessException(1);
    }
    else if (result.size() != 1) {
        throw new IncorrectResultSizeDataAccessException(1, result.size());
    }

    return result.get(0);
}
 
Example 16
protected Set<String> loadUserMemberships(String userName){
    Pattern cnPattern = Pattern.compile("cn=([- _A-Za-z0-9]+)", Pattern.CASE_INSENSITIVE);

    logger.info("Checking Memberships for " +userName );
    Set<String> memberships = new HashSet<>();
    String memberof = "memberOf";
    LdapQuery query = LdapQueryBuilder.query()
            .base(ldapProperties.getUsersBase()).countLimit(1000)
            .searchScope(SearchScope.SUBTREE)
            .attributes(memberof)
            .where("objectClass")
            .is(ldapObjectClass)
            .and(ldapUserId)
            .is(userName);


    LinkedList<String[]> subjects = (LinkedList<String[]>)ldapTemplate.search(query, new OpenLdapMembershipsMapper());

    if (subjects == null || subjects.size() == 0) {
        if(ldapProperties.getTestUsersBase() != null) {
            query = LdapQueryBuilder.query()
                    .base(ldapProperties.getTestUsersBase()).countLimit(1000)
                    .searchScope(SearchScope.SUBTREE)
                    .attributes("memberOf")
                    .where("objectClass")
                    .is(ldapObjectClass)
                    .and(ldapUserId)
                    .is(userName);
            subjects = (LinkedList<String[]>) ldapTemplate.search(query, new OpenLdapMembershipsMapper());
        }
    }

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

    Arrays.asList(subjects.getFirst()).forEach(item -> {
        Matcher m = cnPattern.matcher(item);
        if(m.find()) {
            extracted.add(m.group(1));
        }
    });

    return extracted;
}
 
Example 17
Source Project: herd   Source File: SubjectMatterExpertDaoImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public SubjectMatterExpertContactDetails getSubjectMatterExpertByKey(SubjectMatterExpertKey subjectMatterExpertKey)
{
    // Get LDAP specific configuration settings.
    final String ldapUrl = configurationHelper.getProperty(ConfigurationValue.LDAP_URL);
    final String ldapBase = configurationHelper.getProperty(ConfigurationValue.LDAP_BASE);
    final String ldapUserDn = configurationHelper.getProperty(ConfigurationValue.LDAP_USER_DN);
    final String credStashEncryptionContext = configurationHelper.getProperty(ConfigurationValue.CREDSTASH_HERD_ENCRYPTION_CONTEXT);
    final String ldapUserCredentialName = configurationHelper.getProperty(ConfigurationValue.LDAP_USER_CREDENTIAL_NAME);

    // Log configuration values being used to create LDAP context source.
    LOGGER.info("Creating LDAP context source using the following parameters: {}=\"{}\" {}=\"{}\" {}=\"{}\" {}=\"{}\" {}=\"{}\"...",
        ConfigurationValue.LDAP_URL.getKey(), ldapUrl, ConfigurationValue.LDAP_BASE.getKey(), ldapBase, ConfigurationValue.LDAP_USER_DN.getKey(),
        ldapUserDn, ConfigurationValue.CREDSTASH_HERD_ENCRYPTION_CONTEXT.getKey(), credStashEncryptionContext,
        ConfigurationValue.LDAP_USER_CREDENTIAL_NAME.getKey(), ldapUserCredentialName);

    // Retrieve LDAP user password from the credstash.
    String ldapUserPassword;
    try
    {
        ldapUserPassword = credStashHelper.getCredentialFromCredStash(credStashEncryptionContext, ldapUserCredentialName);
    }
    catch (CredStashGetCredentialFailedException e)
    {
        throw new IllegalStateException(e);
    }

    // Create and initialize an LDAP context source.
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl(ldapUrl);
    contextSource.setBase(ldapBase);
    contextSource.setUserDn(ldapUserDn);
    contextSource.setPassword(ldapUserPassword);
    contextSource.afterPropertiesSet();

    // Create an LDAP template.
    LdapTemplate ldapTemplate = new LdapTemplate(contextSource);

    // Create an LDAP query.
    LdapQuery ldapQuery = query().where(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_ID)).is(subjectMatterExpertKey.getUserId());

    // Create a subject matter expert contact details mapper.
    SubjectMatterExpertContactDetailsMapper subjectMatterExpertContactDetailsMapper =
        new SubjectMatterExpertContactDetailsMapper(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME),
            configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE),
            configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS),
            configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER));

    // Gets information for the specified subject matter expert.
    List<SubjectMatterExpertContactDetails> subjectMatterExpertContactDetailsList =
        ldapOperations.search(ldapTemplate, ldapQuery, subjectMatterExpertContactDetailsMapper);

    // Return the results.
    return CollectionUtils.isNotEmpty(subjectMatterExpertContactDetailsList) ? subjectMatterExpertContactDetailsList.get(0) : null;
}
 
Example 18
Source Project: herd   Source File: LdapOperationsImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public <T> List<T> search(LdapTemplate ldapTemplate, LdapQuery query, AttributesMapper<T> mapper)
{
    return ldapTemplate.search(query, mapper);
}
 
Example 19
Source Project: herd   Source File: SubjectMatterExpertDaoImplTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testGetSubjectMatterExpertByKey() throws Exception
{
    // Create a subject matter expert key.
    SubjectMatterExpertKey subjectMatterExpertKey = new SubjectMatterExpertKey(USER_ID);

    // Create subject matter expert contact details initialised with test data.
    SubjectMatterExpertContactDetails subjectMatterExpertContactDetails =
        new SubjectMatterExpertContactDetails(USER_FULL_NAME, USER_JOB_TITLE, USER_EMAIL_ADDRESS, USER_TELEPHONE_NUMBER);

    // Mock the external calls.
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_URL)).thenReturn(LDAP_URL);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_BASE)).thenReturn(LDAP_BASE);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_USER_DN)).thenReturn(LDAP_USER_DN);
    when(configurationHelper.getProperty(ConfigurationValue.CREDSTASH_HERD_ENCRYPTION_CONTEXT)).thenReturn(CREDSTASH_ENCRYPTION_CONTEXT);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_USER_CREDENTIAL_NAME)).thenReturn(USER_CREDENTIAL_NAME);
    when(credStashHelper.getCredentialFromCredStash(CREDSTASH_ENCRYPTION_CONTEXT, USER_CREDENTIAL_NAME)).thenReturn(PASSWORD);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_ID)).thenReturn(LDAP_ATTRIBUTE_USER_ID);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME)).thenReturn(LDAP_ATTRIBUTE_USER_FULL_NAME);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE)).thenReturn(LDAP_ATTRIBUTE_USER_JOB_TITLE);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS)).thenReturn(LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER)).thenReturn(LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER);
    when(
        ldapOperations.search(any(LdapTemplate.class), any(LdapQuery.class), any(SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper.class)))
        .thenReturn(Collections.singletonList(subjectMatterExpertContactDetails));

    // Call the method under test.
    SubjectMatterExpertContactDetails result = subjectMatterExpertDaoImpl.getSubjectMatterExpertByKey(subjectMatterExpertKey);

    // Validate the results.
    assertEquals(subjectMatterExpertContactDetails, result);

    // Verify the external calls.
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_URL);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_BASE);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_USER_DN);
    verify(configurationHelper).getProperty(ConfigurationValue.CREDSTASH_HERD_ENCRYPTION_CONTEXT);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_USER_CREDENTIAL_NAME);
    verify(credStashHelper).getCredentialFromCredStash(CREDSTASH_ENCRYPTION_CONTEXT, USER_CREDENTIAL_NAME);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_ID);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER);
    verify(ldapOperations)
        .search(any(LdapTemplate.class), any(LdapQuery.class), any(SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper.class));
    verifyNoMoreInteractionsHelper();
}
 
Example 20
Source Project: herd   Source File: SubjectMatterExpertDaoImplTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testGetSubjectMatterExpertByKeyUserNoExists() throws Exception
{
    // Create a subject matter expert key.
    SubjectMatterExpertKey subjectMatterExpertKey = new SubjectMatterExpertKey(USER_ID);

    // Create subject matter expert contact details initialised with test data.
    SubjectMatterExpertContactDetails subjectMatterExpertContactDetails =
        new SubjectMatterExpertContactDetails(USER_FULL_NAME, USER_JOB_TITLE, USER_EMAIL_ADDRESS, USER_TELEPHONE_NUMBER);

    // Mock the external calls.
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_URL)).thenReturn(LDAP_URL);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_BASE)).thenReturn(LDAP_BASE);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_USER_DN)).thenReturn(LDAP_USER_DN);
    when(configurationHelper.getProperty(ConfigurationValue.CREDSTASH_HERD_ENCRYPTION_CONTEXT)).thenReturn(CREDSTASH_ENCRYPTION_CONTEXT);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_USER_CREDENTIAL_NAME)).thenReturn(USER_CREDENTIAL_NAME);
    when(credStashHelper.getCredentialFromCredStash(CREDSTASH_ENCRYPTION_CONTEXT, USER_CREDENTIAL_NAME)).thenReturn(PASSWORD);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_ID)).thenReturn(LDAP_ATTRIBUTE_USER_ID);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME)).thenReturn(LDAP_ATTRIBUTE_USER_FULL_NAME);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE)).thenReturn(LDAP_ATTRIBUTE_USER_JOB_TITLE);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS)).thenReturn(LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS);
    when(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER)).thenReturn(LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER);
    when(
        ldapOperations.search(any(LdapTemplate.class), any(LdapQuery.class), any(SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper.class)))
        .thenReturn(Collections.emptyList());

    // Call the method under test.
    SubjectMatterExpertContactDetails result = subjectMatterExpertDaoImpl.getSubjectMatterExpertByKey(subjectMatterExpertKey);

    // Validate the results.
    assertNull(result);

    // Verify the external calls.
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_URL);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_BASE);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_USER_DN);
    verify(configurationHelper).getProperty(ConfigurationValue.CREDSTASH_HERD_ENCRYPTION_CONTEXT);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_USER_CREDENTIAL_NAME);
    verify(credStashHelper).getCredentialFromCredStash(CREDSTASH_ENCRYPTION_CONTEXT, USER_CREDENTIAL_NAME);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_ID);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS);
    verify(configurationHelper).getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER);
    verify(ldapOperations)
        .search(any(LdapTemplate.class), any(LdapQuery.class), any(SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper.class));
    verifyNoMoreInteractionsHelper();
}
 
Example 21
Source Project: herd   Source File: MockLdapOperations.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Executes {@link org.springframework.ldap.core.LdapTemplate#search(org.springframework.ldap.query.LdapQuery,
 * org.springframework.ldap.core.AttributesMapper)}.
 *
 * @param ldapTemplate the LDAP template to use
 * @param query the LDAP query specification
 * @param mapper the <code>Attributes</code> to supply all found Attributes to
 *
 * @return the predefined LDAP search results constructed by the given {@link org.springframework.ldap.core.AttributesMapper}
 */
@Override
public <T> List<T> search(LdapTemplate ldapTemplate, LdapQuery query, AttributesMapper<T> mapper)
{
    // Create an empty results list.
    List<T> results = new ArrayList<>();

    // Get the query filter as a string.
    String filter = query.filter().toString();

    // Check if we need to respond with the predefined result.
    if (!filter.contains(MOCK_USER_ID_USER_NO_EXISTS))
    {
        // Create attributes object with ignoreCase flag set to "true".
        BasicAttributes attributes = new BasicAttributes(true);

        // Populate the attributes with predefined set of results.
        attributes
            .put(new BasicAttribute(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME), AbstractDaoTest.USER_FULL_NAME));
        attributes
            .put(new BasicAttribute(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE), AbstractDaoTest.USER_JOB_TITLE));
        attributes.put(
            new BasicAttribute(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS), AbstractDaoTest.USER_EMAIL_ADDRESS));

        // Check if it is OK to add the user phone number attribute.
        if (!filter.contains(MOCK_USER_ID_ATTRIBUTE_USER_TELEPHONE_NUMBER_NO_EXISTS))
        {
            attributes.put(new BasicAttribute(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER),
                AbstractDaoTest.USER_TELEPHONE_NUMBER));
        }

        // Map the results.
        try
        {
            results.add(mapper.mapFromAttributes(attributes));
        }
        catch (NamingException e)
        {
            // Do nothing.
        }
    }

    // Return the results.
    return results;
}
 
Example 22
Source Project: spring-ldap   Source File: OdmManagerImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public <T> List<T> search(Class<T> clazz, LdapQuery query) {
    return ldapTemplate.find(query, clazz);
}
 
Example 23
Source Project: spring-ldap   Source File: LdapTemplate.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> List<T> find(LdapQuery query, Class<T> clazz) {
    SearchControls searchControls = searchControlsForQuery(query, RETURN_OBJ_FLAG);
    return find(query.base(), query.filter(), searchControls, clazz);
}
 
Example 24
Source Project: herd   Source File: LdapOperations.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Executes {@link org.springframework.ldap.core.LdapTemplate#search(org.springframework.ldap.query.LdapQuery,
 * org.springframework.ldap.core.AttributesMapper)}.
 *
 * @param ldapTemplate the LDAP template to use
 * @param query the LDAP query specification
 * @param mapper the <code>Attributes</code> to supply all found Attributes to
 *
 * @return the list of objects constructed by the given {@link org.springframework.ldap.core.AttributesMapper}
 */
<T> List<T> search(LdapTemplate ldapTemplate, LdapQuery query, AttributesMapper<T> mapper);
 
Example 25
Source Project: spring-ldap   Source File: OdmManager.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Search for entries in the LDAP directory.
 * <p>
 * Only those entries that both match the query search filter and
 * are represented by the given Java class are returned.
 *
 * @param <T> The Java type to return
 * @param clazz The Java type to return
 * @param query the LDAP query specification
 * @return All matching entries.
 *
 * @throws org.springframework.ldap.NamingException on error.
 * @see org.springframework.ldap.query.LdapQueryBuilder
 */
<T> List<T> search(Class<T> clazz, LdapQuery query);
 
Example 26
Source Project: spring-ldap   Source File: LdapOperations.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Utility method to perform a simple LDAP 'bind' authentication. Search for
 * the LDAP entry to authenticate using the supplied LdapQuery; use
 * the DN of the found entry together with the password as input to
 * {@link ContextSource#getContext(String, String)}, thus authenticating the
 * entry.
 * <p>
 *     <b>Note:</b> This method differs from the older authenticate methods in that encountered
 *     exceptions are thrown rather than supplied to a callback for handling.
 * </p>
 *
 * @param query the LdapQuery specifying the details of the search.
 * @param password the password to use for authentication.
 * @param mapper the callback that will be called to perform operations
 * on the DirContext authenticated with the found user.
 * <code>false</code> otherwise.
 * @return the result from the callback.
 * @throws IncorrectResultSizeDataAccessException if more than one users were found
 * @throws org.springframework.dao.EmptyResultDataAccessException if only one user was found
 * @throws NamingException if something went wrong in authentication.
 *
 * @since 2.0
 * @see org.springframework.ldap.query.LdapQueryBuilder
 */
<T> T authenticate(LdapQuery query, String password, AuthenticatedLdapEntryContextMapper<T> mapper);
 
Example 27
Source Project: spring-ldap   Source File: LdapOperations.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Utility method to perform a simple LDAP 'bind' authentication. Search for
 * the LDAP entry to authenticate using the supplied base DN and filter; use
 * the DN of the found entry together with the password as input to
 * {@link ContextSource#getContext(String, String)}, thus authenticating the
 * entry. If an exception is caught, the same exception is passed on to the given
 * {@link AuthenticationErrorCallback}. This enables the caller to provide a
 * callback that, for example, collects the exception for later processing.
 * <p>
 *     <b>Note:</b> This method differs from the older authenticate methods in that encountered
 *     exceptions are thrown rather than supplied to a callback for handling.
 * </p>
 *
 * @param query the LdapQuery specifying the details of the search.
 * @param password the password to use for authentication.
 * <code>false</code> otherwise.
 * @throws IncorrectResultSizeDataAccessException if more than one users were found
 * @throws org.springframework.dao.EmptyResultDataAccessException if only one user was found
 * @throws NamingException if something went wrong in authentication.
 *
 * @since 2.0
 * @see org.springframework.ldap.query.LdapQueryBuilder
 */
void authenticate(LdapQuery query, String password);
 
Example 28
Source Project: spring-ldap   Source File: LdapOperations.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Perform a search with parameters from the specified LdapQuery. All found objects will be supplied to the
 * <code>NameClassPairCallbackHandler</code> for processing.
 *
 * @param query the LDAP query specification.
 * @param callbackHandler the <code>NameClassPairCallbackHandler</code> to supply all found entries to.
 *
 * @throws NamingException if any error occurs.
 * @since 2.0
 * @see org.springframework.ldap.query.LdapQueryBuilder
 * @see org.springframework.ldap.core.support.CountNameClassPairCallbackHandler
 */
void search(LdapQuery query, NameClassPairCallbackHandler callbackHandler);
 
Example 29
Source Project: spring-ldap   Source File: LdapOperations.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Perform a search with parameters from the specified LdapQuery. All found objects will be supplied to the
 * <code>ContextMapper</code> for processing, and all returned objects will be collected in a list to be returned.
 *
 * @param query the LDAP query specification.
 * @param mapper the <code>ContextMapper</code> to supply all found entries to.
 * @return a <code>List</code> containing all entries received from the
 * <code>ContextMapper</code>.
 *
 * @throws NamingException if any error occurs.
 * @since 2.0
 * @see org.springframework.ldap.query.LdapQueryBuilder
 */
<T> List<T> search(LdapQuery query, ContextMapper<T> mapper);
 
Example 30
Source Project: spring-ldap   Source File: LdapOperations.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Perform a search with parameters from the specified LdapQuery. The Attributes of the found entries will be
 * supplied to the <code>AttributesMapper</code> for processing, and all
 * returned objects will be collected in a list to be returned.
 *
 * @param query the LDAP query specification.
 * @param mapper the <code>Attributes</code> to supply all found Attributes to.
 * @return a <code>List</code> containing all entries received from the
 * <code>Attributes</code>.
 *
 * @throws NamingException if any error occurs.
 * @since 2.0
 * @see org.springframework.ldap.query.LdapQueryBuilder
 */
<T> List<T> search(LdapQuery query, AttributesMapper<T> mapper);