From 8aa869c283305c3011c1e92f002574426a6d3900 Mon Sep 17 00:00:00 2001
From: Jean-Noël Rouvignac <jean-noel.rouvignac@forgerock.com>
Date: Fri, 19 Aug 2016 13:36:19 +0000
Subject: [PATCH] uninstaller: code cleanup

---
 opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/Uninstaller.java        |  330 ++++++++++++++++--------------------
 opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallCliHelper.java |  203 ++++++++++------------
 2 files changed, 238 insertions(+), 295 deletions(-)

diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallCliHelper.java b/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallCliHelper.java
index e4898e1..41d5c18 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallCliHelper.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/UninstallCliHelper.java
@@ -124,21 +124,11 @@
     UninstallUserData userData = new UninstallUserData();
     try
     {
-      boolean isInteractive;
-      boolean isQuiet;
-      boolean isVerbose;
-      boolean isCanceled = false;
-
       /* Step 1: analyze the arguments. */
+      boolean isInteractive = args.isInteractive();
 
-      isInteractive = args.isInteractive();
-
-      isQuiet = args.isQuiet();
-
-      isVerbose = args.isVerbose();
-
-      userData.setQuiet(isQuiet);
-      userData.setVerbose(isVerbose);
+      userData.setQuiet(args.isQuiet());
+      userData.setVerbose(args.isVerbose());
       userData.setForceOnError(args.isForceOnError());
       userData.setTrustManager(args.getTrustManager());
 
@@ -159,8 +149,7 @@
        */
       Set<String> outsideDbs;
       Set<String> outsideLogs;
-      Configuration config =
-        Installation.getLocal().getCurrentConfiguration();
+      Configuration config = Installation.getLocal().getCurrentConfiguration();
       try {
         outsideDbs = config.getOutsideDbs();
       } catch (IOException ioe) {
@@ -184,6 +173,7 @@
         args.removeLogFiles() ||
         args.removeServerLibraries();
 
+      boolean isCanceled = false;
       if (somethingSpecifiedToDelete)
       {
         userData.setRemoveBackups(args.removeAll() || args.removeBackupFiles());
@@ -291,16 +281,13 @@
 
   /**
    * Commodity method used to ask the user to confirm the deletion of certain
-   * parts of the server.  It updates the provided UserData object
-   * accordingly.  Returns <CODE>true</CODE> if the user cancels and <CODE>
-   * false</CODE> otherwise.
+   * parts of the server.  It updates the provided UserData object accordingly.
    * @param userData the UserData object to be updated.
    * @param outsideDbs the set of relative paths of databases located outside
    * the installation path of the server.
    * @param outsideLogs the set of relative paths of log files located outside
    * the installation path of the server.
-   * @return <CODE>true</CODE> if the user cancels and <CODE>false</CODE>
-   * otherwise.
+   * @return {@code true} if the user cancels, {@code false} otherwise.
    */
   private boolean askWhatToDelete(UninstallUserData userData,
       Set<String> outsideDbs, Set<String> outsideLogs) throws UserDataException
@@ -485,14 +472,14 @@
   }
 
   /**
-   * Commodity method used to ask the user (when necessary) if the server must
-   * be stopped or not. It also prompts (if required) for authentication.
+   * Asks the user (when necessary) if the server must be stopped or not.
+   * It also prompts (if required) for authentication.
    *
    * @param userData
    *          the UserData object to be updated with the authentication of the
    *          user.
-   * @return <CODE>true</CODE> if the user wants to continue with uninstall and
-   *         <CODE>false</CODE> otherwise.
+   * @return {@code true} if the user wants to continue with uninstall,
+   *         {@code false} otherwise.
    * @throws UserDataException
    *           if there is a problem with the data provided by the user (in the
    *           particular case where we are on non-interactive uninstall and
@@ -501,8 +488,7 @@
    *           If there is an error processing data in non-interactive mode and
    *           an error must be thrown (not in force on error mode).
    */
-  private boolean checkServerState(UninstallUserData userData)
-  throws UserDataException, ClientException
+  private boolean checkServerState(UninstallUserData userData) throws UserDataException, ClientException
   {
     boolean cancelled = false;
     boolean interactive = parser.isInteractive();
@@ -521,8 +507,7 @@
     logger.info(LocalizableMessage.raw("interactive: "+interactive));
     logger.info(LocalizableMessage.raw("forceOnError: "+forceOnError));
     logger.info(LocalizableMessage.raw("conf.isADS(): "+conf.isADS()));
-    logger.info(LocalizableMessage.raw("conf.isReplicationServer(): "+
-        conf.isReplicationServer()));
+    logger.info(LocalizableMessage.raw("conf.isReplicationServer(): "+conf.isReplicationServer()));
     logger.info(LocalizableMessage.raw("conf.isServerRunning(): "+conf.isServerRunning()));
     if (conf.isADS() && conf.isReplicationServer())
     {
@@ -698,8 +683,8 @@
 
   /**
    *  Ask for confirmation to stop server.
-   *  @return <CODE>true</CODE> if the user wants to continue and stop the
-   *  server.  <CODE>false</CODE> otherwise.
+   *  @return {@code true} if the user wants to continue and stop the server,
+   *          {@code false} otherwise.
    *  @throws ClientException if the user reached the confirmation limit.
    */
   private boolean confirmToStopServer() throws ClientException
@@ -709,32 +694,30 @@
 
   /**
    *  Ask for confirmation to delete files.
-   *  @return <CODE>true</CODE> if the user wants to continue and delete the
-   *  files.  <CODE>false</CODE> otherwise.
+   *  @return {@code true} if the user wants to continue and delete the files,
+   *          {@code false} otherwise.
    *  @throws ClientException if the user reached the confirmation limit.
    */
   private boolean confirmDeleteFiles() throws ClientException
   {
-    return askConfirmation(INFO_CLI_UNINSTALL_CONFIRM_DELETE_FILES.get(), true,
-        logger);
+    return askConfirmation(INFO_CLI_UNINSTALL_CONFIRM_DELETE_FILES.get(), true, logger);
   }
 
   /**
    *  Ask for confirmation to update configuration on remote servers.
-   *  @return <CODE>true</CODE> if the user wants to continue and stop the
-   *  server.  <CODE>false</CODE> otherwise.
+   *  @return {@code true} if the user wants to continue and stop the server.
+   *          {@code false} otherwise.
    *  @throws ClientException if the user reached the confirmation limit.
    */
   private boolean confirmToUpdateRemote() throws ClientException
   {
-    return askConfirmation(INFO_CLI_UNINSTALL_CONFIRM_UPDATE_REMOTE.get(), true,
-        logger);
+    return askConfirmation(INFO_CLI_UNINSTALL_CONFIRM_UPDATE_REMOTE.get(), true, logger);
   }
 
   /**
    *  Ask for confirmation to update configuration on remote servers.
-   *  @return <CODE>true</CODE> if the user wants to continue and stop the
-   *  server.  <CODE>false</CODE> otherwise.
+   *  @return {@code true} if the user wants to continue and stop the server,
+   *          {@code false} otherwise.
    *  @throws ClientException if the user reached the confirmation limit.
    */
   private boolean confirmToUpdateRemoteAndStart() throws ClientException
@@ -745,8 +728,8 @@
 
   /**
    *  Ask for confirmation to provide again authentication.
-   *  @return <CODE>true</CODE> if the user wants to provide authentication
-   *  again.  <CODE>false</CODE> otherwise.
+   *  @return {@code true} if the user wants to provide authentication again,
+   *          {@code false} otherwise.
    *  @throws ClientException if the user reached the confirmation limit.
    */
   private boolean promptToProvideAuthenticationAgain() throws ClientException
@@ -760,8 +743,8 @@
    * data is provided and validated, we assume that the user wants to update the
    * remote servers.
    *
-   * @return <CODE>true</CODE> if the user wants to continue and update the
-   *         remote servers. <CODE>false</CODE> otherwise.
+   * @return {@code true} if the user wants to continue and update the
+   *         remote servers, {@code false} otherwise.
    * @throws UserDataException
    *           if there is a problem with the information provided by the user.
    * @throws ClientException
@@ -909,17 +892,15 @@
 
   private String askForReferencedHostName(String defaultHostName)
   {
-    String s = defaultHostName;
     try
     {
-      s = readInput(INFO_UNINSTALL_CLI_REFERENCED_HOSTNAME_PROMPT.get(),
-          defaultHostName);
+      return readInput(INFO_UNINSTALL_CLI_REFERENCED_HOSTNAME_PROMPT.get(), defaultHostName);
     }
     catch (ClientException ce)
     {
       logger.warn(LocalizableMessage.raw("Error reading input: %s", ce), ce);
+      return defaultHostName;
     }
-    return s;
   }
 
   private boolean startServer(boolean suppressOutput)
@@ -994,8 +975,7 @@
         // no-op
       }
     };
-    application.setProgressMessageFormatter(
-        new PlainTextProgressMessageFormatter());
+    application.setProgressMessageFormatter(new PlainTextProgressMessageFormatter());
     if (!suppressOutput)
     {
       application.addProgressUpdateListener(
@@ -1007,8 +987,7 @@
             }
           });
     }
-    ServerController controller = new ServerController(application,
-        Installation.getLocal());
+    ServerController controller = new ServerController(application, Installation.getLocal());
     try
     {
       if (suppressOutput)
@@ -1043,15 +1022,12 @@
 
   /**
    * Updates the contents of the UninstallUserData while trying to connect to
-   * the remote servers. It returns <CODE>true</CODE> if we could connect to the
-   * remote servers and all the presented certificates were accepted and
-   * <CODE>false</CODE> otherwise. continue if
+   * the remote servers.
    *
    * @param userData
    *          the user data to be updated.
-   * @return <CODE>true</CODE> if we could connect to the remote servers and all
-   *         the presented certificates were accepted and <CODE>false</CODE>
-   *         otherwise.
+   * @return {@code true} if we could connect to the remote servers and all the
+   *         presented certificates were accepted, {@code false} otherwise.
    * @throws UserDataException
    *           if were are not in interactive mode and not in force on error
    *           mode and the operation must be stopped.
@@ -1076,8 +1052,8 @@
     try
     {
       info.setTrustManager(userData.getTrustManager());
-      info.setConnectTimeout(getConnectTimeout());
       info.setConnectionPolicy(ConnectionProtocolPolicy.USE_ADMIN);
+      info.setConnectTimeout(getConnectTimeout());
       conn = new ConnectionWrapper(
           info.getAdminConnectorHostPort(), connectionType,
           getAdministratorDN(userData.getAdminUID()), userData.getAdminPwd(),
@@ -1179,8 +1155,8 @@
    * Method that interacts with the user depending on what errors where
    * encountered in the TopologyCache object.  This method assumes that the
    * TopologyCache has been reloaded.
-   * Returns <CODE>true</CODE> if the user accepts all the problems encountered
-   * and <CODE>false</CODE> otherwise.
+   * @return {@code true} if the user accepts all the problems encountered,
+   *         {@code false} otherwise.
    * @param userData the user data.
    * @throws UserDataException if there is an error with the information
    * provided by the user when we are in non-interactive mode.
@@ -1191,13 +1167,16 @@
   private boolean handleTopologyCache(TopologyCache cache,
       UninstallUserData userData) throws UserDataException, ClientException
   {
-    boolean returnValue;
-    boolean stopProcessing = false;
-    boolean reloadTopologyCache = false;
+    boolean result = handleTopologyCache0(cache, userData);
+    logger.info(LocalizableMessage.raw("Return value: "+result));
+    return result;
+  }
 
+  private boolean handleTopologyCache0(TopologyCache cache,
+      UninstallUserData userData) throws UserDataException, ClientException
+  {
     logger.info(LocalizableMessage.raw("Handle topology cache."));
 
-    Set<TopologyCacheException> exceptions = new HashSet<>();
     /* Analyze if we had any exception while loading servers.  For the moment
      * only throw the exception found if the user did not provide the
      * Administrator DN and this caused a problem authenticating in one server
@@ -1205,6 +1184,7 @@
      */
     Set<ServerDescriptor> servers = cache.getServers();
     userData.setRemoteServers(servers);
+    Set<TopologyCacheException> exceptions = new HashSet<>();
     for (ServerDescriptor server : servers)
     {
       TopologyCacheException e = server.getLastException();
@@ -1213,8 +1193,11 @@
         exceptions.add(e);
       }
     }
-    Set<LocalizableMessage> exceptionMsgs = new LinkedHashSet<>();
+
     /* Check the exceptions and see if we throw them or not. */
+    Set<LocalizableMessage> exceptionMsgs = new LinkedHashSet<>();
+    boolean stopProcessing = false;
+    boolean reloadTopologyCache = false;
     for (TopologyCacheException e : exceptions)
     {
       logger.info(LocalizableMessage.raw("Analyzing exception: "+e, e));
@@ -1259,6 +1242,7 @@
         exceptionMsgs.add(Utils.getMessage(e));
       }
     }
+
     if (isInteractive())
     {
       if (!stopProcessing && !exceptionMsgs.isEmpty())
@@ -1266,10 +1250,9 @@
         println();
         try
         {
-          returnValue = askConfirmation(
-            ERR_UNINSTALL_READING_REGISTERED_SERVERS_CONFIRM_UPDATE_REMOTE.get(
-                Utils.getMessageFromCollection(exceptionMsgs,
-                  Constants.LINE_SEPARATOR)), true, logger);
+          LocalizableMessage errorMsg = Utils.getMessageFromCollection(exceptionMsgs, Constants.LINE_SEPARATOR);
+          return askConfirmation(
+              ERR_UNINSTALL_READING_REGISTERED_SERVERS_CONFIRM_UPDATE_REMOTE.get(errorMsg), true, logger);
         }
         catch (ClientException ce)
         {
@@ -1278,45 +1261,40 @@
       }
       else if (reloadTopologyCache)
       {
-       returnValue = updateUserUninstallDataWithRemoteServers(userData);
+        return updateUserUninstallDataWithRemoteServers(userData);
       }
       else
       {
-        returnValue = !stopProcessing;
+        return !stopProcessing;
       }
     }
     else
     {
       logger.info(LocalizableMessage.raw("exceptionMsgs: "+exceptionMsgs));
-      if (!exceptionMsgs.isEmpty())
+      if (exceptionMsgs.isEmpty())
       {
-        if (parser.isForceOnError())
-        {
-          LocalizableMessage msg = Utils.getMessageFromCollection(exceptionMsgs,
-              Constants.LINE_SEPARATOR);
-          println();
-          printErrorMessage(msg);
-          returnValue = false;
-        }
-        else
-        {
-          LocalizableMessage msg =
-            ERR_UNINSTALL_ERROR_UPDATING_REMOTE_NO_FORCE.get(
-              "--" + parser.getSecureArgsList().getAdminUidArg().getLongIdentifier(),
-              "--" + OPTION_LONG_BINDPWD,
-              "--" + OPTION_LONG_BINDPWD_FILE,
-              "--" + parser.forceOnErrorArg.getLongIdentifier(),
-              Utils.getMessageFromCollection(exceptionMsgs, Constants.LINE_SEPARATOR));
-          throw new ClientException(ReturnCode.APPLICATION_ERROR, msg);
-        }
+        return true;
+      }
+
+      LocalizableMessage errorMsg = Utils.getMessageFromCollection(exceptionMsgs, Constants.LINE_SEPARATOR);
+      if (parser.isForceOnError())
+      {
+        println();
+        printErrorMessage(errorMsg);
+        return false;
       }
       else
       {
-        returnValue = true;
+        LocalizableMessage msg =
+          ERR_UNINSTALL_ERROR_UPDATING_REMOTE_NO_FORCE.get(
+            "--" + parser.getSecureArgsList().getAdminUidArg().getLongIdentifier(),
+            "--" + OPTION_LONG_BINDPWD,
+            "--" + OPTION_LONG_BINDPWD_FILE,
+            "--" + parser.forceOnErrorArg.getLongIdentifier(),
+                errorMsg);
+        throw new ClientException(ReturnCode.APPLICATION_ERROR, msg);
       }
     }
-    logger.info(LocalizableMessage.raw("Return value: "+returnValue));
-    return returnValue;
   }
 
   @Override
@@ -1356,25 +1334,25 @@
    * @param ci the LDAPConnectionConsoleInteraction object to be used to update
    * the user data object.
    */
-   private void updateTrustManager(UninstallUserData userData,
-       LDAPConnectionConsoleInteraction ci)
+  private void updateTrustManager(UninstallUserData userData, LDAPConnectionConsoleInteraction ci)
    {
-     ApplicationTrustManager trust = null;
-     TrustManager t = ci.getTrustManager();
-     if (t != null)
-     {
-       if (t instanceof ApplicationTrustManager)
-       {
-         trust = (ApplicationTrustManager)t;
-       }
-       else
-       {
-         trust = new ApplicationTrustManager(ci.getKeyStore());
-       }
-     }
-     userData.setTrustManager(trust);
+    userData.setTrustManager(getTrustManager(ci));
    }
 
+  private ApplicationTrustManager getTrustManager(LDAPConnectionConsoleInteraction ci)
+  {
+    TrustManager t = ci.getTrustManager();
+    if (t instanceof ApplicationTrustManager)
+    {
+      return (ApplicationTrustManager) t;
+    }
+    else if (t != null)
+    {
+      return new ApplicationTrustManager(ci.getKeyStore());
+    }
+    return null;
+  }
+
    /** Forces the initialization of the trust manager in the LDAPConnectionInteraction object. */
    private void forceTrustManagerInitialization()
    {
@@ -1412,8 +1390,7 @@
      }
      catch (ArgumentException ae)
      {
-       throw new IllegalStateException("Argument parser is not parsed: "+ae,
-           ae);
+       throw new IllegalStateException("Argument parser is not parsed: " + ae, ae);
      }
    }
 }
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/Uninstaller.java b/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/Uninstaller.java
index cc648ec..c6b545c 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/Uninstaller.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/Uninstaller.java
@@ -172,28 +172,28 @@
 
   @Override
   public WizardStep getNextWizardStep(WizardStep step) {
-    Step nextStep = null;
-    if (step != null && step.equals(Step.CONFIRM_UNINSTALL)) {
-      nextStep = Step.PROGRESS;
+    if (Step.CONFIRM_UNINSTALL.equals(step))
+    {
+      return Step.PROGRESS;
     }
     else if (Step.PROGRESS.equals(step))
     {
-      nextStep = Step.FINISHED;
+      return Step.FINISHED;
     }
-    return nextStep;
+    return null;
   }
 
   @Override
   public WizardStep getPreviousWizardStep(WizardStep step) {
-    Step prevStep = null;
-    if (step != null && step.equals(Step.PROGRESS)) {
-      prevStep = Step.CONFIRM_UNINSTALL;
+    if (Step.PROGRESS.equals(step))
+    {
+      return Step.CONFIRM_UNINSTALL;
     }
     else if (Step.FINISHED.equals(step))
     {
-      prevStep = Step.PROGRESS;
+      return Step.PROGRESS;
     }
-    return prevStep;
+    return null;
   }
 
   @Override
@@ -396,22 +396,20 @@
         }
 
         @Override
-        public void backgroundTaskCompleted(UninstallData returnValue,
-                                            Throwable throwable) {
+        public void backgroundTaskCompleted(UninstallData returnValue, Throwable t) {
           qs.getDialog().workerFinished();
-          if (throwable != null) {
-            if (throwable instanceof UserDataException)
+          if (t != null) {
+            LocalizableMessage msg;
+            if (t instanceof UserDataException)
             {
-              qs.displayError(LocalizableMessage.raw(throwable.getLocalizedMessage()),
-                    INFO_ERROR_TITLE.get());
+              msg = LocalizableMessage.raw(t.getLocalizedMessage());
             }
             else
             {
-              logger.warn(LocalizableMessage.raw("Error processing task: "+throwable,
-                  throwable));
-              qs.displayError(LocalizableMessage.raw(throwable.toString()),
-                      INFO_ERROR_TITLE.get());
+              logger.warn(LocalizableMessage.raw("Error processing task: " + t, t));
+              msg = LocalizableMessage.raw(t.toString());
             }
+            qs.displayError(msg, INFO_ERROR_TITLE.get());
           } else {
             conf = returnValue;
             if (conf.isADS() && conf.isReplicationServer())
@@ -540,10 +538,10 @@
 
   /**
    * Returns the ApplicationException that might occur during installation or
-   * <CODE>null</CODE> if no exception occurred.
+   * {@code null} if no exception occurred.
    *
    * @return the ApplicationException that might occur during installation or
-   *         <CODE>null</CODE> if no exception occurred.
+   *         {@code null} if no exception occurred.
    */
   @Override
   public ApplicationException getRunError() {
@@ -1087,13 +1085,11 @@
     }
 
     File[] rootFiles = null;
-
     if (installFiles == null)
     {
       rootFiles = new File(instancePath).listFiles();
     }
-    else
-    if (instanceFiles == null)
+    else if (instanceFiles == null)
     {
       rootFiles = installFiles;
     }
@@ -1113,24 +1109,7 @@
       for (File f : rootFiles) {
         if (filter.accept(f)) {
           Installation installation = getInstallation();
-          int relativeRatio;
-          if (equalsOrDescendant(f, installation.getLibrariesDirectory())) {
-            relativeRatio = 10;
-          } else if (equalsOrDescendant(f, installation.getBinariesDirectory())) {
-            relativeRatio = 5;
-          } else if (equalsOrDescendant(f, installation.getConfigurationDirectory())) {
-            relativeRatio = 5;
-          } else if (equalsOrDescendant(f, installation.getBackupDirectory())) {
-            relativeRatio = 20;
-          } else if (equalsOrDescendant(f, installation.getLdifDirectory())) {
-            relativeRatio = 20;
-          } else if (equalsOrDescendant(f, installation.getDatabasesDirectory())) {
-            relativeRatio = 50;
-          } else if (equalsOrDescendant(f, installation.getLogsDirectory())) {
-            relativeRatio = 30;
-          } else {
-            relativeRatio = 2;
-          }
+          int relativeRatio = getRelativeRatio(f, installation);
           cumulatedRatio.add(totalRatio);
           totalRatio += relativeRatio;
         } else {
@@ -1153,6 +1132,27 @@
     }
   }
 
+  private int getRelativeRatio(File f, Installation installation)
+  {
+    if (equalsOrDescendant(f, installation.getLibrariesDirectory())) {
+      return 10;
+    } else if (equalsOrDescendant(f, installation.getBinariesDirectory())) {
+      return 5;
+    } else if (equalsOrDescendant(f, installation.getConfigurationDirectory())) {
+      return 5;
+    } else if (equalsOrDescendant(f, installation.getBackupDirectory())) {
+      return 20;
+    } else if (equalsOrDescendant(f, installation.getLdifDirectory())) {
+      return 20;
+    } else if (equalsOrDescendant(f, installation.getDatabasesDirectory())) {
+      return 50;
+    } else if (equalsOrDescendant(f, installation.getLogsDirectory())) {
+      return 30;
+    } else {
+      return 2;
+    }
+  }
+
   /**
    * Deletes everything below the specified file.
    *
@@ -1184,13 +1184,7 @@
     }
     if (cfile.exists()) {
       if (cfile.isFile()) {
-        if (filter != null) {
-          if (filter.accept(cfile)) {
-            delete(cfile);
-          }
-        } else {
-          delete(cfile);
-        }
+        maybeDeleteFile(filter, cfile);
       } else {
         File[] children = cfile.listFiles();
         if (children != null) {
@@ -1199,13 +1193,7 @@
             deleteRecursively(element, filter);
           }
         }
-        if (filter != null) {
-          if (filter.accept(cfile)) {
-            delete(cfile);
-          }
-        } else {
-          delete(cfile);
-        }
+        maybeDeleteFile(filter, cfile);
       }
     } else {
       // Just tell that the file/directory does not exist.
@@ -1214,6 +1202,17 @@
     }
   }
 
+  private void maybeDeleteFile(FileFilter filter, File cfile) throws ApplicationException
+  {
+    if (filter != null) {
+      if (filter.accept(cfile)) {
+        delete(cfile);
+      }
+    } else {
+      delete(cfile);
+    }
+  }
+
   /**
    * Deletes the specified file.
    *
@@ -1221,24 +1220,22 @@
    * @throws ApplicationException if something goes wrong.
    */
   private void delete(File file) throws ApplicationException {
-    boolean isFile = file.isFile();
+    final boolean isFile = file.isFile();
+    final String absolutePath = file.getAbsolutePath();
 
     if (isVerbose())
     {
-      if (isFile) {
-        notifyListeners(getFormattedWithPoints(
-            INFO_PROGRESS_DELETING_FILE.get(file.getAbsolutePath())));
-      } else {
-        notifyListeners(getFormattedWithPoints(
-            INFO_PROGRESS_DELETING_DIRECTORY.get(file.getAbsolutePath())));
-      }
+      LocalizableMessage msg = isFile
+          ? INFO_PROGRESS_DELETING_FILE.get(absolutePath)
+          : INFO_PROGRESS_DELETING_DIRECTORY.get(absolutePath);
+      notifyListeners(getFormattedWithPoints(msg));
     }
 
-    boolean delete = false;
     /*
      * Sometimes the server keeps some locks on the files.
      * This is dependent on the OS so there is no much we can do here.
      */
+    boolean delete = false;
     int nTries = 5;
     for (int i = 0; i < nTries && !delete; i++) {
       delete = file.delete();
@@ -1252,12 +1249,9 @@
     }
 
     if (!delete) {
-      LocalizableMessage errMsg;
-      if (isFile) {
-        errMsg = INFO_ERROR_DELETING_FILE.get(file.getAbsolutePath());
-      } else {
-        errMsg = INFO_ERROR_DELETING_DIRECTORY.get(file.getAbsolutePath());
-      }
+      LocalizableMessage errMsg = isFile
+          ? INFO_ERROR_DELETING_FILE.get(absolutePath)
+          : INFO_ERROR_DELETING_DIRECTORY.get(absolutePath);
       throw new ApplicationException(
           ReturnCode.FILE_SYSTEM_ACCESS_ERROR,
           errMsg, null);
@@ -1370,18 +1364,14 @@
    * @throws ApplicationException if something goes wrong.
    */
   private void disableWindowsService() throws ApplicationException {
-    notifyListeners(getFormattedWithPoints(
-            INFO_PROGRESS_DISABLING_WINDOWS_SERVICE.get()));
+    notifyListeners(getFormattedWithPoints(INFO_PROGRESS_DISABLING_WINDOWS_SERVICE.get()));
     int code = disableService(System.out, System.err);
-
-    LocalizableMessage errorMessage = INFO_ERROR_DISABLING_WINDOWS_SERVICE.get(
-            getInstallationPath());
-
     switch (code) {
       case SERVICE_DISABLE_SUCCESS:
       case SERVICE_ALREADY_DISABLED:
         break;
       default:
+        LocalizableMessage errorMessage = INFO_ERROR_DISABLING_WINDOWS_SERVICE.get(getInstallationPath());
         throw new ApplicationException(ReturnCode.WINDOWS_SERVICE_ERROR, errorMessage, null);
     }
     notifyListeners(getLineBreak());
@@ -1394,8 +1384,7 @@
   /**
    * Tries to start the server and launches a progress dialog.  This method
    * assumes that is being called from the event thread.
-   * @return <CODE>true</CODE> if the server could be started and <CODE>
-   * false</CODE> otherwise.
+   * @return {@code true} if the server could be started, {@code false} otherwise.
    * @param frame the JFrame to be used as parent of the progress dialog.
    */
   private boolean startServer(JFrame frame)
@@ -1480,38 +1469,27 @@
         public TopologyCache processBackgroundTask() throws Throwable
         {
           logger.info(LocalizableMessage.raw("Loading Topology Cache in askForAuthentication"));
-          ADSContext adsContext = new ADSContext(conn);
-          TopologyCache cache = new TopologyCache(adsContext,
+          TopologyCache cache = new TopologyCache(new ADSContext(conn),
               getTrustManager(), getConnectTimeout());
           cache.getFilter().setSearchMonitoringInformation(false);
           cache.reloadTopology();
           return cache;
         }
         @Override
-        public void backgroundTaskCompleted(TopologyCache returnValue,
-            Throwable throwable) {
+        public void backgroundTaskCompleted(TopologyCache returnedCache, Throwable t) {
           qs.getDialog().workerFinished();
-          if (throwable != null)
+          if (t != null)
           {
-            logger.warn(LocalizableMessage.raw("Throwable: "+throwable, throwable));
-            if (throwable instanceof TopologyCacheException)
-            {
-              qs.displayError(
-                      getMessage((TopologyCacheException) throwable),
-                      INFO_ERROR_TITLE.get());
-            }
-            else
-            {
-              qs.displayError(
-                  getThrowableMsg(INFO_BUG_MSG.get(), throwable),
-                  INFO_ERROR_TITLE.get());
-            }
+            logger.warn(LocalizableMessage.raw("Throwable: "+t, t));
+            LocalizableMessage msg = t instanceof TopologyCacheException
+                ? getMessage((TopologyCacheException) t)
+                : getThrowableMsg(INFO_BUG_MSG.get(), t);
+            qs.displayError(msg, INFO_ERROR_TITLE.get());
             logger.info(LocalizableMessage.raw("Error was displayed"));
           }
           else
           {
-            TopologyCache cache = returnValue;
-            handleTopologyCache(qs, cache);
+            handleTopologyCache(qs, returnedCache);
           }
         }
       };
@@ -1651,8 +1629,7 @@
   private void handleCertificateException(final QuickSetup qs,
       UserDataCertificateException ce, final TopologyCache cache)
   {
-    CertificateDialog dlg =
-      new CertificateDialog(qs.getDialog().getFrame(), ce);
+    CertificateDialog dlg = new CertificateDialog(qs.getDialog().getFrame(), ce);
     dlg.pack();
     dlg.setVisible(true);
     if (dlg.getUserAnswer() != CertificateDialog.ReturnType.NOT_ACCEPTED)
@@ -1665,8 +1642,7 @@
       {
         logger.info(LocalizableMessage.raw("Accepting certificate presented by host "+host));
         getTrustManager().acceptCertificate(chain, authType, host);
-        BackgroundTask<TopologyCache> worker =
-          new BackgroundTask<TopologyCache>()
+        BackgroundTask<TopologyCache> worker = new BackgroundTask<TopologyCache>()
         {
           @Override
           public TopologyCache processBackgroundTask() throws Throwable
@@ -1677,22 +1653,14 @@
             return cache;
           }
           @Override
-          public void backgroundTaskCompleted(TopologyCache returnValue,
-              Throwable throwable) {
+          public void backgroundTaskCompleted(TopologyCache returnValue, Throwable t) {
             qs.getDialog().workerFinished();
-            if (throwable != null)
+            if (t != null)
             {
-              if (throwable instanceof TopologyCacheException)
-              {
-                qs.displayError(getMessage((TopologyCacheException)throwable),
-                    INFO_ERROR_TITLE.get());
-              }
-              else
-              {
-                qs.displayError(
-                    getThrowableMsg(INFO_BUG_MSG.get(), throwable),
-                    INFO_ERROR_TITLE.get());
-              }
+              LocalizableMessage msg = t instanceof TopologyCacheException
+                  ? getMessage((TopologyCacheException) t)
+                  : getThrowableMsg(INFO_BUG_MSG.get(), t);
+              qs.displayError(msg, INFO_ERROR_TITLE.get());
             }
             else
             {
@@ -1780,7 +1748,7 @@
    * This method updates the replication in the remote server represented by
    * a given ServerProperty object.
    * It also tries to delete the server registration entry from the remote ADS
-   * servers if the serverADSProperties object passed is not null.
+   * servers if the serverADSProperties object passed is not {@code null}.
    * @param server the ServerDescriptor object representing the server where
    * we want to remove references to the server that we are trying to uninstall.
    * @param serverADSProperties the Map with the ADS properties of the server
@@ -2018,85 +1986,83 @@
    * Tells whether this ServerDescriptor object represents the server that we
    * are trying to uninstall or not.
    * @param server the ServerDescriptor object to analyze.
-   * @return <CODE>true</CODE> if the ServerDescriptor object represents the
-   * server that we are trying to uninstall and <CODE>false</CODE> otherwise.
+   * @return {@code true} if the ServerDescriptor object represents the
+   * server that we are trying to uninstall, {@code false} otherwise.
    */
   private boolean isServerToUninstall(ServerDescriptor server)
   {
-    boolean isServerToUninstall = false;
-    String path = (String)server.getAdsProperties().get(
-        ADSContext.ServerProperty.INSTANCE_PATH);
-    if (path == null)
+    Boolean sameInstanceInstallPaths = isSameInstanceInstallPaths(server);
+    return sameInstanceInstallPaths != null
+        ? sameInstanceInstallPaths
+        : isSamePort(server) && isSameHostName(server);
+  }
+
+  private Boolean isSameInstanceInstallPaths(ServerDescriptor server)
+  {
+    final String path = (String) server.getAdsProperties().get(ADSContext.ServerProperty.INSTANCE_PATH);
+    return path != null
+        ? new File(path).equals(Installation.getLocal().getRootDirectory())
+        : null;
+  }
+
+  private boolean isSamePort(ServerDescriptor server)
+  {
+    try
     {
-      // Compare the port of the URL we used.
-      try
+      final UninstallUserData uData = getUninstallUserData();
+      final int port = uData.getLocalServerHostPort().getPort();
+      final boolean isSecure = uData.isLocalServerSecure();
+
+      final ServerDescriptor.ServerProperty property =
+          isSecure ? ServerDescriptor.ServerProperty.ADMIN_PORT : ServerDescriptor.ServerProperty.LDAP_PORT;
+      final List<?> ports = (List<?>) server.getServerProperties().get(property);
+      if (ports != null)
       {
-        UninstallUserData uData = getUninstallUserData();
-        HostPort usedHostPort = uData.getLocalServerHostPort();
-        boolean isSecure = uData.isLocalServerSecure();
-        int port = usedHostPort.getPort();
-        ServerDescriptor.ServerProperty property = isSecure
-            ? ServerDescriptor.ServerProperty.ADMIN_PORT
-            : ServerDescriptor.ServerProperty.LDAP_PORT;
-        ArrayList<?> ports = (ArrayList<?>) server.getServerProperties().get(property);
-        if (ports != null)
-        {
-          isServerToUninstall = ports.contains(port);
-        }
-        else
-        {
-          // This occurs if the instance could not be loaded.
-          ADSContext.ServerProperty adsProperty = isSecure
-              ? ADSContext.ServerProperty.ADMIN_PORT
-              : ADSContext.ServerProperty.LDAP_PORT;
-          String v = (String)server.getAdsProperties().get(adsProperty);
-          if (v != null)
-          {
-            isServerToUninstall = v.equals(String.valueOf(port));
-          }
-        }
+        return ports.contains(port);
       }
-      catch (Throwable t)
-      {
-        logger.warn(LocalizableMessage.raw("Failing checking the port: "+t, t));
-      }
+
+      // This occurs if the instance could not be loaded.
+      final ADSContext.ServerProperty adsProperty =
+          isSecure ? ADSContext.ServerProperty.ADMIN_PORT : ADSContext.ServerProperty.LDAP_PORT;
+      final String v = (String) server.getAdsProperties().get(adsProperty);
+      return v != null ? v.equals(String.valueOf(port)) : false;
     }
-    else
+    catch (Throwable t)
     {
-      File f = new File(path);
-      isServerToUninstall =
-        f.equals(Installation.getLocal().getRootDirectory());
+      logger.warn(LocalizableMessage.raw("Failing checking the port: " + t, t));
+      return false;
+    }
+  }
+
+  private boolean isSameHostName(ServerDescriptor server)
+  {
+    // TODO: the host name comparison made here does not necessarily work in
+    // all environments...
+    final String hostName = server.getHostName();
+    if (getUninstallUserData().getReferencedHostName().equals(hostName))
+    {
+      return true;
     }
 
-    if (isServerToUninstall)
+    try
     {
-      // TODO: the host name comparison made here does not necessarily work in
-      // all environments...
-      String hostName = server.getHostName();
-      boolean hostNameEquals =
-        getUninstallUserData().getReferencedHostName().equals(hostName);
-      try
+      final InetAddress localAddress = InetAddress.getLocalHost();
+      final InetAddress[] addresses = InetAddress.getAllByName(hostName);
+      for (InetAddress address : addresses)
       {
-        InetAddress localAddress = InetAddress.getLocalHost();
-        InetAddress[] addresses = InetAddress.getAllByName(hostName);
-        for (int i=0; i<addresses.length && !hostNameEquals; i++)
+        if (localAddress.equals(address))
         {
-          hostNameEquals = localAddress.equals(addresses[i]);
-        }
-        if (!hostNameEquals)
-        {
-          hostNameEquals =
-            localAddress.getHostName().equalsIgnoreCase(hostName) ||
-            localAddress.getCanonicalHostName().equalsIgnoreCase(hostName);
+          return true;
         }
       }
-      catch (Throwable t)
-      {
-        logger.warn(LocalizableMessage.raw("Failing checking host names: "+t, t));
-      }
-      isServerToUninstall = hostNameEquals;
+      return localAddress.getHostName().equalsIgnoreCase(hostName)
+          || localAddress.getCanonicalHostName().equalsIgnoreCase(hostName);
     }
-    return isServerToUninstall;
+    catch (Throwable t)
+    {
+      logger.warn(LocalizableMessage.raw("Failing checking host names: " + t, t));
+      return false;
+    }
   }
 
   /**

--
Gitblit v1.10.0