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

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

Introduction

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

Prototype

public List getArgList() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:org.icesquirrel.Squirrel.java

public static void main(String[] args) throws Exception {
    Options o = new Options();
    o.addOption("?", "help", true, "Display help and exit.");
    o.addOption("n", "namespace", true, "Namespace of generated classes.");
    o.addOption("m", "mode", true, "Mode. One of " + Arrays.asList(Mode.values()));
    o.addOption("o", "output", true,
            "Output directory for compiled classes. Default is current working directory.");
    o.addOption("l", "level", true,
            "Log level. One of ALL, CONFIG, FINE, FINER, FINEST, WARN, INFO, SEVERE, OFF");
    CommandLine cli = new GnuParser().parse(o, args);

    Squirrel sq = new Squirrel();

    if (cli.hasOption('?') || cli.getArgList().size() == 0) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Squirrel.class.getName()
                + " [-?|--help] [-m <mode>|--mode <mode>] [-o <output directory>|--output <output directory>] [-l <log level>|--log <log level>] <script1.nut> [<script2.nut> ..] [-- <scriptArg1> <scriptArg2> ..]",
                o);//  w w w.  j  av a 2 s. co m
        System.exit(1);
    }

    // Namespace
    if (cli.hasOption('n')) {
        sq.setNamespace(cli.getOptionValue('n'));
    }

    // Mode
    if (cli.hasOption('m')) {
        sq.setMode(Mode.valueOf(cli.getOptionValue('m')));
    }

    // Log level
    if (cli.hasOption('l')) {
        Squirrel.setLogLevel(Level.parse(cli.getOptionValue('l')));
    }

    // Output
    if (cli.hasOption('o')) {
        File dir = new File(cli.getOptionValue('o'));
        sq.setOutput(dir);
    }

    // Process
    List<String> scriptArgList = new ArrayList<>();
    List<String> files = new ArrayList<>();
    boolean scriptArgs = false;
    for (String a : cli.getArgs()) {
        if (a.equals("--") && !scriptArgs) {
            scriptArgs = true;
        } else {
            if (scriptArgs) {
                scriptArgList.add(a);
            } else {
                files.add(a);
            }
        }
    }

    for (String f : files) {
        sq.process(new File(f), scriptArgList.toArray(new String[0]));
    }
}

From source file:org.jcryptool.crypto.classic.model.algorithm.ClassicAlgorithmCmd.java

public void execute(CommandLine commandLine) throws IllegalCommandException {
    /**/*from  www . jav a 2  s . c om*/
     * Order of argument reading:
     *       text
     *       currentAlphabet
     *       something
     *       key (last!)
     */
    super.execute(commandLine);

    currentAlphabet = null;

    result = new StringBuilder();

    // read text 

    try {

        InputStream inputStream = null;
        try {
            inputStream = handleInputOption(commandLine);
        } catch (FileNotFoundException e) {
            result.append(e.getLocalizedMessage());
            return;
        }

        // read currentAlphabet 

        AbstractAlphabet alphabet = handleAlphabetOption(commandLine);
        this.currentAlphabet = alphabet;

        // read other options

        int cryptMode = -1;
        if (commandLine.hasOption(MODEDECRYPTION_OPTIONNAME)) { //$NON-NLS-1$
            cryptMode = AbstractAlgorithm.DECRYPT_MODE;
        } else {
            cryptMode = AbstractAlgorithm.ENCRYPT_MODE;
        }

        boolean filter = !commandLine.hasOption(NOFILTER_OPTIONNAME); //$NON-NLS-1$

        // handle options contributed by subclasses

        handleOtherOptions(commandLine, result);

        // read the key

        char[] key = handleKeyOption(commandLine, result);

        // initialize the algorithm
        AbstractClassicAlgorithm algorithm = initializeAlgorithm(cryptMode, inputStream, alphabet, key, filter);

        //execute

        ClassicDataObject dataObject = (ClassicDataObject) algorithm.execute();

        //finish

        if (!commandLine.getArgList().isEmpty()) {
            result.append(Messages.ClassicAlgorithmCmd_ignoredargs);
            result.append(commandLine.getArgList());
            result.append("\n\n"); //$NON-NLS-1$
        }

        result.append(dataObject.getOutput());

    } catch (ParseException e) {
        result.append(Messages.ClassicAlgorithmCmd_error + e.getMessage());
    }

}

From source file:org.jrman.main.JRMan.java

public static void main(String args[]) {
    try {/*from w w w  .  j  a  v  a  2s  . c o m*/
        Options opts = prepareOptions();
        // parse command line
        CommandLine cmdLine = new BasicParser().parse(opts, args);
        // deal with help and version options or no args at all immediately
        if (cmdLine.getArgList().isEmpty() || cmdLine.hasOption(OPTION_HELP)) {
            printUsage(opts);
            System.exit(0);
        }
        if (cmdLine.hasOption(OPTION_VERSION)) {
            printVersion();
            System.exit(0);
        }
        // process arguments (rib files to render)
        Iterator it = cmdLine.getArgList().iterator();
        long totalStart = System.currentTimeMillis();
        while (it.hasNext())
            try {
                String filename = (String) it.next();
                long start = System.currentTimeMillis();
                Parser parser = new Parser(cmdLine);
                parser.begin(filename);
                File file = new File(filename);
                String directory = file.getParent();
                parser.setCurrentDirectory(directory);
                MipMap.setCurrentDirectory(directory);
                ShadowMap.setCurrentDirectory(directory);
                parser.parse(file.getName());
                parser.end();
                long end = System.currentTimeMillis();
                System.out.println(filename + " time: " + Format.time(end - start));
            } catch (IOException ioe) {
                System.err.println("Error on file " + ioe.getLocalizedMessage());
            } catch (Exception e) {
                System.err.println("Error  " + e.getLocalizedMessage());
            }
        long totalEnd = System.currentTimeMillis();
        System.out.println("Total time: " + Format.time(totalEnd - totalStart));
    } catch (ParseException e) {
        System.err.println(e.getLocalizedMessage());
        System.exit(1);
    }
}

From source file:org.jumpmind.symmetric.AbstractCommandLauncher.java

public void execute(String args[]) {
    PosixParser parser = new PosixParser();
    Options options = new Options();
    buildOptions(options);//from w  w  w .ja v a  2s  .  c om
    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(HELP) || (line.getArgList().contains(HELP)) || ((args == null || args.length == 0)
                && line.getOptions().length == 0 && printHelpIfNoOptionsAreProvided())) {
            printHelp(line, options);
            System.exit(2);
        }

        configureLogging(line);
        configurePropertiesFile(line);

        if (line.getOptions() != null) {
            for (Option option : line.getOptions()) {
                log.info("Option: name={}, value={}",
                        new Object[] { option.getLongOpt() != null ? option.getLongOpt() : option.getOpt(),
                                ArrayUtils.toString(option.getValues()) });
            }
        }

        executeWithOptions(line);

    } catch (ParseException e) {
        System.err.println(e.getMessage());
        printUsage(options);
        System.exit(4);
    } catch (Exception e) {
        System.err.println("-------------------------------------------------------------------------------");
        System.err.println("An exception occurred.  Please see the following for details:");
        System.err.println("-------------------------------------------------------------------------------");

        ExceptionUtils.printRootCauseStackTrace(e, System.err);
        System.err.println("-------------------------------------------------------------------------------");
        System.exit(1);
    }
}

From source file:org.jumpmind.symmetric.SymmetricAdmin.java

@SuppressWarnings("unchecked")
@Override/*from w  w w .  j a  v a 2 s .co m*/
protected boolean executeWithOptions(CommandLine line) throws Exception {
    List<String> args = line.getArgList();
    String cmd = args.remove(0);
    configureCrypto(line);

    if (cmd.equals(CMD_EXPORT_PROPERTIES)) {
        exportDefaultProperties(line, args);
        return true;
    } else if (cmd.equals(CMD_CREATE_WAR)) {
        generateWar(line, args);
        return true;
    } else if (cmd.equals(CMD_EXPORT_SYM_TABLES)) {
        exportSymTables(line, args);
        return true;
    } else if (cmd.equals(CMD_RUN_PURGE)) {
        runPurge(line, args);
        return true;
    } else if (cmd.equals(CMD_OPEN_REGISTRATION)) {
        openRegistration(line, args);
        return true;
    } else if (cmd.equals(CMD_RELOAD_NODE)) {
        reloadNode(line, args);
        return true;
    } else if (cmd.equals(CMD_EXPORT_BATCH)) {
        exportBatch(line, args);
        return true;
    } else if (cmd.equals(CMD_SYNC_TRIGGERS)) {
        syncTrigger(line, args);
        return true;
    } else if (cmd.equals(CMD_DROP_TRIGGERS)) {
        dropTrigger(line, args);
        return true;
    } else if (cmd.equals(CMD_CREATE_SYM_TABLES)) {
        createSymTables();
        return true;
    } else if (cmd.equals(CMD_IMPORT_BATCH)) {
        importBatch(line, args);
        return true;
    } else if (cmd.equals(CMD_ENCRYPT_TEXT)) {
        encryptText(line, args);
        return true;
    } else if (cmd.equals(CMD_SEND_SQL)) {
        sendSql(line, args);
        return true;
    } else if (cmd.equals(CMD_UNINSTALL)) {
        uninstall(line, args);
        return true;
    } else if (cmd.equals(CMD_RELOAD_TABLE)) {
        reloadTable(line, args);
        return true;
    } else if (cmd.equals(CMD_SEND_SCHEMA)) {
        sendSchema(line, args);
        return true;
    } else if (cmd.equals(CMD_SEND_SCRIPT)) {
        sendScript(line, args);
        return true;
    } else {
        System.err.println("ERROR: no subcommand '" + cmd + "' was found.");
        System.err.println("For a list of subcommands, use " + app + " --" + HELP + "\n");
    }

    return false;
}

From source file:org.kie.workbench.common.services.backend.compiler.external339.AFMavenCli.java

protected void cli(AFCliRequest cliRequest) throws Exception {
    ///*from w  ww  .  j  ava  2s.co m*/
    // Parsing errors can happen during the processing of the arguments and we prefer not having to check if
    // the logger is null and construct this so we can use an SLF4J logger everywhere.
    //

    slf4jLogger = new Slf4jStdoutLogger();

    CLIManager cliManager = new CLIManager();

    List<String> args = new ArrayList<String>();

    try {
        Path configFile = Paths.get(cliRequest.getMultiModuleProjectDirectory(), ".mvn/maven.config");

        if (java.nio.file.Files.isRegularFile(configFile)) {
            for (String arg : Files.toString(configFile.toFile(), Charsets.UTF_8).split("\\s+")) {
                args.add(arg);
            }

            CommandLine config = cliManager.parse(args.toArray(new String[args.size()]));
            List<?> unrecongized = config.getArgList();
            if (!unrecongized.isEmpty()) {
                throw new ParseException("Unrecognized maven.config entries: " + unrecongized);
            }
        }
    } catch (ParseException e) {
        System.err.println("Unable to parse maven.config: " + e.getMessage());
        cliManager.displayHelp(output);
        throw e;
    }

    try {
        args.addAll(0, Arrays.asList(cliRequest.getArgs()));
        cliRequest.setCommandLine(cliManager.parse(args.toArray(new String[args.size()])));
    } catch (ParseException e) {
        System.err.println("Unable to parse command line options: " + e.getMessage());
        cliManager.displayHelp(output);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        cliManager.displayHelp(ps);
        throw e;
    }

    if (cliRequest.getCommandLine().hasOption(CLIManager.HELP)) {
        cliManager.displayHelp(output);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        cliManager.displayHelp(ps);
        throw new ExitException(0);
    }

    if (cliRequest.getCommandLine().hasOption(CLIManager.VERSION)) {
        System.out.println(AFCLIReportingUtils.showVersion());
        throw new ExitException(0);
    }
}

From source file:org.kie.workbench.common.services.backend.compiler.external339.AFMavenCli.java

protected MavenExecutionRequest populateRequest(AFCliRequest cliRequest, MavenExecutionRequest request) {

    CommandLine commandLine = cliRequest.getCommandLine();
    String workingDirectory = cliRequest.getWorkingDirectory();
    boolean quiet = cliRequest.isQuiet();
    boolean showErrors = cliRequest.isShowErrors();

    String[] deprecatedOptions = { "up", "npu", "cpu", "npr" };
    for (String deprecatedOption : deprecatedOptions) {
        if (commandLine.hasOption(deprecatedOption)) {
            slf4jLogger.warn("Command line option -" + deprecatedOption
                    + " is deprecated and will be removed in future Maven versions.");
        }//from   www.  j  a  v  a 2s  .c  o m
    }

    // ----------------------------------------------------------------------
    // Now that we have everything that we need we will fire up plexus and
    // bring the maven component to life for use.
    // ----------------------------------------------------------------------

    if (commandLine.hasOption(CLIManager.BATCH_MODE)) {
        request.setInteractiveMode(false);
    }

    boolean noSnapshotUpdates = false;
    if (commandLine.hasOption(CLIManager.SUPRESS_SNAPSHOT_UPDATES)) {
        noSnapshotUpdates = true;
    }

    // ----------------------------------------------------------------------
    //
    // ----------------------------------------------------------------------

    @SuppressWarnings("unchecked")
    List<String> goals = commandLine.getArgList();

    boolean recursive = true;

    // this is the default behavior.
    String reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;

    if (commandLine.hasOption(CLIManager.NON_RECURSIVE)) {
        recursive = false;
    }

    if (commandLine.hasOption(CLIManager.FAIL_FAST)) {
        reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;
    } else if (commandLine.hasOption(CLIManager.FAIL_AT_END)) {
        reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END;
    } else if (commandLine.hasOption(CLIManager.FAIL_NEVER)) {
        reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER;
    }

    if (commandLine.hasOption(CLIManager.OFFLINE)) {
        request.setOffline(true);
    }

    boolean updateSnapshots = false;

    if (commandLine.hasOption(CLIManager.UPDATE_SNAPSHOTS)) {
        updateSnapshots = true;
    }

    String globalChecksumPolicy = null;

    if (commandLine.hasOption(CLIManager.CHECKSUM_FAILURE_POLICY)) {
        globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL;
    } else if (commandLine.hasOption(CLIManager.CHECKSUM_WARNING_POLICY)) {
        globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN;
    }

    File baseDirectory = new File(workingDirectory, "").getAbsoluteFile();

    // ----------------------------------------------------------------------
    // Profile Activation
    // ----------------------------------------------------------------------

    List<String> activeProfiles = new ArrayList<String>();

    List<String> inactiveProfiles = new ArrayList<String>();

    if (commandLine.hasOption(CLIManager.ACTIVATE_PROFILES)) {
        String[] profileOptionValues = commandLine.getOptionValues(CLIManager.ACTIVATE_PROFILES);
        if (profileOptionValues != null) {
            for (String profileOptionValue : profileOptionValues) {
                StringTokenizer profileTokens = new StringTokenizer(profileOptionValue, ",");

                while (profileTokens.hasMoreTokens()) {
                    String profileAction = profileTokens.nextToken().trim();

                    if (profileAction.startsWith("-") || profileAction.startsWith("!")) {
                        inactiveProfiles.add(profileAction.substring(1));
                    } else if (profileAction.startsWith("+")) {
                        activeProfiles.add(profileAction.substring(1));
                    } else {
                        activeProfiles.add(profileAction);
                    }
                }
            }
        }
    }

    TransferListener transferListener;

    if (quiet) {
        transferListener = new QuietMavenTransferListener();
    } else if (request.isInteractiveMode() && !cliRequest.getCommandLine().hasOption(CLIManager.LOG_FILE)) {
        //
        // If we're logging to a file then we don't want the console transfer listener as it will spew
        // download progress all over the place
        //
        transferListener = getConsoleTransferListener();
    } else {
        transferListener = getBatchTransferListener();
    }

    ExecutionListener executionListener = new ExecutionEventLogger();

    if (eventSpyDispatcher != null) {
        executionListener = eventSpyDispatcher.chainListener(executionListener);
    }

    String alternatePomFile = null;
    if (commandLine.hasOption(CLIManager.ALTERNATE_POM_FILE)) {
        alternatePomFile = commandLine.getOptionValue(CLIManager.ALTERNATE_POM_FILE);
    }

    request.setBaseDirectory(baseDirectory).setGoals(goals)
            .setSystemProperties(cliRequest.getSystemProperties())
            .setUserProperties(cliRequest.getUserProperties())
            .setReactorFailureBehavior(reactorFailureBehaviour) // default: fail fast
            .setRecursive(recursive) // default: true
            .setShowErrors(showErrors) // default: false
            .addActiveProfiles(activeProfiles) // optional
            .addInactiveProfiles(inactiveProfiles) // optional
            .setExecutionListener(executionListener).setTransferListener(transferListener) // default: batch mode which goes along with interactive
            .setUpdateSnapshots(updateSnapshots) // default: false
            .setNoSnapshotUpdates(noSnapshotUpdates) // default: false
            .setGlobalChecksumPolicy(globalChecksumPolicy) // default: warn
            .setMultiModuleProjectDirectory(new File(cliRequest.getMultiModuleProjectDirectory()));

    if (alternatePomFile != null) {
        File pom = resolveFile(new File(alternatePomFile.trim()), workingDirectory);
        if (pom.isDirectory()) {
            pom = new File(pom, "pom.xml");
        }

        request.setPom(pom);
    } else if (modelProcessor != null) {
        File pom = modelProcessor.locatePom(baseDirectory);

        if (pom.isFile()) {
            request.setPom(pom);
        }
    }

    if ((request.getPom() != null) && (request.getPom().getParentFile() != null)) {
        request.setBaseDirectory(request.getPom().getParentFile());
    }

    if (commandLine.hasOption(CLIManager.RESUME_FROM)) {
        request.setResumeFrom(commandLine.getOptionValue(CLIManager.RESUME_FROM));
    }

    if (commandLine.hasOption(CLIManager.PROJECT_LIST)) {
        String[] projectOptionValues = commandLine.getOptionValues(CLIManager.PROJECT_LIST);

        List<String> inclProjects = new ArrayList<String>();
        List<String> exclProjects = new ArrayList<String>();

        if (projectOptionValues != null) {
            for (String projectOptionValue : projectOptionValues) {
                StringTokenizer projectTokens = new StringTokenizer(projectOptionValue, ",");

                while (projectTokens.hasMoreTokens()) {
                    String projectAction = projectTokens.nextToken().trim();

                    if (projectAction.startsWith("-") || projectAction.startsWith("!")) {
                        exclProjects.add(projectAction.substring(1));
                    } else if (projectAction.startsWith("+")) {
                        inclProjects.add(projectAction.substring(1));
                    } else {
                        inclProjects.add(projectAction);
                    }
                }
            }
        }

        request.setSelectedProjects(inclProjects);
        request.setExcludedProjects(exclProjects);
    }

    if (commandLine.hasOption(CLIManager.ALSO_MAKE)
            && !commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
        request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_UPSTREAM);
    } else if (!commandLine.hasOption(CLIManager.ALSO_MAKE)
            && commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
        request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM);
    } else if (commandLine.hasOption(CLIManager.ALSO_MAKE)
            && commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
        request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_BOTH);
    }

    String localRepoProperty = request.getUserProperties().getProperty(MavenCli.LOCAL_REPO_PROPERTY);

    if (localRepoProperty == null) {
        localRepoProperty = request.getSystemProperties().getProperty(MavenCli.LOCAL_REPO_PROPERTY);
    }

    if (localRepoProperty != null) {
        request.setLocalRepositoryPath(localRepoProperty);
    }

    request.setCacheNotFound(true);
    request.setCacheTransferError(false);

    //
    // Builder, concurrency and parallelism
    //
    // We preserve the existing methods for builder selection which is to look for various inputs in the threading
    // configuration. We don't have an easy way to allow a pluggable builder to provide its own configuration
    // parameters but this is sufficient for now. Ultimately we want components like Builders to provide a way to
    // extend the command line to accept its own configuration parameters.
    //
    final String threadConfiguration = commandLine.hasOption(CLIManager.THREADS)
            ? commandLine.getOptionValue(CLIManager.THREADS)
            : request.getSystemProperties().getProperty(MavenCli.THREADS_DEPRECATED); // TODO: Remove this setting. Note that the int-tests use it

    if (threadConfiguration != null) {
        //
        // Default to the standard multithreaded builder
        //
        request.setBuilderId("multithreaded");

        if (threadConfiguration.contains("C")) {
            request.setDegreeOfConcurrency(calculateDegreeOfConcurrencyWithCoreMultiplier(threadConfiguration));
        } else {
            request.setDegreeOfConcurrency(Integer.valueOf(threadConfiguration));
        }
    }

    //
    // Allow the builder to be overriden by the user if requested. The builders are now pluggable.
    //
    if (commandLine.hasOption(CLIManager.BUILDER)) {
        request.setBuilderId(commandLine.getOptionValue(CLIManager.BUILDER));
    }

    return request;
}

From source file:org.kie.workbench.common.services.backend.compiler.impl.external339.AFMavenCli.java

protected void cli(AFCliRequest cliRequest) throws Exception {
    ////ww  w .  j  a v a2  s . c om
    // Parsing errors can happen during the processing of the arguments and we prefer not having to check if
    // the logger is null and construct this so we can use an SLF4J logger everywhere.
    //
    slf4jLogger = new Slf4jStdoutLogger();

    /** promoted as a class variable and single instance because with multiple instances
     * on moderate/heavy load the parse of the argumentsub produce mistakes */
    //CLIManager cliManager = new CLIManager();

    List<String> args = new ArrayList<String>();

    try {
        Path configFile = Paths.get(cliRequest.getMultiModuleProjectDirectory(), ".mvn/maven.config");

        if (java.nio.file.Files.isRegularFile(configFile)) {
            for (String arg : Files.toString(configFile.toFile(), Charsets.UTF_8).split("\\s+")) {
                args.add(arg);
            }

            CommandLine config = cliManager.parse(args.toArray(new String[args.size()]));
            List<?> unrecongized = config.getArgList();
            if (!unrecongized.isEmpty()) {
                throw new ParseException("Unrecognized maven.config entries: " + unrecongized);
            }
        }
    } catch (ParseException e) {
        System.err.println("Unable to parse maven.config: " + e.getMessage());
        cliManager.displayHelp(output);
        throw e;
    }

    try {
        args.addAll(0, Arrays.asList(cliRequest.getArgs()));
        cliRequest.setCommandLine(cliManager.parse(args.toArray(new String[args.size()])));
    } catch (ParseException e) {
        System.err.println("Unable to parse command line options: " + e.getMessage());
        cliManager.displayHelp(output);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        cliManager.displayHelp(ps);
        throw e;
    }

    if (cliRequest.getCommandLine().hasOption(CLIManager.HELP)) {
        cliManager.displayHelp(output);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        cliManager.displayHelp(ps);
        throw new ExitException(0);
    }

    if (cliRequest.getCommandLine().hasOption(CLIManager.VERSION)) {
        System.out.println(AFCLIReportingUtils.showVersion());
        throw new ExitException(0);
    }
}

From source file:org.kie.workbench.common.services.backend.compiler.impl.external339.ReusableAFMavenCli.java

protected void cli(AFCliRequest cliRequest) throws Exception {
    ///*  www.  j a va2 s  . co m*/
    // Parsing errors can happen during the processing of the arguments and we prefer not having to check if
    // the logger is null and construct this so we can use an SLF4J logger everywhere.
    //
    reusableSlf4jLogger = new Slf4jStdoutLogger();

    /** promoted as a class variable and single instance because with multiple instances
     * on moderate/heavy load the parse of the argumentsub produce mistakes */
    //CLIManager cliManager = new CLIManager();

    List<String> args = new ArrayList<String>();

    try {
        Path configFile = Paths.get(cliRequest.getMultiModuleProjectDirectory(), ".mvn/maven.config");

        if (java.nio.file.Files.isRegularFile(configFile)) {
            for (String arg : Files.toString(configFile.toFile(), Charsets.UTF_8).split("\\s+")) {
                args.add(arg);
            }

            CommandLine config = cliManager.parse(args.toArray(new String[args.size()]));
            List<?> unrecongized = config.getArgList();
            if (!unrecongized.isEmpty()) {
                throw new ParseException("Unrecognized maven.config entries: " + unrecongized);
            }
        }
    } catch (ParseException e) {
        System.err.println("Unable to parse maven.config: " + e.getMessage());
        cliManager.displayHelp(output);
        throw e;
    }

    try {
        args.addAll(0, Arrays.asList(cliRequest.getArgs()));
        cliRequest.setCommandLine(cliManager.parse(args.toArray(new String[args.size()])));
    } catch (ParseException e) {
        System.err.println("Unable to parse command line options: " + e.getMessage());
        cliManager.displayHelp(output);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        cliManager.displayHelp(ps);
        throw e;
    }

    if (cliRequest.getCommandLine().hasOption(CLIManager.HELP)) {
        cliManager.displayHelp(output);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        cliManager.displayHelp(ps);
        throw new ExitException(0);
    }

    if (cliRequest.getCommandLine().hasOption(CLIManager.VERSION)) {
        System.out.println(AFCLIReportingUtils.showVersion());
        throw new ExitException(0);
    }
}

From source file:org.kie.workbench.common.services.backend.compiler.impl.external339.ReusableAFMavenCli.java

protected MavenExecutionRequest populateRequest(AFCliRequest cliRequest, MavenExecutionRequest request) {

    CommandLine commandLine = cliRequest.getCommandLine();
    String workingDirectory = cliRequest.getWorkingDirectory();
    boolean quiet = cliRequest.isQuiet();
    boolean showErrors = cliRequest.isShowErrors();

    String[] deprecatedOptions = { "up", "npu", "cpu", "npr" };
    for (String deprecatedOption : deprecatedOptions) {
        if (commandLine.hasOption(deprecatedOption)) {
            reusableSlf4jLogger.warn("Command line option -" + deprecatedOption
                    + " is deprecated and will be removed in future Maven versions.");
        }/*from   w  w  w . j a v a2s . co m*/
    }

    // ----------------------------------------------------------------------
    // Now that we have everything that we need we will fire up plexus and
    // bring the maven component to life for use.
    // ----------------------------------------------------------------------

    if (commandLine.hasOption(CLIManager.BATCH_MODE)) {
        request.setInteractiveMode(false);
    }

    boolean noSnapshotUpdates = false;
    if (commandLine.hasOption(CLIManager.SUPRESS_SNAPSHOT_UPDATES)) {
        noSnapshotUpdates = true;
    }

    // ----------------------------------------------------------------------
    //
    // ----------------------------------------------------------------------

    @SuppressWarnings("unchecked")
    List<String> goals = commandLine.getArgList();

    boolean recursive = true;

    // this is the default behavior.
    String reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;

    if (commandLine.hasOption(CLIManager.NON_RECURSIVE)) {
        recursive = false;
    }

    if (commandLine.hasOption(CLIManager.FAIL_FAST)) {
        reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;
    } else if (commandLine.hasOption(CLIManager.FAIL_AT_END)) {
        reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END;
    } else if (commandLine.hasOption(CLIManager.FAIL_NEVER)) {
        reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER;
    }

    if (commandLine.hasOption(CLIManager.OFFLINE)) {
        request.setOffline(true);
    }

    boolean updateSnapshots = false;

    if (commandLine.hasOption(CLIManager.UPDATE_SNAPSHOTS)) {
        updateSnapshots = true;
    }

    String globalChecksumPolicy = null;

    if (commandLine.hasOption(CLIManager.CHECKSUM_FAILURE_POLICY)) {
        globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL;
    } else if (commandLine.hasOption(CLIManager.CHECKSUM_WARNING_POLICY)) {
        globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN;
    }

    File baseDirectory = new File(workingDirectory, "").getAbsoluteFile();

    // ----------------------------------------------------------------------
    // Profile Activation
    // ----------------------------------------------------------------------

    List<String> activeProfiles = new ArrayList<String>();

    List<String> inactiveProfiles = new ArrayList<String>();

    if (commandLine.hasOption(CLIManager.ACTIVATE_PROFILES)) {
        String[] profileOptionValues = commandLine.getOptionValues(CLIManager.ACTIVATE_PROFILES);
        if (profileOptionValues != null) {
            for (String profileOptionValue : profileOptionValues) {
                StringTokenizer profileTokens = new StringTokenizer(profileOptionValue, ",");

                while (profileTokens.hasMoreTokens()) {
                    String profileAction = profileTokens.nextToken().trim();

                    if (profileAction.startsWith("-") || profileAction.startsWith("!")) {
                        inactiveProfiles.add(profileAction.substring(1));
                    } else if (profileAction.startsWith("+")) {
                        activeProfiles.add(profileAction.substring(1));
                    } else {
                        activeProfiles.add(profileAction);
                    }
                }
            }
        }
    }

    TransferListener transferListener;

    if (quiet) {
        transferListener = new QuietMavenTransferListener();
    } else if (request.isInteractiveMode() && !cliRequest.getCommandLine().hasOption(CLIManager.LOG_FILE)) {
        //
        // If we're logging to a file then we don't want the console transfer listener as it will spew
        // download progress all over the place
        //
        transferListener = getConsoleTransferListener();
    } else {
        transferListener = getBatchTransferListener();
    }

    ExecutionListener executionListener = new ExecutionEventLogger();

    if (reusableEventSpyDispatcher != null) {
        executionListener = reusableEventSpyDispatcher.chainListener(executionListener);
    }

    String alternatePomFile = null;
    if (commandLine.hasOption(CLIManager.ALTERNATE_POM_FILE)) {
        alternatePomFile = commandLine.getOptionValue(CLIManager.ALTERNATE_POM_FILE);
    }

    request.setBaseDirectory(baseDirectory).setGoals(goals)
            .setSystemProperties(cliRequest.getSystemProperties())
            .setUserProperties(cliRequest.getUserProperties())
            .setReactorFailureBehavior(reactorFailureBehaviour) // default: fail fast
            .setRecursive(recursive) // default: true
            .setShowErrors(showErrors) // default: false
            .addActiveProfiles(activeProfiles) // optional
            .addInactiveProfiles(inactiveProfiles) // optional
            .setExecutionListener(executionListener).setTransferListener(transferListener) // default: batch mode which goes along with interactive
            .setUpdateSnapshots(updateSnapshots) // default: false
            .setNoSnapshotUpdates(noSnapshotUpdates) // default: false
            .setGlobalChecksumPolicy(globalChecksumPolicy) // default: warn
            .setMultiModuleProjectDirectory(new File(cliRequest.getMultiModuleProjectDirectory()));

    if (alternatePomFile != null) {
        File pom = resolveFile(new File(alternatePomFile.trim()), workingDirectory);
        if (pom.isDirectory()) {
            pom = new File(pom, "pom.xml");
        }

        request.setPom(pom);
    } else if (reusableModelProcessor != null) {
        File pom = reusableModelProcessor.locatePom(baseDirectory);

        if (pom.isFile()) {
            request.setPom(pom);
        }
    }

    if ((request.getPom() != null) && (request.getPom().getParentFile() != null)) {
        request.setBaseDirectory(request.getPom().getParentFile());
    }

    if (commandLine.hasOption(CLIManager.RESUME_FROM)) {
        request.setResumeFrom(commandLine.getOptionValue(CLIManager.RESUME_FROM));
    }

    if (commandLine.hasOption(CLIManager.PROJECT_LIST)) {
        String[] projectOptionValues = commandLine.getOptionValues(CLIManager.PROJECT_LIST);

        List<String> inclProjects = new ArrayList<String>();
        List<String> exclProjects = new ArrayList<String>();

        if (projectOptionValues != null) {
            for (String projectOptionValue : projectOptionValues) {
                StringTokenizer projectTokens = new StringTokenizer(projectOptionValue, ",");

                while (projectTokens.hasMoreTokens()) {
                    String projectAction = projectTokens.nextToken().trim();

                    if (projectAction.startsWith("-") || projectAction.startsWith("!")) {
                        exclProjects.add(projectAction.substring(1));
                    } else if (projectAction.startsWith("+")) {
                        inclProjects.add(projectAction.substring(1));
                    } else {
                        inclProjects.add(projectAction);
                    }
                }
            }
        }

        request.setSelectedProjects(inclProjects);
        request.setExcludedProjects(exclProjects);
    }

    if (commandLine.hasOption(CLIManager.ALSO_MAKE)
            && !commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
        request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_UPSTREAM);
    } else if (!commandLine.hasOption(CLIManager.ALSO_MAKE)
            && commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
        request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM);
    } else if (commandLine.hasOption(CLIManager.ALSO_MAKE)
            && commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
        request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_BOTH);
    }

    String localRepoProperty = request.getUserProperties().getProperty(MavenCli.LOCAL_REPO_PROPERTY);

    if (localRepoProperty == null) {
        localRepoProperty = request.getSystemProperties().getProperty(MavenCli.LOCAL_REPO_PROPERTY);
    }

    if (localRepoProperty != null) {
        request.setLocalRepositoryPath(localRepoProperty);
    }

    request.setCacheNotFound(true);
    request.setCacheTransferError(false);

    //
    // Builder, concurrency and parallelism
    //
    // We preserve the existing methods for builder selection which is to look for various inputs in the threading
    // configuration. We don't have an easy way to allow a pluggable builder to provide its own configuration
    // parameters but this is sufficient for now. Ultimately we want components like Builders to provide a way to
    // extend the command line to accept its own configuration parameters.
    //
    final String threadConfiguration = commandLine.hasOption(CLIManager.THREADS)
            ? commandLine.getOptionValue(CLIManager.THREADS)
            : request.getSystemProperties().getProperty(MavenCli.THREADS_DEPRECATED); // TODO: Remove this setting. Note that the int-tests use it

    if (threadConfiguration != null) {
        //
        // Default to the standard multithreaded builder
        //
        request.setBuilderId("multithreaded");

        if (threadConfiguration.contains("C")) {
            request.setDegreeOfConcurrency(calculateDegreeOfConcurrencyWithCoreMultiplier(threadConfiguration));
        } else {
            request.setDegreeOfConcurrency(Integer.valueOf(threadConfiguration));
        }
    }

    //
    // Allow the builder to be overriden by the user if requested. The builders are now pluggable.
    //
    if (commandLine.hasOption(CLIManager.BUILDER)) {
        request.setBuilderId(commandLine.getOptionValue(CLIManager.BUILDER));
    }

    return request;
}