List of usage examples for org.apache.commons.cli CommandLine getOptions
public Option[] getOptions()
From source file:edu.usc.scrc.PriorityPruner.CommandLineOptions.java
/** * Parses command line arguments, evaluates them, and stores values if * they're correct./*from w w w .j a v a 2 s . c o m*/ * * @param options * collection of Option-objects * @param args * command line arguments * @throws PriorityPrunerException * if error occurs during parsing */ private void parse(Options options, String[] args) throws PriorityPrunerException { try { CommandLineParser cmdLineParser = new GnuParser(); CommandLine commandLine = cmdLineParser.parse(options, args); setParsedOptions(commandLine.getOptions()); // gets set to true if -tfile option is entered through the command // line //boolean tFlag = false; // counts --tped & --tfam options entered through the command line //int tpedCount = 0; //int tfamCount = 0; // loops through all options to save the ones in effect as a String // for printing String tmp = "Options in effect:"; for (Option opt : commandLine.getOptions()) { tmp += ("\r\n -" + opt.getOpt()); if (opt.getValues() != null) { for (int i = 0; i < opt.getValues().length; i++) { tmp += (" " + opt.getValues()[i]); } } } // saves options in effect for printing this.setOptionsInEffect(tmp + "\r\n"); // parse max_distance if (commandLine.hasOption("max_distance")) { this.maxDistance(getLongArgument("max_distance", commandLine.getOptionValue("max_distance"), 0, Long.MAX_VALUE)); checkInput(1, "max_distance", commandLine); } // parse min_maf if (commandLine.hasOption("min_maf")) { this.setMinMaf(getDoubleArgument("min_maf", commandLine.getOptionValue("min_maf"), 0, 0.5)); checkInput(1, "min_maf", commandLine); } // parse min_hwe // if (commandLine.hasOption("min_hwe")) { // this.setMinHwe(getDoubleArgument("min_hwe", // commandLine.getOptionValue("min_hwe"), 0, 1)); // checkInput(1, "min_hwe", commandLine); // } // parses min_snp_callrate if (commandLine.hasOption("min_snp_callrate")) { this.setMinSnpCallRate(getDoubleArgument("min_snp_callrate", commandLine.getOptionValue("min_snp_callrate"), 0, 1)); checkInput(1, "min_snp_callrate", commandLine); } // parses min_design_score if (commandLine.hasOption("min_design_score")) { this.setMinDesignScore(getDoubleArgument("min_design_score", commandLine.getOptionValue("min_design_score"), 0, Double.MAX_VALUE)); checkInput(1, "min_design_score", commandLine); } // // parses option that sets the absolute minimum design score // // value, allowed arguments are doubles between 0.0 and // // Double.MAX_VALUE // if (commandLine.hasOption("amds")) { // this.setAbsoluteMinDesignScore(getDoubleArgument( // "absmindesignscore", // commandLine.getOptionValue("amds"), 0, Double.MAX_VALUE)); // checkInput(1, "amds", commandLine); // } // parse metric if (commandLine.hasOption("metric")) { String[] str = commandLine.getOptionValues("metric"); if (str.length % 2 == 1) { throw new PriorityPrunerException( "Only one argument specified for option \"metric\", a column name (text string) and a weight (decimal number) are required."); } else { for (int i = 0; i < str.length; i++) { if (str[i].equals("design_score")) { throw new PriorityPrunerException("Invalid metric: \"" + str[i] + "\". To filter on design score, simply add correct column in the SNP input file, no metric is needed."); } addMetric(str[i], this.getDoubleArgument("metric", str[i + 1], 0, Double.MAX_VALUE)); i++; } } } // parse st if (commandLine.hasOption("st")) { String[] str = commandLine.getOptionValues("st"); if (str.length % 2 == 1) { throw new PriorityPrunerException( "Only one argument specified for option: \"st\", a p-value (decimal number) and a number of surrogates (integer) are are required."); } else { for (int i = 0; i < str.length; i++) { addSurrogateThreshold(this.getDoubleArgument("st", str[i], 0, 1), this.getIntegerArgument("st", str[i + 1], 0, Integer.MAX_VALUE)); i++; } } } // parse r2t if (commandLine.hasOption("r2t")) { String[] str = commandLine.getOptionValues("r2t"); if (str.length % 2 == 1) { throw new PriorityPrunerException( "Only one argument specified for option: \"r2t\", a p-value and a threshold (decimal numbers between 0 and 1) are required."); } else { for (int i = 0; i < str.length; i++) { addR2Threshold(this.getDoubleArgument("r2t", str[i], 0, 1), this.getDoubleArgument("r2t", str[i + 1], 0, 1)); i++; } } } // parse r2 if (commandLine.hasOption("r2")) { String value = commandLine.getOptionValue("r2"); this.addR2Threshold(1, this.getDoubleArgument("r2", value, 0, 1)); checkInput(1, "r2", commandLine); } // parse chr if (commandLine.hasOption("chr")) { String value = commandLine.getOptionValue("chr"); // recoding chromosome X-representations to "23" if (value.toUpperCase().equals("X") || value.toUpperCase().equals("CHRX")) { //value = "23"; } // if chromosome Y or mitochondrial DNA is encountered, an // exception is thrown else if (value.toUpperCase().equals("M") || value.toUpperCase().equals("MT") || value.toUpperCase().equals("CHRM") || value.toUpperCase().equals("CHRMT") || value.toUpperCase().equals("Y") || value.toUpperCase().equals("CHRY") || value.toUpperCase().equals("24")) { throw new PriorityPrunerException("Chromosome \"" + value + "\" specified in the command line, is not supported. Please update input files and rerun program."); } this.setChr(value); checkInput(1, "chr", commandLine); } // parse out if (commandLine.hasOption("out")) { String value = commandLine.getOptionValue("out"); if (value.endsWith("/")) { value = new StringBuilder(value).append("prioritypruner").toString(); } this.setOutputPrefix(value); checkInput(1, "out", commandLine); } // // parse forceInclude // if (commandLine.hasOption("force_include")) { // String value = commandLine.getOptionValue("force_include"); // this.setForceIncludeFilePath(value); // checkInput(1, "force_include", commandLine); // } // parse do_not_pick_force_included_snps_first if (commandLine.hasOption("do_not_pick_force_included_snps_first")) { this.setSortByForceIncludeAndPValue(false); } // parse snp_table if (commandLine.hasOption("snp_table")) { String[] str = commandLine.getOptionValues("snp_table"); this.setSnpTablePath(str[0]); // counts number of metrics added to command line int metrics = 0; for (int i = 0; i < getParsedOptions().length; i++) { if (getParsedOptions()[i].getOpt().equals("metric")) { metrics++; } } this.setNumMetrics(metrics); checkInput(1, "snp_table", commandLine); } // parse tped if (commandLine.hasOption("tped")) { String value = commandLine.getOptionValue("tped"); checkInput(1, "tped", commandLine); this.setTped(value); } // parse tfam if (commandLine.hasOption("tfam")) { String value = commandLine.getOptionValue("tfam"); checkInput(1, "tfam", commandLine); this.setTfam(value); } // parse tfile if (commandLine.hasOption("tfile")) { String value = commandLine.getOptionValue("tfile"); checkInput(1, "tfile", commandLine); this.setTped(value + ".tped"); this.setTfam(value + ".tfam"); this.setTfile(value); } // parse use_surrogate_for_non_passing_index_snps // if (commandLine.hasOption("use_surrogate_for_non_passing_index_snps")) { // this.setUseSurrogateForNonPassingIndexSnp(true); // } // parses verbose if (commandLine.hasOption("verbose")) { this.setVerbose(true); } // parse outputLDTable if (commandLine.hasOption("ld")) { this.setOutputLDTable(true); } // parse remove if (commandLine.hasOption("remove")) { String value = commandLine.getOptionValue("remove"); checkInput(1, "remove", commandLine); this.setRemove(value); } // parse keep if (commandLine.hasOption("keep")) { String value = commandLine.getOptionValue("keep"); checkInput(1, "keep", commandLine); this.setKeep(value); } // parse keep_random if (commandLine.hasOption("keep_random")) { String value = commandLine.getOptionValue("keep_random"); this.setKeepPercentage(this.getDoubleArgument("keep_random", value, 0, 1)); checkInput(1, "keep_random", commandLine); } // parse no_surrogates_for_force_included_snps if (commandLine.hasOption("no_surrogates_for_force_included_snps")) { this.setAddSurrogatesForForceIncludedSnps(false); } // parse seed if (commandLine.hasOption("seed")) { String value = commandLine.getOptionValue("seed"); this.seed = new Long(this.getLongArgument("seed", value, Long.MIN_VALUE, Long.MAX_VALUE)); } // check that we have all required arguments checkRequiredArguments(commandLine); // checks if any unrecognized arguments been entered checkLeftArguments(commandLine); // if several options from the same options group been entered, // an AlreadySelectedException gets thrown. A custom message is // generated since we wanted another design than the one provided in // the library gave } catch (AlreadySelectedException e) { String message = ""; for (int i = 0; i < e.getOptionGroup().getNames().toArray().length; i++) { message += "\"" + e.getOptionGroup().getNames().toArray()[i] + "\" "; } throw new PriorityPrunerException( "The options: " + message + " may not both be defined. Type --help for help."); // if an undefined option is entered an UnrecognizedOptionException // gets thrown } catch (UnrecognizedOptionException e) { throw new PriorityPrunerException(e.getOption() + " is not a valid option. Type --help for help."); // if an option that is supposed to have arguments is missing, // a MissingArgumentException gets thrown } catch (MissingArgumentException e) { throw new PriorityPrunerException("Missing argument for option \"" + e.getOption().getOpt() + "\". Expected: " + e.getOption().getArgName() + ". Type --help for help."); // if a required option is missing, a MissingOptionException gets // thrown } catch (MissingOptionException e) { // if any other problem occurs while parsing, a general // ParseException gets thrown } catch (ParseException parseException) { throw new PriorityPrunerException("Invalid command line options. Type --help for help."); } }
From source file:alluxio.cli.fsadmin.command.ReportCommand.java
@Override public int run(CommandLine cl) throws IOException { try {// w ww .j a va 2s . co m String[] args = cl.getArgs(); if (cl.hasOption(HELP_OPTION_NAME) && !(args.length > 0 && args[0].equals("capacity"))) { // if category is capacity, we print report capacity usage inside CapacityCommand. System.out.println(getUsage()); System.out.println(getDescription()); return 0; } // Get the report category Command command = Command.SUMMARY; if (args.length == 1) { switch (args[0]) { case "capacity": command = Command.CAPACITY; break; case "configuration": command = Command.CONFIGURATION; break; case "metrics": command = Command.METRICS; break; case "summary": command = Command.SUMMARY; break; case "ufs": command = Command.UFS; break; default: System.out.println(getUsage()); System.out.println(getDescription()); throw new InvalidArgumentException("report category is invalid."); } } // Only capacity category has [category args] if (!command.equals(Command.CAPACITY)) { if (cl.getOptions().length > 0) { throw new InvalidArgumentException(String.format("report %s does not support arguments: %s", command.toString().toLowerCase(), cl.getOptions()[0].getOpt())); } } // Check if Alluxio master and client services are running try (CloseableResource<FileSystemMasterClient> client = FileSystemContext.INSTANCE .acquireMasterClientResource()) { MasterInquireClient inquireClient = null; try { InetSocketAddress address = client.get().getAddress(); List<InetSocketAddress> addresses = Arrays.asList(address); inquireClient = new PollingMasterInquireClient(addresses, () -> new ExponentialBackoffRetry(50, 100, 2)); } catch (UnavailableException e) { System.err.println("Failed to get the leader master."); System.err.println("Please check your Alluxio master status"); return 1; } try { inquireClient.getPrimaryRpcAddress(); } catch (UnavailableException e) { System.err.println("The Alluxio leader master is not currently serving requests."); System.err.println("Please check your Alluxio master status"); return 1; } } switch (command) { case CAPACITY: CapacityCommand capacityCommand = new CapacityCommand(mBlockMasterClient, mPrintStream); capacityCommand.run(cl); break; case CONFIGURATION: ConfigurationCommand configurationCommand = new ConfigurationCommand(mMetaMasterClient, mPrintStream); configurationCommand.run(); break; case METRICS: MetricsCommand metricsCommand = new MetricsCommand(mMetaMasterClient, mPrintStream); metricsCommand.run(); break; case SUMMARY: SummaryCommand summaryCommand = new SummaryCommand(mMetaMasterClient, mBlockMasterClient, mPrintStream); summaryCommand.run(); break; case UFS: UfsCommand ufsCommand = new UfsCommand(mFileSystemMasterClient); ufsCommand.run(); break; default: break; } } finally { mCloser.close(); } return 0; }
From source file:cmd.ArgumentHandler.java
/** * Parses the options in the command line arguments and returns an array of * strings corresponding to the filenames given as arguments only * * @param args//from ww w . j a v a 2 s .c o m * @throws org.apache.commons.cli.ParseException */ @SuppressWarnings("static-access") public void parseCommandLineOptions(String[] args) throws ParseException { options = new Options(); options.addOption("h", "help", false, "Help page for command usage"); options.addOption("s", false, "SubStructure detection"); options.addOption("a", false, "Add Hydrogen"); options.addOption("x", false, "Match Atom Type"); options.addOption("r", false, "Remove Hydrogen"); options.addOption("z", false, "Ring matching"); options.addOption("b", false, "Match Bond types (Single, Double etc)"); options.addOption( OptionBuilder.hasArg().withDescription("Query filename").withArgName("filepath").create("q")); options.addOption( OptionBuilder.hasArg().withDescription("Target filename").withArgName("filepath").create("t")); options.addOption(OptionBuilder.hasArg().withDescription("Add suffix to the files").withArgName("suffix") .create("S")); options.addOption("g", false, "create png of the mapping"); options.addOption(OptionBuilder.hasArg().withDescription("Dimension of the image in pixels") .withArgName("WIDTHxHEIGHT").create("d")); options.addOption("m", false, "Report all Mappings"); String filterDescr = "Default: 0, Stereo: 1, " + "Stereo+Fragment: 2, Stereo+Fragment+Energy: 3"; options.addOption(OptionBuilder.hasArg().withDescription(filterDescr).withArgName("number").create("f")); options.addOption("A", false, "Appends output to existing files, else creates new files"); options.addOption(OptionBuilder.withDescription("Do N-way MCS on the target SD file").create("N")); options.addOption(OptionBuilder.hasArg().withDescription("Query type (MOL, SMI, etc)").withArgName("type") .create("Q")); options.addOption(OptionBuilder.hasArg().withDescription("Target type (MOL, SMI, SMIF, etc)") .withArgName("type").create("T")); options.addOption(OptionBuilder.hasArg().withDescription("Output the substructure to a file") .withArgName("filename").create("o")); options.addOption( OptionBuilder.hasArg().withDescription("Output type (SMI, MOL)").withArgName("type").create("O")); options.addOption(OptionBuilder.hasOptionalArgs(2).withValueSeparator().withDescription("Image options") .withArgName("option=value").create("I")); PosixParser parser = new PosixParser(); CommandLine line = parser.parse(options, args, true); if (line.hasOption('Q')) { queryType = line.getOptionValue("Q"); } //else { // queryType = "MOL"; // } //XXX default type? if (line.hasOption('T')) { targetType = line.getOptionValue("T"); } else { targetType = "MOL"; } if (line.hasOption('a')) { this.setApplyHAdding(true); } if (line.hasOption('r')) { this.setApplyHRemoval(true); } if (line.hasOption('m')) { this.setAllMapping(true); } if (line.hasOption('s')) { this.setSubstructureMode(true); } if (line.hasOption('g')) { this.setImage(true); } if (line.hasOption('b')) { this.setMatchBondType(true); } if (line.hasOption('z')) { this.setMatchRingType(true); } if (line.hasOption('x')) { this.setMatchAtomType(true); } remainingArgs = line.getArgs(); if (line.hasOption('h') || line.getOptions().length == 0) { // System.out.println("Hello"); helpRequested = true; } if (line.hasOption('S')) { String[] suffix_reader = line.getOptionValues('S'); if (suffix_reader.length < 1) { System.out.println("Suffix required!"); helpRequested = true; } setSuffix(suffix_reader[0]); setApplySuffix(true); } if (line.hasOption('f')) { String[] filters = line.getOptionValues('f'); if (filters.length < 1) { System.out.println("Chemical filter required (Ranges: 0 to 3)!"); helpRequested = true; } setChemFilter((int) new Integer(filters[0])); } if (line.hasOption('q')) { queryFilepath = line.getOptionValue('q'); } if (line.hasOption('t')) { targetFilepath = line.getOptionValue('t'); } if (line.hasOption("A")) { this.setAppendMode(true); } if (line.hasOption("N")) { setNMCS(true); } if (line.hasOption("o")) { outputSubgraph = true; outputFilepath = line.getOptionValue("o"); } if (line.hasOption("O")) { outputFiletype = line.getOptionValue("O"); } else { outputFiletype = "MOL"; } if (line.hasOption("d")) { String dimensionString = line.getOptionValue("d"); if (dimensionString.contains("x")) { String[] parts = dimensionString.split("x"); try { setImageWidth(Integer.parseInt(parts[0])); setImageHeight(Integer.parseInt(parts[1])); System.out.println("set image dim to " + getImageWidth() + "x" + getImageHeight()); } catch (NumberFormatException nfe) { throw new ParseException("Malformed dimension string " + dimensionString); } } else { throw new ParseException("Malformed dimension string " + dimensionString); } } if (line.hasOption("I")) { imageProperties = line.getOptionProperties("I"); if (imageProperties.isEmpty()) { // used just "-I" by itself isImageOptionHelp = true; } } }
From source file:io.github.felsenhower.stine_calendar_bot.main.CallLevelWrapper.java
public CallLevelWrapper(String[] args) throws IOException { String username = null;// w w w . jav a 2 s . c o m String password = null; boolean echoPages = false; Path calendarCache = null; Path outputFile = null; boolean echoCalendar = false; // These temporary options don't have descriptions and have their // required-value all set to false final Options tempOptions = getOptions(); final CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; StringProvider strings = null; // Get the StringProvider try { cmd = parser.parse(tempOptions, args, true); if (cmd.hasOption("language")) { String lang = cmd.getOptionValue("language").toLowerCase(); if (lang.equals("de")) { strings = new StringProvider(Locale.GERMAN); } else { strings = new StringProvider(Locale.ENGLISH); if (!lang.equals("en")) { System.err.println(strings.get("HumanReadable.CallLevel.LangNotRecognised", lang)); } } } else { strings = new StringProvider(new Locale(Locale.getDefault().getLanguage())); } } catch (Exception e) { strings = new StringProvider(Locale.ENGLISH); } this.strings = strings; this.cliStrings = strings.from("HumanReadable.CallLevel"); this.messages = strings.from("HumanReadable.Messages"); this.appInfo = strings.from("MachineReadable.App"); // Get the localised options, with all required fields enabled as well. // Note that we are not yet applying the options to any command line, // because we still want to exit if only the help screen shall be // displayed first, but of course, we do need the localised options // here. this.isLangInitialised = true; this.options = getOptions(); try { // If no arguments are supplied, or --help is used, we will exit // after printing the help screen if (cmd.hasOption("help") || (cmd.hasOption("language") && cmd.getOptions().length == 1)) { printHelp(); } cmd = parser.parse(this.options, args, false); username = cmd.getOptionValue("user"); // URL-decode the password (STiNE doesn't actually allow special // chars in passwords, but meh...) password = URLDecoder.decode(cmd.getOptionValue("pass"), "UTF-8"); // Double-dash signals that the password shall be read from stdin if (password.equals("--")) { password = readPassword(messages.get("PasswordQuery"), messages.get("PasswordFallbackMsg")); } echoPages = cmd.hasOption("echo"); // the cache-dir argument is optional, so we read it with a default // value calendarCache = Paths .get(cmd.getOptionValue("cache-dir", strings.get("MachineReadable.Paths.CalendarCache"))) .toAbsolutePath(); // output-argument is optional as well, but this time we check if // double-dash is specified (for echo to stdout) String outputStr = cmd.getOptionValue("output", strings.get("MachineReadable.Paths.OutputFile")); if (outputStr.equals("--")) { echoCalendar = true; outputFile = null; } else { echoCalendar = false; outputFile = Paths.get(outputStr).toAbsolutePath(); } } catch (UnrecognizedOptionException e) { System.err.println(messages.get("UnrecognisedOption", e.getOption().toString())); this.printHelp(); } catch (MissingOptionException e) { // e.getMissingOptions() is just extremely horribly designed and // here is why: // // It returns an unparametrised list, to make your job especially // hard, whose elements may be: // - String-instances, if there are single independent options // missing (NOT the stupid Option itself, just why????) // - OptionGroup-instances, if there are whole OptionGroups missing // (This time the actual OptionGroup and not an unparametrised Set // that may or may not contain an Option, how inconsequential). // - Basically anything because the programmer who wrote that // function was clearly high and is most probably not to be trusted. // // This makes the job of actually displaying all the options as a // comma-separated list unnecessarily hard and hence leads to this // ugly contraption of Java-8-statements. But hey, at least it's not // as ugly as the Java 7 version (for me at least). // Sorry! // TODO: Write better code. // TODO: Write my own command line interpreter, with blackjack and // hookers. try { System.err.println(messages.get("MissingRequiredOption", ((List<?>) (e.getMissingOptions())) .stream().filter(Object.class::isInstance).map(Object.class::cast).map(o -> { if (o instanceof String) { return Collections.singletonList(options.getOption((String) o)); } else { return ((OptionGroup) o).getOptions(); } }).flatMap(o -> o.stream()).filter(Option.class::isInstance).map(Option.class::cast) .map(o -> o.getLongOpt()).collect(Collectors.joining(", ")))); this.printHelp(); } catch (Exception totallyMoronicException) { throw new RuntimeException("I hate 3rd party libraries!", totallyMoronicException); } } catch (MissingArgumentException e) { System.err.println(messages.get("MissingRequiredArgument", e.getOption().getLongOpt())); this.printHelp(); } catch (ParseException e) { System.err.println(messages.get("CallLevelParsingException", e.getMessage())); } this.username = username; this.password = password; this.echoPages = echoPages; this.calendarCache = calendarCache; this.outputFile = outputFile; this.echoCalendar = echoCalendar; }
From source file:cz.pecina.retro.ondra.CommandLineProcessor.java
/** * Creates an instance of the command line procssor. * * @param hardware the hardware object to operate on */// w w w . j a v a 2 s . c om public CommandLineProcessor(final Hardware hardware) { log.fine("New CommandLineProcessor creation started"); this.hardware = hardware; // build options log.fine("Building options"); options.addOption( Option.builder("?").longOpt("help").desc(Application.getString(this, "option.help")).build()); options.addOption( Option.builder("V").longOpt("version").desc(Application.getString(this, "option.version")).build()); options.addOption(Option.builder("l").longOpt("language").hasArg().argName("CODE") .desc(Application.getString(this, "option.language")).build()); options.addOption(Option.builder("p").longOpt("pixel-size").hasArg().argName("SIZE") .desc(Application.getString(this, "option.pixelSize")).build()); options.addOption(Option.builder("a").longOpt("address").hasArg().argName("ADDR") .desc(Application.getString(this, "option.address")).build()); options.addOption(Option.builder("o").longOpt("ROM-file").hasArg().argName("FILE") .desc(Application.getString(this, "option.ROM")).build()); options.addOption(Option.builder("b").longOpt("binary").hasArgs().numberOfArgs(2).argName("FILE>,<ADDR") .valueSeparator(',').desc(Application.getString(this, "option.binary")).build()); options.addOption(Option.builder("h").longOpt("intel-hex").hasArg().argName("FILE") .desc(Application.getString(this, "option.intelHex")).build()); options.addOption(Option.builder("x").longOpt("xml").hasArg().argName("FILE") .desc(Application.getString(this, "option.xml")).build()); options.addOption(Option.builder("s").longOpt("snapshot").hasArg().argName("FILE") .desc(Application.getString(this, "option.snapshot")).build()); options.addOption(Option.builder("w").longOpt("write-snapshot").hasArg().argName("FILE") .desc(Application.getString(this, "option.writeSnapshot")).build()); options.addOption(Option.builder("S").longOpt("speed-up").hasArg().argName("FACTOR") .desc(Application.getString(this, "option.speedUp")).build()); options.addOption( Option.builder("g").longOpt("opengl").desc(Application.getString(this, "option.openGL")).build()); options.addOption(Option.builder("G").longOpt("no-opengl") .desc(Application.getString(this, "option.noOpenGL")).build()); log.finer("Options set up"); // parse the command line final CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, Parameters.arguments); } catch (final Exception exception) { usage(); error(); } log.finer("Command line parsed"); // load default snapshot if exists boolean success = false; for (String name : DEFAULT_SNAPSHOT_NAMES) { final File defaultSnapshot = new File(name); if (defaultSnapshot.canRead()) { try { new Snapshot(hardware).read(defaultSnapshot); } catch (final RuntimeException exception) { log.fine("Error reading default snapshot"); System.out.println(Application.getString(this, "error.errorDefaultShapshot")); error(); } log.fine("Default snapshot read from the current directory"); success = true; break; } } if (!success) { for (String name : DEFAULT_SNAPSHOT_NAMES) { final File defaultSnapshot = new File(new File(System.getProperty("user.home")), name); if (defaultSnapshot.canRead()) { try { new Snapshot(hardware).read(defaultSnapshot); } catch (final Exception exception) { log.fine("Error reading default snapshot"); System.out.println(Application.getString(this, "error.errorDefaultShapshot")); error(); } log.fine("Default snapshot read from the user's home directory"); break; } } } log.finer("Default files processed"); // process the options if (!line.getArgList().isEmpty()) { usage(); error(); } if (line.hasOption("?")) { log.finer("Processing -?"); usage(); System.exit(0); } if (line.hasOption("V")) { log.finer("Processing -V"); System.out.println(Application.getString(this, "longAppName") + " " + Application.getString(this, "version") + " @VERSION@"); System.exit(0); } try { for (Option option : line.getOptions()) { switch (option.getOpt()) { case "l": log.finer("Processing -l"); final String language = option.getValue(); if (!Arrays.asList(GeneralConstants.SUPPORTED_LOCALES).contains(language)) { System.out.println(Application.getString(this, "error.unsupportedLanguage")); error(); } UserPreferences.setLocale(language); break; case "p": log.finer("Processing -p"); final int pixelSize = Integer.parseInt(option.getValue()); if (!Arrays.asList(GeneralConstants.PIXEL_SIZES).contains(pixelSize)) { System.out.println(Application.getString(this, "error.unsupportedPixelSize")); error(); } UserPreferences.setPixelSize(pixelSize); break; case "o": log.finer("Processing -o"); fileNameROM = option.getValue(); break; case "a": log.finer("Processing -a"); int address = Integer.parseInt(option.getValue(), 16); if ((address < 0) || (address >= 0x10000)) { System.out.println(Application.getString(this, "error.invalidAddress")); error(); } Parameters.cpu.setPC(address); break; case "b": log.finer("Processing -b"); File file = new File(option.getValue(0)); address = Integer.parseInt(option.getValue(1), 16); if ((address < 0) || (address >= 0x10000)) { System.out.println(Application.getString(this, "error.invalidAddress")); error(); } new Raw(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file, address); break; case "h": log.finer("Processing -h"); file = new File(option.getValue()); new IntelHEX(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file); break; case "x": log.finer("Processing -x"); file = new File(option.getValue()); new XML(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file); break; case "s": log.finer("Processing -s"); file = new File(option.getValue()); new Snapshot(hardware).read(file); break; case "w": log.finer("Processing -w"); file = new File(option.getValue()); new Snapshot(hardware).write(file); System.exit(0); break; case "S": log.finer("Processing -S"); Parameters.speedUp = Integer.parseInt(option.getValue()); if (Parameters.speedUp < 1) { System.out.println(Application.getString(this, "error.nonPositiveSpeedUp")); error(); } break; case "g": log.finer("Processing -g"); Parameters.openGL = true; break; case "G": log.finer("Processing -G"); Parameters.openGL = false; break; } } } catch (final Exception exception) { usage(); error(); } log.fine("New CommandLineProcessor creation completed"); }
From source file:cz.pecina.retro.pmd85.CommandLineProcessor.java
/** * Creates an instance of the command line procssor. * * @param hardware the hardware object to operate on *///w ww . j a va2 s .co m public CommandLineProcessor(final Hardware hardware) { log.fine("New CommandLineProcessor creation started"); this.hardware = hardware; // build options log.fine("Building options"); options.addOption( Option.builder("?").longOpt("help").desc(Application.getString(this, "option.help")).build()); options.addOption( Option.builder("V").longOpt("version").desc(Application.getString(this, "option.version")).build()); options.addOption(Option.builder("l").longOpt("language").hasArg().argName("CODE") .desc(Application.getString(this, "option.language")).build()); options.addOption(Option.builder("p").longOpt("pixel-size").hasArg().argName("SIZE") .desc(Application.getString(this, "option.pixelSize")).build()); options.addOption(Option.builder("a").longOpt("address").hasArg().argName("ADDR") .desc(Application.getString(this, "option.address")).build()); options.addOption(Option.builder("o").longOpt("ROM-file").hasArg().argName("FILE") .desc(Application.getString(this, "option.ROM")).build()); options.addOption(Option.builder("m").longOpt("RMM-file").hasArg().argName("FILE") .desc(Application.getString(this, "option.RMM")).build()); options.addOption(Option.builder("b").longOpt("binary").hasArgs().numberOfArgs(2).argName("FILE>,<ADDR") .valueSeparator(',').desc(Application.getString(this, "option.binary")).build()); options.addOption(Option.builder("h").longOpt("intel-hex").hasArg().argName("FILE") .desc(Application.getString(this, "option.intelHex")).build()); options.addOption(Option.builder("x").longOpt("xml").hasArg().argName("FILE") .desc(Application.getString(this, "option.xml")).build()); options.addOption(Option.builder("s").longOpt("snapshot").hasArg().argName("FILE") .desc(Application.getString(this, "option.snapshot")).build()); options.addOption(Option.builder("w").longOpt("write-snapshot").hasArg().argName("FILE") .desc(Application.getString(this, "option.writeSnapshot")).build()); options.addOption(Option.builder("S").longOpt("speed-up").hasArg().argName("FACTOR") .desc(Application.getString(this, "option.speedUp")).build()); options.addOption( Option.builder("g").longOpt("opengl").desc(Application.getString(this, "option.openGL")).build()); options.addOption(Option.builder("G").longOpt("no-opengl") .desc(Application.getString(this, "option.noOpenGL")).build()); log.finer("Options set up"); // parse the command line final CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, Parameters.arguments); } catch (final Exception exception) { usage(); error(); } log.finer("Command line parsed"); // load default snapshot if exists boolean success = false; for (String name : DEFAULT_SNAPSHOT_NAMES) { final File defaultSnapshot = new File(name); if (defaultSnapshot.canRead()) { try { new Snapshot(hardware).read(defaultSnapshot); } catch (final RuntimeException exception) { log.fine("Error reading default snapshot"); System.out.println(Application.getString(this, "error.errorDefaultShapshot")); error(); } log.fine("Default snapshot read from the current directory"); success = true; break; } } if (!success) { for (String name : DEFAULT_SNAPSHOT_NAMES) { final File defaultSnapshot = new File(new File(System.getProperty("user.home")), name); if (defaultSnapshot.canRead()) { try { new Snapshot(hardware).read(defaultSnapshot); } catch (final Exception exception) { log.fine("Error reading default snapshot"); System.out.println(Application.getString(this, "error.errorDefaultShapshot")); error(); } log.fine("Default snapshot read from the user's home directory"); break; } } } log.finer("Default files processed"); // process the options if (!line.getArgList().isEmpty()) { usage(); error(); } if (line.hasOption("?")) { log.finer("Processing -?"); usage(); System.exit(0); } if (line.hasOption("V")) { log.finer("Processing -V"); System.out.println(Application.getString(this, "longAppName") + " " + Application.getString(this, "version") + " @VERSION@"); System.exit(0); } try { for (Option option : line.getOptions()) { switch (option.getOpt()) { case "l": log.finer("Processing -l"); final String language = option.getValue(); if (!Arrays.asList(GeneralConstants.SUPPORTED_LOCALES).contains(language)) { System.out.println(Application.getString(this, "error.unsupportedLanguage")); error(); } UserPreferences.setLocale(language); break; case "p": log.finer("Processing -p"); final int pixelSize = Integer.parseInt(option.getValue()); if (!Arrays.asList(GeneralConstants.PIXEL_SIZES).contains(pixelSize)) { System.out.println(Application.getString(this, "error.unsupportedPixelSize")); error(); } UserPreferences.setPixelSize(pixelSize); break; case "o": log.finer("Processing -o"); fileNameROM = option.getValue(); break; case "m": log.finer("Processing -m"); fileNameRMM = option.getValue(); break; case "a": log.finer("Processing -a"); int address = Integer.parseInt(option.getValue(), 16); if ((address < 0) || (address >= 0x10000)) { System.out.println(Application.getString(this, "error.invalidAddress")); error(); } Parameters.cpu.setPC(address); break; case "b": log.finer("Processing -b"); File file = new File(option.getValue(0)); address = Integer.parseInt(option.getValue(1), 16); if ((address < 0) || (address >= 0x10000)) { System.out.println(Application.getString(this, "error.invalidAddress")); error(); } new Raw(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file, address); break; case "h": log.finer("Processing -h"); file = new File(option.getValue()); new IntelHEX(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file); break; case "x": log.finer("Processing -x"); file = new File(option.getValue()); new XML(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file); break; case "s": log.finer("Processing -s"); file = new File(option.getValue()); new Snapshot(hardware).read(file); break; case "w": log.finer("Processing -w"); file = new File(option.getValue()); new Snapshot(hardware).write(file); System.exit(0); break; case "S": log.finer("Processing -S"); Parameters.speedUp = Integer.parseInt(option.getValue()); if (Parameters.speedUp < 1) { System.out.println(Application.getString(this, "error.nonPositiveSpeedUp")); error(); } break; case "g": log.finer("Processing -g"); Parameters.openGL = true; break; case "G": log.finer("Processing -G"); Parameters.openGL = false; break; } } } catch (final Exception exception) { usage(); error(); } log.fine("New CommandLineProcessor creation completed"); }
From source file:cz.pecina.retro.pmi80.CommandLineProcessor.java
/** * Creates an instance of the command line procssor. * * @param hardware the hardware object to operate on *//*w w w.ja va 2s. c om*/ public CommandLineProcessor(final Hardware hardware) { log.fine("New CommandLineProcessor creation started"); this.hardware = hardware; // build options log.fine("Building options"); options.addOption( Option.builder("?").longOpt("help").desc(Application.getString(this, "option.help")).build()); options.addOption( Option.builder("V").longOpt("version").desc(Application.getString(this, "option.version")).build()); options.addOption(Option.builder("l").longOpt("language").hasArg().argName("CODE") .desc(Application.getString(this, "option.language")).build()); options.addOption(Option.builder("p").longOpt("pixel-size").hasArg().argName("SIZE") .desc(Application.getString(this, "option.pixelSize")).build()); options.addOption(Option.builder("a").longOpt("address").hasArg().argName("ADDR") .desc(Application.getString(this, "option.address")).build()); options.addOption(Option.builder("O").longOpt("start-rom").hasArg().argName("ADDR") .desc(Application.getString(this, "option.startRom")).build()); options.addOption(Option.builder("A").longOpt("start-ram").hasArg().argName("ADDR") .desc(Application.getString(this, "option.startRam")).build()); options.addOption(Option.builder("b").longOpt("binary").hasArgs().numberOfArgs(2).argName("FILE>,<ADDR") .valueSeparator(',').desc(Application.getString(this, "option.binary")).build()); options.addOption(Option.builder("h").longOpt("intel-hex").hasArg().argName("FILE") .desc(Application.getString(this, "option.intelHex")).build()); options.addOption(Option.builder("x").longOpt("xml").hasArg().argName("FILE") .desc(Application.getString(this, "option.xml")).build()); options.addOption(Option.builder("s").longOpt("snapshot").hasArg().argName("FILE") .desc(Application.getString(this, "option.snapshot")).build()); options.addOption(Option.builder("w").longOpt("write-snapshot").hasArg().argName("FILE") .desc(Application.getString(this, "option.writeSnapshot")).build()); options.addOption(Option.builder("S").longOpt("speed-up").hasArg().argName("FACTOR") .desc(Application.getString(this, "option.speedUp")).build()); options.addOption( Option.builder("g").longOpt("opengl").desc(Application.getString(this, "option.openGL")).build()); options.addOption(Option.builder("G").longOpt("no-opengl") .desc(Application.getString(this, "option.noOpenGL")).build()); log.finer("Options set up"); // parse the command line final CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, Parameters.arguments); } catch (final Exception exception) { usage(); error(); } log.finer("Command line parsed"); // load default snapshot if exists boolean success = false; for (String name : DEFAULT_SNAPSHOT_NAMES) { final File defaultSnapshot = new File(name); if (defaultSnapshot.canRead()) { try { new Snapshot(hardware).read(defaultSnapshot); } catch (final Exception exception) { log.fine("Error reading default snapshot"); System.out.println(Application.getString(this, "error.errorDefaultShapshot")); error(); } log.fine("Default snapshot read from the current directory"); success = true; break; } } if (!success) { for (String name : DEFAULT_SNAPSHOT_NAMES) { final File defaultSnapshot = new File(new File(System.getProperty("user.home")), name); if (defaultSnapshot.canRead()) { try { new Snapshot(hardware).read(defaultSnapshot); } catch (final RuntimeException exception) { log.fine("Error reading default snapshot"); System.out.println(Application.getString(this, "error.errorDefaultShapshot")); error(); } log.fine("Default snapshot read from the user's home directory"); break; } } } log.finer("Default files processed"); // process the options if (!line.getArgList().isEmpty()) { usage(); error(); } if (line.hasOption("?")) { log.finer("Processing -?"); usage(); System.exit(0); } if (line.hasOption("V")) { log.finer("Processing -V"); System.out.println(Application.getString(this, "longAppName") + " " + Application.getString(this, "version") + " @VERSION@"); System.exit(0); } try { for (Option option : line.getOptions()) { switch (option.getOpt()) { case "l": log.finer("Processing -l"); final String language = option.getValue(); if (!Arrays.asList(GeneralConstants.SUPPORTED_LOCALES).contains(language)) { System.out.println(Application.getString(this, "error.unsupportedLanguage")); error(); } UserPreferences.setLocale(language); break; case "p": log.finer("Processing -p"); final int pixelSize = Integer.parseInt(option.getValue()); if (!Arrays.asList(GeneralConstants.PIXEL_SIZES).contains(pixelSize)) { System.out.println(Application.getString(this, "error.unsupportedPixelSize")); error(); } UserPreferences.setPixelSize(pixelSize); break; case "a": log.finer("Processing -a"); int address = Integer.parseInt(option.getValue(), 16); if ((address < 0) || (address >= 0x10000)) { System.out.println(Application.getString(this, "error.invalidAddress")); error(); } Parameters.cpu.setPC(address); break; case "O": log.finer("Processing -O"); final int startROM = Integer.parseInt(option.getValue()); if ((startROM < 0) || (startROM > 64)) { System.out.println(Application.getString(this, "error.unsupportedMemoryStart")); error(); } UserPreferences.setStartROM(startROM); break; case "A": log.finer("Processing -A"); final int startRAM = Integer.parseInt(option.getValue()); if ((startRAM < 0) || (startRAM > 64)) { System.out.println(Application.getString(this, "error.unsupportedMemoryStart")); error(); } UserPreferences.setStartRAM(startRAM); break; case "b": log.finer("Processing -b"); File file = new File(option.getValue(0)); address = Integer.parseInt(option.getValue(1), 16); if ((address < 0) || (address >= 0x10000)) { System.out.println(Application.getString(this, "error.invalidAddress")); error(); } new Raw(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file, address); break; case "h": log.finer("Processing -h"); file = new File(option.getValue()); new IntelHEX(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file); break; case "x": log.finer("Processing -x"); file = new File(option.getValue()); new XML(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file); break; case "s": log.finer("Processing -s"); file = new File(option.getValue()); new Snapshot(hardware).read(file); break; case "w": log.finer("Processing -w"); file = new File(option.getValue()); new Snapshot(hardware).write(file); System.exit(0); break; case "S": log.finer("Processing -S"); Parameters.speedUp = Integer.parseInt(option.getValue()); if (Parameters.speedUp < 1) { System.out.println(Application.getString(this, "error.nonPositiveSpeedUp")); error(); } break; case "g": log.finer("Processing -g"); Parameters.openGL = true; break; case "G": log.finer("Processing -G"); Parameters.openGL = false; break; } } } catch (final Exception exception) { usage(); error(); } log.fine("New CommandLineProcessor creation completed"); }
From source file:de.rub.syssec.saaf.Main.java
private static void parseOptions(CommandLine cmdLine) { Config conf = Config.getInstance();//ww w .j a v a 2 s . c o m if (cmdLine.hasOption(props.getProperty("options.headless.short"))) { conf.setBooleanConfigValue(ConfigKeys.ANALYSIS_IS_HEADLESS, true); } if (cmdLine.hasOption(props.getProperty("options.color.long"))) { conf.setBooleanConfigValue(ConfigKeys.LOGGING_USE_COLOR, true); conf.setBooleanConfigValue(ConfigKeys.LOGGING_USE_INVERSE_COLOR, false); } if (cmdLine.hasOption(props.getProperty("options.colorinverse.short"))) { conf.setBooleanConfigValue(ConfigKeys.LOGGING_USE_COLOR, true); conf.setBooleanConfigValue(ConfigKeys.LOGGING_USE_INVERSE_COLOR, true); } updateLog4jConfiguration(conf.getBooleanConfigValue(ConfigKeys.LOGGING_USE_COLOR), conf.getBooleanConfigValue(ConfigKeys.LOGGING_USE_INVERSE_COLOR)); if (cmdLine.hasOption(props.getProperty("options.genjava.short"))) { conf.setBooleanConfigValue(ConfigKeys.ANALYSIS_GENERATE_JAVA, true); } if (cmdLine.hasOption(props.getProperty("options.drop.short"))) { conf.setBooleanConfigValue(ConfigKeys.ANALYSIS_DROP_DB_AND_FILES, true); } if (cmdLine.hasOption(props.getProperty("options.skip.short"))) { conf.setBooleanConfigValue(ConfigKeys.ANALYSIS_SKIP_KNOWN_APP, true); } if (cmdLine.hasOption(props.getProperty("options.hl.recursive.short"))) { conf.setBooleanConfigValue(ConfigKeys.RECURSIVE_DIR_ANALYSIS, true); } if (cmdLine.hasOption(props.getProperty("options.hl.filelist.short"))) { conf.setBooleanConfigValue(ConfigKeys.USE_FILE_LIST, true); } if (cmdLine.hasOption(props.getProperty("options.hl.singlethreaded.short"))) { conf.setBooleanConfigValue(ConfigKeys.MULTITHREADING_ENABLED, false); } if (cmdLine.hasOption(props.getProperty("options.nodb.short"))) { conf.setBooleanConfigValue(ConfigKeys.DATABASE_DISABLED, true); } // feature #35: run without database if (conf.getBooleanConfigValue(ConfigKeys.DATABASE_DISABLED)) { // disable database backend conf.setBooleanConfigValue(ConfigKeys.DATABASE_DISABLED, true); // if we are headless (i.e. no other way to see the results if (cmdLine.hasOption(props.getProperty("options.headless.short"))) { // automatically turn on reporting conf.setBooleanConfigValue(ConfigKeys.ANALYSIS_GENERATE_REPORT, true); } } if (cmdLine.hasOption(props.getProperty("options.gui.short")) && cmdLine.hasOption(props.getProperty("options.headless.short"))) { LOGGER.error("You have to decide if GUI or HEADLESS mode. Both is " + "not possible!"); exit(); } if (cmdLine.hasOption(props.getProperty("options.daemon.short"))) { conf.setBooleanConfigValue(ConfigKeys.ANALYSIS_IS_HEADLESS, true); conf.setBooleanConfigValue(ConfigKeys.DAEMON_ENABLED, true); String watched = cmdLine.getOptionValue(props.getProperty("options.daemon.short")); conf.setConfigValue(ConfigKeys.DAEMON_DIRECTORY, watched); } if (cmdLine.hasOption(props.getProperty("options.headless.short"))) { conf.setBooleanConfigValue(ConfigKeys.ANALYSIS_IS_HEADLESS, true); } if (cmdLine.getOptions().length <= 0 || cmdLine.hasOption(props.getProperty("options.gui.short"))) { conf.setBooleanConfigValue(ConfigKeys.ANALYSIS_IS_HEADLESS, false); } // What to analyze? if (cmdLine.hasOption(props.getProperty("options.noheuristic.short"))) { conf.setBooleanConfigValue(ConfigKeys.ANALYSIS_DO_HEURISTIC, false); } if (cmdLine.hasOption(props.getProperty("options.nobt.short"))) { conf.setBooleanConfigValue(ConfigKeys.ANALYSIS_DO_BACKTRACK, false); } // if (cmdLine.hasOption("no-sc")) // Config.DO_SIMILARITY = false; // if (cmdLine.hasOption("sc")) // Config.DO_SIMILARITY = true; // How to analyze? // if (cmdLine.hasOption("ignore-errors")) // Config.QUIT_ON_ERROR = false; // if (cmdLine.hasOption("skip-known-apps")) // Config.SKIP_KNOWN_APP = true; // if (cmdLine.hasOption("del-old-analyses")) // Config.HOLD_ONLY_ONE_ANA_PER_APP = true; if (cmdLine.hasOption(props.getProperty("options.report.short"))) { conf.setBooleanConfigValue(ConfigKeys.ANALYSIS_GENERATE_REPORT, true); String reportPath = cmdLine.getOptionValue(props.getProperty("options.report.short")); conf.setConfigValue(ConfigKeys.DIRECTORY_REPORTS, reportPath); } if (cmdLine.hasOption(props.getProperty("options.rtemplate.short"))) { String templateName = cmdLine.getOptionValue(props.getProperty("options.rtemplate.short")); conf.setConfigValue(ConfigKeys.REPORTING_TEMPLATE_GROUP_DEFAULT, templateName); } if (cmdLine.hasOption(props.getProperty("options.log.short"))) { conf.setBooleanConfigValue(ConfigKeys.LOGGING_CREATE_SEPERATE, true); String logpath = cmdLine.getOptionValue(props.getProperty("options.log.short")); conf.setConfigValue(ConfigKeys.LOGGING_FILE_PATH, logpath); } if (cmdLine.hasOption(props.getProperty("options.cfg.short"))) { conf.setBooleanConfigValue(ConfigKeys.ANALYSIS_GENERATE_CFG, true); } if (cmdLine.hasOption(props.getProperty("options.fuzzy.short"))) { conf.setBooleanConfigValue(ConfigKeys.ANALYSIS_GENERATE_FUZZYHASH, true); } if (cmdLine.hasOption(props.getProperty("options.keep.short"))) { conf.setBooleanConfigValue(ConfigKeys.ANALYSIS_KEEP_FILES, true); } }
From source file:lu.uni.adtool.tools.Clo.java
/** * Class used to parse command line options. Returns true if GUI window should * be shown/* w w w .j a va 2s.c om*/ */ public boolean parse(String[] args) { CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); if (cmd.hasOption("h")) { help(); return false; } else if (cmd.hasOption("v")) { version(); return false; } else if (cmd.hasOption("o")) { this.toOpen = cmd.getOptionValues("o"); if (this.toOpen != null && this.toOpen.length == 0) { this.toOpen = null; } } if (cmd.hasOption("i") && cmd.hasOption("x") || cmd.hasOption("i") && cmd.hasOption("d") && (cmd.getOptionValue("d", "0").equals("?") || cmd.getOptionValue("d", "0").equals("q"))) { ImportExport exporter = new ImportExport(); if (cmd.hasOption("D")) { exporter.setNoDerivedValues(true); } if (cmd.hasOption("m")) { exporter.setMarkEditable(true); } if (cmd.hasOption("r")) { String r = cmd.getOptionValue("r"); try { int x = Integer.parseInt(r); if (x > 0) { exporter.setExportRanking(x); } else { System.err.println(Options.getMsg("clo.wrongrank")); } } catch (NumberFormatException e) { System.err.println(Options.getMsg("clo.wrongrank")); } } if (cmd.hasOption("L")) { exporter.setNoLabels(true); } if (cmd.hasOption("C")) { exporter.setNoComputedValues(true); } if (cmd.hasOption("s")) { String size = cmd.getOptionValue("s"); int index = size.indexOf('x'); if (index > 0) { try { int x = Integer.parseInt(size.substring(0, index)); int y = Integer.parseInt(size.substring(index + 1)); exporter.setViewPortSize(new Dimension(x, y)); } catch (NumberFormatException e) { System.err.println(Options.getMsg("clo.wrongsize")); } } } if (cmd.hasOption("d")) { String[] domainIds = cmd.getOptionValues("d"); if (domainIds != null) { // if (domainId == "?" || domainId=="q") { // System.out.println(new Integer(exporter.countDomains(fileName))); // return false; // } exporter.setExportDomainStr(domainIds); } } String fileName = cmd.getOptionValue("i"); if (fileName != null && exporter.doImport(fileName)) { fileName = cmd.getOptionValue("x"); if (fileName != null) { exporter.doExport(fileName); } } return toOpen != null; } if (cmd.getOptions().length > 0) { System.err.println(Options.getMsg("clo.wrongCombination") + "."); help(); return false; } } catch (ParseException e) { System.err.println(Options.getMsg("clo.parseError") + ": " + e.toString()); help(); return false; } return true; }
From source file:com.tito.easyyarn.appmaster.ApplicationMaster.java
/** * Parse command line options// www . ja v a 2s .c o m * * @param args * Command line args * @return Whether init successful and run should be invoked * @throws ParseException * @throws IOException */ public boolean initAll(CommandLine cliParser) throws ParseException, IOException { if (cliParser.hasOption("help")) { printUsage(getOptions()); return false; } if (cliParser.hasOption("debug")) { dumpOutDebugInfo(); } if (!cliParser.hasOption("jar")) { throw new IllegalArgumentException("Missing Jar file for workers"); } this.jarPath = cliParser.getOptionValue("jar"); Map<String, String> envs = System.getenv(); if (!envs.containsKey(Environment.CONTAINER_ID.name())) { if (cliParser.hasOption("app_attempt_id")) { String appIdStr = cliParser.getOptionValue("app_attempt_id", ""); appAttemptID = ConverterUtils.toApplicationAttemptId(appIdStr); } else { throw new IllegalArgumentException("Application Attempt Id not set in the environment"); } } else { ContainerId containerId = ConverterUtils.toContainerId(envs.get(Environment.CONTAINER_ID.name())); appAttemptID = containerId.getApplicationAttemptId(); } if (!envs.containsKey(ApplicationConstants.APP_SUBMIT_TIME_ENV)) { throw new RuntimeException(ApplicationConstants.APP_SUBMIT_TIME_ENV + " not set in the environment"); } if (!envs.containsKey(Environment.NM_HOST.name())) { throw new RuntimeException(Environment.NM_HOST.name() + " not set in the environment"); } if (!envs.containsKey(Environment.NM_HTTP_PORT.name())) { throw new RuntimeException(Environment.NM_HTTP_PORT + " not set in the environment"); } if (!envs.containsKey(Environment.NM_PORT.name())) { throw new RuntimeException(Environment.NM_PORT.name() + " not set in the environment"); } if (envs.containsKey(YarnConstants.APP_JAR)) { jarPath = envs.get(YarnConstants.APP_JAR); if (envs.containsKey(YarnConstants.APP_JAR_TIMESTAMP)) { appJarTimestamp = Long.valueOf(envs.get(YarnConstants.APP_JAR_TIMESTAMP)); } if (envs.containsKey(YarnConstants.APP_JAR_LENGTH)) { appJarPathLen = Long.valueOf(envs.get(YarnConstants.APP_JAR_LENGTH)); } if (!jarPath.isEmpty() && (appJarTimestamp <= 0 || appJarPathLen <= 0)) { LOG.error("Illegal values in env for jar path" + ", path=" + jarPath + ", len=" + appJarPathLen + ", timestamp=" + appJarTimestamp); throw new IllegalArgumentException("Illegal values in env for jar path"); } } LOG.info("Application master for app" + ", appId=" + appAttemptID.getApplicationId().getId() + ", clustertimestamp=" + appAttemptID.getApplicationId().getClusterTimestamp() + ", attemptId=" + appAttemptID.getAttemptId()); timeLinePublisher = new TimeLinePublisher(conf); if (!init(cliParser)) { return false; } // save passed arguments for (Option op : cliParser.getOptions()) { passedArguments.put(op.getOpt(), cliParser.getOptionValue(op.getOpt())); } return true; }