Package org.apache.directory.server.core.api

Examples of org.apache.directory.server.core.api.DirectoryService


     */
    // This will suppress PMD.EmptyCatchBlock warnings in this method
    @SuppressWarnings("PMD.EmptyCatchBlock")
    public void handleSimpleAuth( LdapSession ldapSession, BindRequest bindRequest ) throws Exception
    {
        DirectoryService directoryService = ldapServer.getDirectoryService();

        // if the user is already bound, we have to unbind him
        if ( ldapSession.isAuthenticated() )
        {
            // We already have a bound session for this user. We have to
            // abandon it first.
            ldapSession.getCoreSession().unbind();
        }

        // Set the status to SimpleAuthPending
        ldapSession.setSimpleAuthPending();

        // Now, bind the user

        // create a new Bind context, with a null session, as we don't have
        // any context yet.
        BindOperationContext bindContext = new BindOperationContext( null );

        // Stores the Dn of the user to check, and its password
        bindContext.setDn( bindRequest.getDn() );
        bindContext.setCredentials( bindRequest.getCredentials() );
        bindContext.setIoSession( ldapSession.getIoSession() );
        bindContext.setInterceptors( directoryService.getInterceptors( OperationEnum.BIND ) );

        // Stores the request controls into the operation context
        LdapProtocolUtils.setRequestControls( bindContext, bindRequest );

        try
        {
            /*
             * Referral handling as specified by RFC 3296 here:
             *   
             *      http://www.faqs.org/rfcs/rfc3296.html
             *     
             * See section 5.6.1 where if the bind principal Dn is a referral
             * we return an invalidCredentials result response.  Optionally we
             * could support delegated authentication in the future with this
             * potential.  See the following JIRA for more on this possibility:
             *
             *      https://issues.apache.org/jira/browse/DIRSERVER-1217
             *     
             * NOTE: if this is done then this handler should extend the
             * a modified form of the ReferralAwareRequestHandler so it can
             * detect conditions where ancestors of the Dn are referrals
             * and delegate appropriately.
             */
            Entry principalEntry = null;

            try
            {
                principalEntry = directoryService.getAdminSession().lookup( bindRequest.getDn() );
            }
            catch ( LdapException le )
            {
                // this is OK
            }

            if ( principalEntry == null )
            {
                LOG.info( "The {} principalDN cannot be found in the server : bind failure.", bindRequest.getName() );
            }
            else if ( ( ( ClonedServerEntry ) principalEntry ).getOriginalEntry().contains(
                SchemaConstants.OBJECT_CLASS_AT,
                SchemaConstants.REFERRAL_OC ) )
            {
                LOG.info( "Bind principalDn points to referral." );
                LdapResult result = bindRequest.getResultResponse().getLdapResult();
                result.setDiagnosticMessage( "Bind principalDn points to referral." );
                result.setResultCode( ResultCodeEnum.INVALID_CREDENTIALS );
                ldapSession.getIoSession().write( bindRequest.getResultResponse() );
                return;
            }

            // TODO - might cause issues since lookups are not returning all
            // attributes right now - this is an optimization that can be
            // enabled later after determining whether or not this will cause
            // issues.
            // reuse the looked up entry so we don't incur another lookup
            // opContext.setEntry( principalEntry );

            // And call the OperationManager bind operation.
            bindContext.setInterceptors( directoryService.getInterceptors( OperationEnum.BIND ) );
            directoryService.getOperationManager().bind( bindContext );

            // As a result, store the created session in the Core Session
            ldapSession.setCoreSession( bindContext.getSession() );

            // And set the current state accordingly
View Full Code Here


                LdapPrincipal ldapPrincipal = ( LdapPrincipal ) ldapSession
                    .getSaslProperty( SaslConstants.SASL_AUTHENT_USER );

                if ( ldapPrincipal != null )
                {
                    DirectoryService ds = ldapSession.getLdapServer().getDirectoryService();
                    String saslMechanism = bindRequest.getSaslMechanism();
                    CoreSession userSession = ds.getSession( ldapPrincipal.getDn(), ldapPrincipal.getUserPassword(),
                        saslMechanism, null );

                    // Set the user session into the ldap session
                    ldapSession.setCoreSession( userSession );
                }
View Full Code Here

        })
    @CreateLdapServer(transports =
        { @CreateTransport(port = 16000, protocol = "LDAP") })
    public static void startProvider() throws Exception
    {
        DirectoryService provDirService = DSAnnotationProcessor.getDirectoryService();

        providerServer = ServerAnnotationProcessor.getLdapServer( provDirService );
        providerServer.setReplicationReqHandler( new SyncReplRequestHandler() );
        providerServer.startReplicationProducer();
View Full Code Here

            refreshInterval = 1000,
            replicaId = 1
        )
        public static void startConsumer() throws Exception
    {
        DirectoryService provDirService = DSAnnotationProcessor.getDirectoryService();
        consumerServer = ServerAnnotationProcessor.getLdapServer( provDirService );

        final ReplicationConsumerImpl consumer = ( ReplicationConsumerImpl ) ServerAnnotationProcessor.createConsumer();

        List<ReplicationConsumer> replConsumers = new ArrayList<ReplicationConsumer>();
        replConsumers.add( consumer );

        consumerServer.setReplConsumers( replConsumers );
        consumerServer.startReplicationConsumers();

        Runnable r = new Runnable()
        {
            public void run()
            {
                try
                {
                    DirectoryService ds = consumerServer.getDirectoryService();

                    Dn configDn = new Dn( ds.getSchemaManager(), "ads-replConsumerId=localhost,ou=system" );
                    consumer.getConfig().setConfigEntryDn( configDn );

                    Entry provConfigEntry = new DefaultEntry( ds.getSchemaManager(), configDn,
                        "objectClass: ads-replConsumer",
                        "ads-replConsumerId: localhost",
                        "ads-searchBaseDN", consumer.getConfig().getBaseDn(),
                        "ads-replProvHostName", consumer.getConfig().getRemoteHost(),
                        "ads-replProvPort", String.valueOf( consumer.getConfig().getRemotePort() ),
View Full Code Here

     */
    // This will suppress PMD.EmptyCatchBlock warnings in this method
    @SuppressWarnings("PMD.EmptyCatchBlock")
    public void handleSimpleAuth( LdapSession ldapSession, BindRequest bindRequest ) throws Exception
    {
        DirectoryService directoryService = ldapServer.getDirectoryService();

        // if the user is already bound, we have to unbind him
        if ( ldapSession.isAuthenticated() )
        {
            // We already have a bound session for this user. We have to
            // abandon it first.
            ldapSession.getCoreSession().unbind();
        }

        // Set the status to SimpleAuthPending
        ldapSession.setSimpleAuthPending();

        // Now, bind the user

        // create a new Bind context, with a null session, as we don't have
        // any context yet.
        BindOperationContext bindContext = new BindOperationContext( null );

        // Stores the Dn of the user to check, and its password
        bindContext.setDn( bindRequest.getDn() );
        bindContext.setCredentials( bindRequest.getCredentials() );
        bindContext.setIoSession( ldapSession.getIoSession() );
        bindContext.setInterceptors( directoryService.getInterceptors( OperationEnum.BIND ) );

        // Stores the request controls into the operation context
        LdapProtocolUtils.setRequestControls( bindContext, bindRequest );

        try
        {
            /*
             * Referral handling as specified by RFC 3296 here:
             *   
             *      http://www.faqs.org/rfcs/rfc3296.html
             *     
             * See section 5.6.1 where if the bind principal Dn is a referral
             * we return an invalidCredentials result response.  Optionally we
             * could support delegated authentication in the future with this
             * potential.  See the following JIRA for more on this possibility:
             *
             *      https://issues.apache.org/jira/browse/DIRSERVER-1217
             *     
             * NOTE: if this is done then this handler should extend the
             * a modified form of the ReferralAwareRequestHandler so it can
             * detect conditions where ancestors of the Dn are referrals
             * and delegate appropriately.
             */
            Entry principalEntry = null;

            try
            {
                principalEntry = directoryService.getAdminSession().lookup( bindRequest.getDn() );
            }
            catch ( LdapException le )
            {
                // this is OK
            }

            if ( principalEntry == null )
            {
                LOG.info( "The {} principalDN cannot be found in the server : bind failure.", bindRequest.getName() );
            }
            else if ( ( ( ClonedServerEntry ) principalEntry ).getOriginalEntry().contains(
                SchemaConstants.OBJECT_CLASS_AT,
                SchemaConstants.REFERRAL_OC ) )
            {
                LOG.info( "Bind principalDn points to referral." );
                LdapResult result = bindRequest.getResultResponse().getLdapResult();
                result.setDiagnosticMessage( "Bind principalDn points to referral." );
                result.setResultCode( ResultCodeEnum.INVALID_CREDENTIALS );
                ldapSession.getIoSession().write( bindRequest.getResultResponse() );
                return;
            }

            // TODO - might cause issues since lookups are not returning all
            // attributes right now - this is an optimization that can be
            // enabled later after determining whether or not this will cause
            // issues.
            // reuse the looked up entry so we don't incur another lookup
            // opContext.setEntry( principalEntry );

            // And call the OperationManager bind operation.
            bindContext.setInterceptors( directoryService.getInterceptors( OperationEnum.BIND ) );
            directoryService.getOperationManager().bind( bindContext );

            // As a result, store the created session in the Core Session
            ldapSession.setCoreSession( bindContext.getSession() );

            // And set the current state accordingly
View Full Code Here

    })
    @CreateLdapServer(transports =
        { @CreateTransport(port = 16000, protocol = "LDAP") })
    public static void startProvider() throws Exception
    {
        DirectoryService provDirService = DSAnnotationProcessor.getDirectoryService();

        providerServer = ServerAnnotationProcessor.getLdapServer( provDirService );

        providerServer.setReplicationReqHandler( new SyncReplRequestHandler() );
        providerServer.startReplicationProducer();
View Full Code Here

                    searchRequest.setScope( config.getSearchScope() );
                    searchRequest.setTypesOnly( false );

                    searchRequest.addAttributes( config.getAttributes() );

                    DirectoryService directoryService = new MockDirectoryService();
                    directoryService.setSchemaManager( schemaManager );
                    ( ( MockSyncReplConsumer ) syncreplClient ).init( directoryService );
                    syncreplClient.connect( true );
                    syncreplClient.startSync();
                }
                catch ( Exception e )
View Full Code Here

                LdapPrincipal ldapPrincipal = ( LdapPrincipal ) ldapSession
                    .getSaslProperty( SaslConstants.SASL_AUTHENT_USER );

                if ( ldapPrincipal != null )
                {
                    DirectoryService ds = ldapSession.getLdapServer().getDirectoryService();
                    String saslMechanism = bindRequest.getSaslMechanism();
                    CoreSession userSession = ds.getSession( ldapPrincipal.getDn(), ldapPrincipal.getUserPassword(),
                        saslMechanism, null );

                    // Set the user session into the ldap session
                    ldapSession.setCoreSession( userSession );
                }
View Full Code Here

     * @throws Exception
     */
    public static DirectoryService createDirectoryService( DirectoryServiceBean directoryServiceBean,
        InstanceLayout instanceLayout, SchemaManager schemaManager ) throws Exception
    {
        DirectoryService directoryService = new DefaultDirectoryService();

        // The schemaManager
        directoryService.setSchemaManager( schemaManager );

        // MUST attributes
        // DirectoryService ID
        directoryService.setInstanceId( directoryServiceBean.getDirectoryServiceId() );

        // Replica ID
        directoryService.setReplicaId( directoryServiceBean.getDsReplicaId() );

        // WorkingDirectory
        directoryService.setInstanceLayout( instanceLayout );

        // Interceptors
        List<Interceptor> interceptors = createInterceptors( directoryServiceBean.getInterceptors() );
        directoryService.setInterceptors( interceptors );

        // Partitions
        Map<String, Partition> partitions = createPartitions( directoryService, directoryServiceBean.getPartitions() );

        Partition systemPartition = partitions.remove( "system" );

        if ( systemPartition == null )
        {
            //throw new Exception( I18n.err( I18n.ERR_505 ) );
        }

        directoryService.setSystemPartition( systemPartition );
        directoryService.setPartitions( new HashSet<Partition>( partitions.values() ) );

        // MAY attributes
        // AccessControlEnabled
        directoryService.setAccessControlEnabled( directoryServiceBean.isDsAccessControlEnabled() );

        // AllowAnonymousAccess
        directoryService.setAllowAnonymousAccess( directoryServiceBean.isDsAllowAnonymousAccess() );

        // ChangeLog
        ChangeLog cl = createChangeLog( directoryServiceBean.getChangeLog() );

        if ( cl != null )
        {
            directoryService.setChangeLog( cl );
        }

        // DenormalizedOpAttrsEnabled
        directoryService.setDenormalizeOpAttrsEnabled( directoryServiceBean.isDsDenormalizeOpAttrsEnabled() );

        // Journal
        Journal journal = createJournal( directoryServiceBean.getJournal() );

        if ( journal != null )
        {
            directoryService.setJournal( journal );
        }

        // PasswordHidden
        directoryService.setPasswordHidden( directoryServiceBean.isDsPasswordHidden() );

        // SyncPeriodMillis
        directoryService.setSyncPeriodMillis( directoryServiceBean.getDsSyncPeriodMillis() );

        // testEntries
        String entryFilePath = directoryServiceBean.getDsTestEntries();

        if ( entryFilePath != null )
        {
            directoryService.setTestEntries( readTestEntries( entryFilePath ) );
        }

        // Enabled
        if ( !directoryServiceBean.isEnabled() )
        {
View Full Code Here

        LOG.debug( "Starting DS {}...", dsBuilder.name() );
        Class<?> factory = dsBuilder.factory();
        DirectoryServiceFactory dsf = ( DirectoryServiceFactory ) factory
            .newInstance();

        DirectoryService service = dsf.getDirectoryService();
        service.setAccessControlEnabled( dsBuilder.enableAccessControl() );
        service.setAllowAnonymousAccess( dsBuilder.allowAnonAccess() );
        service.getChangeLog().setEnabled( dsBuilder.enableChangeLog() );

        dsf.init( dsBuilder.name() );

        for ( Class<?> interceptorClass : dsBuilder.additionalInterceptors() )
        {
            service.addLast( ( Interceptor ) interceptorClass.newInstance() );
        }

        List<Interceptor> interceptorList = service.getInterceptors();

        if ( dsBuilder.authenticators().length != 0 )
        {
            AuthenticationInterceptor authenticationInterceptor = null;

            for ( Interceptor interceptor : interceptorList )
            {
                if ( interceptor instanceof AuthenticationInterceptor )
                {
                    authenticationInterceptor = ( AuthenticationInterceptor ) interceptor;
                    break;
                }
            }

            if ( authenticationInterceptor == null )
            {
                throw new IllegalStateException(
                    "authentication interceptor not found" );
            }

            Set<Authenticator> authenticators = new HashSet<Authenticator>();

            for ( CreateAuthenticator createAuthenticator : dsBuilder
                .authenticators() )
            {
                Authenticator auth = createAuthenticator.type().newInstance();

                if ( auth instanceof DelegatingAuthenticator )
                {
                    DelegatingAuthenticator dauth = ( DelegatingAuthenticator ) auth;
                    dauth.setDelegateHost( createAuthenticator.delegateHost() );
                    dauth.setDelegatePort( createAuthenticator.delegatePort() );
                }

                authenticators.add( auth );
            }
        }

        service.setInterceptors( interceptorList );

        SchemaManager schemaManager = service.getSchemaManager();

        // process the schemas
        for ( LoadSchema loadedSchema : dsBuilder.loadedSchemas() )
        {
            String schemaName = loadedSchema.name();
            Boolean enabled = loadedSchema.enabled();

            // Check if the schema is loaded or not
            boolean isLoaded = schemaManager.isSchemaLoaded( schemaName );

            if ( !isLoaded )
            {
                // We have to load the schema, if it exists
                try
                {
                    isLoaded = schemaManager.load( schemaName );
                }
                catch ( LdapUnwillingToPerformException lutpe )
                {
                    // Cannot load the schema, it does not exists
                    LOG.error( lutpe.getMessage() );
                    continue;
                }
            }

            if ( isLoaded )
            {
                if ( enabled )
                {
                    schemaManager.enable( schemaName );

                    if ( schemaManager.isDisabled( schemaName ) )
                    {
                        LOG.error( "Cannot enable " + schemaName );
                    }
                }
                else
                {
                    schemaManager.disable( schemaName );

                    if ( schemaManager.isEnabled( schemaName ) )
                    {
                        LOG.error( "Cannot disable " + schemaName );
                    }
                }
            }

            LOG.debug( "Loading schema {}, enabled= {}", schemaName, enabled );
        }

        // Process the Partition, if any.
        for ( CreatePartition createPartition : dsBuilder.partitions() )
        {
            Partition partition;

            // Determine the partition type
            if ( createPartition.type() == Partition.class )
            {
                // The annotation does not specify a specific partition type.
                // We use the partition factory to create partition and index
                // instances.
                PartitionFactory partitionFactory = dsf.getPartitionFactory();
                partition = partitionFactory.createPartition(
                    schemaManager,
                    createPartition.name(),
                    createPartition.suffix(),
                    createPartition.cacheSize(),
                    new File( service.getInstanceLayout().getPartitionsDirectory(), createPartition.name() ) );

                CreateIndex[] indexes = createPartition.indexes();

                for ( CreateIndex createIndex : indexes )
                {
                    partitionFactory.addIndex( partition,
                        createIndex.attribute(), createIndex.cacheSize() );
                }

                partition.initialize();
            }
            else
            {
                // The annotation contains a specific partition type, we use
                // that type.
                Class<?> partypes[] = new Class[]
                    { SchemaManager.class };
                Constructor<?> constructor = createPartition.type().getConstructor( partypes );
                partition = ( Partition ) constructor.newInstance( new Object[]
                    { schemaManager } );
                partition.setId( createPartition.name() );
                partition.setSuffixDn( new Dn( schemaManager, createPartition.suffix() ) );

                if ( partition instanceof AbstractBTreePartition )
                {
                    AbstractBTreePartition btreePartition = ( AbstractBTreePartition ) partition;
                    btreePartition.setCacheSize( createPartition.cacheSize() );
                    btreePartition.setPartitionPath( new File( service
                        .getInstanceLayout().getPartitionsDirectory(),
                        createPartition.name() ).toURI() );

                    // Process the indexes if any
                    CreateIndex[] indexes = createPartition.indexes();

                    for ( CreateIndex createIndex : indexes )
                    {
                        // The annotation does not specify a specific index
                        // type.
                        // We use the generic index implementation.
                        JdbmIndex index = new JdbmIndex( createIndex.attribute(), false );

                        btreePartition.addIndexedAttributes( index );
                    }
                }
            }

            partition.setSchemaManager( schemaManager );

            // Inject the partition into the DirectoryService
            service.addPartition( partition );

            // Last, process the context entry
            ContextEntry contextEntry = createPartition.contextEntry();

            if ( contextEntry != null )
View Full Code Here

TOP

Related Classes of org.apache.directory.server.core.api.DirectoryService

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.