List of usage examples for org.apache.commons.cli PosixParser PosixParser
PosixParser
From source file:edu.msu.cme.rdp.multicompare.Reprocess.java
/** * This class reprocesses the classification results (allrank output) and print out hierarchy output file, based on the confidence cutoff; * and print out only the detail classification results with assignment at certain rank with confidence above the cutoff or/and matching a given taxon. * @param args/*from w w w.j a v a2s . c o m*/ * @throws Exception */ public static void main(String[] args) throws Exception { PrintWriter assign_out = new PrintWriter(new NullWriter()); float conf = 0.8f; PrintStream heir_out = null; String hier_out_filename = null; ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank; String rank = null; String taxonFilterFile = null; String train_propfile = null; String gene = null; List<MCSample> samples = new ArrayList(); try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) { hier_out_filename = line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT); heir_out = new PrintStream(hier_out_filename); } else { throw new Exception( "It make sense to provide output filename for " + CmdOptions.HIER_OUTFILE_LONG_OPT); } if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) { assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.RANK_SHORT_OPT)) { rank = line.getOptionValue(CmdOptions.RANK_SHORT_OPT); } if (line.hasOption(CmdOptions.TAXON_SHORT_OPT)) { taxonFilterFile = line.getOptionValue(CmdOptions.TAXON_SHORT_OPT); } if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) { conf = Float.parseFloat(line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT)); if (conf < 0 || conf > 1) { throw new IllegalArgumentException("Confidence must be in the range [0,1]"); } } if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) { String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT); if (f.equalsIgnoreCase("allrank")) { format = ClassificationResultFormatter.FORMAT.allRank; } else if (f.equalsIgnoreCase("fixrank")) { format = ClassificationResultFormatter.FORMAT.fixRank; } else if (f.equalsIgnoreCase("db")) { format = ClassificationResultFormatter.FORMAT.dbformat; } else if (f.equalsIgnoreCase("filterbyconf")) { format = ClassificationResultFormatter.FORMAT.filterbyconf; } else { throw new IllegalArgumentException( "Not valid output format, only allrank, fixrank, filterbyconf and db allowed"); } } if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) { if (gene != null) { throw new IllegalArgumentException( "Already specified the gene from the default location. Can not specify train_propfile"); } else { train_propfile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT); } } if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) { if (train_propfile != null) { throw new IllegalArgumentException( "Already specified train_propfile. Can not specify gene any more"); } gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase(); if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) { throw new IllegalArgumentException(gene + " is NOT valid, only allows " + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", " + ClassifierFactory.FUNGALITS_warcup_GENE + " and " + ClassifierFactory.FUNGALITS_unite_GENE); } } args = line.getArgs(); if (args.length < 1) { throw new Exception("Incorrect number of command line arguments"); } for (String arg : args) { String[] inFileNames = arg.split(","); String inputFile = inFileNames[0]; File idmappingFile = null; if (inFileNames.length == 2) { idmappingFile = new File(inFileNames[1]); if (!idmappingFile.exists()) { System.err.println("Failed to find input file \"" + inFileNames[1] + "\""); return; } } MCSample nextSample = new MCSampleResult(inputFile, idmappingFile); samples.add(nextSample); } } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(120, "Reprocess [options] <Classification_allrank_result>[,idmappingfile] ...", "", options, ""); return; } if (train_propfile == null && gene == null) { gene = ClassifierFactory.RRNA_16S_GENE; } HashSet<String> taxonFilter = null; if (taxonFilterFile != null) { taxonFilter = readTaxonFilterFile(taxonFilterFile); } MultiClassifier multiClassifier = new MultiClassifier(train_propfile, gene); DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(heir_out, samples); MultiClassifierResult result = multiClassifier.multiClassificationParser(samples, conf, assign_out, format, rank, taxonFilter); result.getRoot().topDownVisit(printVisitor); assign_out.close(); heir_out.close(); if (multiClassifier.hasCopyNumber()) { // print copy number corrected counts File cn_corrected_s = new File(new File(hier_out_filename).getParentFile(), "cncorrected_" + hier_out_filename); PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s); printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true); result.getRoot().topDownVisit(printVisitor); cn_corrected_hier_out.close(); } }
From source file:eu.impact_project.iif.tw.cli.ToolWrapper.java
/** * Main method of the command line application * * @param args/*from www.j av a2 s .c o m*/ * Arguments of the command line application * @throws GeneratorException * Exception if project generation fails */ public static void main(String[] args) throws GeneratorException { CommandLineParser cmdParser = new PosixParser(); try { // Parse the command line arguments CommandLine cmd = cmdParser.parse(OPTIONS, args); // If no args or help selected if ((args.length == 0) || (cmd.hasOption(HELP_OPT))) { // OK help needed HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Constants.PROJECT_NAME, OPTIONS, true); if (args.length == 0) logger.info("Reading default configuration files from working " + "directory ..."); else System.exit(0); } String toolspecPath = cmd.getOptionValue(TOOLSPEC_OPT, Constants.DEFAULT_TOOLSPEC); File toolspecFile = new File(toolspecPath); String propertiesPath = cmd.getOptionValue(PROPERTIES_OPT, Constants.DEFAULT_PROJECT_PROPERTIES); File propertiesFile = new File(propertiesPath); ioc.setXmlConf(toolspecFile); ioc.setProjConf(propertiesFile); } catch (ParseException excep) { // Problem parsing the command line args, just print the message and help logger.error("Problem parsing command line arguments.", excep); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Constants.PROJECT_NAME, OPTIONS, true); System.exit(1); } if (!ioc.hasConfig()) { throw new GeneratorException("No configuration available."); } JAXBContext context; try { context = JAXBContext.newInstance("eu.impact_project.iif.tw.toolspec"); Unmarshaller unmarshaller = context.createUnmarshaller(); Toolspec toolspec = (Toolspec) unmarshaller.unmarshal(new File(ioc.getXmlConf())); // general tool specification properties logger.info("Toolspec model: " + toolspec.getModel()); logger.info("Tool id: " + toolspec.getId()); logger.info("Tool name: " + toolspec.getName()); logger.info("Tool version: " + toolspec.getVersion()); // List of services for the tool List<Service> services = toolspec.getServices().getService(); // For each service a different maven project will be generated for (Service service : services) { createService(service, toolspec.getVersion()); } } catch (IOException ex) { logger.error("An IOException occurred", ex); } catch (JAXBException ex) { logger.error("JAXBException", ex); throw new GeneratorException("Unable to create XML binding for toolspec"); } }
From source file:lapispaste.Main.java
public static void main(String[] args) throws Exception { // create Options object Options options = new Options(); String version;//from w w w . j av a 2 s. c om version = "0.1"; // populate Options with.. well options :P options.addOption("v", false, "Display version"); options.addOption("f", true, "File to paste"); // non-critical options options.addOption("t", true, "Code language"); options.addOption("p", false, "Read from pipe"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); // assemble a map of values final Map<String, String> pastemap = new HashMap<String, String>(); if (cmd.hasOption("t")) pastemap.put("format", cmd.getOptionValue("t").toString()); else pastemap.put("format", "text"); // critical options if (cmd.hasOption("v")) System.out.println("lapispaste version " + version); else if (cmd.hasOption("f")) { File file = new File(cmd.getOptionValue("f")); StringBuffer pdata = readData(new FileReader(file)); paster(pastemap, pdata); } else if (cmd.hasOption("p")) { StringBuffer pdata = readData(new InputStreamReader(System.in)); paster(pastemap, pdata); } else { // Did not recieve what was expected HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("lapispaste [OPTIONS] [FILE]", options); } }
From source file:com.bytelightning.opensource.pokerface.PokerFaceApp.java
public static void main(String[] args) { if (JavaVersionAsFloat() < (1.8f - Float.MIN_VALUE)) { System.err.println("PokerFace requires at least Java v8 to run."); return;/* w w w. j a v a 2s . c om*/ } // Configure the command line options parser Options options = new Options(); options.addOption("h", false, "help"); options.addOption("listen", true, "(http,https,secure,tls,ssl,CertAlias)=Address:Port for https."); options.addOption("keystore", true, "Filepath for PokerFace certificate keystore."); options.addOption("storepass", true, "The store password of the keystore."); options.addOption("keypass", true, "The key password of the keystore."); options.addOption("target", true, "Remote Target requestPattern=targetUri"); // NOTE: targetUri may contain user-info and if so will be interpreted as the alias of a cert to be presented to the remote target options.addOption("servercpu", true, "Number of cores the server should use."); options.addOption("targetcpu", true, "Number of cores the http targets should use."); options.addOption("trustany", false, "Ignore certificate identity errors from target servers."); options.addOption("files", true, "Filepath to a directory of static files."); options.addOption("config", true, "Path for XML Configuration file."); options.addOption("scripts", true, "Filepath for root scripts directory."); options.addOption("library", true, "JavaScript library to load into global context."); options.addOption("watch", false, "Dynamically watch scripts directory for changes."); options.addOption("dynamicTargetScripting", false, "WARNING! This option allows scripts to redirect requests to *any* other remote server."); CommandLine cmdLine = null; // parse the command line. try { CommandLineParser parser = new PosixParser(); cmdLine = parser.parse(options, args); if (args.length == 0 || cmdLine.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(PokerFaceApp.class.getSimpleName(), options); return; } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); return; } catch (Exception ex) { ex.printStackTrace(System.err); return; } XMLConfiguration config = new XMLConfiguration(); try { if (cmdLine.hasOption("config")) { Path tmp = Utils.MakePath(cmdLine.getOptionValue("config")); if (!Files.exists(tmp)) throw new FileNotFoundException("Configuration file does not exist."); if (Files.isDirectory(tmp)) throw new FileNotFoundException("'config' path is not a file."); // This is a bit of a pain, but but let's make sure we have a valid configuration file before we actually try to use it. config.setEntityResolver(new DefaultEntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { InputSource retVal = super.resolveEntity(publicId, systemId); if ((retVal == null) && (systemId != null)) { try { URL entityURL; if (systemId.endsWith("/PokerFace_v1Config.xsd")) entityURL = PokerFaceApp.class.getResource("/PokerFace_v1Config.xsd"); else entityURL = new URL(systemId); URLConnection connection = entityURL.openConnection(); connection.setUseCaches(false); InputStream stream = connection.getInputStream(); retVal = new InputSource(stream); retVal.setSystemId(entityURL.toExternalForm()); } catch (Throwable e) { return retVal; } } return retVal; } }); config.setSchemaValidation(true); config.setURL(tmp.toUri().toURL()); config.load(); if (cmdLine.hasOption("listen")) System.out.println("IGNORING 'listen' option because a configuration file was supplied."); if (cmdLine.hasOption("target")) System.out.println("IGNORING 'target' option(s) because a configuration file was supplied."); if (cmdLine.hasOption("scripts")) System.out.println("IGNORING 'scripts' option because a configuration file was supplied."); if (cmdLine.hasOption("library")) System.out.println("IGNORING 'library' option(s) because a configuration file was supplied."); } else { String[] serverStrs; String[] addr = { null }; String[] port = { null }; serverStrs = cmdLine.getOptionValues("listen"); if (serverStrs == null) throw new MissingOptionException("No listening addresses specified specified"); for (int i = 0; i < serverStrs.length; i++) { String addrStr; String alias = null; String protocol = null; Boolean https = null; int addrPos = serverStrs[i].indexOf('='); if (addrPos >= 0) { if (addrPos < 2) throw new IllegalArgumentException("Invalid http argument."); else if (addrPos + 1 >= serverStrs[i].length()) throw new IllegalArgumentException("Invalid http argument."); addrStr = serverStrs[i].substring(addrPos + 1, serverStrs[i].length()); String[] types = serverStrs[i].substring(0, addrPos).split(","); for (String type : types) { if (type.equalsIgnoreCase("http")) break; else if (type.equalsIgnoreCase("https") || type.equalsIgnoreCase("secure")) https = true; else if (type.equalsIgnoreCase("tls") || type.equalsIgnoreCase("ssl")) protocol = type.toUpperCase(); else alias = type; } } else addrStr = serverStrs[i]; ParseAddressString(addrStr, addr, port, alias != null ? 443 : 80); config.addProperty("server.listen(" + i + ")[@address]", addr[0]); config.addProperty("server.listen(" + i + ")[@port]", port[0]); if (alias != null) config.addProperty("server.listen(" + i + ")[@alias]", alias); if (protocol != null) config.addProperty("server.listen(" + i + ")[@protocol]", protocol); if (https != null) config.addProperty("server.listen(" + i + ")[@secure]", https); } String servercpu = cmdLine.getOptionValue("servercpu"); if (servercpu != null) config.setProperty("server[@cpu]", servercpu); String clientcpu = cmdLine.getOptionValue("targetcpu"); if (clientcpu != null) config.setProperty("targets[@cpu]", clientcpu); // Configure static files if (cmdLine.hasOption("files")) { Path tmp = Utils.MakePath(cmdLine.getOptionValue("files")); if (!Files.exists(tmp)) throw new FileNotFoundException("Files directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'files' path is not a directory."); config.setProperty("files.rootDirectory", tmp.toAbsolutePath().toUri()); } // Configure scripting if (cmdLine.hasOption("scripts")) { Path tmp = Utils.MakePath(cmdLine.getOptionValue("scripts")); if (!Files.exists(tmp)) throw new FileNotFoundException("Scripts directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'scripts' path is not a directory."); config.setProperty("scripts.rootDirectory", tmp.toAbsolutePath().toUri()); config.setProperty("scripts.dynamicWatch", cmdLine.hasOption("watch")); String[] libraries = cmdLine.getOptionValues("library"); if (libraries != null) { for (int i = 0; i < libraries.length; i++) { Path lib = Utils.MakePath(libraries[i]); if (!Files.exists(lib)) throw new FileNotFoundException( "Script library does not exist [" + libraries[i] + "]."); if (Files.isDirectory(lib)) throw new FileNotFoundException( "Script library is not a file [" + libraries[i] + "]."); config.setProperty("scripts.library(" + i + ")", lib.toAbsolutePath().toUri()); } } } else if (cmdLine.hasOption("watch")) System.out.println("IGNORING 'watch' option as no 'scripts' directory was specified."); else if (cmdLine.hasOption("library")) System.out.println("IGNORING 'library' option as no 'scripts' directory was specified."); } String keyStorePath = cmdLine.getOptionValue("keystore"); if (keyStorePath != null) config.setProperty("keystore", keyStorePath); String keypass = cmdLine.getOptionValue("keypass"); if (keypass != null) config.setProperty("keypass", keypass); String storepass = cmdLine.getOptionValue("storepass"); if (storepass != null) config.setProperty("storepass", keypass); if (cmdLine.hasOption("trustany")) config.setProperty("targets[@trustAny]", true); config.setProperty("scripts.dynamicTargetScripting", cmdLine.hasOption("dynamicTargetScripting")); String[] targetStrs = cmdLine.getOptionValues("target"); if (targetStrs != null) { for (int i = 0; i < targetStrs.length; i++) { int uriPos = targetStrs[i].indexOf('='); if (uriPos < 2) throw new IllegalArgumentException("Invalid target argument."); else if (uriPos + 1 >= targetStrs[i].length()) throw new IllegalArgumentException("Invalid target argument."); String patternStr = targetStrs[i].substring(0, uriPos); String urlStr = targetStrs[i].substring(uriPos + 1, targetStrs[i].length()); String alias; try { URL url = new URL(urlStr); alias = url.getUserInfo(); String scheme = url.getProtocol(); if ((!"http".equals(scheme)) && (!"https".equals(scheme))) throw new IllegalArgumentException("Invalid target uri scheme."); int port = url.getPort(); if (port < 0) port = url.getDefaultPort(); urlStr = scheme + "://" + url.getHost() + ":" + port + url.getPath(); String ref = url.getRef(); if (ref != null) urlStr += "#" + ref; } catch (MalformedURLException ex) { throw new IllegalArgumentException("Malformed target uri"); } config.addProperty("targets.target(" + i + ")[@pattern]", patternStr); config.addProperty("targets.target(" + i + ")[@url]", urlStr); if (alias != null) config.addProperty("targets.target(" + i + ")[@alias]", alias); } } // config.save(System.out); } catch (Throwable e) { e.printStackTrace(System.err); return; } // If we get here, we have a possibly valid configuration. try { final PokerFace p = new PokerFace(); p.config(config); if (p.start()) { PokerFace.Logger.warn("Started!"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { PokerFace.Logger.warn("Initiating shutdown..."); p.stop(); PokerFace.Logger.warn("Shutdown completed!"); } catch (Throwable e) { PokerFace.Logger.error("Failed to shutdown cleanly!"); e.printStackTrace(System.err); } } }); } else { PokerFace.Logger.error("Failed to start!"); System.exit(-1); } } catch (Throwable e) { e.printStackTrace(System.err); } }
From source file:net.sf.jsignpdf.verify.Verifier.java
/** * @param args/*from ww w .j a va 2s . c o m*/ */ public static void main(String[] args) { // create the Options Option optHelp = new Option("h", "help", false, "print this message"); // Option optVersion = new Option("v", "version", false, // "print version info"); Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files"); optCerts.setArgName("certificates"); Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder"); optExtract.setArgName("folder"); Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java"); Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore"); Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name"); optKsType.setArgName("keystore_type"); Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file"); optKsFile.setArgName("file"); Option optKsPass = new Option("kp", "keystore-password", true, "password for keystore file (look on -kf option)"); optKsPass.setArgName("password"); Option optFailFast = new Option("ff", "fail-fast", false, "flag which sets the Verifier to exit with error code on the first validation failure"); final Options options = new Options(); options.addOption(optHelp); // options.addOption(optVersion); options.addOption(optCerts); options.addOption(optPasswd); options.addOption(optExtract); options.addOption(optListKs); options.addOption(optListCert); options.addOption(optKsType); options.addOption(optKsFile); options.addOption(optKsPass); options.addOption(optFailFast); CommandLine line = null; try { // create the command line parser CommandLineParser parser = new PosixParser(); // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Illegal command used: " + exp.getMessage()); System.exit(SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM); } final boolean failFast = line.hasOption("ff"); final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]", "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null, true); } else if (line.hasOption("lk")) { // list keystores for (String tmpKsType : KeyStoreUtils.getKeyStores()) { System.out.println(tmpKsType); } } else if (line.hasOption("lc")) { // list certificate aliases in the keystore for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp"))) { System.out.println(tmpCert); } } else { final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp")); tmpLogic.setFailFast(failFast); if (line.hasOption("c")) { String tmpCertFiles = line.getOptionValue("c"); for (String tmpCFile : tmpCertFiles.split(";")) { tmpLogic.addX509CertFile(tmpCFile); } } byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } String tmpExtractDir = null; if (line.hasOption("e")) { tmpExtractDir = new File(line.getOptionValue("e")).getPath(); } int exitCode = 0; for (String tmpFilePath : tmpArgs) { int exitCodeForFile = 0; System.out.println("Verifying " + tmpFilePath); final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_FILE_NOT_READABLE; System.err.println("Couln't read the file. Check the path and permissions."); if (failFast) { System.exit(exitCodeForFile); } exitCode = Math.max(exitCode, exitCodeForFile); continue; } final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd); if (tmpResult.getException() != null) { tmpResult.getException().printStackTrace(); exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM; if (failFast) { System.exit(exitCodeForFile); } exitCode = Math.max(exitCode, exitCodeForFile); continue; } else { System.out.println("Total revisions: " + tmpResult.getTotalRevisions()); for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) { System.out.println(tmpSigVer.toString()); if (tmpExtractDir != null) { try { File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_" + tmpSigVer.getRevision() + ".pdf"); System.out.println("Extracting to " + tmpExFile.getCanonicalPath()); FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath()); InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd, tmpSigVer.getName()); IOUtils.copy(tmpIS, tmpFOS); tmpIS.close(); tmpFOS.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } exitCodeForFile = tmpResult.getVerificationResultCode(); if (failFast && SignatureVerification.isError(exitCodeForFile)) { System.exit(exitCodeForFile); } } exitCode = Math.max(exitCode, exitCodeForFile); } if (exitCode != 0 && tmpArgs.length > 1) { System.exit(SignatureVerification.isError(exitCode) ? SignatureVerification.SIG_STAT_CODE_ERROR_ANY_ERROR : SignatureVerification.SIG_STAT_CODE_WARNING_ANY_WARNING); } else { System.exit(exitCode); } } }
From source file:de.tudarmstadt.ukp.teaching.uima.nounDecompounding.ranking.TotalFreqAmout.java
@SuppressWarnings("static-access") public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("index").withDescription("The path to the web1t lucene index") .hasArg().isRequired().create()); CommandLineParser parser = new PosixParser(); CommandLine cmd;//from w ww .jav a2 s . c o m try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Error: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("countTotalFreq", options); return; } TotalFreqAmout amount = new TotalFreqAmout(new File(cmd.getOptionValue("index"))); System.out.println("Total amount: " + amount.countFreq()); }
From source file:gov.nih.nci.indexgen.IndexGenerator.java
/** * Main program.//from w w w . j a va2s . c o m * Two mutually exclusive command line options are possible: * -I include the following classes * -E exclude the following classes * The classes are passed as a space delimited list like: * -I Taxon Cytoband * @param args */ public static void main(String[] args) throws Exception { String[] classFilter = null; boolean isInclude = true; Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("include").withDescription("classes to include") .hasOptionalArgs().create("I")); options.addOption(OptionBuilder.withLongOpt("exclude").withDescription("classes to exclude") .hasOptionalArgs().create("E")); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String[] include = cmd.getOptionValues("I"); String[] exclude = cmd.getOptionValues("E"); if (include != null) { if (exclude != null) argError(); isInclude = true; classFilter = include; } else if (exclude != null) { isInclude = false; classFilter = exclude; } SearchAPIProperties properties = SearchAPIProperties.getInstance(); String ormFileName = properties.getOrmFileName(); ; int threadCount = properties.getThreadCount() > 0 ? properties.getThreadCount() : 1; IndexGenerator indexgen = null; try { indexgen = new IndexGenerator(ormFileName, threadCount, classFilter, isInclude); indexgen.generate(); } finally { if (indexgen != null) indexgen.close(); } }
From source file:com.denimgroup.threadfix.cli.CommandLineParser.java
public static void main(String[] args) { Options options = getOptions();//from w w w . ja v a 2 s . c o m PosixParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar tfcli.jar", options); } else if (cmd.hasOption("s")) { String[] setArgs = cmd.getOptionValues("s"); if (setArgs == null || setArgs.length != 2) { throw new ParseException("Bad arguments for set."); } if ("url".equals(setArgs[0])) { System.out.println("Setting URL to " + setArgs[1]); client.setUrl(setArgs[1]); } else if ("key".equals(setArgs[0])) { System.out.println("Setting API Key to " + setArgs[1]); client.setKey(setArgs[1]); } else { throw new ParseException("First argument to set must be url or key"); } } else if (cmd.hasOption("ct")) { String[] createArgs = cmd.getOptionValues("ct"); if (createArgs.length != 1) { throw new ParseException("Wrong number of arguments."); } System.out.println("Creating a Team with the name " + createArgs[0] + "."); System.out.println(client.createTeam(createArgs[0])); } else if (cmd.hasOption("cw")) { String[] createArgs = cmd.getOptionValues("cw"); if (createArgs.length != 2) { throw new ParseException("Wrong number of arguments."); } System.out.println("Creating a Waf with the name " + createArgs[0] + "."); System.out.println(client.createWaf(createArgs[0], createArgs[1])); } else if (cmd.hasOption("ca")) { String[] createArgs = cmd.getOptionValues("ca"); if (createArgs.length != 3) { throw new ParseException("Wrong number of arguments."); } System.out.println("Creating an Application with the name " + createArgs[1] + "."); System.out.println(client.createApplication(createArgs[0], createArgs[1], createArgs[2])); } else if (cmd.hasOption("teams")) { System.out.println("Getting all teams."); System.out.println(client.getAllTeams()); } else if (cmd.hasOption("u")) { String[] uploadArgs = cmd.getOptionValues("u"); // Upload a scan if (uploadArgs.length != 2) { throw new ParseException("Wrong number of arguments."); } System.out.println("Uploading " + uploadArgs[1] + " to Application " + uploadArgs[0] + "."); System.out.println(client.uploadScan(uploadArgs[0], uploadArgs[1])); } else if (cmd.hasOption("st")) { String[] searchArgs = cmd.getOptionValues("st"); if (searchArgs.length != 2) { throw new ParseException("Wrong number of arguments."); } if ("id".equals(searchArgs[0])) { System.out.println("Searching for team with the id " + searchArgs[1] + "."); System.out.println(client.searchForTeamById(searchArgs[1])); } else if ("name".equals(searchArgs[0])) { System.out.println("Searching for team with the name " + searchArgs[1] + "."); System.out.println(client.searchForTeamByName(searchArgs[1])); } else { System.out.println("Unknown property argument. Try either id or name."); return; } } else if (cmd.hasOption("sw")) { String[] searchArgs = cmd.getOptionValues("sw"); if (searchArgs.length != 4) { throw new ParseException("Wrong number of arguments."); } if ("id".equals(searchArgs[0])) { System.out.println("Searching for WAF with the id " + searchArgs[1] + "."); System.out.println(client.searchForWafById(searchArgs[1])); } else if ("name".equals(searchArgs[0])) { System.out.println("Searching for WAF with the name " + searchArgs[1] + "."); System.out.println(client.searchForWafByName(searchArgs[1])); } else { throw new ParseException("Unknown property argument. Try either id or name."); } } else if (cmd.hasOption("sa")) { String[] searchArgs = cmd.getOptionValues("sa"); if ("id".equals(searchArgs[0])) { if (searchArgs.length != 2) { System.out.println("Wrong number of arguments."); return; } System.out.println("Searching for application with the id " + searchArgs[1] + "."); System.out.println(client.searchForApplicationById(searchArgs[1])); } else if ("name".equals(searchArgs[0])) { if (searchArgs.length != 3) { System.out.println( "Wrong number of arguments. You need to input application name and team name as well."); return; } System.out.println("Searching for application with the name " + searchArgs[1] + " of team " + searchArgs[2]); System.out.println(client.searchForApplicationByName(searchArgs[1], searchArgs[2])); } else { System.out.println("Unknown property argument. Try either id or name."); return; } } else if (cmd.hasOption("r")) { String[] ruleArgs = cmd.getOptionValues("r"); if (ruleArgs.length != 1) { System.out.println("Wrong number of arguments.'"); } System.out.println("Downloading rules from WAF with ID " + ruleArgs[0] + "."); System.out.println(client.getRules(ruleArgs[0])); } else { throw new ParseException("No arguments found."); } } catch (ParseException e) { if (e.getMessage() != null) { System.out.println(e.getMessage()); } HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar tfcli.jar", options); } }
From source file:discovery.compression.kdd2011.ratio.RatioCompressionReport.java
public static void main(String[] args) throws GraphReadingException, IOException, java.text.ParseException { opts.addOption("r", true, "Goal compression ratio"); // opts.addOption( "a", // true, // "Algorithm used for compression. The default and only currently available option is \"greedy\""); //opts.addOption("cost-output",true,"Output file for costs, default is costs.txt"); //opts.addOption("cost-format",true,"Output format for "); opts.addOption("ctype", true, "Connectivity type: global or local, default is global."); opts.addOption("connectivity", false, "enables output for connectivity. Connectivity info will be written to connectivity.txt"); opts.addOption("output_bmg", true, "Write bmg file with groups to given file."); opts.addOption("algorithm", true, "Algorithm to use, one of: greedy random1 random2 bruteforce slowgreedy"); opts.addOption("hop2", false, "Only try to merge nodes that have common neighbors"); opts.addOption("kmedoids", false, "Enables output for kmedoids clustering"); opts.addOption("kmedoids_k", true, "Number of clusters to be used in kmedoids. Default is 3"); opts.addOption("kmedoids_output", true, "Output file for kmedoid clusters. Default is clusters.txt. This file will be overwritten."); opts.addOption("norefresh", false, "Use old style merging: all connectivities are not refreshed when merging"); opts.addOption("edge_attribute", true, "Attribute from bmgraph used as edge weight"); opts.addOption("only_times", false, "Only write times.txt"); //opts.addOption("no_metrics",false,"Exit after compression, don't calculate any metrics or produce output bmg for the compression."); CommandLineParser parser = new PosixParser(); CommandLine cmd = null;//from w w w .j av a 2s . c om try { cmd = parser.parse(opts, args); } catch (ParseException e) { e.printStackTrace(); System.exit(0); } boolean connectivity = false; double ratio = 0; boolean hop2 = cmd.hasOption("hop2"); RatioCompression compression = new GreedyRatioCompression(hop2); if (cmd.hasOption("connectivity")) connectivity = true; ConnectivityType ctype = ConnectivityType.GLOBAL; CompressionMergeModel mergeModel = new PathAverageMergeModel(); if (cmd.hasOption("ctype")) { String ctypeStr = cmd.getOptionValue("ctype"); if (ctypeStr.equals("local")) { ctype = ConnectivityType.LOCAL; mergeModel = new EdgeAverageMergeModel(); } else if (ctypeStr.equals("global")) { ctype = ConnectivityType.GLOBAL; mergeModel = new PathAverageMergeModel(); } else { System.out.println(PROGRAM_NAME + ": unknown connectivity type " + ctypeStr); printHelp(); } } if (cmd.hasOption("norefresh")) mergeModel = new PathAverageMergeModelNorefresh(); if (cmd.hasOption("algorithm")) { String alg = cmd.getOptionValue("algorithm"); if (alg.equals("greedy")) { compression = new GreedyRatioCompression(hop2); } else if (alg.equals("random1")) { compression = new RandomRatioCompression(hop2); } else if (alg.equals("random2")) { compression = new SmartRandomRatioCompression(hop2); } else if (alg.equals("bruteforce")) { compression = new BruteForceCompression(hop2, ctype == ConnectivityType.LOCAL); } else if (alg.equals("slowgreedy")) { compression = new SlowGreedyRatioCompression(hop2); } else { System.out.println("algorithm must be one of: greedy random1 random2 bruteforce slowgreedy"); printHelp(); } } compression.setMergeModel(mergeModel); if (cmd.hasOption("r")) { ratio = Double.parseDouble(cmd.getOptionValue("r")); } else { System.out.println(PROGRAM_NAME + ": compression ratio not defined"); printHelp(); } if (cmd.hasOption("help")) { printHelp(); } String infile = null; if (cmd.getArgs().length != 0) { infile = cmd.getArgs()[0]; } else { printHelp(); } boolean kmedoids = false; int kmedoidsK = 3; String kmedoidsOutput = "clusters.txt"; if (cmd.hasOption("kmedoids")) kmedoids = true; if (cmd.hasOption("kmedoids_k")) kmedoidsK = Integer.parseInt(cmd.getOptionValue("kmedoids_k")); if (cmd.hasOption("kmedoids_output")) kmedoidsOutput = cmd.getOptionValue("kmedoids_output"); String edgeAttrib = "goodness"; if (cmd.hasOption("edge_attribute")) edgeAttrib = cmd.getOptionValue("edge_attribute"); // This program should directly use bmgraph-java to read and // DefaultGraph should have a constructor that takes a BMGraph as an // argument. //VisualGraph vg = new VisualGraph(infile, edgeAttrib, false); //System.out.println("vg read"); //SimpleVisualGraph origSG = new SimpleVisualGraph(vg); BMGraph bmg = BMGraphUtils.readBMGraph(infile); int origN = bmg.getNodes().size(); //for(int i=0;i<origN;i++) //System.out.println(i+"="+origSG.getVisualNode(i)); System.out.println("bmgraph read"); BMNode[] i2n = new BMNode[origN]; HashMap<BMNode, Integer> n2i = new HashMap<BMNode, Integer>(); { int pi = 0; for (BMNode nod : bmg.getNodes()) { n2i.put(nod, pi); i2n[pi++] = nod; } } DefaultGraph dg = new DefaultGraph(); for (BMEdge e : bmg.getEdges()) { dg.addEdge(n2i.get(e.getSource()), n2i.get(e.getTarget()), Double.parseDouble(e.get(edgeAttrib))); } DefaultGraph origDG = dg.copy(); System.out.println("inputs read"); RatioCompression nopCompressor = new RatioCompression.DefaultRatioCompression(); ResultGraph nopResult = nopCompressor.compressGraph(dg, 1); long start = System.currentTimeMillis(); ResultGraph result = compression.compressGraph(dg, ratio); long timeSpent = System.currentTimeMillis() - start; double seconds = timeSpent * 0.001; BufferedWriter timesWriter = new BufferedWriter(new FileWriter("times.txt", true)); timesWriter.append("" + seconds + "\n"); timesWriter.close(); if (cmd.hasOption("only_times")) { System.out.println("Compression done, exiting."); System.exit(0); } BufferedWriter costsWriter = new BufferedWriter(new FileWriter("costs.txt", true)); costsWriter.append("" + nopResult.getCompressorCosts() + " " + result.getCompressorCosts() + "\n"); costsWriter.close(); double[][] origProb; double[][] compProb; int[] group = new int[origN]; for (int i = 0; i < result.partition.size(); i++) for (int x : result.partition.get(i)) group[x] = i; if (ctype == ConnectivityType.LOCAL) { origProb = new double[origN][origN]; compProb = new double[origN][origN]; DefaultGraph g = result.uncompressedGraph(); for (int i = 0; i < origN; i++) { for (int j = 0; j < origN; j++) { origProb[i][j] = dg.getEdgeWeight(i, j); compProb[i][j] = g.getEdgeWeight(i, j); } } System.out.println("Writing edge-dissimilarity"); } else { origProb = ProbDijkstra.getProbMatrix(origDG); compProb = new double[origN][origN]; System.out.println("nodeCount = " + result.graph.getNodeCount()); double[][] ccProb = ProbDijkstra.getProbMatrix(result.graph); System.out.println("ccProb.length = " + ccProb.length); System.out.println("ccProb[0].length = " + ccProb[0].length); for (int i = 0; i < origN; i++) { for (int j = 0; j < origN; j++) { if (group[i] == group[j]) compProb[i][j] = result.graph.getEdgeWeight(group[i], group[j]); else { int gj = group[j]; int gi = group[i]; compProb[i][j] = ccProb[group[i]][group[j]]; } } } System.out.println("Writing best-path-dissimilarity"); //compProb = ProbDijkstra.getProbMatrix(result.uncompressedGraph()); } { BufferedWriter connWr = null;// if (connectivity) { connWr = new BufferedWriter(new FileWriter("connectivity.txt", true)); } double totalDiff = 0; for (int i = 0; i < origN; i++) { for (int j = i + 1; j < origN; j++) { double diff = Math.abs(origProb[i][j] - compProb[i][j]); //VisualNode ni = origSG.getVisualNode(i); //VisualNode nj = origSG.getVisualNode(j); BMNode ni = i2n[i]; BMNode nj = i2n[j]; if (connectivity) connWr.append(ni + "\t" + nj + "\t" + origProb[i][j] + "\t" + compProb[i][j] + "\t" + diff + "\n"); totalDiff += diff * diff; } } if (connectivity) { connWr.append("\n"); connWr.close(); } totalDiff = Math.sqrt(totalDiff); BufferedWriter dissWr = new BufferedWriter(new FileWriter("dissimilarity.txt", true)); dissWr.append("" + totalDiff + "\n"); dissWr.close(); } if (cmd.hasOption("output_bmg")) { BMGraph outgraph = new BMGraph(); String outputfile = cmd.getOptionValue("output_bmg"); HashMap<Integer, BMNode> nodes = new HashMap<Integer, BMNode>(); for (int i = 0; i < result.partition.size(); i++) { ArrayList<Integer> g = result.partition.get(i); if (g.size() == 0) continue; BMNode node = new BMNode("Supernode_" + i); HashMap<String, String> attributes = new HashMap<String, String>(); StringBuffer contents = new StringBuffer(); for (int x : g) contents.append(i2n[x] + ","); contents.delete(contents.length() - 1, contents.length()); attributes.put("nodes", contents.toString()); attributes.put("self-edge", "" + result.graph.getEdgeWeight(i, i)); node.setAttributes(attributes); nodes.put(i, node); outgraph.ensureHasNode(node); } for (int i = 0; i < result.partition.size(); i++) { if (result.partition.get(i).size() == 0) continue; for (int x : result.graph.getNeighbors(i)) { if (x < i) continue; BMNode from = nodes.get(i); BMNode to = nodes.get(x); if (from == null || to == null) { System.out.println(from + "->" + to); System.out.println(i + "->" + x); System.out.println(""); } BMEdge e = new BMEdge(nodes.get(i), nodes.get(x), "notype"); e.setAttributes(new HashMap<String, String>()); e.put("goodness", "" + result.graph.getEdgeWeight(i, x)); outgraph.ensureHasEdge(e); } } BMGraphUtils.writeBMGraph(outgraph, outputfile); } // k medoids! if (kmedoids) { //KMedoidsResult clustersOrig=KMedoids.runKMedoids(origProb,kmedoidsK); if (ctype == ConnectivityType.LOCAL) { compProb = ProbDijkstra.getProbMatrix(result.uncompressedGraph()); } //KMedoidsResult compClusters = KMedoids.runKMedoids(ProbDijkstra.getProbMatrix(result.graph),kmedoidsK); KMedoidsResult clustersComp = KMedoids.runKMedoids(compProb, kmedoidsK); BufferedWriter bw = new BufferedWriter(new FileWriter(kmedoidsOutput)); for (int i = 0; i < origN; i++) { int g = group[i]; //bw.append(origSG.getVisualNode(i).getBMNode()+" "+compClusters.clusters[g]+"\n"); bw.append(i2n[i] + " " + clustersComp.clusters[i] + "\n"); } bw.close(); } System.exit(0); }
From source file:edu.msu.cme.rdp.classifier.train.validation.crossvalidate.CrossValidateMain.java
/** * This is the main method for cross validation test. * @param args/* ww w .ja va 2s . c om*/ * @throws IOException */ public static void main(String[] args) throws IOException { String tax_file = null; String source_file = null; String out_file = null; Integer partialLength = null; // default is full length float fraction = 0.1f; String rdmSelectedRank = null; int min_bootstrap_words = NBClassifier.MIN_BOOTSTRSP_WORDS; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(TRAIN_TAXONFILE_SHORT_OPT)) { tax_file = line.getOptionValue(TRAIN_TAXONFILE_SHORT_OPT); } else { throw new ParseException("Taxonomy file must be specified"); } if (line.hasOption(TRAIN_SEQFILE_SHORT_OPT)) { source_file = line.getOptionValue(TRAIN_SEQFILE_SHORT_OPT); } else { throw new ParseException("Source training fasta file must be specified"); } if (line.hasOption(OUTFILE_SHORT_OPT)) { out_file = line.getOptionValue(OUTFILE_SHORT_OPT); } else { throw new ParseException("Output file must be specified"); } if (line.hasOption(LENGTH_SHORT_OPT)) { ; partialLength = new Integer(line.getOptionValue(LENGTH_SHORT_OPT)); } if (line.hasOption("fraction")) { fraction = Float.parseFloat(line.getOptionValue("fraction")); } if (line.hasOption("rdmRank")) { rdmSelectedRank = line.getOptionValue("rdmRank"); } if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) { min_bootstrap_words = Integer .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)); if (min_bootstrap_words < NBClassifier.MIN_BOOTSTRSP_WORDS) { throw new IllegalArgumentException( min_bootstrap_words + " must be at least " + NBClassifier.MIN_BOOTSTRSP_WORDS); } } } catch (ParseException ex) { new HelpFormatter().printHelp(120, "CrossValidateMain", "", options, "", true); return; } boolean useSeed = true; // use seed for random number generator CrossValidate theObj = new CrossValidate(); theObj.runTest(new File(tax_file), new File(source_file), new File(out_file), rdmSelectedRank, fraction, partialLength, useSeed, min_bootstrap_words); }