1 package org.openecomp.core.tools.commands;
3 import static org.openecomp.core.tools.commands.Command.COMMAND_OPTION;
4 import static org.openecomp.core.tools.util.Utils.printMessage;
6 import java.util.EnumMap;
8 import java.util.Optional;
9 import org.apache.commons.cli.CommandLine;
10 import org.apache.commons.cli.DefaultParser;
11 import org.apache.commons.cli.Option;
12 import org.apache.commons.cli.Options;
13 import org.apache.commons.cli.ParseException;
14 import org.openecomp.core.tools.exportinfo.ExportDataCommand;
15 import org.openecomp.core.tools.importinfo.ImportDataCommand;
16 import org.openecomp.sdc.logging.api.Logger;
17 import org.openecomp.sdc.logging.api.LoggerFactory;
19 public class CommandsHolder {
21 private static final Logger LOGGER = LoggerFactory.getLogger(CommandsHolder.class);
22 private static final Options OPTIONS = new Options();
23 private static final Map<CommandName, Command> COMMANDS = new EnumMap<>(CommandName.class);
27 Option.builder(COMMAND_OPTION).hasArg().argName("command").desc("command name, mandatory").build());
31 private CommandsHolder() {
34 private static void registerCommands() {
35 new SetHealingFlag().register();
36 new ExportDataCommand().register();
37 new ImportDataCommand().register();
38 new HealAll().register();
39 new PopulateUserPermissions().register();
40 new AddContributorCommand().register();
41 new CleanUserDataCommand().register();
42 new DeletePublicVersionCommand().register();
43 new SetHealingFlagByItemVersionCommand().register();
46 public static Optional<Command> getCommand(String[] args) {
47 CommandLine cmd = parseArgs(args);
48 return cmd == null || !cmd.hasOption(COMMAND_OPTION) || cmd.getOptionValue(COMMAND_OPTION) == null
50 : getCommandName(cmd.getOptionValue(COMMAND_OPTION)).map(COMMANDS::get);
53 public static void printUsages() {
54 COMMANDS.values().forEach(Command::printUsage);
57 private static Optional<CommandName> getCommandName(String commandName) {
59 return Optional.of(CommandName.valueOf(commandName));
60 } catch (IllegalArgumentException iae) {
61 printMessage(LOGGER, String.format("message: %s is illegal command.", commandName));
62 return Optional.empty();
66 private static CommandLine parseArgs(String[] args) {
68 return new DefaultParser().parse(OPTIONS, args, true);
69 } catch (ParseException e) {
70 LOGGER.error("Error parsing arguments", e);
75 static void addCommand(Command command) {
76 CommandName commandName = command.getCommandName();
77 if (COMMANDS.containsKey(commandName)) {
78 throw new IllegalArgumentException(
79 String.format("Command with the name %s was already registered", commandName));
81 COMMANDS.put(commandName, command);