Example usage for org.apache.commons.cli CommandLineParser parse

List of usage examples for org.apache.commons.cli CommandLineParser parse

Introduction

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

Prototype

CommandLine parse(Options options, String[] arguments) throws ParseException;

Source Link

Document

Parse the arguments according to the specified options.

Usage

From source file:fr.inria.atlanmod.kyanos.benchmarks.Migrator.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);/*  w ww.ja v  a 2 s.c  om*/
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output file");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(IN_EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of input EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option outClassOpt = OptionBuilder.create(OUT_EPACKAGE_CLASS);
    outClassOpt.setArgName("CLASS");
    outClassOpt.setDescription("FQN of output EPackage implementation class");
    outClassOpt.setArgs(1);
    outClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);
    options.addOption(outClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);
        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        URI targetUri = URI.createFileURI(commandLine.getOptionValue(OUT));
        Class<?> inClazz = Migrator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(IN_EPACKAGE_CLASS));
        Class<?> outClazz = Migrator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(OUT_EPACKAGE_CLASS));

        @SuppressWarnings("unused")
        EPackage inEPackage = (EPackage) inClazz.getMethod("init").invoke(null);
        EPackage outEPackage = (EPackage) outClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());

        Resource sourceResource = resourceSet.getResource(sourceUri, true);
        Resource targetResource = resourceSet.createResource(targetUri);

        targetResource.getContents().clear();
        LOG.log(Level.INFO, "Start migration");
        targetResource.getContents()
                .add(MigratorUtil.migrate(sourceResource.getContents().get(0), outEPackage));
        LOG.log(Level.INFO, "Migration finished");

        Map<String, Object> saveOpts = new HashMap<String, Object>();
        saveOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saving done");
    } catch (ParseException e) {
        showError(e.toString());
        showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        showError(e.toString());
    }
}

From source file:me.cavar.pg2tei.Gutenberg2TEI.java

/**
 * @param args//from w ww . ja  v  a 2 s. c  o  m
 */
public static void main(String[] args) {
    // Process command line
    Options options = new Options();

    options.addOption("c", true, "Catalogue URL");
    options.addOption("o", true, "Output folder");
    // options.addOption("f", true, "Resulting output catalogue file name");
    options.addOption("h", false, "Help");

    // the individual RDF-files are at this URL:
    // The RDF-file name is this.idN + ".rdf"
    String ebookURLStr = "http://www.gutenberg.org/ebooks/";

    // the URL to the catalog.rdf
    String catalogURLStr = "http://www.gutenberg.org/feeds/catalog.rdf.zip";
    String outputFolder = ".";
    String catalogOutFN = "catalog.rdf";

    CommandLineParser parser;
    parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            System.out.println("Project Gutenberg fetch RDF catalog, HTML-files and generate TEI XML");
            System.out.println("");
            return;
        }
        if (cmd.hasOption("c")) {
            catalogURLStr = cmd.getOptionValue("c");
        }
        if (cmd.hasOption("o")) {
            outputFolder = cmd.getOptionValue("o");
        }
        //if (cmd.hasOption("f")) {
        //    catalogOutFN = cmd.getOptionValue("f");
        //}

    } catch (ParseException ex) {
        System.out.println("Command line argument error:" + ex.getMessage());
    }

    // Do the fetching of the RDF catalog
    fetchRDF(catalogURLStr, outputFolder, catalogOutFN);

    // process the RDF file
    processRDF(outputFolder, catalogOutFN, ebookURLStr);
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.CdoQueryGrabats09.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);//from  w w w  .  j  av a2 s  .  c o  m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

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

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoQueryGrabats09.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

            {
                Runtime.getRuntime().gc();
                long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
                LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}",
                        MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                EList<ClassDeclaration> list = ASE2015JavaQueries.grabats09(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
                Runtime.getRuntime().gc();
                long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
                LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}",
                        MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
                LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                        MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));
            }

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:com.bigdata.dastor.tools.SSTableImport.java

/**
 * Converts JSON to an SSTable file. JSON input can either be a file specified
 * using an optional command line argument, or supplied on standard in.
 * /*w  w  w  . jav a  2s  . c o  m*/
 * @param args command line arguments
 * @throws IOException on failure to open/read/write files or output streams
 * @throws ParseException on failure to parse JSON input
 */
public static void main(String[] args) throws IOException, ParseException {
    String usage = String.format("Usage: %s -K keyspace -c column_family <json> <sstable>%n",
            SSTableImport.class.getName());

    CommandLineParser parser = new PosixParser();
    try {
        cmd = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException e1) {
        System.err.println(e1.getMessage());
        System.err.println(usage);
        System.exit(1);
    }

    if (cmd.getArgs().length != 2) {
        System.err.println(usage);
        System.exit(1);
    }

    String json = cmd.getArgs()[0];
    String ssTable = cmd.getArgs()[1];
    String keyspace = cmd.getOptionValue(KEYSPACE_OPTION);
    String cfamily = cmd.getOptionValue(COLFAM_OPTION);

    importJson(json, keyspace, cfamily, ssTable);

    System.exit(0);
}

From source file:de.egore911.versioning.deployer.Main.java

public static void main(String[] args) throws IOException {

    Options options = new Options();
    options.addOption("help", false, "print this message");
    options.addOption("r", "replace-only", false,
            "only perform replacements (skip downloading, extracting, etc.)");

    CommandLine line;// w w  w .  j  av a  2s.c  o  m
    try {
        CommandLineParser parser = new BasicParser();
        line = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("Wrong command line parameters:" + e.getMessage());
        showHelp(options);
        System.exit(1);
        return;
    }

    if (line.getArgs().length == 0) {
        LOG.error("Please pass at least one URL as one and only argument");
        System.exit(1);
        return;
    }

    for (String arg : line.getArgs()) {
        perform(arg, line);
    }
}

From source file:com.flaptor.indextank.rpc.SearcherClient.java

public static void main(String[] args) {

    // create the parser
    CommandLineParser parser = new PosixParser();
    try {/*from  w  ww .j a  v  a2  s .  c  o m*/
        // parse the command line arguments
        CommandLine line = parser.parse(getOptions(), args);
        if (line.hasOption("help")) {
            printHelp(getOptions(), null);
            System.exit(1);
        }

        if (!line.hasOption("function")) {
            printHelp(getOptions(), null);
            System.exit(1);
        }

        Integer scoringFunctionIndex = Integer.valueOf(line.getOptionValue("function"));

        String host = line.getOptionValue("host", "localhost");
        String basePort = line.getOptionValue("port", "7910");
        int port = Integer.valueOf(basePort) + 2;

        TTransport transport;
        transport = new TSocket(host, port);
        TProtocol protocol = new TBinaryProtocol(transport);
        Searcher.Client client = new Searcher.Client(protocol);

        transport.open();
        ResultSet rs = client.search(line.getArgs()[0], 0, 10, scoringFunctionIndex,
                Collections.<Integer, Double>emptyMap(), Lists.<CategoryFilter>newArrayList(),
                Lists.<RangeFilter>newArrayList(), Lists.<RangeFilter>newArrayList(),
                Collections.<String, String>emptyMap()); // TODO join getArgs
        transport.close();
        System.out.println(rs);
    } catch (InvalidQueryException e) {
        e.printStackTrace();
    } catch (MissingQueryVariableException e) {
        e.printStackTrace();
    } catch (IndextankException e) {
        e.printStackTrace();
    } catch (ParseException exp) {
        printHelp(getOptions(), exp.getMessage());
    } catch (TTransportException e) {
        e.printStackTrace();
    } catch (TException e) {
        e.printStackTrace();
    }
}

From source file:mecard.MetroService.java

public static void main(String[] args) {
    // First get the valid options
    Options options = new Options();
    // add t option c to config directory true=arg required.
    options.addOption("c", true,
            "configuration file directory path, include all sys dependant dir seperators like '/'.");
    // add t option c to config directory true=arg required.
    options.addOption("v", false, "Metro server version information.");
    try {/*from w  w  w .  j  a  va  2  s .  co m*/
        // parse the command line.
        CommandLineParser parser = new BasicParser();
        CommandLine cmd;
        cmd = parser.parse(options, args);
        if (cmd.hasOption("v")) {
            System.out.println("Metro (MeCard) server version " + PropertyReader.VERSION);
        }
        // get c option value
        String configDirectory = cmd.getOptionValue("c");
        PropertyReader.setConfigDirectory(configDirectory);
    } catch (ParseException ex) {
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println(
                new Date() + "Unable to parse command line option. Please check your service configuration.");
        System.exit(799);
    }

    Properties properties = PropertyReader.getProperties(ConfigFileTypes.ENVIRONMENT);
    String portString = properties.getProperty(LibraryPropertyTypes.METRO_PORT.toString(), defaultPort);

    try {
        int port = Integer.parseInt(portString);
        serverSocket = new ServerSocket(port);
    } catch (IOException ex) {
        String msg = " Could not listen on port: " + portString;
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg + ex.getMessage());
    } catch (NumberFormatException ex) {
        String msg = "Could not parse port number defined in configuration file.";
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg + ex.getMessage());
    }

    while (listening) {
        try {
            new SocketThread(serverSocket.accept()).start();
        } catch (IOException ex) {
            String msg = "unable to start server socket; either accept or start failed.";
            //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
            System.out.println(new Date() + msg);
        }
    }
    try {
        serverSocket.close();
    } catch (IOException ex) {
        String msg = "failed to close the server socket.";
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg);
    }
}

From source file:co.turnus.analysis.pipelining.SimplePipeliningCliLauncher.java

public static void main(String[] args) {
    try {//from   www  . j a  v  a 2  s  .  com
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(cliOptions, args);
        Configuration config = parseCommandLine(cmd);

        // init models
        AnalysisActivator.init();

        // set logger verbosity
        if (config.getBoolean(VERBOSE, false)) {
            TurnusLogger.setLevel(TurnusLevel.ALL);
        }

        // load trace project
        File tDir = new File(config.getString(TRACE_PROJECT));
        TraceProject project = TraceProject.load(tDir);

        SimplePipelining sp = new SimplePipelining(project);
        sp.setConfiguration(config);

        SimplePipelingData data = sp.run();

        TurnusLogger.info("Storing results...");
        File outPath = new File(config.getString(OUTPUT_PATH));

        // store the analysis report
        String uuid = UUID.randomUUID().toString();
        File rFile = new File(outPath, uuid + "." + TurnusExtension.REPORT);
        Report report = DataFactory.eINSTANCE.createReport();
        report.setDate(new Date());
        report.setComment("Report with only Simple Pipeling results analysis");
        report.getDataSet().add(data);
        EcoreHelper.storeEObject(report, new ResourceSetImpl(), rFile);
        TurnusLogger.info("TURNUS report stored in " + rFile);

        // store formatted reports
        String xlsName = config.getString(XLS, "");
        if (!xlsName.isEmpty()) {
            File xlsFile = new File(outPath, xlsName + ".xls");
            new XlsSimplePipeliningDataWriter().write(data, xlsFile);
            TurnusLogger.info("XLS report stored in " + xlsFile);
        }

        TurnusLogger.info("Analysis Done!");

    } catch (ParseException e) {
        TurnusLogger.error(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(SimplePipeliningCliLauncher.class.getSimpleName(), cliOptions);
    } catch (Exception e) {
        TurnusLogger.error(e.getMessage());
    }

}

From source file:com.dhenton9000.screenshots.ScreenShotLauncher.java

/**
 * main launching method that takes command line arguments
 *
 * @param args/*from w  w  w.  j a v  a 2s .  com*/
 */
public static void main(String[] args) {

    final String[] actions = { ACTIONS.source.toString(), ACTIONS.target.toString(),
            ACTIONS.compare.toString() };
    final List actionArray = Arrays.asList(actions);

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("action").hasArg().isRequired().withArgName("action").create());
    HelpFormatter formatter = new HelpFormatter();

    String header = "Process screenshots\n" + "--action=source   create source screenshots\n"
            + "--action=target     create the screenshots for comparison\n"
            + "--action=compare  compare the images\n" + "%s\n\n";

    String action = null;
    try {
        // parse the command line arguments
        CommandLineParser parser = new PosixParser();
        CommandLine line = parser.parse(options, args);

        // validate that action option has been set
        if (line.hasOption("action")) {
            action = line.getOptionValue("action");
            LOG.debug("action '" + action + "'");
            if (!actionArray.contains(action)) {

                formatter.printHelp(ScreenShotLauncher.class.getName(),
                        String.format(header, String.format("action option '%s' is invalid", action)), options,
                        "\n\n", true);
                System.exit(1);

            }

        } else {
            formatter.printHelp(ScreenShotLauncher.class.getName(), String.format(header, "not found"), options,
                    "\n\n", false);
            System.exit(1);
        }
    } catch (ParseException exp) {
        formatter.printHelp(ScreenShotLauncher.class.getName(),
                String.format(header, "problem " + exp.getMessage()), options, "\n\n", false);
        System.exit(1);

    }
    ACTIONS actionEnum = ACTIONS.valueOf(action);
    ScreenShotLauncher launcher = new ScreenShotLauncher();
    try {
        launcher.handleRequest(actionEnum);
    } catch (Exception ex) {
        LOG.error(ex.getMessage(), ex);

    }
}

From source file:com.opengamma.bbg.referencedata.cache.MongoDBReferenceDataCacheRefresher.java

/**
 * Runs the tool./* ww w .ja  v a2s  .c  om*/
 * 
 * @param args  empty arguments
 * @throws Exception 
 */
public static void main(final String[] args) throws Exception { // CSIGNORE
    PlatformConfigUtils.configureSystemProperties();
    System.out.println("Starting connections");
    String configLocation = "com/opengamma/bbg/bbg-reference-data-context.xml";

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(configLocation);
    try {
        context.start();
        MongoDBValueCachingReferenceDataProvider mongoProvider = context
                .getBean("bloombergReferenceDataProvider", MongoDBValueCachingReferenceDataProvider.class);
        MongoDBReferenceDataCacheRefresher refresher = new MongoDBReferenceDataCacheRefresher(mongoProvider);

        Options options = createOptions();
        CommandLineParser parser = new PosixParser();
        CommandLine line = null;
        try {
            line = parser.parse(options, args);
        } catch (ParseException e) {
            usage(options);
            return;
        }
        if (line.hasOption(HELP_OPTION)) {
            usage(options);
            return;
        }

        //TODO other options, e.g. explicitly specify security 
        int numberOfSecurities = Integer.parseInt(line.getArgs()[0]);
        int id = Integer.parseInt(line.getArgs()[1]);
        System.out.println("Refreshing " + numberOfSecurities + " securities, id " + id);
        refresher.refreshCaches(numberOfSecurities, id);
        System.out.println("Done refreshing");
    } catch (Exception ex) {
        context.close();
        throw ex;
    }
}