List of usage examples for org.apache.commons.cli DefaultParser DefaultParser
DefaultParser
From source file:com.ibm.crail.namenode.NameNode.java
public static void main(String args[]) throws Exception { LOG.info("initalizing namenode "); CrailConfiguration conf = new CrailConfiguration(); CrailConstants.updateConstants(conf); URI uri = CrailUtils.getPrimaryNameNode(); String address = uri.getHost(); int port = uri.getPort(); if (args != null) { Option addressOption = Option.builder("a").desc("ip address namenode is started on").hasArg().build(); Option portOption = Option.builder("p").desc("port namenode is started on").hasArg().build(); Options options = new Options(); options.addOption(portOption);/*from w w w . j a v a 2 s . c om*/ options.addOption(addressOption); CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, args.length)); if (line.hasOption(addressOption.getOpt())) { address = line.getOptionValue(addressOption.getOpt()); } if (line.hasOption(portOption.getOpt())) { port = Integer.parseInt(line.getOptionValue(portOption.getOpt())); } } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Namenode", options); System.exit(-1); } } String namenode = "crail://" + address + ":" + port; long serviceId = CrailUtils.getServiceId(namenode); long serviceSize = CrailUtils.getServiceSize(); if (!CrailUtils.verifyNamenode(namenode)) { throw new Exception("Namenode address/port [" + namenode + "] has to be listed in crail.namenode.address " + CrailConstants.NAMENODE_ADDRESS); } CrailConstants.NAMENODE_ADDRESS = namenode + "?id=" + serviceId + "&size=" + serviceSize; CrailConstants.printConf(); CrailConstants.verify(); RpcNameNodeService service = RpcNameNodeService.createInstance(CrailConstants.NAMENODE_RPC_SERVICE); RpcBinding rpcBinding = RpcBinding.createInstance(CrailConstants.NAMENODE_RPC_TYPE); rpcBinding.init(conf, null); rpcBinding.printConf(LOG); rpcBinding.run(service); System.exit(0); ; }
From source file:com.google.infrastructuredmap.MapAndMarkdownExtractorMain.java
public static void main(String[] args) throws IOException, ParseException { Options options = new Options(); options.addOption(ARG_KML, true, "path to KML input"); options.addOption(ARG_MARKDOWN, true, "path to Markdown input"); options.addOption(ARG_JSON_OUTPUT, true, "path to write json output"); options.addOption(ARG_JSONP, true, "JSONP template to wrap output JSON data"); CommandLineParser parser = new DefaultParser(); CommandLine cli = parser.parse(options, args); // Extract map features from the input KML. MapData data = null;//w w w . jav a 2 s . c om try (InputStream in = openStream(cli.getOptionValue(ARG_KML))) { Kml kml = Kml.unmarshal(in); data = MapDataExtractor.extractMapData(kml); } // Extract project features from the input Markdown. Map<String, List<ProjectReference>> references = MarkdownReferenceExtractor .extractReferences(Paths.get(cli.getOptionValue(ARG_MARKDOWN))); for (MapFeature feature : data.features) { List<ProjectReference> referencesForId = references.get(feature.id); if (referencesForId == null) { throw new IllegalStateException("Unknown project reference: " + feature.id); } feature.projects = referencesForId; } // Write the resulting data to the output path. Gson gson = new Gson(); try (FileWriter out = new FileWriter(cli.getOptionValue(ARG_JSON_OUTPUT))) { String json = gson.toJson(data); if (cli.hasOption(ARG_JSONP)) { json = String.format(cli.getOptionValue(ARG_JSONP), json); } out.write(json); } }
From source file:com.haulmont.mp2xls.MessagePropertiesProcessor.java
public static void main(String[] args) { Options options = new Options(); options.addOption(READ_OPT, "read", false, "read messages from project and save to XLS"); options.addOption(WRITE_OPT, "write", false, "load messages from XLS and write to project"); options.addOption(OVERWRITE_OPT, "overwrite", false, "overwrite existing messages by changed messages from XLS file"); options.addOption(PROJECT_DIR_OPT, "projectDir", true, "project root directory"); options.addOption(XLS_FILE_OPT, "xlsFile", true, "XLS file with translations"); options.addOption(LOG_FILE_OPT, "logFile", true, "log file"); options.addOption(LANGUAGES_OPT, "languages", true, "list of locales separated by comma, for example: 'de,fr'"); CommandLineParser parser = new DefaultParser(); CommandLine cmd;//from w w w .j a v a2 s. c o m try { cmd = parser.parse(options, args); if ((!cmd.hasOption(READ_OPT) && !cmd.hasOption(WRITE_OPT)) || !cmd.hasOption(PROJECT_DIR_OPT) || !cmd.hasOption(XLS_FILE_OPT) || !cmd.hasOption(LANGUAGES_OPT)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Messages To/From XLS Convertor", options); System.exit(-1); } if (cmd.hasOption(READ_OPT) && cmd.hasOption(WRITE_OPT)) { System.out.println("Please provide either 'read' or 'write' option"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Messages To/From XLS Convertor", options); System.exit(-1); } Set<String> languages = getLanguages(cmd.getOptionValue(LANGUAGES_OPT)); if (cmd.hasOption(READ_OPT)) { LocalizationsBatch localizationsBatch = new LocalizationsBatch(cmd.getOptionValue(PROJECT_DIR_OPT)); localizationsBatch.setScanLocalizationIds(languages); LocalizationBatchExcelWriter.exportToXls(localizationsBatch, cmd.getOptionValue(XLS_FILE_OPT)); } else if (cmd.hasOption(WRITE_OPT)) { LocalizationsBatch sourceLocalization = new LocalizationsBatch(cmd.getOptionValue(PROJECT_DIR_OPT)); sourceLocalization.setScanLocalizationIds(languages); LocalizationsBatch fileLocalization = new LocalizationsBatch(cmd.getOptionValue(XLS_FILE_OPT), cmd.getOptionValue(PROJECT_DIR_OPT)); fileLocalization.setScanLocalizationIds(languages); LocalizationBatchFileWriter fileWriter = new LocalizationBatchFileWriter(sourceLocalization, fileLocalization); String logFile = StringUtils.isNotEmpty(cmd.getOptionValue(LOG_FILE_OPT)) ? cmd.getOptionValue(LOG_FILE_OPT) : "log.xls"; fileWriter.process(logFile, cmd.hasOption(OVERWRITE_OPT)); } } catch (Throwable e) { e.printStackTrace(); System.exit(-1); } }
From source file:com.booktrack.vader.Main.java
/** * main entry point and demo case for Vader * @param args the arguments - explained below in the code * @throws Exception anything goes wrong - except *///from w ww.java2 s .com public static void main(String[] args) throws Exception { // create Options object for command line parsing Options options = new Options(); options.addOption("file", true, "input text-file (-file) to read and analyse using Vader"); CommandLineParser cmdParser = new DefaultParser(); CommandLine line = null; try { // parse the command line arguments line = cmdParser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong logger.error("invalid command line: " + exp.getMessage()); System.exit(0); } // get the command line argument -file String inputFile = line.getOptionValue("file"); if (inputFile == null) { help(options); System.exit(0); } if (!new File(inputFile).exists()) { logger.error("file does not exist: " + inputFile); System.exit(0); } // example use of the classes // read the entire input file String fileText = new String(Files.readAllBytes(Paths.get(inputFile))); // setup Vader Vader vader = new Vader(); vader.init(); // load vader // setup nlp processor VaderNLP vaderNLP = new VaderNLP(); vaderNLP.init(); // load open-nlp // parse the text into a set of sentences List<List<Token>> sentenceList = vaderNLP.parse(fileText); // apply vader analysis to each sentence for (List<Token> sentence : sentenceList) { VScore vaderScore = vader.analyseSentence(sentence); logger.info("sentence:" + Token.tokenListToString(sentence)); logger.info("Vader score:" + vaderScore.toString()); } }
From source file:io.github.gsteckman.doorcontroller.INA219Util.java
/** * Reads the Current from the INA219 with an I2C address and for a duration specified on the command line. * /*from w w w .ja v a2 s .c o m*/ * @param args * Command line arguments. * @throws IOException * If an error occurs reading/writing to the INA219 * @throws ParseException * If the command line arguments could not be parsed. */ public static void main(String[] args) throws IOException, ParseException { Options options = new Options(); options.addOption("addr", true, "I2C Address"); options.addOption("d", true, "Acquisition duration, in seconds"); options.addOption("bv", false, "Also read bus voltage"); options.addOption("sv", false, "Also read shunt voltage"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); Address addr = Address.ADDR_40; if (cmd.hasOption("addr")) { int opt = Integer.parseInt(cmd.getOptionValue("addr"), 16); Address a = Address.getAddress(opt); if (a != null) { addr = a; } else { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("INA219Util", options); return; } } int duration = 0; if (cmd.hasOption("d")) { String opt = cmd.getOptionValue("d"); duration = Integer.parseInt(opt); } else { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("INA219Util", options); return; } boolean readBusVoltage = false; if (cmd.hasOption("bv")) { readBusVoltage = true; } boolean readShuntVoltage = false; if (cmd.hasOption("sv")) { readShuntVoltage = true; } INA219 i219 = new INA219(addr, 0.1, 3.2, INA219.Brng.V16, INA219.Pga.GAIN_8, INA219.Adc.BITS_12, INA219.Adc.SAMPLES_128); System.out.printf("Time\tCurrent"); if (readBusVoltage) { System.out.printf("\tBus"); } if (readShuntVoltage) { System.out.printf("\tShunt"); } System.out.printf("\n"); long start = System.currentTimeMillis(); do { try { System.out.printf("%d\t%f", System.currentTimeMillis() - start, i219.getCurrent()); if (readBusVoltage) { System.out.printf("\t%f", i219.getBusVoltage()); } if (readShuntVoltage) { System.out.printf("\t%f", i219.getShuntVoltage()); } System.out.printf("\n"); Thread.sleep(100); } catch (IOException e) { LOG.error("Exception while reading I2C bus", e); } catch (InterruptedException e) { break; } } while (System.currentTimeMillis() - start < duration * 1000); }
From source file:it.serasoft.pdi.PDITools.java
public static void main(String[] args) throws Exception { Options opts = new Options(); opts.addOption("report", false, "Generate a report documenting the procedures under analysis"); opts.addOption("follow", true, "Values: directory, links, none"); opts.addOption("outDir", true, "Path to output directory where we will write eventual output files"); opts.addOption("srcDir", true, "Path to base directory containing the PDI processes source"); CommandLineParser parser = new DefaultParser(); CommandLine cmdLine = parser.parse(opts, args); String outDir = cmdLine.hasOption("outDir") ? cmdLine.getOptionValue("outDir") : null; String srcDir = cmdLine.hasOption("srcDir") ? cmdLine.getOptionValue("srcDir") : null; String follow = cmdLine.hasOption("follow") ? cmdLine.getOptionValue("follow") : FOLLOW_DIR; // Follow links between procedures only if required and recurseSubdir = false (DEFAULT) boolean recurseDir = follow.equals(FOLLOW_DIR); boolean followLinks = follow.equals(FOLLOW_PROCLINKS); startReadingDir(srcDir, recurseDir, followLinks); }
From source file:com.github.braully.graph.UtilResultMerge.java
public static void main(String... args) throws Exception { Options options = new Options(); Option input = new Option("i", "input", true, "input file path"); input.setRequired(false);// w ww . ja v a 2 s .c om options.addOption(input); Option output = new Option("o", "output", true, "output file"); output.setRequired(false); options.addOption(output); Option verb = new Option("v", "verbose", false, "verbose"); output.setRequired(false); options.addOption(verb); Option exluces = new Option("x", "exclude", true, "exclude operations"); exluces.setRequired(false); options.addOption(exluces); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("UtilResult", options); System.exit(1); return; } String[] excludes = cmd.getOptionValues("exclude"); String[] inputs = cmd.getOptionValues("input"); if (inputs == null) { inputs = new String[] { "/home/strike/Dropbox/workspace/graph-caratheodory-np3/grafos-processamento/Almost_hypohamiltonian" // "/media/dados/documentos/grafos-processamento/Almost_hypohamiltonian", // "/home/strike/Documentos/grafos-processamento/Cubic", // "/home/strike/Documentos/grafos-processamento/Critical_H-free", // "/home/strike/Documentos/grafos-processamento/Highly_irregular", // "/home/strike/Documentos/grafos-processamento/Hypohamiltonian_graphs", // "/home/strike/Documentos/grafos-processamento/Maximal_triangle-free", // "/home/strike/Documentos/grafos-processamento/Minimal_Ramsey", // "/home/strike/Documentos/grafos-processamento/Strongly_regular", // "/home/strike/Documentos/grafos-processamento/Vertex-transitive", // "/home/strike/Documentos/grafos-processamento/Trees" }; excludes = new String[] { "carathe" }; verbose = true; } if (cmd.hasOption(verb.getOpt())) { verbose = true; } if (inputs != null) { processInputs(inputs, excludes); } }
From source file:edu.cmu.sv.modelinference.runner.Main.java
public static void main(String[] args) { Options cmdOpts = createCmdOptions(); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null;//from ww w .j a v a 2 s. co m try { cmd = parser.parse(cmdOpts, args, true); } catch (ParseException exp) { logger.error(exp.getMessage()); System.err.println(exp.getMessage()); Util.printHelpAndExit(Main.class, cmdOpts); } String inputType = cmd.getOptionValue(INPUT_TYPE_ARG); String tool = cmd.getOptionValue(TOOL_TYPE_ARG); String logFile = cmd.getOptionValue(LOG_FILE_ARG).replaceFirst("^~", System.getProperty("user.home")); LogHandler<?> logHandler = null; boolean found = false; for (LogHandler<?> lh : logHandlers) { if (lh.getHandlerName().equals(tool)) { logHandler = lh; found = true; break; } } if (!found) { StringBuilder sb = new StringBuilder(); Iterator<LogHandler<?>> logIter = logHandlers.iterator(); while (logIter.hasNext()) { sb.append(logIter.next().getHandlerName()); if (logIter.hasNext()) sb.append(", "); } logger.error("Did not find tool for arg " + tool); System.err.println("Supported tools: " + Util.getSupportedHandlersString(logHandlers)); Util.printHelpAndExit(Main.class, cmdOpts); } logger.info("Using loghandler for logtype: " + logHandler.getHandlerName()); logHandler.process(logFile, inputType, cmd.getArgs()); }
From source file:com.datazuul.iiif.presentation.api.ManifestGenerator.java
public static void main(String[] args) throws ParseException, JsonProcessingException, IOException, URISyntaxException { Options options = new Options(); options.addOption("d", true, "Absolute file path to the directory containing the image files."); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("d")) { String imageDirectoryPath = cmd.getOptionValue("d"); Path imageDirectory = Paths.get(imageDirectoryPath); final List<Path> files = new ArrayList<>(); try {/* www .j a v a 2s . com*/ Files.walkFileTree(imageDirectory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (!attrs.isDirectory()) { // TODO there must be a more elegant solution for filtering jpeg files... if (file.getFileName().toString().endsWith("jpg")) { files.add(file); } } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { e.printStackTrace(); } Collections.sort(files, new Comparator() { @Override public int compare(Object fileOne, Object fileTwo) { String filename1 = ((Path) fileOne).getFileName().toString(); String filename2 = ((Path) fileTwo).getFileName().toString(); try { // numerical sorting Integer number1 = Integer.parseInt(filename1.substring(0, filename1.lastIndexOf("."))); Integer number2 = Integer.parseInt(filename2.substring(0, filename2.lastIndexOf("."))); return number1.compareTo(number2); } catch (NumberFormatException nfe) { // alpha-numerical sorting return filename1.compareToIgnoreCase(filename2); } } }); generateManifest(imageDirectory.getFileName().toString(), files); } else { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ManifestGenerator", options); } }
From source file:com.google.api.codegen.SynchronizerTool.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("h", "help", false, "show usage"); options.addOption(/*from w w w . java 2s.co m*/ Option.builder().longOpt("source_path").desc("The directory which contains the final code.") .hasArg().argName("SOURCE-PATH").required(true).build()); options.addOption( Option.builder().longOpt("generated_path").desc("The directory which contains the generated code.") .hasArg().argName("GENERATED-PATH").build()); options.addOption(Option.builder().longOpt("baseline_path") .desc("The directory which contains the baseline code.").hasArg().argName("BASELINE-PATH").build()); options.addOption(Option.builder().longOpt("auto_merge") .desc("If set, no GUI will be launched if merge can be completed automatically.") .argName("AUTO-MERGE").build()); options.addOption(Option.builder().longOpt("auto_resolve") .desc("Whether to enable smart conflict resolution").argName("AUTO_RESOLVE").build()); options.addOption(Option.builder().longOpt("ignore_base") .desc("If true, the baseline will be ignored and two-way merge will be used.") .argName("IGNORE_BASE").build()); CommandLine cl = (new DefaultParser()).parse(options, args); if (cl.hasOption("help")) { HelpFormatter formater = new HelpFormatter(); formater.printHelp("CodeGeneratorTool", options); } synchronize(cl.getOptionValue("source_path"), cl.getOptionValue("generated_path"), cl.getOptionValue("baseline_path"), cl.hasOption("auto_merge"), cl.hasOption("auto_resolve"), cl.hasOption("ignore_base")); }