From 7f90143dd0cfdf7ed6c35a259e1aec68a3aa2951 Mon Sep 17 00:00:00 2001
From: Nicolas Capponi <nicolas.capponi@forgerock.com>
Date: Thu, 27 Feb 2014 10:48:18 +0000
Subject: [PATCH] Refactor retrieval of serverRoot and instanceRoot to have an unique implementation

---
 opendj-sdk/opendj3-server-dev/src/server/org/opends/server/types/DirectoryEnvironmentConfig.java |  149 ++++++++++++++++++---
 opendj-sdk/opendj3-server-dev/src/server/org/opends/server/extensions/ConfigFileHandler.java     |  104 +-------------
 opendj-sdk/opendj3-server-dev/src/server/org/opends/server/core/ServerContext.java               |   18 ++
 opendj-sdk/opendj3-server-dev/src/server/org/opends/server/core/DirectoryServer.java             |  111 +++++----------
 4 files changed, 191 insertions(+), 191 deletions(-)

diff --git a/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/core/DirectoryServer.java b/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/core/DirectoryServer.java
index 0e8f040..8a69d9d 100644
--- a/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/core/DirectoryServer.java
+++ b/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/core/DirectoryServer.java
@@ -766,6 +766,20 @@
       return directoryServer.schema;
     }
 
+    /** {@inheritDoc} */
+    @Override
+    public DirectoryEnvironmentConfig getEnvironment()
+    {
+      return directoryServer.environmentConfig;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public ServerManagementContext getServerManagementContext()
+    {
+      return ServerManagementContext.getInstance();
+    }
+
   }
 
 
@@ -2836,22 +2850,7 @@
   */
   public static String getServerRoot()
   {
-    if (directoryServer.configHandler == null)
-    {
-      File serverRoot = directoryServer.environmentConfig.getServerRoot();
-      if (serverRoot != null)
-      {
-        return serverRoot.getAbsolutePath();
-      }
-
-      // We don't know where the server root is, so we'll have to assume it's
-      // the current working directory.
-      return System.getProperty("user.dir");
-    }
-    else
-    {
-      return directoryServer.configHandler.getServerRoot();
-    }
+    return directoryServer.environmentConfig.getServerRootAsString();
   }
 
   /**
@@ -2863,28 +2862,7 @@
    */
   public static String getInstanceRoot()
   {
-    if (directoryServer.configHandler == null)
-    {
-      File serverRoot = directoryServer.environmentConfig.getServerRoot();
-      if (serverRoot != null)
-      {
-        File instanceRoot =
-          DirectoryEnvironmentConfig.getInstanceRootFromServerRoot(
-              serverRoot);
-        if (instanceRoot != null)
-        {
-          return instanceRoot.getAbsolutePath();
-        }
-      }
-
-      // We don't know where the server root is, so we'll have to assume it's
-      // the current working directory.
-      return System.getProperty("user.dir");
-    }
-    else
-    {
-      return directoryServer.configHandler.getInstanceRoot();
-    }
+    return directoryServer.environmentConfig.getInstanceRootAsString();
   }
 
   /**
@@ -9015,6 +8993,23 @@
     }
     serverLocked = true;
 
+    // Create an environment configuration for the server and populate a number
+    // of appropriate properties.
+    DirectoryEnvironmentConfig environmentConfig = new DirectoryEnvironmentConfig();
+    try
+    {
+      environmentConfig.setProperty(PROPERTY_CONFIG_CLASS, configClass.getValue());
+      environmentConfig.setProperty(PROPERTY_CONFIG_FILE, configFile.getValue());
+      environmentConfig.setProperty(PROPERTY_USE_LAST_KNOWN_GOOD_CONFIG,
+          String.valueOf(useLastKnownGoodConfig.isPresent()));
+    }
+    catch (Exception e)
+    {
+      // This shouldn't happen.  For the methods we are using, the exception is
+      // just a guard against making changes with the server running.
+      System.err.println("WARNING:  Unable to set environment properties in environment config : "
+          + stackTraceToSingleLineString(e));
+    }
 
     // Configure the JVM to delete the PID file on exit, if it exists.
     boolean pidFileMarkedForDeletion      = false;
@@ -9023,9 +9018,7 @@
     {
       String pidFilePath;
       String startingFilePath;
-      String serverRoot = System.getenv(ENV_VAR_INSTALL_ROOT);
-      File instanceRoot = DirectoryEnvironmentConfig
-          .getInstanceRootFromServerRoot(new File(serverRoot));
+      File instanceRoot = environmentConfig.getInstanceRoot();
       if (instanceRoot == null)
       {
         pidFilePath      = "logs/server.pid";
@@ -9065,23 +9058,15 @@
       // We need to figure out where to put the file.  See if the server root
       // is available as an environment variable and if so then use it.
       // Otherwise, try to figure it out from the location of the config file.
-      String serverRoot = System.getenv(ENV_VAR_INSTALL_ROOT);
-      if (serverRoot == null)
-      {
-        serverRoot = new File(configFile.getValue()).getParentFile().
-                              getParentFile().getAbsolutePath();
-      }
-
+      File serverRoot = environmentConfig.getServerRoot();
       if (serverRoot == null)
       {
         System.err.println("WARNING:  Unable to determine server root in " +
-                           "order to redirect standard output and standard " +
-                           "error.");
+            "order to redirect standard output and standard error.");
       }
       else
       {
-        File instanceRoot = DirectoryEnvironmentConfig
-            .getInstanceRootFromServerRoot(new File(serverRoot));
+        File instanceRoot = environmentConfig.getInstanceRoot();
         File logDir = new File(instanceRoot.getAbsolutePath() + File.separator
             + "logs");
         if (logDir.exists())
@@ -9141,26 +9126,6 @@
     DebugLogPublisher startupDebugLogPublisher =
         DebugLogger.getInstance().addPublisherIfRequired(new TextWriter.STDOUT());
 
-    // Create an environment configuration for the server and populate a number
-    // of appropriate properties.
-    DirectoryEnvironmentConfig environmentConfig =
-         new DirectoryEnvironmentConfig();
-    try
-    {
-      environmentConfig.setProperty(PROPERTY_CONFIG_CLASS,
-                                    configClass.getValue());
-      environmentConfig.setProperty(PROPERTY_CONFIG_FILE,
-                                    configFile.getValue());
-      environmentConfig.setProperty(PROPERTY_USE_LAST_KNOWN_GOOD_CONFIG,
-           String.valueOf(useLastKnownGoodConfig.isPresent()));
-    }
-    catch (Exception e)
-    {
-      // This shouldn't happen.  For the methods we are using, the exception is
-      // just a guard against making changes with the server running.
-    }
-
-
     // Bootstrap and start the Directory Server.
     DirectoryServer theDirectoryServer = DirectoryServer.getInstance();
     try
@@ -9168,7 +9133,7 @@
       theDirectoryServer.setEnvironmentConfig(environmentConfig);
       theDirectoryServer.bootstrapServer();
       theDirectoryServer.initializeConfiguration(configClass.getValue(),
-                                              configFile.getValue());
+          configFile.getValue());
     }
     catch (InitializationException ie)
     {
diff --git a/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/core/ServerContext.java b/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/core/ServerContext.java
index 11d62bf..bfb0fb3 100644
--- a/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/core/ServerContext.java
+++ b/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/core/ServerContext.java
@@ -25,6 +25,9 @@
  */
 package org.opends.server.core;
 
+import org.opends.server.admin.server.ServerManagementContext;
+import org.opends.server.schema.SchemaUpdater;
+import org.opends.server.types.DirectoryEnvironmentConfig;
 import org.opends.server.types.Schema;
 
 /**
@@ -54,4 +57,19 @@
    */
   public Schema getSchema();
 
+  /**
+   * Returns the environment of the server.
+   *
+   * @return the environment
+   */
+  public DirectoryEnvironmentConfig getEnvironment();
+
+  /**
+   * Returns the server management context, which gives
+   * an entry point on configuration objects.
+   *
+   * @return the server management context
+   */
+  public ServerManagementContext getServerManagementContext();
+
 }
diff --git a/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/extensions/ConfigFileHandler.java b/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/extensions/ConfigFileHandler.java
index fa175df..e548f1c 100644
--- a/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/extensions/ConfigFileHandler.java
+++ b/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/extensions/ConfigFileHandler.java
@@ -175,8 +175,6 @@
   /** The instance root directory for the Directory Server. */
   private String instanceRoot;
 
-
-
   /**
    * Creates a new instance of this config file handler.  No initialization
    * should be performed here, as all of that work should be done in the
@@ -200,8 +198,7 @@
     // configuration.  If so, then only do so if such a file exists.  If it
     // doesn't exist, then fall back on the active configuration file.
     this.configFile = configFile;
-    DirectoryEnvironmentConfig envConfig =
-         DirectoryServer.getEnvironmentConfig();
+    DirectoryEnvironmentConfig envConfig = DirectoryServer.getEnvironmentConfig();
     useLastKnownGoodConfig = envConfig.useLastKnownGoodConfiguration();
     File f;
     if (useLastKnownGoodConfig)
@@ -497,107 +494,22 @@
     }
 
 
-    // Determine the appropriate server root.  If it's not defined in the
-    // environment config, then try to figure it out from the location of the
-    // configuration file.
+    // Get the server root
     File rootFile = envConfig.getServerRoot();
     if (rootFile == null)
     {
-      try
-      {
-        File configDirFile = f.getParentFile();
-        if (configDirFile != null &&
-            CONFIG_DIR_NAME.equals(configDirFile.getName()))
-        {
-          /*
-           * Do a best effort to avoid having a relative representation (for
-           * instance to avoid having ../../../).
-           */
-          try
-          {
-            serverRoot = configDirFile.getParentFile().getCanonicalPath();
-          }
-          catch (IOException ioe)
-          {
-            // Best effort
-            serverRoot = configDirFile.getParentFile().getAbsolutePath();
-          }
-        }
-
-        if (serverRoot == null)
-        {
-          LocalizableMessage message = ERR_CONFIG_CANNOT_DETERMINE_SERVER_ROOT.get(
-              ENV_VAR_INSTALL_ROOT);
-          throw new InitializationException(message);
-        }
-      }
-      catch (InitializationException ie)
-      {
-        logger.traceException(ie);
-
-        throw ie;
-      }
-      catch (Exception e)
-      {
-        logger.traceException(e);
-
-        LocalizableMessage message =
-            ERR_CONFIG_CANNOT_DETERMINE_SERVER_ROOT.get(ENV_VAR_INSTALL_ROOT);
-        throw new InitializationException(message);
-      }
+      throw new InitializationException(ERR_CONFIG_CANNOT_DETERMINE_SERVER_ROOT.get(
+          ENV_VAR_INSTALL_ROOT));
     }
-    else
-    {
-      /*
-       * Do a best effort to avoid having a relative representation (for
-       * instance to avoid having ../../../).
-       */
-      try
-      {
-        serverRoot = rootFile.getCanonicalPath();
-      }
-      catch (IOException ioe)
-      {
-        // Best effort
-        serverRoot = rootFile.getAbsolutePath();
-      }
-    }
+    serverRoot = rootFile.getAbsolutePath();
 
-    // Determine the appropriate server root.  If it's not defined in the
-    // environment config, then try to figure it out from the location of the
-    // configuration file.
-    File instanceFile =
-        DirectoryEnvironmentConfig.getInstanceRootFromServerRoot(new File(
-          serverRoot));
-    if (instanceFile == null)
-    {
-      LocalizableMessage message =
-        ERR_CONFIG_CANNOT_DETERMINE_SERVER_ROOT.get(ENV_VAR_INSTALL_ROOT);
-        throw new InitializationException(message);
-    }
-    else
-    {
-      /*
-       * Do a best effort to avoid having a relative representation (for
-       * instance to avoid having ../../../).
-       */
-      try
-      {
-        instanceRoot = instanceFile.getCanonicalPath();
-      }
-      catch (IOException ioe)
-      {
-        // Best effort
-        instanceRoot = instanceFile.getAbsolutePath();
-      }
-    }
-
-
+    // Get the server instance root
+    File instanceFile = envConfig.getInstanceRoot();
+    instanceRoot = instanceFile.getAbsolutePath();
 
     // Register with the Directory Server as an alert generator.
     DirectoryServer.registerAlertGenerator(this);
 
-
     // Register with the Directory Server as the backend that should be used
     // when accessing the configuration.
     baseDNs = new DN[] { configRootEntry.getDN() };
diff --git a/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/types/DirectoryEnvironmentConfig.java b/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/types/DirectoryEnvironmentConfig.java
index 131918a..b4844a6 100644
--- a/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/types/DirectoryEnvironmentConfig.java
+++ b/opendj-sdk/opendj3-server-dev/src/server/org/opends/server/types/DirectoryEnvironmentConfig.java
@@ -22,25 +22,28 @@
  *
  *
  *      Copyright 2008-2010 Sun Microsystems, Inc.
- *      Portions Copyright 2013 ForgeRock AS.
+ *      Portions Copyright 2013-2014 ForgeRock AS.
  */
 package org.opends.server.types;
 
+import static org.opends.messages.ConfigMessages.*;
+import static org.opends.messages.CoreMessages.*;
+import static org.opends.server.config.ConfigConstants.*;
+import static org.opends.server.util.ServerConstants.*;
+
 import java.io.File;
+import java.io.IOException;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Properties;
 
+import org.forgerock.i18n.slf4j.LocalizedLogger;
 import org.opends.quicksetup.util.Utils;
 import org.opends.server.api.ConfigHandler;
 import org.opends.server.core.DirectoryServer;
 import org.opends.server.extensions.ConfigFileHandler;
 
-import static org.opends.messages.CoreMessages.*;
-import static org.opends.server.config.ConfigConstants.*;
-import static org.opends.server.util.ServerConstants.*;
-
 /**
  * This class provides a set of properties that may control various
  * aspects of the server environment.  Note that these properties may
@@ -58,7 +61,7 @@
   /** The set of properties for the environment config. */
   private final Map<String, String> configProperties;
 
-
+  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
   /**
    * Creates a new directory environment configuration initialized
@@ -84,7 +87,7 @@
     configProperties = new HashMap<String,String>();
     if (properties != null)
     {
-      Enumeration propertyNames = properties.propertyNames();
+      Enumeration<?> propertyNames = properties.propertyNames();
       while (propertyNames.hasMoreElements())
       {
         Object o = propertyNames.nextElement();
@@ -176,34 +179,137 @@
     }
   }
 
-
-
   /**
    * Retrieves the directory that should be considered the server
-   * root.  The determination will first be based on the properties
-   * defined in this config object.  If no value is found there, then
+   * root.
+   * <p>
+   * The determination will first be based on the properties
+   * defined in this object.  If no value is found there, then
    * the JVM system properties will be checked, followed by an
-   * environment variable.
+   * environment variable. If there is still no value, then the
+   * location of the config file is used to determine the root.
    *
    * @return  The directory that should be considered the server root,
-   *          or {@code null} if it is not defined.
+   *          or {@code null} if it can't be determined.
    */
   public File getServerRoot()
   {
-    String serverRootPath = getProperty(PROPERTY_SERVER_ROOT);
-    if (serverRootPath == null)
+    File rootFile = null;
+    try
     {
-      serverRootPath = System.getenv(ENV_VAR_INSTALL_ROOT);
+      String serverRootPath = getProperty(PROPERTY_SERVER_ROOT);
+      if (serverRootPath == null)
+      {
+        serverRootPath = System.getenv(ENV_VAR_INSTALL_ROOT);
+      }
+      if (serverRootPath != null)
+      {
+        rootFile = new File(serverRootPath);
+        rootFile = forceNonRelativeFile(rootFile);
+      }
+      else
+      {
+        // try to figure out root
+        // from the location of the configuration file.
+        File configFile = getConfigFile();
+        File configDirFile = configFile.getParentFile();
+        if (configDirFile != null
+            && CONFIG_DIR_NAME.equals(configDirFile.getName()))
+        {
+          File parent = configDirFile.getParentFile();
+          rootFile = forceNonRelativeFile(parent);
+        }
+        else
+        {
+          logger.error(ERR_CONFIG_CANNOT_DETERMINE_SERVER_ROOT,
+              ENV_VAR_INSTALL_ROOT);
+        }
+      }
+    }
+    catch (Exception e)
+    {
+      logger.error(ERR_CONFIG_CANNOT_DETERMINE_SERVER_ROOT,
+          ENV_VAR_INSTALL_ROOT, e);
+    }
+    return rootFile;
+  }
+
+  /**
+   * Retrieves the path of the directory that should be considered the server
+   * root.
+   * <p>
+   * This method uses the same rules than {@code getServerRoot} method, but
+   * never returns {@code null}. If no directory can be found it returns as a
+   * last resort the value of "user.dir" system property.
+   *
+   * @return the path of the directory that should be considered the server
+   *         root.
+   */
+  public String getServerRootAsString() {
+    File serverRoot = getServerRoot();
+    if (serverRoot != null)
+    {
+      return serverRoot.getAbsolutePath();
+    }
+    // We don't know where the server root is, so we'll have to assume it's
+    // the current working directory.
+    return System.getProperty("user.dir");
+  }
+
+  /**
+   * Retrieves the directory that should be considered the instance
+   * root.
+   *
+   * @return  The directory that should be considered the instance
+   *          root or {@code null} if it can't be determined.
+   */
+  public File getInstanceRoot() {
+    File serverRoot = getServerRoot();
+    if (serverRoot != null)
+    {
+      File instanceRoot = new File(Utils.getInstancePathFromInstallPath(getServerRoot().getAbsolutePath()));
+      return forceNonRelativeFile(instanceRoot);
+    }
+    return null;
+  }
+
+  /**
+   * Retrieves the path of the directory that should be considered the instance
+   * root.
+   * <p>
+   * This method uses the same rules than {@code getInstanceRoot} method, but
+   * never returns {@code null}. If no directory can be found it returns as a
+   * last resort the value of "user.dir" system property.
+   *
+   * @return the path of the directory that should be considered the instance
+   *         root.
+   */
+  public String getInstanceRootAsString()
+  {
+    File instanceRoot = getInstanceRoot();
+    if (instanceRoot != null)
+    {
+      return instanceRoot.getAbsolutePath();
     }
 
-    if (serverRootPath == null)
+    // We don't know where the instance root is, so we'll have to assume it's
+    // the current working directory.
+    return System.getProperty("user.dir");
+  }
+
+  private File forceNonRelativeFile(File file) {
+    // Do a best effort to avoid having a relative representation
+    // (for instance to avoid having ../../../).
+    String path = null;
+    try
     {
-      return null;
+      path = file.getCanonicalPath();
     }
-    else
+    catch (IOException ioe)
     {
-      return new File(serverRootPath);
+      path = file.getAbsolutePath();
     }
+    return new File(path);
   }
 
   /**
@@ -220,8 +326,7 @@
    */
   public static File getInstanceRootFromServerRoot(File serverRoot)
   {
-    return new File(Utils.getInstancePathFromInstallPath(
-                                serverRoot.getAbsolutePath()));
+    return new File(Utils.getInstancePathFromInstallPath(serverRoot.getAbsolutePath()));
   }
 
 

--
Gitblit v1.10.0