mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Gaetan Boismal
15.42.2015 5ff46475f706645bc4767faa2efcf295564d8f81
OPENDJ-2027 Code cleanup

Preparatory work for OPENDJ-2027:
* src/main/java/org/opends/server/backends/jeb/DBTest.java
** Reduce visibilty of printMessage and rename it to printErrorMessage to improve code consistency
* src/main/java/org/opends/server/tools/ConfigureWindowsService.java
* src/main/java/org/opends/server/tools/StartWindowsService.java
* src/main/java/org/opends/server/tools/StopWindowsService.java
** Autorefactor'ed file + format
** Use straigt return
** Remove unecessary comment
** Additionnal minor cleanup
** Extract method serviceState() to avoid multiple nullchecks on output streams.
* Changes in other files are related to the serviceState() extracted method
7 files modified
847 ■■■■■ changed files
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/ControlPanelInfo.java 4 ●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/Uninstaller.java 2 ●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/backends/jeb/DBTest.java 108 ●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java 10 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/tools/ConfigureWindowsService.java 493 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/tools/StartWindowsService.java 115 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/server/tools/StopWindowsService.java 115 ●●●●● patch | view | raw | blame | history
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/ControlPanelInfo.java
@@ -464,9 +464,7 @@
      boolean windowsServiceEnabled = false;
      if (isWindows())
      {
        int result = ConfigureWindowsService.serviceState(null, null);
        windowsServiceEnabled =
          result == ConfigureWindowsService.SERVICE_STATE_ENABLED;
        windowsServiceEnabled = ConfigureWindowsService.serviceState() == ConfigureWindowsService.SERVICE_STATE_ENABLED;
      }
      desc.setWindowsServiceEnabled(windowsServiceEnabled);
    }
opendj-server-legacy/src/main/java/org/opends/guitools/uninstaller/Uninstaller.java
@@ -1408,7 +1408,7 @@
  private boolean isWindowsServiceEnabled() {
    if (isWindowsServiceEnabled == null) {
      isWindowsServiceEnabled = serviceState(null, null) == SERVICE_STATE_ENABLED;
      isWindowsServiceEnabled = serviceState() == SERVICE_STATE_ENABLED;
    }
    return isWindowsServiceEnabled.booleanValue();
  }
opendj-server-legacy/src/main/java/org/opends/server/backends/jeb/DBTest.java
@@ -187,9 +187,9 @@
  /** Displays the provided message followed by a help usage reference. */
  private void displayMessageAndUsageReference(LocalizableMessage message) {
    printMessage(message);
    printMessage(LocalizableMessage.EMPTY);
    printMessage(parser.getHelpUsageReference());
    printErrorMessage(message);
    printErrorMessage(LocalizableMessage.EMPTY);
    printErrorMessage(parser.getHelpUsageReference());
  }
@@ -378,7 +378,7 @@
      initializeSubCommands();
    } catch (ArgumentException e) {
      LocalizableMessage message = ERR_CANNOT_INITIALIZE_ARGS.get(e.getMessage());
      printMessage(message);
      printErrorMessage(message);
      return 1;
    }
@@ -404,7 +404,7 @@
    }
    catch (InitializationException e)
    {
      printMessage(e.getMessageObject());
      printErrorMessage(e.getMessageObject());
      return 1;
    }
@@ -423,7 +423,7 @@
      {
        LocalizableMessage message = ERR_SERVER_BOOTSTRAP_ERROR.get(
                getExceptionMessage(e));
        printMessage(message);
        printErrorMessage(message);
        return 1;
      }
@@ -436,14 +436,14 @@
      {
        LocalizableMessage message = ERR_CANNOT_LOAD_CONFIG.get(
            ie.getMessage());
        printMessage(message);
        printErrorMessage(message);
        return 1;
      }
      catch (Exception e)
      {
        LocalizableMessage message = ERR_CANNOT_LOAD_CONFIG.get(
            getExceptionMessage(e));
        printMessage(message);
        printErrorMessage(message);
        return 1;
      }
@@ -457,13 +457,13 @@
      catch (ConfigException | InitializationException e)
      {
        LocalizableMessage message = ERR_CANNOT_LOAD_SCHEMA.get(e.getMessage());
        printMessage(message);
        printErrorMessage(message);
        return 1;
      }
      catch (Exception e)
      {
        LocalizableMessage message = ERR_CANNOT_LOAD_SCHEMA.get(getExceptionMessage(e));
        printMessage(message);
        printErrorMessage(message);
        return 1;
      }
@@ -478,13 +478,13 @@
      catch (ConfigException | InitializationException e)
      {
        LocalizableMessage message = ERR_CANNOT_INITIALIZE_CORE_CONFIG.get(e.getMessage());
        printMessage(message);
        printErrorMessage(message);
        return 1;
      }
      catch (Exception e)
      {
        LocalizableMessage message = ERR_CANNOT_INITIALIZE_CORE_CONFIG.get(getExceptionMessage(e));
        printMessage(message);
        printErrorMessage(message);
        return 1;
      }
@@ -497,13 +497,13 @@
      catch (ConfigException | InitializationException e)
      {
        LocalizableMessage message = ERR_CANNOT_INITIALIZE_CRYPTO_MANAGER.get(e.getMessage());
        printMessage(message);
        printErrorMessage(message);
        return 1;
      }
      catch (Exception e)
      {
        LocalizableMessage message = ERR_CANNOT_INITIALIZE_CRYPTO_MANAGER.get(getExceptionMessage(e));
        printMessage(message);
        printErrorMessage(message);
        return 1;
      }
    }
@@ -551,7 +551,7 @@
      }
      return 0;
    } catch (Exception e) {
      printMessage(LocalizableMessage.raw(StaticUtils.stackTraceToString(e)));
      printErrorMessage(LocalizableMessage.raw(StaticUtils.stackTraceToString(e)));
      return 1;
    }
  }
@@ -598,13 +598,13 @@
      StringBuilder failureReason = new StringBuilder();
      if (! LockFileManager.acquireSharedLock(lockFile, failureReason))
      {
        printMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), failureReason));
        printErrorMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), failureReason));
        return 1;
      }
    }
    catch (Exception e)
    {
      printMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), getExceptionMessage(e)));
      printErrorMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), getExceptionMessage(e)));
      return 1;
    }
@@ -615,7 +615,7 @@
    }
    catch(Exception e)
    {
      printMessage(ERR_DBTEST_ERROR_INITIALIZING_BACKEND.get(
      printErrorMessage(ERR_DBTEST_ERROR_INITIALIZING_BACKEND.get(
          backend.getBackendID(),
          StaticUtils.stackTraceToSingleLineString(e)));
      return 1;
@@ -648,7 +648,7 @@
    }
    catch(DatabaseException de)
    {
      printMessage(ERR_DBTEST_ERROR_READING_DATABASE.get(
      printErrorMessage(ERR_DBTEST_ERROR_READING_DATABASE.get(
          StaticUtils.stackTraceToSingleLineString(de)));
      return 1;
    }
@@ -676,7 +676,7 @@
      }
      catch(DirectoryException de)
      {
        printMessage(ERR_DBTEST_DECODE_BASE_DN.get(baseDN.getValue(),
        printErrorMessage(ERR_DBTEST_DECODE_BASE_DN.get(baseDN.getValue(),
                                                   getExceptionMessage(de)));
        return 1;
      }
@@ -689,13 +689,13 @@
      StringBuilder failureReason = new StringBuilder();
      if (! LockFileManager.acquireSharedLock(lockFile, failureReason))
      {
        printMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), failureReason));
        printErrorMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), failureReason));
        return 1;
      }
    }
    catch (Exception e)
    {
      printMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), getExceptionMessage(e)));
      printErrorMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), getExceptionMessage(e)));
      return 1;
    }
@@ -706,7 +706,7 @@
    }
    catch(Exception e)
    {
      printMessage(ERR_DBTEST_ERROR_INITIALIZING_BACKEND.get(
      printErrorMessage(ERR_DBTEST_ERROR_INITIALIZING_BACKEND.get(
          backend.getBackendID(),
          StaticUtils.stackTraceToSingleLineString(e)));
      return 1;
@@ -729,7 +729,7 @@
        EntryContainer ec = rc.getEntryContainer(base);
        if(ec == null)
        {
          printMessage(ERR_DBTEST_NO_ENTRY_CONTAINERS_FOR_BASE_DN.get(
          printErrorMessage(ERR_DBTEST_NO_ENTRY_CONTAINERS_FOR_BASE_DN.get(
              base, backend.getBackendID()));
          return 1;
        }
@@ -754,7 +754,7 @@
    }
    catch(DatabaseException de)
    {
      printMessage(ERR_DBTEST_ERROR_READING_DATABASE.get(
      printErrorMessage(ERR_DBTEST_ERROR_READING_DATABASE.get(
          StaticUtils.stackTraceToSingleLineString(de)));
      return 1;
    }
@@ -802,12 +802,12 @@
      StringBuilder failureReason = new StringBuilder();
      if (!LockFileManager.releaseLock(lockFile, failureReason))
      {
        printMessage(WARN_DBTEST_CANNOT_UNLOCK_BACKEND.get(backend.getBackendID(), failureReason));
        printErrorMessage(WARN_DBTEST_CANNOT_UNLOCK_BACKEND.get(backend.getBackendID(), failureReason));
      }
    }
    catch (Exception e)
    {
      printMessage(WARN_DBTEST_CANNOT_UNLOCK_BACKEND.get(backend.getBackendID(), getExceptionMessage(e)));
      printErrorMessage(WARN_DBTEST_CANNOT_UNLOCK_BACKEND.get(backend.getBackendID(), getExceptionMessage(e)));
    }
  }
@@ -829,12 +829,12 @@
    {
      if (b.getBackendID().equalsIgnoreCase(backendID))
      {
        printMessage(ERR_DBTEST_NOT_JE_BACKEND.get(backendID));
        printErrorMessage(ERR_DBTEST_NOT_JE_BACKEND.get(backendID));
        return null;
      }
    }
    printMessage(ERR_DBTEST_NO_BACKENDS_FOR_ID.get(backendID));
    printErrorMessage(ERR_DBTEST_NO_BACKENDS_FOR_ID.get(backendID));
    return null;
  }
@@ -855,7 +855,7 @@
      }
      catch(DirectoryException de)
      {
        printMessage(ERR_DBTEST_DECODE_BASE_DN.get(baseDN.getValue(),
        printErrorMessage(ERR_DBTEST_DECODE_BASE_DN.get(baseDN.getValue(),
                                                   getExceptionMessage(de)));
        return 1;
      }
@@ -868,13 +868,13 @@
      StringBuilder failureReason = new StringBuilder();
      if (! LockFileManager.acquireSharedLock(lockFile, failureReason))
      {
        printMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), failureReason));
        printErrorMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), failureReason));
        return 1;
      }
    }
    catch (Exception e)
    {
      printMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), getExceptionMessage(e)));
      printErrorMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), getExceptionMessage(e)));
      return 1;
    }
@@ -885,7 +885,7 @@
    }
    catch(Exception e)
    {
      printMessage(ERR_DBTEST_ERROR_INITIALIZING_BACKEND.get(
      printErrorMessage(ERR_DBTEST_ERROR_INITIALIZING_BACKEND.get(
          backend.getBackendID(),
          StaticUtils.stackTraceToSingleLineString(e)));
      return 1;
@@ -913,7 +913,7 @@
      EntryContainer ec = rc.getEntryContainer(base);
      if(ec == null)
      {
        printMessage(ERR_DBTEST_NO_ENTRY_CONTAINERS_FOR_BASE_DN.get(base, backend.getBackendID()));
        printErrorMessage(ERR_DBTEST_NO_ENTRY_CONTAINERS_FOR_BASE_DN.get(base, backend.getBackendID()));
        return 1;
      }
@@ -1026,7 +1026,7 @@
    }
    catch(DatabaseException de)
    {
      printMessage(ERR_DBTEST_ERROR_READING_DATABASE.get(
      printErrorMessage(ERR_DBTEST_ERROR_READING_DATABASE.get(
          StaticUtils.stackTraceToSingleLineString(de)));
      return 1;
    }
@@ -1056,7 +1056,7 @@
    }
    catch(DirectoryException de)
    {
      printMessage(ERR_DBTEST_DECODE_BASE_DN.get(baseDN.getValue(),
      printErrorMessage(ERR_DBTEST_DECODE_BASE_DN.get(baseDN.getValue(),
                                                 getExceptionMessage(de)));
      return 1;
    }
@@ -1068,13 +1068,13 @@
      StringBuilder failureReason = new StringBuilder();
      if (! LockFileManager.acquireSharedLock(lockFile, failureReason))
      {
        printMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), failureReason));
        printErrorMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), failureReason));
        return 1;
      }
    }
    catch (Exception e)
    {
      printMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), getExceptionMessage(e)));
      printErrorMessage(ERR_DBTEST_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), getExceptionMessage(e)));
      return 1;
    }
@@ -1085,7 +1085,7 @@
    }
    catch(Exception e)
    {
      printMessage(ERR_DBTEST_ERROR_INITIALIZING_BACKEND.get(
      printErrorMessage(ERR_DBTEST_ERROR_INITIALIZING_BACKEND.get(
          backend.getBackendID(),
          StaticUtils.stackTraceToSingleLineString(e)));
      return 1;
@@ -1096,7 +1096,7 @@
      EntryContainer ec = rc.getEntryContainer(base);
      if(ec == null)
      {
        printMessage(ERR_DBTEST_NO_ENTRY_CONTAINERS_FOR_BASE_DN.get(base, backend.getBackendID()));
        printErrorMessage(ERR_DBTEST_NO_ENTRY_CONTAINERS_FOR_BASE_DN.get(base, backend.getBackendID()));
        return 1;
      }
@@ -1115,7 +1115,7 @@
      if(databaseContainer == null)
      {
        printMessage(ERR_DBTEST_NO_DATABASE_CONTAINERS_FOR_NAME.get(
        printErrorMessage(ERR_DBTEST_NO_DATABASE_CONTAINERS_FOR_NAME.get(
            databaseName.getValue(), base, backend.getBackendID()));
        return 1;
      }
@@ -1145,7 +1145,7 @@
          }
          catch(Exception e)
          {
            printMessage(ERR_DBTEST_CANNOT_DECODE_SIZE.get(
            printErrorMessage(ERR_DBTEST_CANNOT_DECODE_SIZE.get(
                maxDataSize.getValue(), getExceptionMessage(e)));
            return 1;
          }
@@ -1159,7 +1159,7 @@
          }
          catch(Exception e)
          {
            printMessage(ERR_DBTEST_CANNOT_DECODE_SIZE.get(
            printErrorMessage(ERR_DBTEST_CANNOT_DECODE_SIZE.get(
                minDataSize.getValue(), getExceptionMessage(e)));
            return 1;
          }
@@ -1174,7 +1174,7 @@
          }
          catch(Exception e)
          {
            printMessage(ERR_DBTEST_CANNOT_DECODE_KEY.get(
            printErrorMessage(ERR_DBTEST_CANNOT_DECODE_KEY.get(
                minKeyValue.getValue(), getExceptionMessage(e)));
            return 1;
          }
@@ -1189,7 +1189,7 @@
          }
          catch(Exception e)
          {
            printMessage(ERR_DBTEST_CANNOT_DECODE_KEY.get(
            printErrorMessage(ERR_DBTEST_CANNOT_DECODE_KEY.get(
                maxKeyValue.getValue(), getExceptionMessage(e)));
            return 1;
          }
@@ -1243,7 +1243,7 @@
                }
                catch(Exception e)
                {
                  printMessage(ERR_DBTEST_DECODE_FAIL.get(getExceptionMessage(e)));
                  printErrorMessage(ERR_DBTEST_DECODE_FAIL.get(getExceptionMessage(e)));
                }
                formatedData = String.valueOf(
                  JebFormat.entryIDFromDatabase(data.getData()));
@@ -1264,7 +1264,7 @@
                }
                catch(Exception e)
                {
                  printMessage(ERR_DBTEST_DECODE_FAIL.get(getExceptionMessage(e)));
                  printErrorMessage(ERR_DBTEST_DECODE_FAIL.get(getExceptionMessage(e)));
                }
              }
              else if(databaseContainer instanceof DN2URI)
@@ -1276,7 +1276,7 @@
                }
                catch(Exception e)
                {
                  printMessage(ERR_DBTEST_DECODE_FAIL.get(getExceptionMessage(e)));
                  printErrorMessage(ERR_DBTEST_DECODE_FAIL.get(getExceptionMessage(e)));
                }
                formatedData = new String(key.getData());
                dataLabel = INFO_LABEL_DBTEST_URI.get();
@@ -1407,7 +1407,7 @@
                }
                catch(Exception e)
                {
                  printMessage(ERR_DBTEST_DECODE_FAIL.get(getExceptionMessage(e)));
                  printErrorMessage(ERR_DBTEST_DECODE_FAIL.get(getExceptionMessage(e)));
                }
              }
            }
@@ -1452,7 +1452,7 @@
    }
    catch(DatabaseException de)
    {
      printMessage(ERR_DBTEST_ERROR_READING_DATABASE.get(
      printErrorMessage(ERR_DBTEST_ERROR_READING_DATABASE.get(
          StaticUtils.stackTraceToSingleLineString(de)));
      return 1;
    }
@@ -1537,13 +1537,7 @@
    return jeBackends;
  }
  /**
   * Displays a message to the error stream.
   *
   * @param msg
   *          The message.
   */
  public final void printMessage(LocalizableMessage msg) {
  private final void printErrorMessage(LocalizableMessage msg) {
    err.println(wrapText(msg.toString(), MAX_LINE_WIDTH));
  }
}
opendj-server-legacy/src/main/java/org/opends/server/core/DirectoryServer.java
@@ -8357,15 +8357,11 @@
   */
  public static boolean isRunningAsWindowsService()
  {
    boolean isRunningAsWindowsService;
    boolean isRunningAsWindowsService = false;
    if (OperatingSystem.isWindows())
    {
      isRunningAsWindowsService = ConfigureWindowsService.serviceState(null,
      null) == ConfigureWindowsService.SERVICE_STATE_ENABLED;
    }
    else
    {
      isRunningAsWindowsService = false;
      isRunningAsWindowsService =
          ConfigureWindowsService.serviceState() == ConfigureWindowsService.SERVICE_STATE_ENABLED;
    }
    return isRunningAsWindowsService;
  }
opendj-server-legacy/src/main/java/org/opends/server/tools/ConfigureWindowsService.java
@@ -73,103 +73,61 @@
  */
public class ConfigureWindowsService
{
  /**
   * The fully-qualified name of this class.
   */
  private static final String CLASS_NAME =
    "org.opends.server.tools.ConfigureWindowsService";
  /** The fully-qualified name of this class. */
  private static final String CLASS_NAME = "org.opends.server.tools.ConfigureWindowsService";
  private static final String DEBUG_OPTION = "--debug";
  /**
   * Option to be used when calling the launchers.
   */
  /** Option to be used when calling the launchers. */
  public static final String LAUNCHER_OPTION = "run";
  private static int ERROR = 1;
  private static final int SUCCESS = 0;
  private static final int ERROR = 1;
  /**
   * Return codes for the method enableService.
   */
  /**
   * The service was successfully enabled.
   */
  /** Return codes for the method enableService. */
  /** The service was successfully enabled. */
  public static final int SERVICE_ENABLE_SUCCESS = 0;
  /**
   * The service was already enabled.
   */
  /** The service was already enabled. */
  public static final int SERVICE_ALREADY_ENABLED = 1;
  /**
   * The service name was already in use.
   */
  /** The service name was already in use. */
  public static final int SERVICE_NAME_ALREADY_IN_USE = 2;
  /**
   * An error occurred enabling the service.
   */
  /** An error occurred enabling the service. */
  public static final int SERVICE_ENABLE_ERROR = 3;
  /**
   * Return codes for the method disableService.
   */
  /**
   * The service was successfully disabled.
   */
  /** Return codes for the method disableService. */
  /** The service was successfully disabled. */
  public static final int SERVICE_DISABLE_SUCCESS = 0;
  /**
   * The service was already disabled.
   */
  /** The service was already disabled. */
  public static final int SERVICE_ALREADY_DISABLED = 1;
  /**
   * The service is marked for deletion.
   */
  /** The service is marked for deletion. */
  public static final int SERVICE_MARKED_FOR_DELETION = 2;
  /**
   * An error occurred disabling the service.
   */
  /** An error occurred disabling the service. */
  public static final int SERVICE_DISABLE_ERROR = 3;
  /**
   * Return codes for the method serviceState.
   */
  /**
   * The service is enabled.
   */
  /** Return codes for the method serviceState. */
  /** The service is enabled. */
  public static final int SERVICE_STATE_ENABLED = 0;
  /**
   * The service is disabled.
   */
  /** The service is disabled. */
  public static final int SERVICE_STATE_DISABLED = 1;
  /**
   * An error occurred checking the service state.
   */
  /** An error occurred checking the service state. */
  public static final int SERVICE_STATE_ERROR = 2;
  /**
   * Return codes for the method cleanupService.
   */
  /**
   * The service cleanup worked.
   */
  /** Return codes for the method cleanupService. */
  /** The service cleanup worked. */
  public static final int SERVICE_CLEANUP_SUCCESS = 0;
  /**
   * The service could not be found.
   */
  /** The service could not be found. */
  public static final int SERVICE_NOT_FOUND = 1;
  /**
   * An error occurred cleaning up the service.
   */
  /** An error occurred cleaning up the service. */
  public static final int SERVICE_CLEANUP_ERROR = 2;
  /**
   * The service is marked for deletion.
   */
  /** The service is marked for deletion. */
  public static final int SERVICE_CLEANUP_MARKED_FOR_DELETION = 3;
  /**
   * Configures the Windows service for this instance on this machine.
   * This tool allows to enable and disable OpenDJ to run as a Windows service
   * and allows to know if OpenDJ is running as a Windows service or not.
   * Configures the Windows service for this instance on this machine. This tool
   * allows to enable and disable OpenDJ to run as a Windows service and allows
   * to know if OpenDJ is running as a Windows service or not.
   *
   * @param  args  The command-line arguments provided to this program.
   * @param args
   *          The command-line arguments provided to this program.
   */
  public static void main(String[] args)
  {
@@ -179,29 +137,28 @@
  }
  /**
   * Configures the Windows service for this instance on this machine.
   * This tool allows to enable and disable OpenDJ to run as a Windows service
   * and allows to know if OpenDJ is running as a Windows service or not.
   * Configures the Windows service for this instance on this machine. This tool
   * allows to enable and disable OpenDJ to run as a Windows service and allows
   * to know if OpenDJ is running as a Windows service or not.
   *
   * @param  args  The command-line arguments provided to this program.
   * @param outStream the stream used to write the standard output.
   * @param errStream the stream used to write the error output.
   * @param args
   *          The command-line arguments provided to this program.
   * @param outStream
   *          the stream used to write the standard output.
   * @param errStream
   *          the stream used to write the error output.
   * @return the integer code describing if the operation could be completed or
   * not.
   *         not.
   */
  public static int configureWindowsService(String[] args,
      OutputStream outStream, OutputStream errStream)
  public static int configureWindowsService(String[] args, OutputStream outStream, OutputStream errStream)
  {
    int returnValue = 0;
    PrintStream out = NullOutputStream.wrapOrNullStream(outStream);
    PrintStream err = NullOutputStream.wrapOrNullStream(errStream);
    JDKLogging.disableLogging();
//  Define all the arguments that may be used with this program.
    LocalizableMessage toolDescription =
        INFO_CONFIGURE_WINDOWS_SERVICE_TOOL_DESCRIPTION.get();
    ArgumentParser argParser = new ArgumentParser(CLASS_NAME,
        toolDescription, false);
    //  Define all the arguments that may be used with this program.
    LocalizableMessage toolDescription = INFO_CONFIGURE_WINDOWS_SERVICE_TOOL_DESCRIPTION.get();
    ArgumentParser argParser = new ArgumentParser(CLASS_NAME, toolDescription, false);
    argParser.setShortToolDescription(REF_SHORT_DESC_WINDOWS_SERVICE.get());
    BooleanArgument enableService = null;
    BooleanArgument disableService = null;
@@ -215,18 +172,15 @@
          INFO_CONFIGURE_WINDOWS_SERVICE_DESCRIPTION_ENABLE.get());
      argParser.addArgument(enableService);
      disableService = new BooleanArgument("disableservice", 'd',
          "disableService",
      disableService = new BooleanArgument("disableservice", 'd', "disableService",
          INFO_CONFIGURE_WINDOWS_SERVICE_DESCRIPTION_DISABLE.get());
      argParser.addArgument(disableService);
      serviceState = new BooleanArgument("servicestate", 's',
          "serviceState",
      serviceState = new BooleanArgument("servicestate", 's', "serviceState",
          INFO_CONFIGURE_WINDOWS_SERVICE_DESCRIPTION_STATE.get());
      argParser.addArgument(serviceState);
      cleanupService = new StringArgument("cleanupservice", 'c',
          "cleanupService", false, false, true,
      cleanupService = new StringArgument("cleanupservice", 'c', "cleanupService", false, false, true,
          INFO_SERVICE_NAME_PLACEHOLDER.get(), null, null,
          INFO_CONFIGURE_WINDOWS_SERVICE_DESCRIPTION_CLEANUP.get());
      argParser.addArgument(cleanupService);
@@ -240,29 +194,25 @@
      LocalizableMessage message = ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage());
      err.println(wrapText(message, MAX_LINE_WIDTH));
      returnValue = ERROR;
      return ERROR;
    }
    // Parse the command-line arguments provided to this program.
    if (returnValue == 0)
    try
    {
      try
      {
        argParser.parseArguments(args);
      }
      catch (ArgumentException ae)
      {
        LocalizableMessage message = ERR_ERROR_PARSING_ARGS.get(ae.getMessage());
      argParser.parseArguments(args);
    }
    catch (ArgumentException ae)
    {
      LocalizableMessage message = ERR_ERROR_PARSING_ARGS.get(ae.getMessage());
        err.println(wrapText(message, MAX_LINE_WIDTH));
        err.println(argParser.getUsage());
        returnValue = ERROR;
      }
      err.println(wrapText(message, MAX_LINE_WIDTH));
      err.println(argParser.getUsage());
      return ERROR;
    }
    // If we should just display usage or version information,
    // then it is already done
    if ((returnValue == 0) && !argParser.usageOrVersionDisplayed())
    if (!argParser.usageOrVersionDisplayed())
    {
      /* Check that the user only asked for one argument */
      int nArgs = 0;
@@ -282,65 +232,53 @@
      {
        nArgs++;
      }
      if (nArgs > 1)
      if (nArgs != 1)
      {
        LocalizableMessage message = ERR_CONFIGURE_WINDOWS_SERVICE_TOO_MANY_ARGS.get();
        LocalizableMessage message = nArgs == 0 ? ERR_CONFIGURE_WINDOWS_SERVICE_TOO_FEW_ARGS.get()
                                                : ERR_CONFIGURE_WINDOWS_SERVICE_TOO_MANY_ARGS.get();
        err.println(wrapText(message, MAX_LINE_WIDTH));
        err.println(argParser.getUsage());
        returnValue = ERROR;
      }
      if (nArgs == 0)
      {
        LocalizableMessage message = ERR_CONFIGURE_WINDOWS_SERVICE_TOO_FEW_ARGS.get();
        err.println(wrapText(message, MAX_LINE_WIDTH));
        err.println(argParser.getUsage());
        returnValue = ERROR;
        return ERROR;
      }
    }
    if ((returnValue == 0) && !argParser.usageOrVersionDisplayed())
    if (argParser.usageOrVersionDisplayed())
    {
      if (enableService.isPresent())
      {
        returnValue = enableService(out, err);
      }
      else if (disableService.isPresent())
      {
        returnValue = disableService(out, err);
      }
      else if (serviceState.isPresent())
      {
        returnValue = serviceState(out, err);
      }
      else
      {
        returnValue = cleanupService(cleanupService.getValue(), out, err);
      }
      return SUCCESS;
    }
    return returnValue;
    if (enableService.isPresent())
    {
      return enableService(out, err);
    }
    else if (disableService.isPresent())
    {
      return disableService(out, err);
    }
    else if (serviceState.isPresent())
    {
      return serviceState(out, err);
    }
    return cleanupService(cleanupService.getValue(), out, err);
  }
  /**
   * Returns the service name associated with OpenDJ or null if no service name
   * could be found.
   *
   * @return the service name associated with OpenDJ or null if no service name
   * could be found.
   *         could be found.
   */
  static String getServiceName()
  {
    String serviceName = null;
    String serverRoot = getServerRoot();
    String[] cmd = {
        getBinaryFullPath(),
        "state",
        serverRoot
    };
    String[] cmd = { getBinaryFullPath(), "state", serverRoot };
    try
    {
      Process p = Runtime.getRuntime().exec(cmd);
      BufferedReader stdout = new BufferedReader(
          new InputStreamReader(p.getInputStream()));
      BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
      boolean processDone = false;
      String s;
      while (!processDone)
@@ -373,13 +311,16 @@
  /**
   * Enables OpenDJ to run as a windows service.
   * @param out the stream used to write the standard output.
   * @param err the stream used to write the error output.
   *
   * @param out
   *          the stream used to write the standard output.
   * @param err
   *          the stream used to write the error output.
   * @return <CODE>SERVICE_ENABLE_SUCCESS</CODE>,
   * <CODE>SERVICE_ENABLE_ERROR</CODE>,
   * <CODE>SERVICE_NAME_ALREADY_IN_USE</CODE> or
   * <CODE>SERVICE_ALREADY_ENABLED</CODE> depending on whether the service could
   * be enabled or not.
   *         <CODE>SERVICE_ENABLE_ERROR</CODE>,
   *         <CODE>SERVICE_NAME_ALREADY_IN_USE</CODE> or
   *         <CODE>SERVICE_ALREADY_ENABLED</CODE> depending on whether the
   *         service could be enabled or not.
   */
  public static int enableService(PrintStream out, PrintStream err)
  {
@@ -390,28 +331,28 @@
    LocalizableMessage serviceDescription = Utils.getCustomizedObject(
        "INFO_WINDOWS_SERVICE_DESCRIPTION",
        INFO_WINDOWS_SERVICE_DESCRIPTION.get(getServerRoot()), LocalizableMessage.class);
    return enableService(out, err, serviceName.toString(),
        serviceDescription.toString());
    return enableService(out, err, serviceName.toString(), serviceDescription.toString());
  }
  /**
   * Enables OpenDJ to run as a windows service.
   * @param out the stream used to write the standard output.
   * @param err the stream used to write the error output.
   * @param serviceName the name of the service as it will appear in the
   * registry.
   * @param serviceDescription the description of the service as it will appear
   * in the registry.
   *
   * @param out
   *          the stream used to write the standard output.
   * @param err
   *          the stream used to write the error output.
   * @param serviceName
   *          the name of the service as it will appear in the registry.
   * @param serviceDescription
   *          the description of the service as it will appear in the registry.
   * @return <CODE>SERVICE_ENABLE_SUCCESS</CODE>,
   * <CODE>SERVICE_ENABLE_ERROR</CODE>,
   * <CODE>SERVICE_NAME_ALREADY_IN_USE</CODE> or
   * <CODE>SERVICE_ALREADY_ENABLED</CODE> depending on whether the service could
   * be enabled or not.
   *         <CODE>SERVICE_ENABLE_ERROR</CODE>,
   *         <CODE>SERVICE_NAME_ALREADY_IN_USE</CODE> or
   *         <CODE>SERVICE_ALREADY_ENABLED</CODE> depending on whether the
   *         service could be enabled or not.
   */
  public static int enableService(PrintStream out, PrintStream err,
      String serviceName, String serviceDescription)
  public static int enableService(PrintStream out, PrintStream err, String serviceName, String serviceDescription)
  {
    int returnValue;
    LocalizableMessage msg;
    String serverRoot = getServerRoot();
@@ -446,8 +387,7 @@
    try
    {
      boolean isServerRunning = Utilities.isServerRunning(
          new File(serverRoot));
      boolean isServerRunning = Utilities.isServerRunning(new File(serverRoot));
      int resultCode = Runtime.getRuntime().exec(cmd).waitFor();
      switch (resultCode)
@@ -458,73 +398,69 @@
          // We have to launch the windows service.  The service code already
          // handles this case (the service binary is executed when the server
          // already runs).
          returnValue = StartWindowsService.startWindowsService(out, err);
          final int returnValue = StartWindowsService.startWindowsService(out, err);
          if (returnValue == 0)
          {
            returnValue = SERVICE_ENABLE_SUCCESS;
            msg = INFO_WINDOWS_SERVICE_SUCCESSULLY_ENABLED.get();
            out.println(wrapText(msg, MAX_LINE_WIDTH));
            return SERVICE_ENABLE_SUCCESS;
          }
          else
          {
            msg = ERR_WINDOWS_SERVICE_ENABLING_ERROR_STARTING_SERVER.get(
                returnValue);
            returnValue = SERVICE_ENABLE_ERROR;
            msg = ERR_WINDOWS_SERVICE_ENABLING_ERROR_STARTING_SERVER.get(returnValue);
            err.println(wrapText(msg, MAX_LINE_WIDTH));
            return SERVICE_ENABLE_ERROR;
          }
        }
        else
        {
          returnValue = SERVICE_ENABLE_SUCCESS;
          msg = INFO_WINDOWS_SERVICE_SUCCESSULLY_ENABLED.get();
          out.println(wrapText(msg, MAX_LINE_WIDTH));
          return SERVICE_ENABLE_SUCCESS;
        }
        break;
      case 1:
        returnValue = SERVICE_ALREADY_ENABLED;
        msg = INFO_WINDOWS_SERVICE_ALREADY_ENABLED.get();
        out.println(wrapText(msg, MAX_LINE_WIDTH));
        break;
        return SERVICE_ALREADY_ENABLED;
      case 2:
        returnValue = SERVICE_NAME_ALREADY_IN_USE;
        msg = ERR_WINDOWS_SERVICE_NAME_ALREADY_IN_USE.get();
        err.println(wrapText(msg, MAX_LINE_WIDTH));
        break;
        return SERVICE_NAME_ALREADY_IN_USE;
      case 3:
        returnValue = SERVICE_ENABLE_ERROR;
        msg = ERR_WINDOWS_SERVICE_ENABLE_ERROR.get();
        err.println(wrapText(msg, MAX_LINE_WIDTH));
        break;
        return SERVICE_ENABLE_ERROR;
      default:
        returnValue = SERVICE_ENABLE_ERROR;
        msg = ERR_WINDOWS_SERVICE_ENABLE_ERROR.get();
        err.println(wrapText(msg, MAX_LINE_WIDTH));
        return SERVICE_ENABLE_ERROR;
      }
    }
    catch (Throwable t)
    {
      err.println("Unexpected throwable: "+t);
      t.printStackTrace();
      returnValue = SERVICE_ENABLE_ERROR;
      msg = ERR_WINDOWS_SERVICE_ENABLE_ERROR.get();
      err.println(wrapText(msg, MAX_LINE_WIDTH));
      return SERVICE_ENABLE_ERROR;
    }
    return returnValue;
  }
  /**
   * Disables OpenDJ to run as a windows service.
   * @param out the stream used to write the standard output.
   * @param err the stream used to write the error output.
   *
   * @param out
   *          the stream used to write the standard output.
   * @param err
   *          the stream used to write the error output.
   * @return <CODE>SERVICE_DISABLE_SUCCESS</CODE>,
   * <CODE>SERVICE_DISABLE_ERROR</CODE>,
   * <CODE>SERVICE_MARKED_FOR_DELETION</CODE> or
   * <CODE>SERVICE_ALREADY_DISABLED</CODE> depending on whether the service
   * could be disabled or not.
   *         <CODE>SERVICE_DISABLE_ERROR</CODE>,
   *         <CODE>SERVICE_MARKED_FOR_DELETION</CODE> or
   *         <CODE>SERVICE_ALREADY_DISABLED</CODE> depending on whether the
   *         service could be disabled or not.
   */
  public static int disableService(PrintStream out, PrintStream err)
  {
    int returnValue;
    LocalizableMessage msg;
    String serverRoot = getServerRoot();
    String[] cmd;
@@ -556,56 +492,54 @@
      switch (resultCode)
      {
      case 0:
        returnValue = SERVICE_DISABLE_SUCCESS;
        msg = INFO_WINDOWS_SERVICE_SUCCESSULLY_DISABLED.get();
        out.println(msg);
        break;
        return SERVICE_DISABLE_SUCCESS;
      case 1:
        returnValue = SERVICE_ALREADY_DISABLED;
        msg = INFO_WINDOWS_SERVICE_ALREADY_DISABLED.get();
        out.println(msg);
        break;
        return SERVICE_ALREADY_DISABLED;
      case 2:
        returnValue = SERVICE_MARKED_FOR_DELETION;
        msg = WARN_WINDOWS_SERVICE_MARKED_FOR_DELETION.get();
        out.println(msg);
        break;
        return SERVICE_MARKED_FOR_DELETION;
      case 3:
        returnValue = SERVICE_DISABLE_ERROR;
        msg = ERR_WINDOWS_SERVICE_DISABLE_ERROR.get();
        err.println(msg);
        break;
        return SERVICE_DISABLE_ERROR;
      default:
        returnValue = SERVICE_DISABLE_ERROR;
        msg = ERR_WINDOWS_SERVICE_DISABLE_ERROR.get();
        err.println(msg);
        return SERVICE_DISABLE_ERROR;
      }
    }
    catch (Throwable t)
    {
      t.printStackTrace();
      returnValue = SERVICE_DISABLE_ERROR;
      msg = ERR_WINDOWS_SERVICE_DISABLE_ERROR.get();
      err.println(msg);
      return SERVICE_DISABLE_ERROR;
    }
    return returnValue;
  }
  /**
   * Cleans up a service for a given service name.
   * @param serviceName the service name to be cleaned up.
   * @param out the stream used to write the standard output.
   * @param err the stream used to write the error output.
   *
   * @param serviceName
   *          the service name to be cleaned up.
   * @param out
   *          the stream used to write the standard output.
   * @param err
   *          the stream used to write the error output.
   * @return <CODE>SERVICE_CLEANUP_SUCCESS</CODE>,
   * <CODE>SERVICE_NOT_FOUND</CODE>,
   * <CODE>SERVICE_MARKED_FOR_DELETION</CODE> or
   * <CODE>SERVICE_CLEANUP_ERROR</CODE> depending on whether the service
   * could be found or not.
   *         <CODE>SERVICE_NOT_FOUND</CODE>,
   *         <CODE>SERVICE_MARKED_FOR_DELETION</CODE> or
   *         <CODE>SERVICE_CLEANUP_ERROR</CODE> depending on whether the service
   *         could be found or not.
   */
  public static int cleanupService(String serviceName, PrintStream out,
      PrintStream err)
  {
    int returnValue;
    LocalizableMessage msg;
    String[] cmd;
    if (hasUAC())
@@ -636,53 +570,64 @@
      switch (resultCode)
      {
      case 0:
        returnValue = SERVICE_CLEANUP_SUCCESS;
        msg = INFO_WINDOWS_SERVICE_CLEANUP_SUCCESS.get(serviceName);
        out.println(msg);
        break;
        return SERVICE_CLEANUP_SUCCESS;
      case 1:
        returnValue = SERVICE_NOT_FOUND;
        msg = ERR_WINDOWS_SERVICE_CLEANUP_NOT_FOUND.get(serviceName);
        err.println(msg);
        break;
        return SERVICE_NOT_FOUND;
      case 2:
        returnValue = SERVICE_CLEANUP_MARKED_FOR_DELETION;
        msg = WARN_WINDOWS_SERVICE_CLEANUP_MARKED_FOR_DELETION.get(serviceName);
        out.println(msg);
        break;
        return SERVICE_CLEANUP_MARKED_FOR_DELETION;
      case 3:
        returnValue = SERVICE_CLEANUP_ERROR;
        msg = ERR_WINDOWS_SERVICE_CLEANUP_ERROR.get(serviceName);
        err.println(msg);
        break;
        return SERVICE_CLEANUP_ERROR;
      default:
        returnValue = SERVICE_CLEANUP_ERROR;
        msg = ERR_WINDOWS_SERVICE_CLEANUP_ERROR.get(serviceName);
        err.println(msg);
        return SERVICE_CLEANUP_ERROR;
      }
    }
    catch (Throwable t)
    {
      returnValue = SERVICE_CLEANUP_ERROR;
      msg = ERR_WINDOWS_SERVICE_CLEANUP_ERROR.get(serviceName);
      err.println(msg);
      err.println("Exception:" + t);
      return SERVICE_CLEANUP_ERROR;
    }
    return returnValue;
  }
  /**
    * Checks if OpenDJ is enabled as a windows service and if it is
    * write the serviceName in the output stream (if it is not null).
    * @param out the stream used to write the standard output.
    * @param err the stream used to write the error output.
    * @return <CODE>SERVICE_STATE_ENABLED</CODE>,
    * <CODE>SERVICE_STATE_DISABLED</CODE> or <CODE>SERVICE_STATE_ERROR</CODE>
    * depending on the state of the service.
    */
   * Checks if OpenDJ is enabled as a windows service.
   *
   * @return <CODE>SERVICE_STATE_ENABLED</CODE>,
   *         <CODE>SERVICE_STATE_DISABLED</CODE> or
   *         <CODE>SERVICE_STATE_ERROR</CODE> depending on the state of the
   *         service.
   */
  public static int serviceState()
  {
    return serviceState(NullOutputStream.printStream(), NullOutputStream.printStream());
  }
  /**
   * Checks if OpenDJ is enabled as a windows service and if it is write the
   * serviceName in the output stream (if it is not null).
   *
   * @param out
   *          the stream used to write the standard output.
   * @param err
   *          the stream used to write the error output.
   * @return <CODE>SERVICE_STATE_ENABLED</CODE>,
   *         <CODE>SERVICE_STATE_DISABLED</CODE> or
   *         <CODE>SERVICE_STATE_ERROR</CODE> depending on the state of the
   *         service.
   */
  public static int serviceState(PrintStream out, PrintStream err)
  {
    int returnValue;
    LocalizableMessage msg;
    String serviceName = null;
@@ -697,11 +642,8 @@
    try
    {
      int resultCode = -1;
      ProcessBuilder pb = new ProcessBuilder(cmd);
      Process process = pb.start();
      BufferedReader stdout =
          new BufferedReader(new InputStreamReader(process.getInputStream()));
      Process process = new ProcessBuilder(cmd).start();
      BufferedReader stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
      boolean processDone = false;
      String s;
@@ -723,60 +665,41 @@
          }
        }
      }
      switch (resultCode)
      {
      case 0:
        returnValue = SERVICE_STATE_ENABLED;
        if (out != null)
        {
          msg = INFO_WINDOWS_SERVICE_ENABLED.get(serviceName);
          out.println(msg);
        }
        break;
        msg = INFO_WINDOWS_SERVICE_ENABLED.get(serviceName);
        out.println(msg);
        return SERVICE_STATE_ENABLED;
      case 1:
        returnValue = SERVICE_STATE_DISABLED;
        if (out != null)
        {
          msg = INFO_WINDOWS_SERVICE_DISABLED.get();
          out.println(msg);
        }
        break;
        msg = INFO_WINDOWS_SERVICE_DISABLED.get();
        out.println(msg);
        return SERVICE_STATE_DISABLED;
      case 2:
        returnValue = SERVICE_STATE_ERROR;
        if (err != null)
        {
          msg = ERR_WINDOWS_SERVICE_STATE_ERROR.get();
          err.println(msg);
        }
        break;
        msg = ERR_WINDOWS_SERVICE_STATE_ERROR.get();
        err.println(msg);
        return SERVICE_STATE_ERROR;
      default:
        returnValue = SERVICE_STATE_ERROR;
        if (err != null)
        {
          msg = ERR_WINDOWS_SERVICE_STATE_ERROR.get();
          err.println(msg);
        }
        msg = ERR_WINDOWS_SERVICE_STATE_ERROR.get();
        err.println(msg);
        return SERVICE_STATE_ERROR;
      }
    }
    catch (Throwable t)
    {
      returnValue = SERVICE_STATE_ERROR;
      if (err != null)
      {
        msg = ERR_WINDOWS_SERVICE_STATE_ERROR.get();
        err.println(msg);
        err.println(wrapText(t.toString(), MAX_LINE_WIDTH));
      }
      msg = ERR_WINDOWS_SERVICE_STATE_ERROR.get();
      err.println(msg);
      err.println(wrapText(t.toString(), MAX_LINE_WIDTH));
      return SERVICE_STATE_ERROR;
    }
    return returnValue;
  }
  /**
   * Returns the Directory Server installation path in a user friendly
   * representation.
   *
   * @return the Directory Server installation path in a user friendly
   * representation.
   *         representation.
   */
  private static String getServerRoot()
  {
@@ -806,40 +729,42 @@
  /**
   * Returns the full path of the executable used by this class to perform
   * operations related to the service.  This binaries file has the asInvoker
   * operations related to the service. This binaries file has the asInvoker
   * value in its manifest.
   *
   * @return the full path of the executable used by this class to perform
   * operations related to the service.
   *         operations related to the service.
   */
  private static String getBinaryFullPath()
  {
    return SetupUtils.getScriptPath(
        getServerRoot()+"\\lib\\opendj_service.exe");
    return SetupUtils.getScriptPath(getServerRoot() + "\\lib\\opendj_service.exe");
  }
  /**
   * Returns the full path of the executable that has a manifest requiring
   * administrator privileges used by this class to perform
   * operations related to the service.
   * administrator privileges used by this class to perform operations related
   * to the service.
   *
   * @return the full path of the executable that has a manifest requiring
   * administrator privileges used by this class to perform
   * operations related to the service.
   *         administrator privileges used by this class to perform operations
   *         related to the service.
   */
  public static String getLauncherAdministratorBinaryFullPath()
  {
    return getServerRoot()+"\\lib\\launcher_administrator.exe";
    return getServerRoot() + "\\lib\\launcher_administrator.exe";
  }
  /**
   * Returns the full path of the executable that has a manifest requiring
   * administrator privileges used by this class to perform
   * operations related to the service.
   * administrator privileges used by this class to perform operations related
   * to the service.
   *
   * @return the full path of the executable that has a manifest requiring
   * administrator privileges used by this class to perform
   * operations related to the service.
   *         administrator privileges used by this class to perform operations
   *         related to the service.
   */
  public static String getLauncherBinaryFullPath()
  {
    return getServerRoot()+"\\lib\\winlauncher.exe";
    return getServerRoot() + "\\lib\\winlauncher.exe";
  }
}
opendj-server-legacy/src/main/java/org/opends/server/tools/StartWindowsService.java
@@ -24,7 +24,6 @@
 *      Copyright 2008-2009 Sun Microsystems, Inc.
 *      Portions Copyright 2013-2015 ForgeRock AS.
 */
package org.opends.server.tools;
import org.forgerock.i18n.LocalizableMessage;
@@ -45,19 +44,13 @@
  */
public class StartWindowsService
{
  /**
    * The service was successfully started.
    */
  private static int SERVICE_START_SUCCESSFUL;
  /**
    * The service could not be found.
    */
  private static int SERVICE_NOT_FOUND = 1;
  /** The service was successfully started. */
  private static final int SERVICE_START_SUCCESSFUL = 0;
  /** The service could not be found. */
  private static final int SERVICE_NOT_FOUND = 1;
  /**
    * The service could not be started.
    */
  private static int SERVICE_START_ERROR = 2;
  /** The service could not be started. */
  private static final int SERVICE_START_ERROR = 2;
  /**
   * Invokes the net start on the service corresponding to this server.
@@ -66,25 +59,25 @@
   */
  public static void main(String[] args)
  {
    int result = startWindowsService(System.out, System.err);
    System.exit(filterExitCode(result));
    System.exit(filterExitCode(startWindowsService(System.out, System.err)));
  }
  /**
   * Invokes the net start on the service corresponding to this server, it
   * writes information and error messages in the provided streams.
   *
   * @return <CODE>SERVICE_START_SUCCESSFUL</CODE>,
   * <CODE>SERVICE_NOT_FOUND</CODE>, <CODE>SERVICE_ALREADY_STARTED</CODE> or
   * <CODE>SERVICE_START_ERROR</CODE> depending on whether the service could be
   * stopped or not.
   * @param  outStream  The stream to write standard output messages.
   * @param  errStream  The stream to write error messages.
   *         <CODE>SERVICE_NOT_FOUND</CODE>,
   *         <CODE>SERVICE_ALREADY_STARTED</CODE> or
   *         <CODE>SERVICE_START_ERROR</CODE> depending on whether the service
   *         could be stopped or not.
   * @param outStream
   *          The stream to write standard output messages.
   * @param errStream
   *          The stream to write error messages.
   */
  public static int startWindowsService(OutputStream outStream,
                           OutputStream errStream)
  public static int startWindowsService(OutputStream outStream, OutputStream errStream)
  {
    int returnValue;
    NullOutputStream.wrapOrNullStream(outStream);
    PrintStream err = NullOutputStream.wrapOrNullStream(errStream);
    JDKLogging.disableLogging();
@@ -94,51 +87,41 @@
    {
      LocalizableMessage message = ERR_WINDOWS_SERVICE_NOT_FOUND.get();
      err.println(message);
      returnValue = SERVICE_NOT_FOUND;
      return SERVICE_NOT_FOUND;
    }
    String[] cmd;
    if (hasUAC())
    {
      cmd= new String[] {
          ConfigureWindowsService.getLauncherBinaryFullPath(),
          ConfigureWindowsService.LAUNCHER_OPTION,
          ConfigureWindowsService.getLauncherAdministratorBinaryFullPath(),
          ConfigureWindowsService.LAUNCHER_OPTION,
          "net",
          "start",
          serviceName
      };
    }
    else
    {
      String[] cmd;
      if (hasUAC())
      {
        cmd= new String[] {
            ConfigureWindowsService.getLauncherBinaryFullPath(),
            ConfigureWindowsService.LAUNCHER_OPTION,
            ConfigureWindowsService.getLauncherAdministratorBinaryFullPath(),
            ConfigureWindowsService.LAUNCHER_OPTION,
            "net",
            "start",
            serviceName
        };
      }
      else
      {
        cmd= new String[] {
            "net",
            "start",
            serviceName
        };
      }
      /* Check if is a running service */
      try
      {
        if (Runtime.getRuntime().exec(cmd).waitFor() == 0)
        {
          returnValue = SERVICE_START_SUCCESSFUL;
        }
        else
        {
          returnValue = SERVICE_START_ERROR;
        }
      }
      catch (Throwable t)
      {
        LocalizableMessage message = ERR_WINDOWS_SERVICE_START_ERROR.get();
        err.println(message);
        err.println("Exception:" + t);
        returnValue = SERVICE_START_ERROR;
      }
      cmd= new String[] {
          "net",
          "start",
          serviceName
      };
    }
    return returnValue;
    /* Check if is a running service */
    try
    {
      return Runtime.getRuntime().exec(cmd).waitFor() == 0 ? SERVICE_START_SUCCESSFUL : SERVICE_START_ERROR;
    }
    catch (Throwable t)
    {
      LocalizableMessage message = ERR_WINDOWS_SERVICE_START_ERROR.get();
      err.println(message);
      err.println("Exception:" + t);
      return SERVICE_START_ERROR;
    }
  }
}
opendj-server-legacy/src/main/java/org/opends/server/tools/StopWindowsService.java
@@ -24,7 +24,6 @@
 *      Copyright 2008-2009 Sun Microsystems, Inc.
 *      Portions Copyright 2012-2014 ForgeRock AS
 */
package org.opends.server.tools;
import org.forgerock.i18n.LocalizableMessage;
@@ -38,7 +37,6 @@
import static com.forgerock.opendj.util.OperatingSystem.hasUAC;
import static com.forgerock.opendj.cli.Utils.filterExitCode;
/**
  * This class is used to stop the Windows service associated with this
  * instance on this machine.
@@ -46,17 +44,11 @@
  */
public class StopWindowsService
{
  /**
    * The service was successfully stopped.
    */
  /** The service was successfully stopped. */
  public static final int SERVICE_STOP_SUCCESSFUL = 0;
  /**
    * The service could not be found.
    */
  /** The service could not be found. */
  public static final int SERVICE_NOT_FOUND = 1;
  /**
    * The service could not be stopped.
    */
  /** The service could not be stopped. */
  public static final int SERVICE_STOP_ERROR = 3;
  /**
@@ -66,24 +58,23 @@
   */
  public static void main(String[] args)
  {
    int result = stopWindowsService(System.out, System.err);
    System.exit(filterExitCode(result));
    System.exit(filterExitCode(stopWindowsService(System.out, System.err)));
  }
  /**
   * Invokes the net stop on the service corresponding to this server, it writes
   * information and error messages in the provided streams.
   *
   * @return <CODE>SERVICE_STOP_SUCCESSFUL</CODE>,
   * <CODE>SERVICE_NOT_FOUND</CODE> or <CODE>SERVICE_STOP_ERROR</CODE>
   * depending on whether the service could be stopped or not.
   * @param  outStream  The stream to write standard output messages.
   * @param  errStream  The stream to write error messages.
   *         <CODE>SERVICE_NOT_FOUND</CODE> or <CODE>SERVICE_STOP_ERROR</CODE>
   *         depending on whether the service could be stopped or not.
   * @param outStream
   *          The stream to write standard output messages.
   * @param errStream
   *          The stream to write error messages.
   */
  public static int stopWindowsService(OutputStream outStream,
                           OutputStream errStream)
  public static int stopWindowsService(OutputStream outStream, OutputStream errStream)
  {
    int returnValue;
    NullOutputStream.wrapOrNullStream(outStream);
    PrintStream err = NullOutputStream.wrapOrNullStream(errStream);
    JDKLogging.disableLogging();
@@ -93,57 +84,49 @@
    {
      LocalizableMessage message = ERR_WINDOWS_SERVICE_NOT_FOUND.get();
      err.println(message);
      returnValue = SERVICE_NOT_FOUND;
      return SERVICE_NOT_FOUND;
    }
    String[] cmd;
    if (hasUAC())
    {
      cmd= new String[] {
          ConfigureWindowsService.getLauncherBinaryFullPath(),
          ConfigureWindowsService.LAUNCHER_OPTION,
          ConfigureWindowsService.getLauncherAdministratorBinaryFullPath(),
          ConfigureWindowsService.LAUNCHER_OPTION,
          "net",
          "stop",
          serviceName
      };
    }
    else
    {
      String[] cmd;
      if (hasUAC())
      cmd= new String[] {
          "net",
          "stop",
          serviceName
      };
    }
    /* Check if is a running service */
    try
    {
      switch (Runtime.getRuntime().exec(cmd).waitFor())
      {
        cmd= new String[] {
            ConfigureWindowsService.getLauncherBinaryFullPath(),
            ConfigureWindowsService.LAUNCHER_OPTION,
            ConfigureWindowsService.getLauncherAdministratorBinaryFullPath(),
            ConfigureWindowsService.LAUNCHER_OPTION,
            "net",
            "stop",
            serviceName
        };
      }
      else
      {
        cmd= new String[] {
            "net",
            "stop",
            serviceName
        };
      }
      /* Check if is a running service */
      try
      {
        int resultCode = Runtime.getRuntime().exec(cmd).waitFor();
        if (resultCode == 0)
        {
          returnValue = SERVICE_STOP_SUCCESSFUL;
        }
        else if (resultCode == 2)
        {
          returnValue = SERVICE_STOP_SUCCESSFUL;
        }
        else
        {
          returnValue = SERVICE_STOP_ERROR;
        }
      }
      catch (Throwable t)
      {
        LocalizableMessage message = ERR_WINDOWS_SERVICE_STOP_ERROR.get();
        err.println(message);
        err.println("Exception:" + t);
        returnValue = SERVICE_STOP_ERROR;
      case 0:
        return SERVICE_STOP_SUCCESSFUL;
      case 2:
        return SERVICE_STOP_SUCCESSFUL;
      default:
        return SERVICE_STOP_ERROR;
      }
    }
    return returnValue;
    catch (Throwable t)
    {
      LocalizableMessage message = ERR_WINDOWS_SERVICE_STOP_ERROR.get();
      err.println(message);
      err.println("Exception:" + t);
      return SERVICE_STOP_ERROR;
    }
  }
}