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

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

Introduction

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

Prototype

GnuParser

Source Link

Usage

From source file:de.prozesskraft.pkraft.Checkconsistency.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    /*----------------------------
      get options from ini-file/*  w  w  w.  j a va 2s  .  c om*/
    ----------------------------*/
    File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Checkconsistency.class) + "/"
            + "../etc/pkraft-checkconsistency.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option odefinition = OptionBuilder.withArgName("definition").hasArg()
            .withDescription("[mandatory] process model in xml format.")
            //            .isRequired()
            .create("definition");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(odefinition);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    commandline = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("startinstance", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }
    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("definition"))) {
        System.out.println("option -definition is mandatory.");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    Process p1 = new Process();

    p1.setInfilexml(commandline.getOptionValue("definition"));
    Process p2;
    try {
        p2 = p1.readXml();

        if (p2.isProcessConsistent()) {
            System.out.println("process structure is consistent.");
        } else {
            System.out.println("process structure is NOT consistent.");
        }

        p2.printLog();

    } catch (JAXBException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

From source file:SequentialPageRank.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
    options.addOption(/*from   www  .j  a v a 2  s  .co m*/
            OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(SequentialPageRank.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String infile = cmdline.getOptionValue(INPUT);
    float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;

    int edgeCnt = 0;
    DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();

    BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));

    String line;
    while ((line = data.readLine()) != null) {
        line.trim();
        String[] arr = line.split("\\t");

        for (int i = 1; i < arr.length; i++) {
            graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
        }
    }

    data.close();

    WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();

    Set<Set<String>> components = clusterer.transform(graph);
    int numComponents = components.size();
    System.out.println("Number of components: " + numComponents);
    System.out.println("Number of edges: " + graph.getEdgeCount());
    System.out.println("Number of nodes: " + graph.getVertexCount());
    System.out.println("Random jump factor: " + alpha);

    // Compute PageRank.
    PageRank<String, Integer> ranker = new PageRank<String, Integer>(graph, alpha);
    ranker.evaluate();

    // Use priority queue to sort vertices by PageRank values.
    PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
    int i = 0;
    for (String pmid : graph.getVertices()) {
        q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
    }

    // Print PageRank values.
    System.out.println("\nPageRank of nodes, in descending order:");
    Ranking<String> r = null;
    while ((r = q.poll()) != null) {
        System.out.println(r.rankScore + "\t" + r.getRanked());
    }
}

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

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

    CommandLineParser clp = new GnuParser();

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

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

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

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

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

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

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

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

From source file:cd.what.DutchBot.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException, IrcException, InterruptedException,
        ConfigurationException, InstantiationException, IllegalAccessException {
    String configfile = "irc.properties";
    DutchBot bot = null;// w  ww. ja  va2 s. com

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("config").withArgName("configfile").hasArg()
            .withDescription("Load configuration from configfile, or use the default irc.cfg").create("c"));
    options.addOption(OptionBuilder.withLongOpt("server").withArgName("<url>").hasArg()
            .withDescription("Connect to this server").create("s"));
    options.addOption(OptionBuilder.withLongOpt("port").hasArg().withArgName("port")
            .withDescription("Connect to the server with this port").create("p"));
    options.addOption(OptionBuilder.withLongOpt("password").hasArg().withArgName("password")
            .withDescription("Connect to the server with this password").create("pw"));
    options.addOption(OptionBuilder.withLongOpt("nick").hasArg().withArgName("nickname")
            .withDescription("Connect to the server with this nickname").create("n"));
    options.addOption(OptionBuilder.withLongOpt("nspass").hasArg().withArgName("password")
            .withDescription("Sets the password for NickServ").create("ns"));
    options.addOption("h", "help", false, "Displays this menu");

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cli = parser.parse(options, args);
        if (cli.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("DutchBot", options);
            return;
        }
        // check for override config file
        if (cli.hasOption("c"))
            configfile = cli.getOptionValue("c");

        bot = new DutchBot(configfile);

        // Read the cli parameters
        if (cli.hasOption("pw"))
            bot.setServerPassword(cli.getOptionValue("pw"));
        if (cli.hasOption("s"))
            bot.setServerAddress(cli.getOptionValue("s"));
        if (cli.hasOption("p"))
            bot.setIrcPort(Integer.parseInt(cli.getOptionValue("p")));
        if (cli.hasOption("n"))
            bot.setBotName(cli.getOptionValue("n"));
        if (cli.hasOption("ns"))
            bot.setNickservPassword(cli.getOptionValue("ns"));

    } catch (ParseException e) {
        System.err.println("Error parsing command line vars " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DutchBot", options);
        System.exit(1);
    }

    boolean result = bot.tryConnect();

    if (result)
        bot.logMessage("Connected");
    else {
        System.out.println(" Connecting failed :O");
        System.exit(1);
    }
}

From source file:com.mindquarry.management.user.UserManagementClient.java

public static void main(String[] args) {
    log = LogFactory.getLog(UserManagementClient.class);
    log.info("Starting user management client..."); //$NON-NLS-1$

    // parse command line arguments
    CommandLine line = null;/*ww w.  j  a v a  2  s.co m*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException e) {
        // oops, something went wrong
        log.error("Parsing of command line failed."); //$NON-NLS-1$
        printUsage();
        return;
    }
    // retrieve login data
    System.out.print("Please enter your login ID: "); //$NON-NLS-1$

    String user = readString();
    user = user.trim();

    System.out.print("Please enter your new password: "); //$NON-NLS-1$

    String password = readString();
    password = password.trim();
    password = new String(DigestUtils.md5(password));
    password = new String(Base64.encodeBase64(password.getBytes()));

    // start PWD change client
    UserManagementClient manager = new UserManagementClient();
    try {
        if (line.hasOption(O_DEL)) {
            manager.deleteUser(line.getOptionValue(O_REPO), ADMIN_LOGIN, ADMIN_PWD, user, password);
        } else {
            manager.changePwd(line.getOptionValue(O_REPO), ADMIN_LOGIN, ADMIN_PWD, user, password);
        }
    } catch (Exception e) {
        log.error("Error while applying password changes.", e); //$NON-NLS-1$
    }
    log.info("User management client finished successfully."); //$NON-NLS-1$
}

From source file:de.jgoestl.massdatagenerator.MassDataGenerator.java

/**
 * @param args the command line arguments
 *///from   w w  w. j  a  v  a  2 s  .  com
public static void main(String[] args) {
    // CommandLine options
    Options options = new Options();
    options.addOption("i", "input", true, "The input file");
    options.addOption("o", "output", true, "The output file");
    options.addOption("c", "count", true, "The amount of generatet data");
    options.addOption("d", "dateFormat", true, "A custom date format");
    options.addOption("h", "help", false, "Show this");

    CommandLineParser parser = new GnuParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        Logger.getLogger(MassDataGenerator.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(1);
    }

    // Show the help
    if (cmd.hasOption("help") || !cmd.hasOption("input") || !cmd.hasOption("output")
            || !cmd.hasOption("count")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("massDataGenerator", options);

        System.out.println("\nFollowing in your input file will be replaced:");
        System.out.println("#UUID# - A random UUID");
        System.out.println("#SEQ#  - A consecutive number (starting with 1)");
        System.out.println("#DATE# - The current date (YYYY-MM-d h:m:s.S)");

        System.exit(0);
    }

    // Get values and validate
    String inputFilePath = cmd.getOptionValue("input");
    String outputPath = cmd.getOptionValue("output");
    int numberOfData = getNumberOfData(cmd);
    validate(inputFilePath, outputPath, numberOfData);
    DateFormat dateFormat = getDateFormat(cmd);

    // Read, generte and write Data
    String inputString = null;
    inputString = readInputFile(inputFilePath, inputString);
    StringBuilder output = generateOutput(numberOfData, inputString, dateFormat);
    writeOutput(outputPath, output);
}

From source file:com.bitsofproof.example.Simple.java

public static void main(String[] args) {
    Security.addProvider(new BouncyCastleProvider());

    final CommandLineParser parser = new GnuParser();
    final Options gnuOptions = new Options();
    gnuOptions.addOption("h", "help", false, "I can't help you yet");
    gnuOptions.addOption("s", "server", true, "Server URL");
    gnuOptions.addOption("u", "user", true, "User");
    gnuOptions.addOption("p", "password", true, "Password");

    System.out.println("BOP Bitcoin Server Simple Client 3.5.0 (c) 2013-2014 bits of proof zrt.");
    CommandLine cl = null;//from   w  w w .  ja  v a 2  s.  c o  m
    String url = null;
    String user = null;
    String password = null;
    try {
        cl = parser.parse(gnuOptions, args);
        url = cl.getOptionValue('s');
        user = cl.getOptionValue('u');
        password = cl.getOptionValue('p');
    } catch (org.apache.commons.cli.ParseException e) {
        e.printStackTrace();
        System.exit(1);
    }
    if (url == null || user == null || password == null) {
        System.err.println("Need -s server -u user -p password");
        System.exit(1);
    }

    BCSAPI api = getServer(url, user, password);
    try {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        long start = System.currentTimeMillis();
        api.ping(start);
        System.out.println("Server round trip " + (System.currentTimeMillis() - start) + "ms");
        api.addAlertListener(new AlertListener() {
            @Override
            public void alert(String s, int severity) {
                System.err.println("ALERT: " + s);
            }
        });
        System.out.println("Talking to " + (api.isProduction() ? "PRODUCTION" : "test") + " server");
        ConfirmationManager confirmationManager = new ConfirmationManager();
        confirmationManager.init(api, 144);
        System.out.printf("Please enter wallet name: ");
        String wallet = input.readLine();
        SimpleFileWallet w = new SimpleFileWallet(wallet + ".wallet");
        TransactionFactory am = null;
        if (!w.exists()) {
            System.out.printf("Enter passphrase: ");
            String passphrase = input.readLine();
            System.out.printf("Enter master (empty for new): ");
            String master = input.readLine();
            if (master.equals("")) {
                w.init(passphrase);
                w.unlock(passphrase);
                System.out.printf("First account: ");
                String account = input.readLine();
                am = w.createAccountManager(account);
                w.lock();
                w.persist();
            } else {
                StringTokenizer tokenizer = new StringTokenizer(master, "@");
                String key = tokenizer.nextToken();
                long since = 0;
                if (tokenizer.hasMoreElements()) {
                    since = Long.parseLong(tokenizer.nextToken()) * 1000;
                }
                w.init(passphrase, ExtendedKey.parse(key), true, since);
                w.unlock(passphrase);
                System.out.printf("First account: ");
                String account = input.readLine();
                am = w.createAccountManager(account);
                w.lock();
                w.persist();
                w.sync(api);
            }
        } else {
            w = SimpleFileWallet.read(wallet + ".wallet");
            w.sync(api);
            List<String> names = w.getAccountNames();
            System.out.println("Accounts:");
            System.out.println("---------");
            String first = null;
            for (String name : names) {
                System.out.println(name);
                if (first == null) {
                    first = name;
                }
            }
            System.out.println("---------");
            am = w.getAccountManager(first);
            System.out.println("Using account " + first);
        }
        confirmationManager.addAccount(am);
        api.registerTransactionListener(am);

        while (true) {
            printMenu();
            String answer = input.readLine();
            System.out.printf("\n");
            if (answer.equals("1")) {
                System.out.printf("The balance is: " + printBit(am.getBalance()) + "\n");
                System.out.printf("     confirmed: " + printBit(am.getConfirmed()) + "\n");
                System.out.printf("    receiveing: " + printBit(am.getReceiving()) + "\n");
                System.out.printf("        change: " + printBit(am.getChange()) + "\n");
                System.out.printf("(      sending: " + printBit(am.getSending()) + ")\n");
            } else if (answer.equals("2")) {
                for (Address a : am.getAddresses()) {
                    System.out.printf(a + "\n");
                }
            } else if (answer.equals("3")) {
                ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am;
                System.out.printf(
                        im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n");
            } else if (answer.equals("4")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am;
                System.out.printf(
                        im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n");
                w.lock();
            } else if (answer.equals("5")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                System.out.printf("Number of recipients");
                Integer nr = Integer.valueOf(input.readLine());
                Transaction spend;
                if (nr.intValue() == 1) {
                    System.out.printf("Receiver address: ");
                    String address = input.readLine();
                    System.out.printf("amount (Bit): ");
                    long amount = parseBit(input.readLine());
                    spend = am.pay(Address.fromSatoshiStyle(address), amount);
                    System.out.println("About to send " + printBit(amount) + " to " + address);
                } else {
                    List<Address> addresses = new ArrayList<>();
                    List<Long> amounts = new ArrayList<>();
                    long total = 0;
                    for (int i = 0; i < nr; ++i) {
                        System.out.printf("Receiver address: ");
                        String address = input.readLine();
                        addresses.add(Address.fromSatoshiStyle(address));
                        System.out.printf("amount (Bit): ");
                        long amount = parseBit(input.readLine());
                        amounts.add(amount);
                        total += amount;
                    }
                    spend = am.pay(addresses, amounts);
                    System.out.println("About to send " + printBit(total));
                }
                System.out.println("inputs");
                for (TransactionInput in : spend.getInputs()) {
                    System.out.println(in.getSourceHash() + " " + in.getIx());
                }
                System.out.println("outputs");
                for (TransactionOutput out : spend.getOutputs()) {
                    System.out.println(out.getOutputAddress() + " " + printBit(out.getValue()));
                }
                w.lock();
                System.out.printf("Type yes to go: ");
                if (input.readLine().equals("yes")) {
                    api.sendTransaction(spend);
                    System.out.printf("Sent transaction: " + spend.getHash());
                } else {
                    System.out.printf("Nothing happened.");
                }
            } else if (answer.equals("6")) {
                System.out.printf("Address: ");
                Set<Address> match = new HashSet<Address>();
                match.add(Address.fromSatoshiStyle(input.readLine()));
                api.scanTransactionsForAddresses(match, 0, new TransactionListener() {
                    @Override
                    public boolean process(Transaction t) {
                        System.out.printf("Found transaction: " + t.getHash() + "\n");
                        return true;
                    }
                });
            } else if (answer.equals("7")) {
                System.out.printf("Public key: ");
                ExtendedKey ek = ExtendedKey.parse(input.readLine());
                api.scanTransactions(ek, 0, 10, 0, new TransactionListener() {
                    @Override
                    public boolean process(Transaction t) {
                        System.out.printf("Found transaction: " + t.getHash() + "\n");
                        return true;
                    }
                });
            } else if (answer.equals("a")) {
                System.out.printf("Enter account name: ");
                String account = input.readLine();
                am = w.getAccountManager(account);
                api.registerTransactionListener(am);
                confirmationManager.addAccount(am);
            } else if (answer.equals("c")) {
                System.out.printf("Enter account name: ");
                String account = input.readLine();
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                am = w.createAccountManager(account);
                System.out.println("using account: " + account);
                w.lock();
                w.persist();
                api.registerTransactionListener(am);
                confirmationManager.addAccount(am);
            } else if (answer.equals("m")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                System.out.println(w.getMaster().serialize(api.isProduction()));
                System.out.println(w.getMaster().getReadOnly().serialize(true));
                w.lock();
            } else if (answer.equals("s")) {
                System.out.printf("Enter private key: ");
                String key = input.readLine();
                ECKeyPair k = ECKeyPair.parseWIF(key);
                KeyListAccountManager alm = new KeyListAccountManager();
                alm.addKey(k);
                alm.syncHistory(api);
                Address a = am.getNextReceiverAddress();
                Transaction t = alm.pay(a, alm.getBalance(), PaymentOptions.receiverPaysFee);
                System.out.println("About to sweep " + printBit(alm.getBalance()) + " to " + a);
                System.out.println("inputs");
                for (TransactionInput in : t.getInputs()) {
                    System.out.println(in.getSourceHash() + " " + in.getIx());
                }
                System.out.println("outputs");
                for (TransactionOutput out : t.getOutputs()) {
                    System.out.println(out.getOutputAddress() + " " + printBit(out.getValue()));
                }
                System.out.printf("Type yes to go: ");
                if (input.readLine().equals("yes")) {
                    api.sendTransaction(t);
                    System.out.printf("Sent transaction: " + t.getHash());
                } else {
                    System.out.printf("Nothing happened.");
                }
            } else {
                System.exit(0);
            }
        }
    } catch (Exception e) {
        System.err.println("Something went wrong");
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:de.mpi_bremen.mgg.FastaValidatorUi.java

/**
 * @param args the command line arguments
 *//*from w  w  w  .  j a v a  2s. co m*/
public static void main(String[] args) {
    // create Options object
    Options options = new Options();
    // add verbose option
    options.addOption("v", "verbose", false, "verbose mode");
    // add inputfile option
    options.addOption("f", "file", true, "FASTA-formatted input file");
    // add help option
    options.addOption("h", "help", false, "print this help message");
    // add sequencetype option
    options.addOption("t", "seqtype", true, "sequence type (allowed values: all|dna|rna|protein)");
    // add gui-mode option
    options.addOption("nogui", false, "start in non-interactive mode");

    //create the cmdline-parser   
    GnuParser parser = new GnuParser();

    // parse the command line arguments
    try {
        //get cmdline arguments
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FastaValidatorUi", options, true);
        System.exit(1); //indicate error to external environment
    }

    if (cmdline.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FastaValidatorUi", options, true);
        System.exit(0); //indicate no errors to external environment
    }

    //which mode? (gui or cmdline)
    if (cmdline.hasOption("nogui")) { //cmdline-mode

        //create new cmdline-gui
        FvCmdline cmdlinegui = new FvCmdline();

        //set verbosity
        cmdlinegui.setVerbose(cmdline.hasOption("v"));

        //handle input file
        if (cmdline.hasOption("f")) {
            cmdlinegui.setInput(cmdline.getOptionValue("f"));
        }

        //set sequencetype
        if (cmdline.hasOption("t")) {
            cmdlinegui.setSequencetype(getSeqtype(cmdline.getOptionValue("t")));
        } else {
            cmdlinegui.setSequencetype(FastaValidator.Sequencetype.ALL);
        }

        //trigger validation and exit with exitcode
        int exitcode = cmdlinegui.validate().getValue();
        System.exit(exitcode);

    } else { //gui-mode
        //start gui in its own thread
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                FvGui w = new FvGui();
            }
        });
    }
}

From source file:cnxchecker.Client.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("H", "host", true, "Remote IP address");
    options.addOption("p", "port", true, "Remote TCP port");
    options.addOption("s", "size", true, "Packet size in bytes (1 KiB)");
    options.addOption("f", "freq", true, "Packets per seconds  (1 Hz)");
    options.addOption("w", "workers", true, "Number of Workers (1)");
    options.addOption("d", "duration", true, "Duration of the test in seconds (60 s)");
    options.addOption("h", "help", false, "Print help");
    CommandLineParser parser = new GnuParser();
    try {/*  w ww .  j  a  v  a  2 s .  co  m*/
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            HelpFormatter hf = new HelpFormatter();
            hf.printHelp("client", options);
            System.exit(0);
        }

        // host
        InetAddress ia = null;
        if (cmd.hasOption("H")) {
            String host = cmd.getOptionValue("H");

            try {
                ia = InetAddress.getByName(host);
            } catch (UnknownHostException e) {
                printAndExit("Unknown host: " + host);
            }
        } else {
            printAndExit("Host option is mandatory");
        }

        // port
        int port = 0;
        if (cmd.hasOption("p")) {
            try {
                port = Integer.parseInt(cmd.getOptionValue("p"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid port number " + cmd.getOptionValue("p"));
            }

            if (port < 0 || port > 65535) {
                printAndExit("Invalid port number " + port);
            }
        }

        // size
        int size = 1024;
        if (cmd.hasOption("s")) {
            try {
                size = Integer.parseInt(cmd.getOptionValue("s"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid packet size " + cmd.getOptionValue("s"));
            }

            if (size < 0) {
                printAndExit("Invalid packet size: " + port);
            }
        }

        // freq
        double freq = 1;
        if (cmd.hasOption("f")) {
            try {
                freq = Double.parseDouble(cmd.getOptionValue("f"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid frequency: " + cmd.getOptionValue("f"));
            }

            if (freq <= 0) {
                printAndExit("Invalid frequency: " + freq);
            }
        }

        // workers
        int workers = 1;
        if (cmd.hasOption("w")) {
            try {
                workers = Integer.parseInt(cmd.getOptionValue("w"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid number of workers: " + cmd.getOptionValue("w"));
            }

            if (workers < 0) {
                printAndExit("Invalid number of workers: " + workers);
            }
        }

        // duration
        int duration = 60000;
        if (cmd.hasOption("d")) {
            try {
                duration = Integer.parseInt(cmd.getOptionValue("d")) * 1000;
            } catch (NumberFormatException e) {
                printAndExit("Invalid duration: " + cmd.getOptionValue("d"));
            }

            if (duration < 0) {
                printAndExit("Invalid duration: " + duration);
            }
        }

        Client client = new Client(ia, port, size, freq, workers, duration);
        client.doit();
    } catch (ParseException e) {
        printAndExit("Failed to parse options: " + e.getMessage());
    }

    System.exit(0);
}

From source file:io.s4.MainApp.java

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

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(/*from   ww  w.  j a  va  2 s  .  co m*/
            OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a"));

    options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d"));

    options.addOption(OptionBuilder.withArgName("seedtime").hasArg()
            .withDescription("event clock initialization time").create("s"));

    options.addOption(
            OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e"));

    options.addOption(
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;
    String clockType = "wall";

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    if (commandLine.hasOption("a")) {
        appsHome = commandLine.getOptionValue("a");
    }

    if (commandLine.hasOption("d")) {
        clockType = commandLine.getOptionValue("d");
    }

    if (commandLine.hasOption("e")) {
        extsHome = commandLine.getOptionValue("e");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    long seedTime = 0;
    if (commandLine.hasOption("s")) {
        seedTime = Long.parseLong(commandLine.getOptionValue("s"));
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    File appsHomeFile = new File(appsHome);
    if (!appsHomeFile.isDirectory()) {
        System.err.println("Bad applications home: " + appsHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    List loArgs = commandLine.getArgList();

    if (loArgs.size() < 1) {
        // System.err.println("No bean configuration file specified");
        // System.exit(1);
    }

    // String s4ConfigXml = (String) loArgs.get(0);
    // System.out.println("s4ConfigXml is " + s4ConfigXml);

    ClassPathResource propResource = new ClassPathResource("s4-core.properties");
    Properties prop = new Properties();
    if (propResource.exists()) {
        prop.load(propResource.getInputStream());
    } else {
        System.err.println("Unable to find s4-core.properties. It must be available in classpath");
        System.exit(1);
    }

    ApplicationContext coreContext = null;
    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = "";
    List<String> coreConfigUrls = new ArrayList<String>();
    File configFile = null;

    // load clock configuration
    configPath = configBase + File.separatorChar + clockType + "-clock.xml";
    coreConfigUrls.add(configPath);

    // load core config xml
    configPath = configBase + File.separatorChar + "s4-core-conf.xml";
    configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("S4 core config file %s does not exist\n", configPath);
        System.exit(1);
    }

    coreConfigUrls.add(configPath);
    String[] coreConfigFiles = new String[coreConfigUrls.size()];
    coreConfigUrls.toArray(coreConfigFiles);

    String[] coreConfigFileUrls = new String[coreConfigFiles.length];
    for (int i = 0; i < coreConfigFiles.length; i++) {
        coreConfigFileUrls[i] = "file:" + coreConfigFiles[i];
    }

    coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext);
    ApplicationContext context = coreContext;

    Clock s4Clock = (Clock) context.getBean("clock");
    if (s4Clock instanceof EventClock && seedTime > 0) {
        EventClock s4EventClock = (EventClock) s4Clock;
        s4EventClock.updateTime(seedTime);
        System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime());
    }

    PEContainer peContainer = (PEContainer) context.getBean("peContainer");

    Watcher w = (Watcher) context.getBean("watcher");
    w.setConfigFilename(configPath);

    // load extension modules
    String[] configFileNames = getModuleConfigFiles(extsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
    }

    // load application modules
    configFileNames = getModuleConfigFiles(appsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
        // attach any beans that implement ProcessingElement to the PE
        // Container
        String[] processingElementBeanNames = context.getBeanNamesForType(ProcessingElement.class);
        for (String processingElementBeanName : processingElementBeanNames) {
            Object bean = context.getBean(processingElementBeanName);
            try {
                Method getS4ClockMethod = bean.getClass().getMethod("getS4Clock");

                if (getS4ClockMethod.getReturnType().equals(Clock.class)) {
                    if (getS4ClockMethod.invoke(bean) == null) {
                        Method setS4ClockMethod = bean.getClass().getMethod("setS4Clock", Clock.class);
                        setS4ClockMethod.invoke(bean, coreContext.getBean("clock"));
                    }
                }
            } catch (NoSuchMethodException mnfe) {
                // acceptable
            }
            System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id "
                    + ((ProcessingElement) bean).getId());
            peContainer.addProcessor((ProcessingElement) bean, processingElementBeanName);
        }
    }
}