Example usage for org.apache.commons.cli DefaultParser DefaultParser

List of usage examples for org.apache.commons.cli DefaultParser DefaultParser

Introduction

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

Prototype

DefaultParser

Source Link

Usage

From source file:it.anyplace.sync.relay.server.Main.java

public static void main(String[] args) throws ParseException, Exception {
    Options options = new Options();
    options.addOption("r", "relay-server", true, "set relay server to serve for");
    options.addOption("p", "port", true, "set http server port");
    options.addOption("h", "help", false, "print help");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("s-client", options);
        return;//from w  w w.  j  av a2s.c om
    }
    int port = cmd.hasOption("p") ? Integer.parseInt(cmd.getOptionValue("p")) : 22080;
    String relayServer = firstNonNull(emptyToNull(cmd.getOptionValue("r")), "relay://localhost");
    logger.info("starting http relay server :{} for relay server {}", port, relayServer);
    HttpRelayServer httpRelayServer = new HttpRelayServer(
            DeviceAddress.newBuilder().setDeviceId("relay").setAddress(relayServer).build().getSocketAddress());
    httpRelayServer.start(port);
    httpRelayServer.join();
}

From source file:com.github.zerkseez.codegen.wrappergenerator.Main.java

public static void main(final String[] args) throws Exception {
    final Options options = new Options();
    options.addOption(Option.builder().longOpt("outputDirectory").hasArg().required().build());
    options.addOption(Option.builder().longOpt("classMappings").hasArgs().required().build());

    final CommandLineParser parser = new DefaultParser();

    try {//  www . ja  v a  2 s . c o m
        final CommandLine line = parser.parse(options, args);
        final String outputDirectory = line.getOptionValue("outputDirectory");
        final String[] classMappings = line.getOptionValues("classMappings");
        for (String classMapping : classMappings) {
            final String[] tokens = classMapping.split(":");
            if (tokens.length != 2) {
                throw new IllegalArgumentException(
                        String.format("Invalid class mapping format \"%s\"", classMapping));
            }
            final Class<?> wrappeeClass = Class.forName(tokens[0]);
            final String fullWrapperClassName = tokens[1];
            final int indexOfLastDot = fullWrapperClassName.lastIndexOf('.');
            final String wrapperPackageName = (indexOfLastDot == -1) ? ""
                    : fullWrapperClassName.substring(0, indexOfLastDot);
            final String simpleWrapperClassName = (indexOfLastDot == -1) ? fullWrapperClassName
                    : fullWrapperClassName.substring(indexOfLastDot + 1);

            System.out.println(String.format("Generating wrapper class for %s...", wrappeeClass));
            final WrapperGenerator generator = new WrapperGenerator(wrappeeClass, wrapperPackageName,
                    simpleWrapperClassName);
            generator.writeTo(outputDirectory, true);
        }
        System.out.println("Done");
    } catch (MissingOptionException e) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(String.format("java -cp CLASSPATH %s", Main.class.getName()), options);
    }
}

From source file:net.geoprism.FileMerger.java

public static void main(String[] args) throws ParseException, IOException {
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();
    options.addOption(Option.builder("b").hasArg().argName("baseFile").longOpt("baseFile")
            .desc("The path to the base properties file.").build());
    options.addOption(Option.builder("o").hasArg().argName("overrideFile").longOpt("overrideFile")
            .desc("The path to the override properties file.").build());
    options.addOption(Option.builder("e").hasArg().argName("exportFile").longOpt("exportFile")
            .desc("The path to the export properties file. A null value defaults to base.").build());
    options.addOption(Option.builder("B").hasArg().argName("baseDir").longOpt("baseDir")
            .desc("The path to the base directory.").build());
    options.addOption(Option.builder("O").hasArg().argName("overrideDir").longOpt("overrideDir")
            .desc("The path to the override directory.").build());
    options.addOption(Option.builder("E").hasArg().argName("exportDir").longOpt("exportDir")
            .desc("The path to the export directory. A null value defaults to base.").build());
    CommandLine line = parser.parse(options, args);

    String sBase = line.getOptionValue("b");
    String sOverride = line.getOptionValue("o");
    String sExport = line.getOptionValue("e");
    String sBaseDir = line.getOptionValue("B");
    String sOverrideDir = line.getOptionValue("O");
    String sExportDir = line.getOptionValue("E");

    if (sBase != null && sOverride != null) {
        if (sExport == null) {
            sExport = sBase;/*w ww  .j  a  v a2  s . com*/
        }

        File fBase = new File(sBase);
        File fOverride = new File(sOverride);
        File fExport = new File(sExport);
        if (!fBase.exists() || !fOverride.exists()) {
            throw new RuntimeException(
                    "The base [" + sBase + "] and the override [" + sOverride + "] paths must both exist.");
        }

        FileMerger merger = new FileMerger();
        merger.mergeProperties(fBase, fOverride, fExport);
    } else if (sBaseDir != null && sOverrideDir != null) {
        if (sExportDir == null) {
            sExportDir = sBaseDir;
        }

        File fBaseDir = new File(sBaseDir);
        File fOverrideDir = new File(sOverrideDir);
        File fExportDir = new File(sExportDir);
        if (!fBaseDir.exists() || !fOverrideDir.exists()) {
            throw new RuntimeException("The base [" + sBaseDir + "] and the override [" + sOverrideDir
                    + "] paths must both exist.");
        }

        FileMerger merger = new FileMerger();
        merger.mergeDirectories(fBaseDir, fOverrideDir, fExportDir);
    } else {
        throw new RuntimeException("Invalid arguments");
    }
}

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  a 2s . c  o m
    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:azkaban.crypto.EncryptionCLI.java

/**
 * Outputs ciphered text to STDOUT.//from  w  w w .j  a  v  a  2 s  . co  m
 *
 * usage: EncryptionCLI [-h] -k <pass phrase> -p <plainText> -v <crypto version>
 * -h,--help                       print this message
 * -k,--key <pass phrase>          Passphrase used for encrypting plain text
 * -p,--plaintext <plainText>      Plaintext that needs to be encrypted
 * -v,--version <crypto version>   Version it will use to encrypt Version: [1.0, 1.1]
 *
 * @param args
 * @throws ParseException
 */
public static void main(String[] args) throws ParseException {
    CommandLineParser parser = new DefaultParser();

    if (parser.parse(createHelpOptions(), args, true).hasOption(HELP_KEY)) {
        new HelpFormatter().printHelp(EncryptionCLI.class.getSimpleName(), createOptions(), true);
        return;
    }

    CommandLine line = parser.parse(createOptions(), args);

    String passphraseKey = line.getOptionValue(PASSPHRASE_KEY);
    String plainText = line.getOptionValue(PLAINTEXT_KEY);
    String version = line.getOptionValue(VERSION_KEY);

    ICrypto crypto = new Crypto();
    String cipheredText = crypto.encrypt(plainText, passphraseKey, Version.fromVerString(version));
    System.out.println(cipheredText);
}

From source file:com.dopsun.msg4j.tools.CodeGen.java

/**
 * @param args/*w ww. j a va 2 s  . c  o  m*/
 * @throws IOException
 * @throws MalformedURLException
 * @throws ParseException
 */
public static void main(String[] args) throws MalformedURLException, IOException, ParseException {
    Options options = new Options();
    options.addOption("o", "out", true, "Output file");
    options.addOption("s", "src", true, "Source file");
    options.addOption("l", "lang", true, "Language");

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

    String lang = cmd.getOptionValue("lang", "Java");
    String srcFile = cmd.getOptionValue("src");
    String outFile = cmd.getOptionValue("out");

    YamlModelSource modelSource = YamlModelSource.load(new File(srcFile).toURI().toURL());
    YamlModelParser parser = YamlModelParser.create();
    ModelInfo modelInfo = parser.parse(modelSource);

    String codeText = null;
    if (lang.equals("Java")) {
        codeText = Generator.JAVA.generate(modelInfo);
    } else {
        throw new UnsupportedOperationException("Unrecognized lang: " + lang);
    }

    if (outFile != null) {
        File file = new File(outFile);
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();

        Files.append(codeText, new File(outFile), Charsets.UTF_8);
    } else {
        System.out.println(codeText);
    }
}

From source file:com.nexmo.client.examples.TestVoiceCall.java

public static void main(String[] argv) throws Exception {
    Options options = new Options().addOption("v", "Verbosity")
            .addOption("f", "from", true, "Phone number to call from")
            .addOption("t", "to", true, "Phone number to call")
            .addOption("h", "webhook", true, "URL to call for instructions");
    CommandLineParser parser = new DefaultParser();

    CommandLine cli;/*from  w  ww .  java  2 s .c om*/
    try {
        cli = parser.parse(options, argv);
    } catch (ParseException exc) {
        System.err.println("Parsing failed: " + exc.getMessage());
        System.exit(128);
        return;
    }

    Queue<String> args = new LinkedList<String>(cli.getArgList());
    String from = cli.getOptionValue("f");
    String to = cli.getOptionValue("t");
    System.out.println("From: " + from);
    System.out.println("To: " + to);

    NexmoClient client = new NexmoClient(new JWTAuthMethod("951614e0-eec4-4087-a6b1-3f4c2f169cb0",
            FileSystems.getDefault().getPath("valid_application_key.pem")));
    client.getVoiceClient().createCall(
            new Call(to, from, "https://nexmo-community.github.io/ncco-examples/first_call_talk.json"));
}

From source file:com.cohesionforce.AvroToParquet.java

public static void main(String[] args) {

    String inputFile = null;//from www.  j a  v  a 2  s. co m
    String outputFile = null;

    HelpFormatter formatter = new HelpFormatter();
    // create Options object
    Options options = new Options();

    // add t option
    options.addOption("i", true, "input avro file");
    options.addOption("o", true, "ouptut Parquet file");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
        inputFile = cmd.getOptionValue("i");
        if (inputFile == null) {
            formatter.printHelp("AvroToParquet", options);
            return;
        }
        outputFile = cmd.getOptionValue("o");
    } catch (ParseException exc) {
        System.err.println("Problem with command line parameters: " + exc.getMessage());
        return;
    }

    File avroFile = new File(inputFile);

    if (!avroFile.exists()) {
        System.err.println("Could not open file: " + inputFile);
        return;
    }
    try {

        DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>();
        DataFileReader<GenericRecord> dataFileReader;
        dataFileReader = new DataFileReader<GenericRecord>(avroFile, datumReader);
        Schema avroSchema = dataFileReader.getSchema();

        // choose compression scheme
        CompressionCodecName compressionCodecName = CompressionCodecName.SNAPPY;

        // set Parquet file block size and page size values
        int blockSize = 256 * 1024 * 1024;
        int pageSize = 64 * 1024;

        String base = FilenameUtils.removeExtension(avroFile.getAbsolutePath()) + ".parquet";
        if (outputFile != null) {
            File file = new File(outputFile);
            base = file.getAbsolutePath();
        }

        Path outputPath = new Path("file:///" + base);

        // the ParquetWriter object that will consume Avro GenericRecords
        ParquetWriter<GenericRecord> parquetWriter;
        parquetWriter = new AvroParquetWriter<GenericRecord>(outputPath, avroSchema, compressionCodecName,
                blockSize, pageSize);
        for (GenericRecord record : dataFileReader) {
            parquetWriter.write(record);
        }
        dataFileReader.close();
        parquetWriter.close();
    } catch (IOException e) {
        System.err.println("Caught exception: " + e.getMessage());
    }
}

From source file:de.topobyte.osm4j.extra.executables.CreateIdBboxListGeometry.java

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

    // @formatter:off
    OptionHelper.addL(options, OPTION_INPUT, true, true, "an IdBboxList input file");
    OptionHelper.addL(options, OPTION_OUTPUT, true, true, "a wkt file to create");
    // @formatter:on

    CommandLine line = null;//from   ww w  .  ja  v a 2  s .  c  om
    try {
        line = new DefaultParser().parse(options, args);
    } catch (ParseException e) {
        System.out.println("unable to parse command line: " + e.getMessage());
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }

    String pathInput = line.getOptionValue(OPTION_INPUT);
    String pathOutput = line.getOptionValue(OPTION_OUTPUT);

    File dirTree = new File(pathInput);
    File fileOutput = new File(pathOutput);

    IdBboxListGeometryCreator task = new IdBboxListGeometryCreator(dirTree, fileOutput);
    task.execute();
}

From source file:com.nextdoor.bender.CreateSchema.java

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

    /*//w  w  w .  j ava2s. co m
     * Parse cli arguments
     */
    Options options = new Options();
    options.addOption(Option.builder().longOpt("out-file").hasArg()
            .desc("Filename to output schema to. Default: schema.json").build());
    options.addOption(Option.builder().longOpt("docson").hasArg(false)
            .desc("Create a schema that is able to be read by docson").build());
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    String filename = cmd.getOptionValue("out-file", "schema.json");

    /*
     * Write schema
     */
    BenderSchema schema = new BenderSchema();
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    JsonNode node = schema.getSchema();

    if (cmd.hasOption("docson")) {
        modifyNode(node);
    }

    mapper.writeValue(new File(filename), node);
}