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:de.zazaz.iot.bosch.indego.util.IndegoIftttAdapter.java

public static void main(String[] args) {
    System.setProperty("log4j.configurationFile", "log4j2-indegoIftttAdapter-normal.xml");

    Options options = new Options();

    StringBuilder commandList = new StringBuilder();
    for (DeviceCommand cmd : DeviceCommand.values()) {
        if (commandList.length() > 0) {
            commandList.append(", ");
        }//from   w  w  w  .java  2 s.  c  o m
        commandList.append(cmd.toString());
    }

    options.addOption(Option //
            .builder("c") //
            .longOpt("config") //
            .desc("The configuration file to use") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("d") //
            .longOpt("debug") //
            .desc("Logs more details") //
            .build());
    options.addOption(Option //
            .builder("?") //
            .longOpt("help") //
            .desc("Prints this help") //
            .build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmds = null;
    try {
        cmds = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        System.err.println();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(IndegoIftttAdapter.class.getName(), options);
        System.exit(1);
        return;
    }

    if (cmds.hasOption("?")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CmdLineTool.class.getName(), options);
        return;
    }

    if (cmds.hasOption("d")) {
        System.setProperty("log4j.configurationFile", "log4j2-indegoIftttAdapter-debug.xml");
    }

    String configFileName = cmds.getOptionValue('c');
    File configFile = new File(configFileName);

    if (!configFile.exists()) {
        System.err.println(String.format("The specified config file (%s) does not exist", configFileName));
        System.err.println();
        System.exit(2);
        return;
    }

    Properties properties = new Properties();
    try (InputStream in = new FileInputStream(configFile)) {
        properties.load(in);
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
        System.err.println(String.format("Was not able to load the properties file (%s)", configFileName));
        System.err.println();
    }

    IftttIndegoAdapterConfiguration config = new IftttIndegoAdapterConfiguration();
    config.setIftttMakerKey(properties.getProperty("indego.ifttt.maker.key"));
    config.setIftttIgnoreServerCertificate(
            Integer.parseInt(properties.getProperty("indego.ifttt.maker.ignore-server-certificate")) != 0);
    config.setIftttReceiverPort(Integer.parseInt(properties.getProperty("indego.ifttt.maker.receiver-port")));
    config.setIftttReceiverSecret(properties.getProperty("indego.ifttt.maker.receiver-secret"));
    config.setIftttOfflineEventName(properties.getProperty("indego.ifttt.maker.eventname-offline"));
    config.setIftttOnlineEventName(properties.getProperty("indego.ifttt.maker.eventname-online"));
    config.setIftttErrorEventName(properties.getProperty("indego.ifttt.maker.eventname-error"));
    config.setIftttErrorClearedEventName(properties.getProperty("indego.ifttt.maker.eventname-error-cleared"));
    config.setIftttStateChangeEventName(properties.getProperty("indego.ifttt.maker.eventname-state-change"));
    config.setIndegoBaseUrl(properties.getProperty("indego.ifttt.device.base-url"));
    config.setIndegoUsername(properties.getProperty("indego.ifttt.device.username"));
    config.setIndegoPassword(properties.getProperty("indego.ifttt.device.password"));
    config.setPollingIntervalMs(Integer.parseInt(properties.getProperty("indego.ifttt.polling-interval-ms")));

    IftttIndegoAdapter adapter = new IftttIndegoAdapter(config);
    adapter.startup();
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.MorsaCreator.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);/*from  ww w  . j  a va2 s .c  o  m*/
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output directory");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

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

        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        URI targetUri = URI.createURI("morsa://" + commandLine.getOptionValue(OUT));

        Class<?> inClazz = MorsaCreator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put("morsa",
                new MorsaResourceFactoryImpl(new MongoDBMorsaBackendFactory()));

        Resource sourceResource = resourceSet.createResource(sourceUri);
        Map<String, Object> loadOpts = new HashMap<String, Object>();
        if ("zxmi".equals(sourceUri.fileExtension())) {
            loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        }

        Runtime.getRuntime().gc();
        long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}",
                MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
        LOG.log(Level.INFO, "Loading source resource");
        sourceResource.load(loadOpts);
        LOG.log(Level.INFO, "Source resource loaded");
        Runtime.getRuntime().gc();
        long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
        LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

        Resource targetResource = resourceSet.createResource(targetUri);

        Map<String, Object> saveOpts = new HashMap<String, Object>();
        //URI of the MongoDB database (e.g. localhost)
        saveOpts.put(IMorsaResource.OPTION_SERVER_URI, "localhost");
        saveOpts.put(IMorsaResource.OPTION_MAX_SAVE_CACHE_SIZE, 30000);
        saveOpts.put(IMorsaResource.OPTION_DEMAND_LOAD, false);
        targetResource.save(saveOpts);

        LOG.log(Level.INFO, "Start moving elements");
        targetResource.getContents().clear();
        targetResource.getContents().addAll(sourceResource.getContents());
        LOG.log(Level.INFO, "End moving elements");
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saved");

        targetResource.unload();

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:eu.annocultor.utils.XmlUtils.java

public static void main(String... args) throws Exception {
    // Handling command line parameters with Apache Commons CLI
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName(OPT_FN).hasArg().isRequired()
            .withDescription("XML file name to be pretty-printed").create(OPT_FN));

    // now lets parse the input
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;//from www  .  ja va2 s.co m
    try {
        cmd = parser.parse(options, Utils.getCommandLineFromANNOCULTOR_ARGS(args));
    } catch (ParseException pe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("pretty", options);
        return;
    }

    List<File> files = Utils.expandFileTemplateFrom(new File("."), cmd.getOptionValue(OPT_FN));
    for (File file : files) {
        // XML pretty print
        System.out.println("Pretty-print for file " + file);
        if (file.exists())
            prettyPrintXmlFileSAX(file.getCanonicalPath());
        else
            throw new Exception("File not found: " + file.getCanonicalPath());
    }
}

From source file:fr.romainf.QRCode.java

public static void main(String[] args) {
    Options options = buildOptions();//www .  jav  a  2s  . c  o m

    CommandLineParser parser = new BasicParser();

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

        int l = args.length;
        if (l != 1) {
            System.out.println("Can only encode one datum at a time (" + l + " given)");
            printUsage(options);
            System.exit(1);
        }
        if (cmd.hasOption("help")) {
            printUsage(options);
            System.exit(0);
        }

        String output = cmd.getOptionValue("o", DEFAULT_OUTPUT_FILE);
        String pixelColourText = cmd.getOptionValue("c", DEFAULT_PIXEL_COLOUR);
        if (pixelColourText.startsWith("0x")) {
            pixelColourText = pixelColourText.substring(2);
        }
        Color pixelColour;
        if (pixelColourText.length() == 6) {
            pixelColour = new Color(Integer.parseInt(pixelColourText, 16));
        } else {
            pixelColour = new Color((int) Long.parseLong(pixelColourText, 16), true);
        }

        writeQRCode(args[l - 1], output, pixelColour);

    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printUsage(options);
        System.exit(1);
    } catch (WriterException e) {
        System.out.println("Could not create QRCode from data (" + e.getMessage() + ")");
        System.exit(2);
    } catch (IOException e) {
        System.out.println("Could not save QRCode to file (" + e.getMessage() + ")");
        System.exit(4);
    }
    System.exit(0);
}

From source file:net.sf.jsignpdf.verify.SignatureCounter.java

/**
 * Main program./* w ww . jav  a  2 s.  c o  m*/
 * 
 * @param args
 */
public static void main(String[] args) {

    // create the Options
    final Option optHelp = new Option("h", "help", false, "print this message");
    final Option optDebug = new Option("d", "debug", false, "enables debug output");
    final Option optNames = new Option("n", "names", false,
            "print comma separated signature names instead of the count");
    final Option optPasswd = new Option("p", "password", true, "set password for opening PDF");
    optPasswd.setArgName("password");

    final Options options = new Options();
    options.addOption(optHelp);
    options.addOption(optDebug);
    options.addOption(optNames);
    options.addOption(optPasswd);

    CommandLine line = null;
    try {
        // create the command line parser
        CommandLineParser parser = new PosixParser();
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Unable to parse command line (Use -h for the help)\n" + exp.getMessage());
        System.exit(Constants.EXIT_CODE_PARSE_ERR);
    }

    final String[] tmpArgs = line.getArgs();
    if (line.hasOption("h") || args == null || args.length == 0) {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(70, "java -jar SignatureCounter.jar [file1.pdf [file2.pdf ...]]",
                "JSignPdf SignatureCounter is a command line tool which prints count of signatures in given PDF document.",
                options, null, true);
    } else {
        byte[] tmpPasswd = null;
        if (line.hasOption("p")) {
            tmpPasswd = line.getOptionValue("p").getBytes();
        }
        final boolean debug = line.hasOption("d");
        final boolean names = line.hasOption("n");

        for (String tmpFilePath : tmpArgs) {
            if (debug) {
                System.out.print("Counting signatures in " + tmpFilePath + ": ");
            }
            final File tmpFile = new File(tmpFilePath);
            if (!tmpFile.canRead()) {
                System.err.println("Couldn't read the file. Check the path and permissions: " + tmpFilePath);
                System.exit(Constants.EXIT_CODE_CANT_READ_FILE);
            }
            try {
                final PdfReader pdfReader = PdfUtils.getPdfReader(tmpFilePath, tmpPasswd);
                @SuppressWarnings("unchecked")
                final List<String> sigNames = pdfReader.getAcroFields().getSignatureNames();
                if (names) {
                    //print comma-separated names
                    boolean isNotFirst = false;
                    for (String sig : sigNames) {
                        if (isNotFirst) {
                            System.out.println(",");
                        } else {
                            isNotFirst = true;
                        }
                        System.out.println(sig);
                    }
                } else {
                    //normal processing print only count of signatures
                    System.out.println(sigNames.size());
                    if (debug) {
                        System.out.println("Signature names: " + sigNames);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(Constants.EXIT_CODE_COMMON_ERROR);
            }
        }
    }
}

From source file:com.fiveclouds.jasper.JasperRunner.java

public static void main(String[] args) {

    // Set-up the options for the utility
    Options options = new Options();
    Option report = new Option("report", true, "jasper report to run (i.e. /path/to/report.jrxml)");
    options.addOption(report);/*from   w  w  w.  j ava 2s. c  o m*/

    Option driver = new Option("driver", true, "the jdbc driver class (i.e. com.mysql.jdbc.Driver)");
    driver.setRequired(true);
    options.addOption(driver);

    options.addOption("jdbcurl", true, "database jdbc url (i.e. jdbc:mysql://localhost:3306/database)");
    options.addOption("excel", true, "Will override the PDF default and export to Microsoft Excel");
    options.addOption("username", true, "database username");
    options.addOption("password", true, "database password");
    options.addOption("output", true, "the output filename (i.e. path/to/report.pdf");
    options.addOption("help", false, "print this message");

    Option propertyOption = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
            .withDescription("use value as report property").create("D");

    options.addOption(propertyOption);

    // Parse the options and build the report
    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("jasper-runner", options);
        } else {

            System.out.println("Building report " + cmd.getOptionValue("report"));
            try {
                Class.forName(cmd.getOptionValue("driver"));
                Connection connection = DriverManager.getConnection(cmd.getOptionValue("jdbcurl"),
                        cmd.getOptionValue("username"), cmd.getOptionValue("password"));
                System.out.println("Connected to " + cmd.getOptionValue("jdbcurl"));
                JasperReport jasperReport = JasperCompileManager.compileReport(cmd.getOptionValue("report"));

                JRPdfExporter pdfExporter = new JRPdfExporter();

                Properties properties = cmd.getOptionProperties("D");
                Map<String, Object> parameters = new HashMap<String, Object>();

                Map<String, JRParameter> reportParameters = new HashMap<String, JRParameter>();

                for (JRParameter param : jasperReport.getParameters()) {
                    reportParameters.put(param.getName(), param);
                }

                for (Object propertyKey : properties.keySet()) {
                    String parameterName = String.valueOf(propertyKey);
                    String parameterValue = String.valueOf(properties.get(propertyKey));
                    JRParameter reportParam = reportParameters.get(parameterName);

                    if (reportParam != null) {
                        if (reportParam.getValueClass().equals(String.class)) {
                            System.out.println(
                                    "Property " + parameterName + " set to String = " + parameterValue);
                            parameters.put(parameterName, parameterValue);
                        } else if (reportParam.getValueClass().equals(Integer.class)) {
                            System.out.println(
                                    "Property " + parameterName + " set to Integer = " + parameterValue);
                            parameters.put(parameterName, Integer.parseInt(parameterValue));
                        } else {
                            System.err.print("Unsupported type for property " + parameterName);
                            System.exit(1);

                        }
                    } else {
                        System.out.println("Property " + parameterName + " not found in the report! IGNORING");

                    }
                }

                JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, connection);

                pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
                pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, cmd.getOptionValue("output"));
                System.out.println("Exporting report to " + cmd.getOptionValue("output"));
                pdfExporter.exportReport();
            } catch (JRException e) {
                System.err.print("Unable to parse report file (" + cmd.getOptionValue("r") + ")");
                e.printStackTrace();
                System.exit(1);
            } catch (ClassNotFoundException e) {
                System.err.print("Unable to find the database driver,  is it on the classpath?");
                e.printStackTrace();
                System.exit(1);
            } catch (SQLException e) {
                System.err.print("An SQL exception has occurred (" + e.getMessage() + ")");
                e.printStackTrace();
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        System.err.print("Unable to parse command line options (" + e.getMessage() + ")");
        System.exit(1);
    }
}

From source file:com.level3.hiper.dyconn.be.Main.java

public static void main(String... args) {

    try {/* w w w.  j a  v  a2s.  c  o  m*/
        String bootstrap = "/dyconn-be-toml.cfg";
        CommandLineParser parser = new DefaultParser();
        Options options = new Options();
        options.addOption("c", "config-file", true, "configuration for hapi dyconn module");
        try {
            CommandLine line = parser.parse(options, args);
            if (line.hasOption("config-file")) {
                bootstrap = line.getOptionValue("config-file");
            }
        } catch (ParseException ex) {
            log.error("command line", ex);
            return;
        }

        // read config file
        log.info("loading configuration");
        Config.instance().initialize(bootstrap);

        // initialize queue subsystem
        log.info("initializing messaging");
        Broker.instance().initialize();

        // initilaize persistence
        log.info("starting exector");
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(new MsgReceiver());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.mvdb.etl.actions.ScanDBChanges.java

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

    String customerName = null;//w  ww .  j  av a2s  .  c  o m
    String snapshotDir = null;
    final CommandLineParser cmdLinePosixParser = new PosixParser();
    final Options posixOptions = constructPosixOptions();
    CommandLine commandLine;
    try {
        commandLine = cmdLinePosixParser.parse(posixOptions, args);
        if (commandLine.hasOption("customer")) {
            customerName = commandLine.getOptionValue("customer");
        }
        if (commandLine.hasOption("snapshotDir")) {
            snapshotDir = commandLine.getOptionValue("snapshotDir");
        }
    } catch (ParseException parseException) // checked exception
    {
        System.err.println(
                "Encountered exception while parsing using PosixParser:\n" + parseException.getMessage());
    }

    if (customerName == null) {
        System.err.println("Could not find customerName. Aborting...");
        System.exit(1);
    }
    if (snapshotDir == null) {
        System.err.println("Could not find snapshotDir. Aborting...");
        System.exit(1);
    }

    ApplicationContext context = Top.getContext();

    final ConfigurationDAO configurationDAO = (ConfigurationDAO) context.getBean("configurationDAO");
    final GenericDAO genericDAO = (GenericDAO) context.getBean("genericDAO");
    File snapshotDirectory = getSnapshotDirectory(configurationDAO, customerName, snapshotDir);
    //write file schema-orders.dat in snapshotDirectory
    Metadata metadata = genericDAO.getMetadata("orders", snapshotDirectory);
    //writes files: header-orders.dat, data-orders.dat in snapshotDirectory
    genericDAO.scan2("orders", snapshotDirectory);

}

From source file:edu.gslis.ts.ChunkToFile.java

public static void main(String[] args) {
    try {//from  w ww .  java  2s  .co m
        // Get the commandline options
        Options options = createOptions();
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        String inputPath = cmd.getOptionValue("input");
        String indexPath = cmd.getOptionValue("index");
        String eventsPath = cmd.getOptionValue("events");
        String stopPath = cmd.getOptionValue("stop");
        String outputPath = cmd.getOptionValue("output");

        IndexWrapper index = IndexWrapperFactory.getIndexWrapper(indexPath);
        Stopper stopper = new Stopper(stopPath);
        Map<Integer, FeatureVector> queries = readEvents(eventsPath, stopper);

        // Setup the filter
        ChunkToFile f = new ChunkToFile();
        if (inputPath != null) {
            File infile = new File(inputPath);
            if (infile.isDirectory()) {
                Iterator<File> files = FileUtils.iterateFiles(infile, null, true);

                while (files.hasNext()) {
                    File file = files.next();
                    System.err.println(file.getAbsolutePath());
                    f.filter(file, queries, index, stopper, outputPath);
                }
            } else
                System.err.println(infile.getAbsolutePath());
            f.filter(infile, queries, index, stopper, outputPath);
        }

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

From source file:com.google.flightmap.parsing.faa.afd.AfdCommParser.java

public static void main(String args[]) {
    CommandLine line = null;// w w  w . ja  v  a  2 s .c  o m
    try {
        final CommandLineParser parser = new PosixParser();
        line = parser.parse(OPTIONS, args);
    } catch (ParseException pEx) {
        System.err.println(pEx.getMessage());
        printHelp(line);
        System.exit(1);
    }

    if (line.hasOption(HELP_OPTION)) {
        printHelp(line);
        System.exit(0);
    }

    final String afdFile = line.getOptionValue(AFD_OPTION);
    final String iataToIcaoFile = line.getOptionValue(IATA_TO_ICAO_OPTION);
    final String dbFile = line.getOptionValue(AVIATION_DB_OPTION);

    (new AfdCommParser(afdFile, iataToIcaoFile, dbFile)).execute();
}