List of usage examples for org.apache.commons.cli BasicParser BasicParser
BasicParser
From source file:com.knewton.mapreduce.example.SSTableMRExample.java
public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException, URISyntaxException, ParseException { long startTime = System.currentTimeMillis(); Options options = buildOptions();/*from w w w . j a v a2 s. com*/ CommandLineParser cliParser = new BasicParser(); CommandLine cli = cliParser.parse(options, args); if (cli.getArgs().length < 2 || cli.hasOption('h')) { printUsage(options); } Job job = getJobConf(cli); job.setJarByClass(SSTableMRExample.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(StudentEventWritable.class); job.setMapperClass(StudentEventMapper.class); job.setReducerClass(StudentEventReducer.class); job.setInputFormatClass(SSTableColumnInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); // input arg String inputPaths = cli.getArgs()[0]; LOG.info("Setting initial input paths to {}", inputPaths); SSTableInputFormat.addInputPaths(job, inputPaths); // output arg FileOutputFormat.setOutputPath(job, new Path(cli.getArgs()[1])); if (cli.hasOption('c')) { LOG.info("Using compression for output."); FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class); FileOutputFormat.setCompressOutput(job, true); } job.waitForCompletion(true); LOG.info("Total runtime: {}s", (System.currentTimeMillis() - startTime) / 1000); }
From source file:edu.usc.pgroup.floe.client.commands.Scale.java
/** * Entry point for Scale command./*from w ww.j a v a 2 s .c o m*/ * @param args command line arguments sent by the floe.py script. */ public static void main(final String[] args) { Options options = new Options(); Option dirOption = OptionBuilder.withArgName("direction").hasArg().isRequired() .withDescription("Scale Direction.").create("dir"); Option appOption = OptionBuilder.withArgName("name").hasArg().isRequired() .withDescription("Application Name").create("app"); Option pelletNameOption = OptionBuilder.withArgName("name").hasArg().isRequired() .withDescription("Pellet Name").create("pellet"); Option cntOption = OptionBuilder.withArgName("num").hasArg().withType(new String()) .withDescription("Number of instances to scale up/down").create("cnt"); options.addOption(dirOption); options.addOption(appOption); options.addOption(pelletNameOption); options.addOption(cntOption); CommandLineParser parser = new BasicParser(); CommandLine line; try { line = parser.parse(options, args); } catch (ParseException e) { LOGGER.error("Invalid command: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("scale options", options); return; } String dir = line.getOptionValue("dir"); String app = line.getOptionValue("app"); String pellet = line.getOptionValue("pellet"); String cnt = line.getOptionValue("cnt"); LOGGER.info("direction: {}", dir); LOGGER.info("Application: {}", app); LOGGER.info("Pellet: {}", pellet); LOGGER.info("count: {}", cnt); ScaleDirection direction = Enum.valueOf(ScaleDirection.class, dir); int count = Integer.parseInt(cnt); try { FloeClient.getInstance().getClient().scale(direction, app, pellet, count); } catch (TException e) { LOGGER.error("Error while connecting to the coordinator: {}", e); } }
From source file:com.cloudera.impala.testutil.SentryServicePinger.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { // Parse command line options to get config file path. Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("config_file") .withDescription("Absolute path to a sentry-site.xml config file (string)").hasArg() .withArgName("CONFIG_FILE").isRequired().create('c')); options.addOption(OptionBuilder.withLongOpt("num_pings") .withDescription("Max number of pings to try before failing (int)").hasArg().isRequired() .withArgName("NUM_PINGS").create('n')); options.addOption(//w ww. j a va2 s.c o m OptionBuilder.withLongOpt("sleep_secs").withDescription("Time (s) to sleep between pings (int)") .hasArg().withArgName("SLEEP_SECS").create('s')); BasicParser optionParser = new BasicParser(); CommandLine cmdArgs = optionParser.parse(options, args); SentryConfig sentryConfig = new SentryConfig(cmdArgs.getOptionValue("config_file")); int numPings = Integer.parseInt(cmdArgs.getOptionValue("num_pings")); int maxPings = numPings; int sleepSecs = Integer.parseInt(cmdArgs.getOptionValue("sleep_secs")); sentryConfig.loadConfig(); while (numPings > 0) { SentryPolicyService policyService = new SentryPolicyService(sentryConfig); try { policyService.listAllRoles(new User(System.getProperty("user.name"))); LOG.info("Sentry Service ping succeeded."); System.exit(0); } catch (Exception e) { LOG.error(String.format("Error issing RPC to Sentry Service (attempt %d/%d): ", maxPings - numPings + 1, maxPings), e); Thread.sleep(sleepSecs * 1000); } --numPings; } System.exit(1); }
From source file:fr.romainf.QRCode.java
public static void main(String[] args) { Options options = buildOptions();//from w ww .ja v a2 s . c o m CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); args = cmd.getArgs(); int l = args.length; if (l != 1) { System.out.println("Can only encode one datum at a time (" + l + " given)"); printUsage(options); System.exit(1); } if (cmd.hasOption("help")) { printUsage(options); System.exit(0); } String output = cmd.getOptionValue("o", DEFAULT_OUTPUT_FILE); String pixelColourText = cmd.getOptionValue("c", DEFAULT_PIXEL_COLOUR); if (pixelColourText.startsWith("0x")) { pixelColourText = pixelColourText.substring(2); } Color pixelColour; if (pixelColourText.length() == 6) { pixelColour = new Color(Integer.parseInt(pixelColourText, 16)); } else { pixelColour = new Color((int) Long.parseLong(pixelColourText, 16), true); } writeQRCode(args[l - 1], output, pixelColour); } catch (ParseException e) { System.out.println(e.getMessage()); printUsage(options); System.exit(1); } catch (WriterException e) { System.out.println("Could not create QRCode from data (" + e.getMessage() + ")"); System.exit(2); } catch (IOException e) { System.out.println("Could not save QRCode to file (" + e.getMessage() + ")"); System.exit(4); } System.exit(0); }
From source file:net.oneandone.shared.artifactory.App.java
public static void main(String[] args) throws ParseException, IOException, NotFoundException { initLogging();// w ww .j av a2 s . c om LOG.info("CLI: {}", Arrays.toString(args)); final Options options = new Options() .addOption("l", "uri", true, "Base-URI in the form of " + DEFAULT_ARTIFACTORY_URI) .addOption("u", "user", true, "Username").addOption("p", "password", true, "Password") .addOption("d", "debug", false, "Turn on debugging"); final CommandLine commandline = new BasicParser().parse(options, args); if (commandline.hasOption("d")) { LOG.info("Setting debug"); java.util.logging.Logger.getLogger("net.oneandone.shared.artifactory").setLevel(Level.ALL); } final List<String> argList = commandline.getArgList(); LOG.info("ARGS: {}", argList); Injector injector = Guice.createInjector(new ArtifactoryModule()); App instance = injector.getInstance(App.class); instance.preemptiveRequestInterceptor.addCredentialsForHost("web.de", "foo", "bar"); List<ArtifactoryStorage> search = instance.searchByGav.search("repo1-cache", Gav.valueOf(argList.get(0))); LOG.info("Got {} search results", search.size()); }
From source file:co.cask.cdap.data.tools.CoprocessorBuildTool.java
public static void main(final String[] args) throws ParseException { Options options = new Options().addOption(new Option("h", "help", false, "Print this usage message.")) .addOption(new Option("f", "force", false, "Overwrites any coprocessors that already exist.")); CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); String[] commandArgs = commandLine.getArgs(); // if help is an option, or if there isn't a single 'ensure' command, print usage and exit. if (commandLine.hasOption("h") || commandArgs.length != 1 || !"check".equalsIgnoreCase(commandArgs[0])) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp(CoprocessorBuildTool.class.getName() + " check", "Checks that HBase coprocessors required by CDAP are loaded onto HDFS. " + "If not, the coprocessors are built and placed on HDFS.", options, ""); System.exit(0);/*from w ww . j a v a2s.co m*/ } boolean overwrite = commandLine.hasOption("f"); CConfiguration cConf = CConfiguration.create(); Configuration hConf = HBaseConfiguration.create(); Injector injector = Guice.createInjector(new ConfigModule(cConf, hConf), // for LocationFactory new PrivateModule() { @Override protected void configure() { bind(FileContext.class).toProvider(FileContextProvider.class).in(Scopes.SINGLETON); expose(LocationFactory.class); } @Provides @Singleton private LocationFactory providesLocationFactory(Configuration hConf, CConfiguration cConf, FileContext fc) { final String namespace = cConf.get(Constants.CFG_HDFS_NAMESPACE); return new FileContextLocationFactory(hConf, fc, namespace); } }); try { SecurityUtil.loginForMasterService(cConf); } catch (Exception e) { LOG.error("Failed to login as CDAP user", e); System.exit(1); } LocationFactory locationFactory = injector.getInstance(LocationFactory.class); HBaseTableUtil tableUtil = new HBaseTableUtilFactory(cConf).get(); CoprocessorManager coprocessorManager = new CoprocessorManager(cConf, locationFactory, tableUtil); try { Location location = coprocessorManager.ensureCoprocessorExists(overwrite); LOG.info("coprocessor exists at {}.", location); } catch (IOException e) { LOG.error("Unable to build and upload coprocessor jars.", e); System.exit(1); } }
From source file:demo.learn.shiro.tool.PasswordMatcherTool.java
/** * Main method.// w w w . j a v a 2 s . co m * @param args Pass in plain text password, hashed password, * and salt. These arguments are generated from * {@link PasswordEncryptionTool}. * @throws ParseException */ @SuppressWarnings("static-access") public static void main(String[] args) throws ParseException { String username = ""; String plainTextPassword = "root"; String hashedPasswordBase64 = "ZzIkhapTVzGkhWRQqdUn2zod5npt9RJMSni8My6X+r8="; String saltBase64 = "BobnkcsIXcZGksA30eOySA=="; String realmName = ""; Option p = OptionBuilder.withArgName("password").hasArg().withDescription("plain text password") .isRequired(false).create('p'); Option h = OptionBuilder.withArgName("password").hasArg().withDescription("hashed password") .isRequired(false).create('h'); Option s = OptionBuilder.withArgName("salt").hasArg().withDescription("salt (Base64 encoded)") .isRequired(false).create('s'); Options options = new Options(); options.addOption(p); options.addOption(h); options.addOption(s); try { CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("p")) { plainTextPassword = cmd.getOptionValue("p"); } if (cmd.hasOption("h")) { hashedPasswordBase64 = cmd.getOptionValue("h"); } if (cmd.hasOption("s")) { saltBase64 = cmd.getOptionValue("s"); } } catch (ParseException pe) { String cmdLineSyntax = "java -cp %CLASSPATH% demo.learn.shiro.tool.PasswordMatcherTool"; HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options, false); return; } SimpleByteSource salt = new SimpleByteSource(Base64.decode(saltBase64)); SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, hashedPasswordBase64, salt, realmName); UsernamePasswordToken token = new UsernamePasswordToken(username, plainTextPassword); HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(); matcher.setHashIterations(S.HASH_ITER); matcher.setStoredCredentialsHexEncoded(false); matcher.setHashAlgorithmName(S.ALGORITHM_NAME); boolean result = matcher.doCredentialsMatch(token, info); System.out.println("match? " + result); }
From source file:fr.inria.edelweiss.kgdqp.core.FedQueryingCLI.java
@SuppressWarnings("unchecked") public static void main(String args[]) throws ParseException, EngineException { List<String> endpoints = new ArrayList<String>(); String queryPath = null;/*from w w w. j av a2 s .co m*/ int slice = -1; Options options = new Options(); Option helpOpt = new Option("h", "help", false, "print this message"); Option queryOpt = new Option("q", "query", true, "specify the sparql query file"); Option endpointOpt = new Option("e", "endpoints", true, "the list of federated sparql endpoint URLs"); Option groupingOpt = new Option("g", "grouping", true, "triple pattern optimisation"); Option slicingOpt = new Option("s", "slicing", true, "size of the slicing parameter"); Option versionOpt = new Option("v", "version", false, "print the version information and exit"); options.addOption(queryOpt); options.addOption(endpointOpt); options.addOption(helpOpt); options.addOption(versionOpt); options.addOption(groupingOpt); options.addOption(slicingOpt); String header = "Corese/KGRAM DQP command line interface"; String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr"; CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("kgdqp", header, options, footer, true); System.exit(0); } if (!cmd.hasOption("e")) { logger.info("You must specify at least the URL of one sparql endpoint !"); System.exit(0); } else { endpoints = new ArrayList<String>(Arrays.asList(cmd.getOptionValues("e"))); } if (!cmd.hasOption("q")) { logger.info("You must specify a path for a sparql query !"); System.exit(0); } else { queryPath = cmd.getOptionValue("q"); } if (cmd.hasOption("s")) { try { slice = Integer.parseInt(cmd.getOptionValue("s")); } catch (NumberFormatException ex) { logger.warn(cmd.getOptionValue("s") + " is not formatted as number for the slicing parameter"); logger.warn("Slicing disabled"); } } if (cmd.hasOption("v")) { logger.info("version 3.0.4-SNAPSHOT"); System.exit(0); } ///////////////// Graph graph = Graph.create(); QueryProcessDQP exec = QueryProcessDQP.create(graph); exec.setGroupingEnabled(cmd.hasOption("g")); if (slice > 0) { exec.setSlice(slice); } Provider sProv = ProviderImplCostMonitoring.create(); exec.set(sProv); for (String url : endpoints) { try { exec.addRemote(new URL(url), WSImplem.REST); } catch (MalformedURLException ex) { logger.error(url + " is not a well-formed URL"); System.exit(1); } } StringBuffer fileData = new StringBuffer(1000); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(queryPath)); } catch (FileNotFoundException ex) { logger.error("Query file " + queryPath + " not found !"); System.exit(1); } char[] buf = new char[1024]; int numRead = 0; try { while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } reader.close(); } catch (IOException ex) { logger.error("Error while reading query file " + queryPath); System.exit(1); } String sparqlQuery = fileData.toString(); // Query q = exec.compile(sparqlQuery, null); // System.out.println(q); StopWatch sw = new StopWatch(); sw.start(); Mappings map = exec.query(sparqlQuery); int dqpSize = map.size(); System.out.println("--------"); long time = sw.getTime(); System.out.println(time + " " + dqpSize); }
From source file:HBBRequestor.java
public static void main(String[] args) throws Exception { String hostId = ""; String partnerId = ""; String userId = ""; CommandLineParser parser = new BasicParser(); Options options = new Options(); options.addOption("h", "host", true, "EBICS Host ID"); options.addOption("p", "partner", true, "Registred Partner ID for you user"); options.addOption("u", "user", true, "User ID to initiate"); // Parse the program arguments CommandLine commandLine = parser.parse(options, args); if (!commandLine.hasOption('h')) { System.out.println("Host-ID is mandatory"); System.exit(0);// w ww. j a va2 s. com } else { hostId = commandLine.getOptionValue('h'); System.out.println("host: " + hostId); } if (!commandLine.hasOption('p')) { System.out.println("Partner-ID is mandatory"); System.exit(0); } else { partnerId = commandLine.getOptionValue('p'); System.out.println("partnerId: " + partnerId); } if (!commandLine.hasOption('u')) { System.out.println("User-ID is mandatory"); System.exit(0); } else { userId = commandLine.getOptionValue('u'); System.out.println("userId: " + userId); } HBBRequestor hbbRequestor; PasswordCallback pwdHandler; Product product; hbbRequestor = new HBBRequestor(); product = new Product("kopiLeft Dev 1.0", Locale.FRANCE, null); pwdHandler = new UserPasswordHandler(userId, "2012"); // Load alredy created user hbbRequestor.loadUser(hostId, partnerId, userId, pwdHandler); // Send hbb Requets hbbRequestor.sendHPBRequest(userId, product); // Perform save for the changed data hbbRequestor.quit(); }
From source file:com.hortonworks.registries.storage.tool.shell.ShellMigrationInitializer.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(Option.builder("s").numberOfArgs(1).longOpt(OPTION_SCRIPT_ROOT_PATH) .desc("Root directory of script path").build()); options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH) .desc("Config file path").build()); options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.MIGRATE.toString()) .desc("Execute schema migration from last check point").build()); options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.INFO.toString()) .desc("Show the status of the schema migration compared to the target database").build()); options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.VALIDATE.toString()) .desc("Validate the target database changes with the migration scripts").build()); options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.REPAIR.toString()).desc( "Repairs the SCRIPT_CHANGE_LOG by removing failed migrations and correcting checksum of existing migration script") .build());//w ww . ja va2 s. co m CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); if (!commandLine.hasOption(OPTION_SCRIPT_ROOT_PATH)) { usage(options); System.exit(1); } boolean isShellMigrationOptionSpecified = false; ShellMigrationOption shellMigrationOptionSpecified = null; for (ShellMigrationOption shellMigrationOption : ShellMigrationOption.values()) { if (commandLine.hasOption(shellMigrationOption.toString())) { if (isShellMigrationOptionSpecified) { System.out.println( "Only one operation can be execute at once, please select one of ',migrate', 'validate', 'info', 'repair'."); System.exit(1); } isShellMigrationOptionSpecified = true; shellMigrationOptionSpecified = shellMigrationOption; } } if (!isShellMigrationOptionSpecified) { System.out.println( "One of the option 'migrate', 'validate', 'info', 'repair' must be specified to execute."); System.exit(1); } String scriptRootPath = commandLine.getOptionValue(OPTION_SCRIPT_ROOT_PATH); String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH); StorageProviderConfiguration storageProperties; try { Map<String, Object> conf = Utils.readConfig(confFilePath); StorageProviderConfigurationReader confReader = new StorageProviderConfigurationReader(); storageProperties = confReader.readStorageConfig(conf); } catch (IOException e) { System.err.println("Error occurred while reading config file: " + confFilePath); System.exit(1); throw new IllegalStateException("Shouldn't reach here"); } ShellMigrationHelper schemaMigrationHelper = new ShellMigrationHelper( ShellFlywayFactory.get(storageProperties, scriptRootPath)); try { schemaMigrationHelper.execute(shellMigrationOptionSpecified); System.out.println(String.format("\"%s\" option successful", shellMigrationOptionSpecified.toString())); } catch (Exception e) { System.err.println(String.format("\"%s\" option failed : %s", shellMigrationOptionSpecified.toString(), e.getMessage())); System.exit(1); } }