Example usage for org.apache.commons.cli DefaultParser DefaultParser

List of usage examples for org.apache.commons.cli DefaultParser DefaultParser

Introduction

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

Prototype

DefaultParser

Source Link

Usage

From source file:es.sistedes.handle.generator.CliLauncher.java

/**
 * Runs the {@link CliLauncher}//from  w  ww.  j a  v  a2s  .c o m
 * 
 * @param args
 * @throws Exception
 */
private static void run(String[] args) throws Exception {
    try {
        CommandLine commandLine = null;

        try {
            CommandLineParser parser = new DefaultParser();
            commandLine = parser.parse(options, args);
        } catch (ParseException e) {
            printError(e.getLocalizedMessage());
            printHelp();
            throw e;
        }

        Conversor conversor = new Conversor(commandLine.getOptionValue(PREFIX));

        FileInputStream input = null;
        if (commandLine.hasOption(INPUT)) {
            input = new FileInputStream(new File(commandLine.getOptionValue(INPUT)));
            conversor.changeInput(input);
        }

        FileOutputStream output = null;
        if (commandLine.hasOption(OUTPUT)) {
            output = new FileOutputStream(new File(commandLine.getOptionValue(OUTPUT)));
            conversor.changeOutput(output);
        }

        conversor.putOption(ConversorOptions.USE_GUID, commandLine.hasOption(USE_GUID));
        conversor.putOption(ConversorOptions.ADD_DELETE, commandLine.hasOption(ADD_DELETE));
        if (commandLine.hasOption(FILTER)) {
            conversor.putOption(ConversorOptions.FILTER, commandLine.getOptionValue(FILTER));
        }

        try {
            conversor.generate();
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(output);
        }
    } catch (ConversionException | FileNotFoundException e) {
        printError("ERROR: " + e.getLocalizedMessage());
        throw e;
    }
}

From source file:at.salzburgresearch.vgi.vgianalyticsframework.activityanalysis.application.OsmHistoryImporter.java

public static void launch(Options options, String[] args) {

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;//from w  w  w .j  a v  a2s . c om
    try (ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
            "classpath:/application-context-osm-op-generator.xml")) {
        cmd = parser.parse(options, args);

        File osmHistoryFile = null;
        File settingsFile = null;

        if (cmd.hasOption('h')) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("java -jar vgi-activity-1.0.jar [OPTION]...", options);
            return;
        }
        if (cmd.hasOption('o')) {
            osmHistoryFile = new File(cmd.getOptionValue('o'));
            if (!osmHistoryFile.exists()) {
                log.warn("OSM History file does not exist! (" + osmHistoryFile.getAbsolutePath() + ")");
                System.exit(0);
            }
        } else {
            log.warn("No osm history file specified! Use option -o to specify a settings XML file");
            System.exit(0);
            osmHistoryFile = null;
        }
        if (cmd.hasOption('s')) {
            settingsFile = new File(cmd.getOptionValue('s'));
            if (!settingsFile.exists()) {
                log.warn("Setting file does not exist! (" + settingsFile.getAbsolutePath() + ")");
                System.exit(0);
            }
        } else {
            log.warn("No setting file specified! Use option -s to specify a settings XML file");
            System.exit(0);
            settingsFile = null;
        }

        IVgiPipelineSettings settings = ((IVgiPipelineSettings) ctx.getBean("vgiPipelineSettings"));
        if (!settings.loadSettings(settingsFile)) {
            System.exit(1);
        }

        InputStream input = new FileInputStream(osmHistoryFile);
        OsmPbfParser osmParser = new OsmPbfParser();

        OsmDataConsumer osmDataConsumer = ((VgiOperationGeneratorDataHandlerImpl) ctx
                .getBean("vgiOperationGeneratorDataHandler"));
        osmParser.setSink(osmDataConsumer);
        new BlockInputStream(input, osmParser).process();

        log.info("importer done");

    } catch (ParseException e) {
        log.error("Parse Error");
    } catch (IOException e) {
        log.error("File Error");
    } catch (Exception e) {
        HelpFormatter helpFormatter = new HelpFormatter();
        if (e.getMessage() != null) {
            e.printStackTrace();
        } else {
            log.error("Unknown error", e);
        }
        helpFormatter.printHelp("java -jar vgi-activity-1.0.jar [OPTION]...", options);
    }
}

From source file:cz.lbenda.dataman.rc.DatamanApp.java

private static CommandLine commandLine(String[] args) {
    Options options = new Options();
    options.addOption("h", "help", false, "Show this help");
    options.addOption(null, "mode", true, "Application mode: development, test");
    DatamanHeadless.setCommandLineOptions(options);
    CommandLineParser parser = new DefaultParser();
    try {/*from ww w .ja va 2s .c o m*/
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            (new HelpFormatter()).printHelp("dataman", options);
        }
        if (cmd.hasOption("mode")) {
            if ("DEVELOPMENT".equals(cmd.getOptionValue("mode").toUpperCase())) {
                Constants.IS_IN_DEVELOP_MODE = true;
            } else if ("TEST".equals(cmd.getOptionValue("mode").toUpperCase())) {
                Constants.IS_IN_DEVELOP_MODE = true;
            }
        }
        cz.lbenda.dataman.Constants.HEADLESS = cmd.hasOption("i") || cmd.hasOption("is");
        return cmd;
    } catch (ParseException e) {
        LOG.error("Problem with parse command line arguments", e);
        (new HelpFormatter()).printHelp("dataman", options);
        System.exit(1);
        throw new RuntimeException(e);
    }
}

From source file:com.congiu.load.csv.Main.java

static CommandLine processArguments(Options opts, String[] args) throws ParseException {
    CommandLineParser parser = new DefaultParser();
    return parser.parse(opts, args);
}

From source file:com.github.sakserv.lslock.cli.parser.LockTakerCliParser.java

/**
 * Parses the passed in command line arguments
 *///from   w  w w  . java 2s  . c o m
@Override
public void parse() {

    CommandLineParser commandLineParser = new DefaultParser();

    try {
        CommandLine commandLine = commandLineParser.parse(options, args);

        // Handle the help option
        if (commandLine.hasOption("h")) {
            help(options, NAME);
        }

        // Handle the directory
        if (commandLine.hasOption("d")) {
            lockDirectory = new File(commandLine.getOptionValue("d"));
        } else {
            LOG.error("The directory option is required");
            help(options, NAME);
        }

        // Handle the lock file count option
        if (commandLine.hasOption("l")) {
            lockCount = Integer.parseInt(commandLine.getOptionValue("l"));
        } else {
            lockCount = 5;
        }

        // Handle the sleep timer option
        if (commandLine.hasOption("s")) {
            sleepTimer = Integer.parseInt(commandLine.getOptionValue("s"));
        } else {
            sleepTimer = 20000;
        }

    } catch (ParseException e) {
        LOG.error("Failed to parse command line args");
        help(options, NAME);
    }
}

From source file:com.dustindoloff.pngtastic.Main.java

/**
 * Parses command-line arguments. Exits with a return code if the args failed to be parsed.
 * @param args The args passed into the main function.
 * @return The parsed arguments.//from www .j  a  v  a  2  s  .c  o  m
 */
private static CommandLine parseArgs(final String[] args) {
    final Options options = new Options()
            .addOption(Option.builder().argName("Input PNG").longOpt(ARG_INPUT_PNG).desc("The input png file")
                    .required().hasArg().build())
            .addOption(Option.builder().argName("Output PNG").longOpt(ARG_OUTPUT_PNG)
                    .desc("The output png file").required().hasArg().build())
            .addOption(Option.builder().argName("Logging Level").longOpt(ARG_LOG_LEVEL)
                    .desc("The logging level").hasArg().build())
            .addOption(Option.builder().argName("Optimization Passes").longOpt(ARG_ITERATIONS)
                    .desc("The number of optimization passes to perform").hasArg().build())
            .addOption(Option.builder().argName("Alternate Compressor").longOpt(ARG_COMPRESSOR)
                    .desc("Path to an alternative compressor").hasArg().build())
            .addOption(Option.builder().argName("Remove Gamma").longOpt(ARG_REMOVE_GAMMA)
                    .desc("Remove gamma correction info").build())
            .addOption(Option.builder().argName("Compression Level").longOpt(ARG_COMPRESSION_LEVEL)
                    .desc("The compresion level (0-9). " + "Default is to brute force all for best result")
                    .build());

    try {
        return new DefaultParser().parse(options, args);
    } catch (final ParseException e) {
        System.out.println(e.getMessage());
        new HelpFormatter().printHelp("pngtastic", options);
        System.exit(1);
        return null;
    }
}

From source file:com.falcon.orca.handlers.SlaveHandler.java

@Override
public void handle() {
    CommandLine commandLine;/*  www.ja va2s.  co m*/
    CommandLineParser commandLineParser = new DefaultParser();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
    Options options = createSlaveOptions();
    printOnCmd("Welcome to ORCA type help to see what ORCA can do.");
    try {
        String command = br.readLine();
        while (command != null) {
            if (!StringUtils.isEmpty(command)) {
                try {
                    String[] treatedCommandParts = treatCommands(command);
                    commandLine = commandLineParser.parse(options, treatedCommandParts);
                    if (commandLine.hasOption("connect")) {
                        String masterHost;
                        if (commandLine.hasOption("masterHost")) {
                            masterHost = commandLine.getOptionValue("masterHost");
                        } else {
                            throw new MissingArgumentException("Master host is required to connect");
                        }

                        Integer masterPort;
                        if (commandLine.hasOption("masterPort")) {
                            masterPort = Integer.valueOf(commandLine.getOptionValue("masterPort"));
                        } else {
                            throw new MissingArgumentException("Master port is required to connect");
                        }
                        nodeManager = actorSystem.actorOf(NodeManager.props(masterHost, masterPort),
                                "node_manager");
                    } else if (commandLine.hasOption("disconnect")) {
                        if (nodeManager == null || nodeManager.isTerminated()) {
                            printOnCmd("node is not part of any cluster");
                        } else {
                            NodeManagerCommand nodeManagerCommand = new NodeManagerCommand();
                            nodeManagerCommand.setType(NodeManagerCommandType.UNREGISTER_FROM_MASTER);
                            nodeManager.tell(nodeManagerCommand, nodeManager);
                        }
                    } else if (commandLine.hasOption("exit")) {
                        if (nodeManager != null && !nodeManager.isTerminated()) {
                            NodeManagerCommand nodeManagerCommand = new NodeManagerCommand();
                            nodeManagerCommand.setType(NodeManagerCommandType.EXIT);
                            nodeManager.tell(nodeManagerCommand, nodeManager);
                        }
                        actorSystem.shutdown();
                        actorSystem.awaitTermination(new FiniteDuration(1, TimeUnit.MINUTES));
                        break;
                    } else {
                        printOnCmd(printHelpSlaveMode());
                    }
                } catch (ParseException pe) {
                    printOnCmd(printHelpSlaveMode());
                }
            } else {
                printOnCmd("", false);
            }
            command = br.readLine();
        }
    } catch (IOException e) {
        printOnCmd("Failed to read input from command line, please try again.");
    }
}

From source file:br.com.mobclip.Application.java

@Override
public void run(String... args) throws Exception {

    Options options = createOptions();/*from  ww w .  j  a v a 2  s.  c o  m*/

    String mode = null;
    int threads = 1;

    try {

        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);

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

        mode = line.getOptionValue("mode", "starter");
        threads = Integer.valueOf(line.getOptionValue("threads", "1"));

    } catch (Exception exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
        System.exit(0);
    }

    switch (mode) {

    case "starter":
        starter.configure(2, 2);
        submitTasks(1, starter);
        break;
    case "persister":
        submitTasks(threads, persister);
        break;
    case "page-extractor":
        submitTasks(threads, new PageExtractor());
        break;
    case "page-detail-extractor":
        submitTasks(threads, new PageDetailExtractor());
        break;

    case "standalone":
        submitTasks(threads, persister);
        submitTasks(threads, new PageExtractor());
        submitTasks(threads, new PageDetailExtractor());
        starter.configure(2, 2);
        submitTasks(1, starter);
        break;

    default:
        System.out.println("Invalid application mode: " + mode);
    }
}

From source file:net.librec.tool.driver.DataDriver.java

/**
 * Execute the command with the given arguments.
 *
 * @param args command specific arguments.
 * @return exit code.//from   w  w w.  j a  va  2 s .c  om
 * @throws Exception if error occurs
 */
public int run(String[] args) throws Exception {
    // init options
    Options options = new Options();
    options.addOption("build", false, "build model");
    options.addOption("load", false, "load model");
    options.addOption("save", false, "save model");
    options.addOption("conf", true, "the path of configuration file");
    options.addOption("jobconf", true, "a specified key-value pair for configuration");
    options.addOption("D", true, "a specified key-value pair for configuration");
    // parse options
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, false);
    // init configuration
    Configuration conf = new Configuration();
    if (cmd.hasOption("conf")) {
        String confFilePath = cmd.getOptionValue("conf");
        Properties prop = new Properties();
        prop.load(new FileInputStream(confFilePath));
        for (String name : prop.stringPropertyNames()) {
            conf.set(name, prop.getProperty(name));
        }
    }
    if (cmd.hasOption("jobconf")) {
        String[] optionValues = cmd.getOptionValues("jobconf");
        for (String optionValue : optionValues) {
            String[] keyValuePair = optionValue.split("=");
            conf.set(keyValuePair[0], keyValuePair[1]);
        }
    }
    if (cmd.hasOption("D")) {
        String[] optionValues = cmd.getOptionValues("D");
        for (String optionValue : optionValues) {
            String[] keyValuePair = optionValue.split("=");
            conf.set(keyValuePair[0], keyValuePair[1]);
        }
    }
    TextDataModel dataModel = new TextDataModel(conf);
    dataModel.buildDataModel();
    System.out.println("well done!!!");
    return 0;
}

From source file:com.ibm.replication.iidr.metadata.ExportMetadataParms.java

public ExportMetadataParms(String[] commandLineArguments) throws ExportMetadataParmsException {
    // Initialize parameters
    debug = false;//from   w  w  w .j  av a 2  s  .c  om
    datastore = "";
    formatter = new HelpFormatter();
    parser = new DefaultParser();
    options = new Options();
    previewOnly = false;
    xmlFileOutput = false;
    subscription = null;
    updateBundle = false;

    options.addOption("d", false, "");
    options.addOption("ub", false, "");
    options.addOption("p", false, "");
    options.addOption("xp", false, "");
    options.addOption(Option.builder("ds").hasArg().build());
    options.addOption(Option.builder("s").hasArg().build());

    try {
        commandLine = parser.parse(options, commandLineArguments);
    } catch (ParseException e) {
        sendInvalidParameterException("");
    }

    this.debug = commandLine.hasOption("d");
    this.updateBundle = commandLine.hasOption("ub");
    this.previewOnly = commandLine.hasOption("p");
    this.xmlFileOutput = commandLine.hasOption("xf");

    // Datastore parameter is mandatory
    if (commandLine.getOptionValue("ds") != null) {
        datastore = commandLine.getOptionValue("ds");
        if (commandLine.getOptionValue("s") != null) {
            subscription = commandLine.getOptionValue("s");
        }

    } else
        sendInvalidParameterException("Datastore (ds parameter) must be specified");

}