View Javadoc
1   /*
2    * Copyright 2013-2025 Brian Thomas Matthews
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.buralotech.oss.ldapunit;
18  
19  import com.unboundid.ldap.listener.InMemoryDirectoryServer;
20  import org.junit.runners.model.Statement;
21  
22  /**
23   * A {@link Statement} wrapper that launches an embedded LDAP directory server before executing the wrapped statement.
24   * The embedded LDAP directory server is shutdown after the wrapped statement has been executed.
25   *
26   * @author <a href="mailto:bmatthews68@gmail.com">Brian Matthews</a>
27   * @since 1.0.0
28   */
29  final class DirectoryServerStatement extends Statement {
30  
31      /**
32       * The wrapped statement {@link Statement}.
33       */
34      private final Statement base;
35      /**
36       * The annotation that defines the directory server configuration.
37       */
38      private final DirectoryServerConfiguration annotation;
39  
40      /**
41       * Initialise the wrapper statement that starts an embedded LDAP directory server and shuts it down before and after
42       * executing the wrapped statement.
43       *
44       * @param stmt The wrapped statement.
45       * @param cfg  The directory server configuration.
46       */
47      DirectoryServerStatement(final Statement stmt, final DirectoryServerConfiguration cfg) {
48          base = stmt;
49          annotation = cfg;
50      }
51  
52      /**
53       * Start an embedded LDAP directory server before executing the wrapped statement and shutdown the LDAP directory
54       * server after the wrapped statement completes.
55       *
56       * @throws Throwable If there was an error starting the server, executing the wrapped statement or shutting the
57       *                   wrapped server.
58       */
59      @Override
60      public void evaluate() throws Throwable {
61          try (InMemoryDirectoryServer server = DirectoryServerUtils.startServer(annotation)) {
62              base.evaluate();
63          }
64      }
65  }