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

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

Introduction

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

Prototype

public Option(String opt, boolean hasArg, String description) throws IllegalArgumentException 

Source Link

Document

Creates an Option using the specified parameters.

Usage

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  ww  .j a v  a2 s .  c om*/

    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:de.huberlin.german.korpling.laudatioteitool.App.java

public static void main(String[] args) {
    Options opts = new Options()
            .addOption(new Option("merge", true,
                    messages.getString("MERGE CONTENT FROM INPUT DIRECTORY INTO ONE TEI HEADER")))
            .addOption(new Option("split", true,
                    messages.getString("SPLIT ONE TEI HEADER INTO SEVERAL HEADER FILES")))
            .addOption(new Option("validate", true, messages.getString("VALIDATE DIRECTORY OR FILE")))
            .addOption(new Option("config", true, messages.getString("CONFIG FILE LOCATION")))
            .addOption(new Option("schemecorpus", true, messages.getString("CORPUS SCHEME LOCATION")))
            .addOption(new Option("schemedoc", true, messages.getString("DOCUMENT SCHEME LOCATION")))
            .addOption(new Option("schemeprep", true, messages.getString("PREPARATION SCHEME LOCATION")))
            .addOption(new Option("help", false, messages.getString("SHOW THIS HELP")));

    HelpFormatter fmt = new HelpFormatter();
    String usage = "java -jar teitool.jar [options] [output directory/file]";
    String header = messages.getString("HELP HEADER");
    String footer = messages.getString("HELP FOOTER");

    try {//w  w w.  ja va 2s.  co m
        CommandLineParser cliParser = new PosixParser();

        CommandLine cmd = cliParser.parse(opts, args);

        Properties props = new Properties();
        if (cmd.hasOption("config")) {
            props = readConfig(cmd.getOptionValue("config"));
        } // end if "config" given
        fillPropertiesFromCommandLine(props, cmd);

        if (cmd.hasOption("help")) {
            fmt.printHelp(usage, header, opts, footer);
        } else if (cmd.hasOption("validate")) {
            validate(cmd.getOptionValue("validate"), props.getProperty("schemecorpus"),
                    props.getProperty("schemedoc"), props.getProperty("schemeprep"));
        } else if (cmd.hasOption("merge")) {
            if (cmd.getArgs().length != 1) {
                System.out.println(messages.getString("YOU NEED TO GIVE AT AN OUTPUT FILE AS ARGUMENT"));
                System.exit(-1);
            }
            MergeTEI merge = new MergeTEI(new File(cmd.getOptionValue("merge")), new File(cmd.getArgs()[0]),
                    props.getProperty("schemecorpus"), props.getProperty("schemedoc"),
                    props.getProperty("schemeprep"));
            merge.merge();

            System.exit(0);
        } else if (cmd.hasOption("split")) {
            if (cmd.getArgs().length != 1) {
                System.out.println(messages.getString("YOU NEED TO GIVE AT AN OUTPUT DIRECTORY AS ARGUMENT"));
                System.exit(-1);
            }
            SplitTEI split = new SplitTEI(new File(cmd.getOptionValue("split")), new File(cmd.getArgs()[0]),
                    props.getProperty("schemecorpus"), props.getProperty("schemedoc"),
                    props.getProperty("schemeprep"));
            split.split();
            System.exit(0);
        } else {
            fmt.printHelp(usage, header, opts, footer);
        }

    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        fmt.printHelp(usage, header, opts, footer);
    } catch (LaudatioException ex) {
        System.err.println(ex.getMessage());
    } catch (UnsupportedOperationException ex) {
        System.err.println(ex.getMessage());
    }

    System.exit(1);

}

From source file:com.genentech.chemistry.tool.SDF2HtmlTab.java

public static void main(String[] args) throws ParseException, JDOMException, IOException {
    long start = System.currentTimeMillis();

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("in", true, "input sd file");
    opt.setRequired(true);/*from  w  w w.  j  av  a 2  s. c o  m*/
    options.addOption(opt);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    String inFile = cmd.getOptionValue("in");

    args = cmd.getArgs();
    if (args.length > 0) {
        exitWithHelp(options);
    }

    oemolistream ifs;
    Set<String> tagSet = getTagSet(inFile);

    System.out.println(
            "<html xmlns:v='urn:schemas-microsoft-com:vml' xmlns:o='urn:schemas-microsoft-com:office:office'>");
    System.out.println("<head>");
    System.out.println("<BASE href='" + BASEUrl + "'/>");
    System.out.println(
            "<link href='/" + Settings.SERVLET_CONTEXT + "/css/Aestel.css' rel='stylesheet' type='text/css'/>");

    System.out.println("<style type='text/css'>");
    System.out.println("td.stru { width: " + (IMGWidth + 2) + "px; height: " + (IMGHeigth + 4)
            + "px; vertical-align: top; }");
    System.out.println("table.grid tr.first { border-top: 3px solid black; }");
    // for tables in tables
    System.out.println("table.grid table td { border: 0px; text-align: right;}");
    System.out.println("table.grid table td:first-child { text-align: left;}");
    System.out.println("th.head { border-left: 1px solid black; border-bottom: 2px solid black;\n"
            + "          empty-cells: show; background-color: #6297ff; color: #000000;\n"
            + "          padding: 0em .3em 0em .3em; vertical-align: middle; }");
    System.out.println("</style>");

    System.out.println("</head>");
    System.out.println("<body>");

    System.out.println("<table class='grid'><tr>");
    System.out.println("<th class='head'>Structure</th>");

    for (String tag : tagSet)
        System.out.println("<th class='head'>" + tag + "</th>");
    System.out.println("</tr>");

    OEGraphMol mol = new OEGraphMol();
    ifs = new oemolistream(inFile);
    int iCounter = 0;
    while (oechem.OEReadMolecule(ifs, mol)) {
        iCounter++;
        System.out.println("<tr>");
        String smi = OETools.molToCanSmi(mol, true);
        String img = DepictHelper.DEFAULT.getExcelSmilesImageElement(BASEUrl, 120, 120, ImageType.PNG, smi,
                null);

        System.out.print(" <td class='stru'>");
        System.out.print(img);
        System.out.println("</td>");

        for (String tag : tagSet) {
            String val = oechem.OEGetSDData(mol, tag);

            System.out.print(" <td>");
            System.out.print(val);
            System.out.println("</td>");
        }

        System.out.println("</tr>");
    }

    System.out.println("</table></body></html>");

    System.err.printf("SDF2HtmlTab: Exported %d structures in %dsec\n", iCounter,
            (System.currentTimeMillis() - start) / 1000);
}

From source file:com.blackducksoftware.tools.vuln_collector.VCRunner.java

public static void main(String[] args) throws Exception {
    System.out.println(TITLE);//from  w  w  w  . j a va  2  s  .c  o  m
    CommandLineParser parser = new DefaultParser();

    options.addOption("h", "help", false, "show help.");

    Option projectNameOption = new Option("projectName", true, "Name of Project (optional)");
    projectNameOption.setRequired(false);
    options.addOption(projectNameOption);

    Option configFileOption = new Option("config", true, "Location of configuration file (required)");
    configFileOption.setRequired(true);
    options.addOption(configFileOption);

    try {

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

        if (cmd.hasOption("h"))
            help();

        String[] projectNameList = null;
        File configFile = null;

        if (cmd.hasOption(VCConstants.CL_PROJECT_NAME)) {
            String projectName = cmd.getOptionValue(VCConstants.CL_PROJECT_NAME);
            log.info("Project name: " + projectName);
            // Could be a single project or comma delim
            projectNameList = VCProcessor.getProjectList(projectName);
        }

        // Config File
        if (cmd.hasOption(VCConstants.CL_CONFIG)) {
            String configFilePath = cmd.getOptionValue(VCConstants.CL_CONFIG);
            log.info("Config file location: " + configFilePath);
            configFile = new File(configFilePath);
            if (!configFile.exists()) {
                log.error("Configuration file does not exist at location: " + configFile);
                System.exit(-1);
            }
        } else {
            log.error("Must specify configuration file!");
            help();
        }

        VCProcessor processor = new VCProcessor(configFile.toString(), projectNameList);
        processor.processReport();

    } catch (ParseException e) {
        log.error("Error parsing: " + e.getMessage());
        help();
    } catch (Exception e) {
        log.error("General error: " + e.getMessage());

    }

}

From source file:eu.delving.x3ml.X3MLCommandLine.java

public static void main(String[] args) {
    Option xml = new Option("xml", true, "XML input records: -xml input.xml (@ = stdin)");
    xml.setRequired(true);/*from   w w  w  . jav  a2  s  . co  m*/
    Option x3ml = new Option("x3ml", true, "X3ML mapping definition: -x3ml mapping.x3ml (@ = stdin)");
    x3ml.setRequired(true);
    Option rdf = new Option("rdf", true, "The RDF output file name: -rdf output.rdf");
    Option policy = new Option("policy", true, "The value policy file: -policy policy.xml");
    Option rdfFormat = new Option("format", true,
            "Output format: -format application/n-triples, text/turtle, application/rdf+xml (default)");
    Option validate = new Option("validate", false, "Validate X3ML v1.0 using XSD");
    Option uuidTestSize = new Option("uuidTestSize", true,
            "Create a test UUID generator of the given size. Default is UUID from operating system");
    options.addOption(rdfFormat).addOption(rdf).addOption(x3ml).addOption(xml).addOption(policy)
            .addOption(validate).addOption(uuidTestSize);
    try {
        CommandLine cli = PARSER.parse(options, args);
        int uuidTestSizeValue = -1;
        String uuidTestSizeString = cli.getOptionValue("uuidTestSize");
        if (uuidTestSizeString != null) {
            uuidTestSizeValue = Integer.parseInt(uuidTestSizeString);
        }
        go(cli.getOptionValue("xml"), cli.getOptionValue("x3ml"), cli.getOptionValue("policy"),
                cli.getOptionValue("rdf"), cli.getOptionValue("format"), cli.hasOption("validate"),
                uuidTestSizeValue);
    } catch (Exception e) {
        error(e.getMessage());
    }

}

From source file:com.browseengine.bobo.index.MakeBobo.java

/**
 * @param args/*from   ww  w.j  av a  2s . co  m*/
 */
public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

    Option help = new Option("help", false, "print this message");

    OptionBuilder.withArgName("path");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("data source - required");
    Option src = OptionBuilder.create("source");
    src.setRequired(true);

    OptionBuilder.withArgName("path");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("index to create - required");
    Option index = OptionBuilder.create("index");
    index.setRequired(true);

    OptionBuilder.withArgName("file");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("field configuration - optional");
    Option conf = OptionBuilder.create("conf");

    OptionBuilder.withArgName("class");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("class name of the data digester - default: xml digester");
    Option digesterOpt = OptionBuilder.create("digester");

    OptionBuilder.withArgName("name");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("character set name - default: UTF-8");
    Option charset = OptionBuilder.create("charset");

    OptionBuilder.withArgName("maxdocs");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("maximum number of documents - default: 100");
    Option maxdocs = OptionBuilder.create("maxdocs");

    Options options = new Options();
    options.addOption(help);
    options.addOption(conf);
    options.addOption(index);
    options.addOption(src);
    options.addOption(charset);
    options.addOption(digesterOpt);
    options.addOption(maxdocs);

    //       create the parser

    CommandLineParser parser = new BasicParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String output = line.getOptionValue("index");
        File data = new File(line.getOptionValue("source"));

        Class digesterClass;
        if (line.hasOption("digester"))
            digesterClass = Class.forName(line.getOptionValue("digester"));
        else
            throw new RuntimeException("digester not specified");

        Charset chset;
        if (line.hasOption("charset")) {
            chset = Charset.forName(line.getOptionValue("charset"));
        } else {
            chset = Charset.forName("UTF-8");
        }

        int maxDocs;
        try {
            maxDocs = Integer.parseInt(line.getOptionValue("maxdocs"));
        } catch (Exception e) {
            maxDocs = 100;
        }

        FileDigester digester;
        try {
            Constructor constructor = digesterClass.getConstructor(new Class[] { File.class });
            digester = (FileDigester) constructor.newInstance(new Object[] { data });
            digester.setCharset(chset);
            digester.setMaxDocs(maxDocs);
        } catch (Exception e) {
            throw new RuntimeException("Invalid digester class.", e);
        }

        BoboIndexer indexer = new BoboIndexer(digester, FSDirectory.open(new File(output)));
        indexer.index();
    } catch (ParseException exp) {
        exp.printStackTrace();
        usage(options);
    } catch (ClassNotFoundException e) {
        System.out.println("Invalid digester class.");
        usage(options);
    }
}

From source file:com.blackducksoftware.tools.nrt.NoticeReportTool.java

/**
 * @param args//from  w  w  w .j a va  2 s .c om
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    System.out.println("Notice Report Tool for Black Duck Suite");
    CommandLineParser parser = new DefaultParser();

    options.addOption("h", "help", false, "show help.");

    Option applicationOption = new Option(NRTConstants.CL_APPLICATION_TYPE, true,
            "Application type [PROTEX|CODECENTER] (required)");
    applicationOption.setRequired(true);
    options.addOption(applicationOption);

    Option configFileOption = new Option(NRTConstants.CL_CONFIG_FILE, true,
            "Location of configuration file (required)");
    configFileOption.setRequired(true);
    options.addOption(configFileOption);

    Option projectNameOption = new Option(NRTConstants.CL_PROJECT_NAME, true,
            "Name of Protex project (will override configuration file)");
    projectNameOption.setRequired(false);
    options.addOption(projectNameOption);

    File configFile = null;
    APPLICATION applicationType = null;
    String projectName = null;

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

        if (cmd.hasOption("h")) {
            help();
        }

        // Config File
        if (cmd.hasOption(NRTConstants.CL_CONFIG_FILE)) {
            String configFilePath = cmd.getOptionValue(NRTConstants.CL_CONFIG_FILE);
            log.info("Config file location: " + configFilePath);
            configFile = new File(configFilePath);
            if (!configFile.exists()) {
                log.error("Configuration file does not exist at location: " + configFile);
                System.exit(-1);
            }
        } else {
            log.error("Must specify configuration file!");
            help();
        }

        if (cmd.hasOption(NRTConstants.CL_APPLICATION_TYPE)) {
            String bdsApplicationType = cmd.getOptionValue(NRTConstants.CL_APPLICATION_TYPE);

            try {
                applicationType = APPLICATION.valueOf(bdsApplicationType);
            } catch (IllegalArgumentException e) {
                log.error("No such application type recognized: " + bdsApplicationType);
                help();
            }

        } else {
            help();
        }

        if (cmd.hasOption(NRTConstants.CL_PROJECT_NAME)) {
            projectName = cmd.getOptionValue(NRTConstants.CL_PROJECT_NAME);
            log.info("User specified project name: " + projectName);
        }

        NoticeReportProcessor processor = new NoticeReportProcessor(configFile.getAbsolutePath(),
                applicationType, projectName);
        try {
            processor.connect();
        } catch (Exception e) {
            log.error("Connection problems: " + e.getMessage());
            throw new Exception(e);
        }
        processor.processReport();

    } catch (Exception e) {
        log.error("Error: " + e.getMessage());
        help();
    }
}

From source file:com.yahoo.pasc.paxos.client.PaxosClient.java

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

    CommandLineParser parser = new PosixParser();
    Options options;//from   w ww.j a v  a 2 s .  c  o m

    {
        Option id = new Option("i", true, "client id");
        Option clients = new Option("c", true, "number of clients");
        Option host = new Option("l", true, "leader (hostname:port)");
        Option servers = new Option("s", true, "number of servers");
        Option quorum = new Option("q", true, "necesarry quorum at the client");
        Option port = new Option("p", true, "port used by client");
        Option buffer = new Option("b", true, "number of concurrent clients");
        Option timeout = new Option("t", true, "timeout in milliseconds");
        Option udp = new Option("u", false, "use UDP");
        Option zookeeper = new Option("z", true, "zookeeper connection string");
        Option warmup = new Option("w", true, "warmup messagges");
        Option measuring = new Option("m", true, "measuring time");
        Option request = new Option("r", true, "request size");
        Option frequency = new Option("f", true, "frequency of throughput info");
        Option anm = new Option("a", false, "use protection");
        Option inlineThresh = new Option("n", true, "threshold for sending requests iNline with accepts ");
        Option asynSize = new Option("y", true, "size of async messages queue");

        options = new Options();
        options.addOption(id).addOption(host).addOption(servers).addOption(quorum).addOption(port)
                .addOption(warmup).addOption(buffer).addOption(timeout).addOption(udp).addOption(zookeeper)
                .addOption(clients).addOption(measuring).addOption(request).addOption(frequency).addOption(anm)
                .addOption(inlineThresh).addOption(asynSize);
    }

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

        String host = line.hasOption('l') ? line.getOptionValue('l')
                : "localhost:20548,localhost:20748,localhost:20778";
        String zkConnection = line.hasOption('z') ? line.getOptionValue('z') : "localhost:2181";
        int clientIds = line.hasOption('i') ? Integer.parseInt(line.getOptionValue('i')) : 0;
        int servers = line.hasOption('s') ? Integer.parseInt(line.getOptionValue('s')) : 3;
        int quorum = line.hasOption('q') ? Integer.parseInt(line.getOptionValue('q')) : 1;
        int buffer = line.hasOption('b') ? Integer.parseInt(line.getOptionValue('b')) : 1;
        int timeout = line.hasOption('t') ? Integer.parseInt(line.getOptionValue('t')) : 5000;
        int clients = line.hasOption('c') ? Integer.parseInt(line.getOptionValue('c')) : 1;
        int requestSize = line.hasOption('r') ? Integer.parseInt(line.getOptionValue('r')) : 0;
        int inlineThreshold = line.hasOption('n') ? Integer.parseInt(line.getOptionValue('n')) : 1000;
        int asynSize = line.hasOption('y') ? Integer.parseInt(line.getOptionValue('y')) : 100;
        boolean protection = line.hasOption('a');

        int threads = Runtime.getRuntime().availableProcessors() * 2;
        final ExecutionHandler executor = new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(threads,
                1024 * 1024, 1024 * 1024 * 1024, 30, TimeUnit.SECONDS, Executors.defaultThreadFactory()));

        String[] serverHosts = host.split(",");

        ServerHelloHandler shello = new ServerHelloHandler();
        ReplyHandler reply = new ReplyHandler();
        SubmitHandler submit = new SubmitHandler();
        TimeoutHandler tout = new TimeoutHandler();
        AsyncMessageHandler asyncm = new AsyncMessageHandler();
        ByeHandler bye = new ByeHandler();
        HelloHandler hello = new HelloHandler();

        Random rnd = new Random();

        for (int i = 0; i < buffer; ++i) {
            ClientState clientState = new ClientState(servers, quorum, inlineThreshold, asynSize);
            final PascRuntime<ClientState> runtime = new PascRuntime<ClientState>(protection);
            runtime.setState(clientState);
            runtime.addHandler(ServerHello.class, shello);
            runtime.addHandler(Reply.class, reply);
            runtime.addHandler(Submit.class, submit);
            runtime.addHandler(Timeout.class, tout);
            runtime.addHandler(AsyncMessage.class, asyncm);
            runtime.addHandler(Bye.class, bye);
            runtime.addHandler(Hello.class, hello);

            final PaxosClientHandler handler = new PaxosClientHandler(runtime, new SimpleClient(requestSize),
                    serverHosts, clients, timeout, zkConnection, executor);

            if (line.hasOption('w'))
                handler.setWarmup(Integer.parseInt(line.getOptionValue('w')));
            if (line.hasOption('m'))
                handler.setMeasuringTime(Integer.parseInt(line.getOptionValue('m')));
            if (line.hasOption('f'))
                handler.setPeriod(Integer.parseInt(line.getOptionValue('f')));

            handler.start();

            Thread.sleep(rnd.nextInt(200));
        }
    } catch (Exception e) {
        System.err.println("Unexpected exception " + e);
        e.printStackTrace();

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Paxos", options);

        System.exit(-1);
    }
}

From source file:com.genentech.retrival.tabExport.TABExporter.java

public static void main(String[] args) throws ParseException, JDOMException, IOException {
    long start = System.currentTimeMillis();
    int nStruct = 0;

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("sqlFile", true, "sql-xml file");
    opt.setRequired(true);/*w ww  .ja  v  a  2s .  c  o m*/
    options.addOption(opt);

    opt = new Option("sqlName", true, "name of SQL element in xml file");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("o", true, "output file");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("newLineReplacement", true,
            "If given newlines in fields will be replaced by this string.");
    options.addOption(opt);

    opt = new Option("noHeader", false, "Do not output header line");
    options.addOption(opt);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    String outFile = cmd.getOptionValue("o");
    String sqlFile = cmd.getOptionValue("sqlFile");
    String sqlName = cmd.getOptionValue("sqlName");
    String newLineReplacement = cmd.getOptionValue("newLineReplacement");

    args = cmd.getArgs();

    try {
        PrintStream out = System.out;
        if (outFile != null)
            out = new PrintStream(outFile);

        SQLStatement stmt = SQLStatement.createFromFile(new File(sqlFile), sqlName);
        Object[] sqlArgs = args;
        if (stmt.getParamTypes().length != args.length) {
            System.err.printf(
                    "\nWarining sql statement needs %d parameters but got only %d. Filling up with NULLs.\n",
                    stmt.getParamTypes().length, args.length);
            sqlArgs = new Object[stmt.getParamTypes().length];
            System.arraycopy(args, 0, sqlArgs, 0, args.length);
        }

        Selecter sel = Selecter.factory(stmt);
        if (!sel.select(sqlArgs)) {
            System.err.println("No rows returned!");
            System.exit(0);
        }

        String[] fieldNames = sel.getFieldNames();
        if (fieldNames.length == 0) {
            System.err.println("Query did not return any columns");
            exitWithHelp(options);
        }

        if (!cmd.hasOption("noHeader")) {
            StringBuilder sb = new StringBuilder(200);
            for (String f : fieldNames)
                sb.append(f).append('\t');
            if (sb.length() > 1)
                sb.setLength(sb.length() - 1); // chop last \t
            String header = sb.toString();

            out.println(header);
        }

        StringBuilder sb = new StringBuilder(200);
        while (sel.hasNext()) {
            Record sqlRec = sel.next();
            sb.setLength(0);

            for (int i = 0; i < fieldNames.length; i++) {
                String fld = sqlRec.getStrg(i);
                if (newLineReplacement != null)
                    fld = NEWLinePattern.matcher(fld).replaceAll(newLineReplacement);

                sb.append(fld).append('\t');
            }

            if (sb.length() > 1)
                sb.setLength(sb.length() - 1); // chop last \t
            String row = sb.toString();

            out.println(row);

            nStruct++;
        }

    } catch (Exception e) {
        throw new Error(e);
    } finally {
        System.err.printf("TABExporter: Exported %d records in %dsec\n", nStruct,
                (System.currentTimeMillis() - start) / 1000);
    }
}

From source file:gr.forth.ics.isl.preprocessfilter1.controller.Controller.java

public static void main(String[] args) throws XPathExpressionException, ParserConfigurationException,
        SAXException, IOException, PreprocessFilterException, org.apache.commons.cli.ParseException {
    PropertyReader prop = new PropertyReader();

    //The following block of code is executed if there are arguments from the command line
    if (args.length > 0) {

        try {/*from www .j a  v a 2  s . c  o m*/

            //The values of the arguments are handled as Option instances
            Options options = new Options();
            CommandLineParser PARSER = new PosixParser();

            Option inputFile = new Option("inputFile", true, "input xml file");
            Option outputFile = new Option("outputFile", true, "output xml file");
            Option parentNode = new Option("parentNode", true, "output xml file");
            Option delimeter = new Option("delimeter", true, "output xml file");
            Option newParentNode = new Option("newParentNode", true, "output xml file");
            Option intermediateNodes = new Option("intermediateNodes", true, "output xml file");
            Option intermediateNode = new Option("intermediateNode", true, "output xml file");

            options.addOption(inputFile).addOption(outputFile).addOption(parentNode).addOption(newParentNode)
                    .addOption(intermediateNode).addOption(intermediateNodes).addOption(delimeter);

            CommandLine cli = PARSER.parse(options, args);

            String inputFileArg = cli.getOptionValue("inputFile");
            String outputFileArg = cli.getOptionValue("outputFile");
            String parentNodeArg = cli.getOptionValue("parentNode");
            String newParentNodeArg = cli.getOptionValue("newParentNode");
            String intermediateNodeArg = cli.getOptionValue("intermediateNode");
            String intermediateNodesArg = cli.getOptionValue("intermediateNodes");
            String delimeterArg = cli.getOptionValue("delimeter");

            PreprocessFilterUtilities process = new PreprocessFilterUtilities();

            //System.out.println("INPUT:"+inputFileArg);
            //System.out.println("OUTPUT:"+outputFileArg);
            //System.out.println("PARENT NODE:"+parentNodeArg);
            //System.out.println("NEW PARENT NODE:"+newParentNodeArg);
            //System.out.println("INTERMEDIATE NODE:"+intermediateNodeArg);
            //System.out.println("INTERMEDIATE NODES:"+intermediateNodesArg);
            //System.out.println("DELIMETER:"+delimeterArg);
            //The filter's code is executed with the command line arguments as parameters
            if (process.createOutputFile(inputFileArg, outputFileArg, parentNodeArg, newParentNodeArg,
                    intermediateNodeArg, intermediateNodesArg, delimeterArg)) {
                System.out.println("Succesfull PreProcessing!!!");
            }
        } catch (PreprocessFilterException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            throw new PreprocessFilterException("PreProcess Filter Exception:", ex);
        }

    } //If there are no command line arguments then the .config file is being used.
    else {

        try {

            String inputFilePathProp = prop.getProperty(inputFilePath);
            String outputFilePathProp = prop.getProperty(outputFilePath);
            String parentNodeProp = prop.getProperty(parentNode);
            String delimeterProp = prop.getProperty(delimeter);

            String newParentNodeProp = prop.getProperty(newParentNode);
            String intermediateNodesProp = prop.getProperty(intermediateNodes);
            String intermediateNodeProp = prop.getProperty(intermediateNode);

            PreprocessFilterUtilities process = new PreprocessFilterUtilities();

            //The filter's code is executed with the .config file's resources as parameters
            if (process.createOutputFile(inputFilePathProp, outputFilePathProp, parentNodeProp,
                    newParentNodeProp, intermediateNodeProp, intermediateNodesProp, delimeterProp)) {
                System.out.println("Succesfull PreProcessing!!!");
            }
        } catch (PreprocessFilterException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            throw new PreprocessFilterException("PreProcess Filter Exception:", ex);
        }

    }
}