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:eu.interedition.collatex.cli.Engine.java

public static void main(String... args) {
    final Engine engine = new Engine();
    try {//from   w w  w. j  av a  2 s .  c  o  m
        final CommandLine commandLine = new GnuParser().parse(OPTIONS, args);
        if (commandLine.hasOption("h")) {
            engine.help();
            return;
        }
        engine.configure(commandLine).read().collate().write();
    } catch (ParseException e) {
        engine.error("Error while parsing command line arguments", e);
        engine.log("\n").help();
    } catch (IllegalArgumentException e) {
        engine.error("Illegal argument", e);
    } catch (IOException e) {
        engine.error("I/O error", e);
    } catch (SAXException e) {
        engine.error("XML error", e);
    } catch (XPathExpressionException e) {
        engine.error("XPath error", e);
    } catch (ScriptException | PluginScript.PluginScriptExecutionException e) {
        engine.error("Script error", e);
    } finally {
        try {
            Closeables.close(engine, false);
        } catch (IOException e) {
        }
    }
}

From source file:com.zimbra.perf.chart.ChartUtil.java

public static void main(String[] args) throws Exception {
    CommandLineParser clParser = new GnuParser();
    Options opts = getOptions();/*from www  .  j av a  2 s . com*/
    try {
        CommandLine cl = clParser.parse(opts, args);

        if (cl.hasOption('h'))
            usage(opts);
        if (!cl.hasOption('s') && !cl.hasOption('d'))
            usage(opts, "-s and -d options are required");
        if (!cl.hasOption('s'))
            usage(opts, "Missing required -s option");

        if (!cl.hasOption('d'))
            usage(opts, "Missing required -d option");

        String[] confs = cl.getOptionValues(OPT_CONF);
        if (confs == null || confs.length == 0)
            usage(opts, "Missing --" + OPT_CONF + " option");
        File[] confFiles = new File[confs.length];
        for (int i = 0; i < confs.length; i++) {
            File conf = new File(confs[i]);
            if (!conf.exists()) {
                System.err.printf("Configuration file %s does not exist\n", conf.getAbsolutePath());
                System.exit(1);
            }
            confFiles[i] = conf;
        }

        String[] srcDirStrs = cl.getOptionValues(OPT_SRCDIR);
        if (srcDirStrs == null || srcDirStrs.length == 0)
            usage(opts, "Missing --" + OPT_SRCDIR + " option");
        List<File> srcDirsList = new ArrayList<File>(srcDirStrs.length);
        for (int i = 0; i < srcDirStrs.length; i++) {
            File srcDir = new File(srcDirStrs[i]);
            if (srcDir.exists())
                srcDirsList.add(srcDir);
            else
                System.err.printf("Source directory %s does not exist\n", srcDir.getAbsolutePath());
        }
        if (srcDirsList.size() < 1)
            usage(opts, "No valid source directory found");
        File[] srcDirs = new File[srcDirsList.size()];
        srcDirsList.toArray(srcDirs);

        String destDirStr = cl.getOptionValue(OPT_DESTDIR);
        if (destDirStr == null)
            usage(opts, "Missing --" + OPT_DESTDIR + " option");
        File destDir = new File(destDirStr);
        if (!destDir.exists()) {
            boolean created = destDir.mkdirs();
            if (!created) {
                System.err.printf("Unable to create destination directory %s\n", destDir.getAbsolutePath());
                System.exit(1);
            }
        }
        if (!destDir.canWrite()) {
            System.err.printf("Destination directory %s is not writable\n", destDir.getAbsolutePath());
            System.exit(1);
        }

        String title = cl.getOptionValue(OPT_TITLE);
        if (title == null)
            title = srcDirs[0].getAbsoluteFile().getName();

        Date startAt = parseTimestampOption(cl, opts, OPT_START_AT);
        Date endAt = parseTimestampOption(cl, opts, OPT_END_AT);
        Date aggStartAt = parseTimestampOption(cl, opts, OPT_AGGREGATE_START_AT);
        Date aggEndAt = parseTimestampOption(cl, opts, OPT_AGGREGATE_END_AT);

        boolean noSummary = cl.hasOption('n');
        ChartUtil app = new ChartUtil(confFiles, srcDirs, destDir, title, startAt, endAt, aggStartAt, aggEndAt,
                noSummary);
        app.doit();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println();
        usage(opts);
    }
}

From source file:io.s4.client.Adapter.java

@SuppressWarnings("static-access")
public static void main(String args[]) throws IOException, InterruptedException {

    Options options = new Options();

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

    options.addOption(/*from  ww w.j av a  2  s. c  o  m*/
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

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

    options.addOption(OptionBuilder.withArgName("userconfig").hasArg()
            .withDescription("user-defined legacy data adapter configuration file").create("d"));

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

    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");
    }

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

    String userConfigFilename = null;
    if (commandLine.hasOption("d")) {
        userConfigFilename = commandLine.getOptionValue("d");
    }

    File userConfigFile = new File(userConfigFilename);
    if (!userConfigFile.isFile()) {
        System.err.println("Bad user configuration file: " + userConfigFilename);
        System.exit(1);
    }

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

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

    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = configBase + File.separatorChar + "client-adapter-conf.xml";
    File configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("adapter config file %s does not exist\n", configPath);
        System.exit(1);
    }

    // load adapter config xml
    ApplicationContext coreContext;
    coreContext = new FileSystemXmlApplicationContext("file:" + configPath);
    ApplicationContext context = coreContext;

    Adapter adapter = (Adapter) context.getBean("client_adapter");

    ApplicationContext appContext = new FileSystemXmlApplicationContext(
            new String[] { "file:" + userConfigFilename }, context);

    Map<?, ?> inputStubBeanMap = appContext.getBeansOfType(InputStub.class);
    Map<?, ?> outputStubBeanMap = appContext.getBeansOfType(OutputStub.class);

    if (inputStubBeanMap.size() == 0 && outputStubBeanMap.size() == 0) {
        System.err.println("No user-defined input/output stub beans");
        System.exit(1);
    }

    ArrayList<InputStub> inputStubs = new ArrayList<InputStub>(inputStubBeanMap.size());
    ArrayList<OutputStub> outputStubs = new ArrayList<OutputStub>(outputStubBeanMap.size());

    // add all input stubs
    for (Map.Entry<?, ?> e : inputStubBeanMap.entrySet()) {
        String beanName = (String) e.getKey();
        System.out.println("Adding InputStub " + beanName);
        inputStubs.add((InputStub) e.getValue());
    }

    // add all output stubs
    for (Map.Entry<?, ?> e : outputStubBeanMap.entrySet()) {
        String beanName = (String) e.getKey();
        System.out.println("Adding OutputStub " + beanName);
        outputStubs.add((OutputStub) e.getValue());
    }

    adapter.setInputStubs(inputStubs);
    adapter.setOutputStubs(outputStubs);

}

From source file:imageviewer.util.PasswordGenerator.java

public static void main(String[] args) {

    Option help = new Option("help", "Print this message");
    Option file = OptionBuilder.withArgName("file").hasArg().withDescription("Password filename")
            .create("file");
    Option addUser = OptionBuilder.withArgName("add").hasArg().withDescription("Add user profile")
            .create("add");
    Option removeUser = OptionBuilder.withArgName("remove").hasArg().withDescription("Remove user profile")
            .create("remove");
    Option updateUser = OptionBuilder.withArgName("update").hasArg().withValueSeparator()
            .withDescription("Update user profile").create("update");

    file.setRequired(true);//from ww w .j  a v  a 2 s  .c  o m
    OptionGroup og = new OptionGroup();
    og.addOption(addUser);
    og.addOption(removeUser);
    og.addOption(updateUser);
    og.setRequired(true);

    Options o = new Options();
    o.addOption(help);
    o.addOption(file);
    o.addOptionGroup(og);

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(o, args);
        PasswordGenerator pg = new PasswordGenerator(line);
        pg.execute();
    } catch (UnrecognizedOptionException uoe) {
        System.err.println("Unknown argument: " + uoe.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("PasswordGenerator", o);
        System.exit(1);
    } catch (MissingOptionException moe) {
        System.err.println("Missing argument: " + moe.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("PasswordGenerator", o);
        System.exit(1);
    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

From source file:ch.psi.zmq.receiver.FileReceiver.java

public static void main(String[] args) {

    int port = 8888;
    String source = "localhost";
    Options options = new Options();
    options.addOption("h", false, "Help");

    @SuppressWarnings("static-access")
    Option optionP = OptionBuilder.withArgName("port").hasArg()
            .withDescription("Source port (default: " + port + ")").create("p");
    options.addOption(optionP);//w w  w  .  j  a v a  2s  . c  o  m

    @SuppressWarnings("static-access")
    Option optionS = OptionBuilder.withArgName("source").hasArg().isRequired().withDescription(
            "Source address of the ZMQ stream (default port " + port + " : use -p to set the port if needed)")
            .create("s");
    options.addOption(optionS);

    @SuppressWarnings("static-access")
    Option optionD = OptionBuilder.withArgName("path").hasArg().isRequired()
            .withDescription("tpath for storing files with relative destination paths").create("d");
    options.addOption(optionD);

    GnuParser parser = new GnuParser();
    CommandLine line;
    String path = ".";
    try {
        line = parser.parse(options, args);
        if (line.hasOption(optionP.getOpt())) {
            port = Integer.parseInt(line.getOptionValue(optionP.getOpt()));
        }
        if (line.hasOption("h")) {
            HelpFormatter f = new HelpFormatter();
            f.printHelp("receiver", options);
            return;
        }

        source = line.getOptionValue(optionS.getOpt());
        path = line.getOptionValue(optionD.getOpt());

    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter f = new HelpFormatter();
        f.printHelp("receiver", options);
        System.exit(-1);
    }

    final FileReceiver r = new FileReceiver(source, port, path);
    r.receive();

    // Control+C
    Signal.handle(new Signal("INT"), new SignalHandler() {
        int count = 0;

        public void handle(Signal sig) {
            if (count < 1) {
                count++;
                r.terminate();
            } else {
                System.exit(-1);
            }

        }
    });
}

From source file:com.zimbra.common.localconfig.LocalConfigUpgrade.java

public static void main(String[] args) throws ServiceException {
    CliUtil.toolSetup();/*from  www.  j a v a  2  s.  c  om*/

    CommandLine cl = null;
    try {
        CommandLineParser parser = new GnuParser();
        Options options = getAllOptions();
        cl = parser.parse(options, args);
        if (cl == null)
            throw new ParseException("");
    } catch (ParseException pe) {
        usage(pe.getMessage());
    }

    if (cl.hasOption(O_HELP)) {
        usage(null);
    }

    if (!cl.hasOption(O_BUG)) {
        usage("no bug specified");
    }

    if (!cl.hasOption(O_TAG)) {
        usage("no backup suffix tag specified");
    }

    LocalConfig lc = null;
    try {
        lc = new LocalConfig(cl.getOptionValue("c"));
        lc.backup(cl.getOptionValue("t"));
    } catch (DocumentException de) {
        ZimbraLog.misc.error("failed reading config file", de);
        System.exit(1);
    } catch (ConfigException ce) {
        ZimbraLog.misc.error("failed reading config file", ce);
        System.exit(2);
    } catch (IOException ioe) {
        ZimbraLog.misc.error("failed to backup config file", ioe);
        System.exit(3);
    }

    String[] bugs = cl.getOptionValues(O_BUG);
    for (String bug : bugs) {
        if (!sUpgrades.containsKey(bug)) {
            ZimbraLog.misc.warn("local config upgrade can't handle bug " + bug);
            continue;
        }

        LocalConfigUpgrade lcu = sUpgrades.get(bug);
        System.out.println("== Running local config upgrade for bug " + lcu.mBug + " (" + lcu.mShortName + ")");
        try {
            lcu.upgrade(lc);
            System.out
                    .println("== Done local config upgrade for bug " + lcu.mBug + " (" + lcu.mShortName + ")");
        } catch (ConfigException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        lc.save();
    } catch (IOException ioe) {
        ZimbraLog.misc.error("failed writing config file", ioe);
        System.exit(1);
    } catch (ConfigException ce) {
        ZimbraLog.misc.error("failed writing config file", ce);
        System.exit(1);
    }
}

From source file:com.zimbra.cs.service.util.ItemDataFile.java

public static void main(String[] args) {
    String cset = null;//from w w w  .j  a  v a2 s.c  om
    Options opts = new Options();
    CommandLineParser parser = new GnuParser();

    opts.addOption("a", "assemble", false, "assemble backup");
    opts.addOption("c", "charset", true, "path charset");
    opts.addOption("e", "extract", false, "extract backup");
    opts.addOption("h", "help", false, "help");
    opts.addOption("l", "list", false, "list backup");
    opts.addOption("n", "nometa", false, "ignore metadata");
    opts.addOption("p", "path", true, "extracted backup path");
    opts.addOption("t", "types", true, "item types");
    ZimbraLog.toolSetupLog4j("ERROR", null);
    try {
        CommandLine cl = parser.parse(opts, args);
        String path = ".";
        String file = null;
        boolean meta = true;
        Set<MailItem.Type> types = null;

        if (cl.hasOption('c')) {
            cset = cl.getOptionValue('c');
        }
        if (cl.hasOption('n')) {
            meta = false;
        }
        if (cl.hasOption('p')) {
            path = cl.getOptionValue('p');
        }
        if (cl.hasOption('t')) {
            try {
                types = MailItem.Type.setOf(cl.getOptionValue('t'));
            } catch (IllegalArgumentException e) {
                throw MailServiceException.INVALID_TYPE(e.getMessage());
            }
        }
        if (cl.hasOption('h') || cl.getArgs().length != 1) {
            usage(opts);
        }
        file = cl.getArgs()[0];
        if (cl.hasOption('a')) {
            create(path, types, cset, new FileOutputStream(file));
        } else if (cl.hasOption('e')) {
            extract(new FileInputStream(file), meta, types, cset, path);
        } else if (cl.hasOption('l')) {
            list(file.equals("-") ? System.in : new FileInputStream(file), types, cset, System.out);
        } else {
            usage(opts);
        }
    } catch (Exception e) {
        if (e instanceof UnrecognizedOptionException)
            usage(opts);
        else
            e.printStackTrace(System.out);
        System.exit(1);
    }
}

From source file:it.crs4.features.ImageToAvro.java

private static CommandLine parseCmdLine(Options opts, String[] args) throws ParseException {
    opts.addOption("o", "outdir", true, "write avro files to this dir");
    CommandLineParser parser = new GnuParser();
    return parser.parse(opts, args);
}

From source file:com.google.play.developerapi.samples.ApplicationConfig.java

public static ApplicationConfig parseArgs(String[] args) {
    Options options = new Options();

    try {// w ww  .j a va 2 s . c  om
        CommandLineParser parser = new GnuParser();

        Option appId = new Option("appId", "Application id (package name)");
        appId.setArgs(1);
        appId.setRequired(true);
        options.addOption(appId);

        Option secrets = new Option("secrets", "Client secrets path");
        secrets.setArgs(1);
        secrets.setRequired(true);
        options.addOption(secrets);

        Option account = new Option("account", "Service account email");
        account.setArgs(1);
        account.setRequired(false);
        options.addOption(account);

        Option appName = new Option("appName", "Application name");
        appName.setArgs(1);
        appName.setRequired(false);
        options.addOption(appName);

        Option apkFilePath = new Option("apkFilePath", "Apk file path");
        apkFilePath.setArgs(1);
        apkFilePath.setRequired(false);
        options.addOption(apkFilePath);

        return new ApplicationConfig(parser.parse(options, args));
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("android-publisher-api", options);
        return null;
    }
}

From source file:com.zimbra.cs.util.GalSyncAccountUtil.java

public static void main(String[] args) throws Exception {
    if (args.length < 1)
        usage();//from   w  w  w.  ja  va2 s  .  c  o  m
    CliUtil.toolSetup();
    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption("a", "account", true, "gal sync account name");
    options.addOption("i", "id", true, "gal sync account id");
    options.addOption("n", "name", true, "datasource name");
    options.addOption("d", "did", true, "datasource id");
    options.addOption("x", "domain", true, "for domain gal sync account");
    options.addOption("f", "folder", true, "folder id");
    options.addOption("p", "polling", true, "polling interval");
    options.addOption("t", "type", true, "gal type");
    options.addOption("s", "server", true, "mailhost");
    options.addOption("h", "help", true, "help");
    CommandLine cl = null;
    boolean err = false;
    try {
        cl = parser.parse(options, args, false);
    } catch (ParseException pe) {
        System.out.println("error: " + pe.getMessage());
        err = true;
    }

    GalSyncAccountUtil cli = new GalSyncAccountUtil();
    if (err || cl.hasOption('h')) {
        usage();
    }
    if (cl.hasOption('i'))
        cli.setAccountId(cl.getOptionValue('i'));
    if (cl.hasOption('a'))
        cli.setAccountName(cl.getOptionValue('a'));
    if (cl.hasOption('n'))
        cli.setDataSourceName(cl.getOptionValue('n'));
    if (cl.hasOption('d'))
        cli.setDataSourceId(cl.getOptionValue('d'));
    setup();
    int cmd = lookupCmd(args[0]);
    try {
        switch (cmd) {
        case TRICKLE_SYNC:
            cli.syncGalAccount();
            break;
        case FULL_SYNC:
            cli.setFullSync();
            cli.syncGalAccount();
            break;
        case FORCE_SYNC:
            cli.setForceSync();
            cli.syncGalAccount();
            break;
        case CREATE_ACCOUNT:
            String acctName = cl.getOptionValue('a');
            String dsName = cl.getOptionValue('n');
            String domain = cl.getOptionValue('x');
            String type = cl.getOptionValue('t');
            String folderName = cl.getOptionValue('f');
            String pollingInterval = cl.getOptionValue('p');
            String mailHost = cl.getOptionValue('s');
            if (acctName == null || mailHost == null || dsName == null || type == null
                    || type.compareTo("zimbra") != 0 && type.compareTo("ldap") != 0)
                usage();
            for (Element account : cli
                    .createGalSyncAccount(acctName, dsName, domain, type, folderName, pollingInterval, mailHost)
                    .listElements(AdminConstants.A_ACCOUNT))
                System.out.println(account.getAttribute(AdminConstants.A_NAME) + "\t"
                        + account.getAttribute(AdminConstants.A_ID));
            break;
        case ADD_DATASOURCE:
            acctName = cl.getOptionValue('a');
            dsName = cl.getOptionValue('n');
            domain = cl.getOptionValue('x');
            type = cl.getOptionValue('t');
            folderName = cl.getOptionValue('f');
            pollingInterval = cl.getOptionValue('p');
            if (acctName == null || dsName == null || type == null
                    || type.compareTo("zimbra") != 0 && type.compareTo("ldap") != 0)
                usage();
            for (Element account : cli
                    .addGalSyncDataSource(acctName, dsName, domain, type, folderName, pollingInterval)
                    .listElements(AdminConstants.A_ACCOUNT))
                System.out.println(account.getAttribute(AdminConstants.A_NAME) + "\t"
                        + account.getAttribute(AdminConstants.A_ID));
            break;
        case DELETE_ACCOUNT:
            String name = cl.getOptionValue('a');
            String id = cl.getOptionValue('i');
            if (name == null && id == null)
                usage();
            cli.deleteGalSyncAccount(name, id);
            break;
        default:
            usage();
        }
    } catch (ServiceException se) {
        System.out.println("Error: " + se.getMessage());
    }
}