java/parameter-lister/src/info/glogalcode/parameterLister/CLI.java
changeset 21 7d86d90e6e0e
child 28 bfef9f34e438
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/java/parameter-lister/src/info/glogalcode/parameterLister/CLI.java	Sat Sep 10 23:03:43 2016 +0200
     1.3 @@ -0,0 +1,53 @@
     1.4 +package info.glogalcode.parameterLister;
     1.5 +
     1.6 +import info.glogalcode.parameterLister.modules.TerminalModuleFactory;
     1.7 +import java.util.Arrays;
     1.8 +import java.util.HashMap;
     1.9 +import java.util.Map;
    1.10 +import java.util.ServiceLoader;
    1.11 +import java.util.logging.Level;
    1.12 +import java.util.logging.Logger;
    1.13 +
    1.14 +/**
    1.15 + *
    1.16 + * @author Ing. František Kučera (frantovo.cz)
    1.17 + */
    1.18 +public class CLI {
    1.19 +
    1.20 +	public static final String ENV_BASE = "PARAMETER_LISTER";
    1.21 +	public static final String ENV_OUTPUT_MODULE_NAME = ENV_BASE + "_OUTPUT";
    1.22 +	public static final String DEFAULT_MODULE = TerminalModuleFactory.MODULE_NAME;
    1.23 +
    1.24 +	public static final int EXIT_SUCCESS = 0;
    1.25 +	public static final int EXIT_UNEXPECTED_ERROR = 1;
    1.26 +	// 2 is reserved: http://www.tldp.org/LDP/abs/html/exitcodes.html#EXITCODESREF
    1.27 +	public static final int EXIT_MODULE_ERROR = 3;
    1.28 +
    1.29 +	private static final Logger log = Logger.getLogger(CLI.class.getName());
    1.30 +
    1.31 +	public static void main(String[] args) {
    1.32 +
    1.33 +		try {
    1.34 +			ServiceLoader<OutputModuleFactory> modulesLoader = ServiceLoader.load(OutputModuleFactory.class);
    1.35 +			final Map<String, OutputModuleFactory> modules = new HashMap<>();
    1.36 +			modulesLoader.forEach(f -> modules.put(f.getName(), f));
    1.37 +
    1.38 +			String moduleName = System.getenv(ENV_OUTPUT_MODULE_NAME);
    1.39 +			OutputModuleFactory moduleFactory = modules.getOrDefault(moduleName, modules.get(DEFAULT_MODULE));
    1.40 +			OutputModule module = moduleFactory.createModule();
    1.41 +
    1.42 +			try {
    1.43 +				module.process(System.out, Arrays.asList(args));
    1.44 +			} catch (OutputModuleException e) {
    1.45 +				log.log(Level.SEVERE, "Error while processing output with module " + module.getClass().getName(), e);
    1.46 +				System.exit(EXIT_MODULE_ERROR);
    1.47 +			}
    1.48 +		} catch (Exception e) {
    1.49 +			log.log(Level.SEVERE, "Unexpected exception, probably bug.", e);
    1.50 +			System.exit(EXIT_UNEXPECTED_ERROR);
    1.51 +
    1.52 +		}
    1.53 +		System.exit(EXIT_SUCCESS);
    1.54 +	}
    1.55 +
    1.56 +}