List of usage examples for java.util Set add
boolean add(E e);
From source file:org.test.LookupSVNUsers.java
/** * @param args/*from w ww .ja va2 s . c om*/ * @throws IOException */ public static void main(String[] args) throws IOException { if (args.length != 2) { log.error("USAGE: <svn users file(input)> <git authors file (output)>"); System.exit(-1); } Set<String> unmatchedNameSet = new LinkedHashSet<String>(); Map<String, GitUser> gitUserMap = new LinkedHashMap<String, GitUser>(); String svnAuthorsFile = args[0]; List<String> lines = FileUtils.readLines(new File(svnAuthorsFile)); for (String line : lines) { // intentionally handle both upper and lower case varients of the same name. String svnUserName = line.trim(); if (svnUserName.contains("(")) continue; // skip over this line as we can't use it on the url if (gitUserMap.keySet().contains(svnUserName)) continue; // skip this duplicate. log.info("starting on user = " + svnUserName); String gitName = extractFullName(svnUserName); if (gitName == null) { gitName = extractFullName(svnUserName.toLowerCase()); } if (gitName == null) { unmatchedNameSet.add(svnUserName); } else { gitUserMap.put(svnUserName, new GitUser(svnUserName, gitName)); log.info("mapped user (" + svnUserName + ") to: " + gitName); } } List<String> mergedList = new ArrayList<String>(); mergedList.add("# GENERATED "); List<String> userNameList = new ArrayList<String>(); userNameList.addAll(gitUserMap.keySet()); Collections.sort(userNameList); for (String userName : userNameList) { GitUser gUser = gitUserMap.get(userName); mergedList.add(gUser.getSvnAuthor() + " = " + gUser.getGitUser() + " <" + gUser.getSvnAuthor() + "@users.sourceforge.net>"); } for (String username : unmatchedNameSet) { log.warn("failed to match SVN User = " + username); // add in the unmatched entries as is. mergedList.add(username + " = " + username + " <" + username + "@users.sourceforge.net>"); } FileUtils.writeLines(new File(args[1]), "UTF-8", mergedList); }
From source file:edu.msu.cme.rdp.probematch.cli.SliceToPrimer.java
public static void main(String[] args) throws Exception { //args = "--fedit-dist 4 --redit-dist=4 -k --max-length=400 --min-length=280 -o java_sliced_edit4.fasta TGCGAYCCSAARGCBGACTC ATSGCCATCATYTCRCCGGA /scratch/fishjord/tae_kwon_primer_match/all_genomes.fasta".split(" "); PatternBitMask64[] fprimers;//ww w . j a va 2 s .c o m String[] fprimerStrs, rprimerStrs; PatternBitMask64[] rprimers; FastaWriter seqOut; PrintStream statsOut; int fEdit = 3; int rEdit = 3; int minLength = Integer.MIN_VALUE; int maxLength = Integer.MAX_VALUE; boolean allowAmbiguities = true; boolean keepPrimers = false; SequenceReader inSeqs; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("edit-dist")) { fEdit = rEdit = Integer.parseInt(line.getOptionValue("edit-dist")); if (line.hasOption("redit-dist") || line.hasOption("fedit-dist")) { throw new Exception("edit-dist, [fedit-dist, redit-dist] are mutually exclusive"); } } if (line.hasOption("fedit-dist")) { fEdit = Integer.parseInt(line.getOptionValue("fedit-dist")); } if (line.hasOption("no-ambiguities")) { allowAmbiguities = false; } if (line.hasOption("keep-primers")) { keepPrimers = true; } if (line.hasOption("redit-dist")) { rEdit = Integer.parseInt(line.getOptionValue("redit-dist")); } if (line.hasOption("seq-out")) { seqOut = new FastaWriter(new File(line.getOptionValue("seq-out"))); } else { throw new Exception("Must specify seq-out"); } if (line.hasOption("stats-out")) { statsOut = new PrintStream(new File(line.getOptionValue("stats-out"))); } else { statsOut = System.out; } if (line.hasOption("min-length")) { minLength = Integer.parseInt(line.getOptionValue("min-length")); } if (line.hasOption("max-length")) { maxLength = Integer.parseInt(line.getOptionValue("max-length")); } args = line.getArgs(); if (args.length != 3) { throw new Exception("Unexpected number of command line arguments"); } fprimers = translateStringPrimers(args[0].split(","), allowAmbiguities, false); fprimerStrs = args[0].split(","); rprimers = translateStringPrimers(args[1].split(","), allowAmbiguities, true); rprimerStrs = args[1].split(","); inSeqs = new SequenceReader(new File(args[2])); } catch (Exception e) { new HelpFormatter().printHelp("SliceToPrimer [options] <f,p,r,i,m,e,r> <r,p,r,i,m,e,r> <in_seq_file>", options); System.err.println("ERROR: " + e.getMessage()); return; } Sequence seq; statsOut.println( "orig_seqid\tsliced_seqid\tfprimer\tstart\tend\tscore\trprimer\tstart\tend\tscore\tlength"); ScoringMatrix sccoringMatrix = ScoringMatrix.getDefaultNuclMatrix(); DPMAligner[] faligners = new DPMAligner[fprimers.length]; for (int index = 0; index < faligners.length; index++) { faligners[index] = new DPMAligner(fprimerStrs[index], Integer.MAX_VALUE); } try { while ((seq = inSeqs.readNextSequence()) != null) { Set<PrimerMatch> fprimerMatches = new HashSet(); Set<PrimerMatch> rprimerMatches = new HashSet(); for (int index = 0; index < fprimers.length; index++) { PatternBitMask64 primer = fprimers[index]; for (BitVector64Match r : BitVector64.process(seq.getSeqString().toCharArray(), primer, fEdit) .getResults()) { PrimerMatch match = new PrimerMatch(); match.start = r.getPosition() - (primer.getPatternLength() + r.getScore()); match.end = r.getPosition(); match.score = r.getScore(); match.primerIndex = index; fprimerMatches.add(match); } } for (int index = 0; index < rprimers.length; index++) { PatternBitMask64 primer = rprimers[index]; for (BitVector64Match r : BitVector64.process(seq.getSeqString().toCharArray(), primer, rEdit) .getResults()) { PrimerMatch match = new PrimerMatch(); match.start = r.getPosition() - (primer.getPatternLength() + r.getScore()); match.end = r.getPosition(); match.score = r.getScore(); match.primerIndex = index; rprimerMatches.add(match); } } if (fprimerMatches.isEmpty() || rprimerMatches.isEmpty()) { statsOut.println(seq.getSeqName() + "\tEither/or no forward/reverse primer hits"); continue; } for (PrimerMatch fmatch : fprimerMatches) { PrimerMatch bestReverse = null; int bestScore = Integer.MAX_VALUE; for (PrimerMatch rmatch : rprimerMatches) { if (rmatch.start > fmatch.end && rmatch.start - fmatch.end < bestScore) { bestReverse = rmatch; bestScore = rmatch.start - fmatch.end; } } if (bestReverse == null) { statsOut.println(seq.getSeqName() + "\tNo reverse primer before " + fmatch.end); continue; } String slicedSeq = null; if (keepPrimers) { slicedSeq = seq.getSeqString().substring(fmatch.start, bestReverse.end); } else { slicedSeq = seq.getSeqString().substring(fmatch.end, bestReverse.start); } String seqid = seq.getSeqName() + "_" + fmatch.primerIndex + "_" + fmatch.start; if (slicedSeq.length() > minLength && slicedSeq.length() < maxLength) { seqOut.writeSeq(seqid, "", slicedSeq); } DPMAlignment seqs = faligners[fmatch.primerIndex] .align(seq.getSeqString().substring(fmatch.start, fmatch.end)); System.err.println(">" + seqid); System.err.println(fprimerStrs[fmatch.primerIndex]); System.err.println(seq.getSeqString().substring(fmatch.start, fmatch.end)); System.err.println(); System.err.println(seqs.getAlignedMatchFragment()); System.err.println(seqs.getAlignedProbe()); System.err.println(); statsOut.println(seq.getSeqName() + "\t" + seqid + "\t" + fmatch.primerIndex + "\t" + fmatch.start + "\t" + fmatch.end + "\t" + fmatch.score + "\t" + bestReverse.primerIndex + "\t" + bestReverse.start + "\t" + bestReverse.end + "\t" + bestReverse.score + "\t" + slicedSeq.length()); } } } catch (Exception e) { e.printStackTrace(); } finally { statsOut.close(); seqOut.close(); } }
From source file:com.act.biointerpretation.ProductExtractor.java
public static void main(String[] args) throws Exception { CLIUtil cliUtil = new CLIUtil(ProductExtractor.class, HELP_MESSAGE, OPTION_BUILDERS); CommandLine cl = cliUtil.parseCommandLine(args); String orgPrefix = cl.getOptionValue(OPTION_ORGANISM_PREFIX); LOGGER.info("Using organism prefix %s", orgPrefix); MongoDB db = new MongoDB(DEFAULT_DB_HOST, DEFAULT_DB_PORT, cl.getOptionValue(OPTION_DB_NAME)); Map<Long, String> validOrganisms = new TreeMap<>(); DBIterator orgIter = db.getDbIteratorOverOrgs(); Organism o = null;/*from www . j a v a 2 s. co m*/ while ((o = db.getNextOrganism(orgIter)) != null) { if (!o.getName().isEmpty() && o.getName().startsWith(orgPrefix)) { validOrganisms.put(o.getUUID(), o.getName()); } } LOGGER.info("Found %d valid organisms", validOrganisms.size()); Set<Long> productIds = new TreeSet<>(); // Use something with implicit ordering we can traverse in order. DBIterator reactionIterator = db.getIteratorOverReactions(); Reaction r; while ((r = db.getNextReaction(reactionIterator)) != null) { Set<JSONObject> proteins = r.getProteinData(); boolean valid = false; for (JSONObject j : proteins) { if (j.has("organism") && validOrganisms.containsKey(j.getLong("organism"))) { valid = true; break; } else if (j.has("organisms")) { JSONArray organisms = j.getJSONArray("organisms"); for (int i = 0; i < organisms.length(); i++) { if (validOrganisms.containsKey(organisms.getLong(i))) { valid = true; break; } } } } if (valid) { for (Long id : r.getProducts()) { productIds.add(id); } for (Long id : r.getProductCofactors()) { productIds.add(id); } } } LOGGER.info("Found %d valid product ids for '%s'", productIds.size(), orgPrefix); PrintWriter writer = cl.hasOption(OPTION_OUTPUT_FILE) ? new PrintWriter(new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE))) : new PrintWriter(System.out); for (Long id : productIds) { Chemical c = db.getChemicalFromChemicalUUID(id); String inchi = c.getInChI(); if (inchi.startsWith("InChI=") && !inchi.startsWith("InChI=/FAKE")) { writer.println(inchi); } } if (cl.hasOption(OPTION_OUTPUT_FILE)) { writer.close(); } LOGGER.info("Done."); }
From source file:com.act.lcms.db.analysis.IonSearchAnalysis.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/* www . j av a2s.c om*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY)); if (!lcmsDir.isDirectory()) { System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } Double fontScale = null; if (cl.hasOption("font-scale")) { try { fontScale = Double.parseDouble(cl.getOptionValue("font-scale")); } catch (IllegalArgumentException e) { System.err.format("Argument for font-scale must be a floating point number.\n"); System.exit(1); } } try (DB db = DB.openDBFromCLI(cl)) { Set<String> includeIons = null; if (cl.hasOption("include-ions")) { String[] ionNames = cl.getOptionValues("include-ions"); includeIons = new HashSet<>(Arrays.asList(ionNames)); System.out.format("Including ions in search: %s\n", StringUtils.join(includeIons, ", ")); } Set<String> excludeIons = null; if (cl.hasOption("exclude-ions")) { String[] ionNames = cl.getOptionValues("exclude-ions"); excludeIons = new HashSet<>(Arrays.asList(ionNames)); System.out.format("Excluding ions from search: %s\n", StringUtils.join(excludeIons, ", ")); } Set<Integer> takeSamplesFromPlateIds = null; if (cl.hasOption(OPTION_FILTER_BY_PLATE_BARCODE)) { String[] plateBarcodes = cl.getOptionValues(OPTION_FILTER_BY_PLATE_BARCODE); System.out.format("Considering only sample wells in plates: %s\n", StringUtils.join(plateBarcodes, ", ")); takeSamplesFromPlateIds = new HashSet<>(plateBarcodes.length); for (String plateBarcode : plateBarcodes) { Plate p = Plate.getPlateByBarcode(db, plateBarcode); if (p == null) { System.err.format("WARNING: unable to find plate in DB with barcode %s\n", plateBarcode); } else { takeSamplesFromPlateIds.add(p.getId()); } } // Allow filtering on barcode even if we couldn't find any in the DB. } System.out.format("Loading/updating LCMS scan files into DB\n"); ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir); System.out.format("Processing LCMS scans\n"); Pair<List<LCMSWell>, Set<Integer>> positiveWellsAndPlateIds = Utils.extractWellsAndPlateIds(db, cl.getOptionValues(OPTION_STRAINS), cl.getOptionValues(OPTION_CONSTRUCTS), takeSamplesFromPlateIds, false); List<LCMSWell> positiveWells = positiveWellsAndPlateIds.getLeft(); if (positiveWells.size() == 0) { throw new RuntimeException("Found no LCMS wells for specified strains/constructs"); } // Only take negative samples from the plates where we found the positive samples. Pair<List<LCMSWell>, Set<Integer>> negativeWellsAndPlateIds = Utils.extractWellsAndPlateIds(db, cl.getOptionValues(OPTION_NEGATIVE_STRAINS), cl.getOptionValues(OPTION_NEGATIVE_CONSTRUCTS), positiveWellsAndPlateIds.getRight(), true); List<LCMSWell> negativeWells = negativeWellsAndPlateIds.getLeft(); if (negativeWells == null || negativeWells.size() == 0) { System.err.format("WARNING: no valid negative samples found in same plates as positive samples\n"); } // Extract the reference MZ that will be used in the LCMS trace processing. List<Pair<String, Double>> searchMZs = null; Set<CuratedChemical> standardChemicals = null; List<ChemicalAssociatedWithPathway> pathwayChems = null; if (cl.hasOption(OPTION_SEARCH_MZ)) { // Assume mz can be an FP number of a chemical name. String massStr = cl.getOptionValue(OPTION_SEARCH_MZ); Pair<String, Double> searchMZ = Utils.extractMassFromString(db, massStr); if (searchMZ != null) { searchMZs = Collections.singletonList(searchMZ); } standardChemicals = Utils.extractTargetsForWells(db, positiveWells); } else { CuratedChemical targetChemical = Utils.requireOneTarget(db, positiveWells); if (targetChemical == null) { throw new RuntimeException( "Unable to find a curated chemical entry for specified strains'/constructs' targets. " + "Please specify a chemical name or m/z explicitly or update the curated chemicals list in the DB."); } System.out.format("Using reference M/Z for positive target %s (%f)\n", targetChemical.getName(), targetChemical.getMass()); searchMZs = Collections.singletonList(Pair.of(targetChemical.getName(), targetChemical.getMass())); standardChemicals = Collections.singleton(targetChemical); } // Look up the standard by name, or use the target if none is specified. List<StandardWell> standardWells = null; if (cl.hasOption(OPTION_NO_STANDARD)) { System.err.format("WARNING: skipping standard comparison (no-standard option specified)\n"); standardWells = new ArrayList<>(0); } else if (cl.hasOption(OPTION_STANDARD_WELLS)) { String[] standardCoordinates = cl.getOptionValues(OPTION_STANDARD_WELLS); standardWells = new ArrayList<>(standardCoordinates.length); Plate standardPlate = Plate.getPlateByBarcode(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE)); List<String> foundCoordinates = new ArrayList<>(standardCoordinates.length); for (String stringCoords : standardCoordinates) { Pair<Integer, Integer> coords = Utils.parsePlateCoordinates(stringCoords); StandardWell well = StandardWell.getInstance().getStandardWellsByPlateIdAndCoordinates(db, standardPlate.getId(), coords.getLeft(), coords.getRight()); if (well == null) { System.err.format("Unable to find standard well at %s [%s]\n", standardPlate.getBarcode(), stringCoords); continue; } standardWells.add(well); foundCoordinates.add(stringCoords); } System.out.format("Using explicitly specified standard wells %s [%s]\n", standardPlate.getBarcode(), StringUtils.join(foundCoordinates, ", ")); } else if (cl.hasOption(OPTION_STANDARD_NAME)) { String standardName = cl.getOptionValue(OPTION_STANDARD_NAME); System.out.format("Using explicitly specified standard %s\n", standardName); standardWells = Collections.singletonList(Utils.extractStandardWellFromPlate(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE), standardName)); } else if (standardChemicals != null && standardChemicals.size() > 0) { // Default to using the target chemical(s) as a standard if none is specified. standardWells = new ArrayList<>(standardChemicals.size()); for (CuratedChemical c : standardChemicals) { String standardName = c.getName(); System.out.format("Searching for well containing standard %s\n", standardName); standardWells.add(Utils.extractStandardWellFromPlate(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE), standardName)); } } boolean useFineGrainedMZ = cl.hasOption("fine-grained-mz"); boolean useSNR = cl.hasOption(OPTION_USE_SNR); /* Process the standard, positive, and negative wells, producing ScanData containers that will allow them to be * iterated over for graph writing. */ HashMap<Integer, Plate> plateCache = new HashMap<>(); Pair<List<ScanData<StandardWell>>, Double> allStandardScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.STANDARD, plateCache, standardWells, useFineGrainedMZ, includeIons, excludeIons, useSNR); Pair<List<ScanData<LCMSWell>>, Double> allPositiveScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.POS_SAMPLE, plateCache, positiveWells, useFineGrainedMZ, includeIons, excludeIons, useSNR); Pair<List<ScanData<LCMSWell>>, Double> allNegativeScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.NEG_CONTROL, plateCache, negativeWells, useFineGrainedMZ, includeIons, excludeIons, useSNR); String fmt = "pdf"; String outImg = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + fmt; String outData = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".data"; System.err.format("Writing combined scan data to %s and graphs to %s\n", outData, outImg); produceLCMSSearchPlots(lcmsDir, outData, outImg, allStandardScans, allPositiveScans, allNegativeScans, fontScale, useFineGrainedMZ, cl.hasOption(OPTION_USE_HEATMAP), useSNR); } }
From source file:com.act.lcms.db.io.PrintConstructInfo.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());// ww w . j a v a2 s . c o m } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY)); if (!lcmsDir.isDirectory()) { System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } try (DB db = DB.openDBFromCLI(cl)) { System.out.print("Loading/updating LCMS scan files into DB\n"); ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir); String construct = cl.getOptionValue(OPTION_CONSTRUCT); List<LCMSWell> lcmsWells = LCMSWell.getInstance().getByConstructID(db, construct); Collections.sort(lcmsWells, new Comparator<LCMSWell>() { @Override public int compare(LCMSWell o1, LCMSWell o2) { return o1.getId().compareTo(o2.getId()); } }); Set<String> uniqueMSIDs = new HashSet<>(); Map<Integer, Plate> platesById = new HashMap<>(); System.out.format("\n\n-- Construct %s --\n\n", construct); List<ChemicalAssociatedWithPathway> pathwayChems = ChemicalAssociatedWithPathway.getInstance() .getChemicalsAssociatedWithPathwayByConstructId(db, construct); System.out.print("Chemicals associated with pathway:\n"); System.out.format(" %-8s%-15s%-45s\n", "index", "kind", "chemical"); for (ChemicalAssociatedWithPathway chem : pathwayChems) { System.out.format(" %-8d%-15s%-45s\n", chem.getIndex(), chem.getKind(), chem.getChemical()); } System.out.print("\nLCMS wells:\n"); System.out.format(" %-15s%-6s%-15s%-15s%-15s\n", "barcode", "well", "msid", "fed", "lcms_count"); for (LCMSWell well : lcmsWells) { uniqueMSIDs.add(well.getMsid()); Plate p = platesById.get(well.getPlateId()); if (p == null) { // TODO: migrate Plate to be a subclass of BaseDBModel. p = Plate.getPlateById(db, well.getPlateId()); platesById.put(p.getId(), p); } String chem = well.getChemical(); List<ScanFile> scanFiles = ScanFile.getScanFileByPlateIDRowAndColumn(db, p.getId(), well.getPlateRow(), well.getPlateColumn()); System.out.format(" %-15s%-6s%-15s%-15s%-15d\n", p.getBarcode(), well.getCoordinatesString(), well.getMsid(), chem == null || chem.isEmpty() ? "--" : chem, scanFiles.size()); System.out.flush(); } List<Integer> plateIds = Arrays.asList(platesById.keySet().toArray(new Integer[platesById.size()])); Collections.sort(plateIds); System.out.print("\nAppears in plates:\n"); for (Integer id : plateIds) { Plate p = platesById.get(id); System.out.format(" %s: %s\n", p.getBarcode(), p.getName()); } List<String> msids = Arrays.asList(uniqueMSIDs.toArray(new String[uniqueMSIDs.size()])); Collections.sort(msids); System.out.format("\nMSIDS: %s\n", StringUtils.join(msids, ", ")); Set<String> availableNegativeControls = new HashSet<>(); for (Map.Entry<Integer, Plate> entry : platesById.entrySet()) { List<LCMSWell> wells = LCMSWell.getInstance().getByPlateId(db, entry.getKey()); for (LCMSWell well : wells) { if (!construct.equals(well.getComposition())) { availableNegativeControls.add(well.getComposition()); } } } // Print available standards for each step w/ plate barcodes and coordinates. System.out.format("\nAvailable Standards:\n"); Map<Integer, Plate> plateCache = new HashMap<>(); for (ChemicalAssociatedWithPathway chem : pathwayChems) { List<StandardWell> matchingWells = StandardWell.getInstance().getStandardWellsByChemical(db, chem.getChemical()); for (StandardWell well : matchingWells) { if (!plateCache.containsKey(well.getPlateId())) { Plate p = Plate.getPlateById(db, well.getPlateId()); plateCache.put(p.getId(), p); } } Map<Integer, List<StandardWell>> standardWellsByPlateId = new HashMap<>(); for (StandardWell well : matchingWells) { List<StandardWell> plateWells = standardWellsByPlateId.get(well.getPlateId()); if (plateWells == null) { plateWells = new ArrayList<>(); standardWellsByPlateId.put(well.getPlateId(), plateWells); } plateWells.add(well); } List<Pair<String, Integer>> plateBarcodes = new ArrayList<>(plateCache.size()); for (Plate p : plateCache.values()) { if (p.getBarcode() == null) { plateBarcodes.add(Pair.of("(no barcode)", p.getId())); } else { plateBarcodes.add(Pair.of(p.getBarcode(), p.getId())); } } Collections.sort(plateBarcodes); System.out.format(" %s:\n", chem.getChemical()); for (Pair<String, Integer> barcodePair : plateBarcodes) { // TODO: hoist this whole sorting/translation step into a utility class. List<StandardWell> wells = standardWellsByPlateId.get(barcodePair.getRight()); if (wells == null) { // Don't print plates that don't apply to this chemical, which can happen because we're caching the plates. continue; } Collections.sort(wells, new Comparator<StandardWell>() { @Override public int compare(StandardWell o1, StandardWell o2) { int c = o1.getPlateRow().compareTo(o2.getPlateRow()); if (c != 0) return c; return o1.getPlateColumn().compareTo(o2.getPlateColumn()); } }); List<String> descriptions = new ArrayList<>(wells.size()); for (StandardWell well : wells) { descriptions.add(String.format("%s in %s%s", well.getCoordinatesString(), well.getMedia(), well.getConcentration() == null ? "" : String.format(" c. %f", well.getConcentration()))); } System.out.format(" %s: %s\n", barcodePair.getLeft(), StringUtils.join(descriptions, ", ")); } } List<String> negativeControlStrains = Arrays .asList(availableNegativeControls.toArray(new String[availableNegativeControls.size()])); Collections.sort(negativeControlStrains); System.out.format("\nAvailable negative controls: %s\n", StringUtils.join(negativeControlStrains, ",")); System.out.print("\n----------\n"); System.out.print("\n\n"); } }
From source file:de.clusteval.serverclient.BackendClient.java
/** * @param args// w w w.ja v a2 s.co m * Command line parameters for the backend client (see * {@link #params}). * @throws IOException */ @SuppressWarnings("unused") public static void main(String[] args) throws IOException { try { CommandLine params = parseParams(args, false); if (params.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("clustevalClient", clientCLIOptions); System.exit(0); } if (params.hasOption("version")) { System.out.println(VERSION); System.exit(0); } initLogging(params); Logger log = LoggerFactory.getLogger(BackendClient.class); System.out.println("Starting clusteval client"); System.out.println(VERSION); System.out.println("========================="); // if command line arguments (except connection parameters) are // passed, we do not start a console Set<String> paramKeys = new HashSet<String>(); @SuppressWarnings("unchecked") Iterator<Option> it = params.iterator(); while (it.hasNext()) { paramKeys.add(it.next().getOpt()); } paramKeys.remove("ip"); paramKeys.remove("port"); paramKeys.remove("clientId"); if (paramKeys.size() > 0) { try { new BackendClient(args); } catch (Exception e) { } } else { String clientId; if (params.hasOption("clientId")) clientId = params.getOptionValue("clientId"); else // parse args because of possible connection parameters clientId = new BackendClient(args).clientId; reader = new ConsoleReader(); List<Completer> completers = new LinkedList<Completer>(); completers.add(new BackendClientCompleter(clientId, args)); String ip = params.hasOption("ip") ? params.getOptionValue("ip") : "localhost"; String port = params.hasOption("port") ? params.getOptionValue("port") : "1099"; setDefaultPromptAndCompleter(ip, port, completers); String line; while ((line = reader.readLine()) != null) { if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit")) { break; } boolean connectException = false; do { try { new BackendClient( ArraysExt.merge(args, ("-clientId " + clientId + " -" + line).split(" "))); connectException = false; } catch (ConnectException e) { e.printStackTrace(); connectException = true; } catch (Exception e) { log.warn(e.getMessage()); } Thread.sleep(1000); } while (connectException); // } } } } catch (ParseException e) { System.err.println("Parsing failed. Reason: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("clustevalClient", "Invoking this client without any parameters will open a shell with tab-completion.", clientCLIOptions, "", true); } catch (Throwable t) { // t.printStackTrace(); } }
From source file:com.clustercontrol.nodemap.session.NodeMapControllerBean.java
public static void main(String[] args) { Set<String> oidList = new HashSet<String>(); oidList.add(SearchConnectionProperties.DEFAULT_OID_FDB); oidList.add(SearchConnectionProperties.DEFAULT_OID_ARP); DataTable tmpTable = Snmp4jPollerImpl.getInstance().polling("172.26.98.5", 161, 1, "public", 3, 5000, oidList, null, null, null, null, null, null); for (String key : tmpTable.keySet()) { System.out.println("key:" + key + ",value:" + tmpTable.getValue(key).getValue()); }//from ww w .ja va2 s .c o m }
From source file:com.zimbra.common.calendar.ZoneInfo2iCalendar.java
public static void main(String[] args) throws Exception { // command line handling CommandLine cl = null;// ww w . j a v a 2s. c om Params params = null; try { cl = parseArgs(args); if (cl.hasOption(OPT_HELP)) { usage(null); System.exit(0); } params = initParams(cl); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(1); } // parse tzdata source ZoneInfoParser parser = new ZoneInfoParser(); for (File tzdataFile : params.tzdataFiles) { Reader r = null; try { r = new InputStreamReader(new FileInputStream(tzdataFile), "UTF-8"); parser.readTzdata(r); } catch (ParseException e) { System.err.println(e.getMessage()); System.err.println("Line: " + e.getErrorOffset()); System.err.println("File: " + tzdataFile.getAbsolutePath()); e.printStackTrace(); System.exit(1); } finally { if (r != null) r.close(); } } parser.analyze(); // read extra data file containing primary TZ list and zone match scores if (params.extraDataFile != null) { Reader r = null; try { r = new InputStreamReader(new FileInputStream(params.extraDataFile), "UTF-8"); readExtraData(r); } catch (ParseException e) { System.err.println(e.getMessage()); System.err.println("Line: " + e.getErrorOffset()); System.err.println("File: " + params.extraDataFile.getAbsolutePath()); e.printStackTrace(); System.exit(1); } finally { if (r != null) r.close(); } } Writer out; if (params.outputFile != null) { out = new PrintWriter(params.outputFile, "UTF-8"); } else { out = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")); } try { StringBuilder hdr = new StringBuilder("BEGIN:VCALENDAR"); hdr.append(CRLF); hdr.append("PRODID:Zimbra-Calendar-Provider").append(CRLF); hdr.append("VERSION:2.0").append(CRLF); hdr.append("METHOD:PUBLISH").append(CRLF); out.write(hdr.toString()); Map<String, VTimeZone> oldTimeZones = makeOldTimeZonesMap(params); Set<Zone> zones = new TreeSet<Zone>(new ZoneComparatorByGmtOffset()); zones.addAll(parser.getZones()); Set<String> zoneIDs = new TreeSet<String>(); for (Zone zone : zones) { zoneIDs.add(zone.getName()); } for (Zone zone : zones) { out.write(getTimeZoneForZone(zone, params, zoneIDs, oldTimeZones)); } StringBuilder footer = new StringBuilder("END:VCALENDAR"); footer.append(CRLF); out.write(footer.toString()); } finally { out.close(); } }
From source file:com.edgenius.wiki.render.handler.MenuMacroHandler.java
public static void main(String[] args) { RenderContextImpl context = new RenderContextImpl(); LinkRenderHelperImpl linkRenderHelper = new LinkRenderHelperImpl(); linkRenderHelper.initialize(context, null, null); context.setLinkRenderHelper(linkRenderHelper); MenuMacroHandler h = new MenuMacroHandler(); Set<MenuItem> menuItems = new TreeSet<MenuItem>(new MenuItem.MenuItemComparator()); MenuItem m1 = new MenuItem(); m1.setTitle("m1"); m1.setPageTitle("t1"); m1.setPageUuid("pm1"); MenuItem m2 = new MenuItem(); m2.setTitle("m2"); m2.setPageTitle("t2"); m2.setPageUuid("pm2"); MenuItem m21 = new MenuItem(); m21.setTitle("m21"); m21.setPageUuid("pm21"); m21.setPageTitle("t21"); m21.setParent("pm2"); MenuItem m22 = new MenuItem(); m22.setTitle("m22"); m22.setPageUuid("pm22"); m22.setPageTitle("t22"); m22.setParent("pm2"); MenuItem m221 = new MenuItem(); m221.setTitle("m221"); m221.setPageTitle("t221"); m221.setPageUuid("pm221"); m221.setParent("pm22"); MenuItem m222 = new MenuItem(); m222.setTitle("m222"); m222.setPageTitle("t222"); m222.setPageUuid("pm222"); m222.setParent("pm22"); MenuItem m3 = new MenuItem(); m3.setTitle("m3"); m3.setPageTitle("t2"); m3.setPageUuid("pm3"); menuItems.add(m1); menuItems.add(m2);// www . jav a2 s. c o m menuItems.add(m21); menuItems.add(m22); menuItems.add(m221); menuItems.add(m222); menuItems.add(m3); System.out.println(h.buildMenu(context, menuItems)); }
From source file:ListAlgorithms.java
public static void main(String[] args) { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Provider[] providers = Security.getProviders(); Set<String> ciphers = new HashSet<String>(); Set<String> keyAgreements = new HashSet<String>(); Set<String> macs = new HashSet<String>(); Set<String> messageDigests = new HashSet<String>(); Set<String> signatures = new HashSet<String>(); Set<String> keyFactory = new HashSet<String>(); Set<String> keyPairGenerator = new HashSet<String>(); Set<String> keyGenerator = new HashSet<String>(); for (int i = 0; i != providers.length; i++) { Iterator it = providers[i].keySet().iterator(); while (it.hasNext()) { String entry = (String) it.next(); if (entry.startsWith("Alg.Alias.")) { entry = entry.substring("Alg.Alias.".length()); }/*from w w w .j a va 2s. c o m*/ if (entry.startsWith("Cipher.")) { ciphers.add(entry.substring("Cipher.".length())); } else if (entry.startsWith("KeyAgreement.")) { keyAgreements.add(entry.substring("KeyAgreement.".length())); } else if (entry.startsWith("Mac.")) { macs.add(entry.substring("Mac.".length())); } else if (entry.startsWith("MessageDigest.")) { messageDigests.add(entry.substring("MessageDigest.".length())); } else if (entry.startsWith("Signature.")) { signatures.add(entry.substring("Signature.".length())); } else if (entry.startsWith("KeyPairGenerator.")) { keyPairGenerator.add(entry.substring("KeyPairGenerator.".length())); } else if (entry.startsWith("KeyFactory.")) { keyFactory.add(entry.substring("KeyFactory.".length())); } else if (entry.startsWith("KeyGenerator.")) { keyGenerator.add(entry.substring("KeyGenerator.".length())); } else { System.out.println(entry); } } } printSet("KeyGenerator", keyGenerator); printSet("KeyFactory", keyFactory); printSet("KeyPairGenerator", keyPairGenerator); printSet("Ciphers", ciphers); printSet("KeyAgreeents", keyAgreements); printSet("Macs", macs); printSet("MessageDigests", messageDigests); printSet("Signatures", signatures); }