123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272 |
- /**
- * MCS Media Computer Software
- * Copyright 2018 by Wilfried Klaas
- * Project: MCSUtils
- * File: ProcessCommandline.java
- * EMail: W.Klaas@gmx.de
- * Created: 29.11.2018 wklaa_000
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- */
- package de.mcs.utils.jsap;
- import java.lang.annotation.Annotation;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import com.martiansoftware.jsap.FlaggedOption;
- import com.martiansoftware.jsap.JSAP;
- import com.martiansoftware.jsap.JSAPException;
- import com.martiansoftware.jsap.JSAPResult;
- import com.martiansoftware.jsap.UnflaggedOption;
- import com.martiansoftware.jsap.stringparsers.FileStringParser;
- import com.martiansoftware.jsap.stringparsers.StringStringParser;
- /**
- * @author wklaa_000
- *
- */
- public class CommandlineProcessor {
- private static JSAP parser;
- private static JSAPResult commandLineArgs;
- private static Map<String, Method> parameterMethods;
- private static Command helpContext;
- public static void processCommandline(Class class1, String[] args) {
- parameterMethods = new HashMap<>();
- parseParameters(class1, args);
- checkParams();
- processParameters();
- };
- private static void processParameters() {
- parameterMethods.entrySet().forEach(e -> {
- String name = e.getKey();
- Method method = e.getValue();
- processSwitchOption(name, method);
- processStringOption(name, method);
- processFileOption(name, method);
- });
- }
- private static void processFileOption(String name, Method method) {
- FileOption annotation = method.getAnnotation(FileOption.class);
- if (annotation != null) {
- try {
- method.invoke(null, commandLineArgs.getFile(annotation.name()));
- } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
- e1.printStackTrace();
- }
- }
- }
- private static void processStringOption(String name, Method method) {
- StringOption annotation = method.getAnnotation(StringOption.class);
- if (annotation != null) {
- try {
- method.invoke(null, commandLineArgs.getString(annotation.name()));
- } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
- e1.printStackTrace();
- }
- }
- }
- private static void processSwitchOption(String name, Method method) {
- SwitchOption annotation = method.getAnnotation(SwitchOption.class);
- if (annotation != null) {
- try {
- method.invoke(null, commandLineArgs.getBoolean(name));
- } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
- e1.printStackTrace();
- }
- }
- }
- /**
- * checking commandline parameters.
- */
- private static void checkParams() {
- if (!commandLineArgs.success()) {
- System.err.println();
- // print out specific error messages describing the problems
- // with the command line, THEN print usage, THEN print full
- // help. This is called "beating the user with a clue stick."
- for (@SuppressWarnings("rawtypes")
- Iterator errs = commandLineArgs.getErrorMessageIterator(); errs.hasNext();) {
- System.err.println("Error: " + errs.next());
- }
- showHelp("error");
- System.exit(-1);
- }
- }
- /**
- * showing the actual help page in console.
- */
- public static void showHelp() {
- showHelp(null);
- }
- /**
- * showing the actual help page in console.
- */
- public static void showHelp(String message) {
- if (helpContext != null) {
- System.out.println(helpContext.help());
- }
- if (message != null) {
- System.out.println(message);
- }
- System.out.println(parser.getHelp());
- }
- /**
- * This function parses the commandline parameters. If the parameter -h or
- * --help is avalible, generate a little help text.
- *
- * @param mainClass
- *
- * @param args
- * Commadline arguments
- */
- public static void parseParameters(Class mainClass, final String[] args) {
- parser = new JSAP();
- try {
- // registering the main help context, if availble
- registerHelpContext(mainClass);
- // registering the parameters with default values
- registerDefaultParameter(mainClass);
- // parsing the commadline
- commandLineArgs = parser.parse(args);
- } catch (JSAPException e) {
- // Something goes wrong
- System.out.println("Parsing exception:" + e.getMessage());
- e.printStackTrace();
- System.exit(1);
- }
- }
- private static void registerHelpContext(Class mainClass) {
- Command annotation = (Command) mainClass.getAnnotation(Command.class);
- if (annotation != null) {
- helpContext = annotation;
- }
- }
- /**
- * registering the parameters to the JSAP Parser.
- *
- * @param mainClass
- *
- * @throws JSAPException
- * Something is going wrong
- */
- private static void registerDefaultParameter(Class mainClass) throws JSAPException {
- Map<Integer, UnflaggedOption> unflaggedOptions = new HashMap<>();
- List<Method> methodes = getMethodsAnnotatedWith(mainClass, SwitchOption.class);
- for (Method method : methodes) {
- SwitchOption annotation = method.getAnnotation(SwitchOption.class);
- com.martiansoftware.jsap.Switch swtOption = new com.martiansoftware.jsap.Switch(annotation.name(),
- annotation.shortKey(), annotation.longKey());
- if (annotation.defaultValue()) {
- swtOption.setDefault(Boolean.TRUE.toString());
- }
- swtOption.setHelp(annotation.help());
- parser.registerParameter(swtOption);
- parameterMethods.put(annotation.name(), method);
- }
- methodes = getMethodsAnnotatedWith(mainClass, StringOption.class);
- for (Method method : methodes) {
- StringOption annotation = method.getAnnotation(StringOption.class);
- StringStringParser stringParser = StringStringParser.getParser();
- if (annotation.index() > 0) {
- UnflaggedOption unflgopt = new UnflaggedOption(annotation.name(), stringParser, annotation.defaultValue(),
- annotation.required(), false, annotation.help());
- unflaggedOptions.put(annotation.index(), unflgopt);
- parameterMethods.put(Integer.toString(annotation.index()), method);
- } else {
- FlaggedOption flgopt = new FlaggedOption(annotation.name(), stringParser, annotation.defaultValue(),
- annotation.required(), annotation.shortKey(), annotation.longKey());
- flgopt.setHelp(annotation.help());
- parser.registerParameter(flgopt);
- parameterMethods.put(annotation.name(), method);
- }
- }
- methodes = getMethodsAnnotatedWith(mainClass, FileOption.class);
- for (Method method : methodes) {
- FileOption annotation = method.getAnnotation(FileOption.class);
- FileStringParser fileStringParser = FileStringParser.getParser();
- fileStringParser.setMustBeDirectory(annotation.mustBeDirectory());
- fileStringParser.setMustExist(annotation.mustExists());
- if (annotation.index() > 0) {
- UnflaggedOption unflgopt = new UnflaggedOption(annotation.name(), fileStringParser, annotation.defaultValue(),
- annotation.required(), false, annotation.help());
- unflaggedOptions.put(annotation.index(), unflgopt);
- parameterMethods.put(Integer.toString(annotation.index()), method);
- } else {
- FlaggedOption flgopt = new FlaggedOption(annotation.name(), fileStringParser, annotation.defaultValue(),
- annotation.required(), annotation.shortKey(), annotation.longKey());
- flgopt.setHelp(annotation.help());
- parser.registerParameter(flgopt);
- parameterMethods.put(annotation.name(), method);
- }
- }
- // sorting unflagged options
- List<Integer> indexes = new ArrayList<>();
- unflaggedOptions.keySet().forEach(e -> indexes.add(e));
- indexes.sort((x, y) -> {
- int diff = x - y;
- return (diff == 0) ? 1 : diff;
- });
- // registering the unflagged options in the right order
- for (Integer e : indexes) {
- parser.registerParameter(unflaggedOptions.get(e));
- }
- }
- private static List<Method> getMethodsAnnotatedWith(Class class1, Class annotationClass) {
- List<Method> list = new ArrayList<>();
- Method[] methods = class1.getMethods();
- for (Method method : methods) {
- Annotation[] annotations = method.getAnnotationsByType(annotationClass);
- if (annotations.length > 0) {
- list.add(method);
- }
- }
- return list;
- }
- }
|