Example usage for org.apache.commons.cli HelpFormatter printHelp

List of usage examples for org.apache.commons.cli HelpFormatter printHelp

Introduction

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

Prototype

public void printHelp(String cmdLineSyntax, Options options, boolean autoUsage) 

Source Link

Document

Print the help for options with the specified command line syntax.

Usage

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

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);//w  ww  .  j a  va 2s. 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 optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

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

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

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

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

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

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                loadOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        // Add the LoadedObjectCounter store
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        //         storeOptions.add(PersistentResourceOptions.EStoreOption.LOADED_OBJECT_COUNTER_LOGGING);
        storeOptions.add(MapResourceOptions.EStoreMapOption.AUTOCOMMIT);
        storeOptions.add(PersistentResourceOptions.EStoreOption.ESTRUCUTRALFEATURE_CACHING);
        storeOptions.add(PersistentResourceOptions.EStoreOption.IS_SET_CACHING);
        storeOptions.add(PersistentResourceOptions.EStoreOption.SIZE_CACHING);
        loadOpts.put(PersistentResourceOptions.STORE_OPTIONS, storeOptions);
        resource.load(loadOpts);
        {
            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<MethodDeclaration> list = ASE2015JavaQueries.getSpecificInvisibleMethodDeclarations(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)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } 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:edu.wisc.doit.tcrypt.cli.TokenCrypt.java

public static void main(String[] args) throws IOException {
    // create Options object
    final Options options = new Options();

    // operation opt group
    final OptionGroup cryptTypeGroup = new OptionGroup();
    cryptTypeGroup.addOption(new Option("e", "encrypt", false, "Encrypt a token"));
    cryptTypeGroup.addOption(new Option("d", "decrypt", false, "Decrypt a token"));
    cryptTypeGroup/*from w w w  . jav a2  s.  c  o  m*/
            .addOption(new Option("c", "check", false, "Check if the string looks like an encrypted token"));
    cryptTypeGroup.setRequired(true);
    options.addOptionGroup(cryptTypeGroup);

    // token source opt group
    final OptionGroup tokenGroup = new OptionGroup();
    final Option tokenOpt = new Option("t", "token", true, "The token(s) to operate on");
    tokenOpt.setArgs(Option.UNLIMITED_VALUES);
    tokenGroup.addOption(tokenOpt);
    final Option tokenFileOpt = new Option("f", "file", true,
            "A file with one token per line to operate on, if - is specified stdin is used");
    tokenGroup.addOption(tokenFileOpt);
    tokenGroup.setRequired(true);
    options.addOptionGroup(tokenGroup);

    final Option keyOpt = new Option("k", "keyFile", true,
            "Key file to use. Must be a private key for decryption and a public key for encryption");
    keyOpt.setRequired(true);
    options.addOption(keyOpt);

    // create the parser
    final CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // automatically generate the help statement
        System.err.println(exp.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java " + TokenCrypt.class.getName(), options, true);
        System.exit(1);
    }

    final Reader keyReader = createKeyReader(line);

    final TokenHandler tokenHandler = createTokenHandler(line, keyReader);

    if (line.hasOption("t")) {
        //tokens on cli
        final String[] tokens = line.getOptionValues("t");
        for (final String token : tokens) {
            handleToken(tokenHandler, token);
        }
    } else {
        //tokens from a file
        final String tokenFile = line.getOptionValue("f");
        final BufferedReader fileReader;
        if ("-".equals(tokenFile)) {
            fileReader = new BufferedReader(new InputStreamReader(System.in));
        } else {
            fileReader = new BufferedReader(new FileReader(tokenFile));
        }

        while (true) {
            final String token = fileReader.readLine();
            if (token == null) {
                break;
            }

            handleToken(tokenHandler, token);
        }
    }
}

From source file:at.newmedialab.ldpath.template.LDTemplate.java

public static void main(String[] args) {
    Options options = buildOptions();/*from  w  ww .  j a v a 2 s  .c om*/

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

        Level logLevel = Level.WARN;

        if (cmd.hasOption("loglevel")) {
            String logLevelName = cmd.getOptionValue("loglevel");
            if ("DEBUG".equals(logLevelName.toUpperCase())) {
                logLevel = Level.DEBUG;
            } else if ("INFO".equals(logLevelName.toUpperCase())) {
                logLevel = Level.INFO;
            } else if ("WARN".equals(logLevelName.toUpperCase())) {
                logLevel = Level.WARN;
            } else if ("ERROR".equals(logLevelName.toUpperCase())) {
                logLevel = Level.ERROR;
            } else {
                log.error("unsupported log level: {}", logLevelName);
            }
        }

        if (logLevel != null) {
            for (String logname : new String[] { "at", "org", "net", "com" }) {

                ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
                        .getLogger(logname);
                logger.setLevel(logLevel);
            }
        }

        File template = null;
        if (cmd.hasOption("template")) {
            template = new File(cmd.getOptionValue("template"));
        }

        GenericSesameBackend backend;
        if (cmd.hasOption("store")) {
            backend = new LDPersistentBackend(new File(cmd.getOptionValue("store")));
        } else {
            backend = new LDMemoryBackend();
        }

        Resource context = null;
        if (cmd.hasOption("context")) {
            context = backend.getRepository().getValueFactory().createURI(cmd.getOptionValue("context"));
        }

        BufferedWriter out = null;
        if (cmd.hasOption("out")) {
            File of = new File(cmd.getOptionValue("out"));
            if (of.canWrite()) {
                out = new BufferedWriter(new FileWriter(of));
            } else {
                log.error("cannot write to output file {}", of);
                System.exit(1);
            }
        } else {
            out = new BufferedWriter(new OutputStreamWriter(System.out));
        }

        if (backend != null && context != null && template != null) {
            TemplateEngine<Value> engine = new TemplateEngine<Value>(backend);

            engine.setDirectoryForTemplateLoading(template.getParentFile());
            engine.processFileTemplate(context, template.getName(), out);
            out.flush();
            out.close();
        }

        if (backend instanceof LDPersistentBackend) {
            ((LDPersistentBackend) backend).shutdown();
        }

    } catch (ParseException e) {
        System.err.println("invalid arguments");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    } catch (FileNotFoundException e) {
        System.err.println("file or program could not be found");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    } catch (IOException e) {
        System.err.println("could not access file");
        e.printStackTrace(System.err);
    } catch (TemplateException e) {
        System.err.println("error while processing template");
        e.printStackTrace(System.err);
    }

}

From source file:com.cloudera.recordbreaker.learnstructure.test.GenerateRandomData.java

/**
 *///from w w  w . jav a 2s .c o  m
public static void main(String argv[]) throws IOException {
    CommandLine cmd = null;
    Options options = new Options();
    options.addOption("?", false, "Help for command-line");
    options.addOption("n", true, "Number elts to emit");

    try {
        CommandLineParser parser = new PosixParser();
        cmd = parser.parse(options, argv);
    } catch (ParseException pe) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("GenerateRandomData", options, true);
        System.exit(-1);
    }

    if (cmd.hasOption("?")) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("GenerateRandomData", options, true);
        System.exit(0);
    }

    int numToEmit = 100;
    if (cmd.hasOption("n")) {
        try {
            numToEmit = Integer.parseInt(cmd.getOptionValue("n"));
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
    }

    String[] argArray = cmd.getArgs();
    if (argArray.length == 0) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("GenerateRandomData", options, true);
        System.exit(0);
    }
    File inputSchemaFile = new File(argArray[0]).getCanonicalFile();
    File outputDataFile = new File(argArray[1]).getCanonicalFile();
    if (outputDataFile.exists()) {
        System.err.println("Output file already exists: " + outputDataFile.getCanonicalPath());
        System.exit(0);
    }

    GenerateRandomData grd = new GenerateRandomData();
    Schema schema = Schema.parse(inputSchemaFile);

    GenericDatumWriter datum = new GenericDatumWriter(schema);
    DataFileWriter out = new DataFileWriter(datum);
    out.create(schema, outputDataFile);
    try {
        for (int i = 0; i < numToEmit; i++) {
            out.append((GenericData.Record) grd.generateData(schema));
        }
    } finally {
        out.close();
    }
}

From source file:com.act.lcms.db.io.LoadTSVIntoDB.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    opts.addOption(Option.builder("t").argName("type")
            .desc("The type of TSV data to read, options are: " + StringUtils.join(TSV_TYPE.values(), ", "))
            .hasArg().required().longOpt("table-type").build());
    opts.addOption(Option.builder("i").argName("path").desc("The TSV file to read").hasArg().required()
            .longOpt("input-file").build());

    // DB connection options.
    opts.addOption(Option.builder().argName("database url")
            .desc("The url to use when connecting to the LCMS db").hasArg().longOpt("db-url").build());
    opts.addOption(Option.builder("u").argName("database user").desc("The LCMS DB user").hasArg()
            .longOpt("db-user").build());
    opts.addOption(Option.builder("p").argName("database password").desc("The LCMS DB password").hasArg()
            .longOpt("db-pass").build());
    opts.addOption(Option.builder("H").argName("database host")
            .desc(String.format("The LCMS DB host (default = %s)", DB.DEFAULT_HOST)).hasArg().longOpt("db-host")
            .build());/*from  ww  w . ja va  2  s.  c o m*/
    opts.addOption(Option.builder("P").argName("database port")
            .desc(String.format("The LCMS DB port (default = %d)", DB.DEFAULT_PORT)).hasArg().longOpt("db-port")
            .build());
    opts.addOption(Option.builder("N").argName("database name")
            .desc(String.format("The LCMS DB name (default = %s)", DB.DEFAULT_DB_NAME)).hasArg()
            .longOpt("db-name").build());

    // Everybody needs a little help from their friends.
    opts.addOption(
            Option.builder("h").argName("help").desc("Prints this help message").longOpt("help").build());

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp(LoadTSVIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        new HelpFormatter().printHelp(LoadTSVIntoDB.class.getCanonicalName(), opts, true);
        return;
    }

    File inputFile = new File(cl.getOptionValue("input-file"));
    if (!inputFile.exists()) {
        System.err.format("Unable to find input file at %s\n", cl.getOptionValue("input-file"));
        new HelpFormatter().printHelp(LoadTSVIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

    TSV_TYPE contentType = null;
    try {
        contentType = TSV_TYPE.valueOf(cl.getOptionValue("table-type"));
    } catch (IllegalArgumentException e) {
        System.err.format("Unrecognized TSV type '%s'\n", cl.getOptionValue("table-type"));
        new HelpFormatter().printHelp(LoadTSVIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

    DB db;

    if (cl.hasOption("db-url")) {
        db = new DB().connectToDB(cl.getOptionValue("db-url"));
    } else {
        Integer port = null;
        if (cl.getOptionValue("P") != null) {
            port = Integer.parseInt(cl.getOptionValue("P"));
        }
        db = new DB().connectToDB(cl.getOptionValue("H"), port, cl.getOptionValue("N"), cl.getOptionValue("u"),
                cl.getOptionValue("p"));
    }

    try {
        db.getConn().setAutoCommit(false);

        TSVParser parser = new TSVParser();
        parser.parse(inputFile);

        List<Pair<Integer, DB.OPERATION_PERFORMED>> results = null;
        switch (contentType) {
        case CURATED_CHEMICAL:
            results = CuratedChemical.insertOrUpdateCuratedChemicalsFromTSV(db, parser);
            break;
        case CONSTRUCT:
            results = ConstructEntry.insertOrUpdateCompositionMapEntriesFromTSV(db, parser);
            break;
        case CHEMICAL_OF_INTEREST:
            results = ChemicalOfInterest.insertOrUpdateChemicalOfInterestsFromTSV(db, parser);
            break;
        default:
            throw new RuntimeException(String.format("Unsupported TSV type: %s", contentType));
        }
        if (results != null) {
            for (Pair<Integer, DB.OPERATION_PERFORMED> r : results) {
                System.out.format("%d: %s\n", r.getLeft(), r.getRight());
            }
        }
        // If we didn't encounter an exception, commit the transaction.
        db.getConn().commit();
    } catch (Exception e) {
        System.err.format("Caught exception when trying to load plate composition, rolling back. %s\n",
                e.getMessage());
        db.getConn().rollback();
        throw (e);
    } finally {
        db.getConn().close();
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosMapCreator.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  w  w. j  av a  2s.c  o m
    inputOpt.setRequired(true);

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

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

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

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

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

        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        URI targetUri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(OUT)));

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

        ResourceSet resourceSet = new ResourceSetImpl();

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource sourceResource = resourceSet.createResource(sourceUri);
        Map<String, Object> loadOpts = new HashMap<String, Object>();
        if ("zxmi".equals(sourceUri.fileExtension())) {
            loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        }

        Runtime.getRuntime().gc();
        long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}",
                MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
        LOG.log(Level.INFO, "Loading source resource");
        sourceResource.load(loadOpts);

        LOG.log(Level.INFO, "Source resource loaded");
        Runtime.getRuntime().gc();
        long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
        LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

        Resource targetResource = resourceSet.createResource(targetUri);

        Map<String, Object> saveOpts = new HashMap<String, Object>();
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        storeOptions.add(MapResourceOptions.EStoreMapOption.AUTOCOMMIT);
        saveOpts.put(MapResourceOptions.STORE_OPTIONS, storeOptions);
        targetResource.save(saveOpts);

        LOG.log(Level.INFO, "Start moving elements");
        targetResource.getContents().clear();
        targetResource.getContents().addAll(sourceResource.getContents());
        LOG.log(Level.INFO, "End moving elements");
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saved");

        if (targetResource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) targetResource);
        } else {
            targetResource.unload();
        }

    } 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());
        e.printStackTrace();
    }
}

From source file:illarion.compile.Compiler.java

public static void main(final String[] args) {
    ByteArrayOutputStream stdOutBuffer = new ByteArrayOutputStream();
    PrintStream orgStdOut = System.out;
    System.setOut(new PrintStream(stdOutBuffer));

    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();/*  ww  w. ja v a2 s  .co  m*/

    Options options = new Options();

    final Option npcDir = new Option("n", "npc-dir", true,
            "The place where the compiled NPC files are stored.");
    npcDir.setArgs(1);
    npcDir.setArgName("directory");
    npcDir.setRequired(false);
    options.addOption(npcDir);

    final Option questDir = new Option("q", "quest-dir", true,
            "The place where the compiled Quest files are stored.");
    questDir.setArgs(1);
    questDir.setArgName("directory");
    questDir.setRequired(false);
    options.addOption(questDir);

    final Option type = new Option("t", "type", true,
            "This option is used to set what kind of parser is supposed to be used in case"
                    + " the content of standard input is processed.");
    type.setArgs(1);
    type.setArgName("type");
    type.setRequired(false);
    options.addOption(type);

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

        String[] files = cmd.getArgs();
        if (files.length > 0) {
            System.setOut(orgStdOut);
            stdOutBuffer.writeTo(orgStdOut);

            processFileMode(cmd);
        } else {
            System.setOut(orgStdOut);
            processStdIn(cmd);
        }
    } catch (final ParseException e) {
        final HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java -jar compiler.jar [Options] File", options, true);
        System.exit(-1);
    } catch (final IOException e) {
        LOGGER.error(e.getLocalizedMessage());
        System.exit(-1);
    }
}

From source file:net.mmberg.nadia.processor.NadiaProcessor.java

/**
 * @param args// ww  w .java2  s  .  c  o  m
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {

    Class<? extends UserInterface> ui_class = ConsoleInterface.class; //default UI
    String dialog_file = default_dialog; //default dialogue

    //process command line args
    Options cli_options = new Options();
    cli_options.addOption("h", "help", false, "print this message");
    cli_options.addOption(OptionBuilder.withLongOpt("interface").withDescription("select user interface")
            .hasArg(true).withArgName("console, rest").create("i"));
    cli_options.addOption("f", "file", true, "specify dialogue path and file, e.g. -f /res/dialogue1.xml");
    cli_options.addOption("r", "resource", true, "load dialogue (by name) from resources, e.g. -r dialogue1");
    cli_options.addOption("s", "store", true, "load dialogue (by name) from internal store, e.g. -s dialogue1");

    CommandLineParser parser = new org.apache.commons.cli.BasicParser();
    try {
        CommandLine cmd = parser.parse(cli_options, args);

        //Help
        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("nadia", cli_options, true);
            return;
        }

        //UI
        if (cmd.hasOption("i")) {
            String interf = cmd.getOptionValue("i");
            if (interf.equals("console"))
                ui_class = ConsoleInterface.class;
            else if (interf.equals("rest"))
                ui_class = RESTInterface.class;
        }

        //load dialogue from path file
        if (cmd.hasOption("f")) {
            dialog_file = "file:///" + cmd.getOptionValue("f");
        }
        //load dialogue from resources
        if (cmd.hasOption("r")) {
            dialog_file = config.getProperty(NadiaProcessorConfig.DIALOGUEDIR) + "/" + cmd.getOptionValue("r")
                    + ".xml";
        }
        //load dialogue from internal store
        if (cmd.hasOption("s")) {
            Dialog store_dialog = DialogStore.getInstance().getDialogFromStore((cmd.getOptionValue("s")));
            store_dialog.save();
            dialog_file = config.getProperty(NadiaProcessorConfig.DIALOGUEDIR) + "/" + cmd.getOptionValue("s")
                    + ".xml";
        }

    } catch (ParseException e1) {
        logger.severe("NADIA: loading by main-method failed. " + e1.getMessage());
        e1.printStackTrace();
    }

    //start Nadia with selected UI
    default_dialog = dialog_file;
    NadiaProcessor nadia = new NadiaProcessor();
    try {
        ui = ui_class.newInstance();
        ui.register(nadia);
        ui.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.uber.tchannel.ping.PingClient.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("h", "host", true, "Server Host to connect to");
    options.addOption("p", "port", true, "Server Port to connect to");
    options.addOption("n", "requests", true, "Number of requests to make");
    options.addOption("?", "help", false, "Usage");
    HelpFormatter formatter = new HelpFormatter();

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

    if (cmd.hasOption("?")) {
        formatter.printHelp("PingClient", options, true);
        return;/*from  w  w w  . j a  v  a2s. c o  m*/
    }

    String host = cmd.getOptionValue("h", "localhost");
    int port = Integer.parseInt(cmd.getOptionValue("p", "8888"));
    int requests = Integer.parseInt(cmd.getOptionValue("n", "10000"));

    System.out.println(String.format("Connecting from client to server on port: %d", port));
    new PingClient(host, port, requests).run();
    System.out.println("Stopping Client...");
}

From source file:com.asakusafw.compiler.bootstrap.BatchCompilerDriver.java

/**
 * The program entry./*from  www. j av  a2s  .c  o m*/
 * @param args command line arguments
 */
public static void main(String... args) {
    try {
        if (start(args) == false) {
            System.exit(1);
        }
    } catch (Exception e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(Integer.MAX_VALUE);
        formatter.printHelp(MessageFormat.format("java -classpath ... {0}", //$NON-NLS-1$
                BatchCompilerDriver.class.getName()), OPTIONS, true);
        e.printStackTrace(System.out);
        System.exit(1);
    }
}