Example usage for org.apache.commons.cli CommandLineParser parse

List of usage examples for org.apache.commons.cli CommandLineParser parse

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLineParser parse.

Prototype

CommandLine parse(Options options, String[] arguments) throws ParseException;

Source Link

Document

Parse the arguments according to the specified options.

Usage

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

/**
 * Ramps up the server/* w ww . ja  v  a2 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:com.runwaysdk.system.metadata.MetadataPatcher.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("vendor").hasArg()
            .withDescription("Database vendor [" + POSTGRESQL + "]").isRequired().create("d"));
    options.addOption(OptionBuilder.withArgName("username").hasArg().withDescription("Database username")
            .isRequired().create("u"));
    options.addOption(OptionBuilder.withArgName("password").hasArg().withDescription("Database password")
            .isRequired().create("p"));
    options.addOption(// w w  w  . ja v a 2s  . co  m
            OptionBuilder.withArgName("url").hasArg().withDescription("Database URL").isRequired().create("l"));

    CommandLineParser parser = new BasicParser();

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

        MetadataPatcher patcher = new MetadataPatcher();
        patcher.setDbms(cmd.getOptionValue("d"));
        patcher.setUserid(cmd.getOptionValue("u"));
        patcher.setPassword(cmd.getOptionValue("p"));
        patcher.setUrl(cmd.getOptionValue("l"));
        patcher.run();
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    } catch (RuntimeException exp) {
        System.err.println("Patching failed. Reason: " + exp.getMessage());
    }
}

From source file:de.akquinet.dustjs.DustEngine.java

public static void main(String[] args) throws URISyntaxException {
    Options cmdOptions = new Options();
    cmdOptions.addOption(DustOptions.CHARSET_OPTION, true, "Input file charset encoding. Defaults to UTF-8.");
    cmdOptions.addOption(DustOptions.DUST_OPTION, true, "Path to a custom dust.js for Rhino version.");
    try {//from   w  w w  . j  a v  a  2s.  c  om
        CommandLineParser cmdParser = new GnuParser();
        CommandLine cmdLine = cmdParser.parse(cmdOptions, args);
        DustOptions options = new DustOptions();
        if (cmdLine.hasOption(DustOptions.CHARSET_OPTION)) {
            options.setCharset(cmdLine.getOptionValue(DustOptions.CHARSET_OPTION));
        }
        if (cmdLine.hasOption(DustOptions.DUST_OPTION)) {
            options.setDust(new File(cmdLine.getOptionValue(DustOptions.DUST_OPTION)).toURI().toURL());
        }
        DustEngine engine = new DustEngine(options);
        String[] files = cmdLine.getArgs();

        String src = null;
        if (files == null || files.length == 0) {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            StringWriter sw = new StringWriter();
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = in.read(buffer))) {
                sw.write(buffer, 0, n);
            }
            src = sw.toString();
        }

        if (src != null && !src.isEmpty()) {
            System.out.println(engine.compile(src, "test"));
            return;
        }

        if (files.length == 1) {
            System.out.println(engine.compile(new File(files[0])));
            return;
        }

        if (files.length == 2) {
            engine.compile(new File(files[0]), new File(files[1]));
            return;
        }

    } catch (IOException ioe) {
        System.err.println("Error opening input file.");
    } catch (ParseException pe) {
        System.err.println("Error parsing arguments.");
    }

    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("java -jar dust-engine.jar input [output] [options]", cmdOptions);
    System.exit(1);
}

From source file:SequentialPageRank.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
    options.addOption(/*from   w ww . j  a  v  a  2s  .  com*/
            OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));

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

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(SequentialPageRank.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String infile = cmdline.getOptionValue(INPUT);
    float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;

    int edgeCnt = 0;
    DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();

    BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));

    String line;
    while ((line = data.readLine()) != null) {
        line.trim();
        String[] arr = line.split("\\t");

        for (int i = 1; i < arr.length; i++) {
            graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
        }
    }

    data.close();

    WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();

    Set<Set<String>> components = clusterer.transform(graph);
    int numComponents = components.size();
    System.out.println("Number of components: " + numComponents);
    System.out.println("Number of edges: " + graph.getEdgeCount());
    System.out.println("Number of nodes: " + graph.getVertexCount());
    System.out.println("Random jump factor: " + alpha);

    // Compute PageRank.
    PageRank<String, Integer> ranker = new PageRank<String, Integer>(graph, alpha);
    ranker.evaluate();

    // Use priority queue to sort vertices by PageRank values.
    PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
    int i = 0;
    for (String pmid : graph.getVertices()) {
        q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
    }

    // Print PageRank values.
    System.out.println("\nPageRank of nodes, in descending order:");
    Ranking<String> r = null;
    while ((r = q.poll()) != null) {
        System.out.println(r.rankScore + "\t" + r.getRanked());
    }
}

From source file:br.usp.poli.lta.cereda.wsn2spa.Main.java

public static void main(String[] args) {

    Utils.printBanner();//from  w  w  w.  ja v  a 2s.  c o  m
    CommandLineParser parser = new DefaultParser();

    try {

        CommandLine line = parser.parse(Utils.getOptions(), args);

        if (line.hasOption("g")) {
            System.out.println("Flag '-g' found, overriding other flags.");
            System.out.println("Please, wait...");
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception nothandled) {
            }
            SwingUtilities.invokeLater(() -> {
                Editor e = new Editor();
                e.setVisible(true);
            });
        } else {
            enableCLI(line);
        }
    } catch (ParseException nothandled) {
        Utils.printHelp();
    } catch (Exception exception) {
        Utils.printException(exception);
    }
}

From source file:info.bitoo.Main.java

public static void main(String[] args)
        throws InterruptedException, IOException, NoSuchAlgorithmException, ClientAdapterException {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/* www  .ja v a2s  .c  o m*/
    try {
        cmd = parser.parse(createCommandLineOptions(), args);
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());
    }

    Properties props = readConfiguration(cmd);
    BiToo biToo = new BiToo(props);

    URL torrentURL = null;

    if (cmd.hasOption("f")) {
        String parmValue = cmd.getOptionValue("f");
        String torrentName = parmValue + ".torrent";
        biToo.setTorrent(torrentName);
    } else if (cmd.hasOption("t")) {
        torrentURL = new URL(cmd.getOptionValue("t"));
        biToo.setTorrent(torrentURL);
    } else {
        return;
    }

    try {
        Thread main = new Thread(biToo);
        main.setName("BiToo");
        main.start();

        //wait until thread complete
        main.join();
    } finally {
        biToo.destroy();
    }

    if (biToo.isCompleted()) {
        System.out.println("Download completed");
        System.exit(0);
    } else {
        System.out.println("Download failed");
        System.exit(1);
    }

}

From source file:com.cws.esolutions.core.main.EmailUtility.java

public static final void main(final String[] args) {
    final String methodName = EmailUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {/*from  ww  w  .j a v a 2 s  .  c  om*/
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", (Object) args);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(EmailUtility.CNAME, options, true);

        return;
    }

    try {
        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        URL xmlURL = null;
        JAXBContext context = null;
        Unmarshaller marshaller = null;
        CoreConfigurationData configData = null;

        xmlURL = FileUtils.getFile(commandLine.getOptionValue("config")).toURI().toURL();
        context = JAXBContext.newInstance(CoreConfigurationData.class);
        marshaller = context.createUnmarshaller();
        configData = (CoreConfigurationData) marshaller.unmarshal(xmlURL);

        EmailMessage message = new EmailMessage();
        message.setMessageTo(new ArrayList<String>(Arrays.asList(commandLine.getOptionValues("to"))));
        message.setMessageSubject(commandLine.getOptionValue("subject"));
        message.setMessageBody((String) commandLine.getArgList().get(0));
        message.setEmailAddr((StringUtils.isNotEmpty(commandLine.getOptionValue("from")))
                ? new ArrayList<String>(Arrays.asList(commandLine.getOptionValue("from")))
                : new ArrayList<String>(Arrays.asList(configData.getMailConfig().getMailFrom())));

        if (DEBUG) {
            DEBUGGER.debug("EmailMessage: {}", message);
        }

        try {
            EmailUtils.sendEmailMessage(configData.getMailConfig(), message, false);
        } catch (MessagingException mx) {
            System.err.println(
                    "An error occurred while sending the requested message. Exception: " + mx.getMessage());
        }
    } catch (ParseException px) {
        px.printStackTrace();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(EmailUtility.CNAME, options, true);
    } catch (MalformedURLException mx) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(EmailUtility.CNAME, options, true);
    } catch (JAXBException jx) {
        jx.printStackTrace();
        System.err.println("An error occurred while loading the provided configuration file. Cannot continue.");
    }
}

From source file:com.twitter.heron.eco.Eco.java

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

    CommandLineParser parser = new DefaultParser();

    CommandLine cmd;/*ww  w .  ja  v a 2  s  .c  o m*/
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        throw new RuntimeException("Error parsing command line options: ", e);
    }

    FileInputStream fin = new FileInputStream(new File(cmd.getOptionValue(ECO_CONFIG_FILE)));

    String propsFile = cmd.getOptionValue(PROPS);
    FileInputStream propsInputStream = null;

    if (propsFile != null) {
        propsInputStream = new FileInputStream(new File(propsFile));
    }

    Boolean filterFromEnv = cmd.hasOption(ENV_PROPS);

    Eco eco = new Eco(new EcoBuilder(new SpoutBuilder(), new BoltBuilder(), new StreamBuilder(),
            new ComponentBuilder(), new ConfigBuilder()), new EcoParser(), new EcoSubmitter());

    eco.submit(fin, propsInputStream, filterFromEnv);
}

From source file:jo.jdk.jacoco_test.ReportGenerator.java

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

    Options options = new Options()
            .addOption(createOption("d", "dataFile", "Location of the Jacoco.exec file", "dir"))
            .addOption(createOption("c", "classes", "Location of the class files", "dir"))
            .addOption(createOption("s", "src", "Source directory", "dir"))
            .addOption(createOption("o", "outdir", "Resport output location", "dir"));

    CommandLineParser parser = new GnuParser();
    CommandLine cmd;//from  w  ww .j a  va  2  s  .  c om
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("gnu", options);
        return;
    }

    File executionDataFile = new File(cmd.getOptionValue("d"));
    File classesDirectory = new File(cmd.getOptionValue("c"));
    File sourceDirectory = new File(cmd.getOptionValue("s"));
    File reportDirectory = new File(cmd.getOptionValue("o"));

    final ReportGenerator generator = new ReportGenerator(executionDataFile, classesDirectory, sourceDirectory,
            reportDirectory);
    generator.create();
}

From source file:net.forkwait.imageautomator.ImageAutomator.java

public static void main(String[] args) throws IOException {
    String inputImage = "";

    Options options = new Options();
    options.addOption("o", true, "output file name (e.g. thumb.jpg), default thumbnail.filename.ext");
    options.addOption("q", true, "jpeg quality (e.g. 0.9, max 1.0), default 0.97");
    options.addOption("s", true, "output max side length in px (e.g. 800), default 1200");
    options.addOption("w", true, "watermark image file");
    options.addOption("wt", true, "watermark transparency (e.g. 0.5, max 1.0), default 1.0");
    options.addOption("wp", true, "watermark position (e.g. 0.9, max 1.0), default BOTTOM_RIGHT");

    /*//from   ww  w . jav a 2  s .  c o  m
    TOP_LEFT
    TOP_CENTER
    TOP_RIGHT
    CENTER_LEFT
    CENTER
    CENTER_RIGHT
    BOTTOM_LEFT
    BOTTOM_CENTER
    BOTTOM_RIGHT
     */

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
        if (cmd.getArgs().length < 1) {
            throw new ParseException("Too few arguments");
        } else if (cmd.getArgs().length > 1) {
            throw new ParseException("Too many arguments");
        }
        inputImage = cmd.getArgs()[0];
    } catch (ParseException e) {
        showHelp(options, e.getLocalizedMessage());
        System.exit(-1);
    }

    Thumbnails.Builder<File> st = Thumbnails.of(inputImage);

    if (cmd.hasOption("q")) {
        st.outputQuality(Double.parseDouble(cmd.getOptionValue("q")));
    } else {
        st.outputQuality(0.97f);
    }

    if (cmd.hasOption("s")) {
        st.size(Integer.parseInt(cmd.getOptionValue("s")), Integer.parseInt(cmd.getOptionValue("s")));
    } else {
        st.size(1200, 1200);
    }
    if (cmd.hasOption("w")) {
        Positions position = Positions.BOTTOM_RIGHT;
        float trans = 0.5f;
        if (cmd.hasOption("wp")) {
            position = Positions.valueOf(cmd.getOptionValue("wp"));
        }
        if (cmd.hasOption("wt")) {
            trans = Float.parseFloat(cmd.getOptionValue("wt"));
        }

        st.watermark(position, ImageIO.read(new File(cmd.getOptionValue("w"))), trans);
    }
    if (cmd.hasOption("o")) {
        st.toFile(new File(cmd.getOptionValue("o")));
    } else {
        st.toFiles(Rename.PREFIX_DOT_THUMBNAIL);
    }

    //.outputFormat("jpg")
    System.exit(0);
}