From a207c614e7398edc4b3af5c0a69e6e836baeb755 Mon Sep 17 00:00:00 2001 From: Robbie Gemmell Date: Tue, 5 Jul 2022 12:52:11 +0100 Subject: [PATCH] ARTEMIS-3883: use same version + junit helpers as rest of build to start embedded test Directory for example, rather than custom classes Also tweak example output for clarity --- .../features/standard/security-ldap/pom.xml | 49 ++---- .../artemis/jms/example/SecurityExample.java | 48 +++--- .../SecurityExampleTestLdapServer.java | 46 +++++ .../ldap/InMemoryDirectoryServiceFactory.java | 161 ------------------ .../example/ldap/InMemorySchemaPartition.java | 95 ----------- .../artemis/jms/example/ldap/LdapServer.java | 100 ----------- 6 files changed, 90 insertions(+), 409 deletions(-) create mode 100644 examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/SecurityExampleTestLdapServer.java delete mode 100644 examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/ldap/InMemoryDirectoryServiceFactory.java delete mode 100644 examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/ldap/InMemorySchemaPartition.java delete mode 100644 examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/ldap/LdapServer.java diff --git a/examples/features/standard/security-ldap/pom.xml b/examples/features/standard/security-ldap/pom.xml index 14fbc39cc7..859bc1d2d2 100644 --- a/examples/features/standard/security-ldap/pom.xml +++ b/examples/features/standard/security-ldap/pom.xml @@ -33,21 +33,8 @@ under the License. ${project.basedir}/../../../.. - 2.0.0-M20 - - - - org.apache.directory.server - apacheds-parent - ${version.org.apache.ds} - import - pom - - - - org.apache.activemq @@ -58,25 +45,22 @@ under the License. org.slf4j slf4j-simple + + - org.apache.directory.server - apacheds-core-annotations - compile - - - org.slf4j - slf4j-log4j12 - - - - - org.apache.directory.api - api-ldap-codec-standalone + junit + junit compile org.apache.directory.server - apacheds-protocol-ldap + apacheds-test-framework + ${directory-version} + + + org.apache.directory.server + apacheds-server-annotations + ${directory-version} @@ -118,9 +102,6 @@ under the License. org.apache.activemq.artemis.jms.example.SecurityExample - - ${project.build.outputDirectory}/example.ldif - @@ -142,6 +123,12 @@ under the License. security-ldap ${project.version} + + junit + junit + ${junit.version} + compile + @@ -150,4 +137,4 @@ under the License. - \ No newline at end of file + diff --git a/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/SecurityExample.java b/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/SecurityExample.java index 2861182ded..503149e0b0 100644 --- a/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/SecurityExample.java +++ b/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/SecurityExample.java @@ -27,13 +27,11 @@ import javax.jms.TextMessage; import javax.jms.Topic; import javax.naming.InitialContext; -import org.apache.activemq.artemis.jms.example.ldap.LdapServer; +import org.junit.runner.JUnitCore; public class SecurityExample { - public static void main(final String[] args) throws Exception { - LdapServer ldapServer = new LdapServer(args[0]); - + public static void securityExample() throws Exception { boolean result = true; Connection failConnection = null; Connection billConnection = null; @@ -58,6 +56,7 @@ public class SecurityExample { try { failConnection = cf.createConnection(); result = false; + System.err.println("Unexpectedly connected with default user"); } catch (JMSSecurityException e) { System.out.println("Default user cannot get a connection. Details: " + e.getMessage()); } @@ -66,8 +65,9 @@ public class SecurityExample { try { billConnection = createConnection("bill", "activemq1", cf); result = false; + System.err.println("User bill unexpectedly connected with wrong password"); } catch (JMSException e) { - System.out.println("User bill failed to connect. Details: " + e.getMessage()); + System.out.println("User bill failed to connect with wrong password. Details: " + e.getMessage()); } // Step 6. bill makes a good connection. @@ -85,16 +85,17 @@ public class SecurityExample { // Step 9. sam makes a good connection. samConnection = createConnection("sam", "activemq3", cf); samConnection.start(); + System.out.println("-------------------------------------------------------------------------------------"); // Step 10. Check every user can publish/subscribe genericTopics. - System.out.println("------------------------Checking permissions on " + genericTopic + "----------------"); + System.out.println("======== Checking permissions on " + genericTopic.getTopicName() + " ========"); checkUserSendAndReceive(genericTopic, billConnection, "bill"); checkUserSendAndReceive(genericTopic, andrewConnection, "andrew"); checkUserSendAndReceive(genericTopic, frankConnection, "frank"); checkUserSendAndReceive(genericTopic, samConnection, "sam"); System.out.println("-------------------------------------------------------------------------------------"); - System.out.println("------------------------Checking permissions on " + europeTopic + "----------------"); + System.out.println("======== Checking permissions on " + europeTopic.getTopicName() + " ========"); // Step 11. Check permissions on news.europe.europeTopic for bill: can't send and can't receive checkUserNoSendNoReceive(europeTopic, billConnection, "bill"); @@ -109,7 +110,7 @@ public class SecurityExample { checkUserReceiveNoSend(europeTopic, samConnection, "sam", andrewConnection); System.out.println("-------------------------------------------------------------------------------------"); - System.out.println("------------------------Checking permissions on " + usTopic + "----------------"); + System.out.println("======== Checking permissions on " + usTopic.getTopicName() + " ========"); // Step 15. Check permissions on news.us.usTopic for bill: can't send and can't receive checkUserNoSendNoReceive(usTopic, billConnection, "bill"); @@ -145,8 +146,6 @@ public class SecurityExample { if (initialContext != null) { initialContext.close(); } - - ldapServer.stop(); } } @@ -166,9 +165,9 @@ public class SecurityExample { " can send message [" + msg.getText() + "] to topic " + - topic); + topic.getTopicName()); } catch (JMSException e) { - System.out.println("User " + user + " cannot send message [" + msg.getText() + "] to topic: " + topic); + System.out.println("User " + user + " cannot send message [" + msg.getText() + "] to topic: " + topic.getTopicName()); } // Now send a good message @@ -179,9 +178,9 @@ public class SecurityExample { TextMessage receivedMsg = (TextMessage) consumer.receive(2000); if (receivedMsg != null) { - System.out.println("User " + user + " can receive message [" + receivedMsg.getText() + "] from topic " + topic); + System.out.println("User " + user + " can receive message [" + receivedMsg.getText() + "] from topic " + topic.getTopicName()); } else { - throw new IllegalStateException("Security setting is broken! User " + user + " cannot receive message from topic " + topic); + throw new IllegalStateException("Security setting is broken! User " + user + " cannot receive message from topic " + topic.getTopicName()); } session1.close(); @@ -198,7 +197,7 @@ public class SecurityExample { try { session.createConsumer(topic); } catch (JMSException e) { - System.out.println("User " + user + " cannot receive any message from topic " + topic); + System.out.println("User " + user + " cannot receive any message from topic " + topic.getTopicName()); } Session session1 = receivingConn.createSession(false, Session.AUTO_ACKNOWLEDGE); @@ -209,13 +208,13 @@ public class SecurityExample { TextMessage receivedMsg = (TextMessage) goodConsumer.receive(2000); if (receivedMsg != null) { - System.out.println("User " + user + " can send message [" + receivedMsg.getText() + "] to topic " + topic); + System.out.println("User " + user + " can send message [" + receivedMsg.getText() + "] to topic " + topic.getTopicName()); } else { throw new IllegalStateException("Security setting is broken! User " + user + " cannot send message [" + msg.getText() + "] to topic " + - topic); + topic.getTopicName()); } session.close(); @@ -232,7 +231,7 @@ public class SecurityExample { try { session.createConsumer(topic); } catch (JMSException e) { - System.out.println("User " + user + " cannot create consumer on topic " + topic); + System.out.println("User " + user + " cannot create consumer on topic " + topic.getTopicName()); } TextMessage msg = session.createTextMessage("hello-world-3"); @@ -242,9 +241,9 @@ public class SecurityExample { " can send message [" + msg.getText() + "] to topic " + - topic); + topic.getTopicName()); } catch (JMSException e) { - System.out.println("User " + user + " cannot send message [" + msg.getText() + "] to topic: " + topic); + System.out.println("User " + user + " cannot send message [" + msg.getText() + "] to topic: " + topic.getTopicName()); } session.close(); @@ -261,8 +260,8 @@ public class SecurityExample { producer.send(msg); TextMessage receivedMsg = (TextMessage) consumer.receive(5000); if (receivedMsg != null) { - System.out.println("User " + user + " can send message: [" + msg.getText() + "] to topic: " + topic); - System.out.println("User " + user + " can receive message: [" + msg.getText() + "] from topic: " + topic); + System.out.println("User " + user + " can send message: [" + msg.getText() + "] to topic: " + topic.getTopicName()); + System.out.println("User " + user + " can receive message: [" + msg.getText() + "] from topic: " + topic.getTopicName()); } else { throw new IllegalStateException("Error! User " + user + " cannot receive the message! "); } @@ -274,4 +273,9 @@ public class SecurityExample { final ConnectionFactory cf) throws JMSException { return cf.createConnection(username, password); } + + // Boiler plate, leverages JUnit integrations to start test LDAP server and then run example code above. + public static void main(final String[] args) throws Exception { + JUnitCore.main(SecurityExampleTestLdapServer.class.getName()); + } } diff --git a/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/SecurityExampleTestLdapServer.java b/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/SecurityExampleTestLdapServer.java new file mode 100644 index 0000000000..9055854c0a --- /dev/null +++ b/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/SecurityExampleTestLdapServer.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.activemq.artemis.jms.example; + +import org.apache.directory.server.core.annotations.CreateDS; +import org.apache.directory.server.core.annotations.CreatePartition; +import org.apache.directory.server.annotations.CreateLdapServer; +import org.apache.directory.server.annotations.CreateTransport; +import org.apache.directory.server.core.annotations.ApplyLdifFiles; +import org.apache.directory.server.core.integ.CreateLdapServerRule; +import org.junit.ClassRule; +import org.junit.Test; + +// Boiler plate JUnit test class, leveraging integrations to stand up test LDAP server and then run example during test. +@CreateDS(name = "myDS", partitions = {@CreatePartition(name = "test", suffix = "dc=activemq,dc=org")}) +@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP", port = 1024)}) +@ApplyLdifFiles({"example.ldif"}) +public class SecurityExampleTestLdapServer { + + @ClassRule + public static CreateLdapServerRule serverRule = new CreateLdapServerRule(); + + @Test + public void securityExampleWrapperTest() throws Exception { + System.out.println("-------------------------------------------------------------------------------------"); + System.out.println("======== Running Example Application Code ========"); + + SecurityExample.securityExample(); + + System.out.println("======== Complete, cleaning up ========"); + } +} diff --git a/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/ldap/InMemoryDirectoryServiceFactory.java b/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/ldap/InMemoryDirectoryServiceFactory.java deleted file mode 100644 index f6aaf44b13..0000000000 --- a/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/ldap/InMemoryDirectoryServiceFactory.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.artemis.jms.example.ldap; - -import java.io.File; -import java.io.IOException; -import java.util.List; - -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.config.CacheConfiguration; -import net.sf.ehcache.config.Configuration; -import org.apache.commons.io.FileUtils; -import org.apache.directory.api.ldap.model.constants.SchemaConstants; -import org.apache.directory.api.ldap.model.schema.LdapComparator; -import org.apache.directory.api.ldap.model.schema.SchemaManager; -import org.apache.directory.api.ldap.model.schema.comparators.NormalizingComparator; -import org.apache.directory.api.ldap.model.schema.registries.ComparatorRegistry; -import org.apache.directory.api.ldap.model.schema.registries.SchemaLoader; -import org.apache.directory.api.ldap.schema.loader.JarLdifSchemaLoader; -import org.apache.directory.api.ldap.schema.manager.impl.DefaultSchemaManager; -import org.apache.directory.api.util.exception.Exceptions; -import org.apache.directory.server.constants.ServerDNConstants; -import org.apache.directory.server.core.DefaultDirectoryService; -import org.apache.directory.server.core.api.CacheService; -import org.apache.directory.server.core.api.DirectoryService; -import org.apache.directory.server.core.api.InstanceLayout; -import org.apache.directory.server.core.api.partition.Partition; -import org.apache.directory.server.core.api.schema.SchemaPartition; -import org.apache.directory.server.core.factory.AvlPartitionFactory; -import org.apache.directory.server.core.factory.DirectoryServiceFactory; -import org.apache.directory.server.core.factory.PartitionFactory; -import org.apache.directory.server.i18n.I18n; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Factory for a fast (mostly in-memory-only) ApacheDS DirectoryService. Use only for tests!! - */ -public class InMemoryDirectoryServiceFactory implements DirectoryServiceFactory { - - private static Logger LOG = LoggerFactory.getLogger(InMemoryDirectoryServiceFactory.class); - - private final DirectoryService directoryService; - private final PartitionFactory partitionFactory; - - /** - * Default constructor which creates {@link DefaultDirectoryService} instance and configures {@link AvlPartitionFactory} as - * the {@link PartitionFactory} implementation. - */ - public InMemoryDirectoryServiceFactory() { - try { - directoryService = new DefaultDirectoryService(); - } catch (Exception e) { - throw new RuntimeException(e); - } - directoryService.setShutdownHookEnabled(false); - partitionFactory = new AvlPartitionFactory(); - } - - /** - * Constructor which uses provided {@link DirectoryService} and {@link PartitionFactory} implementations. - * - * @param directoryService must be not-null - * @param partitionFactory must be not-null - */ - public InMemoryDirectoryServiceFactory(DirectoryService directoryService, PartitionFactory partitionFactory) { - this.directoryService = directoryService; - this.partitionFactory = partitionFactory; - } - - /** - * {@inheritDoc} - */ - @Override - public void init(String name) throws Exception { - if ((directoryService == null) || directoryService.isStarted()) { - return; - } - - directoryService.setInstanceId(name); - - // instance layout - InstanceLayout instanceLayout = new InstanceLayout(System.getProperty("java.io.tmpdir") + "/server-work-" + name); - if (instanceLayout.getInstanceDirectory().exists()) { - try { - FileUtils.deleteDirectory(instanceLayout.getInstanceDirectory()); - } catch (IOException e) { - LOG.warn("couldn't delete the instance directory before initializing the DirectoryService", e); - } - } - directoryService.setInstanceLayout(instanceLayout); - - // EhCache in disabled-like-mode - Configuration ehCacheConfig = new Configuration(); - CacheConfiguration defaultCache = new CacheConfiguration("default", 1).eternal(false).timeToIdleSeconds(30).timeToLiveSeconds(30).overflowToDisk(false); - ehCacheConfig.addDefaultCache(defaultCache); - CacheService cacheService = new CacheService(new CacheManager(ehCacheConfig)); - directoryService.setCacheService(cacheService); - - // Init the schema - // SchemaLoader loader = new SingleLdifSchemaLoader(); - SchemaLoader loader = new JarLdifSchemaLoader(); - SchemaManager schemaManager = new DefaultSchemaManager(loader); - schemaManager.loadAllEnabled(); - ComparatorRegistry comparatorRegistry = schemaManager.getComparatorRegistry(); - for (LdapComparator comparator : comparatorRegistry) { - if (comparator instanceof NormalizingComparator) { - ((NormalizingComparator) comparator).setOnServer(); - } - } - directoryService.setSchemaManager(schemaManager); - InMemorySchemaPartition inMemorySchemaPartition = new InMemorySchemaPartition(schemaManager); - - SchemaPartition schemaPartition = new SchemaPartition(schemaManager); - schemaPartition.setWrappedPartition(inMemorySchemaPartition); - directoryService.setSchemaPartition(schemaPartition); - List errors = schemaManager.getErrors(); - if (errors.size() != 0) { - throw new Exception(I18n.err(I18n.ERR_317, Exceptions.printErrors(errors))); - } - - // Init system partition - Partition systemPartition = partitionFactory.createPartition(directoryService.getSchemaManager(), directoryService.getDnFactory(), "system", ServerDNConstants.SYSTEM_DN, 500, new File(directoryService.getInstanceLayout().getPartitionsDirectory(), "system")); - systemPartition.setSchemaManager(directoryService.getSchemaManager()); - partitionFactory.addIndex(systemPartition, SchemaConstants.OBJECT_CLASS_AT, 100); - directoryService.setSystemPartition(systemPartition); - - directoryService.startup(); - } - - /** - * {@inheritDoc} - */ - @Override - public DirectoryService getDirectoryService() throws Exception { - return directoryService; - } - - /** - * {@inheritDoc} - */ - @Override - public PartitionFactory getPartitionFactory() throws Exception { - return partitionFactory; - } - -} diff --git a/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/ldap/InMemorySchemaPartition.java b/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/ldap/InMemorySchemaPartition.java deleted file mode 100644 index 256a281499..0000000000 --- a/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/ldap/InMemorySchemaPartition.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.artemis.jms.example.ldap; - -import javax.naming.InvalidNameException; -import java.net.URL; -import java.util.Map; -import java.util.TreeSet; -import java.util.UUID; -import java.util.regex.Pattern; - -import org.apache.directory.api.ldap.model.constants.SchemaConstants; -import org.apache.directory.api.ldap.model.entry.DefaultEntry; -import org.apache.directory.api.ldap.model.entry.Entry; -import org.apache.directory.api.ldap.model.ldif.LdifEntry; -import org.apache.directory.api.ldap.model.ldif.LdifReader; -import org.apache.directory.api.ldap.model.schema.SchemaManager; -import org.apache.directory.api.ldap.schema.extractor.impl.DefaultSchemaLdifExtractor; -import org.apache.directory.api.ldap.schema.extractor.impl.ResourceMap; -import org.apache.directory.server.core.api.interceptor.context.AddOperationContext; -import org.apache.directory.server.core.partition.ldif.AbstractLdifPartition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * In-memory schema-only partition which loads the data in the similar way as the - * {@link org.apache.directory.api.ldap.schema.loader.JarLdifSchemaLoader}. - */ -public class InMemorySchemaPartition extends AbstractLdifPartition { - - private static Logger LOG = LoggerFactory.getLogger(InMemorySchemaPartition.class); - - /** - * Filesystem path separator pattern, either forward slash or backslash. java.util.regex.Pattern is immutable so only one - * instance is needed for all uses. - */ - - public InMemorySchemaPartition(SchemaManager schemaManager) { - super(schemaManager); - } - - /** - * Partition initialization - loads schema entries from the files on classpath. - * - * @see org.apache.directory.server.core.partition.impl.avl.AvlPartition#doInit() - */ - @Override - protected void doInit() throws InvalidNameException, Exception { - if (initialized) { - return; - } - - LOG.debug("Initializing schema partition " + getId()); - suffixDn.apply(schemaManager); - super.doInit(); - - // load schema - final Map resMap = ResourceMap.getResources(Pattern.compile("schema[/\\Q\\\\E]ou=schema.*")); - for (String resourcePath : new TreeSet<>(resMap.keySet())) { - if (resourcePath.endsWith(".ldif")) { - URL resource = DefaultSchemaLdifExtractor.getUniqueResource(resourcePath, "Schema LDIF file"); - LdifEntry ldifEntry; - try (LdifReader reader = new LdifReader(resource.openStream())) { - ldifEntry = reader.next(); - } - - Entry entry = new DefaultEntry(schemaManager, ldifEntry.getEntry()); - // add mandatory attributes - if (entry.get(SchemaConstants.ENTRY_CSN_AT) == null) { - entry.add(SchemaConstants.ENTRY_CSN_AT, defaultCSNFactory.newInstance().toString()); - } - if (entry.get(SchemaConstants.ENTRY_UUID_AT) == null) { - entry.add(SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString()); - } - AddOperationContext addContext = new AddOperationContext(null, entry); - super.add(addContext); - } - } - } - -} diff --git a/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/ldap/LdapServer.java b/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/ldap/LdapServer.java deleted file mode 100644 index c9a4b3cf4b..0000000000 --- a/examples/features/standard/security-ldap/src/main/java/org/apache/activemq/artemis/jms/example/ldap/LdapServer.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.artemis.jms.example.ldap; - -import java.io.IOException; - -import org.apache.directory.api.ldap.model.entry.DefaultEntry; -import org.apache.directory.api.ldap.model.ldif.LdifEntry; -import org.apache.directory.api.ldap.model.ldif.LdifReader; -import org.apache.directory.api.ldap.model.name.Dn; -import org.apache.directory.api.ldap.model.schema.SchemaManager; -import org.apache.directory.server.core.api.DirectoryService; -import org.apache.directory.server.core.partition.impl.avl.AvlPartition; -import org.apache.directory.server.protocol.shared.transport.TcpTransport; - -/** - * Creates and starts LDAP server(s). - */ -public class LdapServer { - - private final DirectoryService directoryService; - private final org.apache.directory.server.ldap.LdapServer ldapServer; - - /** - * Create a single LDAP server. - * - * @param ldifFile - * @throws Exception - */ - public LdapServer(String ldifFile) throws Exception { - InMemoryDirectoryServiceFactory dsFactory = new InMemoryDirectoryServiceFactory(); - dsFactory.init("ds"); - - directoryService = dsFactory.getDirectoryService(); - - final SchemaManager schemaManager = directoryService.getSchemaManager(); - importLdif(directoryService, schemaManager, new LdifReader(ldifFile)); - - ldapServer = new org.apache.directory.server.ldap.LdapServer(); - ldapServer.setTransports(new TcpTransport("127.0.0.1", 1024)); - ldapServer.setDirectoryService(directoryService); - - ldapServer.start(); - } - - /** - * Stops LDAP server and the underlying directory service. - * - * @throws Exception - */ - public void stop() throws Exception { - ldapServer.stop(); - directoryService.shutdown(); - } - - private void importLdif(DirectoryService directoryService, - final SchemaManager schemaManager, - LdifReader ldifReader) throws Exception { - try { - for (LdifEntry ldifEntry : ldifReader) { - checkPartition(ldifEntry); - directoryService.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry())); - } - } finally { - try { - ldifReader.close(); - } catch (IOException ioe) { - // ignore - } - } - } - - private void checkPartition(LdifEntry ldifEntry) throws Exception { - Dn dn = ldifEntry.getDn(); - Dn parent = dn.getParent(); - try { - directoryService.getAdminSession().exists(parent); - } catch (Exception e) { - System.out.println("Creating new partition for DN=" + dn + "\n"); - AvlPartition partition = new AvlPartition(directoryService.getSchemaManager()); - partition.setId(dn.getName()); - partition.setSuffixDn(dn); - directoryService.addPartition(partition); - } - } -}