org.apache.directory.api.ldap.model.cursor.EntryCursor Java Examples

The following examples show how to use org.apache.directory.api.ldap.model.cursor.EntryCursor. 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: ApacheLdapProviderImpl.java    From ldapchai with GNU Lesser General Public License v2.1 6 votes vote down vote up
public String readStringAttribute( final String entryDN, final String attribute )
        throws ChaiOperationException, ChaiUnavailableException, IllegalStateException
{
    activityPreCheck();
    getInputValidator().readStringAttribute( entryDN, attribute );

    try
    {
        final EntryCursor entries = connection.search(
                entryDN,
                ChaiConstant.FILTER_OBJECTCLASS_ANY,
                org.apache.directory.api.ldap.model.message.SearchScope.OBJECT,
                attribute
        );
        final Entry entry = entries.iterator().next();
        final Attribute attr = entry.get( attribute );
        return attr == null ? null : attr.getString();

    }
    catch ( LdapException e )
    {
        throw ChaiOperationException.forErrorMessage( e.getMessage() );
    }
}
 
Example #2
Source File: LdapLoginManager.java    From openmeetings with Apache License 2.0 6 votes vote down vote up
private void importUsers(LdapWorker w, EntryCursor cursor, Long domainId, boolean print) throws LdapException, CursorException, OmException, IOException {
	while (cursor.next()) {
		try {
			Entry e = cursor.get();
			User u = userDao.getByLogin(getLogin(w.config, e), Type.LDAP, domainId);
			u = w.getUser(e, u);
			if (print) {
				log.info("Going to import user: {}", u);
			} else {
				userDao.update(u, null);
				log.info("User {}, was imported", u);
			}
		} catch (CursorLdapReferralException cle) {
			log.warn(WARN_REFERRAL);
		}
	}
}
 
Example #3
Source File: LdapLoginManager.java    From openmeetings with Apache License 2.0 6 votes vote down vote up
private void fillGroups(Dn baseDn, String searchQ, List<Dn> groups) throws IOException, LdapException, CursorException {
	try (EntryCursor cursor = new EntryCursorImpl(conn.search(
			new SearchRequestImpl()
				.setBase(baseDn)
				.setFilter(searchQ)
				.setScope(SearchScope.SUBTREE)
				.addAttributes("*")
				.setDerefAliases(AliasDerefMode.DEREF_ALWAYS))))
	{
		while (cursor.next()) {
			try {
				Entry e = cursor.get();
				groups.add(e.getDn());
			} catch (CursorLdapReferralException cle) {
				log.warn(WARN_REFERRAL);
			}
		}
	}
}
 
Example #4
Source File: LdapConnectionWrapper.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public EntryCursor search( Dn baseDn, String filter, SearchScope scope, String... attributes )
    throws LdapException
{
    return connection.search( baseDn, filter, scope, attributes );
}
 
Example #5
Source File: LdapConnectionWrapper.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public EntryCursor search( String baseDn, String filter, SearchScope scope, String... attributes )
    throws LdapException
{
    return connection.search( baseDn, filter, scope, attributes );
}
 
Example #6
Source File: LdapNetworkConnection.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public EntryCursor search( Dn baseDn, String filter, SearchScope scope, String... attributes )
    throws LdapException
{
    if ( baseDn == null )
    {
        if ( LOG.isDebugEnabled() )
        {
            LOG.debug( I18n.msg( I18n.MSG_04138_NULL_DN_SEARCH ) );
        }
        
        throw new IllegalArgumentException( I18n.err( I18n.ERR_04129_NULL_BASE_DN ) );
    }

    // Create a new SearchRequest object
    SearchRequest searchRequest = new SearchRequestImpl();

    searchRequest.setBase( baseDn );
    searchRequest.setFilter( filter );
    searchRequest.setScope( scope );
    searchRequest.addAttributes( attributes );
    searchRequest.setDerefAliases( AliasDerefMode.DEREF_ALWAYS );

    // Process the request in blocking mode
    return new EntryCursorImpl( search( searchRequest ) );
}
 
Example #7
Source File: LdapNetworkConnection.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public EntryCursor search( String baseDn, String filter, SearchScope scope, String... attributes )
    throws LdapException
{
    return search( new Dn( baseDn ), filter, scope, attributes );
}
 
Example #8
Source File: ApacheLdapProviderImpl.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
private List<Value> readMultiAttribute( final String entryDN, final String attribute )
        throws ChaiOperationException
{
    try
    {
        final EntryCursor entries = connection.search(
                entryDN,
                ChaiConstant.FILTER_OBJECTCLASS_ANY,
                org.apache.directory.api.ldap.model.message.SearchScope.OBJECT,
                attribute
        );
        final Entry entry = entries.iterator().next();
        final List<Value> returnSet = new ArrayList<>();
        final Attribute attr = entry.get( attribute );
        if ( attr == null )
        {
            return null;
        }
        for ( final Value value : attr )
        {
            if ( value != null )
            {
                returnSet.add( value );
            }
        }
        return Collections.unmodifiableList( returnSet );

    }
    catch ( LdapException e )
    {
        throw ChaiOperationException.forErrorMessage( e.getMessage() );
    }

}
 
Example #9
Source File: ApacheLdapProviderImpl.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Map<String, String> readStringAttributes( final String entryDN, final Set<String> attributes )
        throws ChaiOperationException, ChaiUnavailableException, IllegalStateException
{
    activityPreCheck();
    getInputValidator().readStringAttributes( entryDN, attributes );

    try
    {
        final EntryCursor entries = connection.search(
                entryDN,
                ChaiConstant.FILTER_OBJECTCLASS_ANY,
                org.apache.directory.api.ldap.model.message.SearchScope.OBJECT,
                attributes.toArray( new String[attributes.size()] )
        );
        final Entry entry = entries.iterator().next();
        final Collection<Attribute> attrs = entry.getAttributes();
        final Map<String, String> returnMap = new LinkedHashMap<>();
        for ( final Attribute attr : attrs )
        {
            final String name = attr.getId();
            final String value = attr.getString();
            returnMap.put( name, value );
        }

        return returnMap;

    }
    catch ( LdapException e )
    {
        throw ChaiOperationException.forErrorMessage( e.getMessage() );
    }
}
 
Example #10
Source File: LdapLoginManager.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
private static Map.Entry<Dn, Entry> searchAndBind(LdapWorker w, String login, String passwd) throws LdapException, CursorException, OmException, IOException {
	Dn userDn = null;
	Entry entry = null;
	bindAdmin(w.conn, w.options);
	Dn baseDn = new Dn(w.options.searchBase);
	String searchQ = String.format(w.options.searchQuery, login);

	try (EntryCursor cursor = new EntryCursorImpl(w.conn.search(
			new SearchRequestImpl()
				.setBase(baseDn)
				.setFilter(searchQ)
				.setScope(w.options.scope)
				.addAttributes("*")
				.setDerefAliases(w.options.derefMode))))
	{
		while (cursor.next()) {
			try {
				Entry e = cursor.get();
				if (userDn != null) {
					log.error("more than 1 user found in LDAP");
					throw UNKNOWN;
				}
				userDn = e.getDn();
				if (w.options.useAdminForAttrs) {
					entry = e;
				}
			} catch (CursorLdapReferralException cle) {
				log.warn(WARN_REFERRAL);
			}
		}
	}
	if (userDn == null) {
		log.error("NONE users found in LDAP");
		throw BAD_CREDENTIALS;
	}
	w.conn.bind(userDn, passwd);
	return new AbstractMap.SimpleEntry<>(userDn, entry);
}
 
Example #11
Source File: LDAPApi.java    From mamute with Apache License 2.0 5 votes vote down vote up
private Entry lookupUser(String username) throws LdapException {
	StringBuilder userQuery = new StringBuilder();
	userQuery.append("(&(objectclass=");
	userQuery.append(userObjectClass);
	userQuery.append(")(|");
	boolean hasCondition = false;
	for (String lookupAttr : lookupAttrs) {
		String attrName = lookupAttr.trim();
		if (!attrName.isEmpty()) {
			userQuery.append('(').append(attrName).append('=').append(username).append(')');
			hasCondition = true;
		}
	}
	userQuery.append("))");

	if (!hasCondition) {
		return null;
	}

	logger.debug("LDAP user query " + userQuery.toString());

	EntryCursor responseCursor = connection.search(userDn, userQuery.toString(), SearchScope.SUBTREE);
	try {
		try {
			if (responseCursor != null && responseCursor.next()) {
				Entry match = responseCursor.get();
				logger.debug("LDAP user query result: " + match.getDn());
				return match;
			}
		} catch (CursorException e) {
			logger.debug("LDAP search error", e);
			return null;
		}
	} finally {
		responseCursor.close();
	}
	return null;
}
 
Example #12
Source File: SingularityLDAPDatastore.java    From Singularity with Apache License 2.0 4 votes vote down vote up
@Override
public Optional<SingularityUser> getUser(String user) {
  if (configuration.isStripUserEmailDomain()) {
    user = user.split("@")[0];
  }

  if (ldapCache.isPresent()) {
    Optional<SingularityUser> cachedResult = ldapCache.get().getIfPresent(user);
    if (cachedResult != null) {
      return cachedResult;
    }
  }

  final Set<String> groups = new HashSet<>();

  try {
    final LdapConnection connection = connectionPool.getConnection();

    try {
      checkState(connection.isConnected(), "not connected");
      checkState(connection.isAuthenticated(), "not authenticated");
      connection.bind();

      final long startTime = System.currentTimeMillis();
      try {
        final EntryCursor userCursor = connection.search(
          configuration.getUserBaseDN(),
          String.format(configuration.getUserFilter(), user),
          SearchScope.ONELEVEL,
          configuration.getUserNameAttribute(),
          configuration.getUserEmailAttribute()
        );

        if (!userCursor.next()) {
          if (ldapCache.isPresent()) {
            ldapCache.get().put(user, Optional.empty());
          }

          return Optional.empty();
        }

        final Entry userEntry = userCursor.get();

        // get group info
        final EntryCursor cursor = connection.search(
          configuration.getGroupBaseDN(),
          String.format(configuration.getGroupFilter(), user),
          configuration.getGroupSearchScope(),
          configuration.getGroupNameAttribute()
        );

        while (cursor.next()) {
          groups.add(
            cursor.get().get(configuration.getGroupNameAttribute()).getString()
          );
        }

        Optional<SingularityUser> result = Optional.of(
          new SingularityUser(
            user,
            Optional.ofNullable(
              Strings.emptyToNull(
                userEntry.get(configuration.getUserNameAttribute()).getString()
              )
            ),
            Optional.ofNullable(
              Strings.emptyToNull(
                userEntry.get(configuration.getUserEmailAttribute()).getString()
              )
            ),
            groups
          )
        );

        if (ldapCache.isPresent()) {
          ldapCache.get().put(user, result);
        }

        return result;
      } finally {
        LOG.trace("Loaded {}'s user data in {}", user, JavaUtils.duration(startTime));
        connection.unBind();
      }
    } finally {
      connectionPool.releaseConnection(connection);
    }
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #13
Source File: LdapConnection.java    From directory-ldap-api with Apache License 2.0 2 votes vote down vote up
/**
 * Do a search, on the base object, using the given filter and scope. The
 * SearchRequest parameters default to
 * <ul>
 * <li> DerefAlias : ALWAYS
 * <li> SizeLimit : none
 * <li> TimeLimit : none
 * <li> TypesOnly : false
 * </ul>
 * 
 * @param baseDn The base for the search. It must be a valid distinguished name and can't be emtpy
 * @param filter The filter to use for this search. It can't be empty
 * @param scope The search scope : OBJECT, ONELEVEL or SUBTREE
 * @param attributes The attributes to use for this search
 * @return An {@link EntryCursor} on the result.
 * @throws LdapException if some error occurred
 */
EntryCursor search( Dn baseDn, String filter, SearchScope scope, String... attributes )
    throws LdapException;
 
Example #14
Source File: LdapConnection.java    From directory-ldap-api with Apache License 2.0 2 votes vote down vote up
/**
 * Do a search, on the base object, using the given filter and scope. The
 * SearchRequest parameters default to
 * <ul>
 * <li> DerefAlias : ALWAYS
 * <li> SizeLimit : none
 * <li> TimeLimit : none
 * <li> TypesOnly : false
 * </ul>
 *
 * @param baseDn The base for the search. It must be a valid distinguished name, and can't be emtpy
 * @param filter The filter to use for this search. It can't be empty
 * @param scope The search scope : OBJECT, ONELEVEL or SUBTREE
 * @param attributes The attributes to use for this search
 * @return An {@link EntryCursor} on the result.
 * @throws LdapException if some error occurred
 */
EntryCursor search( String baseDn, String filter, SearchScope scope, String... attributes )
    throws LdapException;