Skip to content

Commit

Permalink
Added the method CmdUtils.registerIfAvailable
Browse files Browse the repository at this point in the history
  • Loading branch information
Aklakan committed May 17, 2024
1 parent c6928e6 commit db9f26a
Showing 1 changed file with 27 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
* execCmd: Run command and terminate the JVM using System.exit with the exit code
*
* @author raven
*
*/
public class CmdUtils {
private static final Logger logger = LoggerFactory.getLogger(CmdUtils.class);
Expand All @@ -26,6 +25,10 @@ public static void execCmd(Object cmdInstance, String[] args) {
System.exit(exitCode);
}

public static void execCmd(CommandLine cl, String[] args) {
int exitCode = callCmd(cl, args);
System.exit(exitCode);
}

/**
*
Expand Down Expand Up @@ -75,4 +78,27 @@ public static int callCmd(Object cmdInstance, String[] args) {
.execute(args);
return result;
}

/**
* Attempt to register a command by class name. If a {@link ClassNotFoundException} is raised
* then the command is ignored. Useful to deal with commands provided by
* maven dependencies that may needed to be excluded.
*/
public static CommandLine registerIfAvailable(CommandLine commandLine, String className) {
CommandLine result = null;
try {
Class<?> cmdCls = Class.forName(className);
Object cmd;
try {
cmd = cmdCls.getConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
result = commandLine.addSubcommand(cmd);
} catch (ClassNotFoundException e) {
logger.debug("A command was was not found: " + className);
}

return result;
}
}

0 comments on commit db9f26a

Please sign in to comment.