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
This commit is contained in:
Robbie Gemmell 2022-07-05 12:52:11 +01:00
parent 831292e975
commit a207c614e7
6 changed files with 90 additions and 409 deletions

View File

@ -33,21 +33,8 @@ under the License.
<properties> <properties>
<activemq.basedir>${project.basedir}/../../../..</activemq.basedir> <activemq.basedir>${project.basedir}/../../../..</activemq.basedir>
<version.org.apache.ds>2.0.0-M20</version.org.apache.ds>
</properties> </properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-parent</artifactId>
<version>${version.org.apache.ds}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.activemq</groupId> <groupId>org.apache.activemq</groupId>
@ -58,25 +45,22 @@ under the License.
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId> <artifactId>slf4j-simple</artifactId>
</dependency> </dependency>
<!-- Use DS JUnit integrations to run test Directory instance for the example -->
<dependency> <dependency>
<groupId>org.apache.directory.server</groupId> <groupId>junit</groupId>
<artifactId>apacheds-core-annotations</artifactId> <artifactId>junit</artifactId>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.directory.api</groupId>
<artifactId>api-ldap-codec-standalone</artifactId>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.directory.server</groupId> <groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-protocol-ldap</artifactId> <artifactId>apacheds-test-framework</artifactId>
<version>${directory-version}</version>
</dependency>
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-server-annotations</artifactId>
<version>${directory-version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
@ -118,9 +102,6 @@ under the License.
</goals> </goals>
<configuration> <configuration>
<clientClass>org.apache.activemq.artemis.jms.example.SecurityExample</clientClass> <clientClass>org.apache.activemq.artemis.jms.example.SecurityExample</clientClass>
<args>
<arg>${project.build.outputDirectory}/example.ldif</arg>
</args>
</configuration> </configuration>
</execution> </execution>
<execution> <execution>
@ -142,6 +123,12 @@ under the License.
<artifactId>security-ldap</artifactId> <artifactId>security-ldap</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>compile</scope>
</dependency>
</dependencies> </dependencies>
</plugin> </plugin>
<plugin> <plugin>
@ -150,4 +137,4 @@ under the License.
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
</project> </project>

View File

@ -27,13 +27,11 @@ import javax.jms.TextMessage;
import javax.jms.Topic; import javax.jms.Topic;
import javax.naming.InitialContext; import javax.naming.InitialContext;
import org.apache.activemq.artemis.jms.example.ldap.LdapServer; import org.junit.runner.JUnitCore;
public class SecurityExample { public class SecurityExample {
public static void main(final String[] args) throws Exception { public static void securityExample() throws Exception {
LdapServer ldapServer = new LdapServer(args[0]);
boolean result = true; boolean result = true;
Connection failConnection = null; Connection failConnection = null;
Connection billConnection = null; Connection billConnection = null;
@ -58,6 +56,7 @@ public class SecurityExample {
try { try {
failConnection = cf.createConnection(); failConnection = cf.createConnection();
result = false; result = false;
System.err.println("Unexpectedly connected with default user");
} catch (JMSSecurityException e) { } catch (JMSSecurityException e) {
System.out.println("Default user cannot get a connection. Details: " + e.getMessage()); System.out.println("Default user cannot get a connection. Details: " + e.getMessage());
} }
@ -66,8 +65,9 @@ public class SecurityExample {
try { try {
billConnection = createConnection("bill", "activemq1", cf); billConnection = createConnection("bill", "activemq1", cf);
result = false; result = false;
System.err.println("User bill unexpectedly connected with wrong password");
} catch (JMSException e) { } 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. // Step 6. bill makes a good connection.
@ -85,16 +85,17 @@ public class SecurityExample {
// Step 9. sam makes a good connection. // Step 9. sam makes a good connection.
samConnection = createConnection("sam", "activemq3", cf); samConnection = createConnection("sam", "activemq3", cf);
samConnection.start(); samConnection.start();
System.out.println("-------------------------------------------------------------------------------------");
// Step 10. Check every user can publish/subscribe genericTopics. // 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, billConnection, "bill");
checkUserSendAndReceive(genericTopic, andrewConnection, "andrew"); checkUserSendAndReceive(genericTopic, andrewConnection, "andrew");
checkUserSendAndReceive(genericTopic, frankConnection, "frank"); checkUserSendAndReceive(genericTopic, frankConnection, "frank");
checkUserSendAndReceive(genericTopic, samConnection, "sam"); checkUserSendAndReceive(genericTopic, samConnection, "sam");
System.out.println("-------------------------------------------------------------------------------------"); 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 // Step 11. Check permissions on news.europe.europeTopic for bill: can't send and can't receive
checkUserNoSendNoReceive(europeTopic, billConnection, "bill"); checkUserNoSendNoReceive(europeTopic, billConnection, "bill");
@ -109,7 +110,7 @@ public class SecurityExample {
checkUserReceiveNoSend(europeTopic, samConnection, "sam", andrewConnection); checkUserReceiveNoSend(europeTopic, samConnection, "sam", andrewConnection);
System.out.println("-------------------------------------------------------------------------------------"); 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 // Step 15. Check permissions on news.us.usTopic for bill: can't send and can't receive
checkUserNoSendNoReceive(usTopic, billConnection, "bill"); checkUserNoSendNoReceive(usTopic, billConnection, "bill");
@ -145,8 +146,6 @@ public class SecurityExample {
if (initialContext != null) { if (initialContext != null) {
initialContext.close(); initialContext.close();
} }
ldapServer.stop();
} }
} }
@ -166,9 +165,9 @@ public class SecurityExample {
" can send message [" + " can send message [" +
msg.getText() + msg.getText() +
"] to topic " + "] to topic " +
topic); topic.getTopicName());
} catch (JMSException e) { } 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 // Now send a good message
@ -179,9 +178,9 @@ public class SecurityExample {
TextMessage receivedMsg = (TextMessage) consumer.receive(2000); TextMessage receivedMsg = (TextMessage) consumer.receive(2000);
if (receivedMsg != null) { 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 { } 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(); session1.close();
@ -198,7 +197,7 @@ public class SecurityExample {
try { try {
session.createConsumer(topic); session.createConsumer(topic);
} catch (JMSException e) { } 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); Session session1 = receivingConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
@ -209,13 +208,13 @@ public class SecurityExample {
TextMessage receivedMsg = (TextMessage) goodConsumer.receive(2000); TextMessage receivedMsg = (TextMessage) goodConsumer.receive(2000);
if (receivedMsg != null) { 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 { } else {
throw new IllegalStateException("Security setting is broken! User " + user + throw new IllegalStateException("Security setting is broken! User " + user +
" cannot send message [" + " cannot send message [" +
msg.getText() + msg.getText() +
"] to topic " + "] to topic " +
topic); topic.getTopicName());
} }
session.close(); session.close();
@ -232,7 +231,7 @@ public class SecurityExample {
try { try {
session.createConsumer(topic); session.createConsumer(topic);
} catch (JMSException e) { } 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"); TextMessage msg = session.createTextMessage("hello-world-3");
@ -242,9 +241,9 @@ public class SecurityExample {
" can send message [" + " can send message [" +
msg.getText() + msg.getText() +
"] to topic " + "] to topic " +
topic); topic.getTopicName());
} catch (JMSException e) { } 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(); session.close();
@ -261,8 +260,8 @@ public class SecurityExample {
producer.send(msg); producer.send(msg);
TextMessage receivedMsg = (TextMessage) consumer.receive(5000); TextMessage receivedMsg = (TextMessage) consumer.receive(5000);
if (receivedMsg != null) { if (receivedMsg != null) {
System.out.println("User " + user + " can send message: [" + msg.getText() + "] to 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); System.out.println("User " + user + " can receive message: [" + msg.getText() + "] from topic: " + topic.getTopicName());
} else { } else {
throw new IllegalStateException("Error! User " + user + " cannot receive the message! "); throw new IllegalStateException("Error! User " + user + " cannot receive the message! ");
} }
@ -274,4 +273,9 @@ public class SecurityExample {
final ConnectionFactory cf) throws JMSException { final ConnectionFactory cf) throws JMSException {
return cf.createConnection(username, password); 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());
}
} }

View File

@ -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 ========");
}
}

View File

@ -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-<code>null</code>
* @param partitionFactory must be not-<code>null</code>
*/
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<Throwable> 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;
}
}

View File

@ -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<String, Boolean> 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);
}
}
}
}

View File

@ -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);
}
}
}