Example usage for org.apache.commons.cli CommandLine getOptionProperties

List of usage examples for org.apache.commons.cli CommandLine getOptionProperties

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLine getOptionProperties.

Prototype

public Properties getOptionProperties(String opt) 

Source Link

Document

Retrieve the map of values associated to the option.

Usage

From source file:org.apache.hive.beeline.BeeLine.java

private boolean connectUsingArgs(BeelineParser beelineParser, CommandLine cl) {
    String driver = null, user = null, pass = "", url = null;
    String auth = null;//from  w w w . j  a va  2s .com

    if (cl.hasOption("help")) {
        usage();
        getOpts().setHelpAsked(true);
        return true;
    }

    Properties hiveVars = cl.getOptionProperties("hivevar");
    for (String key : hiveVars.stringPropertyNames()) {
        getOpts().getHiveVariables().put(key, hiveVars.getProperty(key));
    }

    Properties hiveConfs = cl.getOptionProperties("hiveconf");
    for (String key : hiveConfs.stringPropertyNames()) {
        setHiveConfVar(key, hiveConfs.getProperty(key));
    }

    driver = cl.getOptionValue("d");
    auth = cl.getOptionValue("a");
    user = cl.getOptionValue("n");
    getOpts().setAuthType(auth);
    if (cl.hasOption("w")) {
        pass = obtainPasswordFromFile(cl.getOptionValue("w"));
    } else {
        if (beelineParser.isPasswordOptionSet) {
            pass = cl.getOptionValue("p");
        }
    }
    url = cl.getOptionValue("u");
    if ((url == null) && cl.hasOption("reconnect")) {
        // If url was not specified with -u, but -r was present, use that.
        url = getOpts().getLastConnectedUrl();
    }
    getOpts().setInitFiles(cl.getOptionValues("i"));
    getOpts().setScriptFile(cl.getOptionValue("f"));

    if (url != null) {
        String com;
        String comForDebug;
        if (pass != null) {
            com = constructCmd(url, user, pass, driver, false);
            comForDebug = constructCmd(url, user, pass, driver, true);
        } else {
            com = constructCmdUrl(url, user, driver, false);
            comForDebug = constructCmdUrl(url, user, driver, true);
        }
        debug(comForDebug);
        return dispatch(com);
    }
    // load property file
    String propertyFile = cl.getOptionValue("property-file");
    if (propertyFile != null) {
        try {
            this.consoleReader = new ConsoleReader();
        } catch (IOException e) {
            handleException(e);
        }
        if (!dispatch("!properties " + propertyFile)) {
            exit = true;
            return false;
        }
    }
    return false;
}

From source file:org.apache.hive.hcatalog.cli.HCatCli.java

@SuppressWarnings("static-access")
public static void main(String[] args) {

    try {//from  w  ww  . ja  v  a  2  s  . c o m
        LogUtils.initHiveLog4j();
    } catch (LogInitializationException e) {

    }
    LOG = LoggerFactory.getLogger(HCatCli.class);

    CliSessionState ss = new CliSessionState(new HiveConf(SessionState.class));
    ss.in = System.in;
    try {
        ss.out = new PrintStream(System.out, true, "UTF-8");
        ss.err = new PrintStream(System.err, true, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        System.exit(1);
    }

    HiveConf conf = ss.getConf();

    HiveConf.setVar(conf, ConfVars.SEMANTIC_ANALYZER_HOOK, HCatSemanticAnalyzer.class.getName());
    String engine = HiveConf.getVar(conf, ConfVars.HIVE_EXECUTION_ENGINE);
    final String MR_ENGINE = "mr";
    if (!MR_ENGINE.equalsIgnoreCase(engine)) {
        HiveConf.setVar(conf, ConfVars.HIVE_EXECUTION_ENGINE, MR_ENGINE);
        LOG.info("Forcing " + ConfVars.HIVE_EXECUTION_ENGINE + " to " + MR_ENGINE);
    }

    Options options = new Options();

    // -e 'quoted-query-string'
    options.addOption(OptionBuilder.hasArg().withArgName("exec")
            .withDescription("hcat command given from command line").create('e'));

    // -f <query-file>
    options.addOption(
            OptionBuilder.hasArg().withArgName("file").withDescription("hcat commands in file").create('f'));

    // -g
    options.addOption(OptionBuilder.hasArg().withArgName("group")
            .withDescription("group for the db/table specified in CREATE statement").create('g'));

    // -p
    options.addOption(OptionBuilder.hasArg().withArgName("perms")
            .withDescription("permissions for the db/table specified in CREATE statement").create('p'));

    // -D
    options.addOption(OptionBuilder.hasArgs(2).withArgName("property=value").withValueSeparator()
            .withDescription("use hadoop value for given property").create('D'));

    // [-h|--help]
    options.addOption(new Option("h", "help", false, "Print help information"));

    Parser parser = new GnuParser();
    CommandLine cmdLine = null;

    try {
        cmdLine = parser.parse(options, args);

    } catch (ParseException e) {
        printUsage(options, System.err);
        // Note, we print to System.err instead of ss.err, because if we can't parse our
        // commandline, we haven't even begun, and therefore cannot be expected to have
        // reasonably constructed or started the SessionState.
        System.exit(1);
    }

    // -D : process these first, so that we can instantiate SessionState appropriately.
    setConfProperties(conf, cmdLine.getOptionProperties("D"));

    // Now that the properties are in, we can instantiate SessionState.
    SessionState.start(ss);

    // -h
    if (cmdLine.hasOption('h')) {
        printUsage(options, ss.out);
        sysExit(ss, 0);
    }

    // -e
    String execString = (String) cmdLine.getOptionValue('e');

    // -f
    String fileName = (String) cmdLine.getOptionValue('f');
    if (execString != null && fileName != null) {
        ss.err.println("The '-e' and '-f' options cannot be specified simultaneously");
        printUsage(options, ss.err);
        sysExit(ss, 1);
    }

    // -p
    String perms = (String) cmdLine.getOptionValue('p');
    if (perms != null) {
        validatePermissions(ss, conf, perms);
    }

    // -g
    String grp = (String) cmdLine.getOptionValue('g');
    if (grp != null) {
        conf.set(HCatConstants.HCAT_GROUP, grp);
    }

    // all done parsing, let's run stuff!

    if (execString != null) {
        sysExit(ss, processLine(execString));
    }

    try {
        if (fileName != null) {
            sysExit(ss, processFile(fileName));
        }
    } catch (FileNotFoundException e) {
        ss.err.println("Input file not found. (" + e.getMessage() + ")");
        sysExit(ss, 1);
    } catch (IOException e) {
        ss.err.println("Could not open input file for reading. (" + e.getMessage() + ")");
        sysExit(ss, 1);
    }

    // -h
    printUsage(options, ss.err);
    sysExit(ss, 1);
}

From source file:org.apache.marmotta.loader.core.MarmottaLoader.java

public static Configuration parseOptions(String[] args) throws ParseException {
    Options options = buildOptions();//from   w ww . j a va 2s.c om

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    Configuration result = new MapConfiguration(new HashMap<String, Object>());

    if (cmd.hasOption('B')) {
        // check backends
        Set<String> existing = Sets
                .newHashSet(Iterators.transform(backends.iterator(), new BackendIdentifierFunction()));
        if (!existing.contains(cmd.getOptionValue('B'))) {
            throw new ParseException("the backend " + cmd.getOptionValue('B') + " does not exist");
        }

        result.setProperty(LoaderOptions.BACKEND, cmd.getOptionValue('B'));
    }

    if (cmd.hasOption('b')) {
        result.setProperty(LoaderOptions.BASE_URI, cmd.getOptionValue('b'));
    }

    if (cmd.hasOption('z')) {
        result.setProperty(LoaderOptions.COMPRESSION, CompressorStreamFactory.GZIP);
    }

    if (cmd.hasOption('j')) {
        result.setProperty(LoaderOptions.COMPRESSION, CompressorStreamFactory.BZIP2);
    }

    if (cmd.hasOption('c')) {
        result.setProperty(LoaderOptions.CONTEXT, cmd.getOptionValue('c'));
    }

    if (cmd.hasOption('t')) {
        RDFFormat fmt = getRDFFormat(cmd.getOptionValue('t'));
        if (fmt == null) {
            throw new ParseException("unrecognized MIME type: " + cmd.getOptionValue('t'));
        }

        result.setProperty(LoaderOptions.FORMAT, fmt.getDefaultMIMEType());
    }

    if (cmd.hasOption('f')) {
        result.setProperty(LoaderOptions.FILES, Arrays.asList(cmd.getOptionValues('f')));
    }

    if (cmd.hasOption('d')) {
        result.setProperty(LoaderOptions.DIRS, Arrays.asList(cmd.getOptionValues('d')));
    }

    if (cmd.hasOption('a')) {
        result.setProperty(LoaderOptions.ARCHIVES, Arrays.asList(cmd.getOptionValues('a')));
    }

    if (cmd.hasOption('s')) {
        result.setProperty(LoaderOptions.STATISTICS_ENABLED, true);
        result.setProperty(LoaderOptions.STATISTICS_GRAPH, cmd.getOptionValue('s'));
    }

    if (cmd.hasOption('D')) {
        for (Map.Entry e : cmd.getOptionProperties("D").entrySet()) {
            result.setProperty(e.getKey().toString(), e.getValue());
        }
    }

    for (LoaderBackend b : backends) {
        for (Option option : b.getOptions()) {
            if (cmd.hasOption(option.getOpt())) {
                String key = String.format("backend.%s.%s", b.getIdentifier(),
                        option.getLongOpt() != null ? option.getLongOpt() : option.getOpt());
                if (option.hasArg()) {
                    if (option.hasArgs()) {
                        result.setProperty(key, Arrays.asList(cmd.getOptionValues(option.getOpt())));
                    } else {
                        result.setProperty(key, cmd.getOptionValue(option.getOpt()));
                    }
                } else {
                    result.setProperty(key, true);
                }
            }
        }
    }

    return result;
}

From source file:org.apache.ofbiz.base.start.StartupCommandUtil.java

private static final List<StartupCommand> mapCommonsCliOptionsToStartupCommands(final CommandLine commandLine) {
    Set<Option> uniqueOptions = new HashSet<Option>(Arrays.asList(commandLine.getOptions()));
    return uniqueOptions.stream()
            .map(option -> new StartupCommand.Builder(option.getLongOpt())
                    .properties(populateMapFromProperties(commandLine.getOptionProperties(option.getLongOpt())))
                    .build())/*from  www  .j av  a2  s .  c om*/
            .collect(Collectors.toList());
}

From source file:org.apache.ofbiz.base.start.StartupCommandUtil.java

private static final void validateAllCommandArguments(CommandLine commandLine) throws StartupException {
    // Make sure no extra options are passed
    if (!commandLine.getArgList().isEmpty()) {
        throw new StartupException("unrecognized options / properties: " + commandLine.getArgList());
    }//from   www.j av a  2  s . co m
    // PORTOFFSET validation
    if (commandLine.hasOption(StartupOption.PORTOFFSET.getName())) {
        Properties optionProperties = commandLine.getOptionProperties(StartupOption.PORTOFFSET.getName());
        try {
            int portOffset = Integer.parseInt(optionProperties.keySet().iterator().next().toString());
            if (portOffset < 0) {
                throw new StartupException("you can only pass positive integers to the option --"
                        + StartupOption.PORTOFFSET.getName());
            }
        } catch (NumberFormatException e) {
            throw new StartupException(
                    "you can only pass positive integers to the option --" + StartupOption.PORTOFFSET.getName(),
                    e);
        }
    }
}

From source file:org.apache.oozie.cli.OozieCLI.java

private Properties getConfiguration(OozieClient wc, CommandLine commandLine) throws IOException {
    if (!isConfigurationSpecified(wc, commandLine)) {
        throw new IOException("configuration is not specified");
    }//  ww  w  . ja va 2  s  .  co  m
    Properties conf = wc.createConfiguration();
    String configFile = commandLine.getOptionValue(CONFIG_OPTION);
    if (configFile != null) {
        File file = new File(configFile);
        if (!file.exists()) {
            throw new IOException("configuration file [" + configFile + "] not found");
        }
        if (configFile.endsWith(".properties")) {
            conf.load(new FileReader(file));
        } else if (configFile.endsWith(".xml")) {
            parse(new FileInputStream(configFile), conf);
        } else {
            throw new IllegalArgumentException("configuration must be a '.properties' or a '.xml' file");
        }
    }
    if (commandLine.hasOption("D")) {
        Properties commandLineProperties = commandLine.getOptionProperties("D");
        conf.putAll(commandLineProperties);
    }
    return conf;
}

From source file:org.apache.oozie.cli.OozieCLI.java

private void scriptLanguageCommand(CommandLine commandLine, String jobType)
        throws IOException, OozieCLIException {
    List<String> args = commandLine.getArgList();
    if (args.size() > 0) {
        // checking if args starts with -X (because CLIParser cannot check this)
        if (!args.get(0).equals("-X")) {
            throw new OozieCLIException("Unrecognized option: " + args.get(0) + " Expecting -X");
        }/*from ww  w.j a  v  a2  s . c o m*/
        args.remove(0);
    }

    if (!commandLine.hasOption(SCRIPTFILE_OPTION)) {
        throw new OozieCLIException("Need to specify -file <scriptfile>");
    }

    if (!commandLine.hasOption(CONFIG_OPTION)) {
        throw new OozieCLIException("Need to specify -config <configfile>");
    }

    try {
        XOozieClient wc = createXOozieClient(commandLine);
        Properties conf = getConfiguration(wc, commandLine);
        String script = commandLine.getOptionValue(SCRIPTFILE_OPTION);
        List<String> paramsList = new ArrayList<String>();
        if (commandLine.hasOption("P")) {
            Properties params = commandLine.getOptionProperties("P");
            for (String key : params.stringPropertyNames()) {
                paramsList.add(key + "=" + params.getProperty(key));
            }
        }
        System.out.println(
                JOB_ID_PREFIX + wc.submitScriptLanguage(conf, script, args.toArray(new String[args.size()]),
                        paramsList.toArray(new String[paramsList.size()]), jobType));
    } catch (OozieClientException ex) {
        throw new OozieCLIException(ex.toString(), ex);
    }
}

From source file:org.apache.tomcat.maven.runner.Tomcat7RunnerCli.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {/*from  w w  w.  j ava2s  .  c o  m*/
        line = parser.parse(Tomcat7RunnerCli.options, args);
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(getCmdLineSyntax(), Tomcat7RunnerCli.options);
        System.exit(1);
    }

    if (line.hasOption(help.getOpt())) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(getCmdLineSyntax(), Tomcat7RunnerCli.options);
        System.exit(0);
    }

    if (line.hasOption(obfuscate.getOpt())) {
        System.out.println(PasswordUtil.obfuscate(line.getOptionValue(obfuscate.getOpt())));
        System.exit(0);
    }
    Tomcat7Runner tomcat7Runner = new Tomcat7Runner();

    tomcat7Runner.runtimeProperties = buildStandaloneProperties();

    if (line.hasOption(serverXmlPath.getOpt())) {
        tomcat7Runner.serverXmlPath = line.getOptionValue(serverXmlPath.getOpt());
    }

    String port = tomcat7Runner.runtimeProperties.getProperty(Tomcat7Runner.HTTP_PORT_KEY);
    if (port != null) {
        tomcat7Runner.httpPort = Integer.parseInt(port);
    }

    // cli win for the port
    if (line.hasOption(httpPort.getOpt())) {
        tomcat7Runner.httpPort = Integer.parseInt(line.getOptionValue(httpPort.getOpt()));
    }

    if (line.hasOption(maxPostSize.getOpt())) {
        tomcat7Runner.maxPostSize = Integer.parseInt(line.getOptionValue(maxPostSize.getOpt()));
    }

    if (line.hasOption(httpsPort.getOpt())) {
        tomcat7Runner.httpsPort = Integer.parseInt(line.getOptionValue(httpsPort.getOpt()));
    }
    if (line.hasOption(ajpPort.getOpt())) {
        tomcat7Runner.ajpPort = Integer.parseInt(line.getOptionValue(ajpPort.getOpt()));
    }
    if (line.hasOption(resetExtract.getOpt())) {
        tomcat7Runner.resetExtract = true;
    }
    if (line.hasOption(debug.getOpt())) {
        tomcat7Runner.debug = true;
    }

    if (line.hasOption(httpProtocol.getOpt())) {
        tomcat7Runner.httpProtocol = line.getOptionValue(httpProtocol.getOpt());
    }

    if (line.hasOption(sysProps.getOpt())) {
        Properties systemProperties = line.getOptionProperties(sysProps.getOpt());
        if (systemProperties != null && !systemProperties.isEmpty()) {
            for (Map.Entry<Object, Object> sysProp : systemProperties.entrySet()) {
                System.setProperty((String) sysProp.getKey(), (String) sysProp.getValue());
            }
        }
    }
    if (line.hasOption(clientAuth.getOpt())) {
        tomcat7Runner.clientAuth = clientAuth.getOpt();
    }
    if (line.hasOption(keyAlias.getOpt())) {
        tomcat7Runner.keyAlias = line.getOptionValue(keyAlias.getOpt());
    }

    if (line.hasOption(extractDirectory.getOpt())) {
        tomcat7Runner.extractDirectory = line.getOptionValue(extractDirectory.getOpt());
    }

    if (line.hasOption(loggerName.getOpt())) {
        tomcat7Runner.loggerName = line.getOptionValue(loggerName.getOpt());
    }

    if (line.hasOption(uriEncoding.getOpt())) {
        tomcat7Runner.uriEncoding = line.getOptionValue(uriEncoding.getOpt());
    }

    // here we go
    tomcat7Runner.run();
}

From source file:org.apache.tomcat.maven.runner.Tomcat8RunnerCli.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {//from   w ww  . j ava2  s . c o  m
        line = parser.parse(Tomcat8RunnerCli.options, args);
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(getCmdLineSyntax(), Tomcat8RunnerCli.options);
        System.exit(1);
    }

    if (line.hasOption(help.getOpt())) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(getCmdLineSyntax(), Tomcat8RunnerCli.options);
        System.exit(0);
    }

    if (line.hasOption(obfuscate.getOpt())) {
        System.out.println(PasswordUtil.obfuscate(line.getOptionValue(obfuscate.getOpt())));
        System.exit(0);
    }
    Tomcat8Runner tomcat8Runner = new Tomcat8Runner();

    tomcat8Runner.runtimeProperties = buildStandaloneProperties();

    if (line.hasOption(serverXmlPath.getOpt())) {
        tomcat8Runner.serverXmlPath = line.getOptionValue(serverXmlPath.getOpt());
    }

    String port = tomcat8Runner.runtimeProperties.getProperty(Tomcat8Runner.HTTP_PORT_KEY);
    if (port != null) {
        tomcat8Runner.httpPort = Integer.parseInt(port);
    }

    // cli win for the port
    if (line.hasOption(httpPort.getOpt())) {
        tomcat8Runner.httpPort = Integer.parseInt(line.getOptionValue(httpPort.getOpt()));
    }

    if (line.hasOption(maxPostSize.getOpt())) {
        tomcat8Runner.maxPostSize = Integer.parseInt(line.getOptionValue(maxPostSize.getOpt()));
    }

    if (line.hasOption(httpsPort.getOpt())) {
        tomcat8Runner.httpsPort = Integer.parseInt(line.getOptionValue(httpsPort.getOpt()));
    }
    if (line.hasOption(ajpPort.getOpt())) {
        tomcat8Runner.ajpPort = Integer.parseInt(line.getOptionValue(ajpPort.getOpt()));
    }
    if (line.hasOption(resetExtract.getOpt())) {
        tomcat8Runner.resetExtract = true;
    }
    if (line.hasOption(debug.getOpt())) {
        tomcat8Runner.debug = true;
    }

    if (line.hasOption(httpProtocol.getOpt())) {
        tomcat8Runner.httpProtocol = line.getOptionValue(httpProtocol.getOpt());
    }

    if (line.hasOption(sysProps.getOpt())) {
        Properties systemProperties = line.getOptionProperties(sysProps.getOpt());
        if (systemProperties != null && !systemProperties.isEmpty()) {
            for (Map.Entry<Object, Object> sysProp : systemProperties.entrySet()) {
                System.setProperty((String) sysProp.getKey(), (String) sysProp.getValue());
            }
        }
    }
    if (line.hasOption(clientAuth.getOpt())) {
        tomcat8Runner.clientAuth = clientAuth.getOpt();
    }
    if (line.hasOption(keyAlias.getOpt())) {
        tomcat8Runner.keyAlias = line.getOptionValue(keyAlias.getOpt());
    }

    if (line.hasOption(extractDirectory.getOpt())) {
        tomcat8Runner.extractDirectory = line.getOptionValue(extractDirectory.getOpt());
    }

    if (line.hasOption(loggerName.getOpt())) {
        tomcat8Runner.loggerName = line.getOptionValue(loggerName.getOpt());
    }

    if (line.hasOption(uriEncoding.getOpt())) {
        tomcat8Runner.uriEncoding = line.getOptionValue(uriEncoding.getOpt());
    }

    // here we go
    tomcat8Runner.run();
}

From source file:org.azyva.dragom.cliutil.CliUtil.java

/**
 * Sets up an {@link ExecContext} assuming an {@link ExecContextFactory} that
 * supports the concept of workspace directory.
 * <p>/*from   www .j  ava  2  s .c  o m*/
 * {@link ExecContextFactoryHolder} is used to get the ExecContextFactory so it
 * is not guaranteed that it will support the concept of workspace directory and
 * implement {@link WorkspaceExecContextFactory}. In such as case an exception is
 * raised.
 * <p>
 * The strategy for setting up the ExecContext supports a user service
 * implementation where a single JVM remains running in the background in the
 * context of a given user account (not system-wide) and can execute Dragom tools
 * for multiple different workspaces while avoiding tool startup overhead.
 * <a href="http://www.martiansoftware.com/nailgun/" target="_blank">Nailgun</a>
 * can be useful for that purpose.
 * <p>
 * A user service implementation is supported by differentiating between workspace
 * initialization Properties passed to {@link ExecContextFactory#getExecContext}
 * and tool initialization Properties passed to
 * {@link ToolLifeCycleExecContext#startTool}.
 * <p>
 * Workspace initialization Properties are constructed in the following way:
 * <ul>
 * <li>Dragom properties are merged into System properties using
 *     {@link Util#applyDragomSystemProperties}. System properties take precedence
 *     over Dragom properties;
 * <li>Initialize an empty Properties with system properties (System.getProperties)
 *     that are prefixed with "org.azyva.dragom.init-property" as defaults. This
 *     Properties when fully initialized will become the workspace initialization
 *     Properties;
 * <li>If the org.azyva.IndUserProperties system property is defined, load the
 *     Properties defined in the properties file specified by the
 *     user-properties command line option. If not defined, use the properties
 *     file specified by the org.azyva.DefaultUserProperties system property. If
 *     not defined or if the properties file does not exist, do not load the
 *     Properties;
 * <li>The workspace directory is added to the Properties created above.
 * </ul>
 * The name of the user-properties command line option can be overridden with the
 * org.azyva.dragom.UserPropertiesCommandLineOption system property.
 * <p>
 * Tool initialization Properties are constructed in the following way (if indSet):
 * <ul>
 * <li>Initialize an empty Properties. This Properties when fully initialized will
 *     become the tool initialization Properties;
 * <li>If the org.azyva.IndToolProperties system property is defined, load the
 *     Properties defined in the Properties file specified by the
 *     tool-properties command line option. If not defined or if the properties
 *     file does not exist, do not load the Properties.
 * </ul>
 * The name of the tool-properties command line option can be overridden with the
 * org.azyva.dragom.ToolPropertiesCommandLineOption system property.
 * <p>
 * It is possible that ExecContextFactory.getExecContext uses a cached ExecContext
 * corresponding to a workspace that has already been initialized previously. In
 * that case workspace initialization Properties will not be considered since
 * ExecContextFactory.getExecContext considers them only when a new ExecContext is
 * created. This is not expected to be a problem or source of confusion since this
 * can happen only if a user service implementation is actually used and in such a
 * case Dragom and system properties are expected to be considered only once when
 * initializing the user service and users are expected to understand that user
 * properties are considered only when initializing a new workspace.
 * <p>
 * If indSet, {@link ExecContextHolder#setAndStartTool} is called with the
 * ExecContext to make it easier for tools to prepare for execution. But it is
 * still the tool's responsibility to call
 * {@link ExecContextHolder#endToolAndUnset} before exiting. This is somewhat
 * asymmetric, but is sufficiently convenient to be warranted. The case where it
 * can be useful to set indSet to false is for subsequently calling
 * {@link ExecContextHolder#forceUnset}.
 * <p>
 * If indSet, the IND_NO_CONFIRM and {@code IND_NO_CONFIRM.<context>} runtime
 * properties are read from the CommandLine.
 *
 * @param commandLine CommandLine where to obtain the user and tool properties
 *   files as well as the workspace path.
 * @param indSet Indicates to set the ExecContext in ExecContextHolder.
 * @return ExecContext.
 */
public static ExecContext setupExecContext(CommandLine commandLine, boolean indSet) {
    ExecContextFactory execContextFactory;
    WorkspaceExecContextFactory workspaceExecContextFactory;
    Properties propertiesInit;
    String workspaceDir;
    String stringPropertiesFile;
    ExecContext execContext;

    execContextFactory = ExecContextFactoryHolder.getExecContextFactory();

    if (!(execContextFactory instanceof WorkspaceExecContextFactory)) {
        throw new RuntimeException("The ExecContextFactory does not support the workspace directory concept.");
    }

    workspaceExecContextFactory = (WorkspaceExecContextFactory) execContextFactory;

    propertiesInit = Util.getPropertiesDefaultInit();

    Util.applyDragomSystemProperties();

    if (Util.isNotNullAndTrue(System.getProperty(CliUtil.SYS_PROPERTY_IND_USER_PROPERTIES))) {
        stringPropertiesFile = commandLine.getOptionValue(CliUtil.getUserPropertiesFileCommandLineOption());

        if (stringPropertiesFile == null) {
            stringPropertiesFile = System.getProperty(CliUtil.SYS_PROPERTY_DEFAULT_USER_PROPERTIES_FILE);
        }

        if (stringPropertiesFile != null) {
            propertiesInit = CliUtil.loadProperties(stringPropertiesFile, propertiesInit);
        }
    }

    // In general initialization properties defined as system properties with the
    // "org.azyva.dragom.init-property." prefix are expected to have been provided
    // as -D JVM arguments and as such are expected by the user to have precedence
    // over initialization properties provided in the user properties file loaded just
    // above. Initialization properties defined in the dragom.properties file
    // (see Util#applyDragomSystemProperties) will therefore also have precedence,
    // which is generally not desirable. That is why a separate dragom-init.properties
    // file (loaded with Util.getPropertiesDefaultInit above) is used for default
    // initialization properties.
    for (String initProperty : System.getProperties().stringPropertyNames()) {
        if (initProperty.startsWith(CliUtil.SYS_PROPERTY_PREFIX_INIT_PROPERTY)) {
            propertiesInit.setProperty(
                    initProperty.substring(CliUtil.SYS_PROPERTY_PREFIX_INIT_PROPERTY.length()),
                    System.getProperty(initProperty));
        }
    }

    workspaceDir = commandLine.getOptionValue(CliUtil.getWorkspacePathCommandLineOption());

    if (workspaceDir != null) {
        propertiesInit.setProperty(workspaceExecContextFactory.getWorkspaceDirInitProperty(), workspaceDir);
    }

    execContext = execContextFactory.getExecContext(propertiesInit);

    if (indSet) {
        Properties propertiesTool;

        propertiesTool = null;

        if (Util.isNotNullAndTrue(System.getProperty(CliUtil.SYS_PROPERTY_IND_TOOL_PROPERTIES))) {
            stringPropertiesFile = commandLine.getOptionValue(CliUtil.getToolPropertiesFileCommandLineOption());

            if (stringPropertiesFile != null) {
                propertiesTool = CliUtil.loadProperties(stringPropertiesFile, null);
            }
        }

        if (Util.isNotNullAndTrue(System.getProperty(CliUtil.SYS_PROPERTY_IND_SINGLE_TOOL_PROPERTIES))) {
            Properties propertiesToolSingle;

            propertiesToolSingle = commandLine.getOptionProperties("D");

            if (propertiesTool != null) {
                // Explicit single properties override similar properties defined in the tool
                // properties file.
                propertiesTool.putAll(propertiesToolSingle);
            } else {
                propertiesTool = propertiesToolSingle;
            }
        }

        if (propertiesTool == null) {
            propertiesTool = new Properties();
        }

        // The following properties can also be generically specified as single tool
        // properties. But they are supported as explicit command line arguments since
        // they are general and often used.
        if (commandLine.hasOption(CliUtil.getNoConfirmCommandLineOption())) {
            propertiesTool.setProperty(Util.RUNTIME_PROPERTY_IND_NO_CONFIRM, "true");
        } else {
            String[] tabNoConfirmContext;

            tabNoConfirmContext = commandLine.getOptionValues(CliUtil.getNoConfirmContextCommandLineOption());

            if (tabNoConfirmContext != null) {
                for (String context : tabNoConfirmContext) {
                    propertiesTool.setProperty(Util.RUNTIME_PROPERTY_IND_NO_CONFIRM + '.' + context, "true");
                }
            }
        }

        ExecContextHolder.setAndStartTool(execContext, propertiesTool);
    }

    return execContext;
}