List of usage examples for org.apache.commons.cli OptionBuilder hasArg
public static OptionBuilder hasArg(boolean hasArg)
hasArg
is true. From source file:de.stz.bt.nanopubsub.StandaloneBroker.java
/** * Main Method for running the standalone Broker * //w w w . j a v a 2 s . co m * @param args * @author jseitter */ public static void main(String[] args) { Options options = new Options(); options.addOption( OptionBuilder.hasArg(true).withArgName("port").withDescription("broker port number").create('p')); Parser parser = new PosixParser(); CommandLine cmdLine = null; try { cmdLine = parser.parse(options, args); } catch (ParseException e) { printHelp(options); } if (cmdLine == null) printHelp(options); new StandaloneBroker(cmdLine); }
From source file:com.discursive.jccook.cmdline.CliComplexExample.java
public static void main(String[] args) throws Exception { CommandLineParser parser = new BasicParser(); Options options = new Options(); options.addOption("h", "help", false, "Print this usage information"); options.addOption("v", "verbose", false, "Print out VERBOSE debugging information"); OptionGroup optionGroup = new OptionGroup(); optionGroup.addOption(OptionBuilder.hasArg(true).create('f')); optionGroup.addOption(OptionBuilder.hasArg(true).create('m')); options.addOptionGroup(optionGroup); CommandLine commandLine = parser.parse(options, args); boolean verbose = false; String file = ""; String mail = ""; if (commandLine.hasOption('h')) { System.out.println("Help Message"); System.exit(0);/*from www . j a v a 2 s . c o m*/ } if (commandLine.hasOption('v')) { verbose = true; } if (commandLine.hasOption('f')) { file = commandLine.getOptionValue('f'); } else if (commandLine.hasOption('m')) { mail = commandLine.getOptionValue('m'); } System.exit(0); }
From source file:com.discursive.jccook.cmdline.SomeApp.java
public static void main(String[] args) throws Exception { // Create a Parser CommandLineParser parser = new BasicParser(); Options options = new Options(); options.addOption("h", "help", false, "Print this usage information"); options.addOption("v", "verbose", false, "Print out VERBOSE information"); OptionGroup optionGroup = new OptionGroup(); optionGroup.addOption(OptionBuilder.hasArg(true).withArgName("file").withLongOpt("file").create('f')); optionGroup.addOption(OptionBuilder.hasArg(true).withArgName("email").withLongOpt("email").create('m')); options.addOptionGroup(optionGroup); // Parse the program arguments try {/* ww w .j a va 2 s . c o m*/ CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption('h')) { printUsage(options); System.exit(0); } // ... do important stuff ... } catch (Exception e) { System.out.println("You provided bad program arguments!"); printUsage(options); System.exit(1); } }
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 w w w . jav a 2s.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:apps.quantification.QuantifySVMPerf.java
public static void main(String[] args) throws IOException { String cmdLineSyntax = QuantifySVMPerf.class.getName() + " [OPTIONS] <path to svm_perf_classify> <testIndexDirectory> <quantificationModelDirectory>"; Options options = new Options(); OptionBuilder.withArgName("d"); OptionBuilder.withDescription("Dump confidences file"); OptionBuilder.withLongOpt("d"); OptionBuilder.isRequired(false);//from w w w. j ava2 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 files 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("v")) customizer.printSvmPerfOutput(true); if (line.hasOption("s")) { System.out.println("Keeping temporary files."); 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 indexFile = remainingArgs[1]; File file = new File(indexFile); String indexName = file.getName(); String indexPath = file.getParent(); String quantifierFilename = remainingArgs[2]; FileSystemStorageManager indexFssm = new FileSystemStorageManager(indexPath, false); indexFssm.open(); IIndex test = TroveReadWriteHelper.readIndex(indexFssm, indexName, TroveContentDBType.Full, TroveClassificationDBType.Full); indexFssm.close(); FileSystemStorageManager quantifierFssm = new FileSystemStorageManager(quantifierFilename, false); quantifierFssm.open(); SvmPerfDataManager classifierDataManager = new SvmPerfDataManager(customizer); FileSystemStorageManager fssm = new FileSystemStorageManager(quantifierFilename, false); fssm.open(); IQuantifier[] quantifiers = QuantificationLearner.read(fssm, classifierDataManager, ClassificationMode.PER_CATEGORY); fssm.close(); quantifierFssm.close(); Quantification ccQuantification = quantifiers[0].quantify(test); Quantification paQuantification = quantifiers[1].quantify(test); Quantification accQuantification = quantifiers[2].quantify(test); Quantification maxQuantification = quantifiers[3].quantify(test); Quantification sccQuantification = quantifiers[4].quantify(test); Quantification spaQuantification = quantifiers[5].quantify(test); Quantification trueQuantification = new Quantification("True", test.getClassificationDB()); File quantifierFile = new File(quantifierFilename); String quantificationName = quantifierFile.getParent() + Os.pathSeparator() + indexName + "_" + quantifierFile.getName() + ".txt"; BufferedWriter writer = new BufferedWriter(new FileWriter(quantificationName)); IShortIterator iterator = test.getCategoryDB().getCategories(); while (iterator.hasNext()) { short category = iterator.next(); String prefix = quantifierFile.getName() + "\t" + indexName + "\t" + test.getCategoryDB().getCategoryName(category) + "\t" + category + "\t" + trueQuantification.getQuantification(category) + "\t"; writer.write(prefix + ccQuantification.getName() + "\t" + ccQuantification.getQuantification(category) + "\n"); writer.write(prefix + paQuantification.getName() + "\t" + paQuantification.getQuantification(category) + "\n"); writer.write(prefix + accQuantification.getName() + "\t" + accQuantification.getQuantification(category) + "\n"); writer.write(prefix + maxQuantification.getName() + "\t" + maxQuantification.getQuantification(category) + "\n"); writer.write(prefix + sccQuantification.getName() + "\t" + sccQuantification.getQuantification(category) + "\n"); writer.write(prefix + spaQuantification.getName() + "\t" + spaQuantification.getQuantification(category) + "\n"); } writer.close(); BufferedWriter bfs = new BufferedWriter(new FileWriter(quantifierFile.getParent() + Os.pathSeparator() + indexName + "_" + quantifierFile.getName() + "_rates.txt")); TShortDoubleHashMap simpleTPRs = ((CCQuantifier) quantifiers[0]).getSimpleTPRs(); TShortDoubleHashMap simpleFPRs = ((CCQuantifier) quantifiers[0]).getSimpleFPRs(); TShortDoubleHashMap maxTPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier()) .getSimpleTPRs(); TShortDoubleHashMap maxFPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier()) .getSimpleFPRs(); TShortDoubleHashMap scaledTPRs = ((PAQuantifier) quantifiers[1]).getScaledTPRs(); TShortDoubleHashMap scaledFPRs = ((PAQuantifier) quantifiers[1]).getScaledFPRs(); ContingencyTableSet simpleContingencyTableSet = ((CCQuantifier) quantifiers[0]).getContingencyTableSet(); ContingencyTableSet maxContingencyTableSet = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]) .getInternalQuantifier()).getContingencyTableSet(); short[] cats = simpleTPRs.keys(); for (int i = 0; i < cats.length; ++i) { short cat = cats[i]; String catName = test.getCategoryDB().getCategoryName(cat); ContingencyTable simpleContingencyTable = simpleContingencyTableSet.getCategoryContingencyTable(cat); ContingencyTable maxContingencyTable = maxContingencyTableSet.getCategoryContingencyTable(cat); double simpleTPR = simpleTPRs.get(cat); double simpleFPR = simpleFPRs.get(cat); double maxTPR = maxTPRs.get(cat); double maxFPR = maxFPRs.get(cat); double scaledTPR = scaledTPRs.get(cat); double scaledFPR = scaledFPRs.get(cat); String line = indexName + "_" + quantifierFile.getName() + "\ttest\tsimple\t" + catName + "\t" + cat + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t" + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + simpleTPR + "\t" + simpleFPR + "\n"; bfs.write(line); line = indexName + "_" + quantifierFile.getName() + "\ttest\tmax\t" + catName + "\t" + cat + "\t" + maxContingencyTable.tp() + "\t" + maxContingencyTable.fp() + "\t" + maxContingencyTable.fn() + "\t" + maxContingencyTable.tn() + "\t" + maxTPR + "\t" + maxFPR + "\n"; bfs.write(line); line = indexName + "_" + quantifierFile.getName() + "\ttest\tscaled\t" + catName + "\t" + cat + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t" + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + scaledTPR + "\t" + scaledFPR + "\n"; bfs.write(line); } bfs.close(); }
From source file:apps.quantification.QuantifySVMLight.java
public static void main(String[] args) throws IOException { String cmdLineSyntax = QuantifySVMLight.class.getName() + " [OPTIONS] <path to svm_light_classify> <testIndexDirectory> <quantificationModelDirectory>"; Options options = new Options(); OptionBuilder.withArgName("d"); OptionBuilder.withDescription("Dump confidences file"); OptionBuilder.withLongOpt("d"); OptionBuilder.isRequired(false);//from w w w . j a v a 2s .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 files in svm_light format (default: delete)"); OptionBuilder.withLongOpt("s"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); SvmLightClassifierCustomizer customizer = null; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); customizer = new SvmLightClassifierCustomizer(remainingArgs[0]); if (line.hasOption("v")) customizer.printSvmLightOutput(true); if (line.hasOption("s")) { System.out.println("Keeping temporary files."); 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 indexFile = remainingArgs[1]; File file = new File(indexFile); String indexName = file.getName(); String indexPath = file.getParent(); String quantifierFilename = remainingArgs[2]; FileSystemStorageManager indexFssm = new FileSystemStorageManager(indexPath, false); indexFssm.open(); IIndex test = TroveReadWriteHelper.readIndex(indexFssm, indexName, TroveContentDBType.Full, TroveClassificationDBType.Full); indexFssm.close(); FileSystemStorageManager quantifierFssm = new FileSystemStorageManager(quantifierFilename, false); quantifierFssm.open(); SvmLightDataManager classifierDataManager = new SvmLightDataManager(customizer); FileSystemStorageManager fssm = new FileSystemStorageManager(quantifierFilename, false); fssm.open(); IQuantifier[] quantifiers = QuantificationLearner.read(fssm, classifierDataManager, ClassificationMode.PER_CATEGORY); fssm.close(); quantifierFssm.close(); Quantification ccQuantification = quantifiers[0].quantify(test); Quantification paQuantification = quantifiers[1].quantify(test); Quantification accQuantification = quantifiers[2].quantify(test); Quantification maxQuantification = quantifiers[3].quantify(test); Quantification sccQuantification = quantifiers[4].quantify(test); Quantification spaQuantification = quantifiers[5].quantify(test); Quantification trueQuantification = new Quantification("True", test.getClassificationDB()); File quantifierFile = new File(quantifierFilename); String quantificationName = quantifierFile.getParent() + Os.pathSeparator() + indexName + "_" + quantifierFile.getName() + ".txt"; BufferedWriter writer = new BufferedWriter(new FileWriter(quantificationName)); IShortIterator iterator = test.getCategoryDB().getCategories(); while (iterator.hasNext()) { short category = iterator.next(); String prefix = quantifierFile.getName() + "\t" + indexName + "\t" + test.getCategoryDB().getCategoryName(category) + "\t" + category + "\t" + trueQuantification.getQuantification(category) + "\t"; writer.write(prefix + ccQuantification.getName() + "\t" + ccQuantification.getQuantification(category) + "\n"); writer.write(prefix + paQuantification.getName() + "\t" + paQuantification.getQuantification(category) + "\n"); writer.write(prefix + accQuantification.getName() + "\t" + accQuantification.getQuantification(category) + "\n"); writer.write(prefix + maxQuantification.getName() + "\t" + maxQuantification.getQuantification(category) + "\n"); writer.write(prefix + sccQuantification.getName() + "\t" + sccQuantification.getQuantification(category) + "\n"); writer.write(prefix + spaQuantification.getName() + "\t" + spaQuantification.getQuantification(category) + "\n"); } writer.close(); BufferedWriter bfs = new BufferedWriter(new FileWriter(quantifierFile.getParent() + Os.pathSeparator() + indexName + "_" + quantifierFile.getName() + "_rates.txt")); TShortDoubleHashMap simpleTPRs = ((CCQuantifier) quantifiers[0]).getSimpleTPRs(); TShortDoubleHashMap simpleFPRs = ((CCQuantifier) quantifiers[0]).getSimpleFPRs(); TShortDoubleHashMap maxTPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier()) .getSimpleTPRs(); TShortDoubleHashMap maxFPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier()) .getSimpleFPRs(); TShortDoubleHashMap scaledTPRs = ((PAQuantifier) quantifiers[1]).getScaledTPRs(); TShortDoubleHashMap scaledFPRs = ((PAQuantifier) quantifiers[1]).getScaledFPRs(); ContingencyTableSet simpleContingencyTableSet = ((CCQuantifier) quantifiers[0]).getContingencyTableSet(); ContingencyTableSet maxContingencyTableSet = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]) .getInternalQuantifier()).getContingencyTableSet(); short[] cats = simpleTPRs.keys(); for (int i = 0; i < cats.length; ++i) { short cat = cats[i]; String catName = test.getCategoryDB().getCategoryName(cat); ContingencyTable simpleContingencyTable = simpleContingencyTableSet.getCategoryContingencyTable(cat); ContingencyTable maxContingencyTable = maxContingencyTableSet.getCategoryContingencyTable(cat); double simpleTPR = simpleTPRs.get(cat); double simpleFPR = simpleFPRs.get(cat); double maxTPR = maxTPRs.get(cat); double maxFPR = maxFPRs.get(cat); double scaledTPR = scaledTPRs.get(cat); double scaledFPR = scaledFPRs.get(cat); String line = indexName + "_" + quantifierFile.getName() + "\ttest\tsimple\t" + catName + "\t" + cat + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t" + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + simpleTPR + "\t" + simpleFPR + "\n"; bfs.write(line); line = indexName + "_" + quantifierFile.getName() + "\ttest\tmax\t" + catName + "\t" + cat + "\t" + maxContingencyTable.tp() + "\t" + maxContingencyTable.fp() + "\t" + maxContingencyTable.fn() + "\t" + maxContingencyTable.tn() + "\t" + maxTPR + "\t" + maxFPR + "\n"; bfs.write(line); line = indexName + "_" + quantifierFile.getName() + "\ttest\tscaled\t" + catName + "\t" + cat + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t" + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + scaledTPR + "\t" + scaledFPR + "\n"; bfs.write(line); } bfs.close(); }
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);/* w w w . j av a 2 s.c om*/ 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(); } }
From source file:com.fonoster.astive.server.AstiveServer.java
public static void main(String[] args) throws Exception { DOMConfigurator.configure(AbstractAstiveServer.ASTIVE_HOME + "/conf/log4j.xml"); astivedSP = getServiceProperties(ASTIVED_PROPERTIES, "astived"); adminDaemonSP = getServiceProperties(ADMIN_DAEMON_PROPERTIES, "admin thread"); telnedSP = getServiceProperties(TELNED_PROPERTIES, "telned"); ArrayList<ServiceProperties> serviceProperties = new ArrayList(); serviceProperties.add(astivedSP);//from w ww . ja v a2 s . co m // Adding security measure AstPolicy ap = AstPolicy.getInstance(); ap.addPermissions(astivedSP); ap.addPermissions(adminDaemonSP); ap.addPermissions(telnedSP); if (!adminDaemonSP.isDisabled()) { serviceProperties.add(adminDaemonSP); } if (!telnedSP.isDisabled()) { serviceProperties.add(telnedSP); } if ((args.length == 0) || args[0].equals("-h") || args[0].equals("--help")) { printUsage(); System.exit(1); } // Create a Parser CommandLineParser parser = new BasicParser(); Options start = new Options(); start.addOption("h", "help", false, AppLocale.getI18n("optionHelp")); start.addOption("v", "version", false, AppLocale.getI18n("optionVersion")); start.addOption("d", "debug", false, AppLocale.getI18n("optionDebug")); start.addOption("q", "quiet", false, AppLocale.getI18n("optionQuiet")); start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("admin-bind") .withDescription(AppLocale.getI18n("optionBind", new Object[] { "admin" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("admin-port") .withDescription(AppLocale.getI18n("optionPort", new Object[] { "admin" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("astived-port") .withDescription(AppLocale.getI18n("optionPort", new Object[] { "astived" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("astived-host") .withDescription(AppLocale.getI18n("optionBind", new Object[] { "astived" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("telned-port") .withDescription(AppLocale.getI18n("optionPort", new Object[] { "telned" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("telned-host") .withDescription(AppLocale.getI18n("optionBind", new Object[] { "telned" })).create()); Options stop = new Options(); stop.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("host") .withDescription(AppLocale.getI18n("optionHelp")).create()); stop.addOption("h", "host", false, AppLocale.getI18n("optionStopHost", new Object[] { DEFAULT_AGI_SERVER_BIND_ADDR })); stop.addOption("p", "port", false, AppLocale.getI18n("optionStopPort", new Object[] { DEFAULT_AGI_SERVER_PORT })); Options deploy = new Options(); deploy.addOption("h", "help", false, AppLocale.getI18n("optionHelp")); Options undeploy = new Options(); undeploy.addOption("h", "help", false, AppLocale.getI18n("optionHelp")); if (args.length == 0) { printUsage(); System.exit(1); } else if (!isCommand(args[0])) { printUnavailableCmd(args[0]); System.exit(1); } AdminCommand cmd = AdminCommand.get(args[0]); // Parse the program arguments try { if (cmd.equals(AdminCommand.START)) { CommandLine commandLine = parser.parse(start, args); Logger root = LogManager.getRootLogger(); Enumeration allLoggers = root.getLoggerRepository().getCurrentLoggers(); if (commandLine.hasOption('q')) { root.setLevel(Level.ERROR); while (allLoggers.hasMoreElements()) { Category tmpLogger = (Category) allLoggers.nextElement(); tmpLogger.setLevel(Level.ERROR); } } else if (commandLine.hasOption('d')) { root.setLevel(Level.DEBUG); while (allLoggers.hasMoreElements()) { Category tmpLogger = (Category) allLoggers.nextElement(); tmpLogger.setLevel(Level.DEBUG); } } else { root.setLevel(Level.INFO); while (allLoggers.hasMoreElements()) { Category tmpLogger = (Category) allLoggers.nextElement(); tmpLogger.setLevel(Level.INFO); } } if (commandLine.hasOption('h')) { printUsage(cmd, start); System.exit(0); } if (commandLine.hasOption('v')) { out.println(AppLocale.getI18n("astivedVersion", new String[] { Version.VERSION, Version.BUILD_TIME })); System.exit(0); } if (commandLine.hasOption("astived-bind")) { astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("astived-port"))); } if (commandLine.hasOption("astived-port")) { astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue("astived-port"))); } if (commandLine.hasOption("admin-bind")) { adminDaemonSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("admin-bind"))); } if (commandLine.hasOption("admin-port")) { adminDaemonSP.setPort(Integer.parseInt(commandLine.getOptionValue("admin-port"))); } if (commandLine.hasOption("telned-bind")) { telnedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("telned-bind"))); } if (commandLine.hasOption("telned-port")) { telnedSP.setPort(Integer.parseInt(commandLine.getOptionValue("telned-port"))); } if (!NetUtil.isPortAvailable(astivedSP.getPort())) { out.println(AppLocale.getI18n("errorCantStartFastAgiServerSocket", new Object[] { astivedSP.getBindAddr().getHostAddress(), astivedSP.getPort() })); System.exit(-1); } if (!NetUtil.isPortAvailable(adminDaemonSP.getPort())) { adminDaemonSP.setUnableToOpen(true); } if (!NetUtil.isPortAvailable(telnedSP.getPort())) { telnedSP.setUnableToOpen(true); } new InitOutput().printInit(serviceProperties); AstiveServer server = new AstiveServer(astivedSP.getPort(), astivedSP.getBacklog(), astivedSP.getBindAddr()); server.start(); } if (!cmd.equals(AdminCommand.START) && adminDaemonSP.isDisabled()) { LOG.warn("errorUnableToAccessAdminDaemon"); } if (cmd.equals(AdminCommand.STOP)) { CommandLine commandLine = parser.parse(stop, args); if (commandLine.hasOption("--help")) { printUsage(cmd, stop); System.exit(0); } if (commandLine.hasOption('h')) { if (commandLine.getOptionValue('h') == null) { printUsage(cmd, stop); System.exit(0); } astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue('h'))); } if (commandLine.hasOption('p')) { if (commandLine.getOptionValue('p') == null) { printUsage(cmd, stop); System.exit(0); } astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue('p'))); } AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(), adminDaemonSP.getPort()); adClient.stop(); } // TODO: This needs to be researched before a full implementation. // for now is only possible to do deployments into a local server. if (cmd.equals(AdminCommand.DEPLOY)) { CommandLine commandLine = parser.parse(deploy, args); if (args.length < 2) { printUsage(cmd, deploy); System.exit(1); } else if (commandLine.hasOption('h')) { printUsage(cmd, deploy); System.exit(0); } AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(), adminDaemonSP.getPort()); adClient.deploy(args[1]); } if (cmd.equals(AdminCommand.UNDEPLOY)) { CommandLine commandLine = parser.parse(undeploy, args); if (args.length < 2) { printUsage(cmd, undeploy); System.exit(1); } else if (commandLine.hasOption('h')) { printUsage(cmd, undeploy); System.exit(0); } AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(), adminDaemonSP.getPort()); adClient.undeploy(args[1]); } } catch (java.net.ConnectException ex) { LOG.error(AppLocale.getI18n("errorServerNotRunning")); } catch (Exception ex) { LOG.error(AppLocale.getI18n("errorUnexpectedFailure", new Object[] { ex.getMessage() })); } }
From source file:com.phonytive.astive.server.AstiveServer.java
public static void main(String[] args) throws Exception { astivedSP = getServiceProperties(ASTIVED_PROPERTIES, "astived"); adminDaemonSP = getServiceProperties(ADMIN_DAEMON_PROPERTIES, "admin thread"); telnedSP = getServiceProperties(TELNED_PROPERTIES, "telned"); ArrayList<ServiceProperties> serviceProperties = new ArrayList(); serviceProperties.add(astivedSP);//from w ww . java2 s. com if (!adminDaemonSP.isDisabled()) { serviceProperties.add(adminDaemonSP); } if (!telnedSP.isDisabled()) { serviceProperties.add(telnedSP); } if ((args.length == 0) || args[0].equals("-h") || args[0].equals("--help")) { printUsage(); System.exit(1); } // Create a Parser CommandLineParser parser = new BasicParser(); Options start = new Options(); start.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage")); start.addOption("v", "version", false, "Prints the Astive Server version and exits."); start.addOption("d", "debug", false, AppLocale.getI18n("cli.option.debug")); start.addOption("q", "quiet", false, AppLocale.getI18n("cli.option.daemonMode")); start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("admin-bind") .withDescription("" + AppLocale.getI18n("cli.option.bind", new Object[] { "admin" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("admin-port") .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "admin" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("astived-port") .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "astived" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("astived-host") .withDescription("" + AppLocale.getI18n("cli.option.bind", new Object[] { "astived" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("telned-port") .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "telned" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("telned-host") .withDescription("" + AppLocale.getI18n("cli.option.host", new Object[] { "telned" })).create()); Options stop = new Options(); stop.addOption(OptionBuilder.withLongOpt("--help") .withDescription("" + AppLocale.getI18n("cli.option.printUsage")).create()); stop.addOption("h", "host", false, AppLocale.getI18n("cli.option.stop.host", new Object[] { DEFAULT_AGI_SERVER_BIND_ADDR })); stop.addOption("p", "port", false, AppLocale.getI18n("cli.option.stop.port", new Object[] { DEFAULT_AGI_SERVER_PORT })); Options deploy = new Options(); deploy.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage")); Options undeploy = new Options(); undeploy.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage")); if (args.length == 0) { printUsage(); System.exit(1); } else if (!isCommand(args[0])) { printUnavailableCmd(args[0]); System.exit(1); } AdminCommand cmd = AdminCommand.get(args[0]); if (cmd.equals(AdminCommand.DEPLOY) && ((args.length < 2) || !isFileJar(args[1]))) { logger.error(AppLocale.getI18n("cli.invalid.app")); printUsage(AdminCommand.DEPLOY, deploy); System.exit(1); } if (cmd.equals(AdminCommand.UNDEPLOY) && ((args.length < 2) || !isFileJar(args[1]))) { printUsage(AdminCommand.UNDEPLOY, undeploy); System.exit(1); } // Parse the program arguments try { if (cmd.equals(AdminCommand.START)) { CommandLine commandLine = parser.parse(start, args); if (commandLine.hasOption('h')) { printUsage(cmd, start); System.exit(0); } if (commandLine.hasOption('v')) { // Them start the server without noise } if (commandLine.hasOption("astived-bind")) { astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("astived-port"))); } if (commandLine.hasOption("astived-port")) { astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue("astived-port"))); } if (commandLine.hasOption("admin-bind")) { adminDaemonSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("admin-bind"))); } if (commandLine.hasOption("admin-port")) { adminDaemonSP.setPort(Integer.parseInt(commandLine.getOptionValue("admin-port"))); } if (commandLine.hasOption("telned-bind")) { telnedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("telned-bind"))); } if (commandLine.hasOption("telned-port")) { adminDaemonSP.setPort(Integer.parseInt(commandLine.getOptionValue("telned-port"))); } if (!NetUtil.available(astivedSP.getPort())) { out.println(AppLocale.getI18n("cantStartFastAgiServerSocket", new Object[] { astivedSP.getBindAddr().getHostAddress(), astivedSP.getPort() })); System.exit(-1); } if (!NetUtil.available(adminDaemonSP.getPort())) { adminDaemonSP.setUnableToOpen(true); } if (!NetUtil.available(telnedSP.getPort())) { telnedSP.setUnableToOpen(true); } InitOutput.printInit(serviceProperties); AstiveServer server = new AstiveServer(astivedSP.getPort(), astivedSP.getBacklog(), astivedSP.getBindAddr()); server.start(); } if (!cmd.equals(AdminCommand.START) && adminDaemonSP.isDisabled()) { logger.info("unableToAccessAdminDaemon"); } if (cmd.equals(AdminCommand.STOP)) { CommandLine commandLine = parser.parse(stop, args); if (commandLine.hasOption("--help")) { printUsage(cmd, stop); System.exit(0); } if (commandLine.hasOption('h')) { if (commandLine.getOptionValue('h') == null) { printUsage(cmd, stop); System.exit(0); } astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue('h'))); } if (commandLine.hasOption('p')) { if (commandLine.getOptionValue('p') == null) { printUsage(cmd, stop); System.exit(0); } astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue('p'))); } AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(), adminDaemonSP.getPort()); adClient.stop(); } // TODO: This needs to be researched before a full implementation. // for now is only possible to do deployments into the local server. if (cmd.equals(AdminCommand.DEPLOY)) { AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(), adminDaemonSP.getPort()); adClient.deploy(args[1]); } if (cmd.equals(AdminCommand.UNDEPLOY)) { AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(), adminDaemonSP.getPort()); adClient.undeploy(args[1]); } } catch (java.net.ConnectException ex) { logger.info("serverNotRunning"); } catch (Exception ex) { logger.error(AppLocale.getI18n("unexpectedError", new Object[] { ex.getMessage() })); } }
From source file:TmlCommandLine.java
@SuppressWarnings("static-access") public static void main(String[] args) { long time = System.nanoTime(); options = new Options(); // Repository options.addOption(OptionBuilder.withDescription( "Full path of the repository folder, where TML will retrieve (or insert) documents. (e.g. /home/user/lucene).") .hasArg().withArgName("folder").isRequired().create("repo")); // Verbosity// w ww .j a va 2s. c o m options.addOption( OptionBuilder.withDescription("Verbose output in the console (it goes verbose to the log file).") .hasArg(false).isRequired(false).create("v")); // Operation on corpus options.addOption(OptionBuilder.hasArg(false).withDescription("Performs an operation on a corpus.") .isRequired(false).create("O")); // The list of operations options.addOption(OptionBuilder.withDescription( "The list of operations you want to execute on the corpus. (e.g. PassageDistances,PassageSimilarity .") .hasArgs().withValueSeparator(',').withArgName("list").isRequired(false).withLongOpt("operations") .create()); // The file to store the results options.addOption(OptionBuilder.withDescription("Folder where to store the results. (e.g. results/run01/).") .hasArg().withArgName("folder").isRequired(false).withLongOpt("oresults").create()); // The corpus on which operate options.addOption(OptionBuilder.withDescription( "Lucene query that defines the corpus to operate with. (e.g. \"type:sentence AND reference:Document01\").") .hasArg().withArgName("query").isRequired(false).withLongOpt("ocorpus").create()); // The corpus on which operate options.addOption(OptionBuilder.withDescription( "Use all documents in repository as single document corpora, it can be sentence or paragraph based. (e.g. sentence).") .hasArgs().withArgName("type").isRequired(false).withLongOpt("oalldocs").create()); // The properties file for the corpus options.addOption(OptionBuilder.withDescription("Properties file with the corpus parameters (optional).") .hasArg().withArgName("parameter file").isRequired(false).withLongOpt("ocpar").create()); // Background knowledge corpus options.addOption(OptionBuilder.withDescription( "Lucene query that defines a background knowledge on which the corpus will be projected. (e.g. \"type:sentences AND reference:Document*\").") .hasArg().withArgName("query").isRequired(false).withLongOpt("obk").create()); // Background knowledge parameters options.addOption(OptionBuilder.withDescription( "Properties file with the background knowledge corpus parameters, if not set it will use the same as the corpus.") .hasArg().withArgName("parameter file").isRequired(false).withLongOpt("obkpar").create()); // Term selection String criteria = ""; for (TermSelection tsel : TermSelection.values()) { criteria += "," + tsel.name(); } criteria = criteria.substring(1); options.addOption(OptionBuilder.hasArgs().withArgName("name") .withDescription("Name of the Term selection criteria (" + criteria + ").").isRequired(false) .withValueSeparator(',').withLongOpt("otsel").create()); // Term selection threshold options.addOption(OptionBuilder.hasArgs().withArgName("number") .withDescription("Threshold for the tsel criteria option.").withType(Integer.TYPE).isRequired(false) .withValueSeparator(',').withLongOpt("otselth").create()); // Dimensionality reduction criteria = ""; for (DimensionalityReduction dim : DimensionalityReduction.values()) { criteria += "," + dim.name(); } criteria = criteria.substring(1); options.addOption(OptionBuilder.hasArgs().withArgName("list") .withDescription("Name of the Dimensionality Reduction criteria. (e.g. " + criteria + ").") .isRequired(false).withValueSeparator(',').withLongOpt("odim").create()); // Dimensionality reduction threshold options.addOption(OptionBuilder.hasArgs().withArgName("list") .withDescription("Threshold for the dim options. (e.g. 0,1,2).").isRequired(false) .withValueSeparator(',').withLongOpt("odimth").create()); // Local weight criteria = ""; for (LocalWeight weight : LocalWeight.values()) { criteria += "," + weight.name(); } criteria = criteria.substring(1); options.addOption(OptionBuilder.hasArgs().withArgName("list") .withDescription("Name of the Local Weight to apply. (e.g." + criteria + ").").isRequired(false) .withValueSeparator(',').withLongOpt("otwl").create()); // Global weight criteria = ""; for (GlobalWeight weight : GlobalWeight.values()) { criteria += "," + weight.name(); } criteria = criteria.substring(1); options.addOption(OptionBuilder.hasArgs().withArgName("list") .withDescription("Name of the Global Weight to apply. (e.g. " + criteria + ").").isRequired(false) .withValueSeparator(',').withLongOpt("otwg").create()); // Use Lanczos options.addOption(OptionBuilder.hasArg(false).withDescription("Use Lanczos for SVD decomposition.") .isRequired(false).withLongOpt("olanczos").create()); // Inserting documents in repository options.addOption(OptionBuilder.hasArg(false).withDescription("Insert documents into repository.") .isRequired(false).create("I")); // Max documents to insert options.addOption(OptionBuilder.hasArg().withArgName("number") .withDescription("Maximum number of documents to index or use in an operation.") .withType(Integer.TYPE).isRequired(false).withLongOpt("imaxdocs").create()); // Clean repository options.addOption( OptionBuilder.hasArg(false).withDescription("Empties the repository before inserting new ones.") .isRequired(false).withLongOpt("iclean").create()); // Use annotator options.addOption(OptionBuilder.hasArgs() .withDescription( "List of annotators to use when inserting the documents. (e.g. PennTreeAnnotator).") .isRequired(false).withValueSeparator(',').withLongOpt("iannotators").create()); // Documents folder options.addOption(OptionBuilder.hasArg().withArgName("folder") .withDescription("The folder that contains the documens to insert.").isRequired(false) .withLongOpt("idocs").create()); // Initializing the line parser CommandLineParser parser = new PosixParser(); try { line = parser.parse(options, args); } catch (ParseException e) { printHelp(options); return; } // Validate that either inserting or an operation are given if (!line.hasOption("I") && !line.hasOption("O")) { System.out.println("One of the options -I or -O must be present."); printHelp(options); return; } repositoryFolder = line.getOptionValue("repo"); try { if (line.hasOption("I")) { indexing(); } else if (line.hasOption("O")) { operation(); } } catch (ParseException e) { System.out.println(e.getMessage()); printHelp(options); return; } System.out.println("TML finished successfully in " + (System.nanoTime() - time) * 10E-9 + " seconds."); return; }