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

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

Introduction

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

Prototype

DefaultParser

Source Link

Usage

From source file:com.act.biointerpretation.sars.SarGenerationDriver.java

public static void main(String[] args) throws Exception {
    // Build command line parser.
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/* w ww  . jav  a2s.c  o  m*/
    }

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

    // Print help.
    if (cl.hasOption(OPTION_HELP)) {
        HELP_FORMATTER.printHelp(SarGenerationDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    // Create DB and DbAPI
    MongoDB mongoDB = new MongoDB(LOCAL_HOST, MONGO_PORT, cl.getOptionValue(OPTION_DB));
    DbAPI dbApi = new DbAPI(mongoDB);

    // Handle output file
    File outputFile = new File(cl.getOptionValue(OPTION_OUTPUT_PATH));
    if (outputFile.isDirectory() || outputFile.exists()) {
        LOGGER.error("Supplied output file is a directory or already exists.");
        HELP_FORMATTER.printHelp(SarGenerationDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }
    outputFile.createNewFile();

    // Check that there is exactly one reaction group input option
    if (cl.hasOption(OPTION_REACTION_LIST) && cl.hasOption(OPTION_REACTIONS_FILE)) {
        LOGGER.error("Cannot process both a reaction list and a reactions file as input.");
        HELP_FORMATTER.printHelp(SarGenerationDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }
    if (!cl.hasOption(OPTION_REACTION_LIST) && !cl.hasOption(OPTION_REACTIONS_FILE)) {
        LOGGER.error("Must supply either a reaction list or a reactions file as input.");
        HELP_FORMATTER.printHelp(SarGenerationDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    // Build input reaction group corpus.
    Iterable<ReactionGroup> groups = null;
    if (cl.hasOption(OPTION_REACTION_LIST)) {
        LOGGER.info("Using specific input reactions.");
        ReactionGroup group = new ReactionGroup("ONLY_GROUP", "NO_DB");
        for (String idString : cl.getOptionValues(OPTION_REACTION_LIST)) {
            group.addReactionId(Long.parseLong(idString));
        }
        groups = Arrays.asList(group);
    }
    if (cl.hasOption(OPTION_REACTIONS_FILE)) {
        LOGGER.info("Using reactions file.");
        File inputFile = new File(cl.getOptionValue(OPTION_REACTIONS_FILE));
        try {
            groups = ReactionGroupCorpus.loadFromJsonFile(inputFile);
            LOGGER.info("Successfully parsed input as json file.");
        } catch (IOException e) {
            LOGGER.info("Input file not json file. Trying txt format.");
            try {
                groups = ReactionGroupCorpus.loadFromTextFile(inputFile);
                LOGGER.info("Successfully parsed input as text file.");
            } catch (IOException f) {
                LOGGER.error("Reactions input file not parseable. %s", f.getMessage());
                throw f;
            }
        }
    }

    // Build all pieces of SAR generator
    ReactionProjector projector = new ReactionProjector();
    ExpandedReactionSearcher generalizer = new ExpandedReactionSearcher(projector);

    McsCalculator reactionMcsCalculator = new McsCalculator(McsCalculator.REACTION_BUILDING_OPTIONS);
    McsCalculator sarMcsCalculator = new McsCalculator(McsCalculator.SAR_OPTIONS);

    FullReactionBuilder reactionBuilder = new FullReactionBuilder(reactionMcsCalculator, generalizer,
            projector);

    SarFactory substructureSarFactory = new OneSubstrateSubstructureSar.Factory(sarMcsCalculator);
    SarFactory carbonCountSarFactory = new OneSubstrateCarbonCountSar.Factory();
    List<SarFactory> sarFactories = Arrays.asList(carbonCountSarFactory, substructureSarFactory);

    ErosCorpus roCorpus = new ErosCorpus();
    roCorpus.loadValidationCorpus();

    ReactionGroupCharacterizer reactionGroupCharacterizer = new OneSubstrateOneRoCharacterizer(dbApi,
            sarFactories, reactionBuilder, roCorpus);
    SarCorpusBuilder corpusBuilder = new SarCorpusBuilder(groups, reactionGroupCharacterizer);
    LOGGER.info("Parsed arguments and constructed SAR corpus builder. Building corpus.");

    SarCorpus sarCorpus = corpusBuilder.build();
    LOGGER.info("Built sar corpus. Printing to file in json format.");

    sarCorpus.printToJsonFile(outputFile);
    LOGGER.info("Complete!");
}

From source file:edu.vassar.cs.cmpu331.tvi.Main.java

public static void main(String[] args) {
    Options options = new Options().addOption("t", "trace", false, "Enable tracing.")
            .addOption("d", "debug", false, "Enable debug output.")
            .addOption("s", "size", true, "Sets amount of memory available.")
            .addOption("v", "version", false, "Prints the TVI version number.")
            .addOption("r", "renumber", true, "Renumbers the lines in a files.")
            .addOption("h", "help", false, "Prints this help message");
    CommandLineParser parser = new DefaultParser();
    try {//from w  ww .j a  va 2  s. c o m
        CommandLine opts = parser.parse(options, args);
        if (opts.hasOption('h')) {
            help(options);
            return;
        }
        if (opts.hasOption('v')) {
            System.out.println();
            System.out.println("The Vassar Interpreter v" + Version.getVersion());
            System.out.println(COPYRIGHT);
            System.out.println();
            return;
        }
        if (opts.hasOption('r')) {
            int returnCode = 0;
            try {
                renumber(opts.getOptionValue('r'));
            } catch (IOException e) {
                e.printStackTrace();
                returnCode = 1;
            }
            System.exit(returnCode);
        }
        files = opts.getArgs();
        if (files.length == 0) {
            System.out.println("ERROR: No file names given.");
            help(options);
            System.exit(1);
        }
        if (opts.hasOption('s')) {
            try {
                memory = Integer.parseInt(opts.getOptionValue('s'));
            } catch (NumberFormatException e) {
                System.out.println("ERROR: Invalid --size parameter.");
                help(options);
                System.exit(1);
            }
        }
        if (opts.hasOption('t')) {
            tracing = true;
        }
        if (opts.hasOption('d')) {
            debugging = true;
        }
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        help(options);
        System.exit(1);
    }
    Main app = new Main();
    Arrays.stream(files).forEach(app::run);
}

From source file:com.github.aptd.simulation.CMain.java

/**
 * main method// ww w.  ja  v a 2  s  . co  m
 * @param p_args command-line parameters
 * @throws IOException error on io errors
 */
public static void main(final String[] p_args) throws IOException {
    // --- define CLI options ------------------------------------------------------------------------------------------------------------------------------

    final Options l_clioptions = new Options();
    l_clioptions.addOption("help", false, "shows this information");
    l_clioptions.addOption("generateconfig", false, "generate default configuration");
    l_clioptions.addOption("config", true,
            "path to configuration directory (default: <user home>/.asimov/configuration.yaml)");
    l_clioptions.addOption("interactive", false, "start web server for interactive execution");
    l_clioptions.addOption("sequential", false, "run simulation in sequential (default is parallel)");
    l_clioptions.addOption("iteration", true, "number of iterations");
    l_clioptions.addOption("scenariotype", true, "comma-separated list of scenario types (default: xml)");
    l_clioptions.addOption("scenario", true, "comma-separated list of scenario files");
    l_clioptions.addOption("timemodel", true, "jump for jumping time, step for stepping time (default: step)");
    l_clioptions.addOption("changetimeseed", true,
            "seed for uniform random generator of passenger platform change duration (default: 1)");
    l_clioptions.addOption("changetimemin", true,
            "minimum value for uniform random generator of passenger platform chnge duration in seconds (default: 100)");
    l_clioptions.addOption("changetimemax", true,
            "maximum value for uniform random generator of passenger platform change duration in seconds (default: 100)");
    l_clioptions.addOption("numberofpassengers", true, "number of passengers (default: 20)");
    l_clioptions.addOption("lightbarrierminfreetime", true,
            "minimum duration how long the light barrier has to be free before the door can close (default: 3)");
    l_clioptions.addOption("delayseconds", true, "primary delay of first train in seconds (default: 0)");

    final CommandLine l_cli;
    try {
        l_cli = new DefaultParser().parse(l_clioptions, p_args);
    } catch (final Exception l_exception) {
        System.err.println("command-line arguments parsing error");
        System.exit(-1);
        return;
    }

    // --- process CLI arguments and initialize configuration ----------------------------------------------------------------------------------------------

    if (l_cli.hasOption("help")) {
        new HelpFormatter().printHelp(
                new java.io.File(CMain.class.getProtectionDomain().getCodeSource().getLocation().getPath())
                        .getName(),
                l_clioptions);
        return;
    }

    if (l_cli.hasOption("generateconfig")) {
        System.out
                .println(CCommon.languagestring(CMain.class, "generateconfig", CConfiguration.createdefault()));
        return;
    }

    if (!l_cli.hasOption("scenario")) {
        System.out.println(CCommon.languagestring(CMain.class, "noscenario", CConfiguration.createdefault()));
        System.exit(-1);
        return;
    }

    execute(l_cli);
}

From source file:com.twitter.heron.scheduler.SchedulerMain.java

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

    // construct the options and help options first.
    Options options = constructOptions();
    Options helpOptions = constructHelpOptions();

    // parse the options
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(helpOptions, args, true);

    // print help, if we receive wrong set of arguments
    if (cmd.hasOption("h")) {
        usage(options);/*from   w w w. j  a  va 2s. c  o  m*/
        return;
    }

    // Now parse the required options
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        usage(options);
        throw new RuntimeException("Error parsing command line options: ", e);
    }

    // initialize the scheduler with the options
    String topologyName = cmd.getOptionValue("topology_name");
    SchedulerMain schedulerMain = createInstance(cmd.getOptionValue("cluster"), cmd.getOptionValue("role"),
            cmd.getOptionValue("environment"), cmd.getOptionValue("topology_jar"), topologyName,
            Integer.parseInt(cmd.getOptionValue("http_port")));

    // run the scheduler
    boolean ret = schedulerMain.runScheduler();

    // Log the result and exit
    if (!ret) {
        throw new RuntimeException("Failed to schedule topology: " + topologyName);
    } else {
        // stop the server and close the state manager
        LOG.log(Level.INFO, "Shutting down topology: {0}", topologyName);
    }
}

From source file:act.installer.pubchem.PubchemSynonymFinder.java

public static void main(String[] args) throws Exception {
    org.apache.commons.cli.Options opts = new org.apache.commons.cli.Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*  w  ww. ja 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(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

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

    File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH));
    if (!rocksDBFile.isDirectory()) {
        System.err.format("Index directory does not exist or is not a directory at '%s'",
                rocksDBFile.getAbsolutePath());
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    List<String> compoundIds = null;
    if (cl.hasOption(OPTION_PUBCHEM_COMPOUND_ID)) {
        compoundIds = Collections.singletonList(cl.getOptionValue(OPTION_PUBCHEM_COMPOUND_ID));
    } else if (cl.hasOption(OPTION_IDS_FILE)) {
        File idsFile = new File(cl.getOptionValue(OPTION_IDS_FILE));
        if (!idsFile.exists()) {
            System.err.format("Cannot find Pubchem CIDs file at %s", idsFile.getAbsolutePath());
            HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                    true);
            System.exit(1);
        }

        compoundIds = getCIDsFromFile(idsFile);

        if (compoundIds.size() == 0) {
            System.err.format("Found zero Pubchem CIDs to process in file at '%s', exiting",
                    idsFile.getAbsolutePath());
            HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                    true);
            System.exit(1);
        }
    } else {
        System.err.format("Must specify one of '%s' or '%s'; index is too big to print all synonyms.",
                OPTION_PUBCHEM_COMPOUND_ID, OPTION_IDS_FILE);
        HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    // Run a quick check to warn users of malformed ids.
    compoundIds.forEach(x -> {
        if (!PC_CID_PATTERN.matcher(x).matches()) { // Use matches() for complete matching.
            LOGGER.warn("Specified compound id does not match expected format: %s", x);
        }
    });

    LOGGER.info("Opening DB and searching for %d Pubchem CIDs", compoundIds.size());
    Pair<RocksDB, Map<PubchemTTLMerger.COLUMN_FAMILIES, ColumnFamilyHandle>> dbAndHandles = null;
    Map<String, PubchemSynonyms> results = new LinkedHashMap<>(compoundIds.size());
    try {
        dbAndHandles = PubchemTTLMerger.openExistingRocksDB(rocksDBFile);
        RocksDB db = dbAndHandles.getLeft();
        ColumnFamilyHandle cidToSynonymsCfh = dbAndHandles.getRight()
                .get(PubchemTTLMerger.COLUMN_FAMILIES.CID_TO_SYNONYMS);

        for (String cid : compoundIds) {
            PubchemSynonyms synonyms = null;
            byte[] val = db.get(cidToSynonymsCfh, cid.getBytes(UTF8));
            if (val != null) {
                ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(val));
                // We're relying on our use of a one-value-type per index model here so we can skip the instanceof check.
                synonyms = (PubchemSynonyms) oi.readObject();
            } else {
                LOGGER.warn("No synonyms available for compound id '%s'", cid);
            }
            results.put(cid, synonyms);
        }
    } finally {
        if (dbAndHandles != null) {
            dbAndHandles.getLeft().close();
        }
    }

    try (OutputStream outputStream = cl.hasOption(OPTION_OUTPUT)
            ? new FileOutputStream(cl.getOptionValue(OPTION_OUTPUT))
            : System.out) {
        OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValue(outputStream, results);
        new OutputStreamWriter(outputStream).append('\n');
    }
    LOGGER.info("Done searching for Pubchem synonyms");
}

From source file:EditBinFile.java

/**
 * @param args the command line arguments
 *//*from  w  w  w. j  a  va  2 s .co m*/
public static void main(String[] args) {

    XBTProfile xBTProfileIn;
    XBTProfile xBTProfileOut = null;
    //Call Sign                      | 9HA2072
    //Latitude                       | 32 35.90 N
    //Longitude                      | 047 29.01 W
    //Transect Name                  | AX07
    //Transect Number                | 0
    //Sequence Number                | 160
    //Year                           | 2016
    //Month                          | 03
    //Day                            | 24
    //Hour                           | 04
    //Minute                         | 15
    //Ship Name                      | CMA CGM MOLIERE
    //IMO Number                     | 9401099
    //SEAS ID                        | 4AC81578
    //SEAS Version                   | 930
    //Probe Serial Number            | 1227259
    //Probe Manufacture Date         | 01/01/1970
    //Data Type                      | 1 (Full Resolution)
    //Data Quality                   | 0 (Data Not Suspect)
    //Deployment Height (meters)     | 8.80
    //Ship Direction                 | 086
    //Ship Speed (knots)             | 16.00
    //Instrument Type                | Sippican Deep Blue (Code 52)
    //Recorder Type                  | Sippican MK-21 (Code 6)
    //Wind Instrument Type           | 15
    //Wind Direction                 | 511.0
    //Wind Speed (knots)             | 409.5
    //Dry Bulb Temperature (celsius) | -1.05
    //Current Measurement Method     | 7
    //Current Direction              | 511
    //Current Speed (knots)          | 81.91
    //Total Water Depth (meters)     | 0
    //XBT Launcher Type              | AOML XBT V8.1 Autolauncher (up to 8 Deep Blue and Fast Deep probes)
    //XBT Recorder Serial Number     | 00000000
    //XBT Recorder Manufacture Date  | 01/01/1970
    //Agency in charge of Operation  | USA, NOAA Atlantic Oceanographic and Meteorological Laboratories (AOML)
    //Ship Rider                     | Grant Rawson
    //Ship Rider Institution         | AOML
    //Ship Rider Email               | grant.rawson@noaa.gov
    //Ship Rider Telephone Number    | 305-361-4363
    //===================================================================

    // create the command line parser
    String help;
    String inFile;
    String outFile;
    String callsign;
    String messagetype;
    String latitude;
    String longitude;
    String transectname;
    String transectnum;
    String sequencenum;
    String year;
    String month;
    String day;
    String hour;
    String minute;
    String shipname;
    String imo;
    String seasversion;
    String probeserial;
    String probeyear;
    String probemonth;
    String probeday;
    String datatype;
    String dataquality;
    String height;
    String shipdir;
    String shipspeed;
    String probetype;
    String recorder;
    String windtype;
    String winddir;
    String windspeed;
    String drybulbtemp;
    String currentmethod;
    String currentdir;
    String currentspeed;
    String launcher;
    String recorderserial;
    String recorderyear;
    String recordermonth;
    String recorderday;
    String agency;
    String rider;
    String riderphone;
    String rideremail;
    String institution;
    String depth;
    String[] stringTemps;
    String[] stringRes;

    CommandLineParser parser = new DefaultParser();
    // create the Options
    Options options = new Options();
    options.addOption("help", false, "this screen.");
    options.addOption("i", true, "input file.");
    options.addOption("o", true, "output file name.");
    options.addOption("callsign", true, "the ship's callsign.");
    options.addOption("messagetype", true, "a number denoting the bin files message type.");
    options.addOption("latitude", true, "latitude in decimal degress.");
    options.addOption("longitude", true, "longitude in decimal degrees.");
    options.addOption("transectname", true, "the name give to the transect. e.g. AX07");
    options.addOption("transectnum", true,
            "the number that denotes which transect in the total number of transects for the year.");
    options.addOption("sequencenum", true,
            "the number that denotes which xbt in the total number of xbts used for this cruise.");
    options.addOption("year", true, "four digit number for the year the probe was used.");
    options.addOption("month", true, "two digit number for the month the probe was used.");
    options.addOption("day", true, "two digit number for the day the probe was used.");
    options.addOption("hour", true, "two digit number for the hour the probe was used.");
    options.addOption("minute", true, "two digit number for the minute the probe was used.");
    options.addOption("shipname", true, "the ship's name");
    options.addOption("imo", true, "the ships IMO number");
    options.addOption("seasversion", true,
            "the three digit integer that denotes the version of amverseas used.");
    options.addOption("probeserial", true, "the xbt's serial number");
    options.addOption("probeyear", true, "four digit number for the year the probe was manufactured.");
    options.addOption("probemonth", true, "two digit number for the monthe the probe was manufactured.");
    options.addOption("probeday", true, "two digit number for the day the probe was manufactured.");
    options.addOption("datatype", true,
            "a number that denotes the type of data. e.g. full resolution, two meter resolution ect...");
    options.addOption("dataquality", true,
            "a number that denotes the quality of the data. e.g. was the data good");
    options.addOption("height", true, "a decimal number that denotes the height from the launch was made.");
    options.addOption("shipdir", true, "a decimal number that denotes the ships direction");
    options.addOption("shipspeed", true, "a decimal number in m/s that denotes the ships speed");
    options.addOption("probetype", true, "a number that denotes the type of XBT used.");
    options.addOption("recorder", true, "a number that denotes the type of recorder used.");
    options.addOption("windtype", true,
            "a number that denotes the type of instrument used to make the wind measurement.");
    options.addOption("winddir", true, "a number that denotes the wind direction.");
    options.addOption("windspeed", true, "a decimal number in m/s that denotes the wind speed.");
    options.addOption("drybulbtemp", true, "a decimal number in K that denotes the dry bulb temperature.");
    options.addOption("currentmethod", true,
            "a number that denotes the sea surface current measurement method.");
    options.addOption("currentdir", true, "a decimal number that denotes the sea surface current direction.");
    options.addOption("currentspeed", true, "a decimal number that denotes the sea surface current speed.");
    options.addOption("launcher", true, "a number that denotes the type of launcher used.");
    options.addOption("recorderserial", true,
            "a number that denotes the serial number for the recording device.");
    options.addOption("recorderyear", true, "four digit number for the year the recorder was manufactured");
    options.addOption("recordermonth", true, "two digit number for the monthe the recorder was manufactured.");
    options.addOption("recorderday", true, "two digit number for the monthe the recorder was manufactured.");
    options.addOption("agency", true,
            "a number denoting the agency in charge of operating the observation platform.");
    options.addOption("rider", true, "the rider(s) name.");
    options.addOption("riderphone", true, "the rider(s) phone numbers.");
    options.addOption("rideremail", true, "the rider(s) emails.");
    options.addOption("institution", true, "the rider(s) institution.");
    options.addOption("depth", true, "the total water depth.");
    options.addOption("temps", true, "temperature points delimited by \"@\"");
    options.addOption("res", true, "resistance points delimited by \"@\"");
    // create the parser
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {

            printHelp(options);
            System.exit(0);

        } //end if          

        if (line.hasOption("i")) {
            inFile = line.getOptionValue("i");
            BinDecoder decodedXBTProfile = new BinDecoder(inFile);
            xBTProfileIn = decodedXBTProfile.getXBTProfile();
            xBTProfileOut = xBTProfileIn;

        } //end if
        else {
            printHelp(options);
            throw new ParseException("must provide an input file. use -i filename");

        } //end else

        if (line.hasOption("callsign")) {
            callsign = line.getOptionValue("callsign");
            xBTProfileOut.setCallsign(callsign);

        } //end if 
        if (line.hasOption("messagetype")) {
            messagetype = line.getOptionValue("messagetype");
            xBTProfileOut.setNewMessageType(Integer.parseInt(messagetype));

        } //end if             
        if (line.hasOption("latitude")) {
            latitude = line.getOptionValue("latitude");
            xBTProfileOut.setLatitude(Double.parseDouble(latitude));

        } //end if 
        if (line.hasOption("longitude")) {
            longitude = line.getOptionValue("longitude");
            xBTProfileOut.setLongitude(Double.parseDouble(longitude));

        } //end if 
        if (line.hasOption("transectname")) {
            transectname = line.getOptionValue("transectname");
            xBTProfileOut.setSoopLine(transectname);

        } //end if 
        if (line.hasOption("transectnum")) {
            transectnum = line.getOptionValue("transectnum");
            xBTProfileOut.setTransectNum(Integer.parseInt(transectnum));

        } //end if 
        if (line.hasOption("sequencenum")) {
            sequencenum = line.getOptionValue("sequencenum");
            xBTProfileOut.setSequenceNum(Integer.parseInt(sequencenum));

        } //end if 
        if (line.hasOption("year")) {
            year = line.getOptionValue("year");
            xBTProfileOut.setYear(Integer.parseInt(year));

        } //end if 
        if (line.hasOption("month")) {
            month = line.getOptionValue("month");
            xBTProfileOut.setMonth(Integer.parseInt(month));

        } //end if 
        if (line.hasOption("day")) {
            day = line.getOptionValue("day");
            xBTProfileOut.setDay(Integer.parseInt(day));

        } //end if 
        if (line.hasOption("hour")) {
            hour = line.getOptionValue("hour");
            xBTProfileOut.setHour(Integer.parseInt(hour));

        } //end if 
        if (line.hasOption("minute")) {
            minute = line.getOptionValue("minute");
            xBTProfileOut.setMinute(Integer.parseInt(minute));

        } //end if 
        if (line.hasOption("shipname")) {
            shipname = line.getOptionValue("shipname");
            xBTProfileOut.setShipName(shipname);

        } //end if 
        if (line.hasOption("imo")) {
            imo = line.getOptionValue("imo");
            xBTProfileOut.setLloyds(Integer.parseInt(imo));

        } //end if 
        if (line.hasOption("seasversion")) {
            seasversion = line.getOptionValue("seasversion");
            xBTProfileOut.setSeasVersion(Integer.parseInt(seasversion));

        } //end if 
        if (line.hasOption("probeserial")) {
            probeserial = line.getOptionValue("probeserial");
            xBTProfileOut.setProbeSerialNumber(Integer.parseInt(probeserial));

        } //end if 
        if (line.hasOption("probeyear")) {
            probeyear = line.getOptionValue("probeyear");
            xBTProfileOut.setXBTProbeManufacturedYear(Integer.parseInt(probeyear));

        } //end if 
        if (line.hasOption("probemonth")) {
            probemonth = line.getOptionValue("probemonth");
            xBTProfileOut.setXBTProbeManufacturedMonth(Integer.parseInt(probemonth));

        } //end if 
        if (line.hasOption("probeday")) {
            probeday = line.getOptionValue("probeday");
            xBTProfileOut.setXBTProbeManufacturedDay(Integer.parseInt(probeday));

        } //end if 
        if (line.hasOption("datatype")) {
            datatype = line.getOptionValue("datatype");
            xBTProfileOut.setThisDataIs(Integer.parseInt(datatype));

        } //end if 
        if (line.hasOption("dataquality")) {
            dataquality = line.getOptionValue("dataquality");
            xBTProfileOut.setDataQuality(Integer.parseInt(dataquality));

        } //end if 
        if (line.hasOption("height")) {
            height = line.getOptionValue("height");
            xBTProfileOut.setLaunchHeight(Double.parseDouble(height));

        } //end if 
        if (line.hasOption("shipdir")) {
            shipdir = line.getOptionValue("shipdir");
            xBTProfileOut.setShipDirection(Double.parseDouble(shipdir));

        } //end if 
        if (line.hasOption("shipspeed")) {
            shipspeed = line.getOptionValue("shipspeed");
            xBTProfileOut.setShipSpeed(Double.parseDouble(shipspeed));

        } //end if 
        if (line.hasOption("probetype")) {
            probetype = line.getOptionValue("probetype");
            xBTProfileOut.setInstrumentType(Integer.parseInt(probetype));

        } //end if 
        if (line.hasOption("recorder")) {
            recorder = line.getOptionValue("recorder");
            xBTProfileOut.setRecorderType(Integer.parseInt(recorder));

        } //end if 
        if (line.hasOption("windtype")) {
            windtype = line.getOptionValue("windtype");
            xBTProfileOut.setWindInstrumentType(Integer.parseInt(windtype));

        } //end if 
        if (line.hasOption("winddir")) {
            winddir = line.getOptionValue("winddir");
            xBTProfileOut.setWindDirection(Double.parseDouble(winddir));

        } //end if 
        if (line.hasOption("windspeed")) {
            windspeed = line.getOptionValue("windspeed");
            xBTProfileOut.setWindSpeed(Double.parseDouble(windspeed));

        } //end if 
        if (line.hasOption("drybulbtemp")) {
            drybulbtemp = line.getOptionValue("drybulbtemp");
            xBTProfileOut.setDryBulbTemperature(Double.parseDouble(drybulbtemp));

        } //end if 
        if (line.hasOption("currentmethod")) {
            currentmethod = line.getOptionValue("currentmethod");
            xBTProfileOut.setSeaSurfaceCurrentMeasurementMethod(Integer.parseInt(currentmethod));

        } //end if 
        if (line.hasOption("currentdir")) {
            currentdir = line.getOptionValue("currentdir");
            xBTProfileOut.setSeaSurfaceCurrentDirection(Integer.parseInt(currentdir));

        } //end if 
        if (line.hasOption("currentspeed")) {
            currentspeed = line.getOptionValue("currentspeed");
            xBTProfileOut.setSeaSurfaceCurrentSpeed(Double.parseDouble(currentspeed));

        } //end if 
        if (line.hasOption("launcher")) {
            launcher = line.getOptionValue("launcher");
            xBTProfileOut.setXBTLauncherType(Integer.parseInt(launcher));

        } //end if    
        if (line.hasOption("recorderserial")) {
            recorderserial = line.getOptionValue("recorderserial");
            xBTProfileOut.setXBTRecorderSerialNumber(recorderserial);

        } //end if 
        if (line.hasOption("recorderyear")) {
            recorderyear = line.getOptionValue("recorderyear");
            xBTProfileOut.setXBTRecorderManufacturedYear(Integer.parseInt(recorderyear));

        } //end if 
        if (line.hasOption("recordermonth")) {
            recordermonth = line.getOptionValue("recordermonth");
            xBTProfileOut.setXBTRecorderManufacturedMonth(Integer.parseInt(recordermonth));

        } //end if 
        if (line.hasOption("recorderday")) {
            recorderday = line.getOptionValue("recorderday");
            xBTProfileOut.setXBTRecorderManufacturedDay(Integer.parseInt(recorderday));

        } //end if             

        if (line.hasOption("agency")) {
            agency = line.getOptionValue("agency");
            xBTProfileOut.setAgencyOwner(Integer.parseInt(agency));

        } //end if
        if (line.hasOption("rider")) {
            rider = line.getOptionValue("rider");
            xBTProfileOut.setRiderNames(rider);

        } //end if  
        if (line.hasOption("riderphone")) {
            riderphone = line.getOptionValue("riderphone");
            xBTProfileOut.setRiderPhones(riderphone);

        } //end if  
        if (line.hasOption("rideremail")) {
            rideremail = line.getOptionValue("rideremail");
            xBTProfileOut.setRiderEmails(rideremail);

        } //end if  
        if (line.hasOption("institution")) {
            institution = line.getOptionValue("institution");
            xBTProfileOut.setRiderInstitutions(institution);

        } //end if 
        if (line.hasOption("depth")) {
            depth = line.getOptionValue("depth");
            xBTProfileOut.setTotalWaterDepth(Integer.parseInt(depth));

        } //end if 
        if (line.hasOption("temps")) {
            stringTemps = line.getOptionValue("temps").split("@");

            double[] doubleTemps;

            if (stringTemps.length > 0 && !stringTemps[0].equals("null")) {

                doubleTemps = new double[stringTemps.length];

                for (int i = 0; i < stringTemps.length; i++) {
                    doubleTemps[i] = Double.parseDouble(stringTemps[i]);
                } //end for

            } //end if
            else {
                doubleTemps = new double[0];
            } //end else

            xBTProfileOut.setTemperaturePoints(doubleTemps);

        } //end if
        if (line.hasOption("res")) {
            stringRes = line.getOptionValue("res").split("@");

            double[] doubleRes;

            if (stringRes.length > 0 && !stringRes[0].equals("null")) {

                doubleRes = new double[stringRes.length];

                for (int i = 0; i < stringRes.length; i++) {
                    doubleRes[i] = Double.parseDouble(stringRes[i]);
                    if (doubleRes[i] < 3199.61) {
                        doubleRes[i] = 3199.61;
                    } //end if
                } //end for

            } //end if
            else {
                doubleRes = new double[0];
            } //end else

            xBTProfileOut.setNewMessageType(MessageType.MESSAGE_TYPE_4);
            xBTProfileOut.setResistancePoints(doubleRes);

        } //end if  
        if (line.hasOption("o")) {
            outFile = line.getOptionValue("o");
            BinEncoder encodedXBTProfile = new BinEncoder(xBTProfileOut);
            encodedXBTProfile.writeOutBinFile(outFile);
        } //end if  

        else {
            System.out.println(xBTProfileOut.toString());
        } //end else            

    } //end try//end try
    catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }

}

From source file:com.github.brosander.java.performance.sampler.analysis.PerformanceSampleAnalyzer.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("i", FILE_OPT, true, "The file to analyze.");
    options.addOption("o", OUTPUT_FILE_OPT, true, "The output file (default json to stdout).");
    options.addOption("p", RELEVANT_PATTERN_OPT, true,
            "Pattern(s) to include as roots in the output (default: " + DEFAULT_PATTERN + ")");
    CommandLineParser parser = new DefaultParser();
    try {//from ww  w .j  a v a2s .c  om
        CommandLine commandLine = parser.parse(options, args);
        String file = commandLine.getOptionValue(FILE_OPT);
        if (StringUtils.isEmpty(file)) {
            printUsageAndExit("Must specify file", options, 1);
        }
        Pattern relevantPattern = Pattern
                .compile(commandLine.getOptionValue(RELEVANT_PATTERN_OPT, DEFAULT_PATTERN));
        PerformanceSampleElement performanceSampleElement = relevantElements(relevantPattern,
                new ObjectMapper().readValue(new File(file), PerformanceSampleElement.class));
        updateCounts(performanceSampleElement);
        String outputFile = commandLine.getOptionValue(OUTPUT_FILE_OPT);
        if (StringUtils.isEmpty(outputFile)) {
            new ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(System.out,
                    new OutputPerformanceSampleElement(performanceSampleElement));
        } else {
            new ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(new File(outputFile),
                    new OutputPerformanceSampleElement(performanceSampleElement));
        }
    } catch (Exception e) {
        e.printStackTrace();
        printUsageAndExit(e.getMessage(), options, 2);
    }
}

From source file:com.google.cloud.speech.grpc.demos.NonStreamingRecognizeClient.java

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

    String audioFile = "";
    String host = "speech.googleapis.com";
    Integer port = 443;//from  w  w w.ja v a2s. c  om
    Integer sampling = 16000;

    CommandLineParser parser = new DefaultParser();

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("uri").withDescription("path to audio uri").hasArg()
            .withArgName("FILE_PATH").create());
    options.addOption(
            OptionBuilder.withLongOpt("host").withDescription("endpoint for api, e.g. speech.googleapis.com")
                    .hasArg().withArgName("ENDPOINT").create());
    options.addOption(OptionBuilder.withLongOpt("port").withDescription("SSL port, usually 443").hasArg()
            .withArgName("PORT").create());
    options.addOption(OptionBuilder.withLongOpt("sampling").withDescription("Sampling Rate, i.e. 16000")
            .hasArg().withArgName("RATE").create());

    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("uri")) {
            audioFile = line.getOptionValue("uri");
        } else {
            System.err.println("An Audio uri must be specified (e.g. file:///foo/baz.raw).");
            System.exit(1);
        }

        if (line.hasOption("host")) {
            host = line.getOptionValue("host");
        } else {
            System.err.println("An API enpoint must be specified (typically speech.googleapis.com).");
            System.exit(1);
        }

        if (line.hasOption("port")) {
            port = Integer.parseInt(line.getOptionValue("port"));
        } else {
            System.err.println("An SSL port must be specified (typically 443).");
            System.exit(1);
        }

        if (line.hasOption("sampling")) {
            sampling = Integer.parseInt(line.getOptionValue("sampling"));
        } else {
            System.err.println("An Audio sampling rate must be specified.");
            System.exit(1);
        }
    } catch (ParseException exp) {
        System.err.println("Unexpected exception:" + exp.getMessage());
        System.exit(1);
    }

    NonStreamingRecognizeClient client = new NonStreamingRecognizeClient(host, port, URI.create(audioFile),
            sampling);
    try {
        client.recognize();
    } finally {
        client.shutdown();
    }
}

From source file:com.act.biointerpretation.l2expansion.L2RenderingDriver.java

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

    // Build command line parser.
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//from   w  w  w  .j av  a 2s . c o  m
    }

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

    // Print help.
    if (cl.hasOption(OPTION_HELP)) {
        HELP_FORMATTER.printHelp(L2RenderingDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    // Set up input corpus file.
    File corpusFile = new File(cl.getOptionValue(OPTION_CORPUS_PATH));
    if (!corpusFile.exists()) {
        LOGGER.error("Input corpus file does not exist");
        return;
    }
    //Set up output directory.
    File outputDirectory = new File(cl.getOptionValue(OPTION_OUTPUT_DIRECTORY));
    if (outputDirectory.exists() && !outputDirectory.isDirectory()) {
        LOGGER.error("Can't render corpus: supplied image directory is an existing non-directory file.");
        return;
    }
    outputDirectory.mkdir();

    LOGGER.info("Reading in corpus from file.");
    L2PredictionCorpus predictionCorpus = L2PredictionCorpus.readPredictionsFromJsonFile(corpusFile);
    LOGGER.info("Finished reading in corpus with %d predictions", predictionCorpus.getCorpus().size());

    // Set image format options
    String format = cl.getOptionValue(OPTION_IMAGE_FORMAT, DEFAULT_IMAGE_FORMAT);
    Integer width = Integer.parseInt(cl.getOptionValue(OPTION_IMAGE_WIDTH, DEFAULT_IMAGE_WIDTH));
    Integer height = Integer.parseInt(cl.getOptionValue(OPTION_IMAGE_HEIGHT, DEFAULT_IMAGE_HEIGHT));

    // Render the corpus.
    LOGGER.info("Drawing images for each prediction in corpus.");
    ReactionRenderer reactionRenderer = new ReactionRenderer(format, width, height);
    PredictionCorpusRenderer renderer = new PredictionCorpusRenderer(reactionRenderer);
    renderer.renderCorpus(predictionCorpus, outputDirectory);

    LOGGER.info("L2RenderingDriver complete!");
}

From source file:com.nextdoor.bender.Bender.java

/**
 * Main entrypoint for the Bender CLI tool - handles the argument parsing and triggers the
 * appropriate methods for ultimately invoking a Bender Handler.
 *
 * @param args//from w  w w. j ava  2s  . c  o  m
 * @throws ParseException
 */
public static void main(String[] args) throws ParseException {

    /*
     * Create the various types of options that we support
     */
    Option help = Option.builder("H").longOpt("help").desc("Print this message").build();
    Option handler = Option.builder("h").longOpt("handler").hasArg()
            .desc("Which Event Handler do you want to simulate? \n"
                    + "Your options are: KinesisHandler, S3Handler. \n" + "Default: KinesisHandler")
            .build();
    Option source_file = Option.builder("s").longOpt("source_file").required().hasArg()
            .desc("Reference to the file that you want to process. Usage depends "
                    + "on the Handler you chose. If you chose KinesisHandler "
                    + "then this is a local file (file://path/to/file). If you chose "
                    + "S3Handler, then this is the path to the file in S3 that you want to process "
                    + "(s3://bucket/file...)")
            .build();
    Option kinesis_stream_name = Option.builder().longOpt("kinesis_stream_name").hasArg()
            .desc("What stream name should we mimic? " + "Default: " + KINESIS_STREAM_NAME
                    + " (Kinesis Handler Only)")
            .build();

    /*
     * Build out the option handler and parse the options
     */
    Options options = new Options();
    options.addOption(help);
    options.addOption(handler);
    options.addOption(kinesis_stream_name);
    options.addOption(source_file);

    /*
     * Prepare our help formatter
     */
    HelpFormatter formatter = new HelpFormatter();
    formatter.setWidth(100);
    formatter.setSyntaxPrefix("usage: BENDER_CONFIG=file://config.yaml java -jar");

    /*
     * Parse the options themselves. Throw an error and help if necessary.
     */
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (UnrecognizedOptionException | MissingOptionException | MissingArgumentException e) {
        logger.error(e.getMessage());
        formatter.printHelp(name, options);
        System.exit(1);
    }

    /*
     * The CLI tool doesn't have any configuration files built into it. We require that the user set
     * BENDER_CONFIG to something reasonable.
     */
    if (System.getenv("BENDER_CONFIG") == null) {
        logger.error("You must set the BENDER_CONFIG environment variable. \n"
                + "Valid options include: file://<file>");
        formatter.printHelp(name, options);
        System.exit(1);
    }

    if (cmd.hasOption("help")) {
        formatter.printHelp(name, options);
        System.exit(0);
    }

    /*
     * Depending on the desired Handler, we invoke a specific method and pass in the options (or
     * defaults) required for that handler.
     */
    String handler_value = cmd.getOptionValue(handler.getLongOpt(), KINESIS);
    try {

        switch (handler_value.toLowerCase()) {

        case KINESIS:
            invokeKinesisHandler(cmd.getOptionValue(kinesis_stream_name.getLongOpt(), KINESIS_STREAM_NAME),
                    cmd.getOptionValue(source_file.getLongOpt()));
            break;

        case S3:
            invokeS3Handler(cmd.getOptionValue(source_file.getLongOpt()));
            break;

        /*
         * Error out if an invalid handler was supplied.
         */
        default:
            logger.error("Invalid Handler Option (" + handler_value + "), valid options are: " + KINESIS);
            formatter.printHelp(name, options);
            System.exit(1);
        }
    } catch (HandlerException e) {
        logger.error("Error executing handler: " + e);
        System.exit(1);
    }
}