Example usage for org.apache.commons.cli CommandLine hasOption

List of usage examples for org.apache.commons.cli CommandLine hasOption

Introduction

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

Prototype

public boolean hasOption(char opt) 

Source Link

Document

Query to see if an option has been set.

Usage

From source file:com.github.brandtg.switchboard.MysqlReplicator.java

/** Main. */
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("u", "user", true, "MySQL user");
    options.addOption("p", "password", true, "MySQL password");
    options.addOption("h", "host", true, "MySQL host");
    options.addOption("P", "port", true, "MySQL port");
    options.addOption("s", "sinkPort", true, "Local sink port");
    options.addOption("l", "lastIndex", true, "Last transaction ID");
    options.addOption("h", "help", false, "Prints help message");
    CommandLine commandLine = new GnuParser().parse(options, args);

    if (commandLine.getArgs().length < 2 || commandLine.hasOption("help")) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("usage: [opts] switchboardHost:port db1 [db2 ...]", options);
        System.exit(1);/*from w  w  w . jav  a 2  s. co  m*/
    }

    // Switchboard host
    String[] hostPort = commandLine.getArgs()[0].split(":");
    InetSocketAddress source = new InetSocketAddress(hostPort[0], Integer.valueOf(hostPort[1]));
    InetSocketAddress sink = new InetSocketAddress(
            Integer.valueOf(commandLine.getOptionValue("sinkPort", "9090")));

    // Databases to replicate
    String[] databases = Arrays.copyOfRange(commandLine.getArgs(), 1, commandLine.getArgs().length);

    // JDBC params for local copy
    String user = commandLine.getOptionValue("user", "root");
    String password = commandLine.getOptionValue("password", "");
    String jdbcString = String.format("jdbc:mysql://%s:%d", commandLine.getOptionValue("host", "localhost"),
            Integer.valueOf(commandLine.getOptionValue("port", "3306")));
    Long lastIndex = Long.valueOf(commandLine.getOptionValue("lastIndex", "-1"));

    // Create replicators
    final List<MysqlReplicator> replicators = new ArrayList<>();
    for (String database : databases) {
        MysqlReplicator replicator = new MysqlReplicator(database, source, sink, jdbcString, user, password,
                lastIndex);
        replicators.add(replicator);
    }

    // Shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            for (MysqlReplicator replicator : replicators) {
                try {
                    replicator.shutdown();
                } catch (Exception e) {
                    LOG.error("Could not shut down {}", replicator, e);
                }
            }
        }
    });

    for (MysqlReplicator replicator : replicators) {
        replicator.start();
        LOG.info("Started {}", replicator);
    }
}

From source file:lapispaste.Main.java

public static void main(String[] args) throws Exception {
    // create Options object
    Options options = new Options();
    String version;/*w ww  . j a  va 2s.c  om*/

    version = "0.1";

    // populate Options with.. well options :P
    options.addOption("v", false, "Display version");
    options.addOption("f", true, "File to paste");

    // non-critical options
    options.addOption("t", true, "Code language");
    options.addOption("p", false, "Read from pipe");

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

    // assemble a map of values
    final Map<String, String> pastemap = new HashMap<String, String>();

    if (cmd.hasOption("t"))
        pastemap.put("format", cmd.getOptionValue("t").toString());
    else
        pastemap.put("format", "text");

    // critical options
    if (cmd.hasOption("v"))
        System.out.println("lapispaste version " + version);
    else if (cmd.hasOption("f")) {
        File file = new File(cmd.getOptionValue("f"));
        StringBuffer pdata = readData(new FileReader(file));
        paster(pastemap, pdata);
    } else if (cmd.hasOption("p")) {
        StringBuffer pdata = readData(new InputStreamReader(System.in));
        paster(pastemap, pdata);
    } else {
        // Did not recieve what was expected
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("lapispaste [OPTIONS] [FILE]", options);
    }

}

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

/**
 * @param args//from   ww  w  .  j av a  2  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.jolbox.benchmark.BenchmarkMain.java

/**
 * @param args/*w  w w.jav a 2s. c o  m*/
 * @throws ClassNotFoundException 
 * @throws PropertyVetoException 
 * @throws SQLException 
 * @throws NoSuchMethodException 
 * @throws InvocationTargetException 
 * @throws IllegalAccessException 
 * @throws InterruptedException 
 * @throws SecurityException 
 * @throws IllegalArgumentException 
 * @throws NamingException 
 * @throws ParseException 
 */
public static void main(String[] args) throws ClassNotFoundException, SQLException, PropertyVetoException,
        IllegalArgumentException, SecurityException, InterruptedException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, NamingException, ParseException {

    Options options = new Options();
    options.addOption("t", "threads", true, "Max number of threads");
    options.addOption("s", "stepping", true, "Stepping of threads");
    options.addOption("p", "poolsize", true, "Pool size");
    options.addOption("h", "help", false, "Help");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("benchmark.jar", options);
        System.exit(1);
    }

    Class.forName("com.jolbox.bonecp.MockJDBCDriver");
    new MockJDBCDriver();
    BenchmarkTests tests = new BenchmarkTests();

    BenchmarkTests.threads = 200;
    BenchmarkTests.stepping = 20;
    BenchmarkTests.pool_size = 200;
    // warm up
    System.out.println("JIT warm up");
    tests.testMultiThreadedConstantDelay(0);

    BenchmarkTests.threads = 200;
    BenchmarkTests.stepping = 5;
    BenchmarkTests.pool_size = 100;

    if (cmd.hasOption("t")) {
        BenchmarkTests.threads = Integer.parseInt(cmd.getOptionValue("t", "400"));
    }
    if (cmd.hasOption("s")) {
        BenchmarkTests.stepping = Integer.parseInt(cmd.getOptionValue("s", "20"));
    }
    if (cmd.hasOption("p")) {
        BenchmarkTests.pool_size = Integer.parseInt(cmd.getOptionValue("p", "200"));
    }

    System.out.println("Starting benchmark tests with " + BenchmarkTests.threads + " threads (stepping "
            + BenchmarkTests.stepping + ") using pool size of " + BenchmarkTests.pool_size + " connections");

    System.out.println("Starting tests");
    plotLineGraph(tests.testMultiThreadedConstantDelay(0), 0, false);
    //      plotLineGraph(tests.testMultiThreadedConstantDelay(10), 10, false);
    //      plotLineGraph(tests.testMultiThreadedConstantDelay(25), 25, false);
    //      plotLineGraph(tests.testMultiThreadedConstantDelay(50), 50, false);
    //      plotLineGraph(tests.testMultiThreadedConstantDelay(75), 75, false);
    //      
    plotBarGraph("Single Thread", "bonecp-singlethread-poolsize-" + BenchmarkTests.pool_size + "-threads-"
            + BenchmarkTests.threads + ".png", tests.testSingleThread());
    plotBarGraph(
            "Prepared Statement\nSingle Threaded", "bonecp-preparedstatement-single-poolsize-"
                    + BenchmarkTests.pool_size + "-threads-" + BenchmarkTests.threads + ".png",
            tests.testPreparedStatementSingleThread());
    //      plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(0), 0, true);
    //      plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(10), 10, true);
    //      plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(25), 25, true);
    //      plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(50), 50, true);
    //      plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(75), 75, true);

}

From source file:de.dknapps.pswgendesktop.main.PswGenDesktop.java

/**
 * Hier werden die Kommandozeilenparameter analysiert und die Anwendung gestartet.
 *///from w  w w .ja v  a  2s.c o m
public static void main(String[] args) throws IOException {
    Options options = new Options();
    Option help = new Option("help", "print this message");
    @SuppressWarnings("static-access")
    Option services = OptionBuilder.withArgName("file").hasArg()
            .withDescription("use given file to store services").create("services");
    @SuppressWarnings("static-access")
    Option upgrade = OptionBuilder.withArgName("passphrase").hasArg()
            .withDescription("converts and re-encrypts services to new format if not too old")
            .create("upgrade");
    options.addOption(help);
    options.addOption(services);
    options.addOption(upgrade);
    CommandLineParser parser = new GnuParser(); // GnuParser => mehrbuchstabige Optionen
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage()); // line bleibt null, dann kommt die Hilfe
    }
    if (line == null || line.hasOption("help")) { // Hilfe ausgeben => nur das tun
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("pswgen", options);
    } else if (line.hasOption("upgrade")) { // Datei umformatieren => nur das tun
        String servicesFilename = line.getOptionValue("services", CoreConstants.SERVICES_FILENAME);
        String passphrase = line.getOptionValue("upgrade");
        PswGenCtl ctl = new PswGenCtl(servicesFilename);
        ctl.upgradeServiceInfoList(passphrase);
    } else {
        String servicesFilename = line.getOptionValue("services", CoreConstants.SERVICES_FILENAME);
        PswGenCtl ctl = new PswGenCtl(servicesFilename);
        ctl.start(); // Anwendung starten, PswGenCtl terminiert die VM
    }
}

From source file:benchmarkio.controlcenter.LaunchRocket.java

public static void main(final String[] args) throws Exception {
    // create the parser
    final CommandLineParser parser = new BasicParser();

    // parse the command line arguments
    final CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("u")) {
        displayHelp();/*from   www.  j a v  a2  s  .c o m*/
    }

    final String host = cmd.getOptionValue("host");
    final int port = Integer.parseInt(cmd.getOptionValue("port"));
    final BrokerType brokerType = BrokerType.valueOf(cmd.getOptionValue("broker-type"));
    final int numConsumers = Integer.parseInt(cmd.getOptionValue("num-consumers"));
    final int numProducers = Integer.parseInt(cmd.getOptionValue("num-producers"));
    final int totalNumberOfMessages = Integer.parseInt(cmd.getOptionValue("total-number-of-messages"));
    final double msgSizeInKB = Double.parseDouble(cmd.getOptionValue("msg-size-in-kb"));

    // Optional options
    final Optional<String> optionalBenchmarkType = Optional.fromNullable(cmd.getOptionValue("benchmark-type"));
    final Optional<String> optionalDurable = Optional.fromNullable(cmd.getOptionValue("durable"));
    // Kafka Specific
    final Optional<String> optionalZookeeper = Optional.fromNullable(cmd.getOptionValue("zookeeper"));
    Optional<String> optionalKafkaProducerType = Optional
            .fromNullable(cmd.getOptionValue("kafka-producer-type"));

    BenchmarkType benchmarkType;
    if (optionalBenchmarkType.isPresent()) {
        benchmarkType = BenchmarkType.valueOf(optionalBenchmarkType.get());
    } else {
        log.info("Benchmark type was not specified, defaulting to: {}", BenchmarkType.PRODUCER_AND_CONSUMER);

        benchmarkType = BenchmarkType.PRODUCER_AND_CONSUMER;
    }

    boolean durable = false;
    if (optionalDurable.isPresent()) {
        durable = Boolean.valueOf(optionalDurable.get());
    } else {
        log.info("Durable parameter was not specified, defaulting to: FALSE");
    }

    if (brokerType == BrokerType.KAFKA) {
        if (!optionalZookeeper.isPresent()) {
            log.error("zookeeper is missing, it is a required property for KAFKA broker");

            System.exit(0);
        }

        if (!optionalKafkaProducerType.isPresent()) {
            log.info("kafka-producer-type is not specified, defaulting to sync");

            optionalKafkaProducerType = Optional.of("sync");
        } else if (!optionalKafkaProducerType.get().equals("sync")
                && !optionalKafkaProducerType.get().equals("async")) {
            log.warn("kafka-producer-type is not one of the accepted sync | async values, defaulting to sync");

            optionalKafkaProducerType = Optional.of("sync");
        }
    }

    log.info("destination (topic or queue): {}", Consts.DESTINATION_NAME);
    log.info("host: {}", host);
    log.info("port: {}", port);
    log.info("broker-type: {}", brokerType);
    log.info("benchmark-type: {}", benchmarkType);
    log.info("durable: {}", durable);
    log.info("num-consumers: {}", numConsumers);
    log.info("num-producers: {}", numProducers);
    log.info("total-number-of-messages: {}", totalNumberOfMessages);
    log.info("msg-size-in-kb: {}", msgSizeInKB);

    if (brokerType == BrokerType.KAFKA) {
        log.info("zookeeper: {}", optionalZookeeper.get());
        log.info("kafka-producer-type: {}", optionalKafkaProducerType.get());
    }

    LaunchRocket.start(brokerType, benchmarkType, durable, host, port, numConsumers, numProducers,
            totalNumberOfMessages, msgSizeInKB, optionalZookeeper, optionalKafkaProducerType);

    System.exit(0);
}

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

public static void main(String[] args) {
    Options options = buildOptions();/*from   ww w  . ja v a2s .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.yahoo.pasc.paxos.client.PaxosClient.java

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

    CommandLineParser parser = new PosixParser();
    Options options;/* w  w w . ja v  a  2  s  .c o  m*/

    {
        Option id = new Option("i", true, "client id");
        Option clients = new Option("c", true, "number of clients");
        Option host = new Option("l", true, "leader (hostname:port)");
        Option servers = new Option("s", true, "number of servers");
        Option quorum = new Option("q", true, "necesarry quorum at the client");
        Option port = new Option("p", true, "port used by client");
        Option buffer = new Option("b", true, "number of concurrent clients");
        Option timeout = new Option("t", true, "timeout in milliseconds");
        Option udp = new Option("u", false, "use UDP");
        Option zookeeper = new Option("z", true, "zookeeper connection string");
        Option warmup = new Option("w", true, "warmup messagges");
        Option measuring = new Option("m", true, "measuring time");
        Option request = new Option("r", true, "request size");
        Option frequency = new Option("f", true, "frequency of throughput info");
        Option anm = new Option("a", false, "use protection");
        Option inlineThresh = new Option("n", true, "threshold for sending requests iNline with accepts ");
        Option asynSize = new Option("y", true, "size of async messages queue");

        options = new Options();
        options.addOption(id).addOption(host).addOption(servers).addOption(quorum).addOption(port)
                .addOption(warmup).addOption(buffer).addOption(timeout).addOption(udp).addOption(zookeeper)
                .addOption(clients).addOption(measuring).addOption(request).addOption(frequency).addOption(anm)
                .addOption(inlineThresh).addOption(asynSize);
    }

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

        String host = line.hasOption('l') ? line.getOptionValue('l')
                : "localhost:20548,localhost:20748,localhost:20778";
        String zkConnection = line.hasOption('z') ? line.getOptionValue('z') : "localhost:2181";
        int clientIds = line.hasOption('i') ? Integer.parseInt(line.getOptionValue('i')) : 0;
        int servers = line.hasOption('s') ? Integer.parseInt(line.getOptionValue('s')) : 3;
        int quorum = line.hasOption('q') ? Integer.parseInt(line.getOptionValue('q')) : 1;
        int buffer = line.hasOption('b') ? Integer.parseInt(line.getOptionValue('b')) : 1;
        int timeout = line.hasOption('t') ? Integer.parseInt(line.getOptionValue('t')) : 5000;
        int clients = line.hasOption('c') ? Integer.parseInt(line.getOptionValue('c')) : 1;
        int requestSize = line.hasOption('r') ? Integer.parseInt(line.getOptionValue('r')) : 0;
        int inlineThreshold = line.hasOption('n') ? Integer.parseInt(line.getOptionValue('n')) : 1000;
        int asynSize = line.hasOption('y') ? Integer.parseInt(line.getOptionValue('y')) : 100;
        boolean protection = line.hasOption('a');

        int threads = Runtime.getRuntime().availableProcessors() * 2;
        final ExecutionHandler executor = new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(threads,
                1024 * 1024, 1024 * 1024 * 1024, 30, TimeUnit.SECONDS, Executors.defaultThreadFactory()));

        String[] serverHosts = host.split(",");

        ServerHelloHandler shello = new ServerHelloHandler();
        ReplyHandler reply = new ReplyHandler();
        SubmitHandler submit = new SubmitHandler();
        TimeoutHandler tout = new TimeoutHandler();
        AsyncMessageHandler asyncm = new AsyncMessageHandler();
        ByeHandler bye = new ByeHandler();
        HelloHandler hello = new HelloHandler();

        Random rnd = new Random();

        for (int i = 0; i < buffer; ++i) {
            ClientState clientState = new ClientState(servers, quorum, inlineThreshold, asynSize);
            final PascRuntime<ClientState> runtime = new PascRuntime<ClientState>(protection);
            runtime.setState(clientState);
            runtime.addHandler(ServerHello.class, shello);
            runtime.addHandler(Reply.class, reply);
            runtime.addHandler(Submit.class, submit);
            runtime.addHandler(Timeout.class, tout);
            runtime.addHandler(AsyncMessage.class, asyncm);
            runtime.addHandler(Bye.class, bye);
            runtime.addHandler(Hello.class, hello);

            final PaxosClientHandler handler = new PaxosClientHandler(runtime, new SimpleClient(requestSize),
                    serverHosts, clients, timeout, zkConnection, executor);

            if (line.hasOption('w'))
                handler.setWarmup(Integer.parseInt(line.getOptionValue('w')));
            if (line.hasOption('m'))
                handler.setMeasuringTime(Integer.parseInt(line.getOptionValue('m')));
            if (line.hasOption('f'))
                handler.setPeriod(Integer.parseInt(line.getOptionValue('f')));

            handler.start();

            Thread.sleep(rnd.nextInt(200));
        }
    } catch (Exception e) {
        System.err.println("Unexpected exception " + e);
        e.printStackTrace();

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Paxos", options);

        System.exit(-1);
    }
}

From source file:edu.ksu.cis.indus.xmlizer.JimpleXMLizerCLI.java

/**
 * The entry point to execute this xmlizer from command prompt.
 * /* www.ja v a  2 s .  c  om*/
 * @param s is the command-line arguments.
 * @throws RuntimeException when jimple xmlization fails.
 * @pre s != null
 */
public static void main(final String[] s) {
    final Scene _scene = Scene.v();

    final Options _options = new Options();
    Option _o = new Option("d", "dump directory", true, "The directory in which to write the xml files.  "
            + "If unspecified, the xml output will be directed standard out.");
    _o.setArgs(1);
    _o.setArgName("path");
    _o.setOptionalArg(false);
    _options.addOption(_o);
    _o = new Option("h", "help", false, "Display message.");
    _options.addOption(_o);
    _o = new Option("p", "soot-classpath", true, "Prepend this to soot class path.");
    _o.setArgs(1);
    _o.setArgName("classpath");
    _o.setOptionalArg(false);
    _options.addOption(_o);

    final HelpFormatter _help = new HelpFormatter();

    try {
        final CommandLine _cl = (new BasicParser()).parse(_options, s);
        final String[] _args = _cl.getArgs();

        if (_cl.hasOption('h')) {
            final String _cmdLineSyn = "java " + JimpleXMLizerCLI.class.getName() + "<options> <class names>";
            _help.printHelp(_cmdLineSyn.length(), _cmdLineSyn, "", _options, "", true);
        } else {
            if (_args.length > 0) {
                if (_cl.hasOption('p')) {
                    _scene.setSootClassPath(
                            _cl.getOptionValue('p') + File.pathSeparator + _scene.getSootClassPath());
                }

                final NamedTag _tag = new NamedTag("JimpleXMLizer");

                for (int _i = 0; _i < _args.length; _i++) {
                    final SootClass _sc = _scene.loadClassAndSupport(_args[_i]);
                    _sc.addTag(_tag);
                }
                final IProcessingFilter _filter = new TagBasedProcessingFilter(_tag.getName());
                writeJimpleAsXML(new Environment(_scene), _cl.getOptionValue('d'), null,
                        new UniqueJimpleIDGenerator(), _filter);
            } else {
                System.out.println("No classes were specified.");
            }
        }
    } catch (final ParseException _e) {
        LOGGER.error("Error while parsing command line.", _e);
        printUsage(_options);
    } catch (final Throwable _e) {
        LOGGER.error("Beyond our control. May day! May day!", _e);
        throw new RuntimeException(_e);
    }
}

From source file:edu.msu.cme.rdp.alignment.errorcheck.RmPartialSeqs.java

/**
* This program detects partial sequences based on the best pairwise alignment for each query sequence, 
* @param args/*from  w ww.  j  av  a  2s  .c  o  m*/
* @throws Exception 
*/
public static void main(String[] args) throws Exception {

    String trainseqFile = null;
    String queryFile = null;
    PrintStream seqOutStream = null;
    PrintStream alignOutStream = null;
    AlignmentMode mode = AlignmentMode.overlap;
    int k = 10;
    int min_gaps = 50;

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("alignment-mode")) {
            String m = line.getOptionValue("alignment-mode").toLowerCase();
            mode = AlignmentMode.valueOf(m);
        }

        if (line.hasOption("min_gaps")) {
            min_gaps = Integer.parseInt(line.getOptionValue("min_gaps"));
        }
        if (line.hasOption("knn")) {
            k = Integer.parseInt(line.getOptionValue("knn"));
        }
        if (line.hasOption("alignment-out")) {
            alignOutStream = new PrintStream(new File(line.getOptionValue("alignment-out")));
        }
        args = line.getArgs();
        if (args.length != 3) {
            throw new Exception("wrong number of arguments");
        }

        trainseqFile = args[0];
        queryFile = args[1];
        seqOutStream = new PrintStream(new File(args[2]));
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
        new HelpFormatter().printHelp(80,
                " [options] fulllengthSeqFile queryFile passedSeqOutFile\n  sequences can be either protein or nucleotide",
                "", options, "");
        return;
    }

    RmPartialSeqs theObj = new RmPartialSeqs(trainseqFile, queryFile, mode, k, min_gaps);

    theObj.checkPartial(seqOutStream, alignOutStream);
}