From 9d6ecd358f1b1c2d32b3a209d0fabe8bb6d4b4a7 Mon Sep 17 00:00:00 2001
From: Gaetan Boismal <gaetan.boismal@forgerock.com>
Date: Thu, 16 Apr 2015 14:17:37 +0000
Subject: [PATCH] OPENDJ-1714 Create a LDIF context management

---
 opendj-server-legacy/src/main/java/org/opends/server/tools/ConfigureDS.java                    |   51 ++++------------
 opendj-config/src/main/java/org/forgerock/opendj/config/client/ldap/LDAPManagementContext.java |   95 +++++++++++++++++++++++++++++++
 2 files changed, 109 insertions(+), 37 deletions(-)

diff --git a/opendj-config/src/main/java/org/forgerock/opendj/config/client/ldap/LDAPManagementContext.java b/opendj-config/src/main/java/org/forgerock/opendj/config/client/ldap/LDAPManagementContext.java
index f352842..6c2be14 100644
--- a/opendj-config/src/main/java/org/forgerock/opendj/config/client/ldap/LDAPManagementContext.java
+++ b/opendj-config/src/main/java/org/forgerock/opendj/config/client/ldap/LDAPManagementContext.java
@@ -27,16 +27,39 @@
 
 package org.forgerock.opendj.config.client.ldap;
 
+import static org.forgerock.opendj.ldap.Connections.*;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.List;
+
+import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.i18n.slf4j.LocalizedLogger;
 import org.forgerock.opendj.config.LDAPProfile;
 import org.forgerock.opendj.config.client.ManagementContext;
 import org.forgerock.opendj.config.client.spi.Driver;
+import org.forgerock.opendj.ldap.AbstractConnectionWrapper;
 import org.forgerock.opendj.ldap.Connection;
+import org.forgerock.opendj.ldap.Entry;
+import org.forgerock.opendj.ldap.MemoryBackend;
+import org.forgerock.opendj.ldap.requests.UnbindRequest;
+import org.forgerock.opendj.ldif.LDIF;
+import org.forgerock.opendj.ldif.LDIFEntryReader;
+import org.forgerock.opendj.ldif.LDIFEntryWriter;
 import org.forgerock.util.Reject;
 
 /**
  * An LDAP management connection context.
  */
 public final class LDAPManagementContext extends ManagementContext {
+
+    private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
+
     /**
      * Create a new LDAP management context using the provided LDAP connection.
      *
@@ -54,6 +77,78 @@
         return context;
     }
 
+    /**
+     * Returns a LDIF management context on the provided LDIF file.
+     *
+     * @param ldifFile
+     *            The LDIF file to manage
+     * @param profile
+     *            The LDAP profile
+     * @param exceptions
+     *            Contains {@code IOException} that may occurred during
+     *            management context close. Could be {@code null}
+     * @return A LDIF file management context
+     * @throws IOException
+     *             If problems occurs while reading the file.
+     */
+    public static ManagementContext newLDIFManagementContext(
+        final File ldifFile, final LDAPProfile profile, final List<IOException> exceptions) throws IOException {
+        final BufferedReader configReader = new BufferedReader(new FileReader(ldifFile));
+        try {
+            final MemoryBackend memoryBackend = new MemoryBackend(new LDIFEntryReader(configReader));
+            final Connection co = new AbstractConnectionWrapper<Connection>(newInternalConnection(memoryBackend)) {
+                @Override
+                public void close() {
+                    try {
+                        final BufferedWriter configWriter = new BufferedWriter(new FileWriter(ldifFile));
+                        try {
+                            final Iterator<Entry> entries = memoryBackend.getAll().iterator();
+                            entries.next(); // skip RootDSE
+                            LDIF.copyTo(LDIF.newEntryIteratorReader(entries), new LDIFEntryWriter(configWriter));
+                        } finally {
+                            configWriter.close();
+                        }
+                    } catch (IOException e) {
+                        if (exceptions != null) {
+                            exceptions.add(e);
+                        } else {
+                            logger.error(LocalizableMessage.raw(
+                                "IOException occured during LDIF context management close:" + e));
+                        }
+                    }
+                }
+
+                @Override
+                public void close(UnbindRequest request, String reason) {
+                    close();
+                }
+            };
+
+            // We need to add the root dse entry to make the configuration
+            // framework work.
+            co.add(LDIFEntryReader.valueOfLDIFEntry("dn:", "objectClass:top", "objectClass:ds-root-dse"));
+            return LDAPManagementContext.newManagementContext(co, LDAPProfile.getInstance());
+        } finally {
+            configReader.close();
+        }
+    }
+
+    /**
+     * Returns a LDIF management context on the provided LDIF file.
+     *
+     * @param ldifFile
+     *            The LDIF file to manage
+     * @param profile
+     *            The LDAP profile
+     * @return A LDIF file management context
+     * @throws IOException
+     *             If problems occurs while reading the file.
+     */
+    public static ManagementContext newLDIFManagementContext(
+        final File ldifFile, final LDAPProfile profile) throws IOException {
+        return newLDIFManagementContext(ldifFile, profile, null);
+    }
+
     /** The LDAP management context driver. */
     private final LDAPDriver driver;
 
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/ConfigureDS.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/ConfigureDS.java
index fef439b..7b19471 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/ConfigureDS.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/tools/ConfigureDS.java
@@ -37,11 +37,8 @@
 import static com.forgerock.opendj.cli.ArgumentConstants.*;
 import static com.forgerock.opendj.cli.Utils.*;
 
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
 import java.io.File;
-import java.io.FileReader;
-import java.io.FileWriter;
+import java.io.IOException;
 import java.io.OutputStream;
 import java.io.PrintStream;
 import java.io.StringReader;
@@ -49,7 +46,6 @@
 import java.security.GeneralSecurityException;
 import java.util.Collection;
 import java.util.HashSet;
-import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Set;
@@ -61,13 +57,7 @@
 import org.forgerock.opendj.config.ManagedObjectDefinition;
 import org.forgerock.opendj.config.client.ManagementContext;
 import org.forgerock.opendj.config.client.ldap.LDAPManagementContext;
-import org.forgerock.opendj.ldap.Connection;
-import org.forgerock.opendj.ldap.Connections;
-import org.forgerock.opendj.ldap.MemoryBackend;
 import org.forgerock.opendj.ldap.schema.Schema;
-import org.forgerock.opendj.ldif.LDIF;
-import org.forgerock.opendj.ldif.LDIFEntryReader;
-import org.forgerock.opendj.ldif.LDIFEntryWriter;
 import org.forgerock.opendj.server.config.client.BackendCfgClient;
 import org.forgerock.opendj.server.config.client.BackendIndexCfgClient;
 import org.forgerock.opendj.server.config.client.LocalDBBackendCfgClient;
@@ -813,45 +803,32 @@
             ERR_CONFIGDS_BACKEND_TYPE_UNKNOWN.get(backendTypeName, backendTypeHelper.getBackendTypeNames()));
       }
 
-      BufferedReader configReader = null;
-      BufferedWriter configWriter = null;
       try
       {
-          final File configurationFile = Installation.getLocal().getCurrentConfigurationFile();
-          configReader = new BufferedReader(new FileReader(configurationFile));
-
-          final MemoryBackend memoryBackend = new MemoryBackend(new LDIFEntryReader(configReader));
-          final Connection co = Connections.newInternalConnection(memoryBackend);
-          // We need to add the root dse entry to make the configuration framework work.
-          co.add(LDIFEntryReader.valueOfLDIFEntry("dn:", "objectClass:top", "objectClass:ds-root-dse"));
-
-          final ManagementContext context = LDAPManagementContext.newManagementContext(co, LDAPProfile.getInstance());
+          final File ldifConfigFile = Installation.getLocal().getCurrentConfigurationFile();
+          final List<IOException> exceptions = new LinkedList<IOException>();
+          final ManagementContext context =
+              LDAPManagementContext.newLDIFManagementContext(ldifConfigFile, LDAPProfile.getInstance(), exceptions);
           createBackend(context.getRootConfiguration(), baseDNs,
-                        (ManagedObjectDefinition<? extends BackendCfgClient, ? extends BackendCfg>) backend);
-
-
-          final Iterator<org.forgerock.opendj.ldap.Entry> entries = memoryBackend.getAll().iterator();
-          entries.next(); // skip RootDSE
-          configWriter = new BufferedWriter(new FileWriter(configurationFile));
-          LDIF.copyTo(LDIF.newEntryIteratorReader(entries), new LDIFEntryWriter(configWriter));
+              (ManagedObjectDefinition<? extends BackendCfgClient, ? extends BackendCfg>) backend);
+          context.close();
+          if (!exceptions.isEmpty())
+          {
+            throw exceptions.get(0);
+          }
       }
       catch (final Exception e)
       {
         throw new ConfigureDSException(ERR_CONFIGDS_SET_BACKEND_TYPE.get(backendTypeName, e.getMessage()));
       }
-      finally
-      {
-        close(configReader, configWriter);
-      }
     }
   }
 
   private void createBackend(final RootCfgClient rootConfiguration, final List<org.forgerock.opendj.ldap.DN> baseDNs,
-      final ManagedObjectDefinition<?, ?> backend) throws Exception
+      final ManagedObjectDefinition<? extends BackendCfgClient, ? extends BackendCfg> backend) throws Exception
   {
-      final BackendCfgClient backendCfgClient = rootConfiguration.createBackend(
-                      (ManagedObjectDefinition<? extends BackendCfgClient, ? extends BackendCfg>) backend,
-                      Installer.ROOT_BACKEND_NAME, null);
+      final BackendCfgClient backendCfgClient =
+          rootConfiguration.createBackend(backend, Installer.ROOT_BACKEND_NAME, null);
       backendCfgClient.setEnabled(true);
       backendCfgClient.setBaseDN(baseDNs);
       backendCfgClient.setWritabilityMode(WritabilityMode.ENABLED);

--
Gitblit v1.10.0