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

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

Introduction

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

Prototype

BasicParser

Source Link

Usage

From source file:com.google.api.ads.adwords.jaxws.extensions.AwReporting.java

/**
 * Main method./*from   w w w .  j  a  v  a 2 s .c  o  m*/
 *
 * @param args the command line arguments.
 */
public static void main(String args[]) {

    // Proxy
    JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault());
    ProxySelector.setDefault(ps);

    Options options = createCommandLineOptions();

    boolean errors = false;
    String propertiesPath = null;

    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmdLine = parser.parse(options, args);

        // Print full help and quit
        if (cmdLine.hasOption("help")) {
            printHelpMessage(options);
            printSamplePropertiesFile();
            System.exit(0);
        }

        setLogLevel(cmdLine);

        if (cmdLine.hasOption("file")) {
            propertiesPath = cmdLine.getOptionValue("file");
        } else {
            LOGGER.error("Missing required option: 'file'");
            System.exit(0);
        }
        LOGGER.info("Using properties file: " + propertiesPath);

        Set<Long> accountIdsSet = Sets.newHashSet();
        if (cmdLine.hasOption("accountIdsFile")) {
            String accountsFileName = cmdLine.getOptionValue("accountIdsFile");
            addAccountsFromFile(accountIdsSet, accountsFileName);
        }

        Properties properties = initApplicationContextAndProperties(propertiesPath);

        ReportModeService.setReportMode(properties.getProperty("reportMode")); //TODO Any other approach?

        LOGGER.debug("Creating ReportProcessor bean...");
        ReportProcessor processor = createReportProcessor();
        LOGGER.debug("... success.");

        if (cmdLine.hasOption("generatePdf")) {

            LOGGER.debug("GeneratePDF option detected.");

            // Get HTML template and output directoy
            String[] pdfFiles = cmdLine.getOptionValues("generatePdf");
            File htmlTemplateFile = new File(pdfFiles[0]);
            File outputDirectory = new File(pdfFiles[1]);

            LOGGER.debug("Html template file to be used: " + htmlTemplateFile);
            LOGGER.debug("Output directory for PDF: " + outputDirectory);

            // Generate PDFs
            generatePdf(processor, cmdLine.getOptionValue("startDate"), cmdLine.getOptionValue("endDate"),
                    properties, htmlTemplateFile, outputDirectory);

        } else if (cmdLine.hasOption("startDate") && cmdLine.hasOption("endDate")) {
            // Generate Reports

            String dateStart = cmdLine.getOptionValue("startDate");
            String dateEnd = cmdLine.getOptionValue("endDate");

            LOGGER.info("Starting report download for dateStart: " + dateStart + " and dateEnd: " + dateEnd);

            processor.generateReportsForMCC(ReportDefinitionDateRangeType.CUSTOM_DATE, dateStart, dateEnd,
                    accountIdsSet, properties);

        } else if (cmdLine.hasOption("dateRange")) {

            ReportDefinitionDateRangeType dateRangeType = ReportDefinitionDateRangeType
                    .fromValue(cmdLine.getOptionValue("dateRange"));

            LOGGER.info("Starting report download for dateRange: " + dateRangeType.name());

            processor.generateReportsForMCC(dateRangeType, null, null, accountIdsSet, properties);

        } else {
            errors = true;
            LOGGER.error("Configuration incomplete. Missing options for command line.");
        }
    } catch (IOException e) {
        errors = true;
        LOGGER.error("File not found: " + e.getMessage());
    } catch (ParseException e) {
        errors = true;
        System.err.println("Error parsing the values for the command line options: " + e.getMessage());
    } catch (Exception e) {
        errors = true;
        LOGGER.error("Unexpected error accessing the API: " + e.getMessage());
        e.printStackTrace();
    }

    if (errors) {
        System.exit(1);
    } else {
        System.exit(0);
    }
}

From source file:co.paralleluniverse.photon.Photon.java

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

    final Options options = new Options();
    options.addOption("rate", true, "Requests per second (default " + rateDefault + ")");
    options.addOption("duration", true,
            "Minimum test duration in seconds: will wait for <duration> * <rate> requests to terminate or, if progress check enabled, no progress after <duration> (default "
                    + durationDefault + ")");
    options.addOption("maxconnections", true,
            "Maximum number of open connections (default " + maxConnectionsDefault + ")");
    options.addOption("timeout", true,
            "Connection and read timeout in millis (default " + timeoutDefault + ")");
    options.addOption("print", true,
            "Print cycle in millis, 0 to disable intermediate statistics (default " + printCycleDefault + ")");
    options.addOption("check", true,
            "Progress check cycle in millis, 0 to disable progress check (default " + checkCycleDefault + ")");
    options.addOption("stats", false, "Print full statistics when finish (default false)");
    options.addOption("minmax", false, "Print min/mean/stddev/max stats when finish (default false)");
    options.addOption("name", true, "Test name to print in the statistics (default '" + testNameDefault + "')");
    options.addOption("help", false, "Print help");

    try {// w  w w  .  jav a 2s .  co m
        final CommandLine cmd = new BasicParser().parse(options, args);
        final String[] ar = cmd.getArgs();
        if (cmd.hasOption("help") || ar.length != 1)
            printUsageAndExit(options);

        final String url = ar[0];

        final int timeout = Integer.parseInt(cmd.getOptionValue("timeout", timeoutDefault));
        final int maxConnections = Integer
                .parseInt(cmd.getOptionValue("maxconnections", maxConnectionsDefault));
        final int duration = Integer.parseInt(cmd.getOptionValue("duration", durationDefault));
        final int printCycle = Integer.parseInt(cmd.getOptionValue("print", printCycleDefault));
        final int checkCycle = Integer.parseInt(cmd.getOptionValue("check", checkCycleDefault));
        final String testName = cmd.getOptionValue("name", testNameDefault);
        final int rate = Integer.parseInt(cmd.getOptionValue("rate", rateDefault));

        final MetricRegistry metrics = new MetricRegistry();
        final Meter requestMeter = metrics.meter("request");
        final Meter responseMeter = metrics.meter("response");
        final Meter errorsMeter = metrics.meter("errors");
        final Logger log = LoggerFactory.getLogger(Photon.class);
        final ConcurrentHashMap<String, AtomicInteger> errors = new ConcurrentHashMap<>();
        final HttpGet request = new HttpGet(url);
        final StripedTimeSeries<Long> sts = new StripedTimeSeries<>(30000, false);
        final StripedHistogram sh = new StripedHistogram(60000, 5);

        log.info("name: " + testName + " url:" + url + " rate:" + rate + " duration:" + duration
                + " maxconnections:" + maxConnections + ", " + "timeout:" + timeout);
        final DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(IOReactorConfig.custom()
                .setConnectTimeout(timeout).setIoThreadCount(10).setSoTimeout(timeout).build());

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            final List<ExceptionEvent> events = ioreactor.getAuditLog();
            if (events != null)
                events.stream().filter(event -> event != null).forEach(event -> {
                    System.err.println(
                            "Apache Async HTTP Client I/O Reactor Error Time: " + event.getTimestamp());
                    //noinspection ThrowableResultOfMethodCallIgnored
                    if (event.getCause() != null)
                        //noinspection ThrowableResultOfMethodCallIgnored
                        event.getCause().printStackTrace();
                });
            if (cmd.hasOption("stats"))
                printFinishStatistics(errorsMeter, sts, sh, testName);
            if (!errors.keySet().isEmpty())
                errors.entrySet().stream()
                        .forEach(p -> log.info(testName + " " + p.getKey() + " " + p.getValue() + "ms"));
            System.out.println(
                    testName + " responseTime(90%): " + sh.getHistogramData().getValueAtPercentile(90) + "ms");
            if (cmd.hasOption("minmax")) {
                final HistogramData hd = sh.getHistogramData();
                System.out.format("%s %8s%8s%8s%8s\n", testName, "min", "mean", "sd", "max");
                System.out.format("%s %8d%8.2f%8.2f%8d\n", testName, hd.getMinValue(), hd.getMean(),
                        hd.getStdDeviation(), hd.getMaxValue());
            }
        }));

        final PoolingNHttpClientConnectionManager mngr = new PoolingNHttpClientConnectionManager(ioreactor);
        mngr.setDefaultMaxPerRoute(maxConnections);
        mngr.setMaxTotal(maxConnections);
        final CloseableHttpAsyncClient ahc = HttpAsyncClientBuilder.create().setConnectionManager(mngr)
                .setDefaultRequestConfig(RequestConfig.custom().setLocalAddress(null).build()).build();
        try (final CloseableHttpClient client = new FiberHttpClient(ahc)) {
            final int num = duration * rate;

            final CountDownLatch cdl = new CountDownLatch(num);
            final Semaphore sem = new Semaphore(maxConnections);
            final RateLimiter rl = RateLimiter.create(rate);

            spawnStatisticsThread(printCycle, cdl, log, requestMeter, responseMeter, errorsMeter, testName);

            for (int i = 0; i < num; i++) {
                rl.acquire();
                if (sem.availablePermits() == 0)
                    log.debug("Maximum connections count reached, waiting...");
                sem.acquireUninterruptibly();

                new Fiber<Void>(() -> {
                    requestMeter.mark();
                    final long start = System.nanoTime();
                    try {
                        try (final CloseableHttpResponse ignored = client.execute(request)) {
                            responseMeter.mark();
                        } catch (final Throwable t) {
                            markError(errorsMeter, errors, t);
                        }
                    } catch (final Throwable t) {
                        markError(errorsMeter, errors, t);
                    } finally {
                        final long now = System.nanoTime();
                        final long millis = TimeUnit.NANOSECONDS.toMillis(now - start);
                        sts.record(start, millis);
                        sh.recordValue(millis);
                        sem.release();
                        cdl.countDown();
                    }
                }).start();
            }
            spawnProgressCheckThread(log, duration, checkCycle, cdl);
            cdl.await();
        }
    } catch (final ParseException ex) {
        System.err.println("Parsing failed.  Reason: " + ex.getMessage());
    }
}

From source file:eu.edisonproject.training.execute.Main.java

public static void main(String args[]) {
    Options options = new Options();
    Option operation = new Option("op", "operation", true,
            "type of operation to perform. " + "For term extraction use 'x'.\n"
                    + "Example: -op x -i E-COCO/documentation/sampleTextFiles/databases.txt "
                    + "-o E-COCO/documentation/sampleTextFiles/databaseTerms.csv"
                    + "For word sense disambiguation use 'w'.\n"
                    + "Example: -op w -i E-COCO/documentation/sampleTextFiles/databaseTerms.csv "
                    + "-o E-COCO/documentation/sampleTextFiles/databse.avro\n"
                    + "For tf-idf vector extraction use 't'.\n" + "For running the apriori algorithm use 'a'");
    operation.setRequired(true);/*from w  w w  .j ava2 s . co m*/
    options.addOption(operation);

    Option input = new Option("i", "input", true, "input file path");
    input.setRequired(true);
    options.addOption(input);

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

    Option popertiesFile = new Option("p", "properties", true, "path for a properties file");
    popertiesFile.setRequired(false);
    options.addOption(popertiesFile);

    Option termsFile = new Option("t", "terms", true, "terms file");
    termsFile.setRequired(false);
    options.addOption(termsFile);

    String helpmasg = "Usage: \n";
    for (Object obj : options.getOptions()) {
        Option op = (Option) obj;
        helpmasg += op.getOpt() + ", " + op.getLongOpt() + "\t Required: " + op.isRequired() + "\t\t"
                + op.getDescription() + "\n";
    }

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

        String propPath = cmd.getOptionValue("properties");
        if (propPath == null) {
            prop = ConfigHelper
                    .getProperties(".." + File.separator + "etc" + File.separator + "configure.properties");
        } else {
            prop = ConfigHelper.getProperties(propPath);
        }
        //            ${user.home}

        switch (cmd.getOptionValue("operation")) {
        case "x":
            termExtraction(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        case "w":
            wsd(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        case "t":
            calculateTFIDF(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        //                case "tt":
        //                    calculateTermTFIDF(cmd.getOptionValue("input"), cmd.getOptionValue("terms"), cmd.getOptionValue("output"));
        //                    break;
        case "a":
            apriori(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        default:
            System.out.println(helpmasg);
        }

    } catch (Exception ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, helpmasg, ex);
    }
}

From source file:com.xtructure.xnet.demos.art.TwoNodeSimulation.java

/**
 * The main method./* www. j a  va 2 s.c  om*/
 * 
 * @param args
 *            the arguments
 */
public static void main(String[] args) {
    Options options = new Options();
    options.addOption("n", "networkFile", true, //
            "the xml file from which the network is loaded");
    options.addOption("i", "inputFile", true, //
            "the xml file from which the input is loaded");
    options.addOption("test", false,
            "run integration test (non-gui, ignores networkFile and inputFile options)");
    BasicParser bp = new BasicParser();
    try {
        CommandLine cl = bp.parse(options, args);
        if (cl.hasOption("test")) {
            new TwoNodeSimulation();
        } else {
            File networkFile = new File(RESOURCE_DIR, "default.network.xml");
            File inputFile = new File(RESOURCE_DIR, "default.input.xml");
            loadConfigFiles(RESOURCE_DIR, inputFile, networkFile);
            if (cl.hasOption("n")) {
                networkFile = new File(cl.getOptionValue("n")).getAbsoluteFile();
            }
            if (cl.hasOption("i")) {
                inputFile = new File(cl.getOptionValue("i")).getAbsoluteFile();
            }
            new TwoNodeSimulation(networkFile, inputFile);
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("Usage:", options);
    } catch (XMLStreamException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.fonoster.astive.server.AstiveServer.java

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

    DOMConfigurator.configure(AbstractAstiveServer.ASTIVE_HOME + "/conf/log4j.xml");

    astivedSP = getServiceProperties(ASTIVED_PROPERTIES, "astived");
    adminDaemonSP = getServiceProperties(ADMIN_DAEMON_PROPERTIES, "admin thread");
    telnedSP = getServiceProperties(TELNED_PROPERTIES, "telned");

    ArrayList<ServiceProperties> serviceProperties = new ArrayList();
    serviceProperties.add(astivedSP);/*from   w  ww .j  a v  a  2 s.c  o m*/

    // Adding security measure
    AstPolicy ap = AstPolicy.getInstance();
    ap.addPermissions(astivedSP);
    ap.addPermissions(adminDaemonSP);
    ap.addPermissions(telnedSP);

    if (!adminDaemonSP.isDisabled()) {
        serviceProperties.add(adminDaemonSP);
    }

    if (!telnedSP.isDisabled()) {
        serviceProperties.add(telnedSP);
    }

    if ((args.length == 0) || args[0].equals("-h") || args[0].equals("--help")) {
        printUsage();
        System.exit(1);
    }

    // Create a Parser
    CommandLineParser parser = new BasicParser();

    Options start = new Options();

    start.addOption("h", "help", false, AppLocale.getI18n("optionHelp"));
    start.addOption("v", "version", false, AppLocale.getI18n("optionVersion"));
    start.addOption("d", "debug", false, AppLocale.getI18n("optionDebug"));
    start.addOption("q", "quiet", false, AppLocale.getI18n("optionQuiet"));

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("admin-bind")
            .withDescription(AppLocale.getI18n("optionBind", new Object[] { "admin" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("admin-port")
            .withDescription(AppLocale.getI18n("optionPort", new Object[] { "admin" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("astived-port")
            .withDescription(AppLocale.getI18n("optionPort", new Object[] { "astived" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("astived-host")
            .withDescription(AppLocale.getI18n("optionBind", new Object[] { "astived" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("telned-port")
            .withDescription(AppLocale.getI18n("optionPort", new Object[] { "telned" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("telned-host")
            .withDescription(AppLocale.getI18n("optionBind", new Object[] { "telned" })).create());

    Options stop = new Options();
    stop.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("host")
            .withDescription(AppLocale.getI18n("optionHelp")).create());

    stop.addOption("h", "host", false,
            AppLocale.getI18n("optionStopHost", new Object[] { DEFAULT_AGI_SERVER_BIND_ADDR }));

    stop.addOption("p", "port", false,
            AppLocale.getI18n("optionStopPort", new Object[] { DEFAULT_AGI_SERVER_PORT }));

    Options deploy = new Options();
    deploy.addOption("h", "help", false, AppLocale.getI18n("optionHelp"));

    Options undeploy = new Options();
    undeploy.addOption("h", "help", false, AppLocale.getI18n("optionHelp"));

    if (args.length == 0) {
        printUsage();
        System.exit(1);
    } else if (!isCommand(args[0])) {
        printUnavailableCmd(args[0]);
        System.exit(1);
    }

    AdminCommand cmd = AdminCommand.get(args[0]);

    // Parse the program arguments
    try {
        if (cmd.equals(AdminCommand.START)) {

            CommandLine commandLine = parser.parse(start, args);

            Logger root = LogManager.getRootLogger();
            Enumeration allLoggers = root.getLoggerRepository().getCurrentLoggers();

            if (commandLine.hasOption('q')) {
                root.setLevel(Level.ERROR);
                while (allLoggers.hasMoreElements()) {
                    Category tmpLogger = (Category) allLoggers.nextElement();
                    tmpLogger.setLevel(Level.ERROR);
                }
            } else if (commandLine.hasOption('d')) {
                root.setLevel(Level.DEBUG);
                while (allLoggers.hasMoreElements()) {
                    Category tmpLogger = (Category) allLoggers.nextElement();
                    tmpLogger.setLevel(Level.DEBUG);
                }
            } else {
                root.setLevel(Level.INFO);
                while (allLoggers.hasMoreElements()) {
                    Category tmpLogger = (Category) allLoggers.nextElement();
                    tmpLogger.setLevel(Level.INFO);
                }
            }

            if (commandLine.hasOption('h')) {
                printUsage(cmd, start);
                System.exit(0);
            }

            if (commandLine.hasOption('v')) {
                out.println(AppLocale.getI18n("astivedVersion",
                        new String[] { Version.VERSION, Version.BUILD_TIME }));
                System.exit(0);
            }

            if (commandLine.hasOption("astived-bind")) {
                astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("astived-port")));
            }

            if (commandLine.hasOption("astived-port")) {
                astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue("astived-port")));
            }

            if (commandLine.hasOption("admin-bind")) {
                adminDaemonSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("admin-bind")));
            }

            if (commandLine.hasOption("admin-port")) {
                adminDaemonSP.setPort(Integer.parseInt(commandLine.getOptionValue("admin-port")));
            }

            if (commandLine.hasOption("telned-bind")) {
                telnedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("telned-bind")));
            }

            if (commandLine.hasOption("telned-port")) {
                telnedSP.setPort(Integer.parseInt(commandLine.getOptionValue("telned-port")));
            }

            if (!NetUtil.isPortAvailable(astivedSP.getPort())) {
                out.println(AppLocale.getI18n("errorCantStartFastAgiServerSocket",
                        new Object[] { astivedSP.getBindAddr().getHostAddress(), astivedSP.getPort() }));
                System.exit(-1);
            }

            if (!NetUtil.isPortAvailable(adminDaemonSP.getPort())) {
                adminDaemonSP.setUnableToOpen(true);
            }

            if (!NetUtil.isPortAvailable(telnedSP.getPort())) {
                telnedSP.setUnableToOpen(true);
            }

            new InitOutput().printInit(serviceProperties);

            AstiveServer server = new AstiveServer(astivedSP.getPort(), astivedSP.getBacklog(),
                    astivedSP.getBindAddr());
            server.start();
        }

        if (!cmd.equals(AdminCommand.START) && adminDaemonSP.isDisabled()) {
            LOG.warn("errorUnableToAccessAdminDaemon");
        }

        if (cmd.equals(AdminCommand.STOP)) {
            CommandLine commandLine = parser.parse(stop, args);

            if (commandLine.hasOption("--help")) {
                printUsage(cmd, stop);
                System.exit(0);
            }

            if (commandLine.hasOption('h')) {
                if (commandLine.getOptionValue('h') == null) {
                    printUsage(cmd, stop);
                    System.exit(0);
                }

                astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue('h')));
            }

            if (commandLine.hasOption('p')) {
                if (commandLine.getOptionValue('p') == null) {
                    printUsage(cmd, stop);
                    System.exit(0);
                }

                astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue('p')));
            }

            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.stop();
        }

        // TODO: This needs to be researched before a full implementation.
        // for now is only possible to do deployments into a local server.
        if (cmd.equals(AdminCommand.DEPLOY)) {
            CommandLine commandLine = parser.parse(deploy, args);

            if (args.length < 2) {
                printUsage(cmd, deploy);
                System.exit(1);
            } else if (commandLine.hasOption('h')) {
                printUsage(cmd, deploy);
                System.exit(0);
            }

            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.deploy(args[1]);
        }

        if (cmd.equals(AdminCommand.UNDEPLOY)) {

            CommandLine commandLine = parser.parse(undeploy, args);

            if (args.length < 2) {
                printUsage(cmd, undeploy);
                System.exit(1);
            } else if (commandLine.hasOption('h')) {
                printUsage(cmd, undeploy);
                System.exit(0);
            }

            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.undeploy(args[1]);
        }
    } catch (java.net.ConnectException ex) {
        LOG.error(AppLocale.getI18n("errorServerNotRunning"));
    } catch (Exception ex) {
        LOG.error(AppLocale.getI18n("errorUnexpectedFailure", new Object[] { ex.getMessage() }));
    }
}

From source file:com.google.testing.pogen.PageObjectGenerator.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    if (args.length == 0) {
        printUsage(System.out);/*from w  ww  . ja v  a2 s .co  m*/
        return;
    }

    String commandName = args[0];
    // @formatter:off
    Options options = new Options()
            .addOption(OptionBuilder.withDescription(
                    "Attribute name to be assigned in tagas containing template variables (default is 'id').")
                    .hasArg().withLongOpt("attr").create('a'))
            .addOption(OptionBuilder.withDescription("Print help for this command.").withLongOpt("help")
                    .create('h'))
            .addOption(OptionBuilder.withDescription("Print processed files verbosely.").withLongOpt("verbose")
                    .create('v'));
    // @formatter:on

    String helpMessage = null;
    if (commandName.equals(GENERATE_COMMAND)) {
        // @formatter:off
        options.addOption(OptionBuilder.withDescription("Package name of generating skeleton test code.")
                .hasArg().isRequired().withLongOpt("package").create('p'))
                .addOption(OptionBuilder.withDescription("Output directory of generating skeleton test code.")
                        .hasArg().isRequired().withLongOpt("out").create('o'))
                .addOption(OptionBuilder.withDescription(
                        "Root input directory of html template files for analyzing the suffixes of the package name.")
                        .hasArg().isRequired().withLongOpt("in").create('i'))
                .addOption(OptionBuilder.withDescription("Regex for finding html template files.").hasArg()
                        .withLongOpt("regex").create('e'))
                .addOption(OptionBuilder.withDescription("Option for finding html template files recursively.")
                        .withLongOpt("recursive").create('r'));
        // @formatter:on
        helpMessage = "java PageObjectGenerator generate -o <test_out_dir> -p <package_name> -i <root_directory> "
                + " [OPTIONS] <template_file1> <template_file2> ...\n"
                + "e.g. java PageObjectGenerator generate -a class -o PageObjectGeneratorTest/src/test/java/com/google/testing/pogen/pages"
                + " -i PageObjectGeneratorTest/src/main/resources -p com.google.testing.pogen.pages -e (.*)\\.html -v";
    } else if (commandName.equals(MEASURE_COMMAND)) {
        helpMessage = "java PageObjectGenerator measure [OPTIONS] <template_file1> <template_file2> ...";
    } else if (commandName.equals(LIST_COMMAND)) {
        helpMessage = "java PageObjectGenerator list <template_file1> <template_file2> ...";
    } else {
        System.err.format("'%s' is not a PageObjectGenerator command.", commandName);
        printUsage(System.err);
        System.exit(-1);
    }

    BasicParser cmdParser = new BasicParser();
    HelpFormatter f = new HelpFormatter();
    try {
        CommandLine cl = cmdParser.parse(options, Arrays.copyOfRange(args, 1, args.length));
        if (cl.hasOption('h')) {
            f.printHelp(helpMessage, options);
            return;
        }

        Command command = null;
        String[] templatePaths = cl.getArgs();
        String attributeName = cl.getOptionValue('a');
        attributeName = attributeName != null ? attributeName : "id";
        if (commandName.equals(GENERATE_COMMAND)) {
            String rootDirectoryPath = cl.getOptionValue('i');
            String templateFilePattern = cl.getOptionValue('e');
            boolean isRecusive = cl.hasOption('r');
            command = new GenerateCommand(templatePaths, cl.getOptionValue('o'), cl.getOptionValue('p'),
                    attributeName, cl.hasOption('v'), rootDirectoryPath, templateFilePattern, isRecusive);
        } else if (commandName.equals(MEASURE_COMMAND)) {
            command = new MeasureCommand(templatePaths, attributeName, cl.hasOption('v'));
        } else if (commandName.equals(LIST_COMMAND)) {
            command = new ListCommand(templatePaths, attributeName);
        }
        try {
            command.execute();
            return;
        } catch (FileProcessException e) {
            System.err.println(e.getMessage());
        } catch (IOException e) {
            System.err.println("Errors occur in processing files.");
            System.err.println(e.getMessage());
        }
    } catch (ParseException e) {
        System.err.println("Errors occur in parsing the command arguments.");
        System.err.println(e.getMessage());
        f.printHelp(helpMessage, options);
    }
    System.exit(-1);
}

From source file:at.ait.dme.magicktiler.MagickTilerCLI.java

public static void main(String... args) throws IOException {
    if (showGui(args))
        return;//from ww  w  . j ava 2 s.  co  m

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

        // Help
        if (cmd.hasOption("h")) {
            printUsage(options);
            return;
        }

        // Log on/off
        if (cmd.hasOption("l")) {
            logger.addAppender(new FileAppender(new PatternLayout(), "log.txt", false));
            logger.setLevel(Level.DEBUG);
        }

        // Convert or validate
        if (cmd.hasOption("v")) {
            validate(cmd);
        } else {
            convert(cmd);
        }
    } catch (ParseException e) {
        System.err.println("Failed to parse command line arguments: " + e.getMessage());
        printUsage(options);
    }
}

From source file:com.threadswarm.imagefeedarchiver.driver.CommandLineDriver.java

public static void main(String[] args) throws InterruptedException, ExecutionException, ParseException {
    // define available command-line options
    Options options = new Options();
    options.addOption("h", "help", false, "display usage information");
    options.addOption("u", "url", true, "RSS feed URL");
    options.addOption("a", "user-agent", true, "User-Agent header value to use when making HTTP requests");
    options.addOption("o", "output-directory", true, "output directory for downloaded images");
    options.addOption("t", "thread-count", true, "number of worker threads, defaults to cpu-count + 1");
    options.addOption("d", "delay", true, "delay between image downloads (in milliseconds)");
    options.addOption("p", "notrack", false, "tell websites that you don't wish to be tracked (DNT)");
    options.addOption("s", "https", false, "Rewrite image URLs to leverage SSL/TLS");

    CommandLineParser commandLineParser = new BasicParser();
    CommandLine commandLine = commandLineParser.parse(options, args);

    // print usage information if 'h'/'help' or no-args were given
    if (args.length == 0 || commandLine.hasOption("h")) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java -jar ImageFeedArchiver.jar", options);
        return; //abort execution
    }/*from   ww  w. ja  v a2  s  .c  o  m*/

    URI rssFeedUri = null;
    if (commandLine.hasOption("u")) {
        String rssFeedUrlString = commandLine.getOptionValue("u");
        try {
            rssFeedUri = FeedUtils.getUriFromUrlString(rssFeedUrlString);
        } catch (MalformedURLException | URISyntaxException e) {
            LOGGER.error("The Feed URL you supplied was malformed or violated syntax rules.. exiting", e);
            System.exit(1);
        }
        LOGGER.info("Target RSS feed URL: {}", rssFeedUri);
    } else {
        throw new IllegalStateException("RSS feed URL was not specified!");
    }

    File outputDirectory = null;
    if (commandLine.hasOption("o")) {
        outputDirectory = new File(commandLine.getOptionValue("o"));
        if (!outputDirectory.isDirectory())
            throw new IllegalArgumentException("output directory must be a *directory*!");
        LOGGER.info("Using output directory: '{}'", outputDirectory);
    } else {
        throw new IllegalStateException("output directory was not specified!");
    }

    String userAgentString = null;
    if (commandLine.hasOption("a")) {
        userAgentString = commandLine.getOptionValue("a");
        LOGGER.info("Setting 'User-Agent' header value to '{}'", userAgentString);
    }

    int threadCount;
    if (commandLine.hasOption("t")) {
        threadCount = Integer.parseInt(commandLine.getOptionValue("t"));
    } else {
        threadCount = Runtime.getRuntime().availableProcessors() + 1;
    }
    LOGGER.info("Using {} worker threads", threadCount);

    long downloadDelay = 0;
    if (commandLine.hasOption("d")) {
        String downloadDelayString = commandLine.getOptionValue("d");
        downloadDelay = Long.parseLong(downloadDelayString);
    }
    LOGGER.info("Using a download-delay of {} milliseconds", downloadDelay);

    boolean doNotTrackRequested = commandLine.hasOption("p");

    boolean forceHttps = commandLine.hasOption("s");

    ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
    ((ConfigurableApplicationContext) context).registerShutdownHook();

    HttpClient httpClient = (HttpClient) context.getBean("httpClient");
    if (userAgentString != null)
        httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgentString);

    ProcessedRssItemDAO processedRssItemDAO = (ProcessedRssItemDAO) context.getBean("processedRssItemDAO");

    CommandLineDriver.Builder driverBuilder = new CommandLineDriver.Builder(rssFeedUri);
    driverBuilder.setDoNotTrackRequested(doNotTrackRequested).setOutputDirectory(outputDirectory)
            .setDownloadDelay(downloadDelay).setThreadCount(threadCount).setHttpClient(httpClient)
            .setForceHttps(forceHttps).setProcessedRssItemDAO(processedRssItemDAO);

    CommandLineDriver driver = driverBuilder.build();
    driver.run();
}

From source file:gobblin.test.TestWorker.java

@SuppressWarnings("all")
public static void main(String[] args) throws Exception {
    // Build command-line options
    Option configOption = OptionBuilder.withArgName("framework config file")
            .withDescription("Configuration properties file for the framework").hasArgs().withLongOpt("config")
            .create('c');
    Option jobConfigsOption = OptionBuilder.withArgName("job config files")
            .withDescription("Comma-separated list of job configuration files").hasArgs()
            .withLongOpt("jobconfigs").create('j');
    Option modeOption = OptionBuilder.withArgName("run mode")
            .withDescription("Test mode (schedule|run); 'schedule' means scheduling the jobs, "
                    + "whereas 'run' means running the jobs immediately")
            .hasArg().withLongOpt("mode").create('m');
    Option helpOption = OptionBuilder.withArgName("help").withDescription("Display usage information")
            .withLongOpt("help").create('h');

    Options options = new Options();
    options.addOption(configOption);//from  w  ww  .  j a  v a 2 s  .  c o  m
    options.addOption(jobConfigsOption);
    options.addOption(modeOption);
    options.addOption(helpOption);

    // Parse command-line options
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption('h')) {
        printUsage(options);
        System.exit(0);
    }

    // Start the test worker with the given configuration properties
    Configuration config = new PropertiesConfiguration(cmd.getOptionValue('c'));
    Properties properties = ConfigurationConverter.getProperties(config);
    TestWorker testWorker = new TestWorker(properties);
    testWorker.start();

    // Job running mode
    Mode mode = Mode.valueOf(cmd.getOptionValue('m').toUpperCase());

    // Get the list of job configuration files
    List<String> jobConfigFiles = Lists
            .newArrayList(Splitter.on(',').omitEmptyStrings().trimResults().split(cmd.getOptionValue('j')));

    CountDownLatch latch = new CountDownLatch(jobConfigFiles.size());
    for (String jobConfigFile : jobConfigFiles) {
        // For each job, load the job configuration, then run or schedule the job.
        Properties jobProps = new Properties();
        jobProps.load(new FileReader(jobConfigFile));
        jobProps.putAll(properties);
        testWorker.runJob(jobProps, mode, new TestJobListener(latch));
    }
    // Wait for all jobs to finish
    latch.await();

    testWorker.stop();
}

From source file:com.phonytive.astive.server.AstiveServer.java

public static void main(String[] args) throws Exception {
    astivedSP = getServiceProperties(ASTIVED_PROPERTIES, "astived");
    adminDaemonSP = getServiceProperties(ADMIN_DAEMON_PROPERTIES, "admin thread");
    telnedSP = getServiceProperties(TELNED_PROPERTIES, "telned");

    ArrayList<ServiceProperties> serviceProperties = new ArrayList();
    serviceProperties.add(astivedSP);//from   ww w .j av  a2  s . co m

    if (!adminDaemonSP.isDisabled()) {
        serviceProperties.add(adminDaemonSP);
    }

    if (!telnedSP.isDisabled()) {
        serviceProperties.add(telnedSP);
    }

    if ((args.length == 0) || args[0].equals("-h") || args[0].equals("--help")) {
        printUsage();
        System.exit(1);
    }

    // Create a Parser
    CommandLineParser parser = new BasicParser();

    Options start = new Options();
    start.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage"));
    start.addOption("v", "version", false, "Prints the Astive Server version and exits.");
    start.addOption("d", "debug", false, AppLocale.getI18n("cli.option.debug"));
    start.addOption("q", "quiet", false, AppLocale.getI18n("cli.option.daemonMode"));
    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("admin-bind")
            .withDescription("" + AppLocale.getI18n("cli.option.bind", new Object[] { "admin" })).create());
    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("admin-port")
            .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "admin" })).create());
    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("astived-port")
            .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "astived" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("astived-host")
            .withDescription("" + AppLocale.getI18n("cli.option.bind", new Object[] { "astived" })).create());
    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("telned-port")
            .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "telned" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("telned-host")
            .withDescription("" + AppLocale.getI18n("cli.option.host", new Object[] { "telned" })).create());

    Options stop = new Options();
    stop.addOption(OptionBuilder.withLongOpt("--help")
            .withDescription("" + AppLocale.getI18n("cli.option.printUsage")).create());

    stop.addOption("h", "host", false,
            AppLocale.getI18n("cli.option.stop.host", new Object[] { DEFAULT_AGI_SERVER_BIND_ADDR }));

    stop.addOption("p", "port", false,
            AppLocale.getI18n("cli.option.stop.port", new Object[] { DEFAULT_AGI_SERVER_PORT }));

    Options deploy = new Options();
    deploy.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage"));

    Options undeploy = new Options();
    undeploy.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage"));

    if (args.length == 0) {
        printUsage();
        System.exit(1);
    } else if (!isCommand(args[0])) {
        printUnavailableCmd(args[0]);
        System.exit(1);
    }

    AdminCommand cmd = AdminCommand.get(args[0]);

    if (cmd.equals(AdminCommand.DEPLOY) && ((args.length < 2) || !isFileJar(args[1]))) {
        logger.error(AppLocale.getI18n("cli.invalid.app"));
        printUsage(AdminCommand.DEPLOY, deploy);
        System.exit(1);
    }

    if (cmd.equals(AdminCommand.UNDEPLOY) && ((args.length < 2) || !isFileJar(args[1]))) {
        printUsage(AdminCommand.UNDEPLOY, undeploy);
        System.exit(1);
    }

    // Parse the program arguments
    try {
        if (cmd.equals(AdminCommand.START)) {
            CommandLine commandLine = parser.parse(start, args);

            if (commandLine.hasOption('h')) {
                printUsage(cmd, start);
                System.exit(0);
            }

            if (commandLine.hasOption('v')) {
                // Them start the server without noise
            }

            if (commandLine.hasOption("astived-bind")) {
                astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("astived-port")));
            }

            if (commandLine.hasOption("astived-port")) {
                astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue("astived-port")));
            }

            if (commandLine.hasOption("admin-bind")) {
                adminDaemonSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("admin-bind")));
            }

            if (commandLine.hasOption("admin-port")) {
                adminDaemonSP.setPort(Integer.parseInt(commandLine.getOptionValue("admin-port")));
            }

            if (commandLine.hasOption("telned-bind")) {
                telnedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("telned-bind")));
            }

            if (commandLine.hasOption("telned-port")) {
                adminDaemonSP.setPort(Integer.parseInt(commandLine.getOptionValue("telned-port")));
            }

            if (!NetUtil.available(astivedSP.getPort())) {
                out.println(AppLocale.getI18n("cantStartFastAgiServerSocket",
                        new Object[] { astivedSP.getBindAddr().getHostAddress(), astivedSP.getPort() }));
                System.exit(-1);
            }

            if (!NetUtil.available(adminDaemonSP.getPort())) {
                adminDaemonSP.setUnableToOpen(true);
            }

            if (!NetUtil.available(telnedSP.getPort())) {
                telnedSP.setUnableToOpen(true);
            }

            InitOutput.printInit(serviceProperties);

            AstiveServer server = new AstiveServer(astivedSP.getPort(), astivedSP.getBacklog(),
                    astivedSP.getBindAddr());
            server.start();
        }

        if (!cmd.equals(AdminCommand.START) && adminDaemonSP.isDisabled()) {
            logger.info("unableToAccessAdminDaemon");
        }

        if (cmd.equals(AdminCommand.STOP)) {
            CommandLine commandLine = parser.parse(stop, args);

            if (commandLine.hasOption("--help")) {
                printUsage(cmd, stop);
                System.exit(0);
            }

            if (commandLine.hasOption('h')) {
                if (commandLine.getOptionValue('h') == null) {
                    printUsage(cmd, stop);
                    System.exit(0);
                }

                astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue('h')));
            }

            if (commandLine.hasOption('p')) {
                if (commandLine.getOptionValue('p') == null) {
                    printUsage(cmd, stop);
                    System.exit(0);
                }

                astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue('p')));
            }

            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.stop();
        }

        // TODO: This needs to be researched before a full implementation.
        // for now is only possible to do deployments into the local server.
        if (cmd.equals(AdminCommand.DEPLOY)) {
            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.deploy(args[1]);
        }

        if (cmd.equals(AdminCommand.UNDEPLOY)) {
            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.undeploy(args[1]);
        }
    } catch (java.net.ConnectException ex) {
        logger.info("serverNotRunning");
    } catch (Exception ex) {
        logger.error(AppLocale.getI18n("unexpectedError", new Object[] { ex.getMessage() }));
    }
}