List of usage examples for org.apache.commons.cli CommandLine hasOption
public boolean hasOption(char opt)
From source file:javadepchecker.Main.java
/** * @param args the command line arguments *///from www . j ava 2s. c om public static void main(String[] args) throws IOException { int exit = 0; try { CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("h", "help", false, "print help"); options.addOption("i", "image", true, "image directory"); options.addOption("v", "verbose", false, "print verbose output"); CommandLine line = parser.parse(options, args); String[] files = line.getArgs(); if (line.hasOption("h") || files.length == 0) { HelpFormatter h = new HelpFormatter(); h.printHelp("java-dep-check [-i <image>] <package.env>+", options); } else { image = line.getOptionValue("i", ""); for (String arg : files) { if (line.hasOption('v')) { System.out.println("Checking " + arg); } if (!checkPkg(new File(arg))) { exit = 1; } } } } catch (ParseException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } System.exit(exit); }
From source file:baldrickv.s3streamingtool.S3StreamingTool.java
public static void main(String args[]) throws Exception { BasicParser p = new BasicParser(); Options o = getOptions();/*from w w w .java 2 s . c o m*/ CommandLine cl = p.parse(o, args); if (cl.hasOption('h')) { HelpFormatter hf = new HelpFormatter(); hf.setWidth(80); StringBuilder sb = new StringBuilder(); sb.append("\n"); sb.append("Upload:\n"); sb.append(" -u -r creds -s 50M -b my_bucket -f hda1.dump -t 10\n"); sb.append("Download:\n"); sb.append(" -d -r creds -s 50M -b my_bucket -f hda1.dump -t 10\n"); sb.append("Upload encrypted:\n"); sb.append(" -u -r creds -z -k secret_key -s 50M -b my_bucket -f hda1.dump -t 10\n"); sb.append("Download encrypted:\n"); sb.append(" -d -r creds -z -k secret_key -s 50M -b my_bucket -f hda1.dump -t 10\n"); sb.append("Cleanup in-progress multipart uploads\n"); sb.append(" -c -r creds -b my_bucket\n"); System.out.println(sb.toString()); hf.printHelp("See above", o); return; } int n = 0; if (cl.hasOption('d')) n++; if (cl.hasOption('u')) n++; if (cl.hasOption('c')) n++; if (cl.hasOption('m')) n++; if (n != 1) { System.err.println("Must specify at exactly one of -d, -u, -c or -m"); System.exit(-1); } if (cl.hasOption('m')) { //InputStream in = new java.io.BufferedInputStream(System.in,1024*1024*2); InputStream in = System.in; System.out.println(TreeHashGenerator.calculateTreeHash(in)); return; } require(cl, 'b'); if (cl.hasOption('d') || cl.hasOption('u')) { require(cl, 'f'); } if (cl.hasOption('z')) { require(cl, 'k'); } AWSCredentials creds = null; if (cl.hasOption('r')) { creds = Utils.loadAWSCredentails(cl.getOptionValue('r')); } else { if (cl.hasOption('i') && cl.hasOption('e')) { creds = new BasicAWSCredentials(cl.getOptionValue('i'), cl.getOptionValue('e')); } else { System.out.println("Must specify either credential file (-r) or AWS key ID and secret (-i and -e)"); System.exit(-1); } } S3StreamConfig config = new S3StreamConfig(); config.setEncryption(false); if (cl.hasOption('z')) { config.setEncryption(true); config.setSecretKey(Utils.loadSecretKey(cl.getOptionValue("k"))); } if (cl.hasOption("encryption-mode")) { config.setEncryptionMode(cl.getOptionValue("encryption-mode")); } config.setS3Bucket(cl.getOptionValue("bucket")); if (cl.hasOption("file")) { config.setS3File(cl.getOptionValue("file")); } if (cl.hasOption("threads")) { config.setIOThreads(Integer.parseInt(cl.getOptionValue("threads"))); } if (cl.hasOption("blocksize")) { String s = cl.getOptionValue("blocksize"); s = s.toUpperCase(); int multi = 1; int end = 0; while ((end < s.length()) && (s.charAt(end) >= '0') && (s.charAt(end) <= '9')) { end++; } int size = Integer.parseInt(s.substring(0, end)); if (end < s.length()) { String m = s.substring(end); if (m.equals("K")) multi = 1024; else if (m.equals("M")) multi = 1048576; else if (m.equals("G")) multi = 1024 * 1024 * 1024; else if (m.equals("KB")) multi = 1024; else if (m.equals("MB")) multi = 1048576; else if (m.equals("GB")) multi = 1024 * 1024 * 1024; else { System.out.println("Unknown suffix on block size. Only K,M and G understood."); System.exit(-1); } } size *= multi; config.setBlockSize(size); } Logger.getLogger("").setLevel(Level.FINE); S3StreamingDownload.log.setLevel(Level.FINE); S3StreamingUpload.log.setLevel(Level.FINE); config.setS3Client(new AmazonS3Client(creds)); config.setGlacierClient(new AmazonGlacierClient(creds)); config.getGlacierClient().setEndpoint("glacier.us-west-2.amazonaws.com"); if (cl.hasOption("glacier")) { config.setGlacier(true); config.setStorageInterface(new StorageGlacier(config.getGlacierClient())); } else { config.setStorageInterface(new StorageS3(config.getS3Client())); } if (cl.hasOption("bwlimit")) { config.setMaxBytesPerSecond(Double.parseDouble(cl.getOptionValue("bwlimit"))); } if (cl.hasOption('c')) { if (config.getGlacier()) { GlacierCleanupMultipart.cleanup(config); } else { S3CleanupMultipart.cleanup(config); } return; } if (cl.hasOption('d')) { config.setOutputStream(System.out); S3StreamingDownload.download(config); return; } if (cl.hasOption('u')) { config.setInputStream(System.in); S3StreamingUpload.upload(config); return; } }
From source file:de.uni_koblenz.jgralab.utilities.converter.TGraphToTGraph2Converter.java
/** * Uses the apache cli interface for command line handling. * //from w w w . j av a2 s.c o m * @param args * the command line parameters */ public static void main(String[] args) { CommandLine cmdl = processCommandLineOptions(args); try { String inputFilename = cmdl.hasOption('i') ? cmdl.getOptionValue('i') : null; String outputFilename = cmdl.hasOption('o') ? cmdl.getOptionValue('o') : null; boolean loadSchema = outputFilename != null && cmdl.hasOption('l'); String tempFilename = outputFilename != null ? outputFilename + "~" + Long.toString(System.currentTimeMillis()) : null; File inputFile = inputFilename != null ? new File(inputFilename) : null; File tempFile = tempFilename != null ? new File(tempFilename) : null; File outputFile = outputFilename != null ? new File(outputFilename) : null; InputStream in = inputFile != null ? new FileInputStream(inputFile) : System.in; OutputStream out = tempFilename != null ? new FileOutputStream(tempFile) : System.out; TGraphToTGraph2Converter converter = new TGraphToTGraph2Converter(); converter.convertTGStream(out, in); if (!tempFile.renameTo(outputFile)) { System.err.println("Warning: temporary file could not be moved to\n" + outputFile.getAbsolutePath() + "\nit can be found at\n" + tempFile.getAbsolutePath()); } System.out.println("Fini."); if (loadSchema) { loadConvertedSchema(outputFilename); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:name.wagners.bpp.Bpp.java
public static void main(final String[] args) { // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("generations") .withDescription("Number of generations [default: 50]").create("g")); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("mutrate") .withDescription("Mutation rate [default: 1]").create()); options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("mutprop") .withDescription("Mutation propability [default: 0.5]").create()); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("populationsize") .withDescription("Size of population [default: 20]").create()); options.addOption(OptionBuilder.hasArg().withArgName("a|b").withLongOpt("recombalg") .withDescription("Recombination algorithm [default: a]").create()); // options.addOption(OptionBuilder // .hasArg()//from w ww . j a v a 2 s . c o m // .withArgName("int") // .withLongOpt("recombrate") // .withDescription("Recombination rate [default: 1]") // .create()); options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("recombprop") .withDescription("Recombination propability [default: 0.8]").create()); options.addOption(OptionBuilder.hasArg().withArgName("a").withLongOpt("selalg") .withDescription("Selection algorithm [default: a]").create()); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("selectionpressure") .withDescription("Selection pressure [default: 4]").create()); options.addOption(OptionBuilder.hasArg().withArgName("bool").withLongOpt("elitism") .withDescription("Enable Elitism [default: 1]").create("e")); options.addOption(OptionBuilder.hasArg().withArgName("filename") // .isRequired() .withLongOpt("datafile").withDescription("Problem data file [default: \"binpack.txt\"]") .create("f")); options.addOptionGroup(new OptionGroup() .addOption(OptionBuilder.withLongOpt("verbose").withDescription("be extra verbose").create("v")) .addOption(OptionBuilder.withLongOpt("quiet").withDescription("be extra quiet").create("q"))); options.addOption(OptionBuilder.withLongOpt("version") .withDescription("print the version information and exit").create("V")); options.addOption(OptionBuilder.withLongOpt("help").withDescription("print this message").create("h")); try { // parse the command line arguments CommandLine line = parser.parse(options, args); // validate that block-size has been set if (line.hasOption("help")) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Bpp", options); System.exit(0); } if (line.hasOption("version")) { log.info("Bpp 0.1 (c) 2007 by Daniel Wagner"); } if (line.hasOption("datafile")) { fname = line.getOptionValue("datafile"); } if (line.hasOption("elitism")) { elitism = Boolean.parseBoolean(line.getOptionValue("elitism")); } if (line.hasOption("generations")) { gen = Integer.parseInt(line.getOptionValue("generations")); } if (line.hasOption("mutprop")) { mp = Double.parseDouble(line.getOptionValue("mutprop")); } if (line.hasOption("mutrate")) { mr = Integer.parseInt(line.getOptionValue("mutrate")); } if (line.hasOption("populationsize")) { ps = Integer.parseInt(line.getOptionValue("populationsize")); } if (line.hasOption("recombalg")) { sel = line.getOptionValue("recombalg").charAt(0); } if (line.hasOption("recombprop")) { rp = Double.parseDouble(line.getOptionValue("recombprop")); } if (line.hasOption("selalg")) { selalg = line.getOptionValue("selalg").charAt(0); } if (line.hasOption("selectionpressure")) { sp = Integer.parseInt(line.getOptionValue("selectionpressure")); } } catch (ParseException exp) { log.info("Unexpected exception:" + exp.getMessage(), exp); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Bpp", options); System.exit(1); } // Ausgabe der eingestellten Optionen log.info("Configuration"); log.info(" Datafile: " + fname); log.info(" Generations: " + gen); log.info(" Population size: " + ps); log.info(" Elitism: " + elitism); log.info(" Mutation propapility: " + mp); log.info(" Mutation rate: " + mr); log.info(" Recombination algorithm " + (char) sel); log.info(" Recombination propapility: " + rp); log.info(" Selection pressure: " + sp); // Daten laden instance = new Instance(); instance.load(fname); Evolutionizer e = new Evolutionizer(instance); e.run(); }
From source file:com.google.api.ads.adwords.awalerting.AwAlerting.java
/** * Main method.//from w ww.j a v a 2 s . com * * @param args the command line arguments */ public static void main(String args[]) { // Set up proxy. JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault()); ProxySelector.setDefault(ps); Options options = createCommandLineOptions(); try { CommandLineParser parser = new BasicParser(); CommandLine cmdLine = parser.parse(options, args); // Print full help and quit if (cmdLine.hasOption("help")) { printHelpMessage(options); printSamplePropertiesFile(); System.exit(0); } if (!cmdLine.hasOption("file")) { LOGGER.error("Missing required option: 'file'"); System.exit(1); } processAlerts(cmdLine); } catch (ParseException e) { LOGGER.error("Error parsing the values for the command line options.", e); System.exit(1); } catch (AlertConfigLoadException e) { LOGGER.error("Error laoding alerts configuration.", e); System.exit(1); } catch (AlertProcessingException e) { LOGGER.error("Error processing alerts.", e); System.exit(1); } }
From source file:com.google.flightmap.parsing.faa.nfd.NfdParser.java
public static void main(String args[]) { CommandLine line = null; try {//from w w w .j a va 2 s . co m final CommandLineParser parser = new PosixParser(); line = parser.parse(OPTIONS, args); } catch (ParseException pEx) { System.err.println(pEx.getMessage()); printHelp(line); System.exit(1); } if (line.hasOption(HELP_OPTION)) { printHelp(line); System.exit(0); } final String nfdPath = line.getOptionValue(NFD_OPTION); final File nfd = new File(nfdPath); final String iataToIcaoPath = line.getOptionValue(IATA_TO_ICAO_OPTION); final File iataToIcao = new File(iataToIcaoPath); (new NfdParser(nfd, iataToIcao)).execute(); }
From source file:apps.classification.ClassifySVMPerf.java
public static void main(String[] args) throws IOException { boolean dumpConfidences = false; String cmdLineSyntax = ClassifySVMPerf.class.getName() + " [OPTIONS] <path to svm_perf_classify> <testIndexDirectory> <modelDirectory>"; Options options = new Options(); OptionBuilder.withArgName("d"); OptionBuilder.withDescription("Dump confidences file"); OptionBuilder.withLongOpt("d"); OptionBuilder.isRequired(false);//from www . j ava 2 s .c o m OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("t"); OptionBuilder.withDescription("Path for temporary files"); OptionBuilder.withLongOpt("t"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("v"); OptionBuilder.withDescription("Verbose output"); OptionBuilder.withLongOpt("v"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("s"); OptionBuilder.withDescription("Don't delete temporary training file in svm_perf format (default: delete)"); OptionBuilder.withLongOpt("s"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); SvmPerfClassifierCustomizer customizer = null; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); customizer = new SvmPerfClassifierCustomizer(remainingArgs[0]); if (line.hasOption("d")) dumpConfidences = true; if (line.hasOption("v")) customizer.printSvmPerfOutput(true); if (line.hasOption("s")) { customizer.setDeleteTestFiles(false); customizer.setDeletePredictionsFiles(false); } if (line.hasOption("t")) customizer.setTempPath(line.getOptionValue("t")); } catch (Exception exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } if (remainingArgs.length != 3) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } String testFile = remainingArgs[1]; File file = new File(testFile); String testName = file.getName(); String testPath = file.getParent(); String classifierFile = remainingArgs[2]; file = new File(classifierFile); String classifierName = file.getName(); String classifierPath = file.getParent(); FileSystemStorageManager storageManager = new FileSystemStorageManager(testPath, false); storageManager.open(); IIndex test = TroveReadWriteHelper.readIndex(storageManager, testName, TroveContentDBType.Full, TroveClassificationDBType.Full); storageManager.close(); SvmPerfDataManager dataManager = new SvmPerfDataManager(customizer); storageManager = new FileSystemStorageManager(classifierPath, false); storageManager.open(); SvmPerfClassifier classifier = (SvmPerfClassifier) dataManager.read(storageManager, classifierName); storageManager.close(); classifier.setRuntimeCustomizer(customizer); // CLASSIFICATION String classificationName = testName + "_" + classifierName; Classifier classifierModule = new Classifier(test, classifier, dumpConfidences); classifierModule.setClassificationMode(ClassificationMode.PER_CATEGORY); classifierModule.exec(); IClassificationDB testClassification = classifierModule.getClassificationDB(); storageManager = new FileSystemStorageManager(testPath, false); storageManager.open(); TroveReadWriteHelper.writeClassification(storageManager, testClassification, classificationName + ".cla", true); storageManager.close(); if (dumpConfidences) { ClassificationScoreDB confidences = classifierModule.getConfidences(); ClassificationScoreDB.write(testPath + Os.pathSeparator() + classificationName + ".confidences", confidences); } }
From source file:com.linkedin.pinot.transport.perf.ScatterGatherPerfTester.java
public static void main(String[] args) throws Exception { CommandLineParser cliParser = new GnuParser(); Options cliOptions = buildCommandLineOptions(); CommandLine cmd = cliParser.parse(cliOptions, args, true); if (!cmd.hasOption(EXECUTION_MODE)) { System.out.println("Missing required argument (" + EXECUTION_MODE + ")"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("", cliOptions); System.exit(-1);/* w w w.j a v a2s. com*/ } ExecutionMode mode = ExecutionMode.valueOf(cmd.getOptionValue(EXECUTION_MODE)); int numClients = 1; int numServers = 1; int requestSize = 1000; int responseSize = 100000; int numRequests = 10000; int startPortNum = 9078; boolean isAsyncRequest = true; List<String> servers = new ArrayList<String>(); int numActiveConnectionsPerPeer = 10; int numResponseReaders = 3; long serverInducedLatency = 10; if (mode == ExecutionMode.RUN_CLIENT) { if (!cmd.hasOption(SERVER_HOSTS)) { System.out.println("Missing required argument (" + SERVER_HOSTS + ")"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("", cliOptions); System.exit(-1); } } if (cmd.hasOption(NUM_CLIENTS)) { numClients = Integer.parseInt(cmd.getOptionValue(NUM_CLIENTS)); } if (cmd.hasOption(NUM_SERVERS)) { numServers = Integer.parseInt(cmd.getOptionValue(NUM_SERVERS)); } if (cmd.hasOption(REQUEST_SIZE)) { requestSize = Integer.parseInt(cmd.getOptionValue(REQUEST_SIZE)); } if (cmd.hasOption(RESPONSE_SIZE)) { responseSize = Integer.parseInt(cmd.getOptionValue(RESPONSE_SIZE)); } if (cmd.hasOption(NUM_REQUESTS)) { numRequests = Integer.parseInt(cmd.getOptionValue(NUM_REQUESTS)); } if (cmd.hasOption(SERVER_START_PORT)) { startPortNum = Integer.parseInt(cmd.getOptionValue(SERVER_START_PORT)); } if (cmd.hasOption(SYNC_REQUEST_DISPATCH)) { isAsyncRequest = false; } if (cmd.hasOption(CONN_POOL_SIZE_PER_PEER)) { numActiveConnectionsPerPeer = Integer.parseInt(cmd.getOptionValue(CONN_POOL_SIZE_PER_PEER)); } if (cmd.hasOption(NUM_RESPONSE_READERS)) { numResponseReaders = Integer.parseInt(cmd.getOptionValue(NUM_RESPONSE_READERS)); } if (cmd.hasOption(RESPONSE_LATENCY)) { serverInducedLatency = Integer.parseInt(cmd.getOptionValue(RESPONSE_LATENCY)); } if (cmd.hasOption(SERVER_HOSTS)) { servers = Arrays.asList(cmd.getOptionValue(SERVER_HOSTS).split(",")); } ScatterGatherPerfTester tester = new ScatterGatherPerfTester(numClients, // num Client Threads numServers, // Num Servers requestSize, // Request Size responseSize, // Response Size numRequests, // Num Requests startPortNum, // Server start port isAsyncRequest, // Async Request sending ExecutionMode.RUN_CLIENT, // Execution mode servers, // Server Hosts. All servers need to run on the same port numActiveConnectionsPerPeer, // Number of Active Client connections per Client-Server pair numResponseReaders, // Number of Response Reader threads in client serverInducedLatency); // 10 ms latency at server tester.run(); }
From source file:co.cask.cdap.cli.CLIMain.java
public static void main(String[] args) { final PrintStream output = System.out; Options options = getOptions();// ww w . j a va 2 s . c o m CLIMainArgs cliMainArgs = CLIMainArgs.parse(args, options); CommandLineParser parser = new BasicParser(); try { CommandLine command = parser.parse(options, cliMainArgs.getOptionTokens()); if (command.hasOption(HELP_OPTION.getOpt())) { usage(); System.exit(0); } LaunchOptions launchOptions = LaunchOptions.builder() .setUri(command.getOptionValue(URI_OPTION.getOpt(), getDefaultURI().toString())) .setDebug(command.hasOption(DEBUG_OPTION.getOpt())) .setVerifySSL(parseBooleanOption(command, VERIFY_SSL_OPTION, DEFAULT_VERIFY_SSL)) .setAutoconnect(parseBooleanOption(command, AUTOCONNECT_OPTION, DEFAULT_AUTOCONNECT)).build(); String scriptFile = command.getOptionValue(SCRIPT_OPTION.getOpt(), ""); boolean hasScriptFile = command.hasOption(SCRIPT_OPTION.getOpt()); String[] commandArgs = cliMainArgs.getCommandTokens(); try { ClientConfig clientConfig = ClientConfig.builder().setConnectionConfig(null).build(); final CLIConfig cliConfig = new CLIConfig(clientConfig, output, new AltStyleTableRenderer()); CLIMain cliMain = new CLIMain(launchOptions, cliConfig); CLI cli = cliMain.getCLI(); cliMain.tryAutoconnect(); CLIConnectionConfig connectionConfig = new CLIConnectionConfig( cliConfig.getClientConfig().getConnectionConfig(), Id.Namespace.DEFAULT, null); cliMain.updateCLIPrompt(connectionConfig); if (hasScriptFile) { File script = cliMain.getFilePathResolver().resolvePathToFile(scriptFile); if (!script.exists()) { output.println("ERROR: Script file '" + script.getAbsolutePath() + "' does not exist"); System.exit(1); } List<String> scriptLines = Files.readLines(script, Charsets.UTF_8); for (String scriptLine : scriptLines) { output.print(cliMain.getPrompt(connectionConfig)); output.println(scriptLine); cli.execute(scriptLine, output); output.println(); } } else if (commandArgs.length == 0) { cli.startInteractiveMode(output); } else { cli.execute(Joiner.on(" ").join(commandArgs), output); } } catch (Exception e) { e.printStackTrace(output); } } catch (ParseException e) { output.println(e.getMessage()); usage(); } }
From source file:com.akana.demo.freemarker.templatetester.App.java
public static void main(String[] args) { final Options options = new Options(); @SuppressWarnings("static-access") Option optionContentType = OptionBuilder.withArgName("content-type").hasArg() .withDescription("content type of model").create("content"); @SuppressWarnings("static-access") Option optionUrlPath = OptionBuilder.withArgName("httpRequestLine").hasArg() .withDescription("url path and parameters in HTTP Request Line format").create("url"); @SuppressWarnings("static-access") Option optionRootMessageName = OptionBuilder.withArgName("messageName").hasArg() .withDescription("root data object name, defaults to 'message'").create("root"); @SuppressWarnings("static-access") Option optionAdditionalMessages = OptionBuilder.withArgName("dataModelPaths") .hasArgs(Option.UNLIMITED_VALUES).withDescription("additional message object data sources") .create("messages"); @SuppressWarnings("static-access") Option optionDebugMessages = OptionBuilder.hasArg(false) .withDescription("Shows debug information about template processing").create("debug"); Option optionHelp = new Option("help", "print this message"); options.addOption(optionHelp);/*www .j a va 2 s .c o m*/ options.addOption(optionContentType); options.addOption(optionUrlPath); options.addOption(optionRootMessageName); options.addOption(optionAdditionalMessages); options.addOption(optionDebugMessages); CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); // Check for help flag if (cmd.hasOption("help")) { showHelp(options); return; } String[] remainingArguments = cmd.getArgs(); if (remainingArguments.length < 2) { showHelp(options); return; } String ftlPath, dataPath = "none"; ftlPath = remainingArguments[0]; dataPath = remainingArguments[1]; String contentType = "text/xml"; // Discover content type from file extension String ext = FilenameUtils.getExtension(dataPath); if (ext.equals("json")) { contentType = "json"; } else if (ext.equals("txt")) { contentType = "txt"; } // Override discovered content type if (cmd.hasOption("content")) { contentType = cmd.getOptionValue("content"); } // Root data model name String rootMessageName = "message"; if (cmd.hasOption("root")) { rootMessageName = cmd.getOptionValue("root"); } // Additional data models String[] additionalModels = new String[0]; if (cmd.hasOption("messages")) { additionalModels = cmd.getOptionValues("messages"); } // Debug Info if (cmd.hasOption("debug")) { System.out.println(" Processing ftl : " + ftlPath); System.out.println(" with data model: " + dataPath); System.out.println(" with content-type: " + contentType); System.out.println(" data model object: " + rootMessageName); if (cmd.hasOption("messages")) { System.out.println("additional models: " + additionalModels.length); } } Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); cfg.setDirectoryForTemplateLoading(new File(".")); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); /* Create the primary data-model */ Map<String, Object> message = new HashMap<String, Object>(); if (contentType.contains("json") || contentType.contains("txt")) { message.put("contentAsString", FileUtils.readFileToString(new File(dataPath), StandardCharsets.UTF_8)); } else { message.put("contentAsXml", freemarker.ext.dom.NodeModel.parse(new File(dataPath))); } if (cmd.hasOption("url")) { message.put("getProperty", new AkanaGetProperty(cmd.getOptionValue("url"))); } Map<String, Object> root = new HashMap<String, Object>(); root.put(rootMessageName, message); if (additionalModels.length > 0) { for (int i = 0; i < additionalModels.length; i++) { Map<String, Object> m = createMessageFromFile(additionalModels[i], contentType); root.put("message" + i, m); } } /* Get the template (uses cache internally) */ Template temp = cfg.getTemplate(ftlPath); /* Merge data-model with template */ Writer out = new OutputStreamWriter(System.out); temp.process(root, out); } catch (ParseException e) { showHelp(options); System.exit(1); } catch (IOException e) { System.out.println("Unable to parse ftl."); e.printStackTrace(); } catch (SAXException e) { System.out.println("XML parsing issue."); e.printStackTrace(); } catch (ParserConfigurationException e) { System.out.println("Unable to configure parser."); e.printStackTrace(); } catch (TemplateException e) { System.out.println("Unable to parse template."); e.printStackTrace(); } }