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

Violette Roche-Montane
13.48.2013 54ca1396ac0b7cbc7c697586bda8f0a4366e2be1
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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
/*
 * 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
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * 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
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  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-2009 Sun Microsystems, Inc.
 *      Portions Copyright 2012-2013 ForgeRock AS
 */
 
package org.opends.server.tools;
 
import org.opends.messages.Message;
import static org.opends.messages.ToolMessages.*;
 
import org.opends.server.api.ErrorLogPublisher;
import org.opends.server.config.ConfigException;
import org.opends.server.core.DirectoryServer;
import static org.opends.server.loggers.ErrorLogger.removeErrorLogPublisher;
 
import org.opends.server.protocols.asn1.ASN1Exception;
import static org.opends.server.tools.ToolConstants.*;
import org.opends.server.tools.tasks.TaskClient;
import org.opends.server.tools.tasks.TaskEntry;
import org.opends.server.types.InitializationException;
import org.opends.server.types.LDAPException;
import org.opends.server.util.BuildVersion;
import org.opends.server.util.StaticUtils;
import static org.opends.server.util.StaticUtils.filterExitCode;
import org.opends.server.util.args.ArgumentException;
import org.opends.server.util.args.BooleanArgument;
import org.opends.server.util.args.LDAPConnectionArgumentParser;
import org.opends.server.util.args.StringArgument;
import org.opends.server.util.cli.CLIException;
import org.opends.server.util.cli.ConsoleApplication;
import org.opends.server.util.cli.LDAPConnectionConsoleInteraction;
import org.opends.server.util.cli.Menu;
import org.opends.server.util.cli.MenuBuilder;
import org.opends.server.util.cli.MenuCallback;
import org.opends.server.util.cli.MenuResult;
import org.opends.server.util.table.TableBuilder;
import org.opends.server.util.table.TextTablePrinter;
 
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.opends.server.backends.task.TaskState;
 
/**
 * Tool for getting information and managing tasks in the Directory Server.
 */
public class ManageTasks extends ConsoleApplication {
 
  private static ErrorLogPublisher errorLogPublisher = null;
 
  // This CLI is always using the administration connector with SSL
  private static final boolean alwaysSSL = true;
 
  /**
   * The main method for TaskInfo tool.
   *
   * @param args The command-line arguments provided to this program.
   */
  public static void main(String[] args) {
    int retCode = mainTaskInfo(args, System.in, System.out, System.err);
 
    if (errorLogPublisher != null) {
      removeErrorLogPublisher(errorLogPublisher);
    }
 
    if (retCode != 0) {
      System.exit(filterExitCode(retCode));
    }
  }
 
  /**
   * Processes the command-line arguments and invokes the process for
   * displaying task information.
   *
   * @param args The command-line arguments provided to this program.
   * @return int return code
   */
  public static int mainTaskInfo(String[] args) {
    return mainTaskInfo(args, System.in, System.out, System.err);
  }
 
  /**
   * Processes the command-line arguments and invokes the export process.
   *
   * @param args             The command-line arguments provided to this
   * @param in               Input stream from which to solicit user input.
   * @param out              The output stream to use for standard output, or
   *                         {@code null} if standard output is not needed.
   * @param err              The output stream to use for standard error, or
   *                         {@code null} if standard error is not needed.
   * @param initializeServer Indicates whether to initialize the server.
   * @return int return code
   */
  public static int mainTaskInfo(String[] args,
                                 InputStream in,
                                 OutputStream out,
                                 OutputStream err,
                                 boolean initializeServer) {
    ManageTasks tool = new ManageTasks(in, out, err);
    return tool.process(args, initializeServer);
  }
 
  /**
   * Processes the command-line arguments and invokes the export process.
   *
   * @param args             The command-line arguments provided to this
   * @param in               Input stream from which to solicit user input.
   * @param out              The output stream to use for standard output, or
   *                         {@code null} if standard output is not needed.
   * @param err              The output stream to use for standard error, or
   *                         {@code null} if standard error is not needed.
 
   * @return int return code
   */
  public static int mainTaskInfo(String[] args,
                                 InputStream in,
                                 OutputStream out,
                                 OutputStream err) {
    return mainTaskInfo(args, in, out, err, true);
  }
 
  private static final int INDENT = 2;
 
  /**
   * ID of task for which to display details and exit.
   */
  private StringArgument task = null;
 
  /**
   * Indicates print summary and exit.
   */
  private BooleanArgument summary = null;
 
  /**
   * ID of task to cancel.
   */
  private StringArgument cancel = null;
 
  /**
   * Argument used to request non-interactive behavior.
   */
  private BooleanArgument noPrompt = null;
 
  /**
   * Accesses the directory's task backend.
   */
  private TaskClient taskClient;
 
  /**
   * Constructs a parameterized instance.
   *
   * @param in               Input stream from which to solicit user input.
   * @param out              The output stream to use for standard output, or
   *                         {@code null} if standard output is not needed.
   * @param err              The output stream to use for standard error, or
   *                         {@code null} if standard error is not needed.
   */
  public ManageTasks(InputStream in, OutputStream out, OutputStream err) {
    super(in, out, err);
  }
 
  /**
   * Processes the command-line arguments and invokes the export process.
   *
   * @param args       The command-line arguments provided to this
   *                   program.
   * @return The error code.
   */
  public int process(String[] args)
  {
    return process(args, true);
  }
 
  /**
   * Processes the command-line arguments and invokes the export process.
   *
   * @param args       The command-line arguments provided to this
   *                   program.
   * @param initializeServer  Indicates whether to initialize the server.
   * @return The error code.
   */
  public int process(String[] args, boolean initializeServer)
  {
    if (initializeServer)
    {
      DirectoryServer.bootstrapClient();
    }
 
    // Create the command-line argument parser for use with this program.
    LDAPConnectionArgumentParser argParser = new LDAPConnectionArgumentParser(
            "org.opends.server.tools.TaskInfo",
            INFO_TASKINFO_TOOL_DESCRIPTION.get(),
            false, null, alwaysSSL);
 
    // Initialize all the command-line argument types and register them with the
    // parser.
    try {
 
       StringArgument propertiesFileArgument = new StringArgument(
          "propertiesFilePath", null, OPTION_LONG_PROP_FILE_PATH, false, false,
          true, INFO_PROP_FILE_PATH_PLACEHOLDER.get(), null, null,
          INFO_DESCRIPTION_PROP_FILE_PATH.get());
      argParser.addArgument(propertiesFileArgument);
      argParser.setFilePropertiesArgument(propertiesFileArgument);
 
      BooleanArgument noPropertiesFileArgument = new BooleanArgument(
          "noPropertiesFileArgument", null, OPTION_LONG_NO_PROP_FILE,
          INFO_DESCRIPTION_NO_PROP_FILE.get());
      argParser.addArgument(noPropertiesFileArgument);
      argParser.setNoPropertiesFileArgument(noPropertiesFileArgument);
 
      task = new StringArgument(
              "info", 'i', "info",
              false, true, INFO_TASK_ID_PLACEHOLDER.get(),
              INFO_TASKINFO_TASK_ARG_DESCRIPTION.get());
      argParser.addArgument(task);
 
      cancel = new StringArgument(
              "cancel", 'c', "cancel",
              false, true, INFO_TASK_ID_PLACEHOLDER.get(),
              INFO_TASKINFO_TASK_ARG_CANCEL.get());
      argParser.addArgument(cancel);
 
      summary = new BooleanArgument(
              "summary", 's', "summary",
              INFO_TASKINFO_SUMMARY_ARG_DESCRIPTION.get());
      argParser.addArgument(summary);
 
      noPrompt = new BooleanArgument(
              OPTION_LONG_NO_PROMPT,
              OPTION_SHORT_NO_PROMPT,
              OPTION_LONG_NO_PROMPT,
              INFO_DESCRIPTION_NO_PROMPT.get());
      argParser.addArgument(noPrompt);
 
      BooleanArgument displayUsage = new BooleanArgument(
              "help", OPTION_SHORT_HELP,
              OPTION_LONG_HELP,
              INFO_DESCRIPTION_USAGE.get());
      argParser.addArgument(displayUsage);
      argParser.setUsageArgument(displayUsage);
    }
    catch (ArgumentException ae) {
      Message message = ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage());
      println(message);
      return 1;
    }
 
    try
    {
      argParser.getArguments().initArgumentsWithConfiguration();
    }
    catch (ConfigException ce)
    {
      // Ignore.
    }
 
    // Parse the command-line arguments provided to this program.
    try {
      argParser.parseArguments(args);
      StaticUtils.checkOnlyOneArgPresent(task, summary, cancel);
    }
    catch (ArgumentException ae) {
      Message message = ERR_ERROR_PARSING_ARGS.get(ae.getMessage());
      println(message);
      println(argParser.getUsageMessage());
      return 1;
    }
 
    if (!argParser.usageOrVersionDisplayed()) {
      // Checks the version - if upgrade required, the tool is unusable
      try
      {
        BuildVersion.checkVersionMismatch();
      }
      catch (InitializationException e)
      {
        println(e.getMessageObject());
        return 1;
      }
 
      try {
        LDAPConnectionConsoleInteraction ui =
                new LDAPConnectionConsoleInteraction(
                        this, argParser.getArguments());
 
        taskClient = new TaskClient(argParser.connect(ui,
                getOutputStream(), getErrorStream()));
 
        if (isMenuDrivenMode()) {
 
          // Keep prompting the user until they specify quit of
          // there is a fatal exception
          while (true) {
            getOutputStream().println();
            Menu<Void> menu = getSummaryMenu();
            MenuResult<Void> result = menu.run();
            if (result.isQuit()) {
              return 0;
            }
          }
 
        } else if (task.isPresent()) {
          getOutputStream().println();
          MenuResult<TaskEntry> r =
                  new PrintTaskInfo(task.getValue()).invoke(this);
          if (r.isAgain()) return 1;
        } else if (summary.isPresent()) {
          getOutputStream().println();
          printSummaryTable();
        } else if (cancel.isPresent()) {
          MenuResult<TaskEntry> r =
                  new CancelTask(cancel.getValue()).invoke(this);
          if (r.isAgain()) return 1;
        } else if (!isInteractive()) {
           // no-prompt option
           getOutputStream().println();
           printSummaryTable();
           return 0;
        }
 
      } catch (LDAPConnectionException lce) {
        println(INFO_TASKINFO_LDAP_EXCEPTION.get(lce.getMessageObject()));
        return 1;
      } catch (Exception e) {
        println(Message.raw(e.getMessage()));
        return 1;
      }
    }
    return 0;
  }
 
  /**
   * {@inheritDoc}
   */
  @Override
  public boolean isAdvancedMode() {
    return false;
  }
 
  /**
   * {@inheritDoc}
   */
  @Override
  public boolean isInteractive() {
    return !noPrompt.isPresent();
  }
 
  /**
   * {@inheritDoc}
   */
  @Override
  public boolean isMenuDrivenMode() {
    return !task.isPresent() && !cancel.isPresent() && !summary.isPresent() &&
           !noPrompt.isPresent();
  }
 
  /**
   * {@inheritDoc}
   */
  @Override
  public boolean isQuiet() {
    return false;
  }
 
  /**
   * {@inheritDoc}
   */
  @Override
  public boolean isScriptFriendly() {
    return false;
  }
 
  /**
   * {@inheritDoc}
   */
  @Override
  public boolean isVerbose() {
    return false;
  }
 
  /**
   * Creates the summary table.
   *
   * @throws IOException if there is a problem with screen I/O
   * @throws LDAPException if there is a problem getting information
   *         out to the directory
   * @throws ASN1Exception if there is a problem with the encoding
   */
  private void printSummaryTable()
          throws LDAPException, IOException, ASN1Exception {
    List<TaskEntry> entries = taskClient.getTaskEntries();
    if (entries.size() > 0) {
      TableBuilder table = new TableBuilder();
      Map<String, TaskEntry> mapIdToEntry =
              new TreeMap<String, TaskEntry>();
      for (TaskEntry entry : entries) {
        String taskId = entry.getId();
        if (taskId != null) {
          mapIdToEntry.put(taskId, entry);
        }
      }
 
      table.appendHeading(INFO_TASKINFO_FIELD_ID.get());
      table.appendHeading(INFO_TASKINFO_FIELD_TYPE.get());
      table.appendHeading(INFO_TASKINFO_FIELD_STATUS.get());
      for (String taskId : mapIdToEntry.keySet()) {
        TaskEntry entryWrapper = mapIdToEntry.get(taskId);
        table.startRow();
        table.appendCell(taskId);
        table.appendCell(entryWrapper.getType());
        table.appendCell(entryWrapper.getState());
      }
      StringWriter sw = new StringWriter();
      TextTablePrinter tablePrinter = new TextTablePrinter(sw);
      tablePrinter.setIndentWidth(INDENT);
      tablePrinter.setTotalWidth(80);
      table.print(tablePrinter);
      getOutputStream().println(Message.raw(sw.getBuffer()));
    } else {
      getOutputStream().println(INFO_TASKINFO_NO_TASKS.get());
      getOutputStream().println();
    }
  }
 
  /**
   * Creates the summary table.
   *
   * @return list of strings of IDs of all the tasks in the table in order
   *         of the indexes printed in the table
   * @throws IOException if there is a problem with screen I/O
   * @throws LDAPException if there is a problem getting information
   *         out to the directory
   * @throws ASN1Exception if there is a problem with the encoding
   */
  private Menu<Void> getSummaryMenu()
          throws LDAPException, IOException, ASN1Exception {
    List<String> taskIds = new ArrayList<String>();
    List<Integer> cancelableIndices = new ArrayList<Integer>();
    List<TaskEntry> entries = taskClient.getTaskEntries();
    MenuBuilder<Void> menuBuilder = new MenuBuilder<Void>(this);
    if (entries.size() > 0) {
      Map<String, TaskEntry> mapIdToEntry =
              new TreeMap<String, TaskEntry>();
      for (TaskEntry entry : entries) {
        String taskId = entry.getId();
        if (taskId != null) {
          mapIdToEntry.put(taskId, entry);
        }
      }
 
      menuBuilder.setColumnHeadings(
              INFO_TASKINFO_FIELD_ID.get(),
              INFO_TASKINFO_FIELD_TYPE.get(),
              INFO_TASKINFO_FIELD_STATUS.get());
      menuBuilder.setColumnWidths(null, null, 0);
      int index = 0;
      for (final String taskId : mapIdToEntry.keySet()) {
        taskIds.add(taskId);
        final TaskEntry taskEntry = mapIdToEntry.get(taskId);
        menuBuilder.addNumberedOption(
                Message.raw(taskEntry.getId()),
                new TaskDrilldownMenu(taskId),
                taskEntry.getType(), taskEntry.getState());
        index++;
        if (taskEntry.isCancelable()) {
          cancelableIndices.add(index);
        }
      }
    } else {
      getOutputStream().println(INFO_TASKINFO_NO_TASKS.get());
      getOutputStream().println();
    }
 
    menuBuilder.addCharOption(
            INFO_TASKINFO_CMD_REFRESH_CHAR.get(),
            INFO_TASKINFO_CMD_REFRESH.get(),
            new PrintSummaryTop());
 
    if (cancelableIndices.size() > 0) {
      menuBuilder.addCharOption(
              INFO_TASKINFO_CMD_CANCEL_CHAR.get(),
              INFO_TASKINFO_CMD_CANCEL.get(),
              new CancelTaskTop(taskIds, cancelableIndices));
    }
    menuBuilder.addQuitOption();
 
    return menuBuilder.toMenu();
  }
 
  /**
   * Gets the client that can be used to interact with the task backend.
   *
   * @return TaskClient for interacting with the task backend.
   */
  public TaskClient getTaskClient() {
    return this.taskClient;
  }
 
  /**
   * Base for callbacks that implement top level menu items.
   */
  static abstract private class TopMenuCallback
          implements MenuCallback<Void> {
 
    /**
     * {@inheritDoc}
     */
    @Override
    public MenuResult<Void> invoke(ConsoleApplication app) throws CLIException {
      return invoke((ManageTasks)app);
    }
 
    /**
     * Called upon task invocation.
     *
     * @param app this console application
     * @return MessageResult result of task
     * @throws CLIException if there is a problem
     */
    protected abstract MenuResult<Void> invoke(ManageTasks app)
            throws CLIException;
 
  }
 
  /**
   * Base for callbacks that manage task entries.
   */
  static abstract private class TaskOperationCallback
          implements MenuCallback<TaskEntry> {
 
    /** ID of the task to manage. */
    protected String taskId;
 
    /**
     * Constructs a parameterized instance.
     *
     * @param taskId if the task to examine
     */
    public TaskOperationCallback(String taskId) {
      this.taskId = taskId;
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    public MenuResult<TaskEntry> invoke(ConsoleApplication app)
            throws CLIException
    {
      return invoke((ManageTasks)app);
    }
 
    /**
     * {@inheritDoc}
     */
    protected abstract MenuResult<TaskEntry> invoke(ManageTasks app)
            throws CLIException;
 
  }
 
  /**
   * Executable for printing a task summary table.
   */
  static private class PrintSummaryTop extends TopMenuCallback {
 
    @Override
    public MenuResult<Void> invoke(ManageTasks app)
            throws CLIException
    {
      // Since the summary table is reprinted every time the
      // user enters the top level this task just returns
      // 'success'
      return MenuResult.success();
    }
  }
 
  /**
   * Exectuable for printing a particular task's details.
   */
  static private class TaskDrilldownMenu extends TopMenuCallback {
 
    private String taskId;
 
    /**
     * Constructs a parameterized instance.
     *
     * @param taskId of the task for which information will be displayed
     */
    public TaskDrilldownMenu(String taskId) {
      this.taskId = taskId;
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    public MenuResult<Void> invoke(ManageTasks app) throws CLIException {
      MenuResult<TaskEntry> res = new PrintTaskInfo(taskId).invoke(app);
      TaskEntry taskEntry = res.getValue();
      if (taskEntry != null) {
        while (true) {
          try {
            taskEntry = app.getTaskClient().getTaskEntry(taskId);
 
            // Show the menu
            MenuBuilder<TaskEntry> menuBuilder =
                    new MenuBuilder<TaskEntry>(app);
            menuBuilder.addBackOption(true);
            menuBuilder.addCharOption(
                    INFO_TASKINFO_CMD_REFRESH_CHAR.get(),
                    INFO_TASKINFO_CMD_REFRESH.get(),
                    new PrintTaskInfo(taskId));
            List<Message> logs = taskEntry.getLogMessages();
            if (logs != null && logs.size() > 0) {
              menuBuilder.addCharOption(
                      INFO_TASKINFO_CMD_VIEW_LOGS_CHAR.get(),
                      INFO_TASKINFO_CMD_VIEW_LOGS.get(),
                      new ViewTaskLogs(taskId));
            }
            if (taskEntry.isCancelable() && !taskEntry.isDone()) {
              menuBuilder.addCharOption(
                      INFO_TASKINFO_CMD_CANCEL_CHAR.get(),
                      INFO_TASKINFO_CMD_CANCEL.get(),
                      new CancelTask(taskId));
            }
            menuBuilder.addQuitOption();
            Menu<TaskEntry> menu = menuBuilder.toMenu();
            MenuResult<TaskEntry> result = menu.run();
            if (result.isCancel()) {
              break;
            } else if (result.isQuit()) {
              System.exit(0);
            }
          } catch (Exception e) {
            app.println(Message.raw(e.getMessage()));
          }
        }
      } else {
        app.println(ERR_TASKINFO_UNKNOWN_TASK_ENTRY.get(taskId));
      }
      return MenuResult.success();
    }
 
  }
 
  /**
   * Exectuable for printing a particular task's details.
   */
  static private class PrintTaskInfo extends TaskOperationCallback {
 
    /**
     * Constructs a parameterized instance.
     *
     * @param taskId of the task for which information will be printed
     */
    public PrintTaskInfo(String taskId) {
      super(taskId);
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    public MenuResult<TaskEntry> invoke(ManageTasks app)
            throws CLIException
    {
      Message m;
      TaskEntry taskEntry;
      try {
        taskEntry = app.getTaskClient().getTaskEntry(taskId);
 
        TableBuilder table = new TableBuilder();
        table.appendHeading(INFO_TASKINFO_DETAILS.get());
 
        table.startRow();
        table.appendCell(INFO_TASKINFO_FIELD_ID.get());
        table.appendCell(taskEntry.getId());
 
        table.startRow();
        table.appendCell(INFO_TASKINFO_FIELD_TYPE.get());
        table.appendCell(taskEntry.getType());
 
        table.startRow();
        table.appendCell(INFO_TASKINFO_FIELD_STATUS.get());
        table.appendCell(taskEntry.getState());
 
        if (TaskState.isRecurring(taskEntry.getTaskState())) {
          table.startRow();
          table.appendCell(INFO_TASKINFO_FIELD_SCHEDULED_START.get());
          m = taskEntry.getScheduleTab();
          table.appendCell(m);
        } else {
          table.startRow();
          table.appendCell(INFO_TASKINFO_FIELD_SCHEDULED_START.get());
          m = taskEntry.getScheduledStartTime();
          if (m == null || m.equals(Message.EMPTY)) {
            table.appendCell(INFO_TASKINFO_IMMEDIATE_EXECUTION.get());
          } else {
            table.appendCell(m);
          }
 
          table.startRow();
          table.appendCell(INFO_TASKINFO_FIELD_ACTUAL_START.get());
          table.appendCell(taskEntry.getActualStartTime());
 
          table.startRow();
          table.appendCell(INFO_TASKINFO_FIELD_COMPLETION_TIME.get());
          table.appendCell(taskEntry.getCompletionTime());
        }
 
        writeMultiValueCells(
                table,
                INFO_TASKINFO_FIELD_DEPENDENCY.get(),
                taskEntry.getDependencyIds());
 
        table.startRow();
        table.appendCell(INFO_TASKINFO_FIELD_FAILED_DEPENDENCY_ACTION.get());
        m = taskEntry.getFailedDependencyAction();
        table.appendCell(m != null ? m : INFO_TASKINFO_NONE.get());
 
        writeMultiValueCells(
                table,
                INFO_TASKINFO_FIELD_NOTIFY_ON_COMPLETION.get(),
                taskEntry.getCompletionNotificationEmailAddresses(),
                INFO_TASKINFO_NONE_SPECIFIED.get());
 
        writeMultiValueCells(
                table,
                INFO_TASKINFO_FIELD_NOTIFY_ON_ERROR.get(),
                taskEntry.getErrorNotificationEmailAddresses(),
                INFO_TASKINFO_NONE_SPECIFIED.get());
 
        StringWriter sw = new StringWriter();
        TextTablePrinter tablePrinter = new TextTablePrinter(sw);
        tablePrinter.setTotalWidth(80);
        tablePrinter.setIndentWidth(INDENT);
        tablePrinter.setColumnWidth(1, 0);
        table.print(tablePrinter);
        app.getOutputStream().println();
        app.getOutputStream().println(Message.raw(sw.getBuffer().toString()));
 
        // Create a table for the task options
        table = new TableBuilder();
        table.appendHeading(INFO_TASKINFO_OPTIONS.get(taskEntry.getType()));
        Map<Message,List<String>> taskSpecificAttrs =
                taskEntry.getTaskSpecificAttributeValuePairs();
        for (Message attrName : taskSpecificAttrs.keySet()) {
          table.startRow();
          table.appendCell(attrName);
          List<String> values = taskSpecificAttrs.get(attrName);
          if (values.size() > 0) {
            table.appendCell(values.get(0));
          }
          if (values.size() > 1) {
            for (int i = 1; i < values.size(); i++) {
              table.startRow();
              table.appendCell();
              table.appendCell(values.get(i));
            }
          }
        }
        sw = new StringWriter();
        tablePrinter = new TextTablePrinter(sw);
        tablePrinter.setTotalWidth(80);
        tablePrinter.setIndentWidth(INDENT);
        tablePrinter.setColumnWidth(1, 0);
        table.print(tablePrinter);
        app.getOutputStream().println(Message.raw(sw.getBuffer().toString()));
 
        // Print the last log message if any
        List<Message> logs = taskEntry.getLogMessages();
        if (logs != null && logs.size() > 0) {
 
          // Create a table for the last log entry
          table = new TableBuilder();
          table.appendHeading(INFO_TASKINFO_FIELD_LAST_LOG.get());
          table.startRow();
          table.appendCell(logs.get(logs.size() - 1));
 
          sw = new StringWriter();
          tablePrinter = new TextTablePrinter(sw);
          tablePrinter.setTotalWidth(80);
          tablePrinter.setIndentWidth(INDENT);
          tablePrinter.setColumnWidth(0, 0);
          table.print(tablePrinter);
          app.getOutputStream().println(Message.raw(sw.getBuffer().toString()));
        }
 
        app.getOutputStream().println();
      } catch (Exception e) {
        app.println(ERR_TASKINFO_RETRIEVING_TASK_ENTRY.get(
                    taskId, e.getMessage()));
        return MenuResult.again();
      }
      return MenuResult.success(taskEntry);
    }
 
    /**
     * Writes an attribute and associated values to the table.
     * @param table of task details
     * @param fieldLabel of attribute
     * @param values of the attribute
     */
    private void writeMultiValueCells(TableBuilder table,
                                      Message fieldLabel,
                                      List<?> values) {
      writeMultiValueCells(table, fieldLabel, values, INFO_TASKINFO_NONE.get());
    }
 
    /**
     * Writes an attribute and associated values to the table.
     *
     * @param table of task details
     * @param fieldLabel of attribute
     * @param values of the attribute
     * @param noneLabel label for the value column when there are no values
     */
    private void writeMultiValueCells(TableBuilder table,
                                      Message fieldLabel,
                                      List<?> values,
                                      Message noneLabel) {
      table.startRow();
      table.appendCell(fieldLabel);
      if (values.isEmpty()) {
        table.appendCell(noneLabel);
      } else {
        table.appendCell(values.get(0));
      }
      if (values.size() > 1) {
        for (int i = 1; i < values.size(); i++) {
          table.startRow();
          table.appendCell();
          table.appendCell(values.get(i));
        }
      }
    }
  }
 
  /**
   * Exectuable for printing a particular task's details.
   */
  static private class ViewTaskLogs extends TaskOperationCallback {
 
    /**
     * Constructs a parameterized instance.
     *
     * @param taskId of the task for which log records will be printed
     */
    public ViewTaskLogs(String taskId) {
      super(taskId);
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    protected MenuResult<TaskEntry> invoke(ManageTasks app)
            throws CLIException
    {
      TaskEntry taskEntry = null;
      try {
        taskEntry = app.getTaskClient().getTaskEntry(taskId);
        List<Message> logs = taskEntry.getLogMessages();
        app.getOutputStream().println();
 
        // Create a table for the last log entry
        TableBuilder table = new TableBuilder();
        table.appendHeading(INFO_TASKINFO_FIELD_LOG.get());
        if (logs != null && logs.size() > 0) {
          for (Message log : logs) {
            table.startRow();
            table.appendCell(log);
          }
        } else {
          table.startRow();
          table.appendCell(INFO_TASKINFO_NONE.get());
        }
        StringWriter sw = new StringWriter();
        TextTablePrinter tablePrinter = new TextTablePrinter(sw);
        tablePrinter.setTotalWidth(80);
        tablePrinter.setIndentWidth(INDENT);
        tablePrinter.setColumnWidth(0, 0);
        table.print(tablePrinter);
        app.getOutputStream().println(Message.raw(sw.getBuffer().toString()));
        app.getOutputStream().println();
      } catch (Exception e) {
        app.println(ERR_TASKINFO_ACCESSING_LOGS.get(taskId, e.getMessage()));
      }
      return MenuResult.success(taskEntry);
    }
  }
 
  /**
   * Executable for canceling a particular task.
   */
  static private class CancelTaskTop extends TopMenuCallback {
 
    private List<String> taskIds;
    private List<Integer> cancelableIndices;
 
    /**
     * Constructs a parameterized instance.
     *
     * @param taskIds of all known tasks
     * @param cancelableIndices list of integers whose elements represent
     *        the indices of <code>taskIds</code> that are cancelable
     */
    public CancelTaskTop(List<String> taskIds,
                         List<Integer> cancelableIndices) {
      this.taskIds = taskIds;
      this.cancelableIndices = cancelableIndices;
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    public MenuResult<Void> invoke(ManageTasks app)
            throws CLIException
    {
      if (taskIds != null && taskIds.size() > 0) {
        if (cancelableIndices != null && cancelableIndices.size() > 0) {
 
          // Prompt for the task number
          Integer index = null;
          String line = app.readLineOfInput(
                  INFO_TASKINFO_CMD_CANCEL_NUMBER_PROMPT.get(
                          cancelableIndices.get(0)));
          if (line.length() == 0) {
            line = String.valueOf(cancelableIndices.get(0));
          }
          try {
            int i = Integer.parseInt(line);
            if (!cancelableIndices.contains(i)) {
              app.println(ERR_TASKINFO_NOT_CANCELABLE_TASK_INDEX.get(i));
            } else {
              index = i - 1;
            }
          } catch (NumberFormatException nfe) {
            // ignore;
          }
          if (index != null) {
            String taskId = taskIds.get(index);
            try {
              CancelTask ct = new CancelTask(taskId);
              MenuResult<TaskEntry> result = ct.invoke(app);
              if (result.isSuccess()) {
                return MenuResult.success();
              } else {
                return MenuResult.again();
              }
            } catch (Exception e) {
              app.println(ERR_TASKINFO_CANCELING_TASK.get(
                          taskId, e.getMessage()));
              return MenuResult.again();
            }
          } else {
            app.println(ERR_TASKINFO_INVALID_MENU_KEY.get(line));
            return MenuResult.again();
          }
        } else {
          app.println(INFO_TASKINFO_NO_CANCELABLE_TASKS.get());
          return MenuResult.cancel();
        }
      } else {
        app.println(INFO_TASKINFO_NO_TASKS.get());
        return MenuResult.cancel();
      }
    }
 
  }
 
  /**
   * Executable for canceling a particular task.
   */
  static private class CancelTask extends TaskOperationCallback {
 
    /**
     * Constructs a parameterized instance.
     *
     * @param taskId of the task to cancel
     */
    public CancelTask(String taskId) {
      super(taskId);
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    public MenuResult<TaskEntry> invoke(ManageTasks app)
            throws CLIException
    {
      try {
        TaskEntry entry = app.getTaskClient().getTaskEntry(taskId);
        if (entry.isCancelable()) {
          app.getTaskClient().cancelTask(taskId);
          app.println(INFO_TASKINFO_CMD_CANCEL_SUCCESS.get(taskId));
          return MenuResult.success(entry);
        } else {
          app.println(ERR_TASKINFO_TASK_NOT_CANCELABLE_TASK.get(taskId));
          return MenuResult.again();
        }
      } catch (Exception e) {
        app.println(ERR_TASKINFO_CANCELING_TASK.get(
                taskId, e.getMessage()));
        return MenuResult.again();
      }
    }
 
  }
 
}