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

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

Introduction

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

Prototype

public String getLongOpt() 

Source Link

Document

Retrieve the long name of this Option.

Usage

From source file:org.wikidata.wdtk.client.ClientConfiguration.java

/**
 * Analyses the command-line arguments which are relevant for the specific
 * action that is to be executed, and returns a corresponding
 * {@link DumpProcessingAction} object.// ww  w  .ja  v  a 2  s  . com
 * 
 * @param cmd
 *            {@link CommandLine} objects; contains the command line
 *            arguments parsed by a {@link CommandLineParser}
 * @return {@link DumpProcessingAction} for the given arguments
 */
private DumpProcessingAction handleActionArguments(CommandLine cmd) {

    DumpProcessingAction result = makeDumpProcessingAction(cmd.getOptionValue(CMD_OPTION_ACTION).toLowerCase());
    if (result == null) {
        return null;
    }

    for (Option option : cmd.getOptions()) {
        result.setOption(option.getLongOpt(), option.getValue());
    }

    checkDuplicateStdOutOutput(result);

    return result;
}

From source file:org.wildfly.security.tool.Command.java

/**
 * Alerts if any of the command line options used are duplicated
 * @param cmdLine the command line options used when invoking the command, after parsing
 *//*from  w  ww  . ja va 2s .  c  o  m*/
public void printDuplicatesWarning(CommandLine cmdLine) {
    List<Option> optionsList = new ArrayList<>(Arrays.asList(cmdLine.getOptions()));
    Set<Option> duplicatesSet = new HashSet<>();
    for (Option option : cmdLine.getOptions()) {
        if (Collections.frequency(optionsList, option) > 1) {
            duplicatesSet.add(option);
        }
    }

    for (Option option : duplicatesSet) {
        System.out.println(ElytronToolMessages.msg.duplicateOptionSpecified(option.getLongOpt()));
    }
}

From source file:org.wildfly.security.tool.Command.java

/**
 * Alerts if any of the command line options used are duplicated, excluding commands
 * that are allowed to have duplicates//from  ww  w .  j  a  v a 2  s.co m
 * @param cmdLine the command line options used when invoking the command, after parsing
 * @param duplicatesAllowed list of the commands line options that can be duplicated. For example:
 *                          <code>
 *                              List<String> allowedDuplicates = new ArrayList<String>()
 *                                  {{ add(PASSWORD_CREDENTIAL_VALUE_PARAM);
*                                  }};
 *                          </code>
 */
public void printDuplicatesWarning(CommandLine cmdLine, List<String> duplicatesAllowed) {
    if (duplicatesAllowed == null) {
        return;
    }

    List<Option> optionsList = new ArrayList<>(Arrays.asList(cmdLine.getOptions()));
    Set<Option> duplicatesSet = new HashSet<>();
    for (Option option : cmdLine.getOptions()) {
        if (Collections.frequency(optionsList, option) > 1
                && !duplicatesAllowed.contains(option.getLongOpt())) {
            duplicatesSet.add(option);
        }
    }

    for (Option option : duplicatesSet) {
        System.out.println(ElytronToolMessages.msg.duplicateOptionSpecified(option.getLongOpt()));
    }
}

From source file:org.wildfly.security.tool.ElytronTool.java

/**
 * Main method to call from scripts./*from ww  w  . j a va  2 s .c o m*/
 *
 * @param args parameters to pass farther. The first parameter is name or alias of the command.
 */
public static void main(String[] args) {

    Security.addProvider(new WildFlyElytronProvider());

    ElytronTool tool = new ElytronTool();
    if (args != null && args.length > 0) {
        if (args[0].startsWith("{")) {
            tool.scriptName = args[0].substring(1, args[0].indexOf('}'));
            args[0] = args[0].substring(args[0].indexOf('}') + 1);
        }
        Command command = tool.findCommand(args[0]);
        if (command != null && tool.scriptName != null) {
            command.setToolCommand(tool.scriptName);
        }
        String[] newArgs = new String[args.length - 1];
        System.arraycopy(args, 1, newArgs, 0, args.length - 1);
        if (command != null && newArgs.length > 0) {
            try {
                command.execute(newArgs);
                System.exit(command.getStatus());
            } catch (Exception e) {
                if (e instanceof AlreadySelectedException) {
                    Option option = ((AlreadySelectedException) e).getOption();
                    System.err.println(ElytronToolMessages.msg.longOptionDescription(option.getOpt(),
                            option.getLongOpt()));
                }
                if (command.isEnableDebug()) {
                    System.err.println(ElytronToolMessages.msg.commandExecuteException());
                    e.printStackTrace(System.err);
                } else {
                    if (e.getLocalizedMessage() != null && (e.getLocalizedMessage().startsWith("ELYTOOL")
                            || e instanceof org.apache.commons.cli.ParseException)) {
                        System.err.println(ElytronToolMessages.msg.commandExecuteException());
                        System.err.println(e.getLocalizedMessage());
                    } else {
                        System.err.println(ElytronToolMessages.msg.commandExecuteExceptionNoDebug());
                    }
                }
                System.exit(command.getStatus());
            }
        } else if ("--help".equals(args[0]) || "-h".equals(args[0])) {
            tool.generalHelp();
        } else if (command != null) {
            command.help();
        } else {
            if (args[0].trim().isEmpty() && newArgs.length == 0) {
                tool.generalHelp();
            } else {
                System.err.println(ElytronToolMessages.msg.commandOrAliasNotFound(args[0]));
                System.exit(ElytronToolExitStatus_unrecognizedCommand);
            }
        }
    } else {
        // no arguments supplied, print general help message and exist.
        tool.generalHelp();
    }
}

From source file:oxis.yologp.CommandLineMain.java

public void printHelp() {

    for (Object obj : options.getOptions().toArray(new Option[0])) {
        Option opt = (Option) obj;
        System.out.println(/*from  w  w w. j a  va 2  s.  c  o  m*/
                String.format("  -%s|--%-30s ", opt.getOpt(), opt.getLongOpt()) + opt.getDescription());
    }
    System.exit(0);
}

From source file:scoutdoc.main.Main.java

/**
 * @param args//from   ww  w . jav  a  2 s .co  m
 */
public static void main(String[] args) {
    Option optHelp = new Option(HELP_ID, "help", false, "print this message");

    Option optProp = new Option(PROP_ID, "config", true, "configuration file");
    optProp.setArgName("file");

    //source
    Option optTask = new Option(SOURCE_TASKS_ID, "task", true, "(source) one or many task files");
    optTask.setArgName("files");
    optTask.setArgs(Option.UNLIMITED_VALUES);

    Option optAllPages = new Option(SOURCE_ALL_PAGES_ID, "pages", false,
            "(source) use the pages contained in the source folder");

    Option optListPages = new Option(SOURCE_LIST_ID, "list", true,
            "(source) list of pages contained in the file");
    optListPages.setArgName("file");

    Option optRecentChange = new Option(SOURCE_RECENT_CHANGES_ID, "recent-changes", false,
            "(source) use the pages from the wiki recent changes");

    Option optRss = new Option(SOURCE_RSS_ID, "rss", false,
            "(source) use the pages from the rss feed of the wiki");

    OptionGroup sourceGroup = new OptionGroup();
    sourceGroup.setRequired(true);
    sourceGroup.addOption(optTask);
    sourceGroup.addOption(optAllPages);
    sourceGroup.addOption(optListPages);
    sourceGroup.addOption(optRecentChange);
    sourceGroup.addOption(optRss);

    Option optfilter = new Option(SOURCE_FILTER_ID, "filter", true, "Filter for list of pages used as source");
    optfilter.setArgName("class");

    List<String> values = Lists.newArrayList();
    for (Operation o : Operation.values()) {
        values.add(o.name());
    }
    Option optOperation = new Option(OPERATION_ID, "operation", true,
            "operation: " + Joiner.on(", ").join(values));
    optOperation.setArgName("operations");
    optOperation.setArgs(Option.UNLIMITED_VALUES);
    optOperation.setRequired(true);

    Option optOutputCheckstyle = new Option(OUTPUT_CHECKSTYLE_ID, "output-checkstyle", true,
            "(CHECK output) create a xml checkstyle file (<filename> is optional. Default: "
                    + DEFAULT_CHECKSTYLE_NAME + ")");
    optOutputCheckstyle.setArgName("filename");
    optOutputCheckstyle.setOptionalArg(true);

    Option optOutputDashboard = new Option(OUTPUT_DASHBOARD_ID, "output-dashboard", true,
            "(CHECK output) create an html dashboard (<folder> is optional. Default: " + DEFAULT_DASHBOARD_NAME
                    + ")");
    optOutputDashboard.setArgName("folder");
    optOutputDashboard.setOptionalArg(true);

    Options options = new Options();
    options.addOption(optHelp);
    options.addOption(optProp);
    options.addOptionGroup(sourceGroup);
    options.addOption(optfilter);
    options.addOption(optOperation);
    options.addOption(optOutputCheckstyle);
    options.addOption(optOutputDashboard);

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption(HELP_ID)) {
            printHelpAndExit(options);
        }

        if (cmd.hasOption(PROP_ID)) {
            ProjectProperties.initProperties(cmd.getOptionValue(PROP_ID));
        }
        Pages.initPageList();

        List<Operation> operations = readOptionEnum(cmd, optOperation, Operation.class);
        List<Task> tasks = readTasks(cmd, optTask);

        Collection<Page> pageList;
        if (cmd.hasOption(SOURCE_ALL_PAGES_ID)) {
            pageList = PageUtility.loadPages(ProjectProperties.getFolderWikiSource());
        } else if (cmd.hasOption(SOURCE_LIST_ID)) {
            String name = cmd.getOptionValue(SOURCE_LIST_ID);
            try {
                pageList = PageUtility.readList(name);
            } catch (IOException e) {
                throw new MissingArgumentException("IOException for file <" + name + "> for <"
                        + optListPages.getLongOpt() + "> : " + e.getMessage());
            }
        } else {
            pageList = Collections.emptyList();
        }

        IPageFilter filter;
        if (cmd.hasOption(SOURCE_FILTER_ID)) {
            if (tasks.size() > 0) {
                throw new MissingArgumentException("Filter <" + optfilter.getLongOpt()
                        + "> is not allowed for source <" + optTask.getLongOpt() + ">.");
            }
            filter = newInstance(cmd.getOptionValue(SOURCE_FILTER_ID), IPageFilter.class,
                    new AcceptAllPageFilter());
        } else {
            filter = new AcceptAllPageFilter();
        }
        List<Page> pages = Lists.newArrayList();
        for (Page page : pageList) {
            if (filter.keepPage(page)) {
                pages.add(page);
            }
        }

        if (operations.contains(Operation.FETCH)) {
            if (pages.size() > 0) {
                ScoutDocFetch sdf = new ScoutDocFetch();
                RelatedPagesStrategy strategy;
                if (cmd.hasOption(SOURCE_ALL_PAGES_ID)) {
                    strategy = RelatedPagesStrategy.NO_RELATED_PAGES;
                } else if (cmd.hasOption(SOURCE_LIST_ID)) {
                    strategy = RelatedPagesStrategy.IMAGES_TEMPLATES_AND_LINKS;
                } else {
                    throw new IllegalStateException("Page list comes from an unexpected option");
                }
                sdf.execute(pages, strategy);
            } else if (cmd.hasOption(SOURCE_RECENT_CHANGES_ID)) {
                ScoutDocFetch sdf = new ScoutDocFetch();
                sdf.executeRecentChanges(filter);
            } else if (cmd.hasOption(SOURCE_RSS_ID)) {
                ScoutDocFetch sdf = new ScoutDocFetch();
                sdf.executeRss(filter);
            } else if (tasks.size() > 0) {
                for (Task task : tasks) {
                    ScoutDocFetch sdf = new ScoutDocFetch();
                    sdf.execute(task);
                }
            } else {
                throw new MissingArgumentException("Missing a source");
            }
        }

        if (operations.contains(Operation.CHECK)) {
            ScoutDocCheck sdc = new ScoutDocCheck();
            List<Check> checks = Lists.newArrayList();
            ensureNotSet(cmd, optRecentChange, Operation.CHECK);
            ensureNotSet(cmd, optRss, Operation.CHECK);
            if (pages.size() > 0) {
                checks = sdc.analysePages(pages);
            } else if (tasks.size() > 0) {
                for (Task task : tasks) {
                    ScoutDocCheck sdcForTask = new ScoutDocCheck();
                    checks.addAll(sdcForTask.execute(task));
                }
            } else {
                throw new MissingArgumentException("Missing a source");
            }
            //output:
            if (cmd.hasOption(OUTPUT_CHECKSTYLE_ID)) {
                String fileName = cmd.getOptionValue(OUTPUT_CHECKSTYLE_ID, DEFAULT_CHECKSTYLE_NAME);
                sdc.writeCheckstyleFile(checks, fileName);
            }
            if (cmd.hasOption(OUTPUT_DASHBOARD_ID)) {
                String folderName = cmd.getOptionValue(OUTPUT_DASHBOARD_ID, DEFAULT_DASHBOARD_NAME);
                sdc.writeDashboardFiles(checks, folderName);
            }
        }

        if (operations.contains(Operation.CONVERT)) {
            ensureNotSet(cmd, optAllPages, Operation.CONVERT);
            ensureNotSet(cmd, optListPages, Operation.CONVERT);
            ensureNotSet(cmd, optRecentChange, Operation.CONVERT);
            ensureNotSet(cmd, optRss, Operation.CONVERT);
            if (tasks.size() > 0) {
                for (Task task : tasks) {
                    ScoutDocConverter sdc = new ScoutDocConverter();
                    sdc.execute(task);
                }
            } else {
                throw new MissingArgumentException("Missing a source");
            }
        }

    } catch (MissingOptionException e) {
        // Check if it is an error or if optHelp was selected.
        boolean help = false;
        try {
            Options helpOptions = new Options();
            helpOptions.addOption(optHelp);
            CommandLineParser parser = new PosixParser();
            CommandLine line = parser.parse(helpOptions, args);
            if (line.hasOption(HELP_ID)) {
                help = true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (!help) {
            System.err.println(e.getMessage());
            System.err.flush();
        }
        printHelpAndExit(options);
    } catch (MissingArgumentException e) {
        System.err.println(e.getMessage());
        printHelpAndExit(options);
    } catch (ParseException e) {
        System.err.println("Error while parsing the command line: " + e.getMessage());
        System.exit(1);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:scoutdoc.main.Main.java

private static void ensureNotSet(CommandLine cmd, Option option, Operation operation)
        throws MissingArgumentException {
    if (cmd.hasOption(option.getOpt())) {
        throw new MissingArgumentException("Source <" + option.getLongOpt() + "> is not allowed for the <"
                + operation.name() + "> operation.");
    }/*www .ja  v a  2 s  .  c  o m*/
}

From source file:scoutdoc.main.Main.java

private static <T extends Enum<T>> List<T> readOptionEnum(CommandLine cmd, Option option, Class<T> c)
        throws MissingArgumentException {
    List<T> operations = Lists.newArrayList();
    for (String name : cmd.getOptionValues(option.getOpt())) {
        try {//from   w  ww  . j  ava 2  s .  co  m
            T operation = Enum.valueOf(c, name);
            operations.add(operation);
        } catch (IllegalArgumentException e) {
            throw new MissingArgumentException(
                    "Unknown value '" + name + "' for '--" + option.getLongOpt() + "'");
        }
    }
    return operations;
}

From source file:scoutdoc.main.Main.java

private static List<Task> readTasks(CommandLine cmd, Option option) throws MissingArgumentException {
    List<Task> result = Lists.newArrayList();
    if (cmd.hasOption(option.getOpt())) {
        for (String name : cmd.getOptionValues(option.getOpt())) {
            try {
                Task task = TaskUtility.toTask(name);
                result.add(task);/* www.  ja v a2  s .c  o m*/
            } catch (IOException e) {
                throw new MissingArgumentException("IOException for file '" + name + "' for '--"
                        + option.getLongOpt() + "' : " + e.getMessage());
            }
        }
    }
    return result;
}

From source file:uk.ac.ebi.mdk.apps.CommandLineMain.java

public void showHelp() {
    for (Object obj : toArray(new Option[0])) {
        Option opt = (Option) obj;
        System.out.println(String.format("    [%s|%s]\n        %s \n", opt.getOpt(), opt.getLongOpt(),
                opt.getDescription()));//from www.  j  a  v a  2  s . c  o m
    }
    System.exit(0);
}