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:com.ethercis.vehr.Launcher.java

public void start(String[] args) throws Exception {
    boolean debug = false;
    List<String> normalizedArguments = new ArrayList<>(Arrays.asList(args));

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

    if (commandLine.hasOption("debug"))
        debug = true;/* w ww .ja  v a2  s. co  m*/

    if (commandLine.hasOption("dialect")) {
        String compatibilityValue = commandLine.getOptionValue("dialect", "STANDARD");
        //TODO: add compatibility argument in args
        normalizedArguments.add("-" + I_ServiceRunMode.SERVER_DIALECT_PARAMETER);
        normalizedArguments.add(I_ServiceRunMode.DialectSpace.valueOf(compatibilityValue).name());
    }

    Integer httpPort = Integer.parseInt(commandLine.getOptionValue(command_server_port, default_port));
    String httpHost = commandLine.getOptionValue(command_server_host, default_host);

    InetSocketAddress socketAddress = new InetSocketAddress(httpHost, httpPort);

    logger.info("Server starting on host:" + httpHost + " port:" + httpPort);

    server = new Server(socketAddress);
    if (debug)
        server.setStopAtShutdown(true);
    //create and initialize vEhrHandler
    vEhrGateServlet = new VEhrGateServlet();
    vEhrGateServlet.init(normalizedArguments.toArray(new String[] {}));

    ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/",
            ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);

    //add filter to allow CORS
    FilterHolder cors = new FilterHolder(CrossOriginFilter.class);
    //        FilterHolder cors = servletContextHandler.addFilter(CrossOriginFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, null);
    cors.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
    cors.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_EXPOSE_HEADERS_HEADER, "*");
    cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET, POST, DELETE, PUT, OPTIONS, HEAD");
    cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM,
            "X-Requested-With,Content-Type,Accept,Origin");
    cors.setName("cross-origin");
    FilterMapping filterMapping = new FilterMapping();
    filterMapping.setFilterName("cross-origin");
    filterMapping.setPathSpec("*");
    servletContextHandler.addFilter(cors, "/*", EnumSet.allOf(DispatcherType.class));
    //        servletContextHandler.addFilter(cors, "/*", null);
    //        servletContextHandler.getServletHandler().addFilter(cors, filterMapping);

    ServletHolder servletHolder = new ServletHolder(vEhrGateServlet);
    servletContextHandler.addServlet(servletHolder, "/");

    HandlerList handlerList = new HandlerList();
    handlerList.setHandlers(new Handler[] { servletContextHandler, new DefaultHandler() });
    server.setHandler(handlerList);

    try {
        server.start();
    } catch (BindException e) {
        logger.error("Address already in use! (" + socketAddress.toString() + ")");
        throw new IllegalArgumentException("Address already in use! (" + socketAddress.toString() + ")");
    }
    logger.info("Server listening at:" + server.getURI().toString());
    if (!debug)
        server.join();

}

From source file:com.antsdb.saltedfish.nosql.LogReplayer.java

private void run(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    CommandLine line = parser.parse(getOptions(), args);

    // help/*from   w ww  .j a v  a  2  s.c  o m*/

    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("replay", getOptions());
        return;
    }

    // other options

    this.hexDump = line.hasOption("hex");
    this.notrx = line.hasOption("notrx");
    if (line.getOptionValue("table") != null) {
        this.tableId = Integer.parseInt(line.getOptionValue("table"));
    }
    if (line.getOptionValue("rowid") != null) {
        this.rowid = Long.parseLong(line.getOptionValue("rowid"));
    }
    Heap heap = new BluntHeap();
    if (line.getOptionValue("key") != null) {
        String keyText = line.getOptionValue("key");
        byte[] keyBytes = Base64.getDecoder().decode(keyText);
        KeyBytes key = KeyBytes.allocSet(heap, keyBytes);
        this.pKey = key.getAddress();
    }

    // start offset

    if (line.getOptionValue('s') != null) {
        String literal = line.getOptionValue('s');
        this.offset = Long.parseUnsignedLong(literal, 16);
    }

    // length

    if (line.getOptionValue('n') != null) {
        String literal = line.getOptionValue('n');
        this.length = Integer.parseInt(literal);
    }

    // now go

    if (line.getOptionValue("home") == null) {
        err.println("error: data directory is not specified");
        return;
    }
    this.home = new File(line.getOptionValue("home"));
    if (!home.isDirectory()) {
        err.println("error: invalid home directory");
        return;
    }
    if (!new File(this.home, "checkpoint.bin").exists()) {
        err.println("error: invalid home directory");
        return;
    }

    // go go go
    this.out.println("log location: {}", this.home);
    this.spaceman = new SpaceManager(home, false);
    spaceman.init();
    Gobbler gobbler = new Gobbler(spaceman, false);
    findStart();
    println("start position: %08x", this.offset);
    try {
        gobbler.replay(this.offset, true, this);
    } catch (JumpException ignored) {
    }
}

From source file:com.act.utils.parser.GenbankInterpreter.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());// w w w .java2 s.com
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        LOGGER.error("Argument parsing failed: %s", e.getMessage());
        HELP_FORMATTER.printHelp(GenbankInterpreter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(GenbankInterpreter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    File genbankFile = new File(cl.getOptionValue(OPTION_GENBANK_PATH));
    String seq_type = cl.getOptionValue(OPTION_SEQ_TYPE);

    if (!genbankFile.exists()) {
        String msg = "Genbank file path is null";
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    } else {
        GenbankInterpreter reader = new GenbankInterpreter(genbankFile, seq_type);
        reader.init();
        reader.printSequences();
    }
}

From source file:com.netflix.imfutility.ttmltostl.inputparameters.CmdLineParametersParser.java

/**
 * Parses cmd line arguments./*from   w  w w. ja va2s. c  o m*/
 *
 * @param args arguments from a command line
 * @return a command line parameter object or null if help was invoked.
 */
public CmdLineParameters parseCmdOptions(String[] args) throws ParseException {
    // create the parser
    CommandLineParser parser = new DefaultParser();
    CommandLine line = parser.parse(options, args);

    // --help
    if (line.hasOption(help.getLongOpt())) {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp("ttml-to-stl", options);
        return null;
    }

    CmdLineParameters result = new CmdLineParameters();
    // --ttml parameters
    for (Option option : line.getOptions()) {
        if (option.equals(ttmlFile)) {
            TtmlInDescriptor ttmlInDescriptor = new TtmlInDescriptor();
            try {
                ttmlInDescriptor.setFile(option.getValue(0));
                ttmlInDescriptor.setOffsetMS(parseTtmlParameter(option, 1, "offsetMS"));
                ttmlInDescriptor.setStartMS(parseTtmlParameter(option, 2, "startMS"));
                ttmlInDescriptor.setEndMS(parseTtmlParameter(option, 3, "endMS"));
            } catch (IndexOutOfBoundsException e) {
                //It is error only if don't have file name
                //For required file it may not be thrown. We will check it later.
            }

            if (ttmlInDescriptor.getFile() == null) {
                throw new ParseException("--ttml parameter must have at least <file> attribute defined.");
            }

            result.getTtmlInDescriptors().add(ttmlInDescriptor);
        }
    }
    if (result.getTtmlInDescriptors().size() == 0) {
        throw new ParseException("At least one input TTML file must be provided");
    }

    // TTML mode parameters
    boolean doOutputTTML = line.hasOption(outputTTML.getLongOpt());
    if (doOutputTTML) {
        result.setDoOuputTTML(true);
        result.setOutputTTMLFile(line.getOptionValue(outputTTML.getLongOpt()));
    }

    // STL mode parameters
    boolean doOutputSTL = line.hasOption(outputSTL.getLongOpt());
    if (doOutputSTL) {
        result.setDoOutputSTL(true);
        result.setOutputSTLFile(line.getOptionValue(outputSTL.getLongOpt()));
        if (!line.hasOption(metadataOpt.getLongOpt())) {
            throw new ParseException("A metadata.xml must be specified for STL mode");
        }
        String metadataXml = line.getOptionValue(metadataOpt.getLongOpt());
        if (!new File(metadataXml).isFile()) {
            throw new ParseException("A metadata.xml must be an existing file.");
        }
        result.setMetadataXml(metadataXml);
    }

    return result;
}

From source file:com.act.utils.CLIUtil.java

public CommandLine parseCommandLine(String[] args) {
    CommandLine cl = null;// www. j  a v a  2 s.  c  om
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        LOGGER.error("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(callingClass.getCanonicalName(), helpMessage, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(callingClass.getCanonicalName(), helpMessage, opts, null, true);
        System.exit(0);
    }

    commandLine = cl;

    return cl;
}

From source file:fr.ortolang.diffusion.client.cmd.CheckBagCommand.java

@Override
public void execute(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;//  ww w. ja  va  2s  . com
    String root = "";
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help();
        }

        if (cmd.hasOption("f")) {
            fix = true;
        }

        if (cmd.hasOption("p")) {
            root = cmd.getOptionValue("p");
        } else {
            help();
        }

        String[] credentials = getCredentials(cmd);
        String username = credentials[0];
        String password = credentials[1];

        client = OrtolangClient.getInstance();
        if (username.length() > 0) {
            client.getAccountManager().setCredentials(username, password);
            client.login(username);
        }
        System.out.println("Connected as user: " + client.connectedProfile());

        if (!Files.exists(Paths.get(root))) {
            errors.append("-> Le chemin de base (").append(root).append(") n'existe pas\r\n");
        } else {
            if (!Files.exists(Paths.get(root, "data", "publication.properties"))) {
                errors.append("-> publication.properties NOT found\r\n");
            }
            if (!Files.exists(Paths.get(root, "data", "workspace.properties"))) {
                errors.append("-> workspace.properties NOT found\r\n");
            } else {
                checkWorkspaceProperties(Paths.get(root, "data", "workspace.properties"));
            }

            if (Files.exists(Paths.get(root, "data", "snapshots"))) {
                Files.list(Paths.get(root, "data", "snapshots")).forEach(this::checkSnapshotMetadata);
                Files.list(Paths.get(root, "data", "snapshots")).forEach(this::checkPermissions);
            }

            if (Files.exists(Paths.get(root, "data", "head"))) {
                checkSnapshotMetadata(Paths.get(root, "data", "head"));
            }
        }
        if (errors.length() > 0) {
            System.out.println("## Some errors has been found : ");
            System.out.print(errors.toString());
            if (fix) {
                System.out.println("## Some errors has been fixed : ");
                System.out.print(fixed.toString());
            }
        } else {
            System.out.println("No error found.");
        }

    } catch (ParseException | IOException e) {
        System.out.println("Failed to parse command line properties: " + e.getMessage());
        help();
    } catch (OrtolangClientException | OrtolangClientAccountException e) {
        System.out.println("Unexpected error !!");
        e.printStackTrace();
    }
}

From source file:net.slkdev.swagger.confluence.cli.SwaggerConfluence.java

private static CommandLine parseCommandLineOptions(final Options options, final String[] args) {
    final CommandLineParser commandLineParser = new DefaultParser();

    try {// ww w .ja v  a  2  s . c o m
        return commandLineParser.parse(options, args);

    } catch (ParseException e) {
        throw new SwaggerConfluenceConfigurationException("Error Parsing Command Line Arguments!", e);
    }
}

From source file:ai.grakn.migration.base.io.MigrationOptions.java

protected <T extends MigrationOptions> T parse(String[] args) {
    try {/*from  w  w  w. j  a  v  a 2  s .com*/
        CommandLineParser parser = new DefaultParser();
        command = parser.parse(options, args);
        numberOptions = command.getOptions().length;

        return (T) this;
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.usf.cutr.gtfsrtvalidator.Main.java

/**
 * Returns the port to use from command line arguments, or 8080 if no args are provided
 *
 * @param args/*w  ww .jav  a2  s.  c o m*/
 * @return the port to use from command line arguments, or 8080 if no args are provided
 */
private static int getPortFromArgs(String[] args) throws ParseException {
    int port = 8080;
    Option portOption = Option.builder(PORT_NUMBER_OPTION).hasArg().desc("Port number the server should run on")
            .build();
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();
    options.addOption(portOption);
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption(PORT_NUMBER_OPTION)) {
        port = Integer.valueOf(cmd.getOptionValue(PORT_NUMBER_OPTION));
    }
    return port;
}

From source file:com.yahoo.athenz.example.zms.tls.client.ZMSTLSClient.java

private static CommandLine parseCommandLine(String[] args) {

    Options options = new Options();

    Option resource = new Option("r", "resource", true, "resource value");
    resource.setRequired(true);//from   w  w  w.  j  a v a 2 s .c  o  m
    options.addOption(resource);

    Option action = new Option("a", "action", true, "action");
    action.setRequired(true);
    options.addOption(action);

    Option principal = new Option("u", "principal", true, "principal to check for");
    principal.setRequired(true);
    options.addOption(principal);

    Option key = new Option("k", "key", true, "private key path");
    key.setRequired(true);
    options.addOption(key);

    Option cert = new Option("c", "cert", true, "certficate path");
    cert.setRequired(true);
    options.addOption(cert);

    Option trustStore = new Option("t", "trustStorePath", true, "CA TrustStore path");
    trustStore.setRequired(true);
    options.addOption(trustStore);

    Option trustStorePassword = new Option("p", "trustStorePassword", true, "CA TrustStore password");
    trustStorePassword.setRequired(true);
    options.addOption(trustStorePassword);

    Option zmsUrl = new Option("z", "zmsurl", true, "ZMS Server url");
    zmsUrl.setRequired(true);
    options.addOption(zmsUrl);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("zms-tls-client", options);
        System.exit(1);
    }

    return cmd;
}