List of usage examples for java.util Map values
Collection<V> values();
From source file:Main.java
public static void main(String[] argv) throws Exception { Map<String, Integer> map = new HashMap<String, Integer>(); map = new TreeMap(); map.put("a", new Integer(1)); map.put("b", new Integer(2)); map.put("c", new Integer(3)); int size = map.size(); // 2 Object oldValue = map.put("a", new Integer(9)); // 1 oldValue = map.remove("c"); // 3 Iterator it = map.keySet().iterator(); while (it.hasNext()) { Object key = it.next();// w w w.ja v a 2s. c o m } it = map.values().iterator(); while (it.hasNext()) { Object value = it.next(); } }
From source file:net.gplatform.sudoor.server.test.unit.CaptchaValidatorTest.java
public static void main(String[] args) { init();//from w w w .j a va2s. c o m String inputCaptcha = "123"; boolean response = true; WebTarget captchaImgTarget = client .target("http://localhost:8080/sudoor" + "/app/sudoor/captcha-image.html"); Response captchaImgResponse = captchaImgTarget.request(MediaType.WILDCARD_TYPE).get(); Map<String, NewCookie> captchaImgCookies = captchaImgResponse.getCookies(); assert (captchaImgResponse.getStatus() == 200); WebTarget validateTarget = client.target("http://localhost:8080/sudoor" + "/data/ws/rest") .path("/sudoor/captcha/validate").queryParam("_captcha", inputCaptcha); Builder validateBuilder = validateTarget.request(MediaType.WILDCARD_TYPE); for (Iterator iterator = captchaImgCookies.values().iterator(); iterator.hasNext();) { Cookie cookie = (Cookie) iterator.next(); validateBuilder.cookie(cookie); } Response validateResponse = validateBuilder.get(); assert (validateResponse.getStatus() == 200); boolean res = validateResponse.readEntity(boolean.class); assert (res == response); }
From source file:ArrayMap.java
public static void main(String args[]) { Map map = new ArrayMap(13); map.put("1", "One"); map.put("2", "Two"); map.put("3", "Three"); map.put("4", "Four"); map.put("5", "Five"); map.put("6", "Six"); map.put("7", "Seven"); map.put("8", "Eight"); map.put("9", "Nine"); map.put("10", "Ten"); map.put("11", "Eleven"); map.put("12", "Twelve"); map.put("13", "Thirteen"); System.out.println(map);/*from w w w. j a v a 2 s . co m*/ System.out.println(map.keySet()); System.out.println(map.values()); }
From source file:ClassFileUtilities.java
/** * Program that computes the dependencies between the Batik jars. * <p>//from w w w . jav a 2 s . com * Run this from the main Batik distribution directory, after building * the jars. For every jar file in the batik-xxx/ build directory, * it will determine which other jar files it directly depends on. * The output is lines of the form: * </p> * <pre> <i>number</i>,<i>from</i>,<i>to</i></pre> * <p> * where mean that the <i>from</i> jar has <i>number</i> class files * that depend on class files in the <i>to</i> jar. * </p> */ public static void main(String[] args) { boolean showFiles = false; if (args.length == 1 && args[0].equals("-f")) { showFiles = true; } else if (args.length != 0) { System.err.println("usage: ClassFileUtilities [-f]"); System.err.println(); System.err.println(" -f list files that cause each jar file dependency"); System.exit(1); } File cwd = new File("."); File buildDir = null; String[] cwdFiles = cwd.list(); for (int i = 0; i < cwdFiles.length; i++) { if (cwdFiles[i].startsWith("batik-")) { buildDir = new File(cwdFiles[i]); if (!buildDir.isDirectory()) { buildDir = null; } else { break; } } } if (buildDir == null || !buildDir.isDirectory()) { System.out.println("Directory 'batik-xxx' not found in current directory!"); return; } try { Map cs = new HashMap(); Map js = new HashMap(); collectJars(buildDir, js, cs); Set classpath = new HashSet(); Iterator i = js.values().iterator(); while (i.hasNext()) { classpath.add(((Jar) i.next()).jarFile); } i = cs.values().iterator(); while (i.hasNext()) { ClassFile fromFile = (ClassFile) i.next(); // System.out.println(fromFile.name); Set result = getClassDependencies(fromFile.getInputStream(), classpath, false); Iterator j = result.iterator(); while (j.hasNext()) { ClassFile toFile = (ClassFile) cs.get(j.next()); if (fromFile != toFile && toFile != null) { fromFile.deps.add(toFile); } } } i = cs.values().iterator(); while (i.hasNext()) { ClassFile fromFile = (ClassFile) i.next(); Iterator j = fromFile.deps.iterator(); while (j.hasNext()) { ClassFile toFile = (ClassFile) j.next(); Jar fromJar = fromFile.jar; Jar toJar = toFile.jar; if (fromFile.name.equals(toFile.name) || toJar == fromJar || fromJar.files.contains(toFile.name)) { continue; } Integer n = (Integer) fromJar.deps.get(toJar); if (n == null) { fromJar.deps.put(toJar, new Integer(1)); } else { fromJar.deps.put(toJar, new Integer(n.intValue() + 1)); } } } List triples = new ArrayList(10); i = js.values().iterator(); while (i.hasNext()) { Jar fromJar = (Jar) i.next(); Iterator j = fromJar.deps.keySet().iterator(); while (j.hasNext()) { Jar toJar = (Jar) j.next(); Triple t = new Triple(); t.from = fromJar; t.to = toJar; t.count = ((Integer) fromJar.deps.get(toJar)).intValue(); triples.add(t); } } Collections.sort(triples); i = triples.iterator(); while (i.hasNext()) { Triple t = (Triple) i.next(); System.out.println(t.count + "," + t.from.name + "," + t.to.name); if (showFiles) { Iterator j = t.from.files.iterator(); while (j.hasNext()) { ClassFile fromFile = (ClassFile) j.next(); Iterator k = fromFile.deps.iterator(); while (k.hasNext()) { ClassFile toFile = (ClassFile) k.next(); if (toFile.jar == t.to && !t.from.files.contains(toFile.name)) { System.out.println("\t" + fromFile.name + " --> " + toFile.name); } } } } } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.mmounirou.spotirss.SpotiRss.java
/** * @param args/* ww w . j a v a 2s . c om*/ * @throws IOException * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InstantiationException * @throws SpotifyClientException * @throws ChartRssException * @throws SpotifyException */ public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SpotifyClientException { if (args.length == 0) { System.err.println("usage : java -jar spotiboard.jar <charts-folder>"); return; } Properties connProperties = new Properties(); InputStream inStream = SpotiRss.class.getResourceAsStream("/spotify-server.properties"); try { connProperties.load(inStream); } finally { IOUtils.closeQuietly(inStream); } String host = connProperties.getProperty("host"); int port = Integer.parseInt(connProperties.getProperty("port")); String user = connProperties.getProperty("user"); final SpotifyClient spotifyClient = new SpotifyClient(host, port, user); final Map<String, Playlist> playlistsByTitle = getPlaylistsByTitle(spotifyClient); final File outputDir = new File(args[0]); outputDir.mkdirs(); TrackCache cache = new TrackCache(); try { for (String strProvider : PROVIDERS) { String providerClassName = EntryToTrackConverter.class.getPackage().getName() + "." + StringUtils.capitalize(strProvider); final EntryToTrackConverter converter = (EntryToTrackConverter) SpotiRss.class.getClassLoader() .loadClass(providerClassName).newInstance(); Iterable<String> chartsRss = getCharts(strProvider); final File resultDir = new File(outputDir, strProvider); resultDir.mkdir(); final SpotifyHrefQuery hrefQuery = new SpotifyHrefQuery(cache); Iterable<String> results = FluentIterable.from(chartsRss).transform(new Function<String, String>() { @Override @Nullable public String apply(@Nullable String chartRss) { try { long begin = System.currentTimeMillis(); ChartRss bilboardChartRss = ChartRss.getInstance(chartRss, converter); Map<Track, String> trackHrefs = hrefQuery.getTrackHrefs(bilboardChartRss.getSongs()); String strTitle = bilboardChartRss.getTitle(); File resultFile = new File(resultDir, strTitle); List<String> lines = Lists.newLinkedList(FluentIterable.from(trackHrefs.keySet()) .transform(Functions.toStringFunction())); lines.addAll(trackHrefs.values()); FileUtils.writeLines(resultFile, Charsets.UTF_8.displayName(), lines); Playlist playlist = playlistsByTitle.get(strTitle); if (playlist != null) { playlist.getTracks().clear(); playlist.getTracks().addAll(trackHrefs.values()); spotifyClient.patch(playlist); LOGGER.info(String.format("%s chart exported patched", strTitle)); } LOGGER.info(String.format("%s chart exported in %s in %d s", strTitle, resultFile.getAbsolutePath(), (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - begin))); } catch (Exception e) { LOGGER.error(String.format("fail to export %s charts", chartRss), e); } return ""; } }); // consume iterables Iterables.size(results); } } finally { cache.close(); } }
From source file:net.landora.justintv.JustinTVAPI.java
public static void main(String[] args) throws Exception { List<JustinArchive> archives = readArchives("tsmtournaments", 64); Map<String, List<JustinArchive>> groups = new HashMap<String, List<JustinArchive>>(); for (int i = 0; i < archives.size(); i++) { JustinArchive archive = archives.get(i); List<JustinArchive> group = groups.get(archive.getBroadcastId()); if (group == null) { group = new ArrayList<JustinArchive>(archive.getBroadcastPart()); groups.put(archive.getBroadcastId(), group); }//from w w w .ja v a 2s. c o m group.add(archive); } BroadcastSorter sorter = new BroadcastSorter(); for (List<JustinArchive> group : groups.values()) { Collections.sort(group, sorter); JustinArchive base = group.get(group.size() - 1); StringBuffer cmd = new StringBuffer(); cmd.append("mkvmerge -o \""); cmd.append(base.getBroadcastId()); cmd.append(" - "); cmd.append(base.getTitle()); cmd.append("\" "); for (int i = 0; i < group.size(); i++) { JustinArchive archive = group.get(i); if (i > 0) cmd.append("+ "); cmd.append(archive.getId()); cmd.append(".mkv "); } System.out.println(cmd); } }
From source file:com.me.jvmi.Main.java
public static void main(String[] args) throws IOException { final Path localProductImagesPath = Paths.get("/Volumes/jvmpubfs/WEB/images/products/"); final Path uploadCSVFile = Paths.get("/Users/jbabic/Documents/products/upload.csv"); final Config config = new Config(Paths.get("../config.properties")); LuminateOnlineClient luminateClient2 = new LuminateOnlineClient("https://secure2.convio.net/jvmi/admin/", 3);/*from ww w.j a va2s . c o m*/ luminateClient2.login(config.luminateUser(), config.luminatePassword()); Set<String> completed = new HashSet<>( IOUtils.readLines(Files.newBufferedReader(Paths.get("completed.txt")))); try (InputStream is = Files.newInputStream(Paths.get("donforms.csv")); PrintWriter pw = new PrintWriter(new FileOutputStream(new File("completed.txt"), true))) { for (String line : IOUtils.readLines(is)) { if (completed.contains(line)) { System.out.println("completed: " + line); continue; } try { luminateClient2.editDonationForm(line, "-1"); pw.println(line); System.out.println("done: " + line); pw.flush(); } catch (Exception e) { System.out.println("skipping: " + line); e.printStackTrace(); } } } // luminateClient2.editDonationForm("8840", "-1"); // Collection<String> ids = luminateClient2.donFormSearch("", true); // // CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n"); // try (FileWriter fileWriter = new FileWriter(new File("donforms.csv")); // CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);) { // // for (String id : ids) { // csvFilePrinter.printRecord(id); // } // } // if (true) { return; } Collection<InputRecord> records = parseInput(uploadCSVFile); LuminateFTPClient ftp = new LuminateFTPClient("customerftp.convio.net"); ftp.login(config.ftpUser(), config.ftpPassword()); ProductImages images = new ProductImages(localProductImagesPath, ftp); validateImages(records, images); Map<String, DPCSClient> dpcsClients = new HashMap<>(); dpcsClients.put("us", new DPCSClient("https://donor.dpconsulting.com/NewDDI/Logon.asp?client=jvm")); dpcsClients.put("ca", new DPCSClient("https://donor.dpconsulting.com/NewDDI/Logon.asp?client=jvcn")); dpcsClients.put("uk", new DPCSClient("https://donor.dpconsulting.com/NewDDI/Logon.asp?client=jvuk")); for (DPCSClient client : dpcsClients.values()) { client.login(config.dpcsUser(), config.dpcsPassword()); } Map<String, LuminateOnlineClient> luminateClients = new HashMap<>(); luminateClients.put("us", new LuminateOnlineClient("https://secure2.convio.net/jvmi/admin/", 10)); luminateClients.put("ca", new LuminateOnlineClient("https://secure3.convio.net/jvmica/admin/", 10)); luminateClients.put("uk", new LuminateOnlineClient("https://secure3.convio.net/jvmiuk/admin/", 10)); Map<String, EcommerceProductFactory> ecommFactories = new HashMap<>(); ecommFactories.put("us", new EcommerceProductFactory(dpcsClients.get("us"), images, Categories.us)); ecommFactories.put("ca", new EcommerceProductFactory(dpcsClients.get("ca"), images, Categories.ca)); ecommFactories.put("uk", new EcommerceProductFactory(dpcsClients.get("uk"), images, Categories.uk)); List<String> countries = Arrays.asList("us", "ca", "uk"); boolean error = false; for (InputRecord record : records) { for (String country : countries) { if (record.ignore(country)) { System.out.println("IGNORE: " + country + " " + record); continue; } try { EcommerceProductFactory ecommFactory = ecommFactories.get(country); LuminateOnlineClient luminateClient = luminateClients.get(country); luminateClient.login(config.luminateUser(), config.luminatePassword()); ECommerceProduct product = ecommFactory.createECommerceProduct(record); luminateClient.createOrUpdateProduct(product); } catch (Exception e) { System.out.println("ERROR: " + country + " " + record); //System.out.println(e.getMessage()); error = true; e.printStackTrace(); } } } if (!error) { for (String country : countries) { LuminateOnlineClient luminateClient = luminateClients.get(country); DPCSClient dpcsClient = dpcsClients.get(country); luminateClient.close(); dpcsClient.close(); } } }
From source file:discovery.DiscoveryExample.java
public static void main(String[] args) throws Exception { // This method is scaffolding to get the example up and running TestingServer server = new TestingServer(); CuratorFramework client = null;/*from w w w. j a v a2 s .c o m*/ ServiceDiscovery<InstanceDetails> serviceDiscovery = null; Map<String, ServiceProvider<InstanceDetails>> providers = Maps.newHashMap(); try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); client.start(); JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>( InstanceDetails.class); serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(PATH) .serializer(serializer).build(); serviceDiscovery.start(); processCommands(serviceDiscovery, providers, client); } finally { for (ServiceProvider<InstanceDetails> cache : providers.values()) { IOUtils.closeQuietly(cache); } IOUtils.closeQuietly(serviceDiscovery); IOUtils.closeQuietly(client); IOUtils.closeQuietly(server); } }
From source file:edu.clemson.cs.nestbed.server.tools.BuildTestbed.java
public static void main(String[] args) { try {//from www . j a va 2s. c o m BasicConfigurator.configure(); //loadProperties(); if (args.length < 2) { System.out.println("Usage: BuildTestbed <testbedID> <inputfile>"); System.exit(0); } int testbedID = Integer.parseInt(args[0]); String filename = args[1]; Connection conn = null; Statement statement = null; MoteSqlAdapter adapter = new MoteSqlAdapter(); Map<Integer, Mote> motes = adapter.readMotes(); log.info(motes); String connStr = System.getProperty("nestbed.options.databaseConnectionString"); log.info("connStr: " + connStr); conn = DriverManager.getConnection(connStr); statement = conn.createStatement(); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line; while ((line = in.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line); int address = Integer.parseInt(tokenizer.nextToken()); String serial = tokenizer.nextToken(); int xLoc = Integer.parseInt(tokenizer.nextToken()); int yLoc = Integer.parseInt(tokenizer.nextToken()); log.info("Input Mote:\n" + "-----------\n" + "address: " + address + "\n" + "serial: " + serial + "\n" + "xLoc: " + xLoc + "\n" + "yLoc: " + yLoc); for (Mote i : motes.values()) { if (i.getMoteSerialID().equals(serial)) { String query = "INSERT INTO MoteTestbedAssignments" + "(testbedID, moteID, moteAddress," + " moteLocationX, moteLocationY) VALUES (" + testbedID + ", " + i.getID() + ", " + address + ", " + xLoc + ", " + yLoc + ")"; log.info(query); statement.executeUpdate(query); } } } conn.commit(); } catch (Exception ex) { log.error("Exception in main", ex); } }
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());//from w ww . j a va 2s . 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); } 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"); } }