Example usage for org.apache.commons.cli ParseException getMessage

List of usage examples for org.apache.commons.cli ParseException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:cloud.elasticity.elastman.App.java

/**
 * The entry point to the ElastMan main program.
 * /*w  w w. ja  v  a  2  s  .com*/
 * @param args   The first argument is the mode which can be inter, ident, or control
 * corresponding to interactive mode, system identification mode, or control mode.
 * The second argument is the configuration file
 * The third argument is password password  
 */
public static void main(String[] args) {
    // 1) parse the command line
    // For more information http://commons.apache.org/cli/
    Options options = new Options();
    options.addOption("i", "ident", false, "Enter system identification mode.");
    options.addOption("c", "control", false, "Enter controller mode.");
    options.addOption("o", "options", true, "Configuration file. Default elastman.conf");
    options.addOption("u", "username", true, "Username in the form Tenant:UserName");
    options.addOption("p", "password", true, "User password");
    options.addOption("k", "keyname", true, "Name of SSH key to use");
    options.addOption("z", "zone", true, "The OpenStack availability zone such as the default RegionOne");
    options.addOption("e", "endpoint", true,
            "The URL to access OpenStack API such as http://192.168.1.1:5000/v2.0/");
    options.addOption("s", "syncserver", true, "The URL access the WebSyncServer");
    options.addOption("h", "help", false, "Print this help");

    CommandLineParser parser = new GnuParser();
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e2) {
        System.out.println(e2.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("ElastMan", options, true);
        System.exit(1);
    }

    // if h then show help and exit
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("ElastMan", options, true);
        System.exit(0);
    }

    // 2) Try to load the properties file.
    // Command line arguments override settings in the properties file
    // If no properties file exists. defaults will be used

    String filename = "control.prop"; // the default file name
    if (cmd.hasOption("o")) {
        filename = cmd.getOptionValue("o");
    }
    Props.load(filename, cmd);
    //      Props.save(filename);
    //      System.exit(-1);

    // 3) If no password in command line nor in config file then ask the user
    if (Props.password == null) {
        Console cons;
        char[] passwd;
        if ((cons = System.console()) != null &&
        // more secure and without echo!
                (passwd = cons.readPassword("[%s]", "Password:")) != null) {
            Props.password = new String(passwd);
        } else {
            // if you don't have a console! E.g., Running in eclipse
            System.out.print("Password: ");
            Props.password = scanner.nextLine();
        }
    }

    // 4) Start the UI
    App app = new App();
    app.textUI(args);

}

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 {/*from w w w  .  ja v  a 2 s.com*/
        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:com.google.flightmap.parsing.faa.nfd.tools.NfdAnalyzer.java

public static void main(String args[]) {
    CommandLine line = null;//from ww  w.j a va 2  s.c  om
    try {
        final CommandLineParser parser = new PosixParser();
        line = parser.parse(OPTIONS, args);
    } catch (ParseException pEx) {
        System.err.println(pEx.getMessage());
        printHelp(line);
        System.exit(1);
    }

    if (line.hasOption(HELP_OPTION)) {
        printHelp(line);
        System.exit(0);
    }

    final String nfdPath = line.getOptionValue(NFD_OPTION);
    final File nfd = new File(nfdPath);

    try {
        (new NfdAnalyzer(nfd)).execute();
    } catch (IOException ioEx) {
        ioEx.printStackTrace();
        System.exit(2);
    }
}

From source file:com.act.lcms.db.io.PrintConstructInfo.java

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

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

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        System.out.print("Loading/updating LCMS scan files into DB\n");
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);

        String construct = cl.getOptionValue(OPTION_CONSTRUCT);
        List<LCMSWell> lcmsWells = LCMSWell.getInstance().getByConstructID(db, construct);
        Collections.sort(lcmsWells, new Comparator<LCMSWell>() {
            @Override
            public int compare(LCMSWell o1, LCMSWell o2) {
                return o1.getId().compareTo(o2.getId());
            }
        });

        Set<String> uniqueMSIDs = new HashSet<>();
        Map<Integer, Plate> platesById = new HashMap<>();

        System.out.format("\n\n-- Construct %s --\n\n", construct);

        List<ChemicalAssociatedWithPathway> pathwayChems = ChemicalAssociatedWithPathway.getInstance()
                .getChemicalsAssociatedWithPathwayByConstructId(db, construct);
        System.out.print("Chemicals associated with pathway:\n");
        System.out.format("  %-8s%-15s%-45s\n", "index", "kind", "chemical");
        for (ChemicalAssociatedWithPathway chem : pathwayChems) {
            System.out.format("  %-8d%-15s%-45s\n", chem.getIndex(), chem.getKind(), chem.getChemical());
        }

        System.out.print("\nLCMS wells:\n");
        System.out.format("  %-15s%-6s%-15s%-15s%-15s\n", "barcode", "well", "msid", "fed", "lcms_count");
        for (LCMSWell well : lcmsWells) {
            uniqueMSIDs.add(well.getMsid());

            Plate p = platesById.get(well.getPlateId());
            if (p == null) {
                // TODO: migrate Plate to be a subclass of BaseDBModel.
                p = Plate.getPlateById(db, well.getPlateId());
                platesById.put(p.getId(), p);
            }

            String chem = well.getChemical();
            List<ScanFile> scanFiles = ScanFile.getScanFileByPlateIDRowAndColumn(db, p.getId(),
                    well.getPlateRow(), well.getPlateColumn());

            System.out.format("  %-15s%-6s%-15s%-15s%-15d\n", p.getBarcode(), well.getCoordinatesString(),
                    well.getMsid(), chem == null || chem.isEmpty() ? "--" : chem, scanFiles.size());
            System.out.flush();
        }

        List<Integer> plateIds = Arrays.asList(platesById.keySet().toArray(new Integer[platesById.size()]));
        Collections.sort(plateIds);
        System.out.print("\nAppears in plates:\n");
        for (Integer id : plateIds) {
            Plate p = platesById.get(id);
            System.out.format("  %s: %s\n", p.getBarcode(), p.getName());
        }

        List<String> msids = Arrays.asList(uniqueMSIDs.toArray(new String[uniqueMSIDs.size()]));
        Collections.sort(msids);
        System.out.format("\nMSIDS: %s\n", StringUtils.join(msids, ", "));

        Set<String> availableNegativeControls = new HashSet<>();
        for (Map.Entry<Integer, Plate> entry : platesById.entrySet()) {
            List<LCMSWell> wells = LCMSWell.getInstance().getByPlateId(db, entry.getKey());
            for (LCMSWell well : wells) {
                if (!construct.equals(well.getComposition())) {
                    availableNegativeControls.add(well.getComposition());
                }
            }
        }

        // Print available standards for each step w/ plate barcodes and coordinates.
        System.out.format("\nAvailable Standards:\n");
        Map<Integer, Plate> plateCache = new HashMap<>();
        for (ChemicalAssociatedWithPathway chem : pathwayChems) {
            List<StandardWell> matchingWells = StandardWell.getInstance().getStandardWellsByChemical(db,
                    chem.getChemical());
            for (StandardWell well : matchingWells) {
                if (!plateCache.containsKey(well.getPlateId())) {
                    Plate p = Plate.getPlateById(db, well.getPlateId());
                    plateCache.put(p.getId(), p);
                }
            }
            Map<Integer, List<StandardWell>> standardWellsByPlateId = new HashMap<>();
            for (StandardWell well : matchingWells) {
                List<StandardWell> plateWells = standardWellsByPlateId.get(well.getPlateId());
                if (plateWells == null) {
                    plateWells = new ArrayList<>();
                    standardWellsByPlateId.put(well.getPlateId(), plateWells);
                }
                plateWells.add(well);
            }
            List<Pair<String, Integer>> plateBarcodes = new ArrayList<>(plateCache.size());
            for (Plate p : plateCache.values()) {
                if (p.getBarcode() == null) {
                    plateBarcodes.add(Pair.of("(no barcode)", p.getId()));
                } else {
                    plateBarcodes.add(Pair.of(p.getBarcode(), p.getId()));
                }
            }
            Collections.sort(plateBarcodes);
            System.out.format("  %s:\n", chem.getChemical());
            for (Pair<String, Integer> barcodePair : plateBarcodes) {
                // TODO: hoist this whole sorting/translation step into a utility class.
                List<StandardWell> wells = standardWellsByPlateId.get(barcodePair.getRight());
                if (wells == null) {
                    // Don't print plates that don't apply to this chemical, which can happen because we're caching the plates.
                    continue;
                }
                Collections.sort(wells, new Comparator<StandardWell>() {
                    @Override
                    public int compare(StandardWell o1, StandardWell o2) {
                        int c = o1.getPlateRow().compareTo(o2.getPlateRow());
                        if (c != 0)
                            return c;
                        return o1.getPlateColumn().compareTo(o2.getPlateColumn());
                    }
                });
                List<String> descriptions = new ArrayList<>(wells.size());
                for (StandardWell well : wells) {
                    descriptions.add(String.format("%s in %s%s", well.getCoordinatesString(), well.getMedia(),
                            well.getConcentration() == null ? ""
                                    : String.format(" c. %f", well.getConcentration())));
                }
                System.out.format("    %s: %s\n", barcodePair.getLeft(), StringUtils.join(descriptions, ", "));
            }
        }

        List<String> negativeControlStrains = Arrays
                .asList(availableNegativeControls.toArray(new String[availableNegativeControls.size()]));
        Collections.sort(negativeControlStrains);
        System.out.format("\nAvailable negative controls: %s\n", StringUtils.join(negativeControlStrains, ","));
        System.out.print("\n----------\n");
        System.out.print("\n\n");
    }
}

From source file:com.c4om.jschematronvalidator.JSchematronValidatorMain.java

/**
 * Main method, executed at application startup
 * @param args CLI arguments (for more details, just run the program with the --help option).
 * @throws Exception if any exception is thrown anywhere
 *///from w  w  w.  ja  v a2 s .  c om
public static void main(String[] args) throws Exception {
    LOGGER.info("Program starts");
    CommandLine cmdLine;
    try {
        // create the command line parser
        CommandLineParser parser = new BasicParser();
        // parse the command line arguments
        cmdLine = parser.parse(CMD_LINE_OPTIONS, args);
    } catch (ParseException e) {
        String fatalMessage = "Error at parsing command line: " + e.getMessage();
        LOGGER.fatal(fatalMessage);
        System.err.println(fatalMessage);
        System.exit(1);
        return; //System.exit() makes this statement unreachable. However, 'return' is necessary to prevent the compiler from crying when I use 'cmdLine' outside the try-catch.
    }
    if (cmdLine.hasOption(CMD_LINE_OPTION_HELP)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CMD_LINE_SYNTAX, CMD_LINE_OPTIONS);
        System.exit(0);
    }
    if (!cmdLine.hasOption(CMD_LINE_OPTION_SCHEMATRON_FILE)) {
        System.err.println("Error at parsing command line: No input schematron is provided.");
        System.exit(1);
    }
    Document inputSchematronDocument = loadW3CDocumentFromInputFile(
            new File(cmdLine.getOptionValue(CMD_LINE_OPTION_SCHEMATRON_FILE)));
    Document candidateDocument;
    if (cmdLine.hasOption(CMD_LINE_OPTION_INPUT)) {
        try (InputStream candidateInputStream = new FileInputStream(
                new File(cmdLine.getOptionValue(CMD_LINE_OPTION_INPUT)))) {
            candidateDocument = loadW3CDocumentFromInputStream(candidateInputStream);
        }
    } else {
        candidateDocument = loadW3CDocumentFromInputStream(System.in);
    }

    String phase = cmdLine.getOptionValue(CMD_LINE_OPTION_PHASE);
    boolean allowForeign = cmdLine.hasOption(CMD_LINE_OPTION_ALLOW_FOREIGN);
    boolean diagnose = !cmdLine.hasOption(CMD_LINE_OPTION_SKIP_DIAGNOSE);
    boolean generatePaths = !cmdLine.hasOption(CMD_LINE_OPTION_SKIP_GENERATE_PATHS);
    boolean generateFiredRule = !cmdLine.hasOption(CMD_LINE_OPTION_SKIP_GENERATE_FIRED_RULE);
    boolean ignoreFileNotAvailableAtDocumentFunction = cmdLine
            .hasOption(CMD_LINE_OPTION_SKIP_OPTIONAL_FILES_ERRORS);

    ValidationMethod currentSchematronValidationMethod = new SaxonXSLT2BasedValidationMethod(
            ignoreFileNotAvailableAtDocumentFunction, allowForeign, diagnose, generatePaths, generateFiredRule);
    Document svrlResult = currentSchematronValidationMethod.performValidation(candidateDocument,
            inputSchematronDocument, phase);

    if (cmdLine.hasOption(CMD_LINE_OPTION_OUTPUT)) {
        OutputStream outputStream = new FileOutputStream(
                new File(cmdLine.getOptionValue(CMD_LINE_OPTION_OUTPUT)));
        printW3CDocumentToOutputStream(svrlResult, outputStream);
    } else {
        printW3CDocumentToOutputStream(svrlResult, System.out);
    }
}

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

/**
 * The main method./*from ww w  .ja  v a2  s. c o m*/
 * 
 * @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:languageTools.Analyzer.java

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

    // Get start time.
    long startTime = System.nanoTime();

    // Parse command line options
    File file;
    try {
        file = parseOptions(args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        showHelp();
        return;
    }

    // Get all files that should be analyzed
    List<File> files = new ArrayList<File>();
    if (file.isDirectory()) {
        // Search directory for indicated file types
        files = searchDirectory(file);
        System.out.println("Found " + files.size() + " file(s).\n");
    } else {
        files.add(file);
    }

    // Process files found
    for (File filefound : files) {
        System.out.println("Processing file: " + filefound.getPath() + ".\n");
        Validator<?, ?, ?, ?> validator = null;
        switch (Extension.getFileExtension(filefound)) {
        case GOAL:
            validator = new AgentValidator(filefound.getPath());
            // TODO we need to set a KR interface; use default (only one)
            // right now. Best we can do now
            // is to ask user to set it.
            try {
                ((AgentValidator) validator).setKRInterface(KRFactory.getDefaultInterface());
            } catch (KRInitFailedException e) {
                // TODO: use logger.
                System.out.println(e.getMessage());
            }
            break;
        case MOD2G:
            validator = new ModuleValidator(filefound.getPath());
            // TODO we need to set a KR interface; use default (only one)
            // right now. Best we can do now
            // is to ask user to set it.
            try {
                ((ModuleValidator) validator).setKRInterface(KRFactory.getDefaultInterface());
            } catch (KRInitFailedException e) {
                // TODO: use logger.
                System.out.println(e.getMessage());
            }
            break;
        case MAS2G:
            validator = new MASValidator(filefound.getPath());
            break;
        case TEST2G:
            validator = new TestValidator(filefound.getPath());
            break;
        default:
            // TODO: use logger.
            System.out.println("Expected file with extension 'goal', 'mas2g', 'mod2g', or 'test2g'");
            continue;
        }

        // Validate program file
        validator.validate();

        // Print lexer tokens
        if (lexer) {
            validator.printLexerTokens();
        }

        // Print constructed program
        if (program) {
            System.out.println("\n\n" + validator.getProgram().toString(" ", " "));
        }

        // Print report with warnings, and parsing and validation messages
        System.out.println(validator.report());
    }

    // Get elapsed time.
    long elapsedTime = (System.nanoTime() - startTime) / 1000000;
    System.out.println("Took " + elapsedTime + " milliseconds to analyze " + files.size() + " file(s).");
}

From source file:com.esri.geoevent.test.tools.RunTcpInTcpOutTest.java

public static void main(String args[]) {
    int numberEvents = 10000;
    //int brake = 1000;
    String server = "ags104";
    int in_port = 5565;
    int out_port = 5575;
    int start_rate = 5000;
    int end_rate = 5005;
    int rate_step = 1;

    Options opts = new Options();
    opts.addOption("n", true, "Number of Events");
    opts.addOption("s", true, "Server");
    opts.addOption("i", true, "Input TCP Port");
    opts.addOption("o", true, "Output TCP Port");
    opts.addOption("r", true, "Range");
    opts.addOption("h", false, "Help");
    try {/*from ww  w.j a v a  2s.  c  om*/

        CommandLineParser parser = new BasicParser();
        CommandLine cmd = null;

        try {
            cmd = parser.parse(opts, args, false);
        } catch (ParseException ignore) {
            System.err.println(ignore.getMessage());
        }

        String cmdInputErrorMsg = "";

        if (cmd.getOptions().length == 0 || cmd.hasOption("h")) {
            throw new ParseException("Show Help");
        }

        if (cmd.hasOption("n")) {
            String val = cmd.getOptionValue("n");
            try {
                numberEvents = Integer.valueOf(val);
            } catch (NumberFormatException e) {
                cmdInputErrorMsg += "Invalid value for n. Must be integer.\n";
            }
        }

        if (cmd.hasOption("s")) {
            server = cmd.getOptionValue("s");
        }

        if (cmd.hasOption("i")) {
            String val = cmd.getOptionValue("i");
            try {
                in_port = Integer.valueOf(val);
            } catch (NumberFormatException e) {
                cmdInputErrorMsg += "Invalid value for i. Must be integer.\n";
            }
        }

        if (cmd.hasOption("o")) {
            String val = cmd.getOptionValue("o");
            try {
                out_port = Integer.valueOf(val);
            } catch (NumberFormatException e) {
                cmdInputErrorMsg += "Invalid value for o. Must be integer.\n";
            }
        }

        if (cmd.hasOption("r")) {
            String val = cmd.getOptionValue("r");
            try {
                String parts[] = val.split(",");
                if (parts.length == 3) {
                    start_rate = Integer.parseInt(parts[0]);
                    end_rate = Integer.parseInt(parts[1]);
                    rate_step = Integer.parseInt(parts[2]);
                } else if (parts.length == 1) {
                    // Run single rate
                    start_rate = Integer.parseInt(parts[0]);
                    end_rate = start_rate;
                    rate_step = start_rate;
                } else {
                    throw new ParseException("Rate must be three comma seperated values or a single value");
                }

            } catch (ParseException e) {
                cmdInputErrorMsg += e.getMessage();
            } catch (NumberFormatException e) {
                cmdInputErrorMsg += "Invalid value for r. Must be integers.\n";
            }
        }

        if (!cmdInputErrorMsg.equalsIgnoreCase("")) {
            throw new ParseException(cmdInputErrorMsg);
        }
        DecimalFormat df = new DecimalFormat("##0");
        RunTcpInTcpOutTest t = new RunTcpInTcpOutTest();

        if (start_rate == end_rate) {
            // Single Rate Test
            System.out.println("*********************************");
            System.out.println("Incremental testing at requested rate: " + start_rate);
            System.out.println("Count,Incremental Rate");

            t.runTest(numberEvents, start_rate, server, in_port, out_port, true);
            if (t.send_rate < 0 || t.rcv_rate < 0) {
                throw new Exception("Test Run Failed!");
            }
            System.out.println("Overall Average Send Rate, Received Rate");
            System.out.println(df.format(t.send_rate) + "," + df.format(t.rcv_rate));

        } else {
            System.out.println("*********************************");
            System.out.println("rateRqstd,avgSendRate,avgRcvdRate");

            //for (int rate: rates) {
            for (int rate = start_rate; rate <= end_rate; rate += rate_step) {

                t.runTest(numberEvents, rate, server, in_port, out_port, false);
                if (t.send_rate < 0 || t.rcv_rate < 0) {
                    throw new Exception("Test Run Failed!");
                }
                System.out.println(
                        Integer.toString(rate) + "," + df.format(t.send_rate) + "," + df.format(t.rcv_rate));
            }

        }

    } catch (ParseException e) {
        System.out.println("Invalid Command Options: ");
        System.out.println(e.getMessage());
        System.out.println(
                "Command line options: -n NumEvents -s Server -i InputPort -o OutputPort -r StartRate,EndRate,Step");

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

From source file:act.installer.wikipedia.ImportantChemicalsWikipedia.java

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

    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/* ww w .  j  a  v  a  2 s. co  m*/
    }

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

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(ImportantChemicalsWikipedia.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    String inputPath = cl.getOptionValue(OPTION_WIKIPEDIA_DUMP_FULL_PATH, "1000");
    String outputPath = cl.getOptionValue(OPTION_OUTPUT_PATH, "1000");
    Boolean outputTSV = cl.hasOption(OPTION_TSV_OUTPUT);

    ImportantChemicalsWikipedia importantChemicalsWikipedia = new ImportantChemicalsWikipedia();

    try (BufferedReader br = new BufferedReader(new FileReader(inputPath))) {
        String line;
        while ((line = br.readLine()) != null) {
            importantChemicalsWikipedia.processLine(line);
        }
    } catch (IOException e) {
        LOGGER.error(e);
    }

    if (outputTSV) {
        importantChemicalsWikipedia.writeToTSV(outputPath);
    } else {
        importantChemicalsWikipedia.writeToJSON(outputPath);
    }
}

From source file:de.mfo.jsurf.grid.RotationGrid.java

public static void main(String args[]) {
    size = 100;/*  w  ww  . java  2s.co  m*/
    int xAngleMin = -90;
    int xAngleMax = 90;
    int xSteps = 11;
    int yAngleMin = -90;
    int yAngleMax = 90;
    int ySteps = 11;
    String jsurf_filename = "";
    String output_filename = null;

    Options options = new Options();

    options.addOption("s", "size", true, "width (and height) of a tile image (default: " + size + ")");
    options.addOption("minXAngle", true, "minimum rotation in x direction (default: " + xAngleMin + ")");
    options.addOption("maxXAngle", true, "maximum rotation in x direction (default: " + xAngleMax + ")");
    options.addOption("stepsX", true, "number of steps in x range of rotation (default: " + ySteps + ")");
    options.addOption("minYAngle", true, "minimum rotation in y direction (default: " + yAngleMin + ")");
    options.addOption("maxYAngle", true, "maximum rotation in y direction (default: " + yAngleMax + ")");
    options.addOption("stepsY", true, "number of steps in y range of rotation (default: " + ySteps + ")");
    options.addOption("q", "quality", true,
            "quality of the rendering: 0 (low), 1 (medium, default), 2 (high), 3 (extreme)");
    options.addOption("o", "output", true, "output PNG into this file (otherwise STDOUT)");

    CommandLineParser parser = new PosixParser();
    HelpFormatter formatter = new HelpFormatter();
    String help_header = "RotationGrid [options] jsurf_file";
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.getArgs().length > 0)
            jsurf_filename = cmd.getArgs()[0];
        else {
            formatter.printHelp(help_header, options);
            return;
        }

        if (cmd.hasOption("output"))
            output_filename = cmd.getOptionValue("output");

        if (cmd.hasOption("size"))
            size = Integer.parseInt(cmd.getOptionValue("size"));

        if (cmd.hasOption("minXAngle"))
            xAngleMin = Integer.parseInt(cmd.getOptionValue("minXAngle"));

        if (cmd.hasOption("maxXAngle"))
            xAngleMax = Integer.parseInt(cmd.getOptionValue("maxXAngle"));

        if (cmd.hasOption("stepsX"))
            xSteps = Integer.parseInt(cmd.getOptionValue("stepsX"));

        if (cmd.hasOption("minYAngle"))
            yAngleMin = Integer.parseInt(cmd.getOptionValue("minYAngle"));

        if (cmd.hasOption("maxYAngle"))
            yAngleMax = Integer.parseInt(cmd.getOptionValue("maxYAngle"));

        if (cmd.hasOption("stepsY"))
            ySteps = Integer.parseInt(cmd.getOptionValue("stepsY"));

        if (cmd.hasOption("stepsY"))
            ySteps = Integer.parseInt(cmd.getOptionValue("stepsY"));

        int quality = 1;
        if (cmd.hasOption("quality"))
            quality = Integer.parseInt(cmd.getOptionValue("quality"));
        switch (quality) {
        case 0:
            aam = AntiAliasingMode.ADAPTIVE_SUPERSAMPLING;
            aap = AntiAliasingPattern.OG_1x1;
            break;
        case 2:
            aam = AntiAliasingMode.ADAPTIVE_SUPERSAMPLING;
            aap = AntiAliasingPattern.OG_4x4;
            break;
        case 3:
            aam = AntiAliasingMode.SUPERSAMPLING;
            aap = AntiAliasingPattern.OG_4x4;
            break;
        case 1:
            aam = AntiAliasingMode.ADAPTIVE_SUPERSAMPLING;
            aap = AntiAliasingPattern.QUINCUNX;
        }
    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
    } catch (NumberFormatException nfe) {
        formatter.printHelp("RotationGrid", options);
    }

    asr = new CPUAlgebraicSurfaceRenderer();

    scale = new Matrix4d();
    scale.setIdentity();
    setScale(0.0);

    basic_rotation = new Matrix4d();
    basic_rotation.setIdentity();

    additional_rotation = new Matrix4d();
    additional_rotation.setIdentity();

    try {
        loadFromFile(new File(jsurf_filename).toURI().toURL());
    } catch (Exception e) {
        e.printStackTrace();
    }
    setOptimalCameraDistance(asr.getCamera());
    try {
        BufferedImage bi = renderAnimGrid(xAngleMin, xAngleMax, xSteps, yAngleMin, yAngleMax, ySteps);
        if (output_filename == null)
            saveToPNG(System.out, bi);
        else
            saveToPNG(new FileOutputStream(new File("test.png")), bi);
    } catch (Exception e) {
        e.printStackTrace();
    }
}