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

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

Introduction

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

Prototype

public boolean hasOption(char opt) 

Source Link

Document

Query to see if an option has been set.

Usage

From source file:com.hortonworks.streamline.storage.tool.SQLScriptRunner.java

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

    options.addOption(option(1, "c", OPTION_CONFIG_FILE_PATH, "Config file path"));
    options.addOption(option(Option.UNLIMITED_VALUES, "f", OPTION_SCRIPT_PATH, "Script path to execute"));
    options.addOption(option(Option.UNLIMITED_VALUES, "m", OPTION_MYSQL_JAR_URL_PATH,
            "Mysql client jar url to download"));
    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);

    if (!commandLine.hasOption(OPTION_CONFIG_FILE_PATH) || !commandLine.hasOption(OPTION_SCRIPT_PATH)
            || commandLine.getOptionValues(OPTION_SCRIPT_PATH).length <= 0) {
        usage(options);//from   w  w w  .j  av a  2s  .co  m
        System.exit(1);
    }

    String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH);
    String[] scripts = commandLine.getOptionValues(OPTION_SCRIPT_PATH);
    String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH);

    try {
        Map<String, Object> conf = Utils.readStreamlineConfig(confFilePath);

        StorageProviderConfigurationReader confReader = new StorageProviderConfigurationReader();
        StorageProviderConfiguration storageProperties = confReader.readStorageConfig(conf);

        String bootstrapDirPath = System.getProperty("bootstrap.dir");

        MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl);

        SQLScriptRunner sqlScriptRunner = new SQLScriptRunner(storageProperties);
        try {
            sqlScriptRunner.initializeDriver();
        } catch (ClassNotFoundException e) {
            System.err.println(
                    "Driver class is not found in classpath. Please ensure that driver is in classpath.");
            System.exit(1);
        }

        for (String script : scripts) {
            sqlScriptRunner.runScriptWithReplaceDBType(script);
        }
    } catch (IOException e) {
        System.err.println("Error occurred while reading config file: " + confFilePath);
        System.exit(1);
    }
}

From source file:de.jackwhite20.japs.server.Main.java

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

    Config config = null;/*w  w  w  .  j a  va  2s . co m*/

    if (args.length > 0) {
        Options options = new Options();
        options.addOption("h", true, "Address to bind to");
        options.addOption("p", true, "Port to bind to");
        options.addOption("b", true, "The backlog");
        options.addOption("t", true, "Worker thread count");
        options.addOption("d", false, "If debug is enabled or not");
        options.addOption("c", true, "Add server as a cluster");
        options.addOption("ci", true, "Sets the cache check interval");
        options.addOption("si", true, "Sets the snapshot interval");

        CommandLineParser commandLineParser = new BasicParser();
        CommandLine commandLine = commandLineParser.parse(options, args);

        if (commandLine.hasOption("h") && commandLine.hasOption("p") && commandLine.hasOption("b")
                && commandLine.hasOption("t")) {

            List<ClusterServer> clusterServers = new ArrayList<>();

            if (commandLine.hasOption("c")) {
                for (String c : commandLine.getOptionValues("c")) {
                    String[] splitted = c.split(":");
                    clusterServers.add(new ClusterServer(splitted[0], Integer.parseInt(splitted[1])));
                }
            }

            config = new Config(commandLine.getOptionValue("h"),
                    Integer.parseInt(commandLine.getOptionValue("p")),
                    Integer.parseInt(commandLine.getOptionValue("b")), commandLine.hasOption("d"),
                    Integer.parseInt(commandLine.getOptionValue("t")), clusterServers,
                    (commandLine.hasOption("ci")) ? Integer.parseInt(commandLine.getOptionValue("ci")) : 300,
                    (commandLine.hasOption("si")) ? Integer.parseInt(commandLine.getOptionValue("si")) : -1);
        } else {
            System.out.println(
                    "Usage: java -jar japs-server.jar -h <Host> -p <Port> -b <Backlog> -t <Threads> [-c IP:Port IP:Port] [-d]");
            System.out.println(
                    "Example (with debugging enabled): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -d");
            System.out.println(
                    "Example (with debugging enabled and cluster setup): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -c localhost:1338 -d");
            System.exit(-1);
        }
    } else {
        File configFile = new File("config.json");
        if (!configFile.exists()) {
            try {
                Files.copy(JaPS.class.getClassLoader().getResourceAsStream("config.json"), configFile.toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                System.err.println("Unable to load default config!");
                System.exit(-1);
            }
        }

        try {
            config = new Gson().fromJson(
                    Files.lines(configFile.toPath()).map(String::toString).collect(Collectors.joining(" ")),
                    Config.class);
        } catch (IOException e) {
            System.err.println("Unable to load 'config.json' in current directory!");
            System.exit(-1);
        }
    }

    if (config == null) {
        System.err.println("Failed to create a Config!");
        System.err.println("Please check the program parameters or the 'config.json' file!");
    } else {
        System.err.println("Using Config: " + config);

        JaPS jaPS = new JaPS(config);
        jaPS.init();
        jaPS.start();
        jaPS.stop();
    }
}

From source file:io.github.azige.whitespace.Cli.java

public static void main(String[] args) {
    Options options = new Options().addOption("h", "help", false, "??")
            .addOptionGroup(new OptionGroup()
                    .addOption(new Option("p",
                            "????????"))
                    .addOption(new Option("c", "?????")))
            .addOption(null, "szm", false,
                    "????")
            .addOption("e", "encoding", true, "??" + DEFAULT_ENCODING);

    try {//from  w w w.  j  ava  2 s. c  o  m
        CommandLineParser parser = new BasicParser();
        CommandLine cl = parser.parse(options, args);

        if (cl.hasOption('h')) {
            printHelp(System.out, options);
            return;
        }

        if (cl.hasOption('e')) {
            encoding = Charset.forName(cl.getOptionValue('e'));
        } else {
            encoding = Charset.forName(DEFAULT_ENCODING);
        }

        if (cl.hasOption("szm")) {
            useSzm = true;
        }

        String[] fileArgs = cl.getArgs();
        if (fileArgs.length != 1) {
            printHelp(System.err, options);
            return;
        }

        try (InputStream input = Files.newInputStream(Paths.get(fileArgs[0]))) {
            if (cl.hasOption('p')) {
                printPseudoCode(input);
            } else if (cl.hasOption('c')) {
                compile(input, fileArgs[0]);
            } else {
                execute(input, fileArgs[0]);
            }
        }
    } catch (ParseException ex) {
        ex.printStackTrace();
        printHelp(System.err, options);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.happy_coding.viralo.coordinator.ViraloRunner.java

/**
 * Main task.//  w w  w .  j  a v a  2  s  .c om
 *
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    // Parser
    CommandLineParser parser = new PosixParser();

    // Options
    Options options = new Options();

    Option createFriends = OptionBuilder.withDescription("Create friends by using the given keywords.").hasArg()
            .withArgName("keywords").create("createFriends");

    options.addOption(createFriends);
    options.addOption("R", "refreshFollowers", false, "refresh followers for current user.");
    options.addOption("C", "cleanup", false, "delete friends which don't follow");
    options.addOption("S", "smartTweet", false, "Posts a smart tweet.");
    options.addOption("F", "createTrendFriends", false, "Create friends to a random trend.");
    options.addOption("T", "answerTopQuestion", false, "answer a top question and post it.");
    options.addOption("RC", "robotConversation", false, "starts a task which answers mentions automatically.");

    if (args.length < 1) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar ...jar", options);
        System.exit(0);
    }

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

    if (line.hasOption("createFriends")) {

        String keywords = line.getOptionValue("createFriends");

        Viralo viralo = new Viralo();

        FriendDiscoverer friendDiscoverer = new FriendDiscoverer();
        Contact forContact = friendDiscoverer.returnMyself();

        System.out.println("Create friends for " + forContact.getName());

        viralo.createNewFriends(forContact, keywords, ";");

    } else if (line.hasOption("refreshFollowers")) {

        Viralo viralo = new Viralo();

        FriendDiscoverer friendDiscoverer = new FriendDiscoverer();
        Contact forContact = friendDiscoverer.returnMyself();

        viralo.refreshFollowers(forContact);

    } else if (line.hasOption("cleanup")) {

        Viralo viralo = new Viralo();

        FriendDiscoverer friendDiscoverer = new FriendDiscoverer();
        Contact forContact = friendDiscoverer.returnMyself();

        viralo.cleanup(forContact);

    } else if (line.hasOption("smartTweet")) {
        Viralo viralo = new Viralo();
        viralo.postSmartTweet();
    } else if (line.hasOption("createTrendFriends")) {
        FriendDiscoverer friendDiscoverer = new FriendDiscoverer();
        Contact forContact = friendDiscoverer.returnMyself();
        Viralo viralo = new Viralo();
        viralo.createNewFriends(forContact);
    } else if (line.hasOption("answerTopQuestion")) {
        Viralo viralo = new Viralo();
        viralo.answerTopQuestion();
    } else if (line.hasOption("robotConversation")) {

        boolean taskFlag = true;
        Viralo viralo = new Viralo();

        while (taskFlag) {

            /*
            reply to mentions
             */
            viralo.autoConversation();

            /*
            wait some seconds.
             */
            Thread.sleep(WAIT_MS_BETWEEN_ACTIONS);
        }

    }

    System.exit(0);
}

From source file:com.mnxfst.stream.server.StreamAnalyzerServer.java

/**
 * Ramps up the server/*from   www . ja v a 2 s  . c o m*/
 * @param args
 */
public static void main(String[] args) throws Exception {

    CommandLineParser parser = new PosixParser();
    CommandLine cl = parser.parse(getOptions(), args);
    if (!cl.hasOption("cfg") || !cl.hasOption("port")) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java " + StreamAnalyzerServer.class.getName(), getOptions());
        return;
    }

    (new StreamAnalyzerServer()).run(cl.getOptionValue("cfg"), Integer.parseInt(cl.getOptionValue("port")));
}

From source file:eu.scape_project.pc.droid.cli.DroidCli.java

public static void main(String[] args) {
    // Static for command line option parsing
    DroidCli tc = new DroidCli();

    CommandLineParser cmdParser = new PosixParser();
    try {/* w  w  w  . j  a  v  a 2  s. c o  m*/
        CommandLine cmd = cmdParser.parse(OPTIONS, args);
        if ((args.length == 0) || (cmd.hasOption(HELP_OPT))) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(Constants.USAGE, OPTIONS, true);
            System.exit(0);
        } else {
            if (cmd.hasOption(DIR_OPT) && cmd.getOptionValue(DIR_OPT) != null) {
                String dirStr = cmd.getOptionValue(DIR_OPT);
                logger.info("Directory: " + dirStr);

                // *** start timer
                long startClock = System.currentTimeMillis();
                try {
                    tc.processFiles(new File(dirStr));

                } catch (FileNotFoundException ex) {
                    logger.error("File not found", ex);
                } catch (IOException ex) {
                    logger.error("I/O Exception", ex);
                }

                // *** stop timer
                long elapsedTimeMillis = System.currentTimeMillis() - startClock;
                logger.info("Identification finished after " + elapsedTimeMillis + " milliseconds");

            } else {
                logger.error("No directory given.");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp(Constants.USAGE, OPTIONS, true);
                System.exit(1);
            }
        }
    } catch (ParseException ex) {
        logger.error("Problem parsing command line arguments.", ex);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Constants.USAGE, OPTIONS, true);
        System.exit(1);
    }
}

From source file:de.thomasvolk.genexample.GenAlg.java

public static void main(String[] args) throws IOException, ParseException {
    System.out.println("Genetische Algorithmen");

    Options options = new Options();
    options.addOption(option("s", "Jede s Generation wird im Bericht ausgegeben"));
    options.addOption(option("w", "Quelldatei Wagon"));
    options.addOption(option("l", "Quelldatei Passagierliste"));
    options.addOption(option("d", "Zielverzeichnis Bericht"));
    options.addOption(option("a", "Algorithmus Typ " + Arrays.asList(AlgorithmusTyp.values()).toString()));
    options.addOption(option("g", "Anzahl der Generationen"));
    options.addOption(option("p", "Anzahl der Populationen"));
    options.addOption("h", false, "Hilfe");
    CommandLineParser parser = new PosixParser();
    try {/*  w ww. ja  v  a  2 s .  c  o  m*/
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption('h')) {
            printUsage(options);
            System.exit(0);
        }

        int generationen = getNummer(options, cmd.getOptionValue('g'), 2000);
        int populationen = getNummer(options, cmd.getOptionValue('p'), 20);
        int schritte = getNummer(options, cmd.getOptionValue('s'), 100);
        AlgorithmusTyp[] alg = AlgorithmusTyp.values();
        if (cmd.hasOption('a')) {
            try {
                alg = new AlgorithmusTyp[] { AlgorithmusTyp.valueOf(cmd.getOptionValue('a')) };
            } catch (IllegalArgumentException e) {
                printErrorAndExit(e, options);
            }
        }
        String reportDir = cmd.getOptionValue('d');
        reportDir = StringUtils.isBlank(reportDir) ? "report" : reportDir;
        String wagonDatei = cmd.getOptionValue('w');
        String passagierDatei = cmd.getOptionValue('l');
        if (wagonDatei == null) {
            wagonDatei = erzeugeBeispielDatei("wagon.txt");
        }
        if (passagierDatei == null) {
            passagierDatei = erzeugeBeispielDatei("passagiere.csv");
        }
        System.out.println("Wagon Datein: " + wagonDatei);
        System.out.println("Passagier Datei: " + passagierDatei);
        System.out.println("Bericht: " + new File(reportDir).getAbsolutePath());
        System.out.println("Anzahl Generationen: " + generationen);
        System.out.println("Anzahl Populationen: " + populationen);
        System.out.printf("Protokolliere jede %dte Generation im Bericht\n", schritte);

        WagonFactory wagonFactory = new WagonFactory();
        PassagierFactory passagierFactory = new CSVPassagierFactory();

        GenAlg genAlg = new GenAlg(wagonFactory, passagierFactory);
        genAlg.run(alg, passagierDatei, wagonDatei, reportDir, schritte, generationen, populationen);
    } catch (ParseException e) {
        printErrorAndExit(e, options);
    }
}

From source file:com.blackducksoftware.tools.nrt.NoticeReportTool.java

/**
 * @param args//from   www  .  j  a v a2  s. c o m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    System.out.println("Notice Report Tool for Black Duck Suite");
    CommandLineParser parser = new DefaultParser();

    options.addOption("h", "help", false, "show help.");

    Option applicationOption = new Option(NRTConstants.CL_APPLICATION_TYPE, true,
            "Application type [PROTEX|CODECENTER] (required)");
    applicationOption.setRequired(true);
    options.addOption(applicationOption);

    Option configFileOption = new Option(NRTConstants.CL_CONFIG_FILE, true,
            "Location of configuration file (required)");
    configFileOption.setRequired(true);
    options.addOption(configFileOption);

    Option projectNameOption = new Option(NRTConstants.CL_PROJECT_NAME, true,
            "Name of Protex project (will override configuration file)");
    projectNameOption.setRequired(false);
    options.addOption(projectNameOption);

    File configFile = null;
    APPLICATION applicationType = null;
    String projectName = null;

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

        if (cmd.hasOption("h")) {
            help();
        }

        // Config File
        if (cmd.hasOption(NRTConstants.CL_CONFIG_FILE)) {
            String configFilePath = cmd.getOptionValue(NRTConstants.CL_CONFIG_FILE);
            log.info("Config file location: " + configFilePath);
            configFile = new File(configFilePath);
            if (!configFile.exists()) {
                log.error("Configuration file does not exist at location: " + configFile);
                System.exit(-1);
            }
        } else {
            log.error("Must specify configuration file!");
            help();
        }

        if (cmd.hasOption(NRTConstants.CL_APPLICATION_TYPE)) {
            String bdsApplicationType = cmd.getOptionValue(NRTConstants.CL_APPLICATION_TYPE);

            try {
                applicationType = APPLICATION.valueOf(bdsApplicationType);
            } catch (IllegalArgumentException e) {
                log.error("No such application type recognized: " + bdsApplicationType);
                help();
            }

        } else {
            help();
        }

        if (cmd.hasOption(NRTConstants.CL_PROJECT_NAME)) {
            projectName = cmd.getOptionValue(NRTConstants.CL_PROJECT_NAME);
            log.info("User specified project name: " + projectName);
        }

        NoticeReportProcessor processor = new NoticeReportProcessor(configFile.getAbsolutePath(),
                applicationType, projectName);
        try {
            processor.connect();
        } catch (Exception e) {
            log.error("Connection problems: " + e.getMessage());
            throw new Exception(e);
        }
        processor.processReport();

    } catch (Exception e) {
        log.error("Error: " + e.getMessage());
        help();
    }
}

From source file:di.uniba.it.tee2.wiki.Wikidump2IndexMT.java

/**
 * language xml_dump output_dir n_thread encoding
 *
 * @param args the command line arguments
 *//*ww  w.j av a 2 s . c  om*/
public static void main(String[] args) {
    try {
        CommandLine cmd = cmdParser.parse(options, args);
        if (cmd.hasOption("l") && cmd.hasOption("d") && cmd.hasOption("o")) {
            encoding = cmd.getOptionValue("e", "UTF-8");
            minTextLegth = Integer.parseInt(cmd.getOptionValue("m", "4000"));
            /*if (cmd.hasOption("p")) {
             pageLimit = Integer.parseInt(cmd.getOptionValue("p"));
             }*/
            int nt = Integer.parseInt(cmd.getOptionValue("n", "2"));
            Wikidump2IndexMT builder = new Wikidump2IndexMT();
            builder.init(cmd.getOptionValue("l"), cmd.getOptionValue("o"), nt);
            //attach a shutdown hook
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        Wikidump2IndexMT.tee.close();
                    } catch (Exception ex) {
                        Logger.getLogger(Wikidump2IndexMT.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }));
            builder.build(cmd.getOptionValue("d"), cmd.getOptionValue("l"));
        } else {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Index Wikipedia dump (multi threads)", options, true);
        }
    } catch (Exception ex) {
        Logger.getLogger(Wikidump2IndexMT.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:metaTile.Main.java

/**
 * @param args/*from   w  w w.j av a2  s.com*/
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    try {
        /* parse the command line arguments */
        // create the command line parser
        CommandLineParser parser = new PosixParser();

        // create the Options
        Options options = new Options();
        options.addOption("i", "input", true, "File to read original tile list from.");
        options.addOption("o", "output", true, "File to write shorter meta-tile list to.");
        options.addOption("m", "metatiles", true,
                "Number of tiles in x and y direction to group into one meta-tile.");

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

        if (!commandLine.hasOption("input") || !commandLine.hasOption("output")
                || !commandLine.hasOption("metatiles"))
            printUsage(options);

        String inputFileName = commandLine.getOptionValue("input");
        String outputFileName = commandLine.getOptionValue("output");
        int metaTileSize = Integer.parseInt(commandLine.getOptionValue("metatiles"));

        ArrayList<RenderingTile> tiles = new ArrayList<RenderingTile>();

        BufferedReader tileListReader = new BufferedReader(new FileReader(new File(inputFileName)));

        BufferedWriter renderMetatileListWriter = new BufferedWriter(new FileWriter(new File(outputFileName)));

        String line = tileListReader.readLine();
        while (line != null) {
            String[] columns = line.split("/");

            if (columns.length == 3)
                tiles.add(new RenderingTile(Integer.parseInt(columns[0]), Integer.parseInt(columns[1]),
                        Integer.parseInt(columns[2])));

            line = tileListReader.readLine();
        }

        tileListReader.close();

        int hits = 0;

        // tiles which we are already rendering as the top left corner of 4x4 metatiles
        HashSet<RenderingTile> whitelist = new HashSet<RenderingTile>();

        // for each tile in the list see if it has a meta-tile in the whitelist already
        for (int i = 0; i < tiles.size(); i++) {
            boolean hit = false; // by default we aren't already rendering this tile as part of another metatile
            for (int dx = 0; dx < metaTileSize; dx++) {
                for (int dy = 0; dy < metaTileSize; dy++) {
                    RenderingTile candidate = new RenderingTile(tiles.get(i).z, tiles.get(i).x - dx,
                            tiles.get(i).y - dy);
                    if (whitelist.contains(candidate)) {
                        hit = true;
                        // now exit the two for loops iterating over tiles inside a meta-tile
                        dx = metaTileSize;
                        dy = metaTileSize;
                    }
                }
            }

            // if this tile doesn't already have a meta-tile in the whitelist, add it
            if (hit == false) {
                hits++;
                renderMetatileListWriter.write(tiles.get(i).toString() + "/" + metaTileSize + "\n");
                whitelist.add(tiles.get(i));
            }
        }
        renderMetatileListWriter.close();
        System.out.println(
                "Reduced " + tiles.size() + " tiles into " + hits + " metatiles of size " + metaTileSize);
    } catch (Exception e) {
        e.printStackTrace();
    }
}