List of usage examples for org.apache.commons.cli Option getOpt
public String getOpt()
From source file:org.mitre.ccv.mapred.CompleteCompositionVectors.java
/** * * The JSO data will be the same as {@link org.mitre.ccv.CompleteMatrix#jsonCompleteMatrix}, but the features * will be in a different order. This version, by default sorts, only by entropy values, whereas the * ccv in-memory version sorts by the k-mer natural order (i.e., lexigraphic). * @param argv/*from w w w . j av a2s .co m*/ * @return * @throws java.lang.Exception */ @Override @SuppressWarnings("static-access") // For OptionBuilder public int run(String[] argv) throws Exception { JobConf conf = new JobConf(getConf()); String cli_title = "CompleteCompositionVectorHadoop"; int start = CalculateKmerCounts.DEFAULT_START; int end = CalculateKmerCounts.DEFAULT_END; int topkmers = 0; String input = null; String output = null; String vectorJsonOutput = null; //String kmerJsonOutput = null; boolean cleanLogs = false; /** create the Options */ Options options = new Options(); /** Hadoop Options */ options.addOption( OptionBuilder.withArgName("number").hasArg(true).withDescription("number of maps").create("m")); options.addOption( OptionBuilder.withArgName("number").hasArg(true).withDescription("number of reducers").create("r")); // org.hadoop.util.GenericOptionsParser should captures this, but it doesn't options.addOption(OptionBuilder.withArgName("property=value").hasArg(true).withValueSeparator() .withDescription("use value for given property").create("D")); /** CompleteCompositionVector Options */ options.addOption(OptionBuilder.withArgName("number").hasArg(true) .withDescription("number of top k-mers to use in calculations").create("topKmers")); options.addOption(OptionBuilder.withArgName("start").hasArg(true).withDescription("starting length of tile") .create("start")); options.addOption(OptionBuilder.withArgName("end").hasArg(true).withDescription("ending length of title") .create("end")); options.addOption(OptionBuilder.hasArg(true).withArgName("file") .withDescription("JSON file to write out k-mers to").create("kmersfile")); options.addOption(OptionBuilder.hasArg(true).withArgName("file") .withDescription("JSON file to write out feature vectors to " + "(Overrides kmersout, only one file will be written).") .create("vectorsfile")); options.addOption(OptionBuilder.withArgName("number").hasArg(true) .withDescription("What preference to use: 0-min 1-median 2-avg(min,med): default is median") .create("prefval")); options.addOption(OptionBuilder.withArgName("help").hasArg(false).withDescription("print this message") .create("help")); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); //GenericOptionsParser gop = new GenericOptionsParser(conf, options, argv); GenericOptionsParser gop = new GenericOptionsParser(conf, argv); String[] remaining_args = gop.getRemainingArgs(); // create the parser CommandLineParser parser = new GnuParser(); //CommandLine line = gop.getCommandLine(); String[] other_args = new String[] {}; try { CommandLine line = parser.parse(options, remaining_args); other_args = line.getArgs(); // Make sure there is a parameter left. if (other_args.length == 0) { System.out.println(cli_title); System.out.println("Missing input path!"); formatter.printHelp("hccv [options] <input> [<output>] ", options); GenericOptionsParser.printGenericCommandUsage(System.out); return -1; } Option[] opts = line.getOptions(); if (line.hasOption("help")) { System.out.println(cli_title); formatter.printHelp("hccv [options] <input> [<output>] ", options); GenericOptionsParser.printGenericCommandUsage(System.out); return -1; } // could also use line.iterator() for (Option opt : opts) { if (opt.getOpt().equals("m")) { conf.setNumMapTasks(Integer.parseInt(opt.getValue())); } if (opt.getOpt().equals("r")) { conf.setNumReduceTasks(Integer.parseInt(opt.getValue())); } if (opt.getOpt().equals("D")) { // We can have multiple properties we want to set String[] properties = opt.getValues(); for (String property : properties) { String[] keyval = property.split("="); conf.set(keyval[0], keyval[1]); } } if (opt.getOpt().equals("start")) { start = Integer.parseInt(opt.getValue()); } if (opt.getOpt().equals("end")) { end = Integer.parseInt(opt.getValue()); } if (opt.getOpt().equals("topKmers")) { topkmers = Integer.parseInt(opt.getValue()); } if (opt.getOpt().equals("vectorsfile")) { vectorJsonOutput = opt.getValue(); } } } catch (ParseException e) { LOG.warn("options parsing faild: " + e.getMessage()); System.out.println(cli_title); formatter.printHelp("hccv [options] <input> [<output>] ", options); GenericOptionsParser.printGenericCommandUsage(System.out); } if (start <= 2) { throw new IllegalArgumentException("Value of 'start' argument must be larger than 2"); } input = other_args[0]; if (other_args.length < 2) { output = input + "_" + FileUtils.getSimpleDate(); } else { output = other_args[2]; } /** * Check output path. Either needs to exist as a directory or not exist */ Path outputPath = new Path(output); FileSystem fs = outputPath.getFileSystem(conf); if (!fs.exists(outputPath)) { fs.mkdirs(outputPath); } else if (fs.exists(outputPath) || !fs.getFileStatus(outputPath).isDir()) { LOG.fatal(String.format("Output directory %s already exists", outputPath.makeQualified(fs))); throw new FileAlreadyExistsException( String.format("Output directory %s already exists", outputPath.makeQualified(fs))); } String outputDir = output + Path.SEPARATOR; int res; /** * Zero, CalculateCompositionVectors */ LOG.info("Starting CalculateCompositionVectors Map-Reduce job"); CalculateCompositionVectors cv = new CalculateCompositionVectors(); res = cv.initJob(conf, start, end, input, outputDir + COMPOSITION_VECTORS, cleanLogs); if (res != 0) { LOG.info("CalculateCompositionVectors returned non-zero result!"); return res; } // We can stop now or continue to reduce dimensionallity using RRE or other means /** * First, CalculateKmerCounts */ LOG.info("Starting CalculateKmerCounts Map-Reduce job"); // FastMap option for CalculateKmers!?! CalculateKmerCounts ckc = new CalculateKmerCounts(); res = ckc.initJob(conf, start, end, input, outputDir + KMER_COUNTS); if (res != 0) { LOG.fatal("CalculateKmerCounts returned non-zero result!"); return res; } /** * Second, TotalSequenceLength */ LOG.info("Starting TotalSequenceLength Map-Reduce job"); TotalSequenceLength tsl = new TotalSequenceLength(); res = tsl.initJob(conf, input, outputDir + TOTAL_LENGTH, cleanLogs); if (res != 0) { LOG.fatal("TotalSequenceLength returned non-zero result!"); return res; } int length = tsl.getCount(conf, outputDir + TOTAL_LENGTH); if (length < 3) { LOG.fatal("TotalSequenceLength returned a total sequence length of less than 3."); return -1; } else { LOG.info(String.format("TotalSequenceLength returned a total sequence length of %d.", length)); } /** * Third, CalculateKmerProbabilities */ LOG.info("Starting CalculateKmerProbabilities Map-Reduce job"); CalculateKmerProbabilities ckp = new CalculateKmerProbabilities(); res = ckp.initJob(conf, start, end, length, outputDir + KMER_COUNTS, outputDir + KMER_PROBABILITIES, cleanLogs); if (res != 0) { LOG.fatal("CalculateKmerProbabilities returned non-zero result!"); return res; } /** * Fourth, InvertKmerProbabilities */ LOG.info("Starting InvertKmerProbabilities Map-Reduce job"); InvertKmerProbabilities ikp = new InvertKmerProbabilities(); res = ikp.initJob(conf, outputDir + KMER_PROBABILITIES, outputDir + INVERTED_KMER_PROBABILITIES, cleanLogs); if (res != 0) { LOG.fatal("InvertKmerProbabilities returned non-zero result!"); return res; } /** * Fifth, CalculateKmerPiValues */ LOG.info("Starting CalculateKmerPiValues Map-Reduce job"); CalculateKmerPiValues kpv = new CalculateKmerPiValues(); res = kpv.initJob(conf, start, end, outputDir + INVERTED_KMER_PROBABILITIES, outputDir + KMER_PI_VALUES, cleanLogs); if (res != 0) { LOG.fatal("CalculateKmerPiValues returned non-zero result!"); return res; } /** * Sixth,CalculateKmerRevisedRelativeEntropy */ LOG.info("Starting CalculateKmerRevisedRelativeEntropy Map-Reduce job"); CalculateKmerRevisedRelativeEntropy krre = new CalculateKmerRevisedRelativeEntropy(); res = krre.initJob(conf, outputDir + KMER_PI_VALUES, outputDir + COMPOSITION_VECTORS, outputDir + ENTROPY_VALUES, cleanLogs); if (res != 0) { LOG.fatal("CalculateKmerRevisedRelativeEntropy returned non-zero result!"); return res; } /** * Seventh, SortKmerRevisedRelativeEntropies */ SortKmerRevisedRelativeEntropies srre = new SortKmerRevisedRelativeEntropies(); res = srre.initJob(conf, outputDir + ENTROPY_VALUES, outputDir + SORTED_ENTROPY_VALUES, cleanLogs); if (res != 0) { LOG.fatal("SortKmerRevisedRelativeEntropies returned non-zero result!"); return res; } /** * Eigth, GenerateFeatureVectors * * Generate a flatten list to add to the cache to be distributed to the map-tasks. */ Path listOutputPath = new Path(outputDir + Integer.toString(topkmers) + KMER_ENTROPY_SET); LOG.info(String.format("Loading %d sorted k-mers from %s to %s", topkmers, outputDir + SORTED_ENTROPY_VALUES, listOutputPath.toString())); int num = CompleteCompositionVectorUtils.flattenKmerEntropySequenceFile(conf, topkmers, outputDir + SORTED_ENTROPY_VALUES, listOutputPath.toString(), cleanLogs); if (num != topkmers) { LOG.fatal(String.format("Requested %d k-mers, but got %d. Using %d", topkmers, num, num)); topkmers = num; } GenerateFeatureVectors fv = new GenerateFeatureVectors(); res = fv.initJob(conf, listOutputPath.toString(), topkmers, outputDir + COMPOSITION_VECTORS, outputDir + FEATURE_VECTORS, cleanLogs); if (res != 0) { LOG.fatal("GenerateFeatureVectors returned non-zero result!"); return res; } /** * Save feature vectors, features (k-mers), and properties to a JSON file. * * The data will be the same as {@link org.mitre.ccv.CompleteMatrix#jsonCompleteMatrix}, but the features * will be in a different order. This version, by default sorts, only by entropy values, whereas the * ccv in-memory version sorts by the k-mer natural order (i.e., lexigraphic). */ if (vectorJsonOutput != null && vectorJsonOutput.length() > 0) { LOG.info("Writing features out to " + vectorJsonOutput); CompleteCompositionVectorUtils.featureVectors2Json(conf, start, end, topkmers, outputDir + SORTED_ENTROPY_VALUES, outputDir + FEATURE_VECTORS, vectorJsonOutput); } LOG.info("All done generating complete composition vectors and feature vectors."); return res; }
From source file:org.mitre.ccv.weka.CompositionCompositionVectorClassifiers.java
/** * Min things needed://from ww w .j ava 2 s . c o m * 1) a json file with ccv params, nmers and vectors, and a fasta file with * samples to classify * 2) a json file with ccv params and nmers, a classifier file, and a fasta file * with samples to classify * * @param argv * @throws java.lang.Exception */ @SuppressWarnings("static-access") public static void main(String[] argv) throws FileNotFoundException, JSONException { CompositionCompositionVectorClassifiers ccvc = new CompositionCompositionVectorClassifiers(); /** JSON file with data set. */ FileReader dataSetReader = null; /** Optional sequences to generate ccvs and classify. */ FastaIterator seqIter = null; /** Optional filename to output the classifier to. */ String outputModelFileName = null; /** Optional filename to input the classifer from. */ String inputModelFileName = null; /** Optional filename (also need a JSON data set) to input sequence data from. */ String inputDataFileName = null; /** Optional filename for the JSON data set containing features and window sizes. */ String inputJsonFileName = null; /** If set, do cross-validation numFolds and quit. */ Integer numFolds = null; /** How to parse the sample name */ int nameParser = 1; /** Limit the max length of sequences processed */ Integer limitLength = null; /** What we are */ String cli_title = APPLICATION_TITLE + " [build: " + APPLICATION_BUILD + "]\n(C) Copyright 2007-2009, by The MITRE Corporation.\n"; /** create the Options */ Options options = new Options(); options.addOption(OptionBuilder.withArgName("file").hasArg(true) .withDescription( "JSON file with ccv " + "parameters, nmers, and vectors for generating " + "the classifier") .create("dataset")); options.addOption(OptionBuilder.withArgName("file").hasArg(true) .withDescription("a saved classifier (must use the same classifier)" + "(dataset then only needs parameters and nmers. " + "Vectors are no longer needed generating) ") .create("inputModel")); options.addOption(OptionBuilder.withArgName("file").hasArg(true) .withDescription("Output the generated tree " + "to a file as binary" + "(optional)") .create("outputModel")); options.addOption( OptionBuilder.withArgName("numFolds").hasArg(true) .withDescription("Cross validate the generated model " + "using the given training set. No final model " + "will be outputed or samples classified. " + "(optional)") .create("crossValidate")); options.addOption(OptionBuilder.withArgName("file").hasArg(true) .withDescription("file with samples" + " to generate ccvs and classify (optional)") .create("samples")); options.addOption(OptionBuilder.withArgName("number").hasArg(true).withDescription( "what name to use: 1-name(default);2-description;3-full header(might break newick-style trees)") .create("name")); options.addOption(OptionBuilder.withArgName("number").hasArg(true) .withDescription("limits the max length of the input samples processed").create("limitLength")); options.addOption(OptionBuilder.withArgName("help").hasArg(false).withDescription("print this message") .create("help")); options.addOption(OptionBuilder.withArgName("level").hasArg(true).withDescription( "Set the logging (verbosity) level: OFF, FATAL, ERROR, WARN, INFO, DEBUG. TRACE, ALL (none to everything)") .create("verbosity")); options.addOption(OptionBuilder.withArgName("property=value").hasArgs().withValueSeparator() .withDescription("use value for given property").create('D')); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); // create the parser CommandLineParser parser = new GnuParser(); // parse the command line arguments CommandLine line; try { line = parser.parse(options, argv); if (line.hasOption("help") || line.hasOption("h")) { USAGE(cli_title, formatter, options); System.exit(0); // they asked for help } if (line.getOptions().length == 0) { USAGE(cli_title, formatter, options); System.exit(-1); // we need some options } if (line.hasOption("verbosity")) { // if this fails then they get DEBUG! ccvc.setLoggingLevel(Level.toLevel(line.getOptionValue("verbosity"))); } Option[] opts = line.getOptions(); for (Option opt : opts) { if (opt.getOpt().equals("D")) { String propertyName = opt.getValue(0); String propertyValue = opt.getValue(1); System.setProperty(propertyName, propertyValue); continue; } if (opt.getOpt().equals("dataset")) { inputJsonFileName = line.getOptionValue("dataset"); continue; } if (opt.getOpt().equals("inputModel")) { inputModelFileName = line.getOptionValue("inputModel"); continue; } if (opt.getOpt().equals("outputModel")) { outputModelFileName = line.getOptionValue("outputModel"); continue; } if (opt.getOpt().equals("samples")) { inputDataFileName = line.getOptionValue("samples"); continue; } if (opt.getOpt().equals("crossValidate")) { try { numFolds = Integer.parseInt(line.getOptionValue("crossValidate")); } catch (NumberFormatException nfe) { LOG.warn("Error while parsing number of fold cross validate", nfe); System.exit(-1); } continue; } if (line.hasOption("name")) { try { nameParser = Integer.parseInt(line.getOptionValue("name")); } catch (NumberFormatException nfe) { throw new ParseException("Error parsing 'name' option. Reason: " + nfe.getMessage()); } } //"limitLength" if (line.hasOption("limitLength")) { try { limitLength = Integer.parseInt(line.getOptionValue("limitLength")); } catch (NumberFormatException nfe) { throw new ParseException("Error parsing 'limitLength' option. Reason: " + nfe.getMessage()); } } } // for opts } catch (ParseException pex) { System.err.println("Error while parse options\n" + pex.getMessage()); USAGE(cli_title, formatter, options); System.exit(-1); } /** Print out who we are */ LOG.info(cli_title); /** Do we have a saved model? */ if (inputModelFileName != null && numFolds == null) { LOG.info(String.format("Loading previous model from '%s'", inputModelFileName)); ccvc.loadClassifierFromModel(inputModelFileName); // we cannot cross-validate because we no longer have the instance data! // @todo: can we set the classifier class at the same time? } else if (inputJsonFileName != null) { /** * Load the dataset and process the sequecnes */ LOG.info("Loading data set from '" + inputJsonFileName + "'"); dataSetReader = new FileReader(inputJsonFileName); JSONObject jsonDataSet = new JSONObject(JsonLoader.getJsonString(dataSetReader)); try { dataSetReader.close(); } catch (IOException ioe) { LOG.warn("Error while closing file reader!"); } ccvc.loadClassifierFromData(jsonDataSet); if (numFolds != null) { LOG.info(String.format("Cross-validating model %d fold using training data....", numFolds)); ccvc.classifier.crossValidateModel(ccvc.classifier.getClassifier(), ccvc.classifier.getInstances(), numFolds); /** Exit, we only do cross validation */ LOG.info("Done."); System.exit(0); } /** * Train/Build the classifier - move this to a method */ LOG.info(String.format("Building the %s classifier...", ccvc.classifier.getClassiferName())); try { ccvc.classifier.buildClassifier(); } catch (Exception ex) { LOG.fatal("Error while building the classifier with the given dataset", ex); throw new RuntimeException(); } /** * Save it? */ if (outputModelFileName != null) { LOG.info("Saving classifier model to '" + outputModelFileName + "'"); try { ccvc.classifier.saveModelObject(outputModelFileName); } catch (IOException ioe) { LOG.warn("IO error while saving model", ioe); } catch (Exception ex) { LOG.fatal("Unknown error", ex); throw new RuntimeException(); } } } else { LOG.fatal("Unknown set of options!"); System.out.println(cli_title); formatter.printHelp(cli_title + " options ", options); System.exit(-1); } /** Check to see if we loaded a classifier!*/ if (ccvc.classifier == null) { LOG.fatal("Somehow we didn't load a classifier!"); throw new RuntimeException(); } /** * Do we have samples to classify? */ if (inputDataFileName == null) { LOG.info("No samples to classify. Quiting."); return; } BufferedReader br = new BufferedReader(new FileReader(inputDataFileName)); seqIter = new FastaIterator(br); if (seqIter != null) { /** Get the ccv begin and end */ Integer begin = ccvc.classifier.getBegin(); Integer end = ccvc.classifier.getEnd(); /** * no way to get FastVector of attirbutes from an Instances Object? */ Attribute classAttribute = (Attribute) ccvc.classifier.getAttributes() .elementAt(ccvc.classifier.getClassIndex()); Integer cv = 0; /** Load and generate CCVs */ while (seqIter.hasNext()) { cv++; Sequence s = null; try { s = seqIter.next(); } catch (NoSuchElementException nsee) { //System.err.println("Iteration error in sequence file!\n " + e.getMessage()); LOG.fatal("Iteration error in sequence file!", nsee); throw new RuntimeException(); } String seqString = s.seqString(); String seqName = CompleteCompositionVectorMain.parseSequenceName(s, nameParser); /** Check the length of the sequence */ if (limitLength != null && seqString.length() > limitLength) { LOG.info(String.format( "Skipping sample '%s' because it is longer (%d) than the limit length (%d)", seqName, seqString.length(), limitLength)); continue; } /** Generate the complete composition vector for this sample */ IndexedCompositionDistribution cd; try { cd = new IndexedCompositionDistribution(new DistributionIndex(), cv, seqString, begin, end); } catch (IllegalArgumentException e) { LOG.warn(String.format( "Composition distribution error on '%s'" + "(potentially to small of a sequence '%d')!", s.getName(), seqString.length()), e); continue; } CompleteCompositionVector ccv = new IndexedCompleteCompositionVector(seqName, cv, begin, end, cd); /** Generate an instance for this */ Instance inst; try { inst = ccvc.classifier.getInstanceSparse(ccv); } catch (Exception ex) { LOG.warn("Error while getting instance! Skipping...", ex); continue; } /** To classify, we need to be part of a DataSet/Instance */ try { LabeledInstance li = ccvc.classifier.runClassifier(inst, classAttribute); double[] clsDist = ccvc.classifier.getClassifier().distributionForInstance(inst); int clsValue = (int) li.inst.classValue(); System.out.printf("%s\t%s\t%f\n", s.getName(), classAttribute.value(clsValue), li.clsDist[clsValue]); /* Below outputs all the confidence values for all the classes. StringBuffer sb = new StringBuffer(); for (int i = 0; i < clsDist.length; i++) { sb.append(clsDist[i]); if (i + 1 < clsDist.length) { sb.append(", "); } } System.out.printf("%s\t%s\t[%s]\n", seqName, classAttribute.value(clsValue), sb.toString()); */ } catch (Exception ex) { LOG.warn(String.format("Error while classifying sample '%s' (# %d)", seqName, cv)); } } } }
From source file:org.mitre.scap.xccdf.XCCDFInterpreter.java
/** * @param args the command line arguments *//*from w ww .j a v a 2 s. co m*/ public static void main(String[] args) throws IOException, XmlException, URISyntaxException { XCCDFInterpreter.generateExecutionTimeStr(); BuildProperties buildProperties = BuildProperties.getInstance(); //System.out.println(); //System.out.println( buildProperties.getApplicationName()+" v"+ buildProperties.getApplicationVersion()+" build "+buildProperties.getApplicationBuild()); //System.out.println("--------------------"); //outputOsProperties(); //System.out.println("--------------------"); //System.out.println(); // Define the commandline options @SuppressWarnings("static-access") Option help = OptionBuilder.withDescription("display usage").withLongOpt("help").create('h'); @SuppressWarnings("static-access") Option workingDir = OptionBuilder.hasArg().withArgName("FILE").withDescription("use result directory FILE") .withLongOpt("result-dir").create('R'); @SuppressWarnings("static-access") Option xccdfResultFilename = OptionBuilder.hasArg().withArgName("FILENAME") .withDescription("use result filename FILENAME").withLongOpt("xccdf-result-filename").create("F"); @SuppressWarnings("static-access") Option nocpe = OptionBuilder.withDescription("do not process CPE references").withLongOpt("no-cpe") .create(); @SuppressWarnings("static-access") Option noresults = OptionBuilder.withDescription("do not display rule results").withLongOpt("no-results") .create(); @SuppressWarnings("static-access") Option nocheck = OptionBuilder.withDescription("do not process checks").withLongOpt("no-check").create(); @SuppressWarnings("static-access") Option profile = OptionBuilder.hasArg().withArgName("PROFILE").withDescription("use given profile id") .withLongOpt("profile-id").create('P'); @SuppressWarnings("static-access") Option ssValidation = OptionBuilder.hasArg().withArgName("SS-VALIDATION") .withDescription("use given validation id").withLongOpt("ssValidation-id").create("S"); @SuppressWarnings("static-access") Option cpeDictionary = OptionBuilder.hasArg().withArgName("FILE") .withDescription("use given CPE 2.0 Dictionary file").withLongOpt("cpe-dictionary").create('C'); @SuppressWarnings("static-access") Option cpeOVALDefinition = OptionBuilder.hasArg().withArgName("FILE") .withDescription("use given CPE OVAL definition file for CPE evaluation").withLongOpt("cpe-oval") .create('c'); @SuppressWarnings("static-access") Option verbose = OptionBuilder.withDescription("produce verbose output").create("v"); // Build the options list Options options = new Options(); options.addOption(help); options.addOption(workingDir); options.addOption(xccdfResultFilename); options.addOption(profile); options.addOption(ssValidation); options.addOption(nocpe); options.addOption(noresults); options.addOption(nocheck); options.addOption(cpeDictionary); options.addOption(cpeOVALDefinition); options.addOption(verbose); // create the parser CommandLineParser parser = new GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); String[] remainingArgs = line.getArgs(); if (line.hasOption("help") || remainingArgs.length != 1) { if (remainingArgs.length != 1) { System.err.print("Invalid arguments: "); for (String arg : remainingArgs) { System.err.print("'" + arg + "' "); } System.out.println(); } // automatically generate the help statement System.out.println(); showHelp(options); System.exit(0); } File xccdfFile = new File(remainingArgs[0]); if (!xccdfFile.exists()) { System.err.println( "!! the specified XCCDF file '" + xccdfFile.getAbsolutePath() + "' does not exist!"); System.exit(1); } XCCDFInterpreter interpreter = new XCCDFInterpreter(xccdfFile.getCanonicalFile()); //System.out.println("** validating XCCDF content"); if (!interpreter.validate()) { System.err.println("!! the XCCDF document is invalid. aborting."); System.exit(8); } if (line.hasOption(verbose.getOpt())) { verboseOutput = true; interpreter.setVerboseOutput(true); } if (line.hasOption(workingDir.getOpt())) { String lineOpt = line.getOptionValue(workingDir.getOpt()); String workingDirValue = (lineOpt == null) ? "" : lineOpt; File f = new File(workingDirValue); if (!f.exists()) { if (verboseOutput) System.out.println("** creating directory: " + f.getAbsolutePath()); if (!f.mkdirs()) { System.err.println("!! unable to create the result directory: " + f.getAbsolutePath()); System.exit(2); } } if (!f.isDirectory()) { System.err.println("!! the path specified for the result directory is not a directory: " + f.getAbsolutePath()); System.exit(3); } if (!f.canWrite()) { System.err.println("!! the path specified for the result directory is not writable: " + f.getAbsolutePath()); System.exit(4); } interpreter.setResultDirectory(f); } if (line.hasOption(xccdfResultFilename.getOpt())) { interpreter.setXccdfResultsFilename(line.getOptionValue(xccdfResultFilename.getOpt())); } if (line.hasOption(profile.getOpt())) { interpreter.setProfileId(line.getOptionValue(profile.getOpt())); } if (line.hasOption(ssValidation.getOpt())) { interpreter.setssValidationId(line.getOptionValue(ssValidation.getOpt())); } if (line.hasOption(nocpe.getLongOpt())) { interpreter.setProcessCPE(false); } if (line.hasOption(noresults.getLongOpt())) { interpreter.setDisplayResults(false); } if (line.hasOption(nocheck.getLongOpt())) { interpreter.setProcessChecks(false); } if (interpreter.processCPE == true) { if (line.hasOption(cpeDictionary.getOpt())) { String lineOpt = line.getOptionValue(cpeDictionary.getOpt()); String cpeDict = (lineOpt == null) ? "" : lineOpt; File f = new File(cpeDict); if (!f.exists()) { System.err.println("The CPE dictionary file does not exist: " + f.getAbsolutePath()); System.exit(5); } if (!f.isFile()) { System.err.println("The path specified for the CPE dictionary file is not a file: " + f.getAbsolutePath()); System.exit(6); } if (!f.canRead()) { System.err.println("The path specified for the CPE dictionary file is not readable: " + f.getAbsolutePath()); System.exit(7); } interpreter.setCPEDictionaryFile(f); } if (line.hasOption(cpeOVALDefinition.getOpt())) { String lineOpt = line.getOptionValue(cpeOVALDefinition.getOpt()); String cpeOVAL = (lineOpt == null) ? "" : lineOpt; File f = new File(cpeOVAL); if (!f.exists()) { System.err.println( "!! the CPE OVAL inventory definition file does not exist: " + f.getAbsolutePath()); System.exit(5); } if (!f.isFile()) { System.err.println( "!! the path specified for the CPE OVAL inventory definition file is not a file: " + f.getAbsolutePath()); System.exit(6); } if (!f.canRead()) { System.err.println( "!! the path specified for the CPE OVAL inventory definition file is not readable: " + f.getAbsolutePath()); System.exit(7); } interpreter.setCPEOVALDefinitionFile(f); } } // END IF processCPE interpreter.process(); } catch (ParseException ex) { System.err.println("!! parsing failed : " + ex.getMessage()); System.out.println(); showHelp(options); } catch (ProfileNotFoundException ex) { if (verboseOutput == true) ex.printStackTrace(); else System.err.println("!! checklist processing failed : " + ex.getMessage()); } catch (CircularReferenceException ex) { System.err.println("!! checklist processing failed : " + ex.getMessage()); if (verboseOutput == true) ex.printStackTrace(); else System.err.println("!! checklist processing failed : " + ex.getMessage()); } catch (ExtensionScopeException ex) { if (verboseOutput == true) ex.printStackTrace(); else System.err.println("!! checklist processing failed : " + ex.getMessage()); } catch (ItemNotFoundException ex) { if (verboseOutput == true) ex.printStackTrace(); else System.err.println("!! checklist processing failed : " + ex.getMessage()); } catch (PropertyNotFoundException ex) { if (verboseOutput == true) ex.printStackTrace(); else System.err.println("!! checklist processing failed : " + ex.getMessage()); } catch (CPEEvaluationException ex) { if (verboseOutput == true) ex.printStackTrace(); else System.err.println("!! checklist processing failed : " + ex.getMessage()); } catch (Exception ex) { if (verboseOutput == true) ex.printStackTrace(); else System.err.println("!! checklist processing failed : " + ex.getMessage()); } }
From source file:org.mitre.secretsharing.cli.cmd.AbstractCommand.java
protected String checkArgument(CommandLine cmd, Option o) { String invalid = ""; if (!requiredArguments().contains(o)) return invalid; if ((o.getOpt() == null || !cmd.hasOption(o.getOpt().charAt(0))) && !cmd.hasOption(o.getLongOpt())) { if (o.getOpt() != null) invalid += "-" + o.getOpt() + ","; invalid += "--" + o.getLongOpt(); if (o.hasArg()) invalid += " <" + o.getArgName() + ">"; invalid += " is missing.\n"; }/*from w ww . j a v a2 s.c o m*/ return invalid; }
From source file:org.mule.util.SystemUtils.java
/** * Returns a Map of all options in the command line. The Map is keyed off the * option name. The value will be whatever is present on the command line. * Options that don't have an argument will have the String "true". *//* w w w .jav a2 s . c om*/ // TODO MULE-1947 Command-line arguments should be handled exclusively by the bootloader public static Map<String, Object> getCommandLineOptions(String args[], String opts[][]) throws DefaultMuleException { CommandLine line = parseCommandLine(args, opts); Map<String, Object> ret = new HashMap<String, Object>(); Option[] options = line.getOptions(); for (int i = 0; i < options.length; i++) { Option option = options[i]; ret.put(option.getOpt(), option.getValue("true")); } return ret; }
From source file:org.northrop.leanne.publisher.Main.java
public static void main(String[] args) { CommandLineParser parser = new GnuParser(); try {/*w w w . java 2 s . c o m*/ // parse the command line arguments CommandLine line = parser.parse(options, args); if (args.length == 0 || line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("pub", options); } else if (line.hasOption("version")) { URLClassLoader cl = (URLClassLoader) Main.class.getClassLoader(); String title = ""; String version = ""; String date = ""; try { URL url = cl.findResource("META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(url.openStream()); Attributes attr = manifest.getMainAttributes(); title = attr.getValue("Implementation-Title"); version = attr.getValue("Implementation-Version"); date = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.MEDIUM) .format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(attr.getValue("Built-Date"))); } catch (Exception e) { e.printStackTrace(); } System.out.println("------------------------------------------------------------"); System.out.println("Publisher Pipeline " + version); System.out.println("------------------------------------------------------------"); System.out.println(""); System.out.println(title + " build time " + date); System.out.println("Java: " + System.getProperty("java.version")); System.out.println("JVM: " + System.getProperty("java.vendor")); System.out.println("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch")); } else { Option[] options = line.getOptions(); Binding binding = new Binding(); binding.setVariable("home", System.getProperty("pub.home")); binding.setVariable("inputDir", System.getProperty("pub.home") + "/input"); binding.setVariable("outputDir", System.getProperty("pub.home") + "/output"); binding.setVariable("appName", System.getProperty("program.name")); binding.setVariable("isdebug", false); for (int i = 0; i < options.length; i++) { Option opt = options[i]; binding.setVariable("is" + opt.getOpt(), true); } String[] roots = new String[] { System.getProperty("pub.home") + "/resources/scripts", System.getProperty("pub.home") + "/resources/scripts/formats" }; ClassLoader parent = Main.class.getClassLoader(); GroovyScriptEngine gse = new GroovyScriptEngine(roots, parent); if (!line.hasOption("rerun")) { gse.run("prep.groovy", binding); } for (String name : getFormats()) { if (line.hasOption(name.toLowerCase())) { String file = ("" + name.charAt(0)).toLowerCase() + name.substring(1) + ".groovy"; gse.run(file, binding); } } } } catch (ParseException exp) { System.err.println("Command line parsing failed. Reason: " + exp.getMessage()); } catch (ResourceException resourceError) { System.err.println("Groovy script failed. Reason: " + resourceError.getMessage()); } catch (IOException ioError) { System.err.println("Groovy script failed. Reason: " + ioError.getMessage()); } catch (ScriptException error) { System.err.println("Groovy script failed. Reason: " + error.getMessage()); error.printStackTrace(); } }
From source file:org.nuunframework.cli.NuunCliPlugin.java
private Map<Class<?>, Options> createOptions(Collection<Class<?>> collection) { Set<String> shortOptions = Sets.newHashSet(); Set<String> longOptions = Sets.newHashSet(); Map<Class<?>, Options> optionsMap = Maps.newHashMap(); for (Class<?> class1 : collection) { logger.info("CLASS " + class1.getSimpleName()); Set<Field> fields = annotatedFields(class1, NuunOption.class); Options internalOptions = new Options(); for (Field field : fields) { logger.info("Class : " + field.getDeclaringClass().getSimpleName() + " / " + field.getName()); Option option = createOptionFromField(field); if (!Strings.isNullOrEmpty(option.getOpt()) && shortOptions.contains(option.getOpt())) { exception("Short option " + option.getOpt() + " already exists!"); }/*from w w w . ja v a 2s. c o m*/ if (!Strings.isNullOrEmpty(option.getLongOpt()) && longOptions.contains(option.getLongOpt())) { exception("Long option " + option.getLongOpt() + " already exists!"); } if (Strings.isNullOrEmpty(option.getOpt()) && Strings.isNullOrEmpty(option.getLongOpt())) { exception("NuunOption defined on " + field + " has no opt nor longOpt."); } internalOptions.addOption(option); // global one optionsAggregated.addOption(option); shortOptions.add(option.getOpt()); longOptions.add(option.getLongOpt()); } optionsMap.put(class1, internalOptions); } return optionsMap; }
From source file:org.obiba.bitwise.client.BitwiseClient.java
/** * Adds a new command to the shell.//from w w w . ja v a 2 s . co m * @param command */ public void registerCommand(CliCommand command) { Option o = command.getOption(); commandMap.put(o.getOpt(), command); options.addOption(o); }
From source file:org.obiba.bitwise.client.BitwiseClient.java
/** * Activates the command line client by providing a BitwiseStore object. * @param pStore is the BitwiseStore to be queried * @throws IOException/* w ww . j a va 2s . co m*/ */ public void execute(BitwiseStore store) throws IOException { //Start command line client BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BasicParser bp = new BasicParser(); //Prepare ClientContext ClientContext context = new ClientContext(); context.setStore(store); System.out.println("Type '-h' for help, '-q' to quit."); //Loop as long as there are no options asking to quit boolean quit = false; while (!quit) { store = context.getStore(); //Store might have been switched prompt(context); String str = br.readLine(); CommandLine cl = null; try { cl = bp.parse(options, str.split(" ")); } catch (ParseException e) { quit = help.execute(null, context); } if (cl != null) { Iterator<Option> commands = cl.iterator(); while (commands.hasNext()) { Option o = commands.next(); CliCommand c = commandMap.get(o.getOpt()); if (c == null) { System.err.println("Cannot find command for option [" + o + "]"); quit = help.execute(null, context); } else { try { quit = c.execute(o, context); } catch (ParseException e) { quit = help.execute(null, context); } } } //The given command is a query, as there are no options specified if (cl.getOptions() == null || cl.getOptions().length == 0) { try { QueryParser parser = new QueryParser(); String[] args = cl.getArgs(); String queryString = StringUtil.aggregate(args, " "); if (StringUtil.isEmptyString(queryString) == false) { long start = System.currentTimeMillis(); Query q = parser.parse(queryString); QueryResult qr = q.execute(context.getStore()); context.setLastResult(qr); long end = System.currentTimeMillis(); //Prepare result display on screen List<String> fieldList = new Vector<String>(); //Filter out template fields for (String field : store.getFieldList()) { if (field.matches(".*_\\d+")) { continue; } fieldList.add(field); } ResultDisplay rd = new ResultDisplay(fieldList); // rd.setDisplayType(ResultDisplay.DisplayType.PLAIN); int hitIndex = qr.next(0); while (hitIndex != -1) { rd.putRecord(store, hitIndex); hitIndex = qr.next(hitIndex + 1); } //Display results in console System.out.println(rd.getOutput()); System.out.println(qr.count() + " results in " + (end - start) + " milliseconds.\n"); } } catch (org.obiba.bitwise.query.ParseException e) { System.err.println(e.getMessage()); } catch (Exception e) { e.printStackTrace(); } } } } }
From source file:org.obiba.genobyte.cli.BitwiseCli.java
/** * Adds a {@link CliCommand} to the set of registered commands. If a command * with the same short or long option string is already registered, an IllegalArgumentException is thrown. * @param command the command to register. * @throws IllegalArgumentException when a command with the same short option string already exists. *//*from w ww. j av a 2 s . co m*/ public void registerCommand(CliCommand command) { Option o = command.getOption(); if (commandMap.containsKey(o.getLongOpt())) { throw new IllegalArgumentException( "A command with key [" + o.getLongOpt() + "] is already registered."); } if (o.getOpt() != null) { for (CliCommand c : commandMap.values()) { Option commandOption = c.getOption(); if (commandOption.getOpt() != null && commandOption.getOpt().equals(o.getOpt())) { throw new IllegalArgumentException("Illegal option [" + o.getLongOpt() + "] conflicts with existing option [" + commandOption.getLongOpt() + "]."); } } } commandMap.put(o.getLongOpt(), command); options.addOption(o); if (command.requiresOpenStore() == false) { noStoreOptions.addOption(o); } }