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:android.example.hlsmerge.crypto.Main.java

public static void main(String[] args) {
    CommandLine commandLine = parseCommandLine(args);
    String[] commandLineArgs = commandLine.getArgs();

    try {/*w  ww. j a v  a 2s . c o  m*/
        String playlistUrl = commandLineArgs[0];
        String outFile = null;
        String key = null;

        if (commandLine.hasOption(OPT_OUT_FILE)) {
            outFile = commandLine.getOptionValue(OPT_OUT_FILE);

            File file = new File(outFile);

            if (file.exists()) {
                if (!commandLine.hasOption(OPT_OVERWRITE)) {
                    System.out.printf("File '%s' already exists. Overwrite? [y/N] ", outFile);

                    int ch = System.in.read();

                    if (!(ch == 'y' || ch == 'Y')) {
                        System.exit(0);
                    }
                }

                file.delete();
            }
        }

        if (commandLine.hasOption(OPT_KEY))
            key = commandLine.getOptionValue(OPT_KEY);

        PlaylistDownloader downloader = new PlaylistDownloader(playlistUrl, null);

        if (commandLine.hasOption(OPT_SILENT)) {
            System.setOut(new PrintStream(new OutputStream() {
                public void close() {
                }

                public void flush() {
                }

                public void write(byte[] b) {
                }

                public void write(byte[] b, int off, int len) {
                }

                public void write(int b) {
                }
            }));
        }

        downloader.download(outFile, key);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.hurence.logisland.plugin.PluginManager.java

public static void main(String... args) throws Exception {
    System.out.println(BannerLoader.loadBanner());

    String logislandHome = new File(
            new File(PluginManager.class.getProtectionDomain().getCodeSource().getLocation().getPath())
                    .getParent()).getParent();
    System.out.println("Using Logisland home: " + logislandHome);
    Options options = new Options();
    OptionGroup mainGroup = new OptionGroup()
            .addOption(OptionBuilder.withDescription(
                    "Install a component. It can be either a logisland plugin or a kafka connect module.")
                    .withArgName("artifact").hasArgs(1).withLongOpt("install").create("i"))
            .addOption(OptionBuilder.withDescription(
                    "Removes a component. It can be either a logisland plugin or a kafka connect module.")
                    .withArgName("artifact").hasArgs(1).withLongOpt("remove").create("r"))
            .addOption(OptionBuilder.withDescription("List installed components.").withLongOpt("list")
                    .create("l"));

    mainGroup.setRequired(true);//w ww . jav  a 2 s  . co m
    options.addOptionGroup(mainGroup);
    options.addOption(OptionBuilder.withDescription("Print this help.").withLongOpt("help").create("h"));

    try {
        CommandLine commandLine = new PosixParser().parse(options, args);
        System.out.println(commandLine.getArgList());
        if (commandLine.hasOption("l")) {
            listPlugins();
        } else if (commandLine.hasOption("i")) {
            installPlugin(commandLine.getOptionValue("i"), logislandHome);

        } else if (commandLine.hasOption("r")) {
            removePlugin(commandLine.getOptionValue("r"));
        } else {
            printUsage(options);
        }

    } catch (ParseException e) {
        if (!options.hasOption("h")) {
            System.err.println(e.getMessage());
            System.out.println();
        }
        printUsage(options);

    }
}

From source file:net.chrislongo.hls.Main.java

public static void main(String[] args) {
    CommandLine commandLine = parseCommandLine(args);
    String[] commandLineArgs = commandLine.getArgs();

    try {//ww  w  .j a  va  2 s  . c o  m
        String playlistUrl = commandLineArgs[0];
        String outFile = null;
        String key = null;

        if (commandLine.hasOption(OPT_OUT_FILE)) {
            outFile = commandLine.getOptionValue(OPT_OUT_FILE);

            File file = new File(outFile);

            if (file.exists()) {
                if (!commandLine.hasOption(OPT_OVERWRITE)) {
                    System.out.printf("File '%s' already exists. Overwrite? [y/N] ", outFile);

                    int ch = System.in.read();

                    if (!(ch == 'y' || ch == 'Y')) {
                        System.exit(0);
                    }
                }

                file.delete();
            }
        }

        if (commandLine.hasOption(OPT_KEY))
            key = commandLine.getOptionValue(OPT_KEY);

        PlaylistDownloader downloader = new PlaylistDownloader(playlistUrl);

        if (commandLine.hasOption(OPT_SILENT)) {
            System.setOut(new PrintStream(new OutputStream() {
                public void close() {
                }

                public void flush() {
                }

                public void write(byte[] b) {
                }

                public void write(byte[] b, int off, int len) {
                }

                public void write(int b) {
                }
            }));
        }

        downloader.download(outFile, key);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.browseengine.bobo.index.MakeBobo.java

/**
 * @param args//w w  w  . j a  v a 2s . c o m
 */
public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

    Option help = new Option("help", false, "print this message");

    OptionBuilder.withArgName("path");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("data source - required");
    Option src = OptionBuilder.create("source");
    src.setRequired(true);

    OptionBuilder.withArgName("path");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("index to create - required");
    Option index = OptionBuilder.create("index");
    index.setRequired(true);

    OptionBuilder.withArgName("file");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("field configuration - optional");
    Option conf = OptionBuilder.create("conf");

    OptionBuilder.withArgName("class");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("class name of the data digester - default: xml digester");
    Option digesterOpt = OptionBuilder.create("digester");

    OptionBuilder.withArgName("name");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("character set name - default: UTF-8");
    Option charset = OptionBuilder.create("charset");

    OptionBuilder.withArgName("maxdocs");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("maximum number of documents - default: 100");
    Option maxdocs = OptionBuilder.create("maxdocs");

    Options options = new Options();
    options.addOption(help);
    options.addOption(conf);
    options.addOption(index);
    options.addOption(src);
    options.addOption(charset);
    options.addOption(digesterOpt);
    options.addOption(maxdocs);

    //       create the parser

    CommandLineParser parser = new BasicParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String output = line.getOptionValue("index");
        File data = new File(line.getOptionValue("source"));

        Class digesterClass;
        if (line.hasOption("digester"))
            digesterClass = Class.forName(line.getOptionValue("digester"));
        else
            throw new RuntimeException("digester not specified");

        Charset chset;
        if (line.hasOption("charset")) {
            chset = Charset.forName(line.getOptionValue("charset"));
        } else {
            chset = Charset.forName("UTF-8");
        }

        int maxDocs;
        try {
            maxDocs = Integer.parseInt(line.getOptionValue("maxdocs"));
        } catch (Exception e) {
            maxDocs = 100;
        }

        FileDigester digester;
        try {
            Constructor constructor = digesterClass.getConstructor(new Class[] { File.class });
            digester = (FileDigester) constructor.newInstance(new Object[] { data });
            digester.setCharset(chset);
            digester.setMaxDocs(maxDocs);
        } catch (Exception e) {
            throw new RuntimeException("Invalid digester class.", e);
        }

        BoboIndexer indexer = new BoboIndexer(digester, FSDirectory.open(new File(output)));
        indexer.index();
    } catch (ParseException exp) {
        exp.printStackTrace();
        usage(options);
    } catch (ClassNotFoundException e) {
        System.out.println("Invalid digester class.");
        usage(options);
    }
}

From source file:com.linkedin.databus2.client.util.DbusClientClusterUtil.java

/**
 * @param args/*  w ww .  j  a  va2 s.c  o m*/
 * DbusClientClusterUtil -s <serverList> -n <namespace> -g <group> -d <dir>     members
 *                                                     leader 
 *                                                    keys 
 *                                                    readSCN <key> 
 *                                                    writeSCN <key> SCN [OFFSET]
 *                                                 remove <key>
 *                                                 readLastTS
 *                                                 writeLastTS TIMESTAMP            
 */
public static void main(String[] args) {
    try {
        GnuParser cmdLineParser = new GnuParser();
        Options options = new Options();
        options.addOption("n", true, "Zookeeper namespace  [/DatabusClient")
                .addOption("g", true, "Groupname [default-group-name] ")
                .addOption("d", true, "Shared directory name [shareddata] ")
                .addOption("s", true, "Zookeeper server list [localhost:2181] ").addOption("h", false, "help");
        CommandLine cmdLineArgs = cmdLineParser.parse(options, args, false);

        if (cmdLineArgs.hasOption('h')) {
            usage();
            System.exit(0);
        }

        String namespace = cmdLineArgs.getOptionValue('n');
        if (namespace == null || namespace.isEmpty()) {
            namespace = "/DatabusClient";
        }
        String groupname = cmdLineArgs.getOptionValue('g');
        if (groupname == null || groupname.isEmpty()) {
            groupname = "default-group-name";
        }
        String sharedDir = cmdLineArgs.getOptionValue('d');
        if (sharedDir == null || sharedDir.isEmpty()) {
            sharedDir = "shareddata";
        }
        String serverList = cmdLineArgs.getOptionValue('s');
        if (serverList == null || serverList.isEmpty()) {
            serverList = "localhost:2181";
        }
        String[] fns = cmdLineArgs.getArgs();
        if (fns.length < 1) {
            usage();
            System.exit(1);
        }
        String function = fns[0];
        String arg1 = (fns.length > 1) ? fns[1] : null;
        String arg2 = (fns.length > 2) ? fns[2] : null;
        try {
            String memberName = "cmd-line-tool";
            DatabusClientNode clusterNode = new DatabusClientNode(new DatabusClientNode.StaticConfig(true,
                    serverList, 2000, 5000, namespace, groupname, memberName, false, sharedDir));
            DatabusClientGroupMember member = clusterNode.getMember(namespace, groupname, memberName);
            if (member == null || !member.joinWithoutLeadershipDuties()) {
                System.err.println("Initialization failed for: " + member);
                System.exit(1);
            }

            if (function.equals("members")) {
                List<String> mlist = member.getMembers();
                for (String m : mlist) {
                    System.out.println(m);
                }

            } else if (function.equals("leader")) {
                String leader = member.getLeader();
                System.out.println(leader);

            } else if (function.equals("keys")) {
                List<String> keyList = member.getSharedKeys();
                if (keyList != null) {
                    for (String m : keyList) {
                        System.out.println(m);
                    }
                }
            } else if (function.equals("readSCN")) {
                List<String> keyList;
                if (arg1 == null) {
                    keyList = member.getSharedKeys();
                } else {
                    keyList = new ArrayList<String>();
                    keyList.add(arg1);
                }
                if (keyList != null) {
                    for (String k : keyList) {
                        if (!k.equals(DatabusClientDSCUpdater.DSCKEY)) {
                            Checkpoint cp = (Checkpoint) member.readSharedData(k);
                            if (cp != null) {
                                System.out.println(k + " " + cp.getWindowScn() + " " + cp.getWindowOffset());
                            } else {
                                System.err.println(k + " null null");
                            }
                        }
                    }
                }

            } else if (function.equals("writeSCN")) {
                if (arg1 != null && arg2 != null) {
                    Checkpoint cp = new Checkpoint();
                    cp.setConsumptionMode(DbusClientMode.ONLINE_CONSUMPTION);
                    cp.setWindowScn(Long.parseLong(arg2));
                    if (fns.length > 3) {
                        cp.setWindowOffset(Integer.parseInt(fns[3]));
                    } else {
                        cp.setWindowOffset(-1);
                    }
                    if (member.writeSharedData(arg1, cp)) {
                        System.out.println(arg1 + " " + cp.getWindowScn() + " " + cp.getWindowOffset());
                    } else {
                        System.err.println("Write failed! " + member + " couldn't write key=" + arg1);
                        System.exit(1);
                    }
                } else {
                    usage();
                    System.exit(1);
                }
            } else if (function.equals("readLastTs")) {
                Long timeInMs = (Long) member.readSharedData(DatabusClientDSCUpdater.DSCKEY);
                if (timeInMs != null) {
                    System.out.println(DatabusClientDSCUpdater.DSCKEY + " " + timeInMs.longValue());
                } else {
                    System.err.println(DatabusClientDSCUpdater.DSCKEY + " null");
                }
            } else if (function.equals("writeLastTs")) {
                if (arg1 != null) {
                    Long ts = Long.parseLong(arg1);
                    if (member.writeSharedData(DatabusClientDSCUpdater.DSCKEY, ts)) {
                        System.out.println(DatabusClientDSCUpdater.DSCKEY + " " + ts);
                    } else {
                        System.err.println("Write failed! " + member + " couldn't write key="
                                + DatabusClientDSCUpdater.DSCKEY);
                        System.exit(1);
                    }

                } else {
                    usage();
                    System.exit(1);
                }
            } else if (function.equals("remove")) {
                if (!member.removeSharedData(arg1)) {
                    System.err.println("Remove failed! " + arg1);
                    System.exit(1);
                }
            } else if (function.equals("create")) {
                if (!member.createPaths()) {
                    System.err.println("Create path failed!");
                    System.exit(1);
                }

            } else {
                usage();
                System.exit(1);
            }
        } catch (InvalidConfigException e) {
            e.printStackTrace();
            usage();
            System.exit(1);
        }

    } catch (ParseException e) {
        usage();
        System.exit(1);
    }

}

From source file:com.thimbleware.jmemcached.Main.java

public static void main(String[] args) throws Exception {
    // look for external log4j.properties

    // setup command line options
    Options options = new Options();
    options.addOption("h", "help", false, "print this help screen");
    options.addOption("bl", "block-store", false, "use external (from JVM) heap");
    options.addOption("f", "mapped-file", false, "use external (from JVM) heap through a memory mapped file");
    options.addOption("bs", "block-size", true,
            "block size (in bytes) for external memory mapped file allocator.  default is 8 bytes");
    options.addOption("i", "idle", true, "disconnect after idle <x> seconds");
    options.addOption("p", "port", true, "port to listen on");
    options.addOption("m", "memory", true,
            "max memory to use; in bytes, specify K, kb, M, GB for larger units");
    options.addOption("c", "ceiling", true,
            "ceiling memory to use; in bytes, specify K, kb, M, GB for larger units");
    options.addOption("l", "listen", true, "Address to listen on");
    options.addOption("s", "size", true, "max items");
    options.addOption("b", "binary", false, "binary protocol mode");
    options.addOption("V", false, "Show version number");
    options.addOption("v", false, "verbose (show commands)");

    // read command line options
    CommandLineParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args);

    if (cmdline.hasOption("help") || cmdline.hasOption("h")) {
        System.out.println("Memcached Version " + MemCacheDaemon.memcachedVersion);
        System.out.println("http://thimbleware.com/projects/memcached\n");

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar memcached.jar", options);
        return;/*  w  w  w .j a va 2 s.  co m*/
    }

    if (cmdline.hasOption("V")) {
        System.out.println("Memcached Version " + MemCacheDaemon.memcachedVersion);
        return;
    }

    int port = 11211;
    if (cmdline.hasOption("p")) {
        port = Integer.parseInt(cmdline.getOptionValue("p"));
    } else if (cmdline.hasOption("port")) {
        port = Integer.parseInt(cmdline.getOptionValue("port"));
    }

    InetSocketAddress addr = new InetSocketAddress(port);
    if (cmdline.hasOption("l")) {
        addr = new InetSocketAddress(cmdline.getOptionValue("l"), port);
    } else if (cmdline.hasOption("listen")) {
        addr = new InetSocketAddress(cmdline.getOptionValue("listen"), port);
    }

    int max_size = 1000000;
    if (cmdline.hasOption("s"))
        max_size = (int) Bytes.valueOf(cmdline.getOptionValue("s")).bytes();
    else if (cmdline.hasOption("size"))
        max_size = (int) Bytes.valueOf(cmdline.getOptionValue("size")).bytes();

    System.out.println("Setting max cache elements to " + String.valueOf(max_size));

    int idle = -1;
    if (cmdline.hasOption("i")) {
        idle = Integer.parseInt(cmdline.getOptionValue("i"));
    } else if (cmdline.hasOption("idle")) {
        idle = Integer.parseInt(cmdline.getOptionValue("idle"));
    }

    boolean memoryMapped = false;
    if (cmdline.hasOption("f")) {
        memoryMapped = true;
    } else if (cmdline.hasOption("mapped-file")) {
        memoryMapped = true;
    }

    boolean blockStore = false;
    if (cmdline.hasOption("bl")) {
        blockStore = true;
    } else if (cmdline.hasOption("block-store")) {
        blockStore = true;
    }

    boolean verbose = false;
    if (cmdline.hasOption("v")) {
        verbose = true;
    }

    long ceiling;
    if (cmdline.hasOption("c")) {
        ceiling = Bytes.valueOf(cmdline.getOptionValue("c")).bytes();
        System.out.println("Setting ceiling memory size to " + Bytes.bytes(ceiling).megabytes() + "M");
    } else if (cmdline.hasOption("ceiling")) {
        ceiling = Bytes.valueOf(cmdline.getOptionValue("ceiling")).bytes();
        System.out.println("Setting ceiling memory size to " + Bytes.bytes(ceiling).megabytes() + "M");
    } else if (!memoryMapped) {
        ceiling = 1024000;
        System.out.println(
                "Setting ceiling memory size to default limit of " + Bytes.bytes(ceiling).megabytes() + "M");
    } else {
        System.out
                .println("ERROR : ceiling memory size mandatory when external memory mapped file is specified");

        return;
    }

    boolean binary = false;
    if (cmdline.hasOption("b")) {
        binary = true;
    }

    int blockSize = 8;
    if (!memoryMapped && (cmdline.hasOption("bs") || cmdline.hasOption("block-size"))) {
        System.out.println(
                "WARN : block size option is only valid for memory mapped external heap storage; ignoring");
    } else if (cmdline.hasOption("bs")) {
        blockSize = Integer.parseInt(cmdline.getOptionValue("bs"));
    } else if (cmdline.hasOption("block-size")) {
        blockSize = Integer.parseInt(cmdline.getOptionValue("block-size"));
    }

    long maxBytes;
    if (cmdline.hasOption("m")) {
        maxBytes = Bytes.valueOf(cmdline.getOptionValue("m")).bytes();
        System.out.println("Setting max memory size to " + Bytes.bytes(maxBytes).gigabytes() + "GB");
    } else if (cmdline.hasOption("memory")) {
        maxBytes = Bytes.valueOf(cmdline.getOptionValue("memory")).bytes();
        System.out.println("Setting max memory size to " + Bytes.bytes(maxBytes).gigabytes() + "GB");
    } else if (!memoryMapped) {
        maxBytes = Runtime.getRuntime().maxMemory();
        System.out
                .println("Setting max memory size to JVM limit of " + Bytes.bytes(maxBytes).gigabytes() + "GB");
    } else {
        System.out.println(
                "ERROR : max memory size and ceiling size are mandatory when external memory mapped file is specified");
        return;
    }

    if (!memoryMapped && !blockStore && maxBytes > Runtime.getRuntime().maxMemory()) {
        System.out.println("ERROR : JVM heap size is not big enough. use '-Xmx"
                + String.valueOf(maxBytes / 1024000) + "m' java argument before the '-jar' option.");
        return;
    } else if ((memoryMapped || !blockStore) && maxBytes > Integer.MAX_VALUE) {
        System.out.println(
                "ERROR : when external memory mapped, memory size may not exceed the size of Integer.MAX_VALUE ("
                        + Bytes.bytes(Integer.MAX_VALUE).gigabytes() + "GB");
        return;
    }

    // create daemon and start it
    final MemCacheDaemon<LocalCacheElement> daemon = new MemCacheDaemon<LocalCacheElement>();

    CacheStorage<Key, LocalCacheElement> storage;
    if (blockStore) {
        BlockStoreFactory blockStoreFactory = ByteBufferBlockStore.getFactory();

        storage = new BlockStorageCacheStorage(8, (int) ceiling, blockSize, maxBytes, max_size,
                blockStoreFactory);
    } else if (memoryMapped) {
        BlockStoreFactory blockStoreFactory = MemoryMappedBlockStore.getFactory();

        storage = new BlockStorageCacheStorage(8, (int) ceiling, blockSize, maxBytes, max_size,
                blockStoreFactory);
    } else {
        storage = ConcurrentLinkedHashMap.create(ConcurrentLinkedHashMap.EvictionPolicy.FIFO, max_size,
                maxBytes);
    }

    daemon.setCache(new CacheImpl(storage));
    daemon.setBinary(binary);
    daemon.setAddr(addr);
    daemon.setIdleTime(idle);
    daemon.setVerbose(verbose);
    daemon.start();

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            if (daemon.isRunning())
                daemon.stop();
        }
    }));
}

From source file:net.robyf.dbpatcher.Launcher.java

public static void main(final String[] args) throws DBPatcherException { //NOSONAR
    Options options = new Options();

    Option usernameOption = new Option("u", "username", true, "Database username");
    usernameOption.setRequired(true);/* ww  w  .j  av a2s . co m*/
    options.addOption(usernameOption);
    Option passwordOption = new Option("p", "password", true, "Database password");
    passwordOption.setRequired(true);
    options.addOption(passwordOption);
    Option databaseOption = new Option("d", "databaseName", true, "Database name");
    databaseOption.setRequired(true);
    options.addOption(databaseOption);
    options.addOption("r", "rollback-if-error", false, "Rolls back the entire operation in case of errors");
    options.addOption("v", "to-version", true, "Target version number");
    options.addOption("s", "simulation", false, "Simulate the operation without touching the current database");
    options.addOption("c", "character-set", true, "Character set (default value: ISO-8859-1)");

    Parameters parameters = new Parameters();
    boolean showHelp = false;
    try {
        CommandLine commandLine = new PosixParser().parse(options, args);

        parameters.setUsername(commandLine.getOptionValue("u"));
        parameters.setPassword(commandLine.getOptionValue("p"));
        parameters.setDatabaseName(commandLine.getOptionValue("d"));

        parameters.setRollbackIfError(commandLine.hasOption("r"));
        parameters.setSimulationMode(commandLine.hasOption("s"));
        if (commandLine.hasOption("v")) {
            parameters.setTargetVersion(new Long(commandLine.getOptionValue("v")));
        }
        if (commandLine.hasOption("c")) {
            parameters.setCharset(Charset.forName(commandLine.getOptionValue("c")));
        }

        if (commandLine.getArgs().length == 1) {
            parameters.setSchemaPath(commandLine.getArgs()[0]);
        } else {
            showHelp = true;
        }
    } catch (ParseException pe) {
        showHelp = true;
    }

    if (showHelp) {
        new HelpFormatter().printHelp("java -jar dbpatcher.jar" + " -u username -p password -d database_name"
                + " [options] schema_root", "Available options:", options, "");
    } else {
        DBPatcherFactory.getDBPatcher().patch(parameters);
    }
}

From source file:at.ait.dme.magicktiler.MagickTilerCLI.java

public static void main(String... args) throws IOException {
    if (showGui(args))
        return;/*  w ww  . j a  v  a 2 s  . co m*/

    try {
        CommandLine cmd = new BasicParser().parse(options, args);

        // Help
        if (cmd.hasOption("h")) {
            printUsage(options);
            return;
        }

        // Log on/off
        if (cmd.hasOption("l")) {
            logger.addAppender(new FileAppender(new PatternLayout(), "log.txt", false));
            logger.setLevel(Level.DEBUG);
        }

        // Convert or validate
        if (cmd.hasOption("v")) {
            validate(cmd);
        } else {
            convert(cmd);
        }
    } catch (ParseException e) {
        System.err.println("Failed to parse command line arguments: " + e.getMessage());
        printUsage(options);
    }
}

From source file:ca.uqac.lif.bullwinkle.BullwinkleCli.java

/**
 * @param args//w  w w. j  av  a  2s  .c  o  m
 */
public static void main(String[] args) {
    // Setup parameters
    int verbosity = 1;
    String output_format = "xml", grammar_filename = null, filename_to_parse = null;

    // Parse command line arguments
    Options options = setupOptions();
    CommandLine c_line = setupCommandLine(args, options);
    assert c_line != null;
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (verbosity > 0) {
        showHeader();
    }
    if (c_line.hasOption("version")) {
        System.err.println("(C) 2014 Sylvain Hall et al., Universit du Qubec  Chicoutimi");
        System.err.println("This program comes with ABSOLUTELY NO WARRANTY.");
        System.err.println("This is a free software, and you are welcome to redistribute it");
        System.err.println("under certain conditions. See the file LICENSE-2.0 for details.\n");
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("f")) {
        output_format = c_line.getOptionValue("f");
    }
    // Get grammar file
    @SuppressWarnings("unchecked")
    List<String> remaining_args = c_line.getArgList();
    if (remaining_args.isEmpty()) {
        System.err.println("ERROR: no grammar file specified");
        System.exit(ERR_ARGUMENTS);
    }
    grammar_filename = remaining_args.get(0);
    // Get file to parse, if any
    if (remaining_args.size() >= 2) {
        filename_to_parse = remaining_args.get(1);
    }

    // Read grammar file
    BnfParser parser = null;
    try {
        parser = new BnfParser(new File(grammar_filename));
    } catch (InvalidGrammarException e) {
        System.err.println("ERROR: invalid grammar");
        System.exit(ERR_GRAMMAR);
    } catch (IOException e) {
        System.err.println("ERROR reading grammar " + grammar_filename);
        System.exit(ERR_IO);
    }
    assert parser != null;

    // Read input file
    BufferedReader bis = null;
    if (filename_to_parse == null) {
        // Read from stdin
        bis = new BufferedReader(new InputStreamReader(System.in));
    } else {
        // Read from file
        try {
            bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filename_to_parse))));
        } catch (FileNotFoundException e) {
            System.err.println("ERROR: file not found " + filename_to_parse);
            System.exit(ERR_IO);
        }
    }
    assert bis != null;
    String str;
    StringBuilder input_file = new StringBuilder();
    try {
        while ((str = bis.readLine()) != null) {
            input_file.append(str).append("\n");
        }
    } catch (IOException e) {
        System.err.println("ERROR reading input");
        System.exit(ERR_IO);
    }
    String file_contents = input_file.toString();

    // Parse contents of file
    ParseNode p_node = null;
    try {
        p_node = parser.parse(file_contents);
    } catch (ca.uqac.lif.bullwinkle.BnfParser.ParseException e) {
        System.err.println("ERROR parsing input\n");
        e.printStackTrace();
        System.exit(ERR_PARSE);
    }
    if (p_node == null) {
        System.err.println("ERROR parsing input\n");
        System.exit(ERR_PARSE);
    }
    assert p_node != null;

    // Output parse node to desired format
    PrintStream output = System.out;
    OutputFormatVisitor out_vis = null;
    if (output_format.compareToIgnoreCase("xml") == 0) {
        // Output to XML
        out_vis = new XmlVisitor();
    } else if (output_format.compareToIgnoreCase("dot") == 0) {
        // Output to DOT
        out_vis = new GraphvizVisitor();
    } else if (output_format.compareToIgnoreCase("txt") == 0) {
        // Output to indented plain text
        out_vis = new IndentedTextVisitor();
    } else if (output_format.compareToIgnoreCase("json") == 0) {
        // Output to JSON
    }
    if (out_vis == null) {
        System.err.println("ERROR: unknown output format " + output_format);
        System.exit(ERR_ARGUMENTS);
    }
    assert out_vis != null;
    p_node.prefixAccept(out_vis);
    output.print(out_vis.toOutputString());

    // Terminate without error
    System.exit(ERR_OK);
}

From source file:br.edu.ufcg.lsd.seghidro.extratoropendap.ui.CLI.java

/**
 * Exemplo:/* w  w  w. j a  va  2 s .  c  o m*/
 * 
 * <pre>
 *   java -jar extrator-opendap.jar -d &quot;dods://150.165.126.97:8080/thredds/dodsC/test/MIMR_SRB1_1_pr-change_2011-2030.nc&quot; -p ../../resources/arquivos_de_entrada/postoBoqueirao.txt -i &quot;2020-05-16&quot; -f &quot;2020-08-16&quot; -o output.txt
 * </pre>
 * 
 * @param args
 * @throws java.text.ParseException
 * @throws ExtratorOpendapException
 * @throws IOException
 */
public static void main(String[] args) throws IOException, ExtratorOpendapException, java.text.ParseException {
    // System.out.println(args[0]+" "+ args[1] +" "+ args[2]+" "+ args[3]
    // +" "+ args[4]);
    // System.out.println("===========================hsdklhfsllll+======");
    // if (args[3].equals("forMarbs")) {
    // ExtratorNoFormatoPMH extrator = new
    // ExtratorNoFormatoPMH(args[4],args[5],args[6]);
    if (args[0].equals("forMarbs")) {
        ExtratorNoFormatoPMH extrator = new ExtratorNoFormatoPMH(args[1], args[2], args[3]);
    } else {
        Options options = new Options();

        options.addOption(PONTOS, "pontos", true, "Caminho para o arquivo de pontos.");
        options.addOption(DATASET, "dataset", true, "Caminho para o dataset de origem.");
        options.addOption(OUTPUT, "output", true, "Nome do arquivo de sada.");
        options.addOption(INICIO, "inicio", true, "Data inicial da extrao.");
        options.addOption(FIM, "fim", true, "Data final da extrao.");
        options.addOption(HELP, false, "Comando de ajuda.");
        options.addOption(USAGE, false, "Instrues de uso.");
        CommandLineParser parser = new PosixParser();
        HelpFormatter formatter = new HelpFormatter();
        CommandLine cmd = null;

        try {
            cmd = parser.parse(options, args);
        } catch (ParseException e) {
            MainUtil.showMessageAndExit(e);
        }

        if (cmd.hasOption(PONTOS) && cmd.hasOption(DATASET) && cmd.hasOption(OUTPUT)) {
            String arquivoNetCDF = cmd.getOptionValue(DATASET);
            String arquivoDePontos = cmd.getOptionValue(PONTOS);
            String outputFileName = cmd.getOptionValue(OUTPUT);
            DataSet dataset;
            try {
                dataset = new DataSet(arquivoNetCDF);
                ExtratorDeVariaveisIF extrator;
                if (cmd.hasOption(INICIO) && cmd.hasOption(FIM)) {
                    Date dataInicial = null;
                    Date dataFinal = null;
                    try {
                        dataInicial = formatadorDeDatas.parse(cmd.getOptionValue(INICIO));
                    } catch (java.text.ParseException e) {
                        MainUtil.showMessageAndExit("A data inicial '" + cmd.getOptionValue(INICIO)
                                + "' no est em um formato reconhecido. Informe no formato "
                                + formatoParaData + ". Por Exemplo: " + formatadorDeDatas.format(new Date())
                                + ".");
                    }
                    try {
                        dataFinal = formatadorDeDatas.parse(cmd.getOptionValue(FIM));
                    } catch (java.text.ParseException e) {
                        MainUtil.showMessageAndExit("A data final '" + cmd.getOptionValue(FIM)
                                + "' no est em um formato reconhecido. Informe no formato "
                                + formatoParaData + ". Por Exemplo: " + formatadorDeDatas.format(new Date())
                                + ".");
                    }
                    extrator = new ExtratorDeVariaveisInterpolado(dataset, new File(arquivoDePontos),
                            dataInicial, dataFinal, new File(outputFileName));
                } else {
                    extrator = new ExtratorDeVariaveisInterpolado(dataset, new File(arquivoDePontos),
                            new File(outputFileName));
                }
                String extracoes = extrator.extraiValoresDeInteresse();
                System.out.println(extracoes);
                extrator.salvaArquivoComExtracoes();
            } catch (ExtratorOpendapException e) {
                MainUtil.showMessageAndExit(e);
            }
        } else {
            if (cmd.hasOption(HELP)) {
                formatter.printHelp(EXECUTION_LINE, options);
            } else if (cmd.hasOption(USAGE)) {
                formatter.printHelp(EXECUTION_LINE, options, true);
            } else {
                formatter.printHelp(EXECUTION_LINE, options, true);
            }
        }

    }
}