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

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

Introduction

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

Prototype

public String getOptionValue(char opt) 

Source Link

Document

Retrieve the argument, if any, of this option.

Usage

From source file:com.yahoo.athenz.example.instance.InstanceClientRefresh.java

public static void main(String[] args) throws MalformedURLException, IOException {

    // parse our command line to retrieve required input

    CommandLine cmd = parseCommandLine(args);

    String domainName = cmd.getOptionValue("domain").toLowerCase();
    String serviceName = cmd.getOptionValue("service").toLowerCase();
    String provider = cmd.getOptionValue("provider").toLowerCase();
    String instance = cmd.getOptionValue("instance");
    String dnsSuffix = cmd.getOptionValue("dnssuffix");
    String instanceKeyPath = cmd.getOptionValue("instancekey");
    String ztsUrl = cmd.getOptionValue("ztsurl");

    // now we need to generate our CSR so we can get
    // a TLS certificate for our instance

    PrivateKey instanceKey = Crypto.loadPrivateKey(new File(instanceKeyPath));
    String csr = generateCSR(domainName, serviceName, instance, dnsSuffix, instanceKey);

    if (csr == null) {
        System.err.println("Unable to generate CSR for instance");
        System.exit(1);/*  ww  w  .  j ava2 s .c  om*/
    }
    System.out.println("CSR: \n" + csr + "\n");

    // now let's generate our instance refresh object that will be sent
    // to the ZTS Server

    InstanceRefreshInformation info = new InstanceRefreshInformation().setToken(true).setCsr(csr);

    // now contact zts server to request identity for instance

    InstanceIdentity identity = null;
    try (ZTSClient ztsClient = new ZTSClient(ztsUrl)) {
        identity = ztsClient.postInstanceRefreshInformation(provider, domainName, serviceName, instance, info);
    } catch (ZTSClientException ex) {
        System.out.println("Unable to register instance: " + ex.getMessage());
        System.exit(2);
    }

    System.out.println("Identity TLS Certificate: \n" + identity.getX509Certificate());
}

From source file:edu.msu.cme.rdp.readseq.ToFasta.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("m", "mask", true, "Mask sequence name indicating columns to drop");
    String maskSeqid = null;//from   ww  w  .j ava2 s .c o  m

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

        if (line.hasOption("mask")) {
            maskSeqid = line.getOptionValue("mask");
        }

        args = line.getArgs();
        if (args.length == 0) {
            throw new Exception("");
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("USAGE: to-fasta <input-file>", options);
        System.err.println("ERROR: " + e.getMessage());
        System.exit(1);
        return;
    }

    SeqReader reader = null;

    FastaWriter out = new FastaWriter(System.out);
    Sequence seq;
    int totalSeqs = 0;
    long totalTime = System.currentTimeMillis();

    for (String fname : args) {
        if (fname.equals("-")) {
            reader = new SequenceReader(System.in);
        } else {
            File seqFile = new File(fname);

            if (maskSeqid == null) {
                reader = new SequenceReader(seqFile);
            } else {
                reader = new IndexedSeqReader(seqFile, maskSeqid);
            }
        }

        long startTime = System.currentTimeMillis();
        int thisFileTotalSeqs = 0;
        while ((seq = reader.readNextSequence()) != null) {
            out.writeSeq(seq.getSeqName().replace(" ", "_"), seq.getDesc(), seq.getSeqString());
            thisFileTotalSeqs++;
        }
        totalSeqs += thisFileTotalSeqs;
        System.err.println("Converted " + thisFileTotalSeqs + " (total sequences: " + totalSeqs
                + ") sequences from " + fname + " (" + reader.getFormat() + ") to fasta in "
                + (System.currentTimeMillis() - startTime) / 1000 + " s");
    }
    System.err.println("Converted " + totalSeqs + " to fasta in "
            + (System.currentTimeMillis() - totalTime) / 1000 + " s");

    out.close();
}

From source file:gr.forth.ics.isl.preprocessfilter2.controller.Controller.java

public static void main(String[] args) throws XPathExpressionException, ParserConfigurationException,
        SAXException, IOException, PreprocessFilterException, TransformerException, ParseException {
    PropertyReader prop = new PropertyReader();

    //The following block of code is executed if there are arguments from the command line
    if (args.length > 0) {

        try {//w  ww .  j  a v a 2 s.  c o  m
            Options options = new Options();
            CommandLineParser PARSER = new PosixParser();
            Option inputFile = new Option("inputFile", true, "input xml file");
            Option outputFile = new Option("outputFile", true, "output xml file");
            Option parentNode = new Option("parentNode", true, "output xml file");
            Option newValuesFile = new Option("newValuesFile", true, "new values xml file");
            Option newParentNode = new Option("newParentNode", true, "new parent node");
            Option newValueTag = new Option("newValueTag", true, "new value tag");
            Option oldValueTag = new Option("oldValueTag", true, "old value tag");
            Option sameValueTag = new Option("sameValueTag", true, "same value tag");
            Option createNewValues = new Option("createNewValues", true, "create new values option");
            options.addOption(inputFile).addOption(outputFile).addOption(parentNode).addOption(newValuesFile)
                    .addOption(newParentNode).addOption(newValueTag).addOption(oldValueTag)
                    .addOption(sameValueTag).addOption(createNewValues);
            CommandLine cli = PARSER.parse(options, args);
            String inputFileArg = cli.getOptionValue("inputFile");
            String outputFileArg = cli.getOptionValue("outputFile");
            String parentNodeArg = cli.getOptionValue("parentNode");
            String newValuesFileArg = cli.getOptionValue("newValuesFile");
            String newParentNodeArg = cli.getOptionValue("newParentNode");
            String newValueTagArg = cli.getOptionValue("newValueTag");
            String oldValueTagArg = cli.getOptionValue("oldValueTag");
            String sameValueTagArg = cli.getOptionValue("sameValueTag");
            String createNewValuesArg = cli.getOptionValue("createNewValues");
            PreprocessFilterUtilities process = new PreprocessFilterUtilities();
            if (createNewValuesArg.equals("yes")) {
                if (process.createNewValuesFile(inputFileArg, newValuesFileArg, parentNodeArg)) {
                    System.out.println("Succesfull PreProcessing!!!");
                }
            } else {
                if (process.createOutputFile(inputFileArg, outputFileArg, parentNodeArg, newParentNodeArg,
                        newValueTagArg, oldValueTagArg, sameValueTagArg, newValuesFileArg)) {
                    System.out.println("Succesfull PreProcessing!!!");
                }
            }
        } catch (PreprocessFilterException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            throw new PreprocessFilterException("PreProcess Filter Exception:", ex);
        }

    } //If there are no command line arguments then the .config file is being used.
    else {

        try {
            String inputFilePathProp = prop.getProperty(inputFilePath);
            String outputFilePathProp = prop.getProperty(outputFilePath);
            String parentNodeProp = prop.getProperty(parentNode);

            String newValuesFilePathProp = prop.getProperty(newValuesFilePath);
            String newParentNodeProp = prop.getProperty(newParentNode);
            String newValueTagProp = prop.getProperty(newValueTag);
            String oldValueTagProp = prop.getProperty(oldValueTag);
            String sameValueTagProp = prop.getProperty(sameValueTag);
            String createNewValuesFileProp = prop.getProperty(createNewValuesFile);

            PreprocessFilterUtilities process = new PreprocessFilterUtilities();

            //The filter's code is executed with the .config file's resources as parameters
            if (createNewValuesFileProp.equals("yes")) {
                process.createNewValuesFile(inputFilePathProp, newValuesFilePathProp, parentNodeProp);
            } else {
                process.createOutputFile(inputFilePathProp, outputFilePathProp, parentNodeProp,
                        newParentNodeProp, newValueTagProp, oldValueTagProp, sameValueTagProp,
                        newValuesFilePathProp);
            }
        } catch (PreprocessFilterException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            throw new PreprocessFilterException("PreProcess Filter Exception:", ex);
        }
    }

}

From source file:Homework4Execute.java

/**
 * @param args//from w w  w  . ja  v a  2s  . c o m
 */
public static void main(String[] args) {
    Parser parser = new GnuParser();
    Options options = getCommandLineOptions();
    String task = null;
    String host = null;
    String dir = null;
    CommandLine commandLine = null;
    try {
        commandLine = parser.parse(options, args);
        task = (String) commandLine.getOptionValue("task");
        if ("traceroute".equals(task) || "cmdWinTrace".equals(task)) {
            host = (String) commandLine.getOptionValue("host");
            if (host == null) {
                System.err.println("--host parameter required at this task!");
                System.exit(-1);
            }
        }
        if ("cmdWinDir".equals(task)) {
            dir = (String) commandLine.getOptionValue("dir");
            if (dir == null) {
                System.err.println("--dir parameter required at this task!");
                System.exit(-1);
            }
        }
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar homework4execute.jar", options);
        System.exit(-1);
    }

    if (task != null) {
        switch (task) {
        case "enviroment":
            PrintEnviroment.printEnviroment();
            break;
        case "traceroute":
            RedirectOutput2Pipe.traceroute(host);
            break;
        case "cmdWinTrace":
            ProcessBuilderExecute.cmdWinTrace(host);
            break;
        case "cmdWinDir":
            RuntimeExecute.cmdWinDir(dir);
            break;
        case "uname":
            RedirectOutput2File.getUname();
            break;
        }
    } else {
        RunWithThread.executeCommand("javac Teszt.java");
        RunWithThread.executeCommand("java -cp ./ Teszt");
    }
}

From source file:cloudlens.cli.Main.java

public static void main(String[] args) throws Exception {
    final CommandLineParser optionParser = new DefaultParser();
    final HelpFormatter formatter = new HelpFormatter();

    final Option lens = Option.builder("r").longOpt("run").hasArg().argName("lens file").desc("Lens file.")
            .required(true).build();//from w w  w. jav a  2  s . c o m
    final Option log = Option.builder("l").longOpt("log").hasArg().argName("log file").desc("Log file.")
            .build();
    final Option jsonpath = Option.builder().longOpt("jsonpath").hasArg().argName("path")
            .desc("Path to logs in a json object.").build();
    final Option js = Option.builder().longOpt("js").hasArg().argName("js file").desc("Load JS file.").build();
    final Option format = Option.builder("f").longOpt("format").hasArg()
            .desc("Choose log format (text or json).").build();
    final Option streaming = Option.builder().longOpt("stream").desc("Streaming mode.").build();
    final Option history = Option.builder().longOpt("history").desc("Store history.").build();

    final Options options = new Options();
    options.addOption(log);
    options.addOption(lens);
    options.addOption(format);
    options.addOption(jsonpath);
    options.addOption(js);
    options.addOption(streaming);
    options.addOption(history);

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

        final String jsonPath = cmd.getOptionValue("jsonpath");
        final String[] jsFiles = cmd.getOptionValues("js");
        final String[] lensFiles = cmd.getOptionValues("run");
        final String[] logFiles = cmd.getOptionValues("log");
        final String source = cmd.getOptionValue("format");

        final boolean stream = cmd.hasOption("stream") || !cmd.hasOption("log");
        final boolean withHistory = cmd.hasOption("history") || !stream;

        final CL cl = new CL(System.out, System.err, stream, withHistory);

        try {
            final InputStream input = (cmd.hasOption("log")) ? FileReader.readFiles(logFiles) : System.in;

            if (source == null) {
                cl.source(input);
            } else {
                switch (source) {
                case "text":
                    cl.source(input);
                    break;
                case "json":
                    cl.json(input, jsonPath);
                    break;
                default:
                    input.close();
                    throw new CLException("Unsupported format: " + source);
                }
            }

            for (final String jsFile : FileReader.fullPaths(jsFiles)) {
                cl.engine.eval("CL.loadjs('file://" + jsFile + "')");
            }

            final List<ASTElement> top = ASTBuilder.parseFiles(lensFiles);
            cl.launch(top);

        } catch (final CLException | ASTException e) {
            cl.errWriter.println(e.getMessage());
        } finally {
            cl.outWriter.flush();
            cl.errWriter.flush();
        }
    } catch (final ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("cloudlens", options);
    }
}

From source file:com.ehi.carshare.Main.java

/**
 * @param args/*ww w .  ja  v  a 2s  .c o  m*/
 *            The commandline arguments
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public static void main(final String[] args) throws Exception {
    // create the command line parser
    CommandLineParser parser = new BasicParser();

    // create the Options
    Options options = new Options();
    options.addOption(buildOption("l", "logFormat", "The apache logformat"));
    options.addOption(buildOption("i", "inputFile", "complete path to the input file"));
    options.addOption(buildOption("o", "outputFile", "complete path to the output file"));

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String logformat = line.getOptionValue('l');
        String inputFile = line.getOptionValue('i');
        String outputFile = line.getOptionValue('o');
        new Main().run(logformat, inputFile, outputFile);

    } catch (ParseException exp) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("myapp", "", options, "", true);
    }

}

From source file:com.example.bigquery.QuerySample.java

/** Prompts the user for the required parameters to perform a query. */
public static void main(final String[] args)
        throws IOException, InterruptedException, TimeoutException, ParseException {
    Options options = new Options();

    // Use an OptionsGroup to choose which sample to run.
    OptionGroup samples = new OptionGroup();
    samples.addOption(Option.builder().longOpt("runSimpleQuery").build());
    samples.addOption(Option.builder().longOpt("runStandardSqlQuery").build());
    samples.addOption(Option.builder().longOpt("runPermanentTableQuery").build());
    samples.addOption(Option.builder().longOpt("runUncachedQuery").build());
    samples.addOption(Option.builder().longOpt("runBatchQuery").build());
    samples.isRequired();//w ww  . j av  a  2 s  .com
    options.addOptionGroup(samples);

    options.addOption(Option.builder().longOpt("query").hasArg().required().build());
    options.addOption(Option.builder().longOpt("destDataset").hasArg().build());
    options.addOption(Option.builder().longOpt("destTable").hasArg().build());
    options.addOption(Option.builder().longOpt("allowLargeResults").build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    String query = cmd.getOptionValue("query");
    if (cmd.hasOption("runSimpleQuery")) {
        runSimpleQuery(query);
    } else if (cmd.hasOption("runStandardSqlQuery")) {
        runStandardSqlQuery(query);
    } else if (cmd.hasOption("runPermanentTableQuery")) {
        String destDataset = cmd.getOptionValue("destDataset");
        String destTable = cmd.getOptionValue("destTable");
        boolean allowLargeResults = cmd.hasOption("allowLargeResults");
        runQueryPermanentTable(query, destDataset, destTable, allowLargeResults);
    } else if (cmd.hasOption("runUncachedQuery")) {
        runUncachedQuery(query);
    } else if (cmd.hasOption("runBatchQuery")) {
        runBatchQuery(query);
    }
}

From source file:FullReindexer.java

public static void main(String[] args) throws IOException {
    if (args == null || args.length == 0) {
        help();// w  ww.  j  a  va  2s .  c  o  m
        System.exit(1);
    }

    final CommandLine cli = parseCli(args);

    FullReindexer fullReindexer = new FullReindexer(cli.getOptionValue("source"), cli.getOptionValue("dest"),
            cli.getOptionValue("zk"), Integer.parseInt(cli.getOptionValue("n")));

    System.out.println("Starting to reindex.");

    fullReindexer.reindex();

    System.out.println("Completed reindexing.");

}

From source file:edu.cmu.tetrad.cli.data.sim.DiscreteTabularData.java

/**
 * @param args the command line arguments
 */// w  w  w .  j  a  va2 s  .c o  m
public static void main(String[] args) {
    if (args == null || args.length == 0 || Args.hasLongOption(args, "help")) {
        Args.showHelp("simulate-discrete-data", MAIN_OPTIONS);
        return;
    }

    try {
        CommandLineParser cmdParser = new DefaultParser();
        CommandLine cmd = cmdParser.parse(MAIN_OPTIONS, args);

        numOfVars = Args.getIntegerMin(cmd.getOptionValue("variable"), 0);
        numOfCases = Args.getIntegerMin(cmd.getOptionValue("case"), 0);
        edgeFactor = Args.getDoubleMin(cmd.getOptionValue("edge"), 1.0);
    } catch (ParseException exception) {
        System.err.println(exception.getLocalizedMessage());
        Args.showHelp("simulate-discrete-data", MAIN_OPTIONS);
        System.exit(-127);
    }

    List<Node> vars = new ArrayList<>();
    for (int i = 0; i < numOfVars; i++) {
        vars.add(new ContinuousVariable("X" + i));
    }
    Graph graph = GraphUtils.randomGraphRandomForwardEdges(vars, 0, (int) (numOfVars * edgeFactor), 30, 12, 15,
            false, true);
    BayesPm pm = new BayesPm(graph, 3, 3);
    BayesIm im = new MlBayesIm(pm, MlBayesIm.RANDOM);
    DataSet data = im.simulateData(numOfCases, false);

    String[] variables = data.getVariableNames().toArray(new String[0]);
    int lastIndex = variables.length - 1;
    for (int i = 0; i < lastIndex; i++) {
        System.out.printf("%s,", variables[i]);
    }
    System.out.printf("%s%n", variables[lastIndex]);

    DataBox dataBox = ((BoxDataSet) data).getDataBox();
    VerticalIntDataBox box = (VerticalIntDataBox) dataBox;
    //        int[][] matrix = box.getVariableVectors();
    //        int numOfColumns = matrix.length;
    //        int numOfRows = matrix[0].length;
    //        int[][] dataset = new int[numOfRows][numOfColumns];
    //        for (int i = 0; i < matrix.length; i++) {
    //            for (int j = 0; j < matrix[i].length; j++) {
    //                dataset[j][i] = matrix[i][j];
    //            }
    //        }
    //        for (int[] rowData : dataset) {
    //            lastIndex = rowData.length - 1;
    //            for (int i = 0; i < lastIndex; i++) {
    //                System.out.printf("%d,", rowData[i]);
    //            }
    //            System.out.printf("%s%n", rowData[lastIndex]);
    //        }
}

From source file:edu.indiana.d2i.sloan.internal.QueryVMSimulator.java

public static void main(String[] args) {
    QueryVMSimulator simulator = new QueryVMSimulator();

    CommandLineParser parser = new PosixParser();

    try {//from w  w w .  j a va2  s .  com
        CommandLine line = simulator.parseCommandLine(parser, args);
        String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR));

        if (!HypervisorCmdSimulator.resourceExist(wdir)) {
            logger.error(String.format("Cannot find VM working dir: %s", wdir));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_EXIST));
        }

        Properties prop = new Properties();
        String filename = HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME;

        prop.load(new FileInputStream(new File(filename)));

        VMStatus status = new VMStatus(
                VMMode.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE))),
                VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE))), ip,
                Integer.parseInt(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VNC_PORT))),
                Integer.parseInt(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.SSH_PORT))),
                Integer.parseInt(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VCPU))),
                Integer.parseInt(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.MEM))));

        // write state query file so shell script can read the vm state info
        filename = HypervisorCmdSimulator.cleanPath(wdir) + QueryVMSimulator.QUERY_RES_FILE_NAME;
        FileUtils.writeStringToFile(new File(filename), status.toString(), Charset.forName("UTF-8"));

    } catch (ParseException e) {
        logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s",
                StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, "")));

        System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR));
    }

}