org.apache.directory.api.ldap.model.message.ResultCodeEnum Java Examples

The following examples show how to use org.apache.directory.api.ldap.model.message.ResultCodeEnum. 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: DeleteNoDResponse.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new instance of NoticeOfDisconnect.
 * 
 * @param rcode The {@link ResultCodeEnum} value to wrap
 */
private DeleteNoDResponse( ResultCodeEnum rcode )
{
    super();

    switch ( rcode )
    {
        case UNAVAILABLE:
            break;

        case PROTOCOL_ERROR:
            break;

        case STRONG_AUTH_REQUIRED:
            break;

        default:
            throw new IllegalArgumentException( I18n.err( I18n.ERR_13503_RESULT_CODE_SHOULD_BE_IN, ResultCodeEnum.UNAVAILABLE,
                ResultCodeEnum.PROTOCOL_ERROR, ResultCodeEnum.STRONG_AUTH_REQUIRED ) );
    }

    super.getLdapResult().setDiagnosticMessage( rcode.toString() + ": The server will disconnect!" );
    super.getLdapResult().setMatchedDn( null );
    super.getLdapResult().setResultCode( rcode );
}
 
Example #2
Source File: NoticeOfDisconnect.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new instance of NoticeOfDisconnect.
 * 
 * @param rcode The result code
 */
private NoticeOfDisconnect( ResultCodeEnum rcode )
{
    super( 0, EXTENSION_OID );

    switch ( rcode )
    {
        case UNAVAILABLE:
            break;

        case PROTOCOL_ERROR:
            break;

        case STRONG_AUTH_REQUIRED:
            break;

        default:
            throw new IllegalArgumentException( I18n.err( I18n.ERR_13503_RESULT_CODE_SHOULD_BE_IN, ResultCodeEnum.UNAVAILABLE,
                ResultCodeEnum.PROTOCOL_ERROR, ResultCodeEnum.STRONG_AUTH_REQUIRED ) );
    }

    super.getLdapResult().setDiagnosticMessage( rcode.toString() + ": The server will disconnect!" );
    super.getLdapResult().setMatchedDn( null );
    super.getLdapResult().setResultCode( rcode );
}
 
Example #3
Source File: LdapNetworkConnection.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Process the SearchResultDone received from the server
 * 
 * @param searchResultDone The SearchResultDone to process
 * @param searchFuture The SearchFuture to feed
 * @param responseId The associated request message ID
 * @throws InterruptedException If the Future is interrupted
 */
private void searchResultDoneReceived( SearchResultDone searchResultDone, SearchFuture searchFuture, 
    int responseId ) throws InterruptedException
{
    if ( LOG.isDebugEnabled() )
    {
        if ( searchResultDone.getLdapResult().getResultCode() == ResultCodeEnum.SUCCESS )
        {
            // Everything is fine, return the response
            LOG.debug( I18n.msg( I18n.MSG_04131_SEARCH_SUCCESSFUL, searchResultDone ) );
        }
        else
        {
            // We have had an error
            LOG.debug( I18n.msg( I18n.MSG_04129_SEARCH_FAILED, searchResultDone ) );
        }
    }

    // Store the response into the future
    searchFuture.set( searchResultDone );

    // Remove the future from the map
    removeFromFutureMaps( responseId );
}
 
Example #4
Source File: LdapNetworkConnection.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Process the CompareResponse received from the server
 * 
 * @param compareResponse The CompareResponse to process
 * @param compareFuture The CompareFuture to feed
 * @param responseId The associated request message ID
 * @throws InterruptedException If the Future is interrupted
 */
private void compareReceived( CompareResponse compareResponse, CompareFuture compareFuture, int responseId ) 
   throws InterruptedException
{
    // remove the listener from the listener map
    if ( LOG.isDebugEnabled() )
    {
        if ( compareResponse.getLdapResult().getResultCode() == ResultCodeEnum.SUCCESS )
        {
            // Everything is fine, return the response
            LOG.debug( I18n.msg( I18n.MSG_04114_COMPARE_SUCCESSFUL, compareResponse ) );
        }
        else
        {
            // We have had an error
            LOG.debug( I18n.msg( I18n.MSG_04113_COMPARE_FAILED, compareResponse ) );
        }
    }

    // Store the response into the future
    compareFuture.set( compareResponse );

    // Remove the future from the map
    removeFromFutureMaps( responseId );
}
 
Example #5
Source File: LdapNetworkConnection.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Process the ExtendedResponse received from the server
 * 
 * @param extendedResponse The ExtendedResponse to process
 * @param extendedFuture The ExtendedFuture to feed
 * @param responseId The associated request message ID
 * @throws InterruptedException If the Future is interrupted
 * @throws DecoderException If the response cannot be decoded
 */
private void extendedReceived( ExtendedResponse extendedResponse, ExtendedFuture extendedFuture, int responseId ) 
    throws InterruptedException, DecoderException
{
    if ( LOG.isDebugEnabled() )
    {
        if ( extendedResponse.getLdapResult().getResultCode() == ResultCodeEnum.SUCCESS )
        {
            // Everything is fine, return the response
            LOG.debug( I18n.msg( I18n.MSG_04118_EXTENDED_SUCCESSFUL, extendedResponse ) );
        }
        else
        {
            // We have had an error
            LOG.debug( I18n.msg( I18n.MSG_04117_EXTENDED_FAILED, extendedResponse ) );
        }
    }
    
    extendedResponse = handleOpaqueResponse( extendedResponse, extendedFuture );

    // Store the response into the future
    extendedFuture.set( extendedResponse );

    // Remove the future from the map
    removeFromFutureMaps( responseId );
}
 
Example #6
Source File: LdapDataProvider.java    From directory-fortress-core with Apache License 2.0 6 votes vote down vote up
/**
 * This method uses the compare ldap func to assert audit record into the directory server's configured audit
 * logger.
 *
 * This is for one reason - to force the ldap server to maintain an audit trail on checkAccess api.
 *
 * Use proxy authz control (RFC4370) to assert the caller's id onto the record.
 *
 * @param connection is LdapConnection object used for all communication with host.
 * @param dn         contains address of distinguished name to begin ldap search
 * @param userDn     dn for user node
 * @param attribute  attribute used for compare
 * @return true if compare operation succeeds
 * @throws LdapException                thrown in the event of error in ldap client or server code.
 * @throws UnsupportedEncodingException in the event the server cannot perform the operation.
 */
protected boolean compareNode( LdapConnection connection, String dn, String userDn,
    Attribute attribute ) throws LdapException, UnsupportedEncodingException
{
    COUNTERS.incrementCompare();

    CompareRequest compareRequest = new CompareRequestImpl();
    compareRequest.setName( new Dn( dn ) );
    compareRequest.setAttributeId( attribute.getId() );
    compareRequest.setAssertionValue( attribute.getString() );

    // Assert the end user's dn onto the reqest using proxy authZ control so openldap can log who the user was (for authZ audit trail)
    ProxiedAuthz proxiedAuthzControl = new ProxiedAuthzImpl();
    proxiedAuthzControl.setAuthzId( "dn: " + userDn );
    compareRequest.addControl( proxiedAuthzControl );
    CompareResponse response = connection.compare( compareRequest );
    return response.getLdapResult().getResultCode() == ResultCodeEnum.SUCCESS;
}
 
Example #7
Source File: ExceptionInterceptor.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void moveAndRename( MoveAndRenameOperationContext moveAndRenameContext ) throws LdapException
{
    Dn oldDn = moveAndRenameContext.getDn();

    // Don't allow M&R in the SSSE
    if ( oldDn.equals( subschemSubentryDn ) )
    {
        throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, I18n.err( I18n.ERR_258,
            subschemSubentryDn, subschemSubentryDn ) );
    }

    // Remove the original entry from the NotAlias cache, if needed
    synchronized ( notAliasCache )
    {
        if ( notAliasCache.containsKey( oldDn.getNormName() ) )
        {
            notAliasCache.remove( oldDn.getNormName() );
        }
    }

    next( moveAndRenameContext );
}
 
Example #8
Source File: DelResponseTest.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Test parsing of a response with Result Code
 */
@Test
public void testResponseWithResultCode()
{
    Dsmlv2ResponseParser parser = null;
    try
    {
        parser = new Dsmlv2ResponseParser( getCodec() );

        parser
            .setInput( DelResponseTest.class.getResource( "response_with_result_code.xml" ).openStream(), "UTF-8" );

        parser.parse();
    }
    catch ( Exception e )
    {
        fail( e.getMessage() );
    }

    DeleteResponse delResponse = ( DeleteResponse ) parser.getBatchResponse().getCurrentResponse();

    LdapResult ldapResult = delResponse.getLdapResult();

    assertEquals( ResultCodeEnum.PROTOCOL_ERROR, ldapResult.getResultCode() );
}
 
Example #9
Source File: SchemaInterceptor.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
/**
 * Checks to see if an attribute is required by as determined from an entry's
 * set of objectClass attribute values.
 *
 * @return true if the objectClass values require the attribute, false otherwise
 * @throws Exception if the attribute is not recognized
 */
private void assertAllAttributesAllowed( Dn dn, Entry entry, Set<String> allowed ) throws LdapException
{
    // Never check the attributes if the extensibleObject objectClass is
    // declared for this entry
    Attribute objectClass = entry.get( OBJECT_CLASS_AT );

    if ( objectClass.contains( SchemaConstants.EXTENSIBLE_OBJECT_OC ) )
    {
        return;
    }

    for ( Attribute attribute : entry )
    {
        String attrOid = attribute.getAttributeType().getOid();

        AttributeType attributeType = attribute.getAttributeType();

        if ( !attributeType.isCollective() && ( attributeType.getUsage() == UsageEnum.USER_APPLICATIONS )
            && !allowed.contains( attrOid ) )
        {
            throw new LdapSchemaViolationException( ResultCodeEnum.OBJECT_CLASS_VIOLATION, I18n.err( I18n.ERR_277,
                attribute.getUpId(), dn.getName() ) );
        }
    }
}
 
Example #10
Source File: BindRequestHandler.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
/**
 * Deal with a received BindRequest
 *
 * @param ldapSession The current session
 * @param bindRequest The received BindRequest
 * @throws Exception If the authentication cannot be handled
 */
public void handle(LdapSession ldapSession, BindRequest bindRequest) throws Exception {
    LOG.debug("Received: {}", bindRequest);

    // Guard clause:  LDAP version 3
    if (!bindRequest.getVersion3()) {
        LOG.error(I18n.err(I18n.ERR_162));
        LdapResult bindResult = bindRequest.getResultResponse().getLdapResult();
        bindResult.setResultCode(ResultCodeEnum.PROTOCOL_ERROR);
        bindResult.setDiagnosticMessage(I18n.err(I18n.ERR_163));
        ldapSession.getIoSession().write(bindRequest.getResultResponse());
        return;
    }

    // Deal with the two kinds of authentication : Simple and SASL
    if (bindRequest.isSimple()) {
        handleSimpleAuth(ldapSession, bindRequest);
    } else {
        handleSaslAuth(ldapSession, bindRequest);
    }
}
 
Example #11
Source File: PasswordModifyResponseImpl.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance for the PwdModify response
 * @param messageId The Message ID
 * @param rcode The result code
 */
public PasswordModifyResponseImpl( int messageId, ResultCodeEnum rcode )
{
    super( messageId, PasswordModifyResponse.EXTENSION_OID );

    super.getLdapResult().setMatchedDn( null );
    super.getLdapResult().setResultCode( rcode );
}
 
Example #12
Source File: DefaultAttribute.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getString() throws LdapInvalidAttributeValueException
{
    Value value = get();

    if ( isHumanReadable() )
    {
        if ( value != null )
        {
            return value.getString();
        }
        else
        {
            return "";
        }
    }
    
    if ( attributeType == null )
    {
        // Special case : the Attribute is not schema aware.
        // The value is binary, we will try to convert it to a String
        return Strings.utf8ToString( value.getBytes() );
    }

    String message = I18n.err( I18n.ERR_13215_VALUE_EXPECT_STRING );
    LOG.error( message );
    throw new LdapInvalidAttributeValueException( ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, message );
}
 
Example #13
Source File: Dsmlv2Engine.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Binds to the ldap server
 * 
 * @param messageId the message Id
 * @throws LdapException If we had an issue while binding
 * @throws IOException If we had an issue while transmitting the request or re ceiving the response
 */
protected void bind( int messageId ) throws LdapException, IOException
{
    if ( ( connection != null ) && connection.isAuthenticated() )
    {
        return;
    }

    if ( connection == null )
    {
        throw new IOException( I18n.err( I18n.ERR_02002_MISSING_CONNECTION_TO_BIND ) );
    }

    BindRequest bindRequest = new BindRequestImpl();
    bindRequest.setSimple( true );
    bindRequest.setCredentials( Strings.getBytesUtf8( password ) );
    bindRequest.setName( user );
    bindRequest.setVersion3( true );
    bindRequest.setMessageId( messageId );

    BindResponse bindResponse = connection.bind( bindRequest );

    if ( bindResponse.getLdapResult().getResultCode() != ResultCodeEnum.SUCCESS )
    {
        if ( LOG.isWarnEnabled() )
        {
            LOG.warn( I18n.msg( I18n.MSG_02003_ERROR, bindResponse.getLdapResult().getDiagnosticMessage() ) );
        }
    }
}
 
Example #14
Source File: AcceleratorDAO.java    From directory-fortress-core with Apache License 2.0 5 votes vote down vote up
/**
 * Deactivate user role from impl session
 * This function follows the pattern from: {@link org.apache.directory.fortress.core.AccessMgr#dropActiveRole(org.apache.directory.fortress.core.model.Session, org.apache.directory.fortress.core.model.UserRole)}.
 * Success will result in impl session state to be modified inside server-side cache.
 * It uses the {@link RbacDropRoleRequest} and {@link RbacDropRoleResponse} accelerator APIs.
 *
 * @param session contains a valid sessionId captured from accelerator createSession method.
 * @param userRole both the {@link org.apache.directory.fortress.core.model.UserRole#userId} and {@link UserRole#name} fields must be set before invoking.
 * @throws SecurityException rethrows {@code LdapException} with {@code GlobalErrIds.ACEL_DROP_ROLE_ERR}.
 */
void dropActiveRole( Session session, UserRole userRole ) throws SecurityException
{
    LdapConnection ld = null;

    try
    {
        ld = getAdminConnection();
        RbacDropRoleRequest dropRoleRequest = new RbacDropRoleRequestImpl();
        dropRoleRequest.setSessionId( session.getSessionId() );
        dropRoleRequest.setRole( userRole.getName() );
        dropRoleRequest.setUserIdentity( userRole.getUserId() );
        // Send the request
        RbacDropRoleResponse rbacDropRoleResponse = ( RbacDropRoleResponse ) ld.extended(
            dropRoleRequest );
        LOG.debug( "dropActiveRole result: {}", rbacDropRoleResponse.getLdapResult().getResultCode() );

        if ( rbacDropRoleResponse.getLdapResult().getResultCode() != ResultCodeEnum.SUCCESS )
        {
            String info = "dropActiveRole Role [" + userRole.getName() + "] User ["
                + session.getUserId() + "], not previously activated.";
            throw new SecurityException( GlobalErrIds.URLE_NOT_ACTIVE, info );
        }
    }
    catch ( LdapException e )
    {
        String error = "dropActiveRole role name [" + userRole.getName() + "] caught LDAPException=" + " msg=" + e
            .getMessage();
        throw new SecurityException( GlobalErrIds.ACEL_DROP_ROLE_ERR, error, e );
    }
    finally
    {
        closeAdminConnection( ld );
    }
}
 
Example #15
Source File: BindResponseImplTest.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Tests for equality of two fully loaded identical BindResponse PDUs.
 */
@Test
public void testEqualsWithTheWorks() throws LdapException
{
    LdapResultImpl r0 = new LdapResultImpl();
    LdapResultImpl r1 = new LdapResultImpl();

    r0.setDiagnosticMessage( "blah blah blah" );
    r1.setDiagnosticMessage( "blah blah blah" );

    r0.setMatchedDn( new Dn( "dc=example,dc=com" ) );
    r1.setMatchedDn( new Dn( "dc=example,dc=com" ) );

    r0.setResultCode( ResultCodeEnum.TIME_LIMIT_EXCEEDED );
    r1.setResultCode( ResultCodeEnum.TIME_LIMIT_EXCEEDED );

    Referral refs0 = new ReferralImpl();
    refs0.addLdapUrl( "ldap://someserver.com" );
    refs0.addLdapUrl( "ldap://anotherserver.org" );

    Referral refs1 = new ReferralImpl();
    refs1.addLdapUrl( "ldap://someserver.com" );
    refs1.addLdapUrl( "ldap://anotherserver.org" );

    BindResponseImpl resp0 = new BindResponseImpl( 1 );
    BindResponseImpl resp1 = new BindResponseImpl( 1 );

    resp0.setServerSaslCreds( PASSWORD );
    resp1.setServerSaslCreds( PASSWORD );

    assertTrue( resp0.equals( resp1 ), "loaded carbon copies should be equal" );
    assertTrue( resp1.equals( resp0 ), "loaded carbon copies should be equal" );
}
 
Example #16
Source File: ImmutableAttributeTypeRegistry.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void addMappingFor( AttributeType attributeType ) throws LdapException
{
    throw new LdapUnwillingToPerformException( ResultCodeEnum.NO_SUCH_OPERATION, 
        I18n.err( I18n.ERR_13701_CANNOT_MODIFY_AT_REGISTRY_COPY ) );
}
 
Example #17
Source File: StartTransactionResponseImpl.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new StartTransactionResponseImpl instance
 */
public StartTransactionResponseImpl()
{
    super( StartTransactionRequest.EXTENSION_OID );
    super.getLdapResult().setMatchedDn( null );
    super.getLdapResult().setResultCode( ResultCodeEnum.UNWILLING_TO_PERFORM );
}
 
Example #18
Source File: StartTlsResponseImpl.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance for the StartTls response
 * @param messageId The Message ID
 * @param rcode The result code
 * @param diagnosticMessage The diagnostic message
 */
public StartTlsResponseImpl( int messageId, ResultCodeEnum rcode, String diagnosticMessage )
{
    super( messageId, EXTENSION_OID );

    super.getLdapResult().setMatchedDn( null );
    super.getLdapResult().setResultCode( rcode );
    super.getLdapResult().setDiagnosticMessage( diagnosticMessage );
}
 
Example #19
Source File: StartTlsResponseImpl.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new StartTls response.
 *
 * @param messageId the message id
 */
public StartTlsResponseImpl( int messageId )
{
    super( messageId, EXTENSION_OID );
    super.getLdapResult().setMatchedDn( null );
    super.getLdapResult().setResultCode( ResultCodeEnum.SUCCESS );
}
 
Example #20
Source File: ImmutableAttributeTypeRegistry.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public AttributeType unregister( String numericOid ) throws LdapException
{
    throw new LdapUnwillingToPerformException( ResultCodeEnum.NO_SUCH_OPERATION,
        I18n.err( I18n.ERR_13701_CANNOT_MODIFY_AT_REGISTRY_COPY ) );
}
 
Example #21
Source File: ResponseCarryingException.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a DecoderException
 * 
 * @param message A message with meaning to a human
 * @param response The response to store
 * @param code the ResultCode
 * @param matchedDn The Matched DN
 * @param cause The Exception which caused the error
 */
public ResponseCarryingException( String message, ResultResponse response, ResultCodeEnum code,
    Dn matchedDn, Throwable cause )
{
    super( message, cause );

    response.getLdapResult().setDiagnosticMessage( message );
    response.getLdapResult().setResultCode( code );
    response.getLdapResult().setMatchedDn( matchedDn );

    this.response = response;
}
 
Example #22
Source File: StartTlsResponseImpl.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new StartTls response.
 */
public StartTlsResponseImpl()
{
    super( EXTENSION_OID );
    super.getLdapResult().setMatchedDn( null );
    super.getLdapResult().setResultCode( ResultCodeEnum.SUCCESS );
}
 
Example #23
Source File: DefaultOperationManager.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
private void ensureStarted() throws LdapServiceUnavailableException
{
    if ( !directoryService.isStarted() )
    {
        throw new LdapServiceUnavailableException( ResultCodeEnum.UNAVAILABLE, I18n.err( I18n.ERR_316 ) );
    }
}
 
Example #24
Source File: BindRequestTest.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Test the decoding of a BindRequest with an empty sasl
 */
@Test
public void testDecodeBindRequestEmptySasl() throws DecoderException
{
    ByteBuffer stream = ByteBuffer.allocate( 0x0E );
    stream.put( new byte[]
        {
            0x30, 0x0C,             // LDAPMessage ::=SEQUENCE {
              0x02, 0x01, 0x01,     // messageID MessageID
              0x60, 0x07,           // CHOICE { ..., bindRequest BindRequest, ...
                0x02, 0x01, 0x03,   // version INTEGER (1..127),
                0x04, 0x00,
                ( byte ) 0xA3, 0x00
        } );

    stream.flip();

    // Allocate a LdapMessage Container
    LdapMessageContainer<BindRequest> container = new LdapMessageContainer<>( codec );

    // Decode a BindRequest message
    assertThrows( DecoderException.class, ( ) ->
    {
        try
        {
            Asn1Decoder.decode( stream, container );
        }
        catch ( DecoderException de )
        {
            assertTrue( de instanceof ResponseCarryingException );
            Message response = ( ( ResponseCarryingException ) de ).getResponse();
            assertTrue( response instanceof BindResponseImpl );
            assertEquals( ResultCodeEnum.INVALID_CREDENTIALS, ( ( BindResponseImpl ) response ).getLdapResult()
                .getResultCode() );

            throw de;
        }
    } );
}
 
Example #25
Source File: SearchRequestHandler.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * Handles search requests containing the persistent search decorator but
 * delegates to doSimpleSearch() if the changesOnly parameter of the
 * decorator is set to false.
 *
 * @param session the LdapSession for which this search is conducted
 * @param req the search request containing the persistent search decorator
 * @param psearchDecorator the persistent search decorator extracted
 * @throws Exception if failures are encountered while searching
 */
private void handlePersistentSearch( LdapSession session, SearchRequest req,
    PersistentSearch psearch ) throws Exception
{
    /*
     * We want the search to complete first before we start listening to
     * events when the decorator does NOT specify changes ONLY mode.
     */
    if ( !psearch.isChangesOnly() )
    {
        SearchResultDone done = doSimpleSearch( session, req );

        // ok if normal search beforehand failed somehow quickly abandon psearch
        if ( done.getLdapResult().getResultCode() != ResultCodeEnum.SUCCESS )
        {
            session.getIoSession().write( done );
            return;
        }
    }

    if ( req.isAbandoned() )
    {
        return;
    }

    // now we process entries forever as they change
    PersistentSearchListener persistentSearchListener = new PersistentSearchListener( session, req );

    // compose notification criteria and add the listener to the event
    // service using that notification criteria to determine which events
    // are to be delivered to the persistent search issuing client
    NotificationCriteria criteria = new NotificationCriteria();
    criteria.setAliasDerefMode( req.getDerefAliases() );
    criteria.setBase( req.getBase() );
    criteria.setFilter( req.getFilter() );
    criteria.setScope( req.getScope() );
    criteria.setEventMask( EventType.getEventTypes( psearch.getChangeTypes() ) );
    getLdapServer().getDirectoryService().getEventService().addListener( persistentSearchListener, criteria );
    req.addAbandonListener( new SearchAbandonListener( ldapServer, persistentSearchListener ) );
}
 
Example #26
Source File: LdapUnwillingToPerformException.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param resultCode the ResultCodeEnum for this exception
 * @param message The exception message
 * @param cause The root cause for this exception
 */
public LdapUnwillingToPerformException( ResultCodeEnum resultCode, String message, Throwable cause )
{
    super( message, cause );
    checkResultCode( resultCode );
    this.resultCode = resultCode;
}
 
Example #27
Source File: BindResponseImplTest.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Tests for equal hashCode of two fully loaded identical BindResponse PDUs.
 */
@Test
public void testHashCodeWithTheWorks() throws LdapException
{
    LdapResultImpl r0 = new LdapResultImpl();
    LdapResultImpl r1 = new LdapResultImpl();

    r0.setDiagnosticMessage( "blah blah blah" );
    r1.setDiagnosticMessage( "blah blah blah" );

    r0.setMatchedDn( new Dn( "dc=example,dc=com" ) );
    r1.setMatchedDn( new Dn( "dc=example,dc=com" ) );

    r0.setResultCode( ResultCodeEnum.TIME_LIMIT_EXCEEDED );
    r1.setResultCode( ResultCodeEnum.TIME_LIMIT_EXCEEDED );

    Referral refs0 = new ReferralImpl();
    refs0.addLdapUrl( "ldap://someserver.com" );
    refs0.addLdapUrl( "ldap://anotherserver.org" );

    Referral refs1 = new ReferralImpl();
    refs1.addLdapUrl( "ldap://someserver.com" );
    refs1.addLdapUrl( "ldap://anotherserver.org" );

    BindResponseImpl resp0 = new BindResponseImpl( 1 );
    BindResponseImpl resp1 = new BindResponseImpl( 1 );

    resp0.setServerSaslCreds( PASSWORD );
    resp1.setServerSaslCreds( PASSWORD );

    assertTrue( resp0.hashCode() == resp1.hashCode() );
}
 
Example #28
Source File: ImmutableObjectClassRegistry.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void unregisterDescendants( ObjectClass attributeType, List<ObjectClass> ancestors ) throws LdapException
{
    throw new LdapUnwillingToPerformException( ResultCodeEnum.NO_SUCH_OPERATION, I18n.err( I18n.ERR_13710_CANNOT_MODIFY_OC_REGISTRY_COPY ) );
}
 
Example #29
Source File: Dn.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Get the descendant of a given DN, using the ancestr DN. Assuming that
 * a DN has two parts :<br>
 * DN = [descendant DN][ancestor DN]<br>
 * To get back the descendant from the full DN, you just pass the ancestor DN
 * as a parameter. Here is a working example :
 * <pre>
 * Dn dn = new Dn( "cn=test, dc=server, dc=directory, dc=apache, dc=org" );
 *
 * Dn descendant = dn.getDescendantOf( "dc=apache, dc=org" );
 *
 * // At this point, the descendant contains cn=test, dc=server, dc=directory"
 * </pre>
 *
 * @param ancestor The parent DN
 * @return The part of the DN that is the descendant
 * @throws LdapInvalidDnException If the Dn is invalid
 */
public Dn getDescendantOf( Dn ancestor ) throws LdapInvalidDnException
{
    if ( ( ancestor == null ) || ( ancestor.size() == 0 ) )
    {
        return this;
    }

    if ( rdns.isEmpty() )
    {
        return EMPTY_DN;
    }

    int length = ancestor.size();

    if ( length > rdns.size() )
    {
        String message = I18n.err( I18n.ERR_13612_POSITION_NOT_IN_RANGE, length, rdns.size() );
        LOG.error( message );
        throw new ArrayIndexOutOfBoundsException( message );
    }

    Dn newDn = new Dn( schemaManager );
    List<Rdn> rdnsAncestor = ancestor.getRdns();

    for ( int i = 0; i < ancestor.size(); i++ )
    {
        Rdn rdn = rdns.get( size() - 1 - i );
        Rdn rdnDescendant = rdnsAncestor.get( ancestor.size() - 1 - i );

        if ( !rdn.equals( rdnDescendant ) )
        {
            throw new LdapInvalidDnException( ResultCodeEnum.INVALID_DN_SYNTAX );
        }
    }

    for ( int i = 0; i < rdns.size() - length; i++ )
    {
        newDn.rdns.add( rdns.get( i ) );
    }

    newDn.toUpName();

    return newDn;
}
 
Example #30
Source File: LdapNetworkConnection.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Bind to the server using a SaslExternalRequest object.
 *
 * @param request The SaslExternalRequest POJO containing all the needed parameters
 * @return A LdapResponse containing the result
 * @throws LdapException if some error occurred
 */
public BindResponse bind( SaslExternalRequest request ) throws LdapException
{
    if ( request == null )
    {
        String msg = I18n.msg( I18n.MSG_04103_NULL_REQUEST );

        if ( LOG.isDebugEnabled() )
        {
            LOG.debug( msg );
        }
        
        throw new IllegalArgumentException( msg );
    }

    BindFuture bindFuture = bindAsync( request );

    // Get the result from the future
    try
    {
        // Read the response, waiting for it if not available immediately
        // Get the response, blocking
        BindResponse bindResponse = bindFuture.get( timeout, TimeUnit.MILLISECONDS );

        if ( bindResponse == null )
        {
            // We didn't received anything : this is an error
            if ( LOG.isErrorEnabled() )
            { 
                LOG.error( I18n.err( I18n.ERR_04112_OP_FAILED_TIMEOUT, "Bind" ) );
            }
            
            throw new LdapException( TIME_OUT_ERROR );
        }

        if ( bindResponse.getLdapResult().getResultCode() == ResultCodeEnum.SUCCESS )
        {
            authenticated.set( true );

            // Everything is fine, return the response
            if ( LOG.isDebugEnabled() )
            { 
                LOG.debug( I18n.msg( I18n.MSG_04101_BIND_SUCCESSFUL, bindResponse ) );
            }
        }
        else
        {
            // We have had an error
            if ( LOG.isDebugEnabled() )
            { 
                LOG.debug( I18n.msg( I18n.MSG_04100_BIND_FAIL, bindResponse ) );
            }
        }

        return bindResponse;
    }
    catch ( Exception ie )
    {
        // Catch all other exceptions
        LOG.error( NO_RESPONSE_ERROR, ie );

        throw new LdapException( NO_RESPONSE_ERROR, ie );
    }
}