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

Violette Roche-Montane
26.15.2014 afa089fedd62a29826d57cc34293ad5e0e6a4efd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2008-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2011-2014 ForgeRock AS
 */
 
package org.opends.server.tools;
import java.io.*;
 
import org.forgerock.i18n.LocalizableMessage;
import org.opends.guitools.controlpanel.util.Utilities;
import org.opends.quicksetup.util.Utils;
import org.opends.server.core.DirectoryServer;
import org.opends.server.loggers.JDKLogging;
import org.opends.server.types.NullOutputStream;
import org.opends.server.util.DynamicConstants;
import org.opends.server.util.SetupUtils;
 
import com.forgerock.opendj.cli.*;
 
import static org.opends.messages.ToolMessages.*;
import static org.opends.server.util.ServerConstants.*;
import static org.opends.server.util.StaticUtils.*;
import static com.forgerock.opendj.util.OperatingSystem.hasUAC;
 
/**
  * This class is used to configure 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.
  *
  * Some comments about Vista:
  * In Vista, when we launch the subcommands that require administrator
  * privileges (enable, disable and cleanup) we cannot use the administrator
  * launcher binary directly from Java (see
  * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6410605) so we use
  * winlauncher.exe.
  * When we launch subcommands that required administrator privileges
  * we must launch a binary containing the manifest that specifies that we
  * require administrator privileges (requireAdministrator value): if UAC is
  * enabled, the user will be asked for confirmation.
  * To minimize the number of confirmation that the user must provide when
  * launching the state subcommand we will use a binary whose manifest does
  * not contain the requireAdministrator value.
  *
  * See the files under src/build-tools/windows for more details.
  */
public class 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.
   */
  public static final String LAUNCHER_OPTION = "run";
 
  private static int ERROR = 1;
 
  /**
   * Return codes for the method enableService.
   */
  /**
   * The service was successfully enabled.
   */
  public static final int SERVICE_ENABLE_SUCCESS = 0;
  /**
   * The service was already enabled.
   */
  public static final int SERVICE_ALREADY_ENABLED = 1;
  /**
   * The service name was already in use.
   */
  public static final int SERVICE_NAME_ALREADY_IN_USE = 2;
  /**
   * 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.
   */
  public static final int SERVICE_DISABLE_SUCCESS = 0;
  /**
   * The service was already disabled.
   */
  public static final int SERVICE_ALREADY_DISABLED = 1;
  /**
   * The service is marked for deletion.
   */
  public static final int SERVICE_MARKED_FOR_DELETION = 2;
  /**
   * An error occurred disabling the service.
   */
  public static final int SERVICE_DISABLE_ERROR = 3;
 
  /**
   * Return codes for the method serviceState.
   */
  /**
   * The service is enabled.
   */
  public static final int SERVICE_STATE_ENABLED = 0;
  /**
   * The service is disabled.
   */
  public static final int SERVICE_STATE_DISABLED = 1;
  /**
   * 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.
   */
  public static final int SERVICE_CLEANUP_SUCCESS = 0;
  /**
   * The service could not be found.
   */
  public static final int SERVICE_NOT_FOUND = 1;
  /**
   * An error occurred cleaning up the service.
   */
  public static final int SERVICE_CLEANUP_ERROR = 2;
  /**
   * 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.
   *
   * @param  args  The command-line arguments provided to this program.
   */
  public static void main(String[] args)
  {
    int result = configureWindowsService(args, System.out, System.err);
 
    System.exit(filterExitCode(result));
  }
 
  /**
   * 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.
   * @return the integer code describing if the operation could be completed or
   * not.
   */
  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);
    BooleanArgument enableService = null;
    BooleanArgument disableService = null;
    BooleanArgument serviceState = null;
    StringArgument cleanupService = null;
    BooleanArgument showUsage = null;
 
    try
    {
      enableService = new BooleanArgument("enableservice", 'e', "enableService",
          INFO_CONFIGURE_WINDOWS_SERVICE_DESCRIPTION_ENABLE.get());
      argParser.addArgument(enableService);
 
      disableService = new BooleanArgument("disableservice", 'd',
          "disableService",
          INFO_CONFIGURE_WINDOWS_SERVICE_DESCRIPTION_DISABLE.get());
      argParser.addArgument(disableService);
 
      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,
          INFO_SERVICE_NAME_PLACEHOLDER.get(), null, null,
          INFO_CONFIGURE_WINDOWS_SERVICE_DESCRIPTION_CLEANUP.get());
      argParser.addArgument(cleanupService);
 
      showUsage = CommonArguments.getShowUsage();
      argParser.addArgument(showUsage);
      argParser.setUsageArgument(showUsage, out);
    }
    catch (ArgumentException ae)
    {
      LocalizableMessage message = ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage());
 
      err.println(wrapText(message, MAX_LINE_WIDTH));
      returnValue = ERROR;
    }
 
    // Parse the command-line arguments provided to this program.
    if (returnValue == 0)
    {
      try
      {
        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;
      }
    }
 
    // If we should just display usage or version information,
    // then it is already done
    if ((returnValue == 0) && !argParser.usageOrVersionDisplayed())
    {
      /* Check that the user only asked for one argument */
      int nArgs = 0;
      if (enableService.isPresent())
      {
        nArgs++;
      }
      if (disableService.isPresent())
      {
        nArgs++;
      }
      if (serviceState.isPresent())
      {
        nArgs++;
      }
      if (cleanupService.isPresent())
      {
        nArgs++;
      }
      if (nArgs > 1)
      {
        LocalizableMessage message = 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;
      }
    }
 
    if ((returnValue == 0) && !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 returnValue;
  }
 
  /**
   * 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.
   */
  static String getServiceName()
  {
    String serviceName = null;
    String serverRoot = getServerRoot();
    String[] cmd = {
        getBinaryFullPath(),
        "state",
        serverRoot
    };
    try
    {
      Process p = Runtime.getRuntime().exec(cmd);
      BufferedReader stdout = new BufferedReader(
          new InputStreamReader(p.getInputStream()));
      boolean processDone = false;
      String s;
      while (!processDone)
      {
        try
        {
          p.exitValue();
          processDone = true;
        }
        catch (Throwable t)
        {
        }
        while ((s = stdout.readLine()) != null)
        {
          serviceName = s;
          if (serviceName.trim().length() == 0)
          {
            serviceName = null;
          }
        }
      }
    }
    catch (Throwable t)
    {
      serviceName = null;
    }
 
    return serviceName;
  }
 
  /**
   * 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.
   * @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.
   */
  public static int enableService(PrintStream out, PrintStream err)
  {
    LocalizableMessage serviceName = Utils.getCustomizedObject(
        "INFO_WINDOWS_SERVICE_NAME",
        INFO_WINDOWS_SERVICE_NAME.get(DynamicConstants.PRODUCT_NAME),
        LocalizableMessage.class);
    LocalizableMessage serviceDescription = Utils.getCustomizedObject(
        "INFO_WINDOWS_SERVICE_DESCRIPTION",
        INFO_WINDOWS_SERVICE_DESCRIPTION.get(getServerRoot()), LocalizableMessage.class);
    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.
   * @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.
   */
  public static int enableService(PrintStream out, PrintStream err,
      String serviceName, String serviceDescription)
  {
    int returnValue;
    LocalizableMessage msg;
    String serverRoot = getServerRoot();
 
    String[] cmd;
 
    if (hasUAC())
    {
      cmd = new String[] {
          getLauncherBinaryFullPath(),
          LAUNCHER_OPTION,
          getLauncherAdministratorBinaryFullPath(),
          LAUNCHER_OPTION,
          getBinaryFullPath(),
          "create",
          serverRoot,
          serviceName,
          serviceDescription,
          DEBUG_OPTION
      };
    }
    else
    {
      cmd = new String[] {
          getBinaryFullPath(),
          "create",
          serverRoot,
          serviceName,
          serviceDescription,
          DEBUG_OPTION
      };
    }
 
    try
    {
      boolean isServerRunning = Utilities.isServerRunning(
          new File(serverRoot));
 
      int resultCode = Runtime.getRuntime().exec(cmd).waitFor();
      switch (resultCode)
      {
      case 0:
        if (isServerRunning)
        {
          // 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);
          if (returnValue == 0)
          {
            returnValue = SERVICE_ENABLE_SUCCESS;
            msg = INFO_WINDOWS_SERVICE_SUCCESSULLY_ENABLED.get();
            out.println(wrapText(msg, MAX_LINE_WIDTH));
          }
          else
          {
            msg = ERR_WINDOWS_SERVICE_ENABLING_ERROR_STARTING_SERVER.get(
                returnValue);
            returnValue = SERVICE_ENABLE_ERROR;
            err.println(wrapText(msg, MAX_LINE_WIDTH));
          }
        }
        else
        {
          returnValue = SERVICE_ENABLE_SUCCESS;
          msg = INFO_WINDOWS_SERVICE_SUCCESSULLY_ENABLED.get();
          out.println(wrapText(msg, MAX_LINE_WIDTH));
        }
        break;
      case 1:
        returnValue = SERVICE_ALREADY_ENABLED;
        msg = INFO_WINDOWS_SERVICE_ALREADY_ENABLED.get();
        out.println(wrapText(msg, MAX_LINE_WIDTH));
        break;
      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;
      case 3:
        returnValue = SERVICE_ENABLE_ERROR;
        msg = ERR_WINDOWS_SERVICE_ENABLE_ERROR.get();
        err.println(wrapText(msg, MAX_LINE_WIDTH));
        break;
      default:
        returnValue = SERVICE_ENABLE_ERROR;
        msg = ERR_WINDOWS_SERVICE_ENABLE_ERROR.get();
        err.println(wrapText(msg, MAX_LINE_WIDTH));
      }
    }
    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 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.
   * @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.
   */
  public static int disableService(PrintStream out, PrintStream err)
  {
    int returnValue;
    LocalizableMessage msg;
    String serverRoot = getServerRoot();
    String[] cmd;
    if (hasUAC())
    {
      cmd = new String[] {
          getLauncherBinaryFullPath(),
          LAUNCHER_OPTION,
          getLauncherAdministratorBinaryFullPath(),
          LAUNCHER_OPTION,
          getBinaryFullPath(),
          "remove",
          serverRoot,
          DEBUG_OPTION
      };
    }
    else
    {
      cmd = new String[] {
        getBinaryFullPath(),
        "remove",
        serverRoot,
        DEBUG_OPTION
        };
    }
    try
    {
      int resultCode = Runtime.getRuntime().exec(cmd).waitFor();
      switch (resultCode)
      {
      case 0:
        returnValue = SERVICE_DISABLE_SUCCESS;
        msg = INFO_WINDOWS_SERVICE_SUCCESSULLY_DISABLED.get();
        out.println(msg);
        break;
      case 1:
        returnValue = SERVICE_ALREADY_DISABLED;
        msg = INFO_WINDOWS_SERVICE_ALREADY_DISABLED.get();
        out.println(msg);
        break;
      case 2:
        returnValue = SERVICE_MARKED_FOR_DELETION;
        msg = WARN_WINDOWS_SERVICE_MARKED_FOR_DELETION.get();
        out.println(msg);
        break;
      case 3:
        returnValue = SERVICE_DISABLE_ERROR;
        msg = ERR_WINDOWS_SERVICE_DISABLE_ERROR.get();
        err.println(msg);
        break;
      default:
        returnValue = SERVICE_DISABLE_ERROR;
        msg = ERR_WINDOWS_SERVICE_DISABLE_ERROR.get();
        err.println(msg);
      }
    }
    catch (Throwable t)
    {
      t.printStackTrace();
      returnValue = SERVICE_DISABLE_ERROR;
      msg = ERR_WINDOWS_SERVICE_DISABLE_ERROR.get();
      err.println(msg);
    }
    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.
   * @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.
   */
  public static int cleanupService(String serviceName, PrintStream out,
      PrintStream err)
  {
    int returnValue;
    LocalizableMessage msg;
    String[] cmd;
    if (hasUAC())
    {
      cmd = new String[] {
          getLauncherBinaryFullPath(),
          LAUNCHER_OPTION,
          getLauncherAdministratorBinaryFullPath(),
          LAUNCHER_OPTION,
          getBinaryFullPath(),
          "cleanup",
          serviceName,
          DEBUG_OPTION
      };
    }
    else
    {
      cmd = new String[] {
          getBinaryFullPath(),
          "cleanup",
          serviceName,
          DEBUG_OPTION
      };
    }
    try
    {
      int resultCode = Runtime.getRuntime().exec(cmd).waitFor();
      switch (resultCode)
      {
      case 0:
        returnValue = SERVICE_CLEANUP_SUCCESS;
        msg = INFO_WINDOWS_SERVICE_CLEANUP_SUCCESS.get(serviceName);
        out.println(msg);
        break;
      case 1:
        returnValue = SERVICE_NOT_FOUND;
        msg = ERR_WINDOWS_SERVICE_CLEANUP_NOT_FOUND.get(serviceName);
        err.println(msg);
        break;
      case 2:
        returnValue = SERVICE_CLEANUP_MARKED_FOR_DELETION;
        msg = WARN_WINDOWS_SERVICE_CLEANUP_MARKED_FOR_DELETION.get(serviceName);
        out.println(msg);
        break;
      case 3:
        returnValue = SERVICE_CLEANUP_ERROR;
        msg = ERR_WINDOWS_SERVICE_CLEANUP_ERROR.get(serviceName);
        err.println(msg);
        break;
      default:
        returnValue = SERVICE_CLEANUP_ERROR;
        msg = ERR_WINDOWS_SERVICE_CLEANUP_ERROR.get(serviceName);
        err.println(msg);
      }
    }
    catch (Throwable t)
    {
      returnValue = SERVICE_CLEANUP_ERROR;
      msg = ERR_WINDOWS_SERVICE_CLEANUP_ERROR.get(serviceName);
      err.println(msg);
      err.println("Exception:" + t.toString());
    }
    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.
    */
  public static int serviceState(PrintStream out, PrintStream err)
  {
    int returnValue;
    LocalizableMessage msg;
    String serviceName = null;
 
    String serverRoot = getServerRoot();
    String[] cmd = new String[] {
        getBinaryFullPath(),
        "state",
        serverRoot,
        DEBUG_OPTION
    };
 
    try
    {
      int resultCode = -1;
      ProcessBuilder pb = new ProcessBuilder(cmd);
      Process process = pb.start();
 
      BufferedReader stdout =
          new BufferedReader(new InputStreamReader(process.getInputStream()));
 
      boolean processDone = false;
      String s;
      while (!processDone)
      {
        try
        {
          resultCode = process.exitValue();
          processDone = true;
        }
        catch (Throwable t)
        {
        }
        while ((s = stdout.readLine()) != null)
        {
          if (s.trim().length() != 0)
          {
            serviceName = s;
          }
        }
      }
 
      switch (resultCode)
      {
      case 0:
        returnValue = SERVICE_STATE_ENABLED;
        if (out != null)
        {
          msg = INFO_WINDOWS_SERVICE_ENABLED.get(serviceName);
          out.println(msg);
        }
        break;
      case 1:
        returnValue = SERVICE_STATE_DISABLED;
        if (out != null)
        {
          msg = INFO_WINDOWS_SERVICE_DISABLED.get();
          out.println(msg);
        }
        break;
      case 2:
        returnValue = SERVICE_STATE_ERROR;
        if (err != null)
        {
          msg = ERR_WINDOWS_SERVICE_STATE_ERROR.get();
          err.println(msg);
        }
        break;
      default:
        returnValue = SERVICE_STATE_ERROR;
        if (err != null)
        {
          msg = ERR_WINDOWS_SERVICE_STATE_ERROR.get();
          err.println(msg);
        }
      }
    }
    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));
      }
    }
    return returnValue;
  }
 
  /**
   * Returns the Directory Server installation path in a user friendly
   * representation.
   * @return the Directory Server installation path in a user friendly
   * representation.
   */
  private static String getServerRoot()
  {
    String serverRoot = DirectoryServer.getServerRoot();
    File f = new File(serverRoot);
    try
    {
      /*
       * Do a best effort to avoid having a relative representation (for
       * instance to avoid having ../../../).
       */
      f = f.getCanonicalFile();
    }
    catch (IOException ioe)
    {
      /* This is a best effort to get the best possible representation of the
       * file: reporting the error is not necessary.
       */
    }
    serverRoot = f.toString();
    if (serverRoot.endsWith(File.separator))
    {
      serverRoot = serverRoot.substring(0, serverRoot.length() - 1);
    }
    return serverRoot;
  }
 
  /**
   * Returns the full path of the executable used by this class to perform
   * 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.
   */
  private static String getBinaryFullPath()
  {
    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.
   * @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.
   */
  public static String getLauncherAdministratorBinaryFullPath()
  {
    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.
   * @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.
   */
  public static String getLauncherBinaryFullPath()
  {
    return getServerRoot()+"\\lib\\winlauncher.exe";
  }
}