List of usage examples for java.util Set iterator
Iterator<E> iterator();
From source file:DaytimeServer.java
public static void main(String args[]) { try { // Handle startup exceptions at the end of this block // Get an encoder for converting strings to bytes CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder(); // Allow an alternative port for testing with non-root accounts int port = 13; // RFC867 specifies this port. if (args.length > 0) port = Integer.parseInt(args[0]); // The port we'll listen on SocketAddress localport = new InetSocketAddress(port); // Create and bind a tcp channel to listen for connections on. ServerSocketChannel tcpserver = ServerSocketChannel.open(); tcpserver.socket().bind(localport); // Also create and bind a DatagramChannel to listen on. DatagramChannel udpserver = DatagramChannel.open(); udpserver.socket().bind(localport); // Specify non-blocking mode for both channels, since our // Selector object will be doing the blocking for us. tcpserver.configureBlocking(false); udpserver.configureBlocking(false); // The Selector object is what allows us to block while waiting // for activity on either of the two channels. Selector selector = Selector.open(); // Register the channels with the selector, and specify what // conditions (a connection ready to accept, a datagram ready // to read) we'd like the Selector to wake up for. // These methods return SelectionKey objects, which we don't // need to retain in this example. tcpserver.register(selector, SelectionKey.OP_ACCEPT); udpserver.register(selector, SelectionKey.OP_READ); // This is an empty byte buffer to receive emtpy datagrams with. // If a datagram overflows the receive buffer size, the extra bytes // are automatically discarded, so we don't have to worry about // buffer overflow attacks here. ByteBuffer receiveBuffer = ByteBuffer.allocate(0); // Now loop forever, processing client connections for (;;) { try { // Handle per-connection problems below // Wait for a client to connect selector.select();/* w w w . j a v a 2 s . co m*/ // If we get here, a client has probably connected, so // put our response into a ByteBuffer. String date = new java.util.Date().toString() + "\r\n"; ByteBuffer response = encoder.encode(CharBuffer.wrap(date)); // Get the SelectionKey objects for the channels that have // activity on them. These are the keys returned by the // register() methods above. They are returned in a // java.util.Set. Set keys = selector.selectedKeys(); // Iterate through the Set of keys. for (Iterator i = keys.iterator(); i.hasNext();) { // Get a key from the set, and remove it from the set SelectionKey key = (SelectionKey) i.next(); i.remove(); // Get the channel associated with the key Channel c = (Channel) key.channel(); // Now test the key and the channel to find out // whether something happend on the TCP or UDP channel if (key.isAcceptable() && c == tcpserver) { // A client has attempted to connect via TCP. // Accept the connection now. SocketChannel client = tcpserver.accept(); // If we accepted the connection successfully, // the send our respone back to the client. if (client != null) { client.write(response); // send respone client.close(); // close connection } } else if (key.isReadable() && c == udpserver) { // A UDP datagram is waiting. Receive it now, // noting the address it was sent from. SocketAddress clientAddress = udpserver.receive(receiveBuffer); // If we got the datagram successfully, send // the date and time in a response packet. if (clientAddress != null) udpserver.send(response, clientAddress); } } } catch (java.io.IOException e) { // This is a (hopefully transient) problem with a single // connection: we log the error, but continue running. // We use our classname for the logger so that a sysadmin // can configure logging for this server independently // of other programs. Logger l = Logger.getLogger(DaytimeServer.class.getName()); l.log(Level.WARNING, "IOException in DaytimeServer", e); } catch (Throwable t) { // If anything else goes wrong (out of memory, for example) // then log the problem and exit. Logger l = Logger.getLogger(DaytimeServer.class.getName()); l.log(Level.SEVERE, "FATAL error in DaytimeServer", t); System.exit(1); } } } catch (Exception e) { // This is a startup error: there is no need to log it; // just print a message and exit System.err.println(e); System.exit(1); } }
From source file:com.bright.utils.rmDuplicateLines.java
public static void main(String args) { File monfile = new File(args); Set<String> userIdSet = new LinkedHashSet<String>(); if (monfile.isFile() && monfile.getName().endsWith(".txt")) { try {//from w w w. j a va 2 s. c o m List<String> content = FileUtils.readLines(monfile, Charset.forName("UTF-8")); userIdSet.addAll(content); Iterator<String> itr = userIdSet.iterator(); StringBuffer output = new StringBuffer(); while (itr.hasNext()) { output.append(itr.next() + System.getProperty("line.separator")); } BufferedWriter out = new BufferedWriter(new FileWriter(monfile)); String outText = output.toString(); out.write(outText); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:SyncTest.java
public static void main(String args[]) { Set simpsons = new HashSet(); simpsons.add("Bart"); simpsons.add("Hugo"); simpsons.add("Lisa"); simpsons.add("Marge"); simpsons.add("Homer"); simpsons.add("Maggie"); simpsons.add("Roy"); simpsons = Collections.synchronizedSet(simpsons); synchronized (simpsons) { Iterator iter = simpsons.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); }//from w w w . j ava 2s . com } Map map = Collections.synchronizedMap(new HashMap(89)); Set set = map.entrySet(); synchronized (map) { Iterator iter = set.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } } }
From source file:PrintServiceWebInterface.java
public static void main(String[] args) throws IOException { // Get the character encoders and decoders we'll need Charset charset = Charset.forName("ISO-8859-1"); CharsetEncoder encoder = charset.newEncoder(); // The HTTP headers we send back to the client are fixed String headers = "HTTP/1.1 200 OK\r\n" + "Content-type: text/html\r\n" + "Connection: close\r\n" + "\r\n"; // We'll use two buffers in our response. One holds the fixed // headers, and the other holds the variable body of the response. ByteBuffer[] buffers = new ByteBuffer[2]; buffers[0] = encoder.encode(CharBuffer.wrap(headers)); ByteBuffer body = ByteBuffer.allocateDirect(16 * 1024); buffers[1] = body;//from w ww . j av a2 s. c o m // Find all available PrintService objects to describe PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null); // All of the channels we use in this code will be in non-blocking // mode. So we create a Selector object that will block while // monitoring all of the channels and will only stop blocking when // one or more of the channels is ready for I/O of some sort. Selector selector = Selector.open(); // Create a new ServerSocketChannel, and bind it to port 8000. // Note that we have to do this using the underlying ServerSocket. ServerSocketChannel server = ServerSocketChannel.open(); server.socket().bind(new java.net.InetSocketAddress(8000)); // Put the ServerSocketChannel into non-blocking mode server.configureBlocking(false); // Now register the channel with the Selector. The SelectionKey // represents the registration of this channel with this Selector. SelectionKey serverkey = server.register(selector, SelectionKey.OP_ACCEPT); for (;;) { // The main server loop. The server runs forever. // This call blocks until there is activity on one of the // registered channels. This is the key method in non-blocking I/O. selector.select(); // Get a java.util.Set containing the SelectionKey objects for // all channels that are ready for I/O. Set keys = selector.selectedKeys(); // Use a java.util.Iterator to loop through the selected keys for (Iterator i = keys.iterator(); i.hasNext();) { // Get the next SelectionKey in the set, and then remove it // from the set. It must be removed explicitly, or it will // be returned again by the next call to select(). SelectionKey key = (SelectionKey) i.next(); i.remove(); // Check whether this key is the SelectionKey we got when // we registered the ServerSocketChannel. if (key == serverkey) { // Activity on the ServerSocketChannel means a client // is trying to connect to the server. if (key.isAcceptable()) { // Accept the client connection, and obtain a // SocketChannel to communicate with the client. SocketChannel client = server.accept(); // Make sure we actually got a connection if (client == null) continue; // Put the client channel in non-blocking mode. client.configureBlocking(false); // Now register the client channel with the Selector, // specifying that we'd like to know when there is // data ready to read on the channel. SelectionKey clientkey = client.register(selector, SelectionKey.OP_READ); } } else { // If the key we got from the Set of keys is not the // ServerSocketChannel key, then it must be a key // representing one of the client connections. // Get the channel from the key. SocketChannel client = (SocketChannel) key.channel(); // If we got here, it should mean that there is data to // be read from the channel, but we double-check here. if (!key.isReadable()) continue; // Now read bytes from the client. We assume that // we get all the client's bytes in one read operation client.read(body); // The data we read should be some kind of HTTP GET // request. We don't bother checking it however since // there is only one page of data we know how to return. body.clear(); // Build an HTML document as our reponse. // The body of the document contains PrintService details StringBuffer response = new StringBuffer(); response.append( "<html><head><title>Printer Status</title></head>" + "<body><h1>Printer Status</h1>"); for (int s = 0; s < services.length; s++) { PrintService service = services[s]; response.append("<h2>").append(service.getName()).append("</h2><table>"); Attribute[] attrs = service.getAttributes().toArray(); for (int a = 0; a < attrs.length; a++) { Attribute attr = attrs[a]; response.append("<tr><td>").append(attr.getName()).append("</td><td>").append(attr) .append("</tr>"); } response.append("</table>"); } response.append("</body></html>\r\n"); // Encode the response into the body ByteBuffer encoder.reset(); encoder.encode(CharBuffer.wrap(response), body, true); encoder.flush(body); body.flip(); // Prepare the body buffer to be drained // While there are bytes left to write while (body.hasRemaining()) { // Write both header and body buffers client.write(buffers); } buffers[0].flip(); // Prepare header buffer for next write body.clear(); // Prepare body buffer for next read // Once we've sent our response, we have no more interest // in the client channel or its SelectionKey client.close(); // Close the channel. key.cancel(); // Tell Selector to stop monitoring it. } } } }
From source file:SetTest.java
public static void main(String[] args) { Set<String> words = new HashSet<String>(); // HashSet implements Set long totalTime = 0; Scanner in = new Scanner(System.in); while (in.hasNext()) { String word = in.next();/*from w w w . j a v a2s . c om*/ long callTime = System.currentTimeMillis(); words.add(word); callTime = System.currentTimeMillis() - callTime; totalTime += callTime; } Iterator<String> iter = words.iterator(); for (int i = 1; i <= 20 && iter.hasNext(); i++) System.out.println(iter.next()); System.out.println(". . ."); System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds."); }
From source file:cosmos.example.BuildingPermitsExample.java
public static void main(String[] args) throws Exception { BuildingPermitsExample example = new BuildingPermitsExample(); new JCommander(example, args); File inputFile = new File(example.fileName); Preconditions.checkArgument(inputFile.exists() && inputFile.isFile() && inputFile.canRead(), "Expected " + example.fileName + " to be a readable file"); String zookeepers;/*ww w. ja va 2 s . com*/ String instanceName; Connector connector; MiniAccumuloCluster mac = null; File macDir = null; // Use the MiniAccumuloCluster is requested if (example.useMiniAccumuloCluster) { macDir = Files.createTempDir(); String password = "password"; MiniAccumuloConfig config = new MiniAccumuloConfig(macDir, password); config.setNumTservers(1); mac = new MiniAccumuloCluster(config); mac.start(); zookeepers = mac.getZooKeepers(); instanceName = mac.getInstanceName(); ZooKeeperInstance instance = new ZooKeeperInstance(instanceName, zookeepers); connector = instance.getConnector("root", new PasswordToken(password)); } else { // Otherwise connect to a running instance zookeepers = example.zookeepers; instanceName = example.instanceName; ZooKeeperInstance instance = new ZooKeeperInstance(instanceName, zookeepers); connector = instance.getConnector(example.username, new PasswordToken(example.password)); } // Instantiate an instance of Cosmos Cosmos cosmos = new CosmosImpl(zookeepers); // Create a definition for the data we want to load Store id = Store.create(connector, new Authorizations(), AscendingIndexIdentitySet.create()); // Register the definition with Cosmos so it can track its progress. cosmos.register(id); // Load all of the data from our inputFile LoadBuildingPermits loader = new LoadBuildingPermits(cosmos, id, inputFile); loader.run(); // Finalize the SortableResult which will prevent future writes to the data set cosmos.finalize(id); // Flush the ingest traces to the backend so we can see the results; id.sendTraces(); // Get back the Set of Columns that we've ingested. Set<Column> schema = Sets.newHashSet(cosmos.columns(id)); log.debug("\nColumns: " + schema); Iterator<Column> iter = schema.iterator(); while (iter.hasNext()) { Column c = iter.next(); // Remove the internal ID field and columns that begin with CONTRACTOR_ if (c.equals(LoadBuildingPermits.ID) || c.name().startsWith("CONTRACTOR_")) { iter.remove(); } } Iterable<Index> indices = Iterables.transform(schema, new Function<Column, Index>() { @Override public Index apply(Column col) { return Index.define(col); } }); // Ensure that we have locality groups set as we expect log.info("Ensure locality groups are set"); id.optimizeIndices(indices); // Compact down the data for this SortableResult log.info("Issuing compaction for relevant data"); id.consolidate(); final int numTopValues = 10; // Walk through each column in the result set for (Column c : schema) { Stopwatch sw = new Stopwatch(); sw.start(); // Get the number of times we've seen each value in a given column CloseableIterable<Entry<RecordValue<?>, Long>> groupingsInColumn = cosmos.groupResults(id, c); log.info(c.name() + ":"); // Iterate over the counts, collecting the top N values in each column TreeMap<Long, RecordValue<?>> topValues = Maps.newTreeMap(); for (Entry<RecordValue<?>, Long> entry : groupingsInColumn) { if (topValues.size() == numTopValues) { Entry<Long, RecordValue<?>> least = topValues.pollFirstEntry(); if (least.getKey() < entry.getValue()) { topValues.put(entry.getValue(), entry.getKey()); } else { topValues.put(least.getKey(), least.getValue()); } } else if (topValues.size() < numTopValues) { topValues.put(entry.getValue(), entry.getKey()); } } for (Long key : topValues.descendingKeySet()) { log.info(topValues.get(key).value() + " occurred " + key + " times"); } sw.stop(); log.info("Took " + sw.toString() + " to run query.\n"); } log.info("Deleting records"); // Delete the records we've ingested if (!example.useMiniAccumuloCluster) { // Because I'm lazy and don't want to wait around to run the BatchDeleter when we're just going // to rm -rf the directory in a few secs. cosmos.delete(id); } // And shut down Cosmos cosmos.close(); log.info("Cosmos stopped"); // If we were using MAC, also stop that if (example.useMiniAccumuloCluster && null != mac) { mac.stop(); if (null != macDir) { FileUtils.deleteDirectory(macDir); } } }
From source file:com.ibm.wala.cast.js.html.DomLessSourceExtractor.java
public static void main(String[] args) throws IOException, Error { // DomLessSourceExtractor domLessScopeGenerator = new DomLessSourceExtractor(); JSSourceExtractor domLessScopeGenerator = new DefaultSourceExtractor(); JSSourceExtractor.DELETE_UPON_EXIT = false; URL entrypointUrl = new URL(args[0]); IHtmlParser htmlParser = new JerichoHtmlParser(); IUrlResolver urlResolver = new IdentityUrlResolver(); Set<MappedSourceModule> res = domLessScopeGenerator.extractSources(entrypointUrl, htmlParser, urlResolver); MappedSourceModule entry = res.iterator().next(); System.out.println(entry);//from w ww . j ava2s. c o m System.out.println(entry.getMapping()); }
From source file:HashSetExample.java
public static void main(String[] args) { Set<Integer> set = new HashSet<Integer>(); set.add(new Integer(1)); set.add(new Integer(2)); set.add(new Integer(3)); set.add(new Integer(4)); set.add(new Integer(5)); set.add(new Integer(6)); set.add(new Integer(7)); set.add(new Integer(8)); set.add(new Integer(9)); set.add(new Integer(10)); // Use iterator to display the vsetes System.out.println("HashSet Before: "); for (Iterator i = set.iterator(); i.hasNext();) { Integer integer = (Integer) i.next(); System.out.println(integer); }//from ww w .j av a 2s . c o m // Remove the integer 6 System.out.println("\nRemove integer 6"); set.remove(new Integer(6)); // Use iterator to display the vsetes System.out.println("\nHashSet After: "); for (Iterator i = set.iterator(); i.hasNext();) { Integer integer = (Integer) i.next(); System.out.println(integer); } }
From source file:net.ontopia.topicmaps.cmdlineutils.rdbms.RDBMSIndexTool.java
public static void main(String[] argv) throws Exception { // Initialize logging CmdlineUtils.initializeLogging();//from w ww. j a v a 2s . c o m // Register logging options CmdlineOptions options = new CmdlineOptions("RDBMSIndexTool", argv); CmdlineUtils.registerLoggingOptions(options); // Parse command line options try { options.parse(); } catch (CmdlineOptions.OptionsException e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } // Get command line arguments String[] args = options.getArguments(); if (args.length != 1) { usage(); System.exit(3); } // load database schema project ClassLoader cloader = RDBMSIndexTool.class.getClassLoader(); InputStream istream = cloader.getResourceAsStream("net/ontopia/topicmaps/impl/rdbms/config/schema.xml"); Project dbp = DatabaseProjectReader.loadProject(istream); // open database connection String propfile = args[0]; ConnectionFactoryIF cf = new DefaultConnectionFactory(PropertyUtils.loadProperties(new File(propfile)), true); Connection conn = cf.requestConnection(); try { DatabaseMetaData dbm = conn.getMetaData(); boolean downcase = dbm.storesLowerCaseIdentifiers(); Map extra_indexes = new TreeMap(); Map missing_indexes = new TreeMap(); Iterator tables = dbp.getTables().iterator(); while (tables.hasNext()) { Table table = (Table) tables.next(); String table_name = (downcase ? table.getName().toLowerCase() : table.getName()); //! System.out.println("T :" + table_name); // get primary keys from database Map pkeys = getPrimaryKeys(table_name, dbm); // get indexes from database Map indexes = getIndexes(table_name, dbm); Map dindexes = new HashMap(); if (table.getPrimaryKeys() != null) { String pkey = table_name + '(' + StringUtils.join(table.getPrimaryKeys(), ',') + ')'; if (!pkeys.containsKey(pkey)) System.out.println("PKM: " + pkey); } Iterator iter = table.getIndexes().iterator(); while (iter.hasNext()) { Index index = (Index) iter.next(); String i = table_name + '(' + StringUtils.join(index.getColumns(), ',') + ')'; String index_name = (downcase ? index.getName().toLowerCase() : index.getName()); dindexes.put(i, index_name); } Set extra = new HashSet(indexes.keySet()); extra.removeAll(dindexes.keySet()); extra.removeAll(pkeys.keySet()); if (!extra.isEmpty()) { Iterator i = extra.iterator(); while (i.hasNext()) { Object k = i.next(); extra_indexes.put(k, indexes.get(k)); } } Set missing = new HashSet(dindexes.keySet()); missing.addAll(pkeys.keySet()); missing.removeAll(indexes.keySet()); if (!missing.isEmpty()) { Iterator i = missing.iterator(); while (i.hasNext()) { Object k = i.next(); missing_indexes.put(k, dindexes.get(k)); } } } if (!extra_indexes.isEmpty()) System.out.println("/* --- Extra indexes ----------------------------------------- */"); Iterator eiter = extra_indexes.keySet().iterator(); while (eiter.hasNext()) { Object k = eiter.next(); System.out.println("drop index " + extra_indexes.get(k) + "; /* " + k + " */"); } if (!missing_indexes.isEmpty()) System.out.println("/* --- Missing indexes---------------------------------------- */"); Iterator miter = missing_indexes.keySet().iterator(); while (miter.hasNext()) { Object k = miter.next(); System.out.println("create index " + missing_indexes.get(k) + " on " + k + ";"); } } finally { conn.rollback(); conn.close(); } }
From source file:TreeSetExample.java
public static void main(String[] args) { // Create a new TreeSet Set<Integer> set = new TreeSet<Integer>(); // Add Items to the TreeSet set.add(new Integer(1)); set.add(new Integer(2)); set.add(new Integer(3)); set.add(new Integer(4)); set.add(new Integer(5)); set.add(new Integer(6)); set.add(new Integer(7)); set.add(new Integer(8)); set.add(new Integer(9)); set.add(new Integer(10)); // Use iterator to display the vsetes System.out.println("TreeSet Before: "); for (Iterator i = set.iterator(); i.hasNext();) { Integer integer = (Integer) i.next(); System.out.println(integer); }/* w ww . jav a2 s. c om*/ // Remove the integer 6 System.out.println("\nRemove Integer 6"); set.remove(new Integer(6)); // Use iterator to display the vsetes System.out.println("\nTreeSet After: "); for (Iterator i = set.iterator(); i.hasNext();) { Integer integer = (Integer) i.next(); System.out.println(integer); } }