List of usage examples for java.util NavigableMap size
int size();
From source file:com.google.gwt.emultest.java.util.TreeMapTest.java
public void testEntrySet() { K[] keys = getSortedKeys();//from ww w .ja va 2 s. c o m V[] values = getSortedValues(); NavigableMap<K, V> map = createNavigableMap(); map.put(keys[0], values[0]); map.put(keys[1], values[1]); map.put(keys[2], values[2]); Set<Map.Entry<K, V>> entries = map.entrySet(); Iterator<Map.Entry<K, V>> entrySetIterator = entries.iterator(); assertEquals(3, entries.size()); assertEquals(keys[0] + "=" + values[0], entrySetIterator.next().toString()); while (entrySetIterator.hasNext()) { Map.Entry<K, V> entry = entrySetIterator.next(); assertTrue(map.get(entry.getKey()) == entry.getValue()); } assertEquals(map.size(), entries.size()); _assertEquals(entries, map.entrySet()); map.clear(); assertEquals(map.size(), entries.size()); _assertEquals(entries, map.entrySet()); map.put(keys[0], values[0]); assertEquals(map.size(), entries.size()); _assertEquals(entries, map.entrySet()); entries.clear(); assertEquals(map.size(), entries.size()); _assertEquals(entries, map.entrySet()); map.put(keys[1], values[1]); map.put(keys[2], values[2]); Iterator<Entry<K, V>> it = entries.iterator(); while (it.hasNext()) { Map.Entry<K, V> entry = it.next(); map.containsKey(entry.getKey()); map.containsValue(entry.getValue()); it.remove(); } try { it.next(); fail("should throw NoSuchElementException"); } catch (NoSuchElementException expected) { } _assertEmpty(map); }
From source file:com.google.gwt.emultest.java.util.TreeMapTest.java
public void testDescendingMap() { K[] keys = getSortedKeys();/*from ww w .j a v a 2s .c om*/ V[] values = getSortedValues(); NavigableMap<K, V> map = createNavigableMap(); map.put(keys[0], values[0]); NavigableMap<K, V> descendingMap = map.descendingMap(); _assertEquals(descendingMap, map.descendingMap()); map.put(keys[1], values[1]); _assertEquals(map, descendingMap.descendingMap()); _assertEquals(reverseCollection(map.entrySet()), descendingMap.entrySet()); descendingMap.put(keys[2], values[2]); _assertEquals(reverseCollection(map.entrySet()), descendingMap.entrySet()); _assertEquals(map.entrySet(), descendingMap.descendingMap().entrySet()); descendingMap.remove(keys[1]); _assertEquals(reverseCollection(map.entrySet()), descendingMap.entrySet()); descendingMap.clear(); assertEquals(0, descendingMap.size()); assertEquals(0, map.size()); map.put(keys[0], values[0]); map.put(keys[1], values[1]); map.put(keys[2], values[2]); assertEquals(3, descendingMap.size()); NavigableMap<K, V> headMap = descendingMap.headMap(keys[1], false); assertEquals(1, headMap.size()); assertTrue(headMap.containsKey(keys[2])); NavigableMap<K, V> subMap = descendingMap.subMap(keys[2], true, keys[1], true); assertEquals(2, subMap.size()); assertTrue(subMap.containsKey(keys[1])); assertTrue(subMap.containsKey(keys[2])); NavigableMap<K, V> tailMap = descendingMap.tailMap(keys[1], false); assertEquals(1, tailMap.size()); assertTrue(tailMap.containsKey(keys[0])); }
From source file:com.google.gwt.emultest.java.util.TreeMapTest.java
public void testSubMap_entrySet() { K[] keys = getSortedKeys();/*from w w w. j ava2 s . co m*/ V[] values = getSortedValues(); NavigableMap<K, V> map = createNavigableMap(); map.put(keys[0], values[0]); map.put(keys[1], values[1]); map.put(keys[2], values[2]); map.put(keys[3], values[3]); SortedMap<K, V> subMap = map.subMap(keys[1], keys[3]); Set<Entry<K, V>> entries = subMap.entrySet(); assertEquals(2, subMap.size()); assertEquals(subMap.size(), entries.size()); assertFalse(entries.contains(new SimpleEntry<K, V>(keys[0], values[0]))); assertTrue(entries.contains(new SimpleEntry<K, V>(keys[1], values[1]))); assertTrue(entries.contains(new SimpleEntry<K, V>(keys[2], values[2]))); assertFalse(entries.contains(new SimpleEntry<K, V>(keys[3], values[3]))); entries.remove(new SimpleEntry<K, V>(keys[1], values[1])); assertEquals(3, map.size()); assertEquals(subMap.size(), entries.size()); assertFalse(entries.contains(new SimpleEntry<K, V>(keys[1], values[1]))); assertFalse(subMap.containsKey(keys[1])); assertFalse(subMap.containsValue(values[1])); entries.clear(); assertEquals(2, map.size()); assertEquals(subMap.size(), entries.size()); assertTrue(entries.isEmpty()); assertTrue(subMap.isEmpty()); subMap.put(keys[2], values[2]); assertEquals(1, subMap.size()); assertEquals(subMap.size(), entries.size()); subMap.put(keys[1], values[1]); Iterator<Entry<K, V>> it = entries.iterator(); while (it.hasNext()) { Map.Entry<K, V> entry = it.next(); subMap.containsKey(entry.getKey()); subMap.containsValue(entry.getValue()); it.remove(); } try { it.next(); fail("should throw NoSuchElementException"); } catch (NoSuchElementException expected) { } assertEquals(2, map.size()); assertEquals(0, subMap.size()); assertEquals(subMap.size(), entries.size()); map = createNavigableMap(); Set<Entry<K, V>> entrySet = map.entrySet(); map.put(keys[0], values[0]); map.put(keys[1], values[1]); map.put(keys[2], values[2]); assertEquals(map.size(), entrySet.size()); _assertEquals(entrySet, map.entrySet()); map.clear(); assertEquals(map.size(), entrySet.size()); _assertEquals(entrySet, map.entrySet()); map.put(keys[0], values[0]); assertEquals(map.size(), entrySet.size()); _assertEquals(entrySet, map.entrySet()); entrySet.clear(); assertEquals(map.size(), entrySet.size()); _assertEquals(entrySet, map.entrySet()); }
From source file:com.google.gwt.emultest.java.util.TreeMapTest.java
public void testHeadMapLjava_lang_ObjectZL() { K[] keys = getSortedKeys();/*w w w .ja v a 2s . co m*/ V[] values = getSortedValues(); NavigableMap<K, V> map = createNavigableMap(); for (int i = 0; i < keys.length; i++) { map.put(keys[i], values[i]); } // normal case SortedMap<K, V> subMap = map.headMap(keys[2], true); assertEquals(3, subMap.size()); subMap = map.headMap(keys[3], true); assertEquals(4, subMap.size()); for (int i = 0; i < 4; i++) { assertEquals(values[i], subMap.get(keys[i])); } subMap = map.headMap(keys[2], false); assertEquals(2, subMap.size()); assertNull(subMap.get(keys[3])); // Exceptions assertEquals(0, map.headMap(keys[0], false).size()); try { map.headMap(null, true); assertTrue("expected exception", useNullKey()); } catch (NullPointerException e) { assertFalse("unexpected NPE", useNullKey()); } try { map.headMap(null, false); assertTrue("expected exception", useNullKey()); } catch (NullPointerException e) { assertFalse("unexpected NPE", useNullKey()); } subMap = map.headMap(keys[2]); assertEquals(2, subMap.size()); try { subMap.put(keys[2], values[2]); fail("should throw IllegalArgumentException"); } catch (IllegalArgumentException expected) { } assertEquals(keys.length, map.size()); subMap = map.headMap(keys[2], true); assertEquals(3, subMap.size()); subMap.remove(keys[1]); assertFalse(subMap.containsKey(keys[1])); assertFalse(subMap.containsValue(values[1])); assertFalse(map.containsKey(keys[1])); assertFalse(map.containsValue(values[1])); assertEquals(2, subMap.size()); assertEquals(keys.length - 1, map.size()); subMap.put(keys[1], values[1]); try { subMap.subMap(keys[1], keys[3]); fail("should throw IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { subMap.subMap(keys[3], keys[1]); fail("should throw IllegalArgumentException"); } catch (IllegalArgumentException expected) { } if (useNullKey() && useNullValue()) { map.put(null, null); subMap = map.headMap(null, true); assertEquals(1, subMap.size()); assertTrue(subMap.containsValue(null)); assertNull(subMap.get(null)); subMap = map.subMap(null, false, keys[2], true); assertEquals(3, subMap.size()); Set<K> keySet = subMap.keySet(); assertEquals(3, keySet.size()); Set<Map.Entry<K, V>> entrySet = subMap.entrySet(); assertEquals(3, entrySet.size()); Collection<V> valueCollection = subMap.values(); assertEquals(3, valueCollection.size()); map.remove(null); } // head map of head map NavigableMap<K, V> headMap = map.headMap(keys[3], true); assertEquals(4, headMap.size()); headMap = headMap.headMap(keys[3], false); assertEquals(3, headMap.size()); headMap = headMap.headMap(keys[2], false); assertEquals(2, headMap.size()); headMap = headMap.tailMap(keys[0], false); assertEquals(1, headMap.size()); headMap = headMap.tailMap(keys[1], false); assertEquals(0, headMap.size()); }
From source file:com.google.gwt.emultest.java.util.TreeMapTest.java
public void testNavigableKeySet() { K[] keys = getSortedKeys();/*from w ww . ja v a 2 s. c om*/ V[] values = getSortedValues(); NavigableMap<K, V> map = createNavigableMap(); map.put(keys[0], values[0]); Set<K> keySet = map.navigableKeySet(); _assertEquals(keySet, map.navigableKeySet()); map.put(keys[1], values[1]); map.put(keys[2], values[2]); _assertEquals(map.navigableKeySet(), keySet); _assertEquals(keySet, keySet); try { keySet.add(keys[3]); fail("should throw UnsupportedOperationException"); } catch (UnsupportedOperationException expected) { } try { keySet.add(null); fail("should throw UnsupportedOperationException"); } catch (UnsupportedOperationException expected) { } try { keySet.addAll(null); fail("should throw NullPointerException"); } catch (NullPointerException expected) { } Collection<K> collection = new ArrayList<K>(); keySet.addAll(collection); try { collection.add(keys[3]); keySet.addAll(collection); fail("should throw UnsupportedOperationException"); } catch (UnsupportedOperationException expected) { } Iterator<K> iter = keySet.iterator(); iter.next(); iter.remove(); assertFalse(map.containsKey(keys[0])); collection = new ArrayList<K>(); collection.add(keys[2]); keySet.retainAll(collection); assertEquals(1, map.size()); assertTrue(keySet.contains(keys[2])); keySet.removeAll(collection); _assertEmpty(map); map.put(keys[0], values[0]); assertEquals(1, map.size()); assertTrue(keySet.contains(keys[0])); keySet.clear(); _assertEmpty(map); }
From source file:nz.co.fortytwo.signalk.model.impl.SignalKModelFactory.java
/** * Save the current state of the signalk config * /*from ww w. j a v a 2s. c o m*/ * @throws IOException */ public static void saveConfig(SignalKModel model) throws IOException { if (model != null) { File jsonFile = new File(SIGNALK_CFG_SAVE_FILE); NavigableMap<String, Object> config = model.getSubMap(SignalKConstants.CONFIG); JsonSerializer ser = new JsonSerializer(); ser.setPretty(3); StringBuffer buffer = new StringBuffer(); if (config != null && config.size() > 0) { ser.write(config.entrySet().iterator(), '.', buffer); } else { buffer.append("{}"); } FileUtils.writeStringToFile(jsonFile, buffer.toString()); logger.debug(" Saved model state to " + SIGNALK_CFG_SAVE_FILE); } }
From source file:org.alfresco.repo.imap.ImapServiceImpl.java
/** * Search for emails in specified folder depending on view mode. * //from ww w . j a va 2s . c o m * Shallow list of files * * @param contextNodeRef context folder for search * @param viewMode context folder view mode * @return list of emails that context folder contains. */ public FolderStatus getFolderStatus(final String userName, final NodeRef contextNodeRef, ImapViewMode viewMode) { if (logger.isDebugEnabled()) { logger.debug("getFolderStatus contextNodeRef=" + contextNodeRef + ", viewMode=" + viewMode); } // No need to ACL check the change token read String changeToken = AuthenticationUtil.runAs(new RunAsWork<String>() { @Override public String doWork() throws Exception { return (String) nodeService.getProperty(contextNodeRef, ImapModel.PROP_CHANGE_TOKEN); } }, AuthenticationUtil.getSystemUserName()); Pair<String, String> cacheKey = null; if (changeToken != null) { cacheKey = new Pair<String, String>(userName, changeToken); this.folderCacheLock.readLock().lock(); try { FolderStatus result = this.folderCache.get(cacheKey); if (result != null) { return result; } } finally { this.folderCacheLock.readLock().unlock(); } } List<FileInfo> fileInfos = null; FileFilterMode.setClient(Client.imap); try { fileInfos = fileFolderService.listFiles(contextNodeRef); } finally { FileFilterMode.clearClient(); } final NavigableMap<Long, FileInfo> currentSearch = new TreeMap<Long, FileInfo>(); switch (viewMode) { case MIXED: for (FileInfo fileInfo : fileInfos) { currentSearch.put((Long) fileInfo.getProperties().get(ContentModel.PROP_NODE_DBID), fileInfo); } break; case ARCHIVE: for (FileInfo fileInfo : fileInfos) { if (nodeService.hasAspect(fileInfo.getNodeRef(), ImapModel.ASPECT_IMAP_CONTENT)) { currentSearch.put((Long) fileInfo.getProperties().get(ContentModel.PROP_NODE_DBID), fileInfo); } } break; case VIRTUAL: for (FileInfo fileInfo : fileInfos) { if (!nodeService.hasAspect(fileInfo.getNodeRef(), ImapModel.ASPECT_IMAP_CONTENT)) { currentSearch.put((Long) fileInfo.getProperties().get(ContentModel.PROP_NODE_DBID), fileInfo); } } break; } int messageCount = currentSearch.size(), recentCount = 0, unseenCount = 0, firstUnseen = 0; int i = 1; for (FileInfo fileInfo : currentSearch.values()) { Flags flags = getFlags(fileInfo); if (flags.contains(Flags.Flag.RECENT)) { recentCount++; } if (!flags.contains(Flags.Flag.SEEN)) { if (firstUnseen == 0) { firstUnseen = i; } unseenCount++; } i++; } // Add the IMAP folder aspect with appropriate initial values if it is not already there if (changeToken == null) { changeToken = GUID.generate(); cacheKey = new Pair<String, String>(userName, changeToken); final String finalToken = changeToken; doAsSystem(new RunAsWork<Void>() { @Override public Void doWork() throws Exception { nodeService.setProperty(contextNodeRef, ImapModel.PROP_CHANGE_TOKEN, finalToken); nodeService.setProperty(contextNodeRef, ImapModel.PROP_MAXUID, currentSearch.isEmpty() ? 0 : currentSearch.lastKey()); return null; } }); } Long uidValidity = (Long) nodeService.getProperty(contextNodeRef, ImapModel.PROP_UIDVALIDITY); FolderStatus result = new FolderStatus(messageCount, recentCount, firstUnseen, unseenCount, uidValidity == null ? 0 : uidValidity, changeToken, currentSearch); this.folderCacheLock.writeLock().lock(); try { FolderStatus oldResult = this.folderCache.get(cacheKey); if (oldResult != null) { if (logger.isDebugEnabled()) { logger.debug("At end of getFolderStatus. Found info in cache, changeToken:" + changeToken); } return oldResult; } this.folderCache.put(cacheKey, result); if (logger.isDebugEnabled()) { logger.debug("At end of getFolderStatus. Found files:" + currentSearch.size() + ", changeToken:" + changeToken); } return result; } finally { this.folderCacheLock.writeLock().unlock(); } }
From source file:org.apache.hadoop.hbase.catalog.TestMetaReaderEditorNoCluster.java
/** * Test that MetaReader will ride over server throwing * "Server not running" IOEs.//ww w. j av a2s . co m * @see @link {https://issues.apache.org/jira/browse/HBASE-3446} * @throws IOException * @throws InterruptedException */ @Test public void testRideOverServerNotRunning() throws IOException, InterruptedException, ServiceException { // Need a zk watcher. ZooKeeperWatcher zkw = new ZooKeeperWatcher(UTIL.getConfiguration(), this.getClass().getSimpleName(), ABORTABLE, true); // This is a servername we use in a few places below. ServerName sn = ServerName.valueOf("example.com", 1234, System.currentTimeMillis()); HConnection connection; CatalogTracker ct = null; try { // Mock an ClientProtocol. Our mock implementation will fail a few // times when we go to open a scanner. final ClientProtos.ClientService.BlockingInterface implementation = Mockito .mock(ClientProtos.ClientService.BlockingInterface.class); // When scan called throw IOE 'Server not running' a few times // before we return a scanner id. Whats WEIRD is that these // exceptions do not show in the log because they are caught and only // printed if we FAIL. We eventually succeed after retry so these don't // show. We will know if they happened or not because we will ask // mockito at the end of this test to verify that scan was indeed // called the wanted number of times. List<Cell> kvs = new ArrayList<Cell>(); final byte[] rowToVerify = Bytes.toBytes("rowToVerify"); kvs.add(new KeyValue(rowToVerify, HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER, HRegionInfo.FIRST_META_REGIONINFO.toByteArray())); kvs.add(new KeyValue(rowToVerify, HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER, Bytes.toBytes(sn.getHostAndPort()))); kvs.add(new KeyValue(rowToVerify, HConstants.CATALOG_FAMILY, HConstants.STARTCODE_QUALIFIER, Bytes.toBytes(sn.getStartcode()))); final List<CellScannable> cellScannables = new ArrayList<CellScannable>(1); cellScannables.add(Result.create(kvs)); final ScanResponse.Builder builder = ScanResponse.newBuilder(); for (CellScannable result : cellScannables) { builder.addCellsPerResult(((Result) result).size()); } Mockito.when(implementation.scan((RpcController) Mockito.any(), (ScanRequest) Mockito.any())) .thenThrow(new ServiceException("Server not running (1 of 3)")) .thenThrow(new ServiceException("Server not running (2 of 3)")) .thenThrow(new ServiceException("Server not running (3 of 3)")) .thenReturn(ScanResponse.newBuilder().setScannerId(1234567890L).build()) .thenAnswer(new Answer<ScanResponse>() { public ScanResponse answer(InvocationOnMock invocation) throws Throwable { ((PayloadCarryingRpcController) invocation.getArguments()[0]) .setCellScanner(CellUtil.createCellScanner(cellScannables)); return builder.build(); } }).thenReturn(ScanResponse.newBuilder().setMoreResults(false).build()); // Associate a spied-upon HConnection with UTIL.getConfiguration. Need // to shove this in here first so it gets picked up all over; e.g. by // HTable. connection = HConnectionTestingUtility.getSpiedConnection(UTIL.getConfiguration()); // Fix the location lookup so it 'works' though no network. First // make an 'any location' object. final HRegionLocation anyLocation = new HRegionLocation(HRegionInfo.FIRST_META_REGIONINFO, sn); // Return the any location object when locateRegion is called in HTable // constructor and when its called by ServerCallable (it uses getRegionLocation). // The ugly format below comes of 'Important gotcha on spying real objects!' from // http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mockito.html Mockito.doReturn(anyLocation).when(connection).locateRegion((TableName) Mockito.any(), (byte[]) Mockito.any()); Mockito.doReturn(anyLocation).when(connection).getRegionLocation((TableName) Mockito.any(), (byte[]) Mockito.any(), Mockito.anyBoolean()); // Now shove our HRI implementation into the spied-upon connection. Mockito.doReturn(implementation).when(connection).getClient(Mockito.any(ServerName.class)); // Now start up the catalogtracker with our doctored Connection. ct = new CatalogTracker(zkw, null, connection, ABORTABLE); ct.start(); // Scan meta for user tables and verify we got back expected answer. NavigableMap<HRegionInfo, Result> hris = MetaReader.getServerUserRegions(ct, sn); assertEquals(1, hris.size()); assertTrue(hris.firstEntry().getKey().equals(HRegionInfo.FIRST_META_REGIONINFO)); assertTrue(Bytes.equals(rowToVerify, hris.firstEntry().getValue().getRow())); // Finally verify that scan was called four times -- three times // with exception and then on 4th, 5th and 6th attempt we succeed Mockito.verify(implementation, Mockito.times(6)).scan((RpcController) Mockito.any(), (ScanRequest) Mockito.any()); } finally { if (ct != null) ct.stop(); HConnectionManager.deleteConnection(UTIL.getConfiguration()); zkw.close(); } }
From source file:org.apache.hadoop.hbase.client.HTable.java
/** * Gets the starting and ending row keys for every region in the currently * open table.//from w w w . j a va2s .com * <p> * This is mainly useful for the MapReduce integration. * @return Pair of arrays of region starting and ending row keys * @throws IOException if a remote or network exception occurs */ public Pair<byte[][], byte[][]> getStartEndKeys() throws IOException { NavigableMap<HRegionInfo, ServerName> regions = getRegionLocations(); final List<byte[]> startKeyList = new ArrayList<byte[]>(regions.size()); final List<byte[]> endKeyList = new ArrayList<byte[]>(regions.size()); for (HRegionInfo region : regions.keySet()) { startKeyList.add(region.getStartKey()); endKeyList.add(region.getEndKey()); } return new Pair<byte[][], byte[][]>(startKeyList.toArray(new byte[startKeyList.size()][]), endKeyList.toArray(new byte[endKeyList.size()][])); }
From source file:org.apache.hadoop.hbase.client.TestFromClientSide.java
@Test public void testClientPoolRoundRobin() throws IOException { final byte[] tableName = Bytes.toBytes("testClientPoolRoundRobin"); int poolSize = 3; int numVersions = poolSize * 2; Configuration conf = TEST_UTIL.getConfiguration(); conf.set(HConstants.HBASE_CLIENT_IPC_POOL_TYPE, "round-robin"); conf.setInt(HConstants.HBASE_CLIENT_IPC_POOL_SIZE, poolSize); HTable table = TEST_UTIL.createTable(tableName, new byte[][] { FAMILY }, conf, Integer.MAX_VALUE); final long ts = EnvironmentEdgeManager.currentTimeMillis(); Get get = new Get(ROW); get.addColumn(FAMILY, QUALIFIER);//from w w w. j a va 2s .c o m get.setMaxVersions(); for (int versions = 1; versions <= numVersions; versions++) { Put put = new Put(ROW); put.add(FAMILY, QUALIFIER, ts + versions, VALUE); table.put(put); Result result = table.get(get); NavigableMap<Long, byte[]> navigableMap = result.getMap().get(FAMILY).get(QUALIFIER); assertEquals("The number of versions of '" + FAMILY + ":" + QUALIFIER + " did not match " + versions, versions, navigableMap.size()); for (Map.Entry<Long, byte[]> entry : navigableMap.entrySet()) { assertTrue("The value at time " + entry.getKey() + " did not match what was put", Bytes.equals(VALUE, entry.getValue())); } } }