Запуск Apache DS, встроенный в мое приложение

Я пытаюсь запустить встроенный ApacheDS в свое приложение. После прочтения http://directory.apache.org/apacheds/1.5/41-embedding-apacheds-into-an-application.html Я создаю это:

public void startDirectoryService() throws Exception {
    service = new DefaultDirectoryService();
    service.getChangeLog().setEnabled( false );

    Partition apachePartition = addPartition("apache", "dc=apache,dc=org");
    addIndex(apachePartition, "objectClass", "ou", "uid");

    service.startup();

    // Inject the apache root entry if it does not already exist
    try
    {
        service.getAdminSession().lookup( apachePartition.getSuffixDn() );
    }
    catch ( LdapNameNotFoundException lnnfe )
    {
        LdapDN dnApache = new LdapDN( "dc=Apache,dc=Org" );
        ServerEntry entryApache = service.newEntry( dnApache );
        entryApache.add( "objectClass", "top", "domain", "extensibleObject" );
        entryApache.add( "dc", "Apache" );
        service.getAdminSession().add( entryApache );
    }
}

Но я не могу подключиться к серверу после его запуска. Какой порт по умолчанию? Или я что-то упускаю?

Вот решение:

    service = new DefaultDirectoryService();
    service.getChangeLog().setEnabled( false );

    Partition apachePartition = addPartition("apache", "dc=apache,dc=org");

    LdapServer ldapService = new LdapServer();
    ldapService.setTransports(new TcpTransport(389));
    ldapService.setDirectoryService(service);

    service.startup();
    ldapService.start();

person cringe    schedule 13.10.2009    source источник


Ответы (7)


Я не смог запустить его ни в версии cringe, ни в версии Kevin, ни в версии Jörg Pfünder. Постоянно получал NPE из моего теста JUnit. Я отладил это и скомпилировал все в рабочее решение:

public class DirContextSourceAnonAuthTest {

  private static DirectoryService directoryService;
  private static LdapServer ldapServer;

  @BeforeClass
  public static void startApacheDs() throws Exception {
    String buildDirectory = System.getProperty("buildDirectory");
    File workingDirectory = new File(buildDirectory, "apacheds-work");
    workingDirectory.mkdir();

    directoryService = new DefaultDirectoryService();
    directoryService.setWorkingDirectory(workingDirectory);

    SchemaPartition schemaPartition = directoryService.getSchemaService()
        .getSchemaPartition();

    LdifPartition ldifPartition = new LdifPartition();
    String workingDirectoryPath = directoryService.getWorkingDirectory()
        .getPath();
    ldifPartition.setWorkingDirectory(workingDirectoryPath + "/schema");

    File schemaRepository = new File(workingDirectory, "schema");
    SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor(
        workingDirectory);
    extractor.extractOrCopy(true);

    schemaPartition.setWrappedPartition(ldifPartition);

    SchemaLoader loader = new LdifSchemaLoader(schemaRepository);
    SchemaManager schemaManager = new DefaultSchemaManager(loader);
    directoryService.setSchemaManager(schemaManager);

    schemaManager.loadAllEnabled();

    schemaPartition.setSchemaManager(schemaManager);

    List<Throwable> errors = schemaManager.getErrors();

    if (!errors.isEmpty())
      throw new Exception("Schema load failed : " + errors);

    JdbmPartition systemPartition = new JdbmPartition();
    systemPartition.setId("system");
    systemPartition.setPartitionDir(new File(directoryService
        .getWorkingDirectory(), "system"));
    systemPartition.setSuffix(ServerDNConstants.SYSTEM_DN);
    systemPartition.setSchemaManager(schemaManager);
    directoryService.setSystemPartition(systemPartition);

    directoryService.setShutdownHookEnabled(false);
    directoryService.getChangeLog().setEnabled(false);

    ldapServer = new LdapServer();
    ldapServer.setTransports(new TcpTransport(11389));
    ldapServer.setDirectoryService(directoryService);

    directoryService.startup();
    ldapServer.start();
  }

  @AfterClass
  public static void stopApacheDs() throws Exception {
    ldapServer.stop();
    directoryService.shutdown();
    directoryService.getWorkingDirectory().delete();
  }

  @Test
  public void anonAuth() throws NamingException {
    DirContextSource.Builder builder = new DirContextSource.Builder(
        "ldap://localhost:11389");
    DirContextSource contextSource = builder.build();

    DirContext context = contextSource.getDirContext();
    assertNotNull(context.getNameInNamespace());
    context.close();
  }

}
person Michael-O    schedule 19.01.2013

Вот сокращенная версия того, как мы его используем:

File workingDirectory = ...;

Partition partition = new JdbmPartition();
partition.setId(...);
partition.setSuffix(...);

DirectoryService directoryService = new DefaultDirectoryService();
directoryService.setWorkingDirectory(workingDirectory);
directoryService.addPartition(partition);

LdapService ldapService = new LdapService();
ldapService.setSocketAcceptor(new SocketAcceptor(null));
ldapService.setIpPort(...);
ldapService.setDirectoryService(directoryService);

directoryService.startup();
ldapService.start();
person Kevin    schedule 13.10.2009
comment
Спасибо, это все. Мне пришлось изменить некоторые строки, чтобы они соответствовали моей версии ApacheDS. Результат вы можете увидеть в вопросе. - person cringe; 14.10.2009


Порт по умолчанию для LDAP — 389.

person JuanZe    schedule 13.10.2009
comment
Но является ли он также портом по умолчанию для ApacheDS? И создает ли ApacheDS доступ к LDAP с помощью приведенного выше кода...? - person cringe; 13.10.2009
comment
Я использую Apache Directory Studio для просмотра LDAP, но я не знаком с запуском встроенного ApacheDS. Только что ответил на ваш вопрос о порте по умолчанию для LDAP. - person JuanZe; 13.10.2009
comment
Я загрузил пример кода и библиотеки и запустил его из Eclipse. Вывод показывает: log4j:WARN Не удалось найти приложения для регистратора (org.apache.directory.server.schema.registries.DefaultNormalizerRegistry). log4j:WARN Пожалуйста, правильно инициализируйте систему log4j. Найдена запись: ServerEntry dn[n]: dc=Apache,dc=Org objectClass: extensibleObject objectClass: domain objectClass: top dc: Apache - person JuanZe; 13.10.2009

Начиная с ApacheDS 1.5.7 вы получите исключение NullpointerException. Воспользуйтесь учебным пособием по адресу http://svn.apache.org/repos/asf/directory/documentation/samples/trunk/embedded-sample

person Jörg Pfründer    schedule 01.08.2011

Мне помог этот проект: Проект встроенного примера

Я использую эту зависимость в pom.xml:

<dependency>
    <groupId>org.apache.directory.server</groupId>
    <artifactId>apacheds-server-integ</artifactId>
    <version>1.5.7</version>
    <scope>test</scope>
</dependency>
person AC de Souza    schedule 17.10.2012

Кроме того, в 2.0. * рабочий каталог и другие пути больше не определяются в DirectoryService, а скорее в отдельном классе InstanceLayout, который вам нужно создать, а затем вызвать

InstanceLayout il = new InstanceLayout(BASE_PATH);
directotyService.setInstanceLayout(il);
person Zorkus    schedule 12.02.2013