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:ee.ria.xroad.opmonitordaemon.OperationalDataRecordsGenerator.java

/**
 * Main function.//from  w  w  w  .j  a v a  2 s .  c  o m
 * @param args args
 * @throws Exception if something goes wrong.
 */
public static void main(String args[]) throws Exception {

    CommandLine cmd = parseCommandLine(args);

    if (cmd.hasOption("help")) {
        usage();

        System.exit(0);
    }

    long startTimestamp = cmd.getOptionValue("timestamp") != null
            ? Long.parseLong(cmd.getOptionValue("timestamp"))
            : DEFAULT_FIRST_TIMESTAMP;

    int batchSize = cmd.getOptionValue("batch-size") != null
            ? Integer.parseInt(cmd.getOptionValue("batch-size"))
            : DEFAULT_BATCH_SIZE;

    int batchCount = cmd.getOptionValue("batch-count") != null
            ? Integer.parseInt(cmd.getOptionValue("batch-count"))
            : DEFAULT_BATCH_COUNT;

    String longString = cmd.getOptionValue("long-string-length") != null
            ? getDummyStr(Integer.parseInt(cmd.getOptionValue("long-string-length")))
            : getDummyStr(DEFAULT_LONG_STRING_LENGTH);

    String shortString = cmd.getOptionValue("short-string-length") != null
            ? getDummyStr(Integer.parseInt(cmd.getOptionValue("short-string-length")))
            : getDummyStr(DEFAULT_SHORT_LONG_STRING_LENGTH);

    log.info("first timestamp: {}, batch-size: {}, batch-count: {}", startTimestamp, batchSize, batchCount);

    for (int i = 0; i < batchCount; ++i) {
        storeRecords(batchSize, startTimestamp++, longString, shortString);
    }

    log.info("{} records generated", batchCount * batchSize);
}

From source file:es.upm.oeg.tools.quality.ldsniffer.cmd.LDSnifferApp.java

public static void main(String[] args) {

    HelpFormatter help = new HelpFormatter();
    String header = "Assess a list of Linked Data resources using Linked Data Quality Model.";
    String footer = "Please report issues at https://github.com/nandana/ld-sniffer";

    try {/*from   w w w. j  a  va  2  s .c  o m*/
        CommandLine line = parseArguments(args);
        if (line.hasOption("help")) {
            help.printHelp("LDSnifferApp", header, OPTIONS, footer, true);
            System.exit(0);
        }

        evaluationTimeout = Integer.parseInt(line.getOptionValue("t", "10"));

        if (line.hasOption("md")) {
            includeMetricDefinitions = true;
        }
        if (line.hasOption("rdf")) {
            rdfOutput = true;
        }

        logger.info("URL List: " + line.getOptionValue("ul"));
        logger.info("TDB Path: " + line.getOptionValue("tdb"));
        logger.info("Metrics Path: " + line.getOptionValue("ml"));
        logger.info("Include Metric definitions: " + line.getOptionValue("ml"));
        logger.info("RDF output: " + line.getOptionValue("rdf"));
        logger.info("Timeout (mins): " + evaluationTimeout);

        if (line.hasOption("ml")) {
            Path path = Paths.get(line.getOptionValue("ml"));
            if (!Files.exists(path)) {
                throw new IOException(path.toAbsolutePath().toString() + " : File doesn't exit.");
            }
        }

        //Set the TDB path
        String tdbDirectory;
        if (line.hasOption("tdb")) {
            tdbDirectory = line.getOptionValue("tdb");
        } else {
            Path tempPath = Files.createTempDirectory("tdb_");
            tdbDirectory = tempPath.toAbsolutePath().toString();
        }

        // Create the URL list for the evaluation
        if (!line.hasOption("ul") && !line.hasOption("url")) {
            System.out.println("One of the following parameters are required: url or urlList ");
            help.printHelp("LDSnifferApp", header, OPTIONS, footer, true);
            System.exit(0);
        } else if (line.hasOption("ul") && line.hasOption("url")) {
            System.out.println("You have to specify either url or urlList, not both.");
            help.printHelp("LDSnifferApp", header, OPTIONS, footer, true);
            System.exit(0);
        }

        List<String> urlList = null;
        if (line.hasOption("ul")) {
            Path path = Paths.get(line.getOptionValue("ul"));
            logger.info("Path : " + path.toAbsolutePath().toString());
            logger.info("Path exits : " + Files.exists(path));
            urlList = Files.readAllLines(path, Charset.defaultCharset());
        } else if (line.hasOption("url")) {
            urlList = new ArrayList<>();
            urlList.add(line.getOptionValue("url"));
        }

        Executor executor = new Executor(tdbDirectory, urlList);
        executor.execute();

    } catch (MissingOptionException e) {
        help.printHelp("LDSnifferApp", header, OPTIONS, footer, true);
        logger.error("Missing arguments.  Reason: " + e.getMessage(), e);
        System.exit(1);
    } catch (ParseException e) {
        logger.error("Parsing failed.  Reason: " + e.getMessage(), e);
        System.exit(1);
    } catch (IOException e) {
        logger.error("Execution failed.  Reason: " + e.getMessage(), e);
        System.exit(1);
    }

}

From source file:com.mosso.client.cloudfiles.sample.FilesList.java

public static void main(String args[]) {
    //Build the command line options
    Options options = addCommandLineOptions();

    if (args.length <= 0)
        printHelp(options);//from  w  w  w. jav  a 2 s  .  c  o  m

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help"))
            printHelp(options);

        if (line.hasOption("containersOnly")) {
            if (line.hasOption("H"))
                printContainers(true);
            else
                printContainers(false);
        } else if (line.hasOption("all")) {
            if (line.hasOption("H"))
                printContainersAll(true);
            else
                printContainersAll(false);
        } //if (line.hasOption("all"))
        else if (line.hasOption("container")) {
            String containerName = line.getOptionValue("container");
            if (StringUtils.isNotBlank(containerName)) {
                if (line.hasOption("H"))
                    printContainer(containerName, true);
                else
                    printContainer(containerName, false);
            }
        } //if (line.hasOption("container"))
        else if (line.hasOption("H")) {
            System.out.println(
                    "This option needs to be used in conjunction with another option that lists objects or container.");
        }
    } catch (ParseException err) {
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
        err.printStackTrace(System.err);
    } //catch( ParseException err )
    catch (FilesException err) {
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch (FilesAuthorizationException err)

    catch (IOException err) {
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch ( IOException err)
}

From source file:eu.scape_project.droid_identify.DroidIdentification.java

public static void main(String[] args)
        throws ParseException, IOException, InterruptedException, ClassNotFoundException {
    CommandLineParser cmdParser = new PosixParser();

    DroidCliOptions droidCliOpts = new DroidCliOptions();
    appConfig = new DroidCliConfig();

    CommandLine cmd = cmdParser.parse(droidCliOpts.options, args);
    if ((args.length == 0) || (cmd.hasOption(droidCliOpts.HELP_OPT))) {
        droidCliOpts.exit("Help", 0);
    } else {// ww  w. ja  va 2  s.c  o  m
        droidCliOpts.initOptions(cmd, appConfig);
        DroidIdentification tc = new DroidIdentification();
        if (appConfig.isLocal()) {
            tc.startApplication();
        } else {
            tc.startHadoopJob();
        }
    }
}

From source file:CountandraServer.java

public static void main(String args[]) {

    try {/*from  w  w  w.j a va 2s  .c  o  m*/
        System.out.println(args[0]);

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

        if (line.hasOption("cassandrahostip")) {
            CountandraUtils.setCassandraHostIp(line.getOptionValue("cassandrahostip"));
            if (line.hasOption("consistencylevel")) {
                if (line.hasOption("replicationfactor")) {

                    CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip"),
                            line.getOptionValue("consistencylevel"));
                    CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip"),
                            line.getOptionValue("replicationfactor"));

                } else {

                    CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip"),
                            line.getOptionValue("consistencylevel"));
                    CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip"));

                }
            }

            else { // no consistency level -- assumed to be ONE
                if (line.hasOption("replicationfactor")) {

                    CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip"));
                    CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip"),
                            line.getOptionValue("replicationfactor"));

                } else {

                    CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip"));
                    CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip"));

                }
            }
        } else {
            CassandraStorage.setGlobalParams(cassandraServerForClient);
            CassandraDB.setGlobalParams(cassandraServerForClient);
        }

        if (line.hasOption("s")) {
            System.out.println("Starting Cassandra");
            // cassandra server
            CassandraUtils.startupCassandraServer();

        }
        if (line.hasOption("i")) {
            System.out.print("Checking if Cassandra is initialized");
            CassandraDB csdb = new CassandraDB();
            while (!csdb.isCassandraUp()) {
                System.out.print(".");
            }
            System.out.println(".");
            System.out.println("Initializing Basic structures");
            CountandraUtils.initBasicDataStructures();
            System.out.println("Initialized Basic structures");

        }

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

            if (line.hasOption("httpserverport")) {
                httpPort = Integer.parseInt(line.getOptionValue("httpserverport"));
            }
            NettyUtils.startupNettyServer(httpPort);
            System.out.println("Started Http Server");
        }

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

            KafkaUtils.startupKafkaConsumer();
            System.out.println("Started Kafka Consumer");
        }

        // Unit Tests
        if (line.hasOption("t")) {
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            org.junit.runner.JUnitCore.main(CountandraTestCases.class.getName());
        }

    } catch (IOException ioe) {
        System.out.println(ioe);
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:galen.api.server.GalenApiServer.java

public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    Options options = defineCommandOptions();
    HelpFormatter formatter = new HelpFormatter();
    try {/*  w ww . j  ava2 s  . c o m*/
        CommandLine commandLine = parser.parse(options, args);

        if (asList(args).size() == 0) {
            formatter.printHelp("galen-api-server", options);
            System.exit(0);
        } else if (commandLine.hasOption("help")) {
            formatter.printHelp("galen-api-server", options);
        } else if (commandLine.hasOption("run")) {
            String port = commandLine.getOptionValue("run");
            int serverPort = valueOf(port);
            handler = new GalenCommandExecutor();
            processor = new GalenApiRemoteService.Processor(handler);
            log.info("Starting server on port " + serverPort);
            runService(processor, serverPort);

        }
    } catch (ParseException e) {
        System.out.print("Invalid usage: ");
        System.out.println(e.getMessage());
        formatter.printHelp("galen-api-server", options);
    }
}

From source file:gdv.xport.Main.java

/**
 * Diese Main-Klasse dient hautpsaechlich zu Demo-Zwecken. Werden keine Optionen angegeben, wird von der
 * Standard-Eingabe (System.in) gelesen und das Ergebnis nach System.out geschrieben. <br/>
 * Mit "-help" bekommt man eine kleine Uebersicht der Optionen.
 *
 * @param args//from w w w .j  a  v a2s. com
 *            die verschiendene Argumente (z.B. -import
 *            http://www.gdv-online.de/vuvm/musterdatei_bestand/musterdatei_041222.txt -validate -xml)
 * @throws IOException
 *             falls der Import oder Export schief gegangen ist
 * @throws XMLStreamException
 *             falls bei der XML-Generierung was schief gelaufen ist.
 */
public static void main(final String[] args) throws IOException, XMLStreamException {
    Options options = createOptions();
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        // Option "-help"
        if (cmd.hasOption("help")) {
            printHelp(options);
            System.exit(0);
        }
        Datenpaket datenpaket = importDatenpaket(cmd);
        formatDatenpaket(cmd, datenpaket);
        // Option "-validate"
        if (cmd.hasOption("validate")) {
            printViolations(datenpaket.validate());
        }
    } catch (ParseException ex) {
        LOG.log(Level.SEVERE, "Cannot parse " + Arrays.toString(args), ex);
        System.err.println("Fehler beim Aufruf von " + Main.class);
        printHelp(options);
        System.exit(1);
    }
}

From source file:com.rackspacecloud.client.cloudfiles.sample.FilesList.java

public static void main(String args[]) {
    //Build the command line options
    Options options = addCommandLineOptions();

    if (args.length <= 0)
        printHelp(options);//ww  w . ja  v a2s .c  om

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help"))
            printHelp(options);

        if (line.hasOption("containersOnly")) {
            if (line.hasOption("H"))
                printContainers(true);
            else
                printContainers(false);
        } else if (line.hasOption("all")) {
            if (line.hasOption("H"))
                printContainersAll(true);
            else
                printContainersAll(false);
        } //if (line.hasOption("all"))
        else if (line.hasOption("container")) {
            String containerName = line.getOptionValue("container");
            if (StringUtils.isNotBlank(containerName)) {
                if (line.hasOption("H"))
                    printContainer(containerName, true);
                else
                    printContainer(containerName, false);
            }
        } //if (line.hasOption("container"))
        else if (line.hasOption("H")) {
            System.out.println(
                    "This option needs to be used in conjunction with another option that lists objects or container.");
        }
    } catch (ParseException err) {
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
        err.printStackTrace(System.err);
    } //catch( ParseException err )
    catch (HttpException err) {
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
        err.printStackTrace(System.err);
    } //catch( ParseException err )

    catch (IOException err) {
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch ( IOException err)
}

From source file:edu.msu.cme.rdp.classifier.train.validation.distance.PairwiseSeqDistance.java

/**
* This program does the pairwise alignment between each pair of sequences, 
* reports a summary of the average distances and the stdev at each rank.
* @param args/*from www .j av  a2  s  .com*/
* @throws Exception 
*/
public static void main(String[] args) throws Exception {

    String trainseqFile = null;
    String taxFile = null;
    PrintStream outStream = null;
    AlignmentMode mode = AlignmentMode.overlap;
    boolean show_alignment = false;

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

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

        }

        if (args.length != 3) {
            throw new Exception("wrong arguments");
        }
        args = line.getArgs();
        trainseqFile = args[0];
        taxFile = args[1];
        outStream = new PrintStream(new File(args[2]));
    } catch (Exception e) {
        System.err.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(80, " [options] trainseqFile taxonFile outFile", "", options, "");
        return;
    }

    PairwiseSeqDistance theObj = new PairwiseSeqDistance(trainseqFile, taxFile, mode, show_alignment);

    theObj.printSummary(outStream);
}

From source file:com.novadart.silencedetect.SilenceDetect.java

public static void main(String[] args) {

    // create the parser
    CommandLineParser parser = new BasicParser();
    try {//from w  w w.ja  v a 2  s  .c  om
        // parse the command line arguments
        CommandLine line = parser.parse(OPTIONS, args);

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

            printHelp();

        } else {

            String decibels = "-10";
            if (line.hasOption("b")) {
                decibels = "-" + line.getOptionValue("b");
            } else {
                throw new RuntimeException();
            }

            String videoFile = null;

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

                videoFile = line.getOptionValue("i");

                Boolean debug = line.hasOption("d");

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

                    System.out.println(printAudioTracksList(videoFile, debug));

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

                    int trackNumber = Integer.parseInt(line.getOptionValue("s"));
                    System.out.println(printAudioTrackSilenceDuration(videoFile, trackNumber, decibels, debug));

                } else {

                    printHelp();

                }

            } else if (line.hasOption("-j")) {

                // choose file
                final JFileChooser fc = new JFileChooser();
                fc.setVisible(true);
                int returnVal = fc.showOpenDialog(null);
                if (returnVal == JFileChooser.APPROVE_OPTION) {

                    videoFile = fc.getSelectedFile().getAbsolutePath();

                } else {
                    return;
                }

                JTextArea tracks = new JTextArea();
                tracks.setText(printAudioTracksList(videoFile, true));
                JSpinner trackNumber = new JSpinner();
                trackNumber.setValue(1);
                final JComponent[] inputs = new JComponent[] { new JLabel("Audio Tracks"), tracks,
                        new JLabel("Track to analyze"), trackNumber };
                JOptionPane.showMessageDialog(null, inputs, "Select Audio Track", JOptionPane.PLAIN_MESSAGE);

                JTextArea results = new JTextArea();
                results.setText(printAudioTrackSilenceDuration(videoFile, (int) trackNumber.getValue(),
                        decibels, false));
                final JComponent[] resultsInputs = new JComponent[] { new JLabel("Results"), results };
                JOptionPane.showMessageDialog(null, resultsInputs, "RESULTS!", JOptionPane.PLAIN_MESSAGE);

            } else {
                printHelp();
                return;
            }

        }

    } catch (ParseException | IOException | InterruptedException exp) {
        // oops, something went wrong
        System.out.println("There was a problem :(\nReason: " + exp.getMessage());
    }
}