Example usage for org.apache.commons.cli HelpFormatter printHelp

List of usage examples for org.apache.commons.cli HelpFormatter printHelp

Introduction

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

Prototype

public void printHelp(String cmdLineSyntax, Options options) 

Source Link

Document

Print the help for options with the specified command line syntax.

Usage

From source file:de.zazaz.iot.bosch.indego.util.CmdLineTool.java

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

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

    options.addOption(Option //
            .builder() //
            .longOpt("base-url") //
            .desc("Sets the base URL of the web service") //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("u") //
            .longOpt("username") //
            .desc("The username for authentication (usually mail address)") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("p") //
            .longOpt("password") //
            .desc("The password for authentication") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("c") //
            .longOpt("command") //
            .desc(String.format("The command, which should be sent to the device (%s)", commandList)) //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("q") //
            .longOpt("query-status") //
            .desc("Queries the status of the device") //
            .build());
    options.addOption(Option //
            .builder() //
            .longOpt("query-calendar") //
            .desc("Queries the calendar of the device") //
            .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(CmdLineTool.class.getName(), options);
        System.exit(1);
        return;
    }

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

    String baseUrl = cmds.getOptionValue("base-url");
    String username = cmds.getOptionValue('u');
    String password = cmds.getOptionValue('p');
    String commandStr = cmds.getOptionValue('c');
    boolean doQueryState = cmds.hasOption('q');
    boolean doQueryCalendar = cmds.hasOption("query-calendar");

    DeviceCommand command = null;
    if (commandStr != null) {
        try {
            command = DeviceCommand.valueOf(commandStr.toUpperCase());
        } catch (IllegalArgumentException ex) {
            System.err.println("Unknown command: " + commandStr);
            System.exit(1);
        }
    }

    IndegoController controller = new IndegoController(baseUrl, username, password);
    try {
        System.out.println("Connecting to device");
        controller.connect();
        System.out.println(String.format("...Connection established. Device serial number is: %s",
                controller.getDeviceSerialNumber()));
        if (command != null) {
            System.out.println(String.format("Sending command (%s)...", command));
            controller.sendCommand(command);
            System.out.println("...Command sent successfully!");
        }
        if (doQueryState) {
            System.out.println("Querying device state");
            DeviceStateInformation state = controller.getState();
            printState(System.out, state);
        }
        if (doQueryCalendar) {
            System.out.println("Querying device calendar");
            DeviceCalendar calendar = controller.getCalendar();
            printCalendar(System.out, calendar);
        }
    } catch (IndegoException ex) {
        ex.printStackTrace();
        System.exit(2);
    } finally {
        controller.disconnect();
    }
}

From source file:de.tudarmstadt.ukp.teaching.uima.nounDecompounding.web1t.LuceneIndexer.java

/**
 * Execute the indexer. Following parameter are allowed:
 * /* w w  w .j  a  v  a  2 s  . co m*/
 *   * --web1t The folder with all extracted n-gram files
 *   * --outputPath The lucene index folder
 *   * --index (optional) Number of how many indexes should be created. Default: 1
 * 
 * @param args
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("web1t")
            .withDescription("Folder with the web1t extracted documents").hasArg().isRequired().create());
    options.addOption(OptionBuilder.withLongOpt("outputPath")
            .withDescription("File, where the index should be created").hasArg().isRequired().create());
    options.addOption(OptionBuilder.withLongOpt("index")
            .withDescription("(optional) Number of how many indexes should be created. Default: 1").hasArg()
            .create());
    options.addOption(OptionBuilder.withLongOpt("igerman98").withDescription(
            "(optional) If this argument is set, only words of the german dictionary will be added to the index")
            .create());

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

        int i = 1;
        if (cmd.hasOption("index")) {
            i = Integer.valueOf(cmd.getOptionValue("index"));
        }

        LuceneIndexer indexer = new LuceneIndexer(new File(cmd.getOptionValue("web1t")),
                new File(cmd.getOptionValue("outputPath")), i);

        if (cmd.hasOption("igerman98")) {
            indexer.setDictionary(new IGerman98Dictionary(new File("src/main/resources/de_DE.dic"),
                    new File("src/main/resources/de_DE.aff")));
        }

        indexer.index();
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());

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

From source file:com.amertkara.multiplerunners.Application.java

public static void main(String[] args) {
    if (args.length == 0) {
        Options options = new Options();
        CommandLineParser parser = new DefaultParser();
        HelpFormatter formatter = new HelpFormatter();

        Option parserOpt = Option.builder("parse").desc("Parser").build();
        Option analyzerOpt = Option.builder("analyze").desc("Analyzer").build();

        options.addOption(analyzerOpt);//from  w ww.  j  av a 2s.  c  om
        options.addOption(parserOpt);

        formatter.printHelp("sample", options);
    } else {
        SpringApplication.run(Application.class, args);
    }
}

From source file:imageviewer.util.PasswordGenerator.java

public static void main(String[] args) {

    Option help = new Option("help", "Print this message");
    Option file = OptionBuilder.withArgName("file").hasArg().withDescription("Password filename")
            .create("file");
    Option addUser = OptionBuilder.withArgName("add").hasArg().withDescription("Add user profile")
            .create("add");
    Option removeUser = OptionBuilder.withArgName("remove").hasArg().withDescription("Remove user profile")
            .create("remove");
    Option updateUser = OptionBuilder.withArgName("update").hasArg().withValueSeparator()
            .withDescription("Update user profile").create("update");

    file.setRequired(true);//ww  w.  jav  a2s.c  o m
    OptionGroup og = new OptionGroup();
    og.addOption(addUser);
    og.addOption(removeUser);
    og.addOption(updateUser);
    og.setRequired(true);

    Options o = new Options();
    o.addOption(help);
    o.addOption(file);
    o.addOptionGroup(og);

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(o, args);
        PasswordGenerator pg = new PasswordGenerator(line);
        pg.execute();
    } catch (UnrecognizedOptionException uoe) {
        System.err.println("Unknown argument: " + uoe.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("PasswordGenerator", o);
        System.exit(1);
    } catch (MissingOptionException moe) {
        System.err.println("Missing argument: " + moe.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("PasswordGenerator", o);
        System.exit(1);
    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

From source file:io.druid.server.sql.SQLRunner.java

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

    Options options = new Options();
    options.addOption("h", "help", false, "help");
    options.addOption("v", false, "verbose");
    options.addOption("e", "host", true, "endpoint [hostname:port]");

    CommandLine cmd = new GnuParser().parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("SQLRunner", options);
        System.exit(2);/*from  www.j a v  a2 s. c om*/
    }

    String hostname = cmd.getOptionValue("e", "localhost:8080");
    String sql = cmd.getArgs().length > 0 ? cmd.getArgs()[0] : STATEMENT;

    ObjectMapper objectMapper = new DefaultObjectMapper();
    ObjectWriter jsonWriter = objectMapper.writerWithDefaultPrettyPrinter();

    CharStream stream = new ANTLRInputStream(sql);
    DruidSQLLexer lexer = new DruidSQLLexer(stream);
    TokenStream tokenStream = new CommonTokenStream(lexer);
    DruidSQLParser parser = new DruidSQLParser(tokenStream);
    lexer.removeErrorListeners();
    parser.removeErrorListeners();

    lexer.addErrorListener(ConsoleErrorListener.INSTANCE);
    parser.addErrorListener(ConsoleErrorListener.INSTANCE);

    try {
        DruidSQLParser.QueryContext queryContext = parser.query();
        if (parser.getNumberOfSyntaxErrors() > 0)
            throw new IllegalStateException();
        //      parser.setBuildParseTree(true);
        //      System.err.println(q.toStringTree(parser));
    } catch (Exception e) {
        String msg = e.getMessage();
        if (msg != null)
            System.err.println(e);
        System.exit(1);
    }

    final Query query;
    final TypeReference typeRef;
    boolean groupBy = false;
    if (parser.groupByDimensions.isEmpty()) {
        query = Druids.newTimeseriesQueryBuilder().dataSource(parser.getDataSource())
                .aggregators(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                .postAggregators(parser.postAggregators).intervals(parser.intervals)
                .granularity(parser.granularity).filters(parser.filter).build();

        typeRef = new TypeReference<List<Result<TimeseriesResultValue>>>() {
        };
    } else {
        query = GroupByQuery.builder().setDataSource(parser.getDataSource())
                .setAggregatorSpecs(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                .setPostAggregatorSpecs(parser.postAggregators).setInterval(parser.intervals)
                .setGranularity(parser.granularity).setDimFilter(parser.filter)
                .setDimensions(new ArrayList<DimensionSpec>(parser.groupByDimensions.values())).build();

        typeRef = new TypeReference<List<Row>>() {
        };
        groupBy = true;
    }

    String queryStr = jsonWriter.writeValueAsString(query);
    if (cmd.hasOption("v"))
        System.err.println(queryStr);

    URL url = new URL(String.format("http://%s/druid/v2/?pretty", hostname));
    final URLConnection urlConnection = url.openConnection();
    urlConnection.addRequestProperty("content-type", MediaType.APPLICATION_JSON);
    urlConnection.getOutputStream().write(StringUtils.toUtf8(queryStr));
    BufferedReader stdInput = new BufferedReader(
            new InputStreamReader(urlConnection.getInputStream(), Charsets.UTF_8));

    Object res = objectMapper.readValue(stdInput, typeRef);

    Joiner tabJoiner = Joiner.on("\t");

    if (groupBy) {
        List<Row> rows = (List<Row>) res;
        Iterable<String> dimensions = Iterables.transform(parser.groupByDimensions.values(),
                new Function<DimensionSpec, String>() {
                    @Override
                    public String apply(@Nullable DimensionSpec input) {
                        return input.getOutputName();
                    }
                });

        System.out.println(
                tabJoiner.join(Iterables.concat(Lists.newArrayList("timestamp"), dimensions, parser.fields)));
        for (final Row r : rows) {
            System.out.println(tabJoiner.join(Iterables.concat(
                    Lists.newArrayList(parser.granularity.toDateTime(r.getTimestampFromEpoch())),
                    Iterables.transform(parser.groupByDimensions.values(),
                            new Function<DimensionSpec, String>() {
                                @Override
                                public String apply(@Nullable DimensionSpec input) {
                                    return Joiner.on(",").join(r.getDimension(input.getOutputName()));
                                }
                            }),
                    Iterables.transform(parser.fields, new Function<String, Object>() {
                        @Override
                        public Object apply(@Nullable String input) {
                            return r.getFloatMetric(input);
                        }
                    }))));
        }
    } else {
        List<Result<TimeseriesResultValue>> rows = (List<Result<TimeseriesResultValue>>) res;
        System.out.println(tabJoiner.join(Iterables.concat(Lists.newArrayList("timestamp"), parser.fields)));
        for (final Result<TimeseriesResultValue> r : rows) {
            System.out.println(tabJoiner.join(Iterables.concat(Lists.newArrayList(r.getTimestamp()),
                    Lists.transform(parser.fields, new Function<String, Object>() {
                        @Override
                        public Object apply(@Nullable String input) {
                            return r.getValue().getMetric(input);
                        }
                    }))));
        }
    }

    CloseQuietly.close(stdInput);
}

From source file:edu.freiburg.dbis.rdd.RddExtractor.java

/**
 * @param args/*w ww .  java2  s  . c o m*/
 */
public static void main(String[] args) {
    String Classname = RddExtractor.class.getName();
    // Creating and parsing commandline options
    Options options = createOptions();
    CommandLineParser parser = new BasicParser();
    HelpFormatter help = new HelpFormatter();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help.printHelp(Classname, options);
            return;
        }
        // XOR (either input-file or sparql-endpoint) --> Throw error if it is the same
        if (cmd.hasOption("i") == cmd.hasOption("e")) {
            help.printHelp(Classname, options);
            System.err.println(
                    "Use either the the option to read from an input file or (XOR) the option to send queries against an SPARQL Endpoint");
            return;
        }
        // the graph variable can only be used with the sparql-enpoint
        if ((cmd.hasOption("g") == true) && (cmd.hasOption("e") == false)) {
            help.printHelp(Classname, options);
            System.err.println(
                    "The graph variable can only be used when sending queries against a SPARQL Endpoint");
            return;
        }

    } catch (ParseException e) {
        help.printHelp(Classname, options);
        System.err.println("Command line parsing failed. Reason: " + e.getMessage());
        return;
    }

    String INPUT_FILE = cmd.getOptionValue("i");
    String OUTPUT_FILE = cmd.getOptionValue("o");
    String ENDPOINTURL = cmd.getOptionValue("e");
    String VIRTUOSO_GRAPH_NAME = cmd.getOptionValue("g");
    String WA = cmd.getOptionValue("w");
    String propertyFile = "src/main/resources/log4j.properties2";
    if (cmd.hasOption("v")) {
        propertyFile = "src/main/resources/log4j.properties";
    } else if (cmd.hasOption("l")) {
        propertyFile = cmd.getOptionValue("l");
    }
    //      String propertyFile = (cmd.hasOption("l")) ? cmd.getOptionValue("l") : "src/main/resources/log4j.properties2";

    PropertyConfigurator.configure(propertyFile);

    logger.debug("INPUT FILE  : " + INPUT_FILE);
    logger.debug("OUTPUT FILE : " + OUTPUT_FILE);
    logger.debug("ENDPOINT URL: " + ENDPOINTURL);
    logger.debug("GRAPH NAME  : " + VIRTUOSO_GRAPH_NAME);
    logger.debug("WORLD ASSUMP: " + WA);

    long start = System.currentTimeMillis();
    long end = 0;
    logger.info("Starting The Generator");
    Backend back = new Backend(INPUT_FILE, OUTPUT_FILE, ENDPOINTURL, VIRTUOSO_GRAPH_NAME, WA);
    end = System.currentTimeMillis();
    logger.info("Runtime of Generator in ms: " + (end - start));
}

From source file:main.Main.java

/**
 * The public main function./*  w  w  w  . j  av  a2s .  c o m*/
 * @param args
 */
public static void main(String[] args) {
    System.out.println("Starting");

    Options options = new Options();

    Option solutionOption = new Option("s", "solution", true,
            "This will be the " + "solution of the cross word game. (aka. This will be the first"
                    + " vertical word on the canvas.)");

    //        solutionOption.setRequired(true);

    Option numOfBatchOption = new Option("n", "numOfBatch", true, "");

    Option verboseOption = new Option("v", "verbose", false, "Print some debug information during running.");
    Option veryVerboseOption = new Option("vv", "very-verbose", false, "Print more debug information.");

    options.addOption(solutionOption);
    options.addOption(numOfBatchOption);
    options.addOption(verboseOption);
    options.addOption(veryVerboseOption);

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

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("utility-name", options);

        System.exit(1);
        return;
    }

    System.out.println(cmd.getArgList());

    int debugLevel = 0;
    if (cmd.hasOption("verbose")) {
        debugLevel = 1;
    }
    if (cmd.hasOption("very-verbose")) {
        debugLevel = 2;
    }
    String solution = cmd.getOptionValue("solution");
    if (null == solution) {
        startGui();
    } else {
        int numOfBatch = Integer.valueOf(cmd.getOptionValue("numOfBatch", "200"));
        System.out.println(solution);
        Generator gen = new Generator(solution, debugLevel); // <---- EDIT THIS LINE FOR DIFFERENT SOLUTIONS.
        long startTime = System.currentTimeMillis();
        gen.generate(numOfBatch);
        long estimatedTime = System.currentTimeMillis() - startTime;
        System.out.print("estimatedTime: " + estimatedTime + "ms");
    }
}

From source file:it.geosolutions.unredd.apputil.AreaBuilder.java

public static void main(String[] args) {
    Option help = OptionBuilder.withLongOpt("help").withDescription("print help").create('?');

    Options helpOptions = new Options().addOption(help);

    Options options = new Options().addOption(help)
            .addOption(OptionBuilder.withLongOpt("extents").withArgName("n/e/s/w")
                    .withDescription("extents in the format n/e/s/w").hasArgs(4).withValueSeparator('/')
                    .isRequired().withType(Double.class).create(OPT_EXTENTS))
            .addOption(OptionBuilder.withLongOpt("size").withArgName("width,height")
                    .withDescription("size of output image in pixel in the format width,height").hasArgs(2)
                    .withValueSeparator(',').isRequired().withType(Integer.class).create(OPT_SIZE))
            .addOption(OptionBuilder.withLongOpt("outfile").withArgName("file")
                    .withDescription("the output tiff file").hasArg().isRequired().withType(String.class)
                    .create(OPT_OUTFILE))
            .addOption(OptionBuilder.withLongOpt("mem").withArgName("megabytes")
                    .withDescription("the max memory available for the operation").hasArg().create(OPT_MEM))
            .addOption(OptionBuilder.withLongOpt("threads").withArgName("numThreads")
                    .withDescription("number of threads JAI will use").hasArg().create(OPT_THREADS));

    try {/*from  ww w.j a  v a  2 s .  com*/

        //=== Create parser
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);

        //=== Parse input params
        String sFile = cmd.getOptionValue(OPT_OUTFILE);

        String[] sSizeArr = cmd.getOptionValues(OPT_SIZE);
        if (sSizeArr.length != 2) {
            LOGGER.error("size requires 2 args");
            return;
        }
        String[] sExtArr = cmd.getOptionValues(OPT_EXTENTS);
        if (sExtArr.length != 4) {
            LOGGER.error("extents require 4 args");
            return;
        }

        File file = new File(sFile);
        LOGGER.info("Output file " + file);

        int w = Integer.parseInt(sSizeArr[0]);
        int h = Integer.parseInt(sSizeArr[1]);
        LOGGER.info("Image size " + w + " x " + h);

        double boxn = Double.parseDouble(sExtArr[0]);
        double boxe = Double.parseDouble(sExtArr[1]);
        double boxs = Double.parseDouble(sExtArr[2]);
        double boxw = Double.parseDouble(sExtArr[3]);
        LOGGER.info("Image bbox is n:" + boxn + "e:" + boxe + " s:" + boxs + " w:" + boxw);

        //=== Parse and set tilecache memory
        Long mega = 512l;
        if (cmd.hasOption(OPT_MEM)) {
            mega = Long.parseLong(cmd.getOptionValue(OPT_MEM));
            LOGGER.info("JAI tilecache memory set to " + mega + "MB");
        } else {
            LOGGER.info("JAI tilecache memory defaulting to " + mega + "MB");
        }

        JAI.getDefaultInstance().getTileCache().setMemoryCapacity(mega * MEGA);

        //=== Parse and set JAI parallelism level
        int threads = 4;
        if (cmd.hasOption(OPT_THREADS)) {
            threads = Integer.parseInt(cmd.getOptionValue(OPT_THREADS));
            LOGGER.info("JAI tile scheduler parallelism set to " + threads);
        } else {
            LOGGER.info("JAI tile scheduler parallelism defaulting to " + threads);
        }

        TileScheduler ts = JAI.getDefaultInstance().getTileScheduler();
        ts.setParallelism(threads);
        ts.setPrefetchParallelism(threads);

        //=== Create grid and save

        System.setProperty("org.geotools.referencing.forceXY", "true");
        GridCoverage2D grid = createAreaGrid(w, h, boxw, boxe, boxs, boxn);
        saveAreaGrid(grid, file);

    } catch (ParseException ex) {

        CommandLine cmd0 = null;
        try { // find out if an help was requested (it's missing mandatory params)
            CommandLineParser helpParser = new PosixParser();
            cmd0 = helpParser.parse(helpOptions, args);
        } catch (ParseException ex1) {
            LOGGER.error("Unexpected error: " + ex1);
        }

        if (cmd0 == null || !cmd0.hasOption("help")) {
            LOGGER.error("Parse error: " + ex);
        }

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("createAreaLayer", options);
    } catch (Exception e) {
        LOGGER.error("Unexpected exception", e);
    }
}

From source file:com.ibm.crail.storage.StorageServer.java

public static void main(String[] args) throws Exception {
    Logger LOG = CrailUtils.getLogger();
    CrailConfiguration conf = new CrailConfiguration();
    CrailConstants.updateConstants(conf);
    CrailConstants.printConf();/*from   w ww.j av  a  2  s  .  c  o m*/
    CrailConstants.verify();

    int splitIndex = 0;
    for (String param : args) {
        if (param.equalsIgnoreCase("--")) {
            break;
        }
        splitIndex++;
    }

    //default values
    StringTokenizer tokenizer = new StringTokenizer(CrailConstants.STORAGE_TYPES, ",");
    if (!tokenizer.hasMoreTokens()) {
        throw new Exception("No storage types defined!");
    }
    String storageName = tokenizer.nextToken();
    int storageType = 0;
    HashMap<String, Integer> storageTypes = new HashMap<String, Integer>();
    storageTypes.put(storageName, storageType);
    for (int type = 1; tokenizer.hasMoreElements(); type++) {
        String name = tokenizer.nextToken();
        storageTypes.put(name, type);
    }
    int storageClass = -1;

    //custom values
    if (args != null) {
        Option typeOption = Option.builder("t").desc("storage type to start").hasArg().build();
        Option classOption = Option.builder("c").desc("storage class the server will attach to").hasArg()
                .build();
        Options options = new Options();
        options.addOption(typeOption);
        options.addOption(classOption);
        CommandLineParser parser = new DefaultParser();

        try {
            CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, splitIndex));
            if (line.hasOption(typeOption.getOpt())) {
                storageName = line.getOptionValue(typeOption.getOpt());
                storageType = storageTypes.get(storageName).intValue();
            }
            if (line.hasOption(classOption.getOpt())) {
                storageClass = Integer.parseInt(line.getOptionValue(classOption.getOpt()));
            }
        } catch (ParseException e) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Storage tier", options);
            System.exit(-1);
        }
    }
    if (storageClass < 0) {
        storageClass = storageType;
    }

    StorageTier storageTier = StorageTier.createInstance(storageName);
    if (storageTier == null) {
        throw new Exception("Cannot instantiate datanode of type " + storageName);
    }

    String extraParams[] = null;
    splitIndex++;
    if (args.length > splitIndex) {
        extraParams = new String[args.length - splitIndex];
        for (int i = splitIndex; i < args.length; i++) {
            extraParams[i - splitIndex] = args[i];
        }
    }
    storageTier.init(conf, extraParams);
    storageTier.printConf(LOG);

    RpcClient rpcClient = RpcClient.createInstance(CrailConstants.NAMENODE_RPC_TYPE);
    rpcClient.init(conf, args);
    rpcClient.printConf(LOG);

    ConcurrentLinkedQueue<InetSocketAddress> namenodeList = CrailUtils.getNameNodeList();
    ConcurrentLinkedQueue<RpcConnection> connectionList = new ConcurrentLinkedQueue<RpcConnection>();
    while (!namenodeList.isEmpty()) {
        InetSocketAddress address = namenodeList.poll();
        RpcConnection connection = rpcClient.connect(address);
        connectionList.add(connection);
    }
    RpcConnection rpcConnection = connectionList.peek();
    if (connectionList.size() > 1) {
        rpcConnection = new RpcDispatcher(connectionList);
    }
    LOG.info("connected to namenode(s) " + rpcConnection.toString());

    StorageServer server = storageTier.launchServer();
    StorageRpcClient storageRpc = new StorageRpcClient(storageType, CrailStorageClass.get(storageClass),
            server.getAddress(), rpcConnection);

    HashMap<Long, Long> blockCount = new HashMap<Long, Long>();
    long sumCount = 0;
    while (server.isAlive()) {
        StorageResource resource = server.allocateResource();
        if (resource == null) {
            break;
        } else {
            storageRpc.setBlock(resource.getAddress(), resource.getLength(), resource.getKey());
            DataNodeStatistics stats = storageRpc.getDataNode();
            long newCount = stats.getFreeBlockCount();
            long serviceId = stats.getServiceId();

            long oldCount = 0;
            if (blockCount.containsKey(serviceId)) {
                oldCount = blockCount.get(serviceId);
            }
            long diffCount = newCount - oldCount;
            blockCount.put(serviceId, newCount);
            sumCount += diffCount;
            LOG.info("datanode statistics, freeBlocks " + sumCount);
        }
    }

    while (server.isAlive()) {
        DataNodeStatistics stats = storageRpc.getDataNode();
        long newCount = stats.getFreeBlockCount();
        long serviceId = stats.getServiceId();

        long oldCount = 0;
        if (blockCount.containsKey(serviceId)) {
            oldCount = blockCount.get(serviceId);
        }
        long diffCount = newCount - oldCount;
        blockCount.put(serviceId, newCount);
        sumCount += diffCount;

        LOG.info("datanode statistics, freeBlocks " + sumCount);
        Thread.sleep(2000);
    }
}

From source file:frankhassanabad.com.github.Jasperize.java

/**
 * Main method to call through Java in order to take a LinkedInProfile on disk and load it.
 *
 * @param args command line arguments where the options are stored
 * @throws FileNotFoundException Thrown if any file its expecting cannot be found.
 * @throws JRException  If there's generic overall Jasper issues.
 * @throws ParseException If there's command line parsing issues.
 *//*  w w w .j  a  va2 s .c  om*/
public static void main(String[] args) throws IOException, JRException, ParseException {

    Options options = new Options();
    options.addOption("h", "help", false, "Shows the help documentation");
    options.addOption("v", "version", false, "Shows the help documentation");
    options.addOption("cl", "coverLetter", false, "Utilizes a cover letter defined in coverletter.xml");
    options.addOption("sig", true, "Picture of your signature to add to the cover letter.");
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Jasperize [OPTIONS] [InputJrxmlFile] [OutputExportFile]", options);
        System.exit(0);
    }
    if (cmd.hasOption("v")) {
        System.out.println("Version:" + version);
        System.exit(0);
    }
    boolean useCoverLetter = cmd.hasOption("cl");
    String signatureLocation = cmd.getOptionValue("sig");
    BufferedImage signatureImage = null;
    if (signatureLocation != null) {
        signatureImage = ImageIO.read(new File(signatureLocation));
        ;
    }

    @SuppressWarnings("unchecked")
    List<String> arguments = cmd.getArgList();

    final String jrxmlFile;
    final String jasperOutput;
    if (arguments.size() == 2) {
        jrxmlFile = arguments.get(0);
        jasperOutput = arguments.get(1);
        System.out.println("*Detected* the command line arguments of:");
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    } else if (arguments.size() == 3) {
        jrxmlFile = arguments.get(1);
        jasperOutput = arguments.get(2);
        System.out.println("*Detected* the command line arguments of:");
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    } else {
        System.out.println("Using the default arguments of:");
        jrxmlFile = "data/jasperTemplates/resume1.jrxml";
        jasperOutput = "data/jasperOutput/linkedInResume.pdf";
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    }

    final String compiledMasterFile;
    final String outputType;
    final String jrPrintFile;
    //Split the inputFile
    final String[] inputSplit = jrxmlFile.split("\\.");
    if (inputSplit.length != 2 || !(inputSplit[1].equalsIgnoreCase("jrxml"))) {
        //Error
        System.out.println("Your [InputjrxmlFile] (1st argument) should have a jrxml extension like such:");
        System.out.println("    data/jasperTemplates/resume1.jrxml");
        System.exit(1);
    }
    //Split the outputFile
    final String[] outputSplit = jasperOutput.split("\\.");
    if (outputSplit.length != 2) {
        //Error
        System.out.println("Your [OutputExportFile] (2nd argument) should have a file extension like such:");
        System.out.println("    data/jasperOutput/linkedInResume.pdf");
        System.exit(1);
    }

    File inputFile = new File(inputSplit[0]);
    String inputFileName = inputFile.getName();
    String inputFileParentPath = inputFile.getParent();

    File outputFile = new File(outputSplit[0]);
    String outputFileParentPath = outputFile.getParent();

    System.out.println("Compiling report(s)");
    compileAllJrxmlTemplateFiles(inputFileParentPath, outputFileParentPath);
    System.out.println("Done compiling report(s)");

    compiledMasterFile = outputFileParentPath + File.separator + inputFileName + ".jasper";
    jrPrintFile = outputFileParentPath + File.separator + inputFileName + ".jrprint";

    System.out.println("Filling report: " + compiledMasterFile);
    Reporting.fill(compiledMasterFile, useCoverLetter, signatureImage);
    System.out.println("Done filling reports");
    outputType = outputSplit[1];
    System.out.println("Creating output export file of: " + jasperOutput);
    if (outputType.equalsIgnoreCase("pdf")) {
        Reporting.pdf(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("pptx")) {
        Reporting.pptx(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("docx")) {
        Reporting.docx(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("odt")) {
        Reporting.odt(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("xhtml")) {
        Reporting.xhtml(jrPrintFile, jasperOutput);
    }
    System.out.println("Done creating output export file of: " + jasperOutput);
}