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.xandrev.altafitcalendargenerator.Main.java

public static void main(String[] args) {
    CalendarPrinter printer = new CalendarPrinter();
    XLSExtractor extractor = new XLSExtractor();
    if (args != null && args.length > 0) {

        try {//w  w w .  j  ava 2 s .  c o  m
            Options opt = new Options();
            opt.addOption("f", true, "Filepath of the XLS file");
            opt.addOption("t", true, "Type name of activities");
            opt.addOption("m", true, "Month index");
            opt.addOption("o", true, "Output filename of the generated ICS");
            BasicParser parser = new BasicParser();
            CommandLine cliParser = parser.parse(opt, args);
            if (cliParser.hasOption("f")) {
                String fileName = cliParser.getOptionValue("f");
                LOG.debug("File name to be imported: " + fileName);

                String activityNames = cliParser.getOptionValue("t");
                LOG.debug("Activity type names: " + activityNames);

                ArrayList<String> nameList = new ArrayList<>();
                String[] actNames = activityNames.split(",");
                if (actNames != null) {
                    nameList.addAll(Arrays.asList(actNames));
                }
                LOG.debug("Sucessfully activities parsed: " + nameList.size());

                if (cliParser.hasOption("m")) {
                    String monthIdx = cliParser.getOptionValue("m");
                    LOG.debug("Month index: " + monthIdx);
                    int month = Integer.parseInt(monthIdx) - 1;

                    if (cliParser.hasOption("o")) {
                        String outputfilePath = cliParser.getOptionValue("o");
                        LOG.debug("Output file to be generated: " + monthIdx);

                        LOG.debug("Starting to extract the spreadsheet");
                        HashMap<Integer, ArrayList<TimeTrack>> result = extractor.importExcelSheet(fileName);
                        LOG.debug("Extracted the spreadsheet done");

                        LOG.debug("Starting the filter of the data");
                        HashMap<Date, String> cal = printer.getCalendaryByItem(result, nameList, month);
                        LOG.debug("Finished the filter of the data");

                        LOG.debug("Creating the ics Calendar");
                        net.fortuna.ical4j.model.Calendar calendar = printer.createICSCalendar(cal);
                        LOG.debug("Finished the ics Calendar");

                        LOG.debug("Printing the ICS file to: " + outputfilePath);
                        printer.saveCalendar(calendar, outputfilePath);
                        LOG.debug("Finished the ICS file to: " + outputfilePath);
                    }
                }
            }
        } catch (ParseException ex) {
            LOG.error("Error parsing the argument list: ", ex);
        }
    }
}

From source file:GossipP2PServer.java

public static void main(String args[]) {
    // Arguments that should be passed in
    int port = -1;
    String databasePath = "";

    // Set up arg options
    Options options = new Options();
    Option p = new Option("p", true, "Port for server to listen on.");
    options.addOption(p);// w  w  w . j a  v  a2s  . c  om
    Option d = new Option("d", true, "Path to database.");
    options.addOption(d);

    CommandLineParser clp = new DefaultParser();

    try {
        CommandLine cl = clp.parse(options, args);

        if (cl.hasOption("p")) {
            port = Integer.parseInt(cl.getOptionValue("p"));
        }
        if (cl.hasOption("d")) {
            databasePath = cl.getOptionValue("d");
        }

        // If we have all we need start the server and setup database.
        if (port != -1 && !databasePath.isEmpty() && databasePath != null) {
            Database.getInstance().initializeDatabase(databasePath);
            runConcurrentServer(port);
        } else {
            showArgMenu(options);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.adobe.aem.demomachine.Checksums.java

public static void main(String[] args) {

    String rootFolder = null;//from   w ww  . j  av  a2  s.  com

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Demo Machine root folder");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {
            rootFolder = cmd.getOptionValue("f");
        }

    } catch (Exception e) {
        System.exit(-1);
    }

    Properties md5properties = new Properties();
    List<String[]> listPaths = Arrays.asList(AemDemoConstants.demoPaths);
    for (String[] path : listPaths) {
        if (path.length == 5) {
            logger.debug(path[1]);
            File pathFolder = new File(rootFolder + (path[1].length() > 0 ? (File.separator + path[1]) : ""));
            if (pathFolder.exists()) {
                String md5 = AemDemoUtils.calcMD5HashForDir(pathFolder, Boolean.parseBoolean(path[3]), false);
                logger.debug("MD5 is: " + md5);
                md5properties.setProperty("demo.path." + path[0], path[1]);
                md5properties.setProperty("demo.md5." + path[0], md5);
            } else {
                logger.error("Folder cannot be found");
            }
        }
    }

    File md5 = new File(rootFolder + File.separator + "conf" + File.separator + "checksums.properties");
    try {

        @SuppressWarnings("serial")
        Properties tmpProperties = new Properties() {
            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(new TreeSet<Object>(super.keySet()));
            }
        };
        tmpProperties.putAll(md5properties);
        tmpProperties.store(new FileOutputStream(md5), null);
    } catch (Exception e) {
        logger.error(e.getMessage());
    }

    System.out.println("MD5 checkums generated");

}

From source file:com.discursive.jccook.cmdline.CliBasicExample.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new BasicParser();

    Options options = new Options();
    options.addOption("h", "help", false, "Print this usage information");
    options.addOption("v", "verbose", false, "Print out VERBOSE debugging information");
    options.addOption("f", "file", true, "File to save program output to");

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

    boolean verbose = false;
    String file = "";

    if (commandLine.hasOption('h')) {
        System.out.println("Help Message");
        System.exit(0);/*  ww  w  .ja v  a2  s .  c o  m*/
    }

    if (commandLine.hasOption('v')) {
        verbose = true;
    }

    if (commandLine.hasOption('f')) {
        file = commandLine.getOptionValue('f');
    }

    System.exit(0);
}

From source file:io.wcm.devops.conga.tooling.cli.CongaCli.java

/**
 * CLI entry point//w w  w .  ja  v  a2s .c o  m
 * @param args Command line arguments
 * @throws Exception
 */
//CHECKSTYLE:OFF
public static void main(String[] args) throws Exception {
    //CHECKSTYLE:ON
    CommandLine commandLine = new DefaultParser().parse(CLI_OPTIONS, args);

    if (commandLine.hasOption("?")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(150);
        formatter.printHelp("java -cp io.wcm.devops.conga.tooling.cli-<version>.jar "
                + "io.wcm.devops.conga.tooling.cli.CongaCli <arguments>", CLI_OPTIONS);
        return;
    }

    String templateDir = commandLine.getOptionValue("templateDir", "templates");
    String roleDir = commandLine.getOptionValue("roleDir", "roles");
    String environmentDir = commandLine.getOptionValue("environmentDir", "environments");
    String targetDir = commandLine.getOptionValue("target", "target");
    String[] environments = StringUtils.split(commandLine.getOptionValue("environments", null), ",");

    ResourceLoader resourceLoader = new ResourceLoader();
    List<ResourceCollection> roleDirs = ImmutableList
            .of(resourceLoader.getResourceCollection(ResourceLoader.FILE_PREFIX + roleDir));
    List<ResourceCollection> templateDirs = ImmutableList
            .of(resourceLoader.getResourceCollection(ResourceLoader.FILE_PREFIX + templateDir));
    List<ResourceCollection> environmentDirs = ImmutableList
            .of(resourceLoader.getResourceCollection(ResourceLoader.FILE_PREFIX + environmentDir));
    File targetDirecotry = new File(targetDir);

    Generator generator = new Generator(roleDirs, templateDirs, environmentDirs, targetDirecotry);
    generator.setDeleteBeforeGenerate(true);
    generator.generate(environments);
}

From source file:io.proscript.jlight.JLight.java

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

    CommandLineParser parser = new DefaultParser();
    Options options = new Options();

    Option host = new Option("h", "host", true, "Host of the HTTP server (default 127.0.0.1)");
    Option port = new Option("p", "port", true, "Port of the HTTP server (default 9000)");

    Option main = new Option("c", "class", true, "Application to run, e.g. org.vendor.class");
    Option help = new Option("h", "help", false, "Display help and exit");
    Option version = new Option("v", "version", false, "Display JLight version");

    options.addOption(host);/*  w  w  w. j  av  a 2 s .  c o m*/
    options.addOption(port);

    options.addOption(main);
    options.addOption(help);
    options.addOption(version);

    CommandLine line;

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

        if (line.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            Version.print();
            formatter.printHelp("jlight", options);
            return;
        }

        if (line.hasOption("v")) {
            Version.print();
            return;
        }

        if (!line.hasOption("c")) {
            throw new ParseException("Option 'class' is required");
        }

        Runtime.run(line);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
    }
}

From source file:com.act.lcms.MassCalculator2.java

public static void main(String[] args) throws Exception {
    CommandLine cl = CLI_UTIL.parseCommandLine(args);

    if (cl.hasOption(OPTION_LICENSE_FILE)) {
        LOGGER.info("Using license file at %s", cl.getOptionValue(OPTION_LICENSE_FILE));
        LicenseManager.setLicenseFile(cl.getOptionValue(OPTION_LICENSE_FILE));
    }/* w ww  .j  a  v a  2 s.c  om*/

    List<String> inchis = new ArrayList<>();

    if (cl.hasOption(OPTION_INPUT_FILE)) {
        try (BufferedReader reader = new BufferedReader(new FileReader(cl.getOptionValue(OPTION_INPUT_FILE)))) {
            String line;
            while ((line = reader.readLine()) != null) {
                inchis.add(line);
            }
        }
    }

    if (cl.getArgList().size() > 0) {
        LOGGER.info("Reading %d InChIs from the command line", cl.getArgList().size());
        inchis.addAll(cl.getArgList());
    }

    try (PrintWriter writer = new PrintWriter(
            cl.hasOption(OPTION_OUTPUT_FILE) ? new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE))
                    : new OutputStreamWriter(System.out))) {
        writer.format("InChI\tMass\tCharge\n");

        for (String inchi : inchis) {
            try {
                Pair<Double, Integer> massAndCharge = calculateMassAndCharge(inchi);
                writer.format("%s\t%.6f\t%3d\n", inchi, massAndCharge.getLeft(), massAndCharge.getRight());
            } catch (MolFormatException e) {
                LOGGER.error("Unable to compute mass for %s: %s", inchi, e.getMessage());
            }
        }
    }
}

From source file:edu.umass.cs.gnsclient.client.testing.CreateGuidTest.java

/**
 * The main routine run from the command line.
 *
 * @param args//from   ww  w  .ja  v a  2  s .c o m
 * @throws Exception
 */
public static void main(String args[]) throws Exception {
    try {
        CommandLine parser = initializeOptions(args);
        if (parser.hasOption("help") || args.length == 0) {
            printUsage();
            System.exit(1);
        }
        String alias = parser.getOptionValue("alias");
        new CreateGuidTest(alias != null ? alias : ACCOUNT_ALIAS);
        System.exit(0);
    } catch (HeadlessException e) {
        System.out
                .println("When running headless you'll need to specify the host and port on the command line");
        printUsage();
        System.exit(1);
    }
}

From source file:net.jingx.main.Main.java

/**
 * @param args/*w  w  w  .  j  a v a 2  s .c  o  m*/
 * @throws IOException 
 */
public static void main(String[] args) {
    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    options.addOption(CLI_SECRET, true, "generate secret key (input is the configuration key from google)");
    options.addOption(CLI_PASSCODE, true, "generate passcode (input is the secret key)");
    options.addOption(new Option(CLI_HELP, "print this message"));
    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption(CLI_SECRET)) {
            String confKey = line.getOptionValue(CLI_SECRET);
            String secret = generateSecret(confKey);
            System.out.println("Your secret to generate pins: " + secret);
        } else if (line.hasOption(CLI_PASSCODE)) {
            String secret = line.getOptionValue(CLI_PASSCODE);
            String pin = computePin(secret, null);
            System.out.println(pin);
        } else if (line.hasOption(CLI_HELP)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("GAuthCli", options);
        } else {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        MainGui window = new MainGui();
                        window.doSetVisible();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            return;
        }
        System.out.println("Press any key to exit");
        System.in.read();
    } catch (Exception e) {
        System.out.println("Unexpected exception:" + e.getMessage());
    }
    System.exit(0);
}

From source file:net.ninjacat.stubborn.Stubborn.java

public static void main(String[] argv) throws ClassNotFoundException, ParseException {
    Options options = createOptions();//  ww w  . j a  v  a  2 s  .  c o  m
    if (argv.length == 0) {
        printHelp(options);
        return;
    }

    Class.forName(Bootstrapper.class.getCanonicalName());
    CommandLineParser parser = new GnuParser();

    try {
        CommandLine commandLine = parser.parse(options, argv);
        if (commandLine.hasOption("h")) {
            printHelp(options);
            return;
        }

        Context context = new Context(commandLine);

        Transformer transformer = Bootstrapper.get(Transformer.class);

        transformer.transform(context);
    } catch (MissingOptionException ex) {
        System.out.println("Missing required parameter " + ex.getMissingOptions());
        printHelp(options);
    } catch (TransformationException ex) {
        System.out.println("Failed to perform transformation caused by " + ex.getCause());
        System.out.println(ex.getMessage());
    }
}