1 package org.cyclopsgroup.jmxterm.cc;
2
3 import org.apache.commons.lang3.Validate;
4 import org.cyclopsgroup.jcli.ArgumentProcessor;
5 import org.cyclopsgroup.jcli.annotation.Argument;
6 import org.cyclopsgroup.jcli.annotation.Cli;
7 import org.cyclopsgroup.jcli.annotation.MultiValue;
8 import org.cyclopsgroup.jmxterm.Command;
9 import org.cyclopsgroup.jmxterm.io.RuntimeIOException;
10
11 import java.io.IOException;
12 import java.io.PrintWriter;
13 import java.util.ArrayList;
14 import java.util.Collections;
15 import java.util.List;
16
17
18
19
20
21
22 @Cli(name = "help", description = "Display available commands or usage of a command",
23 note = "Run \"help [command1] [command2] ...\" to display usage or certain command(s). Help without argument shows list of available commands")
24 public class HelpCommand extends Command {
25 private List<String> argNames = Collections.emptyList();
26
27 private CommandCenter commandCenter = null;
28
29 @Override
30 public void execute() {
31 Validate.notNull(commandCenter, "Command center hasn't been set yet");
32 if (argNames.isEmpty()) {
33 List<String> commandNames = new ArrayList<String>(commandCenter.getCommandNames());
34 Collections.sort(commandNames);
35 getSession().output.printMessage("following commands are available to use:");
36 for (String commandName : commandNames) {
37 Class<? extends Command> commandType = commandCenter.getCommandType(commandName);
38 org.cyclopsgroup.jcli.spi.Cli cli =
39 ArgumentProcessor.forType(commandType).createParsingContext().cli();
40 getSession().output.println(String.format("%-8s - %s", commandName, cli.getDescription()));
41 }
42 } else {
43 for (String argName : argNames) {
44 Class<? extends Command> commandType = commandCenter.getCommandType(argName);
45 if (commandType == null) {
46 throw new IllegalArgumentException("Command " + argName + " is not found");
47 }
48 ArgumentProcessor<? extends Command> ap = ArgumentProcessor.forType(commandType);
49 try {
50 ap.printHelp(new PrintWriter(System.out, true));
51 } catch (IOException e) {
52 throw new RuntimeIOException("Can't print help message", e);
53 }
54 }
55 }
56 }
57
58
59
60
61 @MultiValue(listType = ArrayList.class)
62 @Argument
63 public final void setArgNames(List<String> argNames) {
64 Validate.notNull(argNames, "argNames can't be NULL");
65 this.argNames = argNames;
66 }
67
68
69
70
71 final void setCommandCenter(CommandCenter commandCenter) {
72 Validate.notNull(commandCenter, "commandCenter can't be NULL");
73 this.commandCenter = commandCenter;
74 }
75 }