Java Code Examples for org.springframework.ldap.filter.AndFilter#and()

The following examples show how to use org.springframework.ldap.filter.AndFilter#and() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LdapClient.java    From taskana with 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 File: LdapClient.java    From taskana with 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 File: LdapManagerImpl.java    From zstack with 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 File: ChoerodonAuthenticationProvider.java    From oauth-server with Apache License 2.0 5 votes vote down vote up
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 5
Source File: LdapAuthRepositoryCustomImpl.java    From Spring-5.0-Projects with 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 6
Source File: LdapClient.java    From taskana with 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 7
Source File: LdapClient.java    From taskana with 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 8
Source File: LdapUpgradeExtension.java    From zstack with 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 9
Source File: LdapUtil.java    From zstack with 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 10
Source File: LdapUtils.java    From cxf with 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 11
Source File: DefaultObjectDirectoryMapper.java    From spring-ldap with 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;
}
 
Example 12
Source File: LdapUtil.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
public boolean authentication(String username, String password) throws RuntimeException {
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("uid", username));
    return ldapTemplate.authenticate("", filter.toString(), password);
}
 
Example 13
Source File: LdapPrincipalDaoImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
public <T> List<T> search(Class<T> type, Map<String, Object> criteria) {
    AndFilter filter = new AndFilter();
    
    for (Map.Entry<String, Object> entry : criteria.entrySet()) {
        //attempting to handle null values to prevent NPEs in this code.
        if (entry.getValue() == null) {
            entry.setValue("null");
        }
        if (entry.getValue() instanceof Iterable) {
            OrFilter orFilter = new OrFilter();
            for (String value : (Iterable<String>) entry.getValue()) {
                if (value.startsWith("!")) {
                    orFilter.or(new NotFilter(new LikeFilter(entry.getKey(), value.substring(1))));
                } else {
                    orFilter.or(new LikeFilter(entry.getKey(), value));
                }
            }
            filter.and(orFilter);
        }
        else {
            if (((String)entry.getValue()).startsWith("!")) {
                filter.and(new NotFilter(new LikeFilter(entry.getKey(), ((String)entry.getValue()).substring(1))));
            } else {
                filter.and(new LikeFilter(entry.getKey(), (String) entry.getValue()));
            }
        }
    };
    
    info("Using filter ", filter);

    debug("Looking up mapper for ", type.getSimpleName());
    final ContextMapper customMapper = contextMappers.get(type.getSimpleName());

    ContextMapperCallbackHandler callbackHandler = new CustomContextMapperCallbackHandler(customMapper);
    
    try {
        getLdapTemplate().search(DistinguishedName.EMPTY_PATH, 
                                 filter.encode(), 
                                 getSearchControls(), callbackHandler);
    }
    catch (SizeLimitExceededException e) {
        // Ignore this. We want to limit our results.
    }

    return callbackHandler.getList();
}