Example usage for org.apache.commons.cli Option getOpt

List of usage examples for org.apache.commons.cli Option getOpt

Introduction

In this page you can find the example usage for org.apache.commons.cli Option getOpt.

Prototype

public String getOpt() 

Source Link

Document

Retrieve the name of this Option.

Usage

From source file:com.milaboratory.mitcr.cli.Main.java

public static void printHelp() {
    HelpFormatter formatter = new HelpFormatter();
    formatter.setOptionComparator(new Comparator<Option>() {
        @Override// www.java2 s  .c o m
        public int compare(Option o1, Option o2) {
            return Integer.compare(orderingMap.get(o1.getOpt()), orderingMap.get(o2.getOpt()));
        }
    });
    final String executable = System.getProperty("executable", "java -jar mitcr.jar");
    err.println("usage: " + executable + " -pset <preset name> [options] input_file output_file.cls");
    err.println("       " + executable + " -pset <preset name> [options] input_file output_file.txt");
    err.println("       " + executable + " -pset <preset name> [options] -export newPresetName");
    err.println();

    formatter.printOptions(new PrintWriter(err, true), 85, options, 2, 3);
    err.println();
}

From source file:eu.project.ttc.tools.cli.TermSuiteCLIUtils.java

/**
 * Displays all command line options in log messages.
 * @param line//www.j a va 2s .  com
 */
public static void logCommandLineOptions(CommandLine line) {
    for (Option myOption : line.getOptions()) {
        String message;
        String opt = "";
        if (myOption.getOpt() != null) {
            opt += "-" + myOption.getOpt();
            if (myOption.getLongOpt() != null)
                opt += " (--" + myOption.getLongOpt() + ")";
        } else
            opt += "--" + myOption.getLongOpt() + "";

        if (myOption.hasArg())
            message = opt + " " + myOption.getValue();
        else
            message = opt;

        LOGGER.info("with option: " + message);
    }
}

From source file:com.spectralogic.ds3cli.Arguments.java

public static boolean matchesOption(final Option opt, final String token) {
    return token.equals('-' + opt.getOpt()) || token.equals("--" + opt.getLongOpt());
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.app.Main.java

private static void parseCli(String[] args) {
    CommandLineParser parser = new PosixParser();
    try {//from  www .ja v  a 2s.  c  om
        CommandLine cmd = parser.parse(options, args);

        // Show usage, ignore other parameters and quit
        if (cmd.hasOption('h')) {
            usage();
            logger.debug("Help called, main() exit.");
            System.exit(0);
        }

        if (cmd.hasOption('d')) {
            // Activate debug markup only - does not affect logging!
            debugMarkupOutput = true;
        }

        if (cmd.hasOption('m')) {
            exportMarkup = true;
        }

        if (cmd.hasOption('t')) {
            title = cmd.getOptionValue('t');
        }

        if (cmd.hasOption('f')) {
            filename = cmd.getOptionValue('f');
        }

        if (cmd.hasOption('n')) {
            exportMarkup = true; // implicit markup export
            noMobiConversion = true;
        }

        if (cmd.hasOption('i')) {
            String[] inputValues = cmd.getOptionValues('i');
            for (String inputValue : inputValues) {
                inputPaths.add(Paths.get(inputValue));
            }
        } else {
            logger.error("You have to specify an inputPath file or directory!");
            usage();
            System.exit(1);
        }

        if (cmd.hasOption('o')) {
            String outputDirectory = cmd.getOptionValue('o');

            outputPath = Paths.get(outputDirectory).toAbsolutePath();
            logger.debug("Output path: " + outputPath.toAbsolutePath().toString());
            if (!Files.isDirectory(outputPath) && Files.isRegularFile(outputPath)) {
                logger.error("Given output directory is a file! Exiting...");

                System.exit(1);
            }

            if (!Files.exists(outputPath)) {
                Files.createDirectory(outputPath);
            }

            if (!Files.isWritable(outputPath)) {
                logger.error("Given output directory is not writable! Exiting...");
                logger.debug(outputPath.toAbsolutePath().toString());
                System.exit(1);
            }
            logger.debug("Output path: " + outputPath.toAbsolutePath().toString());

        } else {
            // Set default output directory if none is given
            outputPath = workingDirectory;
        }

        // If set, replace LaTeX Formulas with PNG images, created by
        if (cmd.hasOption("r")) {
            logger.debug("Picture Flag set");
            replaceWithPictures = true;
        }

        if (cmd.hasOption("u")) {
            logger.debug("Use calibre instead of kindlegen");
            useCalibreInsteadOfKindleGen = true;
        }

        // Executable configuration
        LatexToHtmlConverter latexToHtmlConverter = (LatexToHtmlConverter) applicationContext
                .getBean("latex2html-converter");
        if (cmd.hasOption(latexToHtmlConverter.getExecOption().getOpt())) {
            String execValue = cmd.getOptionValue(latexToHtmlConverter.getExecOption().getOpt());
            logger.info("LaTeX to HTML Executable argument was given: " + execValue);
            Path execPath = Paths.get(execValue);
            latexToHtmlConverter.setExecPath(execPath);
        }

        String htmlToMobiConverterBean = KINDLEGEN_HTML2MOBI_CONVERTER;
        if (useCalibreInsteadOfKindleGen) {
            htmlToMobiConverterBean = CALIBRE_HTML2MOBI_CONVERTER;
        }

        HtmlToMobiConverter htmlToMobiConverter = (HtmlToMobiConverter) applicationContext
                .getBean(htmlToMobiConverterBean);
        Option htmlToMobiOption = htmlToMobiConverter.getExecOption();
        if (cmd.hasOption(htmlToMobiOption.getOpt())) {
            String execValue = cmd.getOptionValue(htmlToMobiOption.getOpt());
            logger.info("HTML to Mobi Executable argument was given: " + execValue);
            try {
                Path execPath = Paths.get(execValue);
                htmlToMobiConverter.setExecPath(execPath);
            } catch (InvalidPathException e) {
                logger.error("Invalid path given for --" + htmlToMobiOption.getLongOpt() + " <"
                        + htmlToMobiOption.getArgName() + ">");
                logger.error("I will try to use your system's PATH variable...");
            }
        }

    } catch (MissingOptionException m) {

        Iterator<String> missingOptionsIterator = m.getMissingOptions().iterator();
        while (missingOptionsIterator.hasNext()) {
            logger.error("Missing required options: " + missingOptionsIterator.next() + "\n");
        }
        usage();
        System.exit(1);
    } catch (MissingArgumentException a) {
        logger.error("Missing required argument for option: " + a.getOption().getOpt() + "/"
                + a.getOption().getLongOpt() + "<" + a.getOption().getArgName() + ">");
        usage();
        System.exit(2);
    } catch (ParseException e) {
        logger.error("Error parsing command line arguments, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(3);
    } catch (IOException e) {
        logger.error("Error creating output path at " + outputPath.toAbsolutePath().toString());
        logger.error(e.getMessage(), e);
        logger.error("Exiting...");
        System.exit(4);
    }
}

From source file:EditBinFile.java

private static void printHelp(Options options) {

    Collection list = options.getOptions();
    Iterator iterator = list.iterator();

    // while loop
    String tmp = "";
    Option otmp;
    while (iterator.hasNext()) {
        otmp = (Option) iterator.next();
        System.out.println(String.format("%-15s %s", "-" + otmp.getOpt(), otmp.getDescription()));
    }// w w w .  j a v a 2s .c  o  m
}

From source file:de.bmw.yamaica.common.console.CommandExecuter.java

/**
 * Converts an instance the CommandLine Object into an array of strings.
 *
 * @param commandLine//from  w w  w  .  ja  v  a2 s .c om
 *            instance
 * @param keepIdOption
 *            if true the returned array will contain the ID option if available
 * @return Arguments split into string array
 */
public static String[] getArguments(CommandLine commandLine, boolean keepIdOption) {
    Assert.isNotNull(commandLine);

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

    Option[] options = commandLine.getOptions();

    if (null != options) {
        for (Option option : options) {
            String optionString = option.getOpt();

            if (keepIdOption == false && SHORT_ID_OPTION.equals(optionString)) {
                continue;
            }

            argumentsList.add("-" + optionString);

            String[] values = option.getValues();

            if (null != values) {
                for (String value : values) {
                    argumentsList.add(value);
                }
            }
        }
    }

    return argumentsList.toArray(new String[argumentsList.size()]);
}

From source file:net.sf.markov4jmeter.behaviormodelextractor.CommandLineArgumentsHandler.java

/**
 * Reads the value for a given option from the specified command-line as
 * <code>int</code>.//  w  w  w  . j  a  va 2  s  .c  o m
 * 
 * @param commandLine
 *            command-line which provides the values.
 * @param option
 *            option whose value shall be read from command-line.
 * 
 * @return an <code>int</code> value which is 0, if the option's value is
 *         optional and undefined.
 * 
 * @throws NullPointerException
 *             in case the value is required, but could not be read as
 *             <code>int</code>.
 * @throws NumberFormatException
 *             if the parsed value does not denote an <code>int</code>
 *             value.
 */
private static int readOptionValueAsInt(final CommandLine commandLine, final Option option)
        throws NullPointerException, NumberFormatException {

    int value; // to be returned;

    final String opt = option.getOpt();

    // build an instance for reading "typed" options from command-line;
    final CmdlOptionsReader cmdlOptionsReader = new CmdlOptionsReader(commandLine);

    try {

        // might throw a NullPointer- or NumberFormatException;
        value = cmdlOptionsReader.readOptionValueAsInt(opt);

    } catch (final Exception ex) {

        if (option.isRequired()) {

            throw ex;

        } else {

            value = 0; // accept undefined value for optional option;
        }
    }

    return value;
}

From source file:net.sf.markov4jmeter.behaviormodelextractor.CommandLineArgumentsHandler.java

/**
 * Reads the value for a given option from the specified command-line as
 * <code>String</code>./*from   www.ja  va 2  s  . c  o  m*/
 * 
 * @param commandLine
 *            command-line which provides the values.
 * @param option
 *            option whose value shall be read from command-line.
 * 
 * @return a valid <code>String</code>, or <code>null</code> if the option's
 *         value is optional and undefined.
 * 
 * @throws NullPointerException
 *             in case the value is required, but could not be read as
 *             <code>String</code>.
 * @throws IllegalArgumentException
 *             if an option flag denotes an empty <code>String</code> (
 *             <code>""</code>).
 */
private static String readOptionValueAsString(final CommandLine commandLine, final Option option)
        throws NullPointerException, IllegalArgumentException {

    String value; // to be returned;

    final String opt = option.getOpt();

    // build an instance for reading "typed" options from command-line;
    final CmdlOptionsReader cmdlOptionsReader = new CmdlOptionsReader(commandLine);

    try {

        // might throw a NullPointer- or IllegalArgumentException;
        value = cmdlOptionsReader.readOptionValueAsString(opt);

    } catch (final Exception ex) {

        if (option.isRequired()) {

            throw ex;

        } else {

            value = null; // accept undefined value for optional option;
        }
    }

    return value;
}

From source file:com.google.api.ads.adwords.keywordoptimizer.KeywordOptimizer.java

/**
 * Returns the only specified 'seed' option or an exception if no or more than one is specified.
 *
 * @param cmdLine the parsed command line parameters
 * @return the 'seed' {@link Option}//from  w w  w . ja  v  a2 s  . c o  m
 * @throws KeywordOptimizerException in case there is no or more than one 'seed' parameter
 *         specified
 */
private static Option getOnlySeedOption(CommandLine cmdLine) throws KeywordOptimizerException {
    Option seedOption = null;

    for (Option option : cmdLine.getOptions()) {
        if (option.getOpt().startsWith("s")) {
            if (seedOption != null) {
                throw new KeywordOptimizerException("Only one 'seed' option is allowed " + "(remove either "
                        + seedOption.getOpt() + " or " + option.getOpt() + ")");
            }

            seedOption = option;
        }
    }

    if (seedOption == null) {
        throw new KeywordOptimizerException("You must specify a 'seed' parameter");
    }

    return seedOption;
}

From source file:com.asakusafw.dmdl.thundergate.Main.java

private static void checkIf(CommandLine cmd, Option target, Option condition) {
    String conditionValue = getOption(cmd, condition, false);
    if (trim(conditionValue) == null) {
        return;//from  w w w .  j a va2  s . co m
    }
    String targetValue = getOption(cmd, target, false);
    if (trim(targetValue) == null) {
        throw new IllegalArgumentException(MessageFormat.format(
                " \"-{0}\" ?????? (\"-{1}\"?????)",
                target.getOpt(), condition.getOpt()));
    }
}