List of usage examples for java.lang IllegalArgumentException IllegalArgumentException
public IllegalArgumentException(Throwable cause)
From source file:com.stumbleupon.hbaseadmin.HBaseCompact.java
/** * Main entry point// w ww .ja va 2 s .co m * @param args command line arguments * @throws Exception */ public static void main(String[] args) throws Exception { CommandLineParser parser = new PosixParser(); CommandLine cmd = null; String hbaseSite = null; String jmxRemotePasswordFile = null; String jmxPort = null; Date startDate = null; Date endDate = null; int throttleFactor = 1; int numCycles = 1; int pauseInterval = DEFAULT_PAUSE_INTERVAL; int waitInterval = DEFAULT_WAIT_INTERVAL; int filesKeep = DEFAULT_FILES_KEEP; long regionCompactWaitTime = DEFAULT_REGION_COMPACT_WAIT_TIME; long maxStoreFileAge = 0; boolean excludeTables = false; String tableNamesString = ""; List<String> tableNames = new ArrayList<String>(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); // Parse command line options try { cmd = parser.parse(getOptions(), args); } catch (org.apache.commons.cli.ParseException e) { System.out.println(e.getMessage()); printOptions(); System.exit(-1); } for (Option option : cmd.getOptions()) { switch (option.getId()) { case 'c': hbaseSite = option.getValue(); break; case 'j': jmxRemotePasswordFile = option.getValue(); break; case 't': throttleFactor = Integer.parseInt(option.getValue()); break; case 'n': numCycles = Integer.parseInt(option.getValue()); break; case 'p': pauseInterval = Integer.parseInt(option.getValue()); break; case 'w': waitInterval = Integer.parseInt(option.getValue()); break; case 's': startDate = sdf.parse(option.getValue()); break; case 'e': endDate = sdf.parse(option.getValue()); break; case 'b': tableNamesString = option.getValue(); tableNames = Arrays.asList(option.getValue().split(",")); break; case 'f': filesKeep = Integer.parseInt(option.getValue()); break; case 'r': jmxPort = option.getValue(); break; case 'x': excludeTables = true; break; case 'm': regionCompactWaitTime = Long.parseLong(option.getValue()); break; case 'a': maxStoreFileAge = Long.parseLong(option.getValue()); break; default: throw new IllegalArgumentException("unexpected option " + option); } } LOG.info("Starting compactor"); LOG.info("--------------------------------------------------"); LOG.info("HBase site : {}", hbaseSite); LOG.info("RegionServer Jmx port : {}", jmxPort); LOG.info("Jmx password file : {}", jmxRemotePasswordFile); LOG.info("Compact interval : {}", pauseInterval); LOG.info("Check interval : {}", waitInterval); LOG.info("Throttle factor : {}", throttleFactor); LOG.info("Number of cycles : {}", numCycles); LOG.info("Off-peak start time : {}", Utils.dateString(startDate, "HH:mm")); LOG.info("Off-peak end time : {}", Utils.dateString(endDate, "HH:mm")); LOG.info("Minimum store files : {}", filesKeep); LOG.info("Table names : {}", tableNamesString); LOG.info("Exclude tables : {}", excludeTables); LOG.info("Region compact wait time: {}", regionCompactWaitTime); LOG.info("Max store file age : {}", maxStoreFileAge); LOG.info("--------------------------------------------------"); // Get command line options final Configuration conf = HBaseConfiguration.create(); conf.addResource(new Path(hbaseSite)); HBaseCompact compact = new HBaseCompact(); ClusterUtils clusterUtils = new ClusterUtils(compact, regionCompactWaitTime); compact.setClusterUtils(clusterUtils); compact.setAdmin(new HBaseAdmin(conf)); compact.setSleepBetweenCompacts(pauseInterval); compact.setSleepBetweenChecks(waitInterval); compact.setThrottleFactor(throttleFactor); compact.setNumCycles(numCycles); compact.setStartDate(startDate); compact.setEndDate(endDate); compact.setNumStoreFiles(filesKeep); compact.setTableNames(tableNames); compact.setExcludeTables(excludeTables); compact.setMaxStoreFileAge(maxStoreFileAge); clusterUtils.setJmxPort(jmxPort); clusterUtils.setJmxPasswordFile(jmxRemotePasswordFile); compact.runCompactions(); }
From source file:com.l2jfree.loginserver.tools.L2AccountManager.java
/** * Launches the interactive account manager. * //from ww w.j a v a 2 s.co m * @param args ignored */ public static void main(String[] args) { // LOW rework this crap Util.printSection("Account Management"); _log.info("Please choose:"); //_log.info("list - list registered accounts"); _log.info("reg - register a new account"); _log.info("rem - remove a registered account"); _log.info("prom - promote a registered account"); _log.info("dem - demote a registered account"); _log.info("ban - ban a registered account"); _log.info("unban - unban a registered account"); _log.info("quit - exit this application"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); L2AccountManager acm = new L2AccountManager(); String line; try { while ((line = br.readLine()) != null) { line = line.trim(); Connection con = null; switch (acm.getState()) { case USER_NAME: line = line.toLowerCase(); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?"); ps.setString(1, line); ResultSet rs = ps.executeQuery(); if (!rs.next()) { acm.setUser(line); _log.info("Desired password:"); acm.setState(ManagerState.PASSWORD); } else { _log.info("User name already in use."); acm.setState(ManagerState.INITIAL_CHOICE); } rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not access database!", e); acm.setState(ManagerState.INITIAL_CHOICE); } finally { L2Database.close(con); } break; case PASSWORD: try { MessageDigest sha = MessageDigest.getInstance("SHA"); byte[] pass = sha.digest(line.getBytes("US-ASCII")); acm.setPass(HexUtil.bytesToHexString(pass)); } catch (NoSuchAlgorithmException e) { _log.fatal("SHA1 is not available!", e); Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE); } catch (UnsupportedEncodingException e) { _log.fatal("ASCII is not available!", e); Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE); } _log.info("Super user: [y/n]"); acm.setState(ManagerState.SUPERUSER); break; case SUPERUSER: try { if (line.length() != 1) throw new IllegalArgumentException("One char required."); else if (line.charAt(0) == 'y') acm.setSuper(true); else if (line.charAt(0) == 'n') acm.setSuper(false); else throw new IllegalArgumentException("Invalid choice."); _log.info("Date of birth: [yyyy-mm-dd]"); acm.setState(ManagerState.DOB); } catch (IllegalArgumentException e) { _log.info("[y/n]?"); } break; case DOB: try { Date d = Date.valueOf(line); if (d.after(new Date(System.currentTimeMillis()))) throw new IllegalArgumentException("Future date specified."); acm.setDob(d); _log.info("Ban reason ID or nothing:"); acm.setState(ManagerState.SUSPENDED); } catch (IllegalArgumentException e) { _log.info("[yyyy-mm-dd] in the past:"); } break; case SUSPENDED: try { if (line.length() > 0) { int id = Integer.parseInt(line); acm.setBan(L2BanReason.getById(id)); } else acm.setBan(null); try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement( "INSERT INTO account (username, password, superuser, birthDate, banReason) VALUES (?, ?, ?, ?, ?)"); ps.setString(1, acm.getUser()); ps.setString(2, acm.getPass()); ps.setBoolean(3, acm.isSuper()); ps.setDate(4, acm.getDob()); L2BanReason lbr = acm.getBan(); if (lbr == null) ps.setNull(5, Types.INTEGER); else ps.setInt(5, lbr.getId()); ps.executeUpdate(); _log.info("Account " + acm.getUser() + " has been registered."); ps.close(); } catch (SQLException e) { _log.error("Could not register an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); } catch (NumberFormatException e) { _log.info("Ban reason ID or nothing:"); } break; case REMOVE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement("DELETE FROM account WHERE username LIKE ?"); ps.setString(1, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been removed."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not remove an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case PROMOTE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?"); ps.setBoolean(1, true); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been promoted."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not promote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case DEMOTE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?"); ps.setBoolean(1, false); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been demoted."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not demote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case UNBAN: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?"); ps.setNull(1, Types.INTEGER); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been unbanned."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not demote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case BAN: line = line.toLowerCase(); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?"); ps.setString(1, line); ResultSet rs = ps.executeQuery(); if (rs.next()) { acm.setUser(line); _log.info("Ban reason ID:"); acm.setState(ManagerState.REASON); } else { _log.info("Account does not exist."); acm.setState(ManagerState.INITIAL_CHOICE); } rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not access database!", e); acm.setState(ManagerState.INITIAL_CHOICE); } finally { L2Database.close(con); } break; case REASON: try { int ban = Integer.parseInt(line); con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?"); ps.setInt(1, ban); ps.setString(2, acm.getUser()); ps.executeUpdate(); _log.info("Account " + acm.getUser() + " has been banned."); ps.close(); } catch (NumberFormatException e) { _log.info("Ban reason ID:"); } catch (SQLException e) { _log.error("Could not ban an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; default: line = line.toLowerCase(); if (line.equals("reg")) { _log.info("Desired user name:"); acm.setState(ManagerState.USER_NAME); } else if (line.equals("rem")) { _log.info("User name:"); acm.setState(ManagerState.REMOVE); } else if (line.equals("prom")) { _log.info("User name:"); acm.setState(ManagerState.PROMOTE); } else if (line.equals("dem")) { _log.info("User name:"); acm.setState(ManagerState.DEMOTE); } else if (line.equals("unban")) { _log.info("User name:"); acm.setState(ManagerState.UNBAN); } else if (line.equals("ban")) { _log.info("User name:"); acm.setState(ManagerState.BAN); } else if (line.equals("quit")) Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN); else _log.info("Incorrect command."); break; } } } catch (IOException e) { _log.fatal("Could not process input!", e); } finally { IOUtils.closeQuietly(br); } }
From source file:com.tamingtext.classifier.mlt.TestMoreLikeThis.java
public static void main(String[] args) throws Exception { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option helpOpt = DefaultOptionCreator.helpOption(); Option inputDirOpt = obuilder.withLongName("input").withRequired(true) .withArgument(abuilder.withName("input").withMinimum(1).withMaximum(1).create()) .withDescription("The input directory").withShortName("i").create(); Option modelOpt = obuilder.withLongName("model").withRequired(true) .withArgument(abuilder.withName("index").withMinimum(1).withMaximum(1).create()) .withDescription("The directory containing the index model").withShortName("m").create(); Option categoryFieldOpt = obuilder.withLongName("categoryField").withRequired(true) .withArgument(abuilder.withName("index").withMinimum(1).withMaximum(1).create()) .withDescription("Name of the field containing category information").withShortName("catf") .create();//from w ww. j a v a2 s .c o m Option contentFieldOpt = obuilder.withLongName("contentField").withRequired(true) .withArgument(abuilder.withName("index").withMinimum(1).withMaximum(1).create()) .withDescription("Name of the field containing content information").withShortName("contf") .create(); Option maxResultsOpt = obuilder.withLongName("maxResults").withRequired(false) .withArgument(abuilder.withName("gramSize").withMinimum(1).withMaximum(1).create()) .withDescription("Number of results to retrive, default: 10 ").withShortName("r").create(); Option gramSizeOpt = obuilder.withLongName("gramSize").withRequired(false) .withArgument(abuilder.withName("gramSize").withMinimum(1).withMaximum(1).create()) .withDescription("Size of the n-gram. Default Value: 1 ").withShortName("ng").create(); Option typeOpt = obuilder.withLongName("classifierType").withRequired(false) .withArgument(abuilder.withName("classifierType").withMinimum(1).withMaximum(1).create()) .withDescription("Type of classifier: knn|tfidf. Default: bayes").withShortName("type").create(); Group group = gbuilder.withName("Options").withOption(gramSizeOpt).withOption(helpOpt) .withOption(inputDirOpt).withOption(modelOpt).withOption(typeOpt).withOption(contentFieldOpt) .withOption(categoryFieldOpt).withOption(maxResultsOpt).create(); try { Parser parser = new Parser(); parser.setGroup(group); parser.setHelpOption(helpOpt); CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return; } String classifierType = (String) cmdLine.getValue(typeOpt); int gramSize = 1; if (cmdLine.hasOption(gramSizeOpt)) { gramSize = Integer.parseInt((String) cmdLine.getValue(gramSizeOpt)); } int maxResults = 10; if (cmdLine.hasOption(maxResultsOpt)) { maxResults = Integer.parseInt((String) cmdLine.getValue(maxResultsOpt)); } String inputPath = (String) cmdLine.getValue(inputDirOpt); String modelPath = (String) cmdLine.getValue(modelOpt); String categoryField = (String) cmdLine.getValue(categoryFieldOpt); String contentField = (String) cmdLine.getValue(contentFieldOpt); MatchMode mode; if ("knn".equalsIgnoreCase(classifierType)) { mode = MatchMode.KNN; } else if ("tfidf".equalsIgnoreCase(classifierType)) { mode = MatchMode.TFIDF; } else { throw new IllegalArgumentException("Unkown classifierType: " + classifierType); } Directory directory = FSDirectory.open(new File(modelPath)); IndexReader indexReader = IndexReader.open(directory); Analyzer analyzer //<co id="mlt.analyzersetup"/> = new EnglishAnalyzer(Version.LUCENE_36); MoreLikeThisCategorizer categorizer = new MoreLikeThisCategorizer(indexReader, categoryField); categorizer.setAnalyzer(analyzer); categorizer.setMatchMode(mode); categorizer.setFieldNames(new String[] { contentField }); categorizer.setMaxResults(maxResults); categorizer.setNgramSize(gramSize); File f = new File(inputPath); if (!f.isDirectory()) { throw new IllegalArgumentException(f + " is not a directory or does not exit"); } File[] inputFiles = FileUtil.buildFileList(f); String line = null; //<start id="lucene.examples.mlt.test"/> final ClassifierResult UNKNOWN = new ClassifierResult("unknown", 1.0); ResultAnalyzer resultAnalyzer = //<co id="co.mlt.ra"/> new ResultAnalyzer(categorizer.getCategories(), UNKNOWN.getLabel()); for (File ff : inputFiles) { //<co id="co.mlt.read"/> BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(ff), "UTF-8")); while ((line = in.readLine()) != null) { String[] parts = line.split("\t"); if (parts.length != 2) { continue; } CategoryHits[] hits //<co id="co.mlt.cat"/> = categorizer.categorize(new StringReader(parts[1])); ClassifierResult result = hits.length > 0 ? hits[0] : UNKNOWN; resultAnalyzer.addInstance(parts[0], result); //<co id="co.mlt.an"/> } in.close(); } System.out.println(resultAnalyzer.toString());//<co id="co.mlt.print"/> /* <calloutlist> <callout arearefs="co.mlt.ra">Create <classname>ResultAnalyzer</classname></callout> <callout arearefs="co.mlt.read">Read Test data</callout> <callout arearefs="co.mlt.cat">Categorize</callout> <callout arearefs="co.mlt.an">Collect Results</callout> <callout arearefs="co.mlt.print">Display Results</callout> </calloutlist> */ //<end id="lucene.examples.mlt.test"/> } catch (OptionException e) { log.error("Error while parsing options", e); } }
From source file:edu.msu.cme.rdp.framebot.stat.TaxonAbundance.java
/** * this class group the nearest matches by phylum/class, or by match * @param args//www . j a va 2s. c o m * @throws Exception */ public static void main(String[] args) throws Exception { HashMap<String, Double> coveragetMap = null; double identity = 0.0; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("seqCoverage")) { String coveragefile = line.getOptionValue("seqCoverage"); coveragetMap = parseKmerCoverage(coveragefile); } if (line.hasOption("identity")) { identity = Double.parseDouble(line.getOptionValue("identity")); if (identity < 0 || identity > 100) { throw new IllegalArgumentException("identity cutoff should be in the range of 0 and 100"); } } args = line.getArgs(); if (args.length != 3) { throw new Exception(""); } } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(80, "[options] <FrameBot Alignment file or Dir> <seqLineage> <out file> ", "", options, "seqLineage: a tab-delimited file with ref seqID and lineage, or fasta of ref seq with lineage as the descrption" + "\nframeBot alignment file or Dir: frameBot alignment files " + "\noutfile: output with the nearest match count group by phylum/class; and by match name"); } TaxonAbundance.mapAbundance(new File(args[0]), new File(args[1]), args[2], coveragetMap, identity); }
From source file:edu.msu.cme.rdp.multicompare.Main.java
public static void main(String[] args) throws Exception { PrintStream hier_out = null;/*ww w . j av a 2s . c o m*/ PrintWriter assign_out = new PrintWriter(new NullWriter()); PrintStream bootstrap_out = null; File hier_out_filename = null; String propFile = null; File biomFile = null; File metadataFile = null; PrintWriter shortseq_out = null; List<MCSample> samples = new ArrayList(); ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank; float conf = CmdOptions.DEFAULT_CONF; String gene = null; int min_bootstrap_words = Classifier.MIN_BOOTSTRSP_WORDS; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) { assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT)); } else { throw new IllegalArgumentException("Require the output file for classification assignment"); } if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) { hier_out_filename = new File(line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT)); hier_out = new PrintStream(hier_out_filename); } if (line.hasOption(CmdOptions.BIOMFILE_SHORT_OPT)) { biomFile = new File(line.getOptionValue(CmdOptions.BIOMFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.METADATA_SHORT_OPT)) { metadataFile = new File(line.getOptionValue(CmdOptions.METADATA_SHORT_OPT)); } 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 { propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT); } } 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("filterbyconf")) { format = ClassificationResultFormatter.FORMAT.filterbyconf; } else if (f.equalsIgnoreCase("db")) { format = ClassificationResultFormatter.FORMAT.dbformat; } else if (f.equalsIgnoreCase("biom")) { format = ClassificationResultFormatter.FORMAT.biom; } else { throw new IllegalArgumentException( "Not an valid output format, only allrank, fixrank, biom, filterbyconf and db allowed"); } } if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) { if (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 + " not found, choose from" + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", " + ClassifierFactory.FUNGALITS_warcup_GENE + ", " + ClassifierFactory.FUNGALITS_unite_GENE); } } 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 < Classifier.MIN_BOOTSTRSP_WORDS) { throw new IllegalArgumentException(CmdOptions.MIN_BOOTSTRAP_WORDS_LONG_OPT + " must be at least " + Classifier.MIN_BOOTSTRSP_WORDS); } } if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) { String confString = line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT); try { conf = Float.valueOf(confString); } catch (NumberFormatException e) { throw new IllegalArgumentException("Confidence must be a decimal number"); } if (conf < 0 || conf > 1) { throw new IllegalArgumentException("Confidence must be in the range [0,1]"); } } if (line.hasOption(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)) { shortseq_out = new PrintWriter(line.getOptionValue(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)) { bootstrap_out = new PrintStream(line.getOptionValue(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)); } if (format.equals(ClassificationResultFormatter.FORMAT.biom) && biomFile == null) { throw new IllegalArgumentException("biom format requires an input biom file"); } if (biomFile != null) { // if input biom file provided, use biom format format = ClassificationResultFormatter.FORMAT.biom; } args = line.getArgs(); for (String arg : args) { String[] inFileNames = arg.split(","); File inputFile = new File(inFileNames[0]); File idmappingFile = null; if (!inputFile.exists()) { throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[0] + "\""); } if (inFileNames.length == 2) { idmappingFile = new File(inFileNames[1]); if (!idmappingFile.exists()) { throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[1] + "\""); } } MCSample nextSample = new MCSample(inputFile, idmappingFile); samples.add(nextSample); } if (propFile == null && gene == null) { gene = CmdOptions.DEFAULT_GENE; } if (samples.size() < 1) { throw new IllegalArgumentException("Require at least one sample files"); } } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(80, " [options] <samplefile>[,idmappingfile] ...", "", options, ""); return; } MultiClassifier multiClassifier = new MultiClassifier(propFile, gene, biomFile, metadataFile); MultiClassifierResult result = multiClassifier.multiCompare(samples, conf, assign_out, format, min_bootstrap_words); assign_out.close(); if (hier_out != null) { DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(hier_out, samples); result.getRoot().topDownVisit(printVisitor); hier_out.close(); if (multiClassifier.hasCopyNumber()) { // print copy number corrected counts File cn_corrected_s = new File(hier_out_filename.getParentFile(), "cnadjusted_" + hier_out_filename.getName()); 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(); } } if (bootstrap_out != null) { for (MCSample sample : samples) { MCSamplePrintUtil.printBootstrapCountTable(bootstrap_out, sample); } bootstrap_out.close(); } if (shortseq_out != null) { for (String id : result.getBadSequences()) { shortseq_out.write(id + "\n"); } shortseq_out.close(); } }
From source file:edu.msu.cme.rdp.classifier.ClassifierCmd.java
/** * This is the main method to do classification. * <p>Usage: java ClassifierCmd queryFile outputFile [property file]. * <br>//from w w w . jav a 2s . c o m * queryFile can be one of the following formats: Fasta, Genbank and EMBL. * <br> * outputFile will be used to save the classification output. * <br> * property file contains the mapping of the training files. * <br> * Note: the training files and the property file should be in the same directory. * The default property file is set to data/classifier/16srrna/rRNAClassifier.properties. */ public static void main(String[] args) throws Exception { String queryFile = null; String outputFile = null; String propFile = null; String gene = null; ClassificationResultFormatter.FORMAT format = CmdOptions.DEFAULT_FORMAT; int min_bootstrap_words = Classifier.MIN_BOOTSTRSP_WORDS; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) { outputFile = line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT); } else { throw new Exception("outputFile must be specified"); } 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 { propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT); } } 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("filterbyconf")) { format = ClassificationResultFormatter.FORMAT.filterbyconf; } else if (f.equalsIgnoreCase("db")) { format = ClassificationResultFormatter.FORMAT.dbformat; } else { throw new IllegalArgumentException( "Not valid output format, only allrank, fixrank, filterbyconf and db allowed"); } } if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) { if (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)) { throw new IllegalArgumentException(gene + " is NOT valid, only allows " + ClassifierFactory.RRNA_16S_GENE + " and " + ClassifierFactory.FUNGALLSU_GENE); } } 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 < Classifier.MIN_BOOTSTRSP_WORDS) { throw new IllegalArgumentException(CmdOptions.MIN_BOOTSTRAP_WORDS_LONG_OPT + " must be at least " + Classifier.MIN_BOOTSTRSP_WORDS); } } args = line.getArgs(); if (args.length != 1) { throw new Exception("Expect one query file"); } queryFile = args[0]; } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(120, "ClassifierCmd [options] <samplefile>\nNote this is the legacy command for one sample classification ", "", options, ""); return; } if (propFile == null && gene == null) { gene = CmdOptions.DEFAULT_GENE; } ClassifierCmd classifierCmd = new ClassifierCmd(); printLicense(); classifierCmd.doClassify(queryFile, outputFile, propFile, format, gene, min_bootstrap_words); }
From source file:ch.vorburger.mifos.wiki.ZWikiScraper.java
public static void main(String[] args) throws IOException { if (args.length != 2) throw new IllegalArgumentException("Missing uid & pwd, as args"); long startTime = System.currentTimeMillis(); String uid = args[0];/*w ww. j a va 2 s . co m*/ String pwd = args[1]; ZWikiScraper s = new ZWikiScraper("http://www.mifos.org/developers/wiki/", uid, pwd); List<WikiNode> rootNodes = s.getContents(); long midTime = System.currentTimeMillis() - startTime; /* WikiPage p = s.getPage("MigrateDeveloperWiki"); System.out.println(p.pageName); System.out.println(p.pageContent); System.out.println(s.wd.getPageSource()); */ File dumpDir = new File("target/wikiContent"); Properties pageId2Name = new Properties(); Properties pageName2Id = new Properties(); try { for (WikiNode node : rootNodes) { node.dumpToDirectory(dumpDir, pageId2Name, pageName2Id); } } finally { s.close(); saveProperties(pageId2Name, new File(dumpDir, "pageId2Name.properties")); saveProperties(pageName2Id, new File(dumpDir, "pageName2Id.properties")); long stopTime = System.currentTimeMillis(); long totalTime = stopTime - startTime; System.out.println("\n\nZWikiScraper index page fetching and parsing took " + midTime / 1000 + "s"); System.out .println("\n\nZWikiScraper took " + totalTime / 1000 + "s total (fetched all pages on index)"); } }
From source file:com.threadswarm.imagefeedarchiver.driver.CommandLineDriver.java
public static void main(String[] args) throws InterruptedException, ExecutionException, ParseException { // define available command-line options Options options = new Options(); options.addOption("h", "help", false, "display usage information"); options.addOption("u", "url", true, "RSS feed URL"); options.addOption("a", "user-agent", true, "User-Agent header value to use when making HTTP requests"); options.addOption("o", "output-directory", true, "output directory for downloaded images"); options.addOption("t", "thread-count", true, "number of worker threads, defaults to cpu-count + 1"); options.addOption("d", "delay", true, "delay between image downloads (in milliseconds)"); options.addOption("p", "notrack", false, "tell websites that you don't wish to be tracked (DNT)"); options.addOption("s", "https", false, "Rewrite image URLs to leverage SSL/TLS"); CommandLineParser commandLineParser = new BasicParser(); CommandLine commandLine = commandLineParser.parse(options, args); // print usage information if 'h'/'help' or no-args were given if (args.length == 0 || commandLine.hasOption("h")) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java -jar ImageFeedArchiver.jar", options); return; //abort execution }//w ww . j av a 2 s . co m URI rssFeedUri = null; if (commandLine.hasOption("u")) { String rssFeedUrlString = commandLine.getOptionValue("u"); try { rssFeedUri = FeedUtils.getUriFromUrlString(rssFeedUrlString); } catch (MalformedURLException | URISyntaxException e) { LOGGER.error("The Feed URL you supplied was malformed or violated syntax rules.. exiting", e); System.exit(1); } LOGGER.info("Target RSS feed URL: {}", rssFeedUri); } else { throw new IllegalStateException("RSS feed URL was not specified!"); } File outputDirectory = null; if (commandLine.hasOption("o")) { outputDirectory = new File(commandLine.getOptionValue("o")); if (!outputDirectory.isDirectory()) throw new IllegalArgumentException("output directory must be a *directory*!"); LOGGER.info("Using output directory: '{}'", outputDirectory); } else { throw new IllegalStateException("output directory was not specified!"); } String userAgentString = null; if (commandLine.hasOption("a")) { userAgentString = commandLine.getOptionValue("a"); LOGGER.info("Setting 'User-Agent' header value to '{}'", userAgentString); } int threadCount; if (commandLine.hasOption("t")) { threadCount = Integer.parseInt(commandLine.getOptionValue("t")); } else { threadCount = Runtime.getRuntime().availableProcessors() + 1; } LOGGER.info("Using {} worker threads", threadCount); long downloadDelay = 0; if (commandLine.hasOption("d")) { String downloadDelayString = commandLine.getOptionValue("d"); downloadDelay = Long.parseLong(downloadDelayString); } LOGGER.info("Using a download-delay of {} milliseconds", downloadDelay); boolean doNotTrackRequested = commandLine.hasOption("p"); boolean forceHttps = commandLine.hasOption("s"); ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/applicationContext.xml"); ((ConfigurableApplicationContext) context).registerShutdownHook(); HttpClient httpClient = (HttpClient) context.getBean("httpClient"); if (userAgentString != null) httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgentString); ProcessedRssItemDAO processedRssItemDAO = (ProcessedRssItemDAO) context.getBean("processedRssItemDAO"); CommandLineDriver.Builder driverBuilder = new CommandLineDriver.Builder(rssFeedUri); driverBuilder.setDoNotTrackRequested(doNotTrackRequested).setOutputDirectory(outputDirectory) .setDownloadDelay(downloadDelay).setThreadCount(threadCount).setHttpClient(httpClient) .setForceHttps(forceHttps).setProcessedRssItemDAO(processedRssItemDAO); CommandLineDriver driver = driverBuilder.build(); driver.run(); }
From source file:net.tirasa.ilgrosso.resetdb.Main.java
public static void main(final String[] args) { ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); final DBMS dbms = ctx.getBean(DBMS.class); if (dbms == null) { throw new IllegalArgumentException("Could not find a valid DBMS bean"); }//ww w . j a va2 s . co m final DataSource dataSource = ctx.getBean(DataSource.class); final Connection conn = DataSourceUtils.getConnection(dataSource); try { switch (dbms) { case POSTGRESQL: resetPostgreSQL(conn); break; case MYSQL: resetMySQL(conn); break; case ORACLE: resetOracle(conn); break; case SQLSERVER: resetSQLServer(conn); break; default: LOG.warn("Unsupported DBMS: {}", dbms); } } catch (Throwable t) { LOG.error("During execution", t); } finally { DataSourceUtils.releaseConnection(conn, dataSource); } LOG.info("Reset successfully done."); }
From source file:com.github.brandtg.switchboard.FileLogAggregator.java
/** Main. */ public static void main(String[] args) throws Exception { Options opts = new Options(); opts.addOption("h", "help", false, "Prints help message"); opts.addOption("f", "file", true, "File to output aggregated logs to"); opts.addOption("s", "separator", true, "Line separator in log"); CommandLine cli = new GnuParser().parse(opts, args); if (cli.getArgs().length == 0 || cli.hasOption("help")) { new HelpFormatter().printHelp("usage: [opts] sourceHost:port ...", opts); System.exit(1);/*from w w w . j a va 2 s.c o m*/ } // Parse sources Set<InetSocketAddress> sources = new HashSet<>(); for (int i = 0; i < cli.getArgs().length; i++) { String[] tokens = cli.getArgs()[i].split(":"); sources.add(new InetSocketAddress(tokens[0], Integer.valueOf(tokens[1]))); } // Parse output stream OutputStream outputStream; if (cli.hasOption("file")) { outputStream = new FileOutputStream(cli.getOptionValue("file")); } else { outputStream = System.out; } // Separator String separator = cli.getOptionValue("separator", "\n"); if (separator.length() != 1) { throw new IllegalArgumentException("Separator must only be 1 character"); } final FileLogAggregator fileLogAggregator = new FileLogAggregator(sources, separator.charAt(0), outputStream); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { fileLogAggregator.stop(); } catch (Exception e) { LOG.error("Error when stopping log aggregator", e); } } }); fileLogAggregator.start(); }