Example usage for org.apache.commons.cli ParseException getClass

List of usage examples for org.apache.commons.cli ParseException getClass

Introduction

In this page you can find the example usage for org.apache.commons.cli ParseException getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.dasasian.chok.tool.ZkTool.java

public static void main(String[] args) {
    final Options options = new Options();

    Option lsOption = new Option("ls", true, "list zp path contents");
    lsOption.setArgName("path");
    Option readOption = new Option("read", true, "read and print zp path contents");
    readOption.setArgName("path");
    Option rmOption = new Option("rm", true, "remove zk files");
    rmOption.setArgName("path");
    Option rmrOption = new Option("rmr", true, "remove zk directories");
    rmrOption.setArgName("path");

    OptionGroup actionGroup = new OptionGroup();
    actionGroup.setRequired(true);//from  w  w w . j a v  a  2s. c  om
    actionGroup.addOption(lsOption);
    actionGroup.addOption(readOption);
    actionGroup.addOption(rmOption);
    actionGroup.addOption(rmrOption);
    options.addOptionGroup(actionGroup);

    final CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    try {
        final CommandLine line = parser.parse(options, args);
        ZkTool zkTool = new ZkTool();
        if (line.hasOption(lsOption.getOpt())) {
            String path = line.getOptionValue(lsOption.getOpt());
            zkTool.ls(path);
        } else if (line.hasOption(readOption.getOpt())) {
            String path = line.getOptionValue(readOption.getOpt());
            zkTool.read(path);
        } else if (line.hasOption(rmOption.getOpt())) {
            String path = line.getOptionValue(rmOption.getOpt());
            zkTool.rm(path, false);
        } else if (line.hasOption(rmrOption.getOpt())) {
            String path = line.getOptionValue(rmrOption.getOpt());
            zkTool.rm(path, true);
        }
        zkTool.close();
    } catch (ParseException e) {
        System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
        formatter.printHelp(ZkTool.class.getSimpleName(), options);
    }

}

From source file:hrytsenko.csv.App.java

/**
 * Creates environment and executes script.
 * /* ww w  .  j  a  va  2 s  .c o  m*/
 * <p>
 * First argument is the filename of script, and all others will be passed into this script.
 * 
 * @param args
 *            the command-line arguments
 */
public static void main(String[] args) {
    try {
        execute(args);
    } catch (ParseException exception) {
        printHelp();
        exit(-1);
    } catch (Exception exception) {
        LOGGER.error("Error: ({}) {}", exception.getClass().getCanonicalName(), exception.getMessage());
        exit(-1);
    }

    exit(0);
}

From source file:de.topobyte.livecg.LiveCG.java

public static void main(String[] args) {
    // @formatter:off
    Options options = new Options();
    OptionHelper.add(options, OPTION_CONFIG, true, false, "path", "config file");
    // @formatter:on

    CommandLineParser clp = new GnuParser();

    CommandLine line = null;// ww w.  java  2s.co  m
    try {
        line = clp.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Parsing command line failed: " + e.getMessage());
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }

    StringOption config = ArgumentHelper.getString(line, OPTION_CONFIG);
    if (config.hasValue()) {
        String configPath = config.getValue();
        LiveConfig.setPath(configPath);
    }

    Configuration configuration = PreferenceManager.getConfiguration();
    String lookAndFeel = configuration.getSelectedLookAndFeel();
    if (lookAndFeel == null) {
        lookAndFeel = UIManager.getSystemLookAndFeelClassName();
    }
    try {
        UIManager.setLookAndFeel(lookAndFeel);
    } catch (Exception e) {
        logger.error("error while setting look and feel '" + lookAndFeel + "': " + e.getClass().getSimpleName()
                + ", message: " + e.getMessage());
    }

    Content content = null;
    String filename = "res/presets/Startup.geom";

    String[] extra = line.getArgs();
    if (extra.length > 0) {
        filename = extra[0];
    }

    ContentReader reader = new ContentReader();
    InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
    try {
        content = reader.read(input);
    } catch (Exception e) {
        logger.info("unable to load startup geometry file", e);
        logger.info("Exception: " + e.getClass().getSimpleName());
        logger.info("Message: " + e.getMessage());
    }

    final LiveCG runner = new LiveCG();
    final Content c = content;

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            runner.setup(true, c);
        }
    });
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            runner.frame.requestFocus();
        }
    });
}

From source file:de.topobyte.livecg.ShowVisualization.java

public static void main(String[] args) {
    EnumNameLookup<Visualization> visualizationSwitch = new EnumNameLookup<Visualization>(Visualization.class,
            true);/*from www  .  j  a v  a 2  s.  c o  m*/

    // @formatter:off
    Options options = new Options();
    OptionHelper.add(options, OPTION_CONFIG, true, false, "path", "config file");
    OptionHelper.add(options, OPTION_VISUALIZATION, true, true, "type",
            "type of visualization. one of <" + VisualizationUtil.getListOfAvailableVisualizations() + ">");
    OptionHelper.add(options, OPTION_STATUS, true, false,
            "status to " + "set the algorithm to. The format depends on the algorithm");
    // @formatter:on

    Option propertyOption = new Option(OPTION_PROPERTIES, "set a special property");
    propertyOption.setArgName("property=value");
    propertyOption.setArgs(2);
    propertyOption.setValueSeparator('=');
    options.addOption(propertyOption);

    CommandLineParser clp = new GnuParser();

    CommandLine line = null;
    try {
        line = clp.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Parsing command line failed: " + e.getMessage());
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }

    String[] extra = line.getArgs();
    if (extra.length == 0) {
        System.out.println("Missing file argument");
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }
    String input = extra[0];

    StringOption argConfig = ArgumentHelper.getString(line, OPTION_CONFIG);
    if (argConfig.hasValue()) {
        String configPath = argConfig.getValue();
        LiveConfig.setPath(configPath);
    }

    StringOption argVisualization = ArgumentHelper.getString(line, OPTION_VISUALIZATION);
    StringOption argStatus = ArgumentHelper.getString(line, OPTION_STATUS);

    Visualization visualization = visualizationSwitch.find(argVisualization.getValue());
    if (visualization == null) {
        System.err.println("Unsupported visualization '" + argVisualization.getValue() + "'");
        System.exit(1);
    }

    System.out.println("Visualization: " + visualization);

    ContentReader contentReader = new ContentReader();
    Content content = null;
    try {
        content = contentReader.read(new File(input));
    } catch (Exception e) {
        System.out.println("Error while reading input file '" + input + "'. Exception type: "
                + e.getClass().getSimpleName() + ", message: " + e.getMessage());
        System.exit(1);
    }

    Properties properties = line.getOptionProperties(OPTION_PROPERTIES);

    ContentLauncher launcher = null;

    switch (visualization) {
    case GEOMETRY: {
        launcher = new ContentDisplayLauncher();
        break;
    }
    case DCEL: {
        launcher = new DcelLauncher();
        break;
    }
    case FREESPACE: {
        launcher = new FreeSpaceChainsLauncher();
        break;
    }
    case DISTANCETERRAIN: {
        launcher = new DistanceTerrainChainsLauncher();
        break;
    }
    case CHAN: {
        launcher = new ChanLauncher();
        break;
    }
    case FORTUNE: {
        launcher = new FortunesSweepLauncher();
        break;
    }
    case MONOTONE_PIECES: {
        launcher = new MonotonePiecesLauncher();
        break;
    }
    case MONOTONE_TRIANGULATION: {
        launcher = new MonotoneTriangulationLauncher();
        break;
    }
    case TRIANGULATION: {
        launcher = new MonotonePiecesTriangulationLauncher();
        break;
    }
    case SPIP: {
        launcher = new ShortestPathInPolygonLauncher();
        break;
    }
    case BUFFER: {
        launcher = new PolygonBufferLauncher();
        break;
    }
    }

    try {
        launcher.launch(content, true);
    } catch (LaunchException e) {
        System.err.println("Unable to start visualization");
        System.err.println("Error message: " + e.getMessage());
        System.exit(1);
    }
}

From source file:de.topobyte.livecg.CreateImage.java

public static void main(String[] args) {
    EnumNameLookup<ExportFormat> exportSwitch = new EnumNameLookup<ExportFormat>(ExportFormat.class, true);

    EnumNameLookup<Visualization> visualizationSwitch = new EnumNameLookup<Visualization>(Visualization.class,
            true);//from w w w .j  a  v  a2  s  . co m

    // @formatter:off
    Options options = new Options();
    OptionHelper.add(options, OPTION_CONFIG, true, false, "path", "config file");
    OptionHelper.add(options, OPTION_INPUT, true, true, "file", "input geometry file");
    OptionHelper.add(options, OPTION_OUTPUT, true, true, "file", "output file");
    OptionHelper.add(options, OPTION_OUTPUT_FORMAT, true, true, "type",
            "type of output. one of <png,svg,tikz,ipe>");
    OptionHelper.add(options, OPTION_VISUALIZATION, true, true, "type",
            "type of visualization. one of <" + VisualizationUtil.getListOfAvailableVisualizations() + ">");
    OptionHelper.add(options, OPTION_STATUS, true, false,
            "status to " + "set the algorithm to. The format depends on the algorithm");
    // @formatter:on

    Option propertyOption = new Option(OPTION_PROPERTIES, "set a special property");
    propertyOption.setArgName("property=value");
    propertyOption.setArgs(2);
    propertyOption.setValueSeparator('=');
    options.addOption(propertyOption);

    CommandLineParser clp = new GnuParser();

    CommandLine line = null;
    try {
        line = clp.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Parsing command line failed: " + e.getMessage());
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }

    StringOption argConfig = ArgumentHelper.getString(line, OPTION_CONFIG);
    if (argConfig.hasValue()) {
        String configPath = argConfig.getValue();
        LiveConfig.setPath(configPath);
    }

    StringOption argInput = ArgumentHelper.getString(line, OPTION_INPUT);
    StringOption argOutput = ArgumentHelper.getString(line, OPTION_OUTPUT);
    StringOption argOutputFormat = ArgumentHelper.getString(line, OPTION_OUTPUT_FORMAT);
    StringOption argVisualization = ArgumentHelper.getString(line, OPTION_VISUALIZATION);
    StringOption argStatus = ArgumentHelper.getString(line, OPTION_STATUS);

    ExportFormat exportFormat = exportSwitch.find(argOutputFormat.getValue());
    if (exportFormat == null) {
        System.err.println("Unsupported output format '" + argOutputFormat.getValue() + "'");
        System.exit(1);
    }

    Visualization visualization = visualizationSwitch.find(argVisualization.getValue());
    if (visualization == null) {
        System.err.println("Unsupported visualization '" + argVisualization.getValue() + "'");
        System.exit(1);
    }

    System.out.println("Visualization: " + visualization);
    System.out.println("Output format: " + exportFormat);

    ContentReader contentReader = new ContentReader();
    Content content = null;
    try {
        content = contentReader.read(new File(argInput.getValue()));
    } catch (Exception e) {
        System.out.println("Error while reading input file '" + argInput.getValue() + "'. Exception type: "
                + e.getClass().getSimpleName() + ", message: " + e.getMessage());
        System.exit(1);
    }

    Properties properties = line.getOptionProperties(OPTION_PROPERTIES);

    double zoom = 1;

    String statusArgument = null;
    if (argStatus.hasValue()) {
        statusArgument = argStatus.getValue();
    }

    VisualizationSetup setup = null;

    switch (visualization) {
    case GEOMETRY: {
        setup = new ContentVisualizationSetup();
        break;
    }
    case DCEL: {
        setup = new DcelVisualizationSetup();
        break;
    }
    case FREESPACE: {
        setup = new FreeSpaceVisualizationSetup();
        break;
    }
    case DISTANCETERRAIN: {
        setup = new DistanceTerrainVisualizationSetup();
        break;
    }
    case CHAN: {
        setup = new ChanVisualizationSetup();
        break;
    }
    case MONOTONE_PIECES: {
        setup = new MonotonePiecesVisualizationSetup();
        break;
    }
    case MONOTONE_TRIANGULATION: {
        setup = new MonotoneTriangulationVisualizationSetup();
        break;
    }
    case TRIANGULATION: {
        setup = new MonotonePiecesTriangulationVisualizationSetup();
        break;
    }
    case BUFFER: {
        setup = new BufferVisualizationSetup();
        break;
    }
    case FORTUNE: {
        setup = new FortunesSweepVisualizationSetup();
        break;
    }
    case SPIP: {
        setup = new ShortestPathVisualizationSetup();
        break;
    }
    }

    if (setup == null) {
        System.err.println("Not yet implemented");
        System.exit(1);
    }

    SetupResult setupResult = setup.setup(content, statusArgument, properties, zoom);

    int width = setupResult.getWidth();
    int height = setupResult.getHeight();

    VisualizationPainter visualizationPainter = setupResult.getVisualizationPainter();

    File output = new File(argOutput.getValue());

    visualizationPainter.setZoom(zoom);

    switch (exportFormat) {
    case IPE: {
        try {
            IpeExporter.exportIpe(output, visualizationPainter, width, height);
        } catch (Exception e) {
            System.err.println("Error while exporting. Exception type: " + e.getClass().getSimpleName()
                    + ", message: " + e.getMessage());
            System.exit(1);
        }
        break;
    }
    case PNG: {
        try {
            GraphicsExporter.exportPNG(output, visualizationPainter, width, height);
        } catch (IOException e) {
            System.err.println("Error while exporting. Exception type: " + e.getClass().getSimpleName()
                    + ", message: " + e.getMessage());
            System.exit(1);
        }
        break;
    }
    case SVG: {
        try {
            SvgExporter.exportSVG(output, visualizationPainter, width, height);
        } catch (Exception e) {
            System.err.println("Error while exporting. Exception type: " + e.getClass().getSimpleName()
                    + ", message: " + e.getMessage());
            System.exit(1);
        }
        break;
    }
    case TIKZ: {
        try {
            TikzExporter.exportTikz(output, visualizationPainter, width, height);
        } catch (Exception e) {
            System.err.println("Error while exporting. Exception type: " + e.getClass().getSimpleName()
                    + ", message: " + e.getMessage());
            System.exit(1);
        }
        break;
    }
    }
}

From source file:carmen.utils.CommandLineUtilities.java

/**
 * This uses the apache Jakarta CLI to parse the command line.
 * A single static instance of this class exists for global access by all parts 
 * of the program.//  w  ww  .j a  va2 s  .  c  o  m
 * To use this class, a list of options must be specified and passed to this method.
 * Manditory arguments should be encoded as strings.
 * @param args The command line received by main
 * @param manditory_args A list of strings that contain the names of manditory arguments.
 * @param specified_options A list of options to use for this program.
 */
public static void initCommandLineParameters(String[] args, List<Option> specified_options,
        String[] manditory_args) {
    Options options = new Options();
    if (specified_options != null)
        for (Option option : specified_options)
            options.addOption(option);

    Option option = null;

    OptionBuilder.withArgName("file");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("A file containing command line parameters as a Java properties file.");
    option = OptionBuilder.create("parameter_file");

    options.addOption(option);

    CommandLineParser command_line_parser = new GnuParser();
    CommandLineUtilities._properties = new Properties();
    try {
        CommandLineUtilities._command_line = command_line_parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("***ERROR: " + e.getClass() + ": " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("parameters:", options);
        System.exit(0);
    }
    if (CommandLineUtilities.hasArg("parameter_file")) {
        String parameter_file = CommandLineUtilities.getOptionValue("parameter_file");
        // Read the property file.
        try {
            _properties.load(new FileInputStream(parameter_file));
        } catch (IOException e) {
            System.err.println("Problem reading parameter file: " + parameter_file);
        }
    }

    boolean failed = false;
    if (manditory_args != null) {
        for (String arg : manditory_args) {
            if (!CommandLineUtilities.hasArg(arg)) {
                failed = true;
                System.out.println("Missing argument: " + arg);
            }
        }
        if (failed) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("parameters:", options);
            System.exit(0);
        }

    }
}

From source file:com.deploymentio.cfnstacker.StackerOptions.java

public StackerOptions(String[] args) {

    Options options = new Options();
    options.addOption(Option.builder("c").desc("Stack configuration file").longOpt("config").hasArg()
            .argName("file").type(File.class).required().build());
    options.addOption(Option.builder("a").desc("Action to take").longOpt("action").hasArg().argName("name")
            .required().build());/*from  w  w  w.j  a  va  2s. c  om*/
    options.addOption(Option.builder("d").desc("Print debug messages").longOpt("debug").build());
    options.addOption(Option.builder("t").desc("Print trace messages").longOpt("trace").build());

    String desiredActionValue = null;

    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine = null;
    try {
        commandLine = parser.parse(options, args);

        desiredActionValue = commandLine.getOptionValue("action");
        configFile = (File) commandLine.getParsedOptionValue("config");
        debugEnabled = commandLine.hasOption("debug");
        traceEnabled = commandLine.hasOption("trace");

    } catch (ParseException e) {
        errors.add("Invalid or missing arguments, see usage message");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(usageWriter, 100,
                "java -jar cfn-stacker.jar -c <file> -a <" + StringUtils.join(Action.values(), '|') + ">",
                "\nCFN Stacker is used to create/update/delete an AWS CloudFormation stack\n", options, 3, 3,
                "");
        usageWriter.append('\n').flush();
    }

    if (!hasErrors()) {

        if (!configFile.exists() || !configFile.isFile()) {
            errors.add("Config file doesn't exist: Path=" + configFile.getAbsolutePath());
        } else {
            try {
                stackConfig = new StackConfigCreator(configFile).getStackConfig();
            } catch (Exception e) {
                errors.add("Can't load stack configuration: File=" + configFile.getAbsolutePath() + " Error="
                        + e.getClass().getName() + " ErrorMessage=" + e.getMessage());
            }
        }

        try {
            desiredAction = Action.valueOf(desiredActionValue);
        } catch (IllegalArgumentException e) {
            errors.add("Action is not valid: Found=" + desiredActionValue + " Expected="
                    + StringUtils.join(Action.values(), '|'));
        }
    }
}

From source file:com.marklogic.shell.Shell.java

private void run(String[] args) {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//from w ww .  ja v a 2s. co  m
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        exitWithError(e.getMessage());
    }

    if (cmd.hasOption("h")) {
        printHelp();
    }

    String user = cmd.getOptionValue("u");
    String password = cmd.getOptionValue("p");
    String host = cmd.getOptionValue("H");
    String database = cmd.getOptionValue("d");
    Integer port = null;
    try {
        port = new Integer(cmd.getOptionValue("P"));
    } catch (NumberFormatException ignored) {
    }

    if (user == null)
        user = properties.getString("user");
    if (password == null)
        password = properties.getString("password");
    if (host == null)
        host = properties.getString("host");
    if (port == null) {
        try {
            port = new Integer(properties.getInt("port", DEFAULT_PORT));
        } catch (ConversionException e) {
            printHelp("Invalid port number: " + properties.getString("port"));
        }
    }

    if (user == null || password == null || port == null || host == null) {
        printHelp("You must provide a user, password, host and port.");
    }

    properties.setProperty("user", user);
    properties.setProperty("password", password);
    properties.setProperty("host", host);
    properties.setProperty("database", database);
    properties.setProperty("port", port.toString());
    if (properties.getString("scroll") == null || properties.getString("scroll").length() <= 0) {
        properties.setProperty("scroll", String.valueOf(DEFAULT_SCROLL));
    }

    if (cmd.hasOption("F")) {
        properties.setProperty("pretty-print-xml", "true");
    }

    String xqueryFile = cmd.getOptionValue("f");
    InputStream in = null;
    if (xqueryFile != null) {
        try {
            in = new FileInputStream(new File(xqueryFile));
        } catch (FileNotFoundException e) {
            exitWithError("File " + xqueryFile + " not found: " + e.getMessage());
        }
    } else {
        in = System.in;
    }
    int stdinBytes = 0;
    try {
        stdinBytes = in.available();
    } catch (IOException ignored) {
    }

    if (cmd.hasOption("l")) {
        // XXX this is a hack to support loading from command line without
        // duplication of code
        // XXX make sure load command doesn't have conflicting args
        load loader = new load(this.options);
        loader.execute(this, args);
    } else if (stdinBytes > 0) {
        StringBuffer xquery = new StringBuffer();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            char[] b = new char[4 * 1024];
            int n;
            while ((n = reader.read(b)) > 0) {
                xquery.append(b, 0, n);
            }
        } catch (IOException e) {
            exitWithError("Failed to read query from stdin: " + e.getMessage());
        }

        Session session = getContentSource().newSession();
        AdhocQuery request = session.newAdhocQuery(xquery.toString());
        try {
            outputResultSequence(session.submitRequest(request), false);
        } catch (RequestException e) {
            outputException(e);
        }
    } else {
        try {
            checkConnection(properties.getString("user"), properties.getString("password"),
                    properties.getString("host"), properties.getInt("port", DEFAULT_PORT));
        } catch (ShellException e) {
            outputLine("Failed to connect to Mark Logic. Invalid connection information.");
            outputException(e);
            exitWithError("Goodbye.");
        }
        printWelcome();
        outputLine("");
        try {
            startShell();
        } catch (Exception e) {
            e.printStackTrace();
            outputLine("Shell exited abnormally with exception: " + e.getClass().toString());
            outputLine("Error message: " + e.getMessage());
            outputLine("Goodbye.");
        }
    }
}

From source file:org.apache.batchee.cli.BatchEECLI.java

public static void main(final String[] args) {
    final Iterator<CliConfiguration> configuration = ServiceLoader.load(CliConfiguration.class).iterator();
    final CliConfiguration cliConfiguration = configuration.hasNext() ? configuration.next()
            : new DefaultCliConfiguration();

    final Map<String, Class<? extends Runnable>> commands = new TreeMap<String, Class<? extends Runnable>>();
    if (cliConfiguration.addDefaultCommands()) {
        for (final Class<? extends Runnable> type : Arrays.asList(Names.class, Start.class, Restart.class,
                Status.class, Running.class, Stop.class, Abandon.class, Instances.class, Executions.class,
                StepExecutions.class, Eviction.class)) {
            addCommand(commands, type);//from   w  ww  .  j a va 2  s. co  m
        }
    }
    final Iterator<Class<? extends UserCommand>> userCommands = cliConfiguration.userCommands();
    if (userCommands != null) {
        while (userCommands.hasNext()) {
            addCommand(commands, userCommands.next());
        }
    }

    if (args == null || args.length == 0) {
        System.err.print(help(commands));
        return;
    }

    final Class<? extends Runnable> cmd = commands.get(args[0]);
    if (cmd == null) {
        if (args[0].equals("help")) {
            if (args.length > 1) {
                final Class<? extends Runnable> helpCmd = commands.get(args[1]);
                if (helpCmd != null) {
                    printHelp(helpCmd.getAnnotation(Command.class),
                            buildOptions(helpCmd, new HashMap<String, Field>()));
                    return;
                }
            } // else let use the default help
        }
        System.err.print(help(commands));
        return;
    }

    // build the command now
    final Command command = cmd.getAnnotation(Command.class);
    if (command == null) {
        System.err.print(help(commands));
        return;
    }

    final Map<String, Field> fields = new HashMap<String, Field>();
    final Options options = buildOptions(cmd, fields);

    final Collection<String> newArgs = new ArrayList<String>(asList(args));
    newArgs.remove(newArgs.iterator().next());

    final CommandLineParser parser = new DefaultParser();
    try {
        final CommandLine line = parser.parse(options, newArgs.toArray(new String[newArgs.size()]));
        cliConfiguration.decorate(instantiate(cmd, cliConfiguration, fields, !newArgs.isEmpty(), line)).run();
    } catch (final ParseException e) {
        printHelp(command, options);
    } catch (final RuntimeException e) {
        Class<?> current = e.getClass();
        while (current != null) {
            final Exit annotation = current.getAnnotation(Exit.class);
            if (annotation != null) {
                System.exit(annotation.value());
            }
            current = current.getSuperclass();
        }
        throw e;
    } catch (final InstantiationException e) {
        throw new IllegalStateException(e);
    } catch (final IllegalAccessException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.apache.directory.server.tools.BaseCommand.java

public CommandLine getCommandLine(String command, String[] args) {
    Options all = allOptions(command);/* ww  w. j a v a 2s.c  o m*/
    CommandLineParser parser = new PosixParser();
    CommandLine cmdline = null;
    try {
        cmdline = parser.parse(all, args);
    } catch (AlreadySelectedException ase) {
        System.err.println("Command line parsing failed for " + command + ".  Reason: already selected "
                + ase.getMessage());
        System.exit(1);
    } catch (MissingArgumentException mae) {
        System.err.println("Command line parsing failed for " + command + ".  Reason: missing argument "
                + mae.getMessage());
        System.exit(1);
    } catch (MissingOptionException moe) {
        System.err.println(
                "Command line parsing failed for " + command + ".  Reason: missing option " + moe.getMessage());
        System.exit(1);
    } catch (UnrecognizedOptionException uoe) {
        System.err.println("Command line parsing failed for " + command + ".  Reason: unrecognized option"
                + uoe.getMessage());
        System.exit(1);
    } catch (ParseException pe) {
        System.err.println("Command line parsing failed for " + command + ".  Reason: " + pe.getClass());
        System.exit(1);
    }

    return cmdline;
}