use of com.terran4j.commons.jfinger.CommandExecutor in project commons by terran4j.
the class CommandLineService method execute.
private void execute(String groupName, String commandName, CommandDefine command, String[] args, PrintStream out) throws BusinessException {
Options options = new Options();
List<CommandOptionDefine> optionConfigs = command.getOptions();
if (optionConfigs != null && optionConfigs.size() > 0) {
for (CommandOptionDefine optionConfig : optionConfigs) {
String key = optionConfig.getKey();
String name = optionConfig.getName();
String desc = optionConfig.getDesc();
OptionType type = optionConfig.getType();
if (type == OptionType.BOOLEAN) {
options.addOption(key, name, false, desc);
} else if (type == OptionType.PROPERTIES) {
Option option = //
Option.builder(key).argName("property=value").numberOfArgs(5).valueSeparator('=').desc(//
desc).build();
options.addOption(option);
} else {
Builder builder = Option.builder(key).hasArg();
if (!StringUtils.isEmpty(name)) {
builder = builder.longOpt(name);
}
Option option = builder.desc(desc).build();
options.addOption(option);
}
}
}
CommandLine commandLine = null;
try {
commandLine = parser.parse(options, args);
} catch (UnrecognizedOptionException e) {
String optionKey = e.getOption();
out.println("无效的命令行选项: " + optionKey);
out.println(getHelp(groupName, commandName));
return;
} catch (ParseException e) {
out.println("解析命令出错:" + e.getMessage());
out.println(getHelp(groupName, commandName));
return;
}
CommandExecutor executor = command.getExecutor();
CommandInterpreter ci = new CommandInterpreterImpl(out, commandLine, command);
if (optionConfigs != null && optionConfigs.size() > 0) {
for (CommandOptionDefine optionConfig : optionConfigs) {
if (optionConfig.isRequired() && optionConfig.getType() != OptionType.BOOLEAN) {
String key = optionConfig.getKey();
String name = optionConfig.getName();
String value = ci.getOption(key);
if (value == null) {
throw //
new CommandException(CommandErrorCode.OPTION_KEY_EMPTY.getName()).put("group", //
groupName).put("commandName", //
commandName).put("optionKey", //
key).put("optionName", //
name).setMessage("命令 [${group} ${commandName}] 需要 ${optionName} 选项," + "请在命令后面附上 -${optionKey} [${optionName}]");
}
}
}
}
executor.execute(ci);
}
Aggregations