org.apache.directory.server.core.api.filtering.EntryFilteringCursor Java Examples

The following examples show how to use org.apache.directory.server.core.api.filtering.EntryFilteringCursor. 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: LDAPIAMPoller.java    From aws-iam-ldap-bridge with Apache License 2.0 6 votes vote down vote up
private Collection<Entry> getAllEntries(String rootDN, String className) {
    try {
        Dn dn = directory.getDnFactory().create(rootDN);
        dn.apply(directory.getSchemaManager());
        ExprNode filter = FilterParser.parse(directory.getSchemaManager(), String.format("(ObjectClass=%s)", className));
        NameComponentNormalizer ncn = new ConcreteNameComponentNormalizer( directory.getSchemaManager() );
        FilterNormalizingVisitor visitor = new FilterNormalizingVisitor( ncn, directory.getSchemaManager() );
        filter.accept(visitor);
        SearchOperationContext context = new SearchOperationContext(directory.getAdminSession(),
                dn, SearchScope.SUBTREE, filter, SchemaConstants.ALL_USER_ATTRIBUTES, SchemaConstants.ALL_OPERATIONAL_ATTRIBUTES);
        EntryFilteringCursor cursor = directory.getPartitionNexus().search(context);
        cursor.beforeFirst();
        Collection<Entry> entries = new ArrayList<Entry>();
        while (cursor.next()) {
            Entry ent = cursor.get();
            if (ent.getDn().equals(dn)) continue;
            entries.add(ent);
        }
        cursor.close();
        return entries;
    } catch (Throwable e) {
        return Collections.emptyList();
    }
}
 
Example #2
Source File: LDAPIAMPoller.java    From aws-iam-ldap-bridge with Apache License 2.0 6 votes vote down vote up
private void clearDN(String dnStr) throws LdapException, ParseException, IOException, CursorException {
    Dn dn = directory.getDnFactory().create(dnStr);
    dn.apply(directory.getSchemaManager());
    ExprNode filter = FilterParser.parse(directory.getSchemaManager(), "(ObjectClass=*)");
    NameComponentNormalizer ncn = new ConcreteNameComponentNormalizer( directory.getSchemaManager() );
    FilterNormalizingVisitor visitor = new FilterNormalizingVisitor( ncn, directory.getSchemaManager() );
    filter.accept(visitor);
    SearchOperationContext context = new SearchOperationContext(directory.getAdminSession(),
            dn, SearchScope.SUBTREE, filter, SchemaConstants.ALL_USER_ATTRIBUTES, SchemaConstants.ALL_OPERATIONAL_ATTRIBUTES);
    EntryFilteringCursor cursor = directory.getPartitionNexus().search(context);
    cursor.beforeFirst();
    Collection<Dn> dns = new ArrayList<Dn>();
    while (cursor.next()) {
        Entry ent = cursor.get();
        if (ent.getDn().equals(dn)) continue;
        dns.add(ent.getDn());
    }
    cursor.close();

    LOG.debug("Deleting " + dns.size() + " items from under " + dnStr);
    for (Dn deleteDn: dns) {
        directory.getAdminSession().delete(deleteDn);
    }
}
 
Example #3
Source File: DefaultCoreSession.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public EntryFilteringCursor search( Dn dn, String filter, boolean ignoreReferrals ) throws LdapException
{
    OperationManager operationManager = directoryService.getOperationManager();
    ExprNode filterNode = null;

    try
    {
        filterNode = FilterParser.parse( directoryService.getSchemaManager(), filter );
    }
    catch ( ParseException pe )
    {
        throw new LdapInvalidSearchFilterException( pe.getMessage() );
    }

    SearchOperationContext searchContext = new SearchOperationContext( this, dn, SearchScope.OBJECT, filterNode,
        ( String ) null );
    searchContext.setAliasDerefMode( AliasDerefMode.DEREF_ALWAYS );
    setReferralHandling( searchContext, ignoreReferrals );

    return operationManager.search( searchContext );
}
 
Example #4
Source File: DefaultCoreSession.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
public EntryFilteringCursor search( SearchRequest searchRequest ) throws LdapException
{
    SearchOperationContext searchContext = new SearchOperationContext( this, searchRequest );
    searchContext.setSyncreplSearch( searchRequest.getControls().containsKey( SyncRequestValue.OID ) );

    OperationManager operationManager = directoryService.getOperationManager();

    EntryFilteringCursor cursor = null;

    try
    {
        cursor = operationManager.search( searchContext );
    }
    catch ( LdapException e )
    {
        searchRequest.getResultResponse().addAllControls( searchContext.getResponseControls() );
        throw e;
    }

    searchRequest.getResultResponse().addAllControls( searchContext.getResponseControls() );

    return cursor;
}
 
Example #5
Source File: DefaultPartitionNexus.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public EntryFilteringCursor search( SearchOperationContext searchContext ) throws LdapException
{
    Dn base = searchContext.getDn();

    // TODO since we're handling the *, and + in the EntryFilteringCursor
    // we may not need this code: we need see if this is actually the
    // case and remove this code.
    if ( base.size() == 0 )
    {
        return searchFromRoot( searchContext );
    }

    // Not sure we need this code...
    base.apply( schemaManager );

    // Normal case : do a search on the specific partition
    Partition backend = getPartition( base );

    return backend.search( searchContext );
}
 
Example #6
Source File: DefaultPartitionNexus.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public EntryFilteringCursor search( SearchOperationContext searchContext ) throws LdapException
{
    Dn base = searchContext.getDn();

    // TODO since we're handling the *, and + in the EntryFilteringCursor
    // we may not need this code: we need see if this is actually the
    // case and remove this code.
    if ( base.size() == 0 )
    {
        return searchFromRoot( searchContext );
    }

    // Not sure we need this code...
    base.apply( schemaManager );

    // Normal case : do a search on the specific partition
    Partition backend = getPartition( base );

    return backend.search( searchContext );
}
 
Example #7
Source File: RangedAttributeInterceptor.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public RangedEntryFilteringCursor(EntryFilteringCursor c, String name, Integer min, Integer max) {
    this.c = c;
    this.name = name;
    this.min = min;
    this.max = max;
    AttributeType type = new AttributeType(name);
}
 
Example #8
Source File: SearchRequestHandler.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * Manage the abandoned Paged Search (when paged size = 0). We have to
 * remove the cookie and its associated cursor from the session.
 */
private SearchResultDone abandonPagedSearch( LdapSession session, SearchRequest req ) throws Exception
{
    PagedResults pagedSearchControl = ( PagedResults ) req.getControls().get( PagedResults.OID );
    byte[] cookie = pagedSearchControl.getCookie();

    if ( !Strings.isEmpty( cookie ) )
    {
        // If the cookie is not null, we have to destroy the associated
        // cursor stored into the session (if any)
        int cookieValue = pagedSearchControl.getCookieValue();
        PagedSearchContext psCookie = session.removePagedSearchContext( cookieValue );
        pagedSearchControl.setCookie( psCookie.getCookie() );
        pagedSearchControl.setSize( 0 );
        pagedSearchControl.setCritical( true );

        // Close the cursor
        EntryFilteringCursor cursor = psCookie.getCursor();

        if ( cursor != null )
        {
            cursor.close();
        }
    }
    else
    {
        pagedSearchControl.setSize( 0 );
        pagedSearchControl.setCritical( true );
    }

    // and return
    // DO NOT WRITE THE RESPONSE - JUST RETURN IT
    LdapResult ldapResult = req.getResultResponse().getLdapResult();
    ldapResult.setResultCode( ResultCodeEnum.SUCCESS );
    req.getResultResponse().addControl( pagedSearchControl );
    return req.getResultResponse();
}
 
Example #9
Source File: DefaultCoreSession.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
public EntryFilteringCursor list( Dn dn, AliasDerefMode aliasDerefMode,
    String... returningAttributes ) throws LdapException
{
    OperationManager operationManager = directoryService.getOperationManager();

    PresenceNode filter = new PresenceNode( OBJECT_CLASS_AT );
    SearchOperationContext searchContext = new SearchOperationContext( this, dn, SearchScope.ONELEVEL, filter,
        returningAttributes );
    searchContext.setAliasDerefMode( aliasDerefMode );

    return operationManager.search( searchContext );
}
 
Example #10
Source File: DefaultCoreSession.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
public EntryFilteringCursor search( Dn dn, SearchScope scope, ExprNode filter, AliasDerefMode aliasDerefMode,
    String... returningAttributes ) throws LdapException
{
    OperationManager operationManager = directoryService.getOperationManager();

    SearchOperationContext searchContext = new SearchOperationContext( this, dn, scope, filter, returningAttributes );
    searchContext.setAliasDerefMode( aliasDerefMode );

    return operationManager.search( searchContext );
}
 
Example #11
Source File: NormalizationInterceptor.java    From syncope with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public EntryFilteringCursor search( SearchOperationContext searchContext ) throws LdapException
{
    Dn dn = searchContext.getDn();
    
    if ( !dn.isSchemaAware() )
    {
        searchContext.setDn( new Dn( schemaManager, dn ) );
    }

    ExprNode filter = searchContext.getFilter();

    if ( filter == null )
    {
        LOG.warn( "undefined filter based on undefined attributeType not evaluted at all.  Returning empty enumeration." );
        return new EntryFilteringCursorImpl( new EmptyCursor<Entry>(), searchContext, schemaManager );
    }

    // Normalize the filter
    filter = ( ExprNode ) filter.accept( normVisitor );

    if ( filter == null )
    {
        LOG.warn( "undefined filter based on undefined attributeType not evaluted at all.  Returning empty enumeration." );
        return new EntryFilteringCursorImpl( new EmptyCursor<Entry>(), searchContext, schemaManager );
    }

    // We now have to remove the (ObjectClass=*) filter if it's present, and to add the scope filter
    ExprNode modifiedFilter = removeObjectClass( filter );

    searchContext.setFilter( modifiedFilter );

    // TODO Normalize the returned Attributes, storing the UP attributes to format the returned values.
    return next( searchContext );
}
 
Example #12
Source File: SearchRequestHandler.java    From MyVirtualDirectory with Apache License 2.0 4 votes vote down vote up
private void writeResults( LdapSession session, SearchRequest req, LdapResult ldapResult,
    EntryFilteringCursor cursor, long sizeLimit ) throws Exception
{
    long count = 0;

    while ( ( count < sizeLimit ) && cursor.next() )
    {
        // Handle closed session
        if ( session.getIoSession().isClosing() )
        {
            // The client has closed the connection
            if ( IS_DEBUG )
            {
                LOG.debug( "Request terminated for message {}, the client has closed the session",
                    req.getMessageId() );
            }

            break;
        }

        if ( req.isAbandoned() )
        {
            cursor.close( new OperationAbandonedException() );

            // The cursor has been closed by an abandon request.
            if ( IS_DEBUG )
            {
                LOG.debug( "Request terminated by an AbandonRequest for message {}", req.getMessageId() );
            }

            break;
        }

        Entry entry = cursor.get();
        session.getIoSession().write( generateResponse( session, req, entry ) );

        if ( IS_DEBUG )
        {
            LOG.debug( "Sending {}", entry.getDn() );
        }

        count++;
    }

    // DO NOT WRITE THE RESPONSE - JUST RETURN IT
    ldapResult.setResultCode( ResultCodeEnum.SUCCESS );

    if ( ( count >= sizeLimit ) && ( cursor.next() ) )
    {
        // We have reached the limit
        // Move backward on the cursor to restore the previous position, as we moved forward
        // to check if there is one more entry available
        cursor.previous();
        // Special case if the user has requested more elements than the request size limit
        ldapResult.setResultCode( ResultCodeEnum.SIZE_LIMIT_EXCEEDED );
    }
}
 
Example #13
Source File: RangedAttributeInterceptor.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public EntryFilteringCursor search(SearchOperationContext sc) throws LdapException {
    Set<AttributeTypeOptions> attrs = sc.getReturningAttributes();
    Integer lmin = null, lmax = max;
    if (attrs != null) {
        for (AttributeTypeOptions attr : attrs) {
            if (attr.getAttributeType().getName().equalsIgnoreCase(name)) {
                if (attr.getOptions() != null) {
                    for (String option : attr.getOptions()) {
                        if (option.startsWith("range=")) {
                            String[] ranges = option.substring(6).split("-");
                            if (ranges.length == 2) {
                                try {
                                    lmin = Integer.parseInt(ranges[0]);
                                    if (lmin < 0) {
                                        lmin = 0;
                                    }
                                    if ("*".equals(ranges[1])) {
                                        lmax = lmin + max;
                                    } else {
                                        lmax = Integer.parseInt(ranges[1]);
                                        if (lmax < lmin) {
                                            lmax = lmin;
                                        } else if (lmax > lmin + max) {
                                            lmax = lmin + max;
                                        }
                                    }
                                } catch (NumberFormatException e) {
                                    lmin = null;
                                    lmax = max;
                                }
                            }
                        }
                    }
                }
                break;
            }
        }
    }
    return new RangedEntryFilteringCursor(super.next(sc), name, lmin, lmax);
}
 
Example #14
Source File: DefaultCoreSession.java    From MyVirtualDirectory with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public EntryFilteringCursor search( Dn dn, String filter ) throws LdapException
{
    return search( dn, filter, true );
}
 
Example #15
Source File: SearchRequestHandler.java    From MyVirtualDirectory with Apache License 2.0 4 votes vote down vote up
/**
 * Conducts a simple search across the result set returning each entry
 * back except for the search response done.  This is calculated but not
 * returned so the persistent search mechanism can leverage this method
 * along with standard search.<br>
 * <br>
 * @param session the LDAP session object for this request
 * @param req the search request
 * @return the result done
 * @throws Exception if there are failures while processing the request
 */
private SearchResultDone doSimpleSearch( LdapSession session, SearchRequest req ) throws Exception
{
    LdapResult ldapResult = req.getResultResponse().getLdapResult();

    // Check if we are using the Paged Search Control
    Object control = req.getControls().get( PagedResults.OID );

    if ( control != null )
    {
        // Let's deal with the pagedControl
        return doPagedSearch( session, req, ( PagedResultsDecorator ) control );
    }

    // A normal search
    // Check that we have a cursor or not.
    // No cursor : do a search.
    EntryFilteringCursor cursor = session.getCoreSession().search( req );

    // register the request in the session
    session.registerSearchRequest( req, cursor );

    // Position the cursor at the beginning
    cursor.beforeFirst();

    /*
     * Iterate through all search results building and sending back responses
     * for each search result returned.
     */
    try
    {
        // Get the size limits
        // Don't bother setting size limits for administrators that don't ask for it
        long serverLimit = getServerSizeLimit( session, req );

        long requestLimit = req.getSizeLimit() == 0L ? Long.MAX_VALUE : req.getSizeLimit();

        req.addAbandonListener( new SearchAbandonListener( ldapServer, cursor ) );
        setTimeLimitsOnCursor( req, session, cursor );

        if ( IS_DEBUG )
        {
            LOG.debug( "using <{},{}> for size limit", requestLimit, serverLimit );
        }

        long sizeLimit = min( requestLimit, serverLimit );

        writeResults( session, req, ldapResult, cursor, sizeLimit );
    }
    finally
    {
        if ( ( cursor != null ) && !cursor.isClosed() )
        {
            try
            {
                cursor.close();
            }
            catch ( Exception e )
            {
                LOG.error( I18n.err( I18n.ERR_168 ), e );
            }
        }
    }

    return req.getResultResponse();
}
 
Example #16
Source File: SearchRequestHandler.java    From MyVirtualDirectory with Apache License 2.0 4 votes vote down vote up
private void readPagedResults( LdapSession session, SearchRequest req, LdapResult ldapResult,
    EntryFilteringCursor cursor, long sizeLimit, int pagedLimit, PagedSearchContext pagedContext,
    PagedResultsDecorator pagedResultsControl ) throws Exception
{
    req.addAbandonListener( new SearchAbandonListener( ldapServer, cursor ) );
    setTimeLimitsOnCursor( req, session, cursor );

    if ( IS_DEBUG )
    {
        LOG.debug( "using <{},{}> for size limit", sizeLimit, pagedLimit );
    }

    int cookieValue = 0;

    int count = pagedContext.getCurrentPosition();
    int pageCount = 0;

    while ( ( count < sizeLimit ) && ( pageCount < pagedLimit ) && cursor.next() )
    {
        if ( session.getIoSession().isClosing() )
        {
            break;
        }

        Entry entry = cursor.get();
        session.getIoSession().write( generateResponse( session, req, entry ) );
        count++;
        pageCount++;
    }

    // DO NOT WRITE THE RESPONSE - JUST RETURN IT
    ldapResult.setResultCode( ResultCodeEnum.SUCCESS );

    boolean hasMoreEntry = cursor.next();

    // We have some entry, move back to the first one, as we just moved forward 
    // to get the first entry
    if ( hasMoreEntry )
    {
        cursor.previous();
    }

    if ( !hasMoreEntry )
    {
        // That means we don't have anymore entry
        // If we are here, it means we have returned all the entries
        // We have to remove the cookie from the session
        cookieValue = pagedContext.getCookieValue();
        PagedSearchContext psCookie = session.removePagedSearchContext( cookieValue );

        // Close the cursor if there is one
        if ( psCookie != null )
        {
            cursor = psCookie.getCursor();

            if ( cursor != null )
            {
                cursor.close();
            }
        }

        pagedResultsControl = new PagedResultsDecorator( ldapServer.getDirectoryService()
            .getLdapCodecService() );
        pagedResultsControl.setCritical( true );
        pagedResultsControl.setSize( 0 );
        req.getResultResponse().addControl( pagedResultsControl );

        return;
    }
    else
    {
        // We have reached one limit

        if ( count < sizeLimit )
        {
            // We stop here. We have to add a ResponseControl
            // DO NOT WRITE THE RESPONSE - JUST RETURN IT
            ldapResult.setResultCode( ResultCodeEnum.SUCCESS );
            req.getResultResponse().addControl( pagedResultsControl );

            // Stores the cursor current position
            pagedContext.incrementCurrentPosition( pageCount );
            return;
        }
        else
        {
            // Return an exception, close the cursor, and clean the session
            ldapResult.setResultCode( ResultCodeEnum.SIZE_LIMIT_EXCEEDED );

            if ( cursor != null )
            {
                cursor.close();
            }

            session.removePagedSearchContext( cookieValue );

            return;
        }
    }
}
 
Example #17
Source File: SearchRequestHandler.java    From MyVirtualDirectory with Apache License 2.0 4 votes vote down vote up
/**
 * Based on the server maximum time limits configured for search and the
 * requested time limits this method determines if at all to replace the
 * default ClosureMonitor of the result set Cursor with one that closes
 * the Cursor when either server mandated or request mandated time limits
 * are reached.
 *
 * @param req the {@link SearchRequest} issued
 * @param session the {@link LdapSession} on which search was requested
 * @param cursor the {@link EntryFilteringCursor} over the search results
 */
private void setTimeLimitsOnCursor( SearchRequest req, LdapSession session,
    final EntryFilteringCursor cursor )
{
    // Don't bother setting time limits for administrators
    if ( session.getCoreSession().isAnAdministrator() && req.getTimeLimit() == NO_TIME_LIMIT )
    {
        return;
    }

    /*
     * Non administrator based searches are limited by time if the server
     * has been configured with unlimited time and the request specifies
     * unlimited search time
     */
    if ( ldapServer.getMaxTimeLimit() == NO_TIME_LIMIT && req.getTimeLimit() == NO_TIME_LIMIT )
    {
        return;
    }

    /*
     * If the non-administrator user specifies unlimited time but the server
     * is configured to limit the search time then we limit by the max time
     * allowed by the configuration
     */
    if ( req.getTimeLimit() == 0 )
    {
        cursor.setClosureMonitor( new SearchTimeLimitingMonitor( ldapServer.getMaxTimeLimit(), TimeUnit.SECONDS ) );
        return;
    }

    /*
     * If the non-administrative user specifies a time limit equal to or
     * less than the maximum limit configured in the server then we
     * constrain search by the amount specified in the request
     */
    if ( ldapServer.getMaxTimeLimit() >= req.getTimeLimit() )
    {
        cursor.setClosureMonitor( new SearchTimeLimitingMonitor( req.getTimeLimit(), TimeUnit.SECONDS ) );
        return;
    }

    /*
     * Here the non-administrative user's requested time limit is greater
     * than what the server's configured maximum limit allows so we limit
     * the search to the configured limit
     */
    cursor.setClosureMonitor( new SearchTimeLimitingMonitor( ldapServer.getMaxTimeLimit(), TimeUnit.SECONDS ) );
}
 
Example #18
Source File: CoreSession.java    From MyVirtualDirectory with Apache License 2.0 2 votes vote down vote up
/**
 * Searches the directory using a specified filter. The scope is defaulting
 * to 'base'. The alias dereferencing default to 'always'. the returned attributes 
 * defaults to 'all the user attributes)
 *
 * @param dn the distinguished name of the entry to list the children of
 * @param filter the search filter
 * @param ignoreReferrals a flag to tell the server to ignore referrals
 * @throws Exception if there are failures while listing children
 */
EntryFilteringCursor search( Dn dn, String filter, boolean ignoreReferrals ) throws LdapException;
 
Example #19
Source File: CoreSession.java    From MyVirtualDirectory with Apache License 2.0 2 votes vote down vote up
/**
 * Searches the directory using a specified search scope and filter.
 *
 * @param dn the distinguished name of the entry to list the children of
 * @param scope the search scope to apply
 * @param filter the search filter
 * @param aliasDerefMode the alias dereferencing mode used
 * @param returningAttributes the attributes to return
 * @throws Exception if there are failures while listing children
 */
EntryFilteringCursor search( Dn dn, SearchScope scope, ExprNode filter, AliasDerefMode aliasDerefMode,
    String... returningAttributes ) throws LdapException;
 
Example #20
Source File: CoreSession.java    From MyVirtualDirectory with Apache License 2.0 2 votes vote down vote up
/**
 * Searches the directory using a specified filter. The scope is defaulting
 * to 'base'. The alias dereferencing default to 'always'. the returned attributes 
 * defaults to 'all the user attributes)
 *
 * @param dn the distinguished name of the entry to list the children of
 * @param filter the search filter
 * @throws Exception if there are failures while listing children
 */
EntryFilteringCursor search( Dn dn, String filter ) throws LdapException;
 
Example #21
Source File: CoreSession.java    From MyVirtualDirectory with Apache License 2.0 2 votes vote down vote up
/**
 * An optimized search operation using one level search scope which 
 * returns all the children of an entry specified by distinguished name.
 * This is equivalent to a search operation with one level scope using
 * the <code>(objectClass=*)</code> filter.
 *
 * @param dn the distinguished name of the entry to list the children of
 * @param aliasDerefMode the alias dereferencing mode used
 * @param returningAttributes the attributes to return
 * @throws Exception if there are failures while listing children
 */
EntryFilteringCursor list( Dn dn, AliasDerefMode aliasDerefMode,
    String... returningAttributes ) throws LdapException;
 
Example #22
Source File: CoreSession.java    From MyVirtualDirectory with Apache License 2.0 votes vote down vote up
EntryFilteringCursor search( SearchRequest searchRequest ) throws LdapException;