OptionParser { public void parse(String[] args) throws ParseException, FileNotFoundException, ClassNotFoundException, OdpsException { CommandLineParser parser = new BasicParser(); if (args == null || args.length <= 0) { throw new UnsupportedOperationException("Main class not specified."); } CommandLine cmd = parser.parse(options, args, true); OdpsConf odpsConf = new OdpsConf(); if (cmd.hasOption("odps")) { String odpsconf = cmd.getOptionValue("odps"); File conf = new File(odpsconf); InputStream in = new FileInputStream(conf); odpsConf.addResource(in); } if (cmd.hasOption("odpsconf")) { String[] odpsconf = cmd.getOptionValues("odpsconf"); for (String conf : odpsconf) { String[] kv = conf.split("=", 2); odpsConf.set(kv[0], kv[1]); } } Account account = getAccount(odpsConf); Odps odps = new Odps(account); odps.setDefaultProject(odpsConf.getProjName()); if (odpsConf.getEndpoint() != null) { odps.setEndpoint(odpsConf.getEndpoint()); } ss.setOdps(odps); if (cmd.hasOption("job")) { String jobconf = cmd.getOptionValue("job"); File conf = new File(jobconf); InputStream in = new FileInputStream(conf); ss.getDefaultJob().addResource(in); } if (cmd.hasOption("jobconf")) { String[] jobconfs = cmd.getOptionValues("jobconf"); for (String conf : jobconfs) { String[] kv = conf.split("=", 2); ss.getDefaultJob().set(kv[0], kv[1]); } } if (cmd.hasOption("aliases")) { String aliases = cmd.getOptionValue("aliases"); Map<String, String> map; try { map = new GsonBuilder().disableHtmlEscaping().create() .fromJson(aliases, new TypeToken<Map<String, String>>() {}.getType()); } catch (Exception e) { throw new RuntimeException(e); } ss.setAliases(map); } if (cmd.hasOption("resources")) { String resources = cmd.getOptionValue("resources"); ss.getDefaultJob().setResources(resources); } if (cmd.hasOption("local")) { ss.setLocalRun(true); } String[] remain = cmd.getArgs(); if (remain == null || remain.length <= 0) { throw new UnsupportedOperationException("Main class not specified."); } mainClass = Class.forName(remain[0]); if (remain.length > 1) { arguments = Arrays.copyOfRange(remain, 1, remain.length); } else { arguments = new String[0]; } } OptionParser(SessionState ss); void parse(String[] args); void usage(); Class<?> getMainClass(); String[] getArguments();  }
@Test public void testParse() throws Exception { SessionState ss = SessionState.get(); OptionParser parser = new OptionParser(ss); parser .parse(new String[]{"-resources", "jar1.jar,jar2.jar", "-odpsconf", "odps.access.id=accessId", "-odpsconf", "odps.access.key=accessKey", "-odpsconf", "odps.account.provider=ALIYUN", "com.aliyun.odps.mapred.example.WordCount", "tin", "tout"}); assertArrayEquals(new String[]{"jar1.jar", "jar2.jar"}, ss.getDefaultJob().getResources()); assertEquals("com.aliyun.odps.mapred.example.WordCount", parser.getMainClass().getName()); assertArrayEquals(new String[]{"tin", "tout"}, parser.getArguments()); }