List of usage examples for org.apache.commons.cli CommandLine hasOption
public boolean hasOption(char opt)
From source file:de.ncoder.studipsync.Starter.java
public static void main(String[] args) throws Exception { boolean displayHelp = false; CommandLineParser parser = new DefaultParser(); try {//from w w w.j av a2 s . c o m CommandLine cmd = parser.parse(OPTIONS, args); if (cmd.hasOption(OPTION_HELP)) { displayHelp = true; return; } Syncer syncer = createSyncer(cmd); StorageLog storeLog = new StorageLog(); syncer.getStorage().registerListener(storeLog); try { log.info("Started " + getImplementationTitle() + " " + getImplementationVersion()); syncer.sync(); log.info(storeLog.getStatusMessage(syncer.getStorage().getRoot())); log.info("Finished"); } finally { syncer.close(); } } catch (ParseException e) { System.out.println("Illegal arguments passed. " + e.getMessage()); displayHelp = true; } finally { if (displayHelp) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("studip-sync", OPTIONS); } } //TODO AWT Event Queue blocks termination with modality level 1 System.exit(0); }
From source file:com.benasmussen.tools.testeditor.ExtractorCLI.java
public static void main(String[] args) throws Exception { HelpFormatter formatter = new HelpFormatter(); // cli options Options options = new Options(); options.addOption(CMD_OPT_INPUT, true, "Input file"); // options.addOption(CMD_OPT_OUTPUT, true, "Output file"); try {/*from w w w . j a va 2 s. c o m*/ // evaluate command line options CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption(CMD_OPT_INPUT)) { // option value String optionValue = cmd.getOptionValue(CMD_OPT_INPUT); // input file File inputFile = new File(optionValue); // id extractor IdExtractor idExtractor = new IdExtractor(inputFile); Vector<Vector> data = idExtractor.parse(); // // TODO implement output folder // if (cmd.hasOption(CMD_OPT_OUTPUT)) // { // // file output // throw new Exception("Not implemented"); // } // else // { // console output System.out.println("Id;Value"); for (Vector vector : data) { StringBuilder sb = new StringBuilder(); if (vector.size() >= 1) { sb.append(vector.get(0)); } sb.append(";"); if (vector.size() >= 2) { sb.append(vector.get(1)); } System.out.println(sb.toString()); } // } } else { throw new IllegalArgumentException(); } } catch (ParseException e) { formatter.printHelp("ExtractorCLI", options); } catch (IllegalArgumentException e) { formatter.printHelp("ExtractorCLI", options); } }
From source file:com.github.jasmo.Bootstrap.java
public static void main(String[] args) { Options options = new Options().addOption("h", "help", false, "Print help message") .addOption("v", "verbose", false, "Increase verbosity") .addOption("c", "cfn", true, "Enable 'crazy fucking names and set name length (large names == large output size)'") .addOption("p", "package", true, "Move obfuscated classes to this package") .addOption("k", "keep", true, "Don't rename this class"); try {//from w w w . j a v a 2 s . co m CommandLineParser clp = new DefaultParser(); CommandLine cl = clp.parse(options, args); if (cl.hasOption("help")) { help(options); return; } if (cl.hasOption("verbose")) { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); loggerConfig.setLevel(Level.DEBUG); ctx.updateLoggers(); } String[] keep = cl.getOptionValues("keep"); if (cl.getArgList().size() < 2) { throw new ParseException("Expected at-least two arguments"); } log.debug("Input: {}, Output: {}", cl.getArgList().get(0), cl.getArgList().get(1)); Obfuscator o = new Obfuscator(); try { o.supply(Paths.get(cl.getArgList().get(0))); } catch (Exception e) { log.error("An error occurred while reading the source target", e); return; } try { UniqueStringGenerator usg; if (cl.hasOption("cfn")) { int size = Integer.parseInt(cl.getOptionValue("cfn")); usg = new UniqueStringGenerator.Crazy(size); } else { usg = new UniqueStringGenerator.Default(); } o.apply(new FullAccessFlags()); o.apply(new ScrambleStrings()); o.apply(new ScrambleClasses(usg, cl.getOptionValue("package", ""), keep == null ? new String[0] : keep)); o.apply(new ScrambleFields(usg)); o.apply(new ScrambleMethods(usg)); o.apply(new InlineAccessors()); o.apply(new RemoveDebugInfo()); o.apply(new ShuffleMembers()); } catch (Exception e) { log.error("An error occurred while applying transform", e); return; } try { o.write(Paths.get(cl.getArgList().get(1))); } catch (Exception e) { log.error("An error occurred while writing to the destination target", e); return; } } catch (ParseException e) { log.error("Failed to parse command line arguments", e); help(options); } }
From source file:com.trovit.hdfstree.HdfsTree.java
public static void main(String... args) { Options options = new Options(); options.addOption("l", false, "Use local filesystem."); options.addOption("p", true, "Path used as root for the tree."); options.addOption("s", false, "Display the size of the directory"); options.addOption("d", true, "Maximum depth of the tree (when displaying)"); CommandLineParser parser = new PosixParser(); TreeBuilder treeBuilder;/*from w w w . j a v a 2 s. c om*/ FSInspector fsInspector = null; String rootPath = null; Displayer displayer = new ConsoleDisplayer(); try { CommandLine cmd = parser.parse(options, args); // local or hdfs. if (cmd.hasOption("l")) { fsInspector = new LocalFSInspector(); } else { fsInspector = new HDFSInspector(); } // check that it has the root path. if (cmd.hasOption("p")) { rootPath = cmd.getOptionValue("p"); } else { throw new ParseException("Mandatory option (-p) is not specified."); } if (cmd.hasOption("d")) { displayer.setMaxDepth(Integer.parseInt(cmd.getOptionValue("d"))); } if (cmd.hasOption("s")) { displayer.setDisplaySize(); } } catch (ParseException e) { System.out.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("hdfstree", options); System.exit(1); } treeBuilder = new TreeBuilder(rootPath, fsInspector); TreeNode tree = treeBuilder.buildTree(); displayer.display(tree); }
From source file:de.meldanor.autothesis.Core.java
public static void main(String[] args) { try {/*ww w .ja v a2s. c o m*/ AutoThesisCommandOption options = AutoThesisCommandOption.getInstance(); CommandLine commandLine = new GnuParser().parse(options, args); // Missing commands if (!commandLine.hasOption(options.getUserCommand()) || !commandLine.hasOption(options.getTokenCommand()) || !commandLine.hasOption(options.getRepoCommand())) { new HelpFormatter().printHelp("autothesis", options); return; } String user = commandLine.getOptionValue(options.getUserCommand()); String repo = commandLine.getOptionValue(options.getRepoCommand()); String token = commandLine.getOptionValue(options.getTokenCommand()); logger.info("Hello World, this is AutoThesis!"); long intervalMinutes = Long.parseLong(commandLine.getOptionValue(options.getIntervalCommand(), "60")); logger.info("Check for update interval: " + intervalMinutes + " min"); final AutoThesis autoThesis = new AutoThesis(user, repo, token); Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> { try { autoThesis.execute(); } catch (Exception e) { throw new RuntimeException(e); } }, 0, intervalMinutes, TimeUnit.MINUTES); } catch (Exception e) { logger.throwing(Level.ERROR, e); } }
From source file:eu.interedition.collatex.tools.CollateX.java
public static void main(String... args) { try {/*from www.j a v a 2s . co m*/ final CommandLine commandLine = new GnuParser().parse(OPTIONS, args); if (commandLine.hasOption("h")) { help(); } else if (commandLine.hasOption("S")) { CollationServer.start(commandLine); } else { CollationPipe.start(commandLine); } } catch (ParseException e) { error("Error while parsing command line arguments (-h for usage instructions)", e); } catch (IllegalArgumentException e) { error("Illegal argument", e); } catch (IOException e) { error("I/O error", e); } catch (SAXException e) { error("XML error", e); } catch (XPathExpressionException e) { error("XPath error", e); } catch (ScriptException | PluginScript.PluginScriptExecutionException e) { error("Script error", e); } catch (Throwable t) { error("Unexpected error", t); t.printStackTrace(ERROR_LOG); } finally { ERROR_LOG.flush(); } }
From source file:cloudnet.examples.evaluations.ConfigurableEvaluation.java
/** * @param args the command line arguments *//*from w w w .ja va 2 s.c o m*/ public static void main(String[] args) { Options options = makeOptions(); CommandLineParser parser = new DefaultParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("vmPlacementSimApp", options); return; } // apply options applyOptions(cmd); // run simulation runSimulation(); } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); } // exit in order to stop R-Environment if it is used. System.exit(0); }
From source file:demo.learn.shiro.tool.PasswordMatcherTool.java
/** * Main method./* w ww. j a va 2 s .com*/ * @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:com.boulmier.machinelearning.jobexecutor.JobExecutor.java
public static void main(String[] args) throws ParseException, IOException, InterruptedException { Options options = defineOptions();/* w w w .j a v a 2 s . co m*/ sysMon = new JavaSysMon(); InetAddress vmscheduler_ip, mongodb_ip = null; Integer vmscheduler_port = null, mongodb_port = null; CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGPORTFIELD)) { vmscheduler_port = Integer.valueOf(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGPORTFIELD)); } mongodb_port = (int) (cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGMONGOPORTFIELD) ? cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGMONGOPORTFIELD) : JobExecutorConfig.OPTIONS.LOGGING.MONGO_DEFAULT_PORT); mongodb_ip = InetAddress.getByName(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGMONGOIPFIELD)); vmscheduler_ip = InetAddress.getByName(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGIPFIELD)); decryptKey = cmd.getOptionValue("decrypt-key"); debugState = cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGDEBUGFIELD); logger = LoggerFactory.getLogger(); logger.info("Attempt to connect on master @" + vmscheduler_ip + ":" + vmscheduler_port); new RequestConsumer().start(); } catch (MissingOptionException moe) { logger.error(moe.getMissingOptions() + " are missing"); HelpFormatter help = new HelpFormatter(); help.printHelp(JobExecutor.class.getSimpleName(), options); } catch (UnknownHostException ex) { logger.error(ex.getMessage()); } finally { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { logger.info("JobExeutor is shutting down"); } }); } }
From source file:dk.statsbiblioteket.jpar2.filecompare.FileCompare.java
/** * Main method. //from w w w. ja v a2 s.c om * @param args */ public static void main(String[] args) { Options options = new Options(); options.addOption("s", "slices", true, "The number of slices to use in the comparison"); CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); args = cmd.getArgs(); if (!cmd.hasOption("s") || args.length != 2) { System.exit(2); } int slices = Integer.parseInt(cmd.getOptionValue("s").trim()); File f1 = new File(args[0]); File f2 = new File(args[1]); if (f1.length() == f2.length()) { int sliceSize = (int) (f1.length() / slices);//rounding here... DataFile df1 = new DataFile(f1, sliceSize); DataFile df2 = new DataFile(f2, sliceSize); List<Integer> defectIndexes = df1.compareWithIndex(df2); for (int index : defectIndexes) { System.out.println("index " + index + ", from " + index * sliceSize + " to " + (index + 1) * sliceSize + " is defect"); } if (defectIndexes.size() == 0) { System.out.println("Files are identical"); } } else { System.out.println("Files differ in length, cannot help you"); } } catch (ParseException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } }