Java Code Examples for org.springframework.ldap.filter.AndFilter

The following examples show how to use org.springframework.ldap.filter.AndFilter. 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: taskana   Source File: LdapClient.java    License: Apache License 2.0 6 votes vote down vote up
public List<AccessIdRepresentationModel> searchGroupsByName(final String name)
    throws InvalidArgumentException {
  LOGGER.debug("entry to searchGroupsByName(name = {}).", name);
  isInitOrFail();
  testMinSearchForLength(name);

  final AndFilter andFilter = new AndFilter();
  andFilter.and(new EqualsFilter(getGroupSearchFilterName(), getGroupSearchFilterValue()));
  final OrFilter orFilter = new OrFilter();
  orFilter.or(new WhitespaceWildcardsFilter(getGroupNameAttribute(), name));
  if (!CN.equals(getGroupNameAttribute())) {
    orFilter.or(new WhitespaceWildcardsFilter(CN, name));
  }
  andFilter.and(orFilter);

  final List<AccessIdRepresentationModel> accessIds =
      ldapTemplate.search(
          getGroupSearchBase(),
          andFilter.encode(),
          SearchControls.SUBTREE_SCOPE,
          getLookUpGroupAttributesToReturn(),
          new GroupContextMapper());
  LOGGER.debug("Exit from searchGroupsByName. Retrieved the following groups: {}", accessIds);
  return accessIds;
}
 
Example 2
Source Project: taskana   Source File: LdapClient.java    License: Apache License 2.0 6 votes vote down vote up
public List<AccessIdRepresentationModel> searchGroupsofUsersIsMember(final String name)
    throws InvalidArgumentException {
  LOGGER.debug("entry to searchGroupsofUsersIsMember(name = {}).", name);
  isInitOrFail();
  testMinSearchForLength(name);

  final AndFilter andFilter = new AndFilter();
  andFilter.and(new WhitespaceWildcardsFilter(getGroupNameAttribute(), ""));
  andFilter.and(new EqualsFilter(getGroupsOfUser(), name));

  String[] userAttributesToReturn = {getUserIdAttribute(), getGroupNameAttribute()};

  final List<AccessIdRepresentationModel> accessIds =
      ldapTemplate.search(
          getGroupSearchBase(),
          andFilter.encode(),
          SearchControls.SUBTREE_SCOPE,
          userAttributesToReturn,
          new GroupContextMapper());
  LOGGER.debug(
      "exit from searchGroupsofUsersIsMember. Retrieved the following users: {}.", accessIds);
  return accessIds;
}
 
Example 3
Source Project: zstack   Source File: LdapManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void handle(APIGetCandidateLdapEntryForBindingMsg msg) {
    APIGetLdapEntryReply reply = new APIGetLdapEntryReply();

    AndFilter andFilter = new AndFilter();
    andFilter.and(new HardcodedFilter(msg.getLdapFilter()));

    List<String> boundLdapEntryList = Q.New(LdapAccountRefVO.class)
            .select(LdapAccountRefVO_.ldapUid)
            .listValues();

    List<Object> result = ldapUtil.searchLdapEntry(andFilter.toString(), msg.getLimit(), new ResultFilter() {
        @Override
        public boolean needSelect(String dn) {
            return !boundLdapEntryList.contains(dn);
        }
    });

    reply.setInventories(result);

    bus.reply(msg, reply);
}
 
Example 4
Source Project: cxf   Source File: LdapUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Name getDnOfEntry(LdapTemplate ldapTemplate, String baseDN,
    String objectClass, String filterAttributeName, String filterAttributeValue) {

    ContextMapper<Name> mapper =
        new AbstractContextMapper<Name>() {
            public Name doMapFromContext(DirContextOperations ctx) {
                return ctx.getDn();
            }
        };

    AndFilter filter = new AndFilter();
    filter.and(
        new EqualsFilter("objectclass", objectClass)).and(
            new EqualsFilter(filterAttributeName, filterAttributeValue));

    List<Name> result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, mapper);

    if (result != null && !result.isEmpty()) {
        //not only the first one....
        return result.get(0);
    }
    return null;
}
 
Example 5
Source Project: secure-data-service   Source File: UserService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param realm
 *            The realm under which the user exists
 * @param userId
 *            The id of the user
 * @return List of roles assigned to this user
 */
public List<String> getUserGroups(String realm, String userId) {
    DistinguishedName dn = new DistinguishedName("ou=" + realm);
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", groupObjectClass)).and(
            new EqualsFilter(groupSearchAttribute, userId));
    @SuppressWarnings("unchecked")
    List<String> groups = ldapTemplate.search(dn, filter.toString(), new GroupContextMapper());

    // map the roles in LDAP which are better suited for Posix systems to
    // the roles used by the API
    List<String> result = new LinkedList<String>();
    for (String group : groups) {
        result.add(LDAP_ROLE_MAPPING.containsKey(group) ? LDAP_ROLE_MAPPING.get(group) : group);
    }
    return result;
}
 
Example 6
Source Project: secure-data-service   Source File: LdapServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public User getUser(String realm, String uid) {
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter(OBJECTCLASS, userObjectClass)).and(new EqualsFilter(userSearchAttribute, uid));
    DistinguishedName dn = new DistinguishedName("ou=" + realm);
    User user;
    try {
        List userList = ldapTemplate.search(dn, filter.toString(), SearchControls.SUBTREE_SCOPE, new String[] {
                "*", CREATE_TIMESTAMP, MODIFY_TIMESTAMP }, new UserContextMapper());
        if (userList == null || userList.size() == 0) {
            throw new EmptyResultDataAccessException(1);
        } else if (userList.size() > 1) {
            throw new IncorrectResultSizeDataAccessException("User must be unique", 1);
        }
        user = (User) userList.get(0);
        user.setUid(uid);
        user.setGroups(getGroupNames(getUserGroups(realm, uid)));
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
    return user;
}
 
Example 7
@Test
   @Category(NoAdTest.class)
public void testAuthenticateWithLookupOperationPerformedOnAuthenticatedContext() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
	AuthenticatedLdapEntryContextCallback contextCallback = new AuthenticatedLdapEntryContextCallback() {
		public void executeWithContext(DirContext ctx, LdapEntryIdentification ldapEntryIdentification) {
			try {
				DirContextAdapter adapter = (DirContextAdapter) ctx.lookup(ldapEntryIdentification.getRelativeDn());
				assertThat(adapter.getStringAttribute("cn")).isEqualTo("Some Person3");
			}
			catch (NamingException e) {
				throw new RuntimeException("Failed to lookup " + ldapEntryIdentification.getRelativeDn(), e);
			}
		}
	};
	assertThat(tested.authenticate("", filter.toString(), "password", contextCallback)).isTrue();
}
 
Example 8
private AndFilter getLoginFilter(LdapE ldap, String loginName) {
    String objectClass = ldap.getObjectClass();
    String[] arr = objectClass.split(",");
    AndFilter andFilter = new AndFilter();
    for (String str : arr) {
        andFilter.and(new EqualsFilter(OBJECT_CLASS, str));
    }
    andFilter.and(new EqualsFilter(ldap.getLoginNameField(), loginName));
    return andFilter;
}
 
Example 9
private String accountAsUserDn2Authentication(String loginName, LdapE ldap, LdapContextSource contextSource, AndFilter filter) {
    contextSource.setUserDn(ldap.getAccount());
    contextSource.setPassword(ldap.getPassword());
    contextSource.afterPropertiesSet();
    LdapTemplate template = new LdapTemplate(contextSource);
    if (DirectoryType.MICROSOFT_ACTIVE_DIRECTORY.value().equals(ldap.getDirectoryType())) {
        template.setIgnorePartialResultException(true);
    }
    String userDn = null;
    try {
        List<String> names =
                template.search(
                        query()
                                .searchScope(SearchScope.SUBTREE)
                                .filter(filter),
                        new AbstractContextMapper() {
                            @Override
                            protected Object doMapFromContext(DirContextOperations ctx) {
                                return ctx.getNameInNamespace();
                            }
                        });
        userDn = getUserDn(names, ldap.getLoginNameField(), loginName);
    } catch (Exception e) {
        LOG.error("use ldap account as userDn and password to authentication but search failed, filter {}," +
                " maybe the account or password is illegal, and check for the ldap config, exception {}", filter, e);
    }
    return userDn;
}
 
Example 10
Source Project: Spring-5.0-Projects   Source File: LdapAuthRepositoryCustomImpl.java    License: MIT License 5 votes vote down vote up
/**
 * This method will return roles of given user.
 */
@Override
public List<LdapGranntedAuthority> getUserAuthorities(String userName) {
	AndFilter groupFilter = new AndFilter();
	groupFilter.and(new EqualsFilter("objectclass","groupOfNames"));
	groupFilter.and(new EqualsFilter("member","uid="+userName+",ou=users,o=packtPublisher"));
	List<LdapGranntedAuthority> userRoleLst = ldapTemplate.search(LdapQueryBuilder.query().filter(groupFilter),new LdapRoleMapper());
	return userRoleLst;
}
 
Example 11
Source Project: taskana   Source File: LdapClient.java    License: Apache License 2.0 5 votes vote down vote up
public List<AccessIdRepresentationModel> searchUsersByNameOrAccessId(final String name)
    throws InvalidArgumentException {
  LOGGER.debug("entry to searchUsersByNameOrAccessId(name = {}).", name);
  isInitOrFail();
  testMinSearchForLength(name);

  final AndFilter andFilter = new AndFilter();
  andFilter.and(new EqualsFilter(getUserSearchFilterName(), getUserSearchFilterValue()));
  final OrFilter orFilter = new OrFilter();

  orFilter.or(new WhitespaceWildcardsFilter(getUserFirstnameAttribute(), name));
  orFilter.or(new WhitespaceWildcardsFilter(getUserLastnameAttribute(), name));
  orFilter.or(new WhitespaceWildcardsFilter(getUserIdAttribute(), name));
  andFilter.and(orFilter);

  String[] userAttributesToReturn = {
    getUserFirstnameAttribute(), getUserLastnameAttribute(), getUserIdAttribute()
  };

  final List<AccessIdRepresentationModel> accessIds =
      ldapTemplate.search(
          getUserSearchBase(),
          andFilter.encode(),
          SearchControls.SUBTREE_SCOPE,
          userAttributesToReturn,
          new UserContextMapper());
  LOGGER.debug(
      "exit from searchUsersByNameOrAccessId. Retrieved the following users: {}.", accessIds);
  return accessIds;
}
 
Example 12
Source Project: taskana   Source File: LdapClient.java    License: Apache License 2.0 5 votes vote down vote up
public List<AccessIdRepresentationModel> getUsersByAccessId(final String accessId) {
  LOGGER.debug("entry to searchUsersByAccessId(name = {}).", accessId);
  isInitOrFail();

  final AndFilter andFilter = new AndFilter();
  andFilter.and(new EqualsFilter(getUserSearchFilterName(), getUserSearchFilterValue()));
  andFilter.and(new EqualsFilter(getUserIdAttribute(), accessId));

  String[] userAttributesToReturn = {
    getUserFirstnameAttribute(), getUserLastnameAttribute(), getUserIdAttribute()
  };

  final List<AccessIdRepresentationModel> accessIds =
      ldapTemplate.search(
          getUserSearchBase(),
          andFilter.encode(),
          SearchControls.SUBTREE_SCOPE,
          userAttributesToReturn,
          new UserContextMapper());
  LOGGER.debug("exit from searchUsersByAccessId. Retrieved the following users: {}.", accessIds);
  return accessIds;
}
 
Example 13
Source Project: zstack   Source File: LdapUpgradeExtension.java    License: Apache License 2.0 5 votes vote down vote up
private void update(LdapTemplate ldapTemplate, LdapAccountRefVO ref){
    String uid = ref.getLdapUid();

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("uid", ref.getLdapUid()));

    List<Object> result = ldapTemplate.search("", filter.toString(), new AbstractContextMapper<Object>() {
        @Override
        protected Object doMapFromContext(DirContextOperations ctx) {
            return ctx.getNameInNamespace();
        }
    });

    if(result.size() == 0){
        logger.error(String.format("Can not find ldapUid[%s] dn", uid));
        return;
    }

    if(result.size() > 1){
        logger.error(String.format("ldapUid[%s] More than one dn result", uid));
        return;
    }

    String dn = result.get(0).toString();
    ref.setLdapUid(dn);
    dbf.update(ref);
    logger.info(String.format("update ldapUid[%s] to ldapDn[%s] success", uid, dn));
}
 
Example 14
Source Project: zstack   Source File: LdapUtil.java    License: Apache License 2.0 5 votes vote down vote up
void findLdapDnMemberOfList(LdapTemplate ldapTemplate, String ldapDn, List<String> resultDnList, List<String> dnIgnoreList){
    if(dnIgnoreList.contains(ldapDn)){
        return;
    }

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter(getMemberKey(), ldapDn));

    List<Object> groupList = ldapTemplate.search("", filter.toString(), new AbstractContextMapper<Object>() {
        @Override
        protected Object doMapFromContext(DirContextOperations ctx) {
            return ctx.getNameInNamespace();
        }
    });

    if(groupList.isEmpty()){
        dnIgnoreList.add(ldapDn);
        return;
    }

    for(Object groupObj : groupList){
        if(groupObj == null || !(groupObj instanceof String)){
            continue;
        }

        String groupDn = (String)groupObj;

        if(resultDnList.contains(groupDn)){
            continue;
        }

        resultDnList.add(groupDn);
        findLdapDnMemberOfList(ldapTemplate, groupDn, resultDnList, dnIgnoreList);
    }
}
 
Example 15
Source Project: cxf   Source File: UserServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static Map<String, Attribute> getAttributesOfEntry(LdapTemplate ldapTemplate, String baseDN,
                                                           String objectClass, String searchFilter,
                                                           String[] searchAttributes) {

    Map<String, Attribute> ldapAttributes = null;

    AttributesMapper<Map<String, Attribute>> mapper =
        new AttributesMapper<Map<String, Attribute>>() {
        public Map<String, Attribute> mapFromAttributes(Attributes attrs) throws NamingException {
            Map<String, Attribute> map = new HashMap<>();
            NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
            while (attrEnum.hasMore()) {
                Attribute att = attrEnum.next();
                map.put(att.getID(), att);
            }
            return map;
        }
    };

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", objectClass)).and(new HardcodedFilter(searchFilter));

    List<?> result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
    if (result != null && !result.isEmpty()) {
        ldapAttributes = CastUtils.cast((Map<?, ?>)result.get(0));
    }

    return ldapAttributes;
}
 
Example 16
Source Project: cxf   Source File: LdapUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Map<String, Attribute> getAttributesOfEntry(LdapTemplate ldapTemplate, String baseDN,
    String objectClass, String filterAttributeName, String filterAttributeValue,
    String[] searchAttributes) {

    Map<String, Attribute> ldapAttributes = null;

    AttributesMapper<Map<String, Attribute>> mapper =
        new AttributesMapper<Map<String, Attribute>>() {
            public Map<String, Attribute> mapFromAttributes(Attributes attrs) throws NamingException {
                Map<String, Attribute> map = new HashMap<>();
                NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
                while (attrEnum.hasMore()) {
                    Attribute att = attrEnum.next();
                    map.put(att.getID(), att);
                }
                return map;
            }
        };

    List<?> result = null;
    AndFilter filter = new AndFilter();
    filter.and(
            new EqualsFilter("objectclass", objectClass)).and(
                    new EqualsFilter(filterAttributeName, filterAttributeValue));

    result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
    if (result != null && !result.isEmpty()) {
        ldapAttributes = CastUtils.cast((Map<?, ?>)result.get(0));
    }

    return ldapAttributes;
}
 
Example 17
Source Project: cxf   Source File: LdapUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static List<String> getAttributeOfEntries(
    LdapTemplate ldapTemplate, String baseDN,
    String objectClass, List<Filter> filters,
    String searchAttribute) {

    List<String> ldapAttributes = null;

    AttributesMapper<Object> mapper =
        new AttributesMapper<Object>() {
        public Object mapFromAttributes(Attributes attrs) throws NamingException {
            NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
            while (attrEnum.hasMore()) {
                return attrEnum.next().get();
            }
            return null;
        }
    };

    String[] searchAttributes = new String[] {searchAttribute};

    List<?> result = null;
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", objectClass));
    if (filters != null) {
        for (Filter f : filters) {
            filter.and(f);
        }
    }

    result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
    if (result != null && !result.isEmpty()) {
        ldapAttributes = CastUtils.cast((List<?>)result);
    }

    return ldapAttributes;
}
 
Example 18
Source Project: secure-data-service   Source File: UserService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param realm
 *            The realm under which the user exists
 * @param userId
 *            The id of the user
 * @return
 */
public User getUser(String realm, String userId) {
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", userObjectClass)).and(new EqualsFilter(userSearchAttribute, userId));
    DistinguishedName dn = new DistinguishedName("ou=" + realm);
    PersonContextMapper pcm = new PersonContextMapper();
    boolean needAdditionalAttributes = (realm != null && realm.equals(sliAdminRealmName));
    pcm.setAddAttributes(needAdditionalAttributes);
    return (User) ldapTemplate.searchForObject(dn, filter.toString(), pcm);
}
 
Example 19
Source Project: secure-data-service   Source File: LdapServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Collection<Group> getUserGroups(String realm, String uid) {
    DistinguishedName dn = new DistinguishedName("ou=" + realm);
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter(OBJECTCLASS, groupObjectClass)).and(new EqualsFilter(groupSearchAttribute, uid));
    List<Group> groups = ldapTemplate.search(dn, filter.toString(), new GroupContextMapper());
    return groups;
}
 
Example 20
Source Project: secure-data-service   Source File: LdapServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Group getGroup(String realm, String groupName) {
    DistinguishedName dn = new DistinguishedName("ou=" + realm);
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter(OBJECTCLASS, groupObjectClass)).and(new EqualsFilter("cn", groupName));
    try {
        return (Group) ldapTemplate.searchForObject(dn, filter.toString(), new GroupContextMapper());
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
}
 
Example 21
@Test
   @Category(NoAdTest.class)
public void testAuthenticate() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
	assertThat(tested.authenticate("", filter.toString(), "password")).isTrue();
}
 
Example 22
@Test
@Category(NoAdTest.class)
public void testAuthenticateWithLdapQuery() {
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
    tested.authenticate(query()
            .where("objectclass").is("person")
            .and("uid").is("some.person3"),
            "password");
}
 
Example 23
@Test
   @Category(NoAdTest.class)
public void testAuthenticateWithInvalidPassword() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
	assertThat(tested.authenticate("", filter.toString(), "invalidpassword")).isFalse();
}
 
Example 24
@Test(expected = AuthenticationException.class)
@Category(NoAdTest.class)
public void testAuthenticateWithLdapQueryAndInvalidPassword() {
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
    tested.authenticate(query()
            .where("objectclass").is("person")
            .and("uid").is("some.person3"),
            "invalidpassword");
}
 
Example 25
@Test
   @Category(NoAdTest.class)
public void testAuthenticateWithInvalidPasswordAndCollectedException() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
	final CollectingAuthenticationErrorCallback errorCallback = new CollectingAuthenticationErrorCallback();
	assertThat(tested.authenticate("", filter.toString(), "invalidpassword", errorCallback)).isFalse();
	final Exception error = errorCallback.getError();
	assertThat(error).as("collected error should not be null").isNotNull();
	assertThat(error instanceof AuthenticationException).as("expected org.springframework.ldap.AuthenticationException").isTrue();
	assertThat(error.getCause() instanceof javax.naming.AuthenticationException).as("expected javax.naming.AuthenticationException").isTrue();
}
 
Example 26
@Test
   @Category(NoAdTest.class)
public void testAuthenticateWithFilterThatDoesNotMatchAnything() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(
			new EqualsFilter("uid", "some.person.that.isnt.there"));
	assertThat(tested.authenticate("", filter.toString(), "password")).isFalse();
}
 
Example 27
@Test(expected=IncorrectResultSizeDataAccessException.class)
   @Category(NoAdTest.class)
public void testAuthenticateWithFilterThatMatchesSeveralEntries() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("cn", "Some Person"));
	tested.authenticate("", filter.toString(), "password");
}
 
Example 28
@Test
   @Category(NoAdTest.class)
public void testLookupAttemptingCallback() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
	LookupAttemptingCallback callback = new LookupAttemptingCallback();
	assertThat(tested.authenticate("", filter.encode(), "password", callback)).isTrue();
}
 
Example 29
Source Project: spring-ldap   Source File: SimpleLdapTemplateITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
   @Category(NoAdTest.class)
public void testAuthenticate() {
	AndFilter filter = new AndFilter();
	filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
	assertThat(ldapTemplate.authenticate("", filter.toString(), "password")).isTrue();
}
 
Example 30
Source Project: spring-ldap   Source File: DefaultObjectDirectoryMapper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds an {@link org.springframework.ldap.odm.annotations} annotated class to the set
 * managed by this OdmManager.
 *
 * @param managedClass The class to add to the managed set.
 */
private EntityData addManagedClass(Class<?> managedClass) {
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Adding class %1$s to managed set", managedClass));
    }

    // Extract the meta-data from the class
    ObjectMetaData metaData=new ObjectMetaData(managedClass);

    // Check we can construct the target type - it must have a zero argument public constructor
    try {
        managedClass.getConstructor();
    } catch (NoSuchMethodException e) {
        throw new InvalidEntryException(String.format(
                "The class %1$s must have a zero argument constructor to be an Entry", managedClass), e);
    }

    // Check we have all of the necessary converters for the class
    for (Field field : metaData) {
        AttributeMetaData attributeInfo = metaData.getAttribute(field);
        if (!attributeInfo.isTransient() && !attributeInfo.isId() && !(attributeInfo.isObjectClass())) {
            verifyConversion(managedClass, field, attributeInfo);
        }
    }

    // Filter so we only read the object classes supported by the managedClass
    AndFilter ocFilter = new AndFilter();
    for (CaseIgnoreString oc : metaData.getObjectClasses()) {
        ocFilter.and(new EqualsFilter(OBJECT_CLASS_ATTRIBUTE, oc.toString()));
    }

    EntityData newValue = new EntityData(metaData, ocFilter);
    EntityData previousValue = metaDataMap.putIfAbsent(managedClass, newValue);
    // Just in case someone beat us to it
    if(previousValue != null) {
        return previousValue;
    }

    return newValue;
}