target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test(expectedExceptions = UnsupportedOperationException.class) public void testGetTotalSpace() { fs.getFile("nonsuch.txt").getTotalSpace(); }
@Override public long getTotalSpace() { throw new UnsupportedOperationException("Not implemented"); }
GridFile extends File { @Override public long getTotalSpace() { throw new UnsupportedOperationException("Not implemented"); } }
GridFile extends File { @Override public long getTotalSpace() { throw new UnsupportedOperationException("Not implemented"); } GridFile(String pathname, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(String parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(File parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); }
GridFile extends File { @Override public long getTotalSpace() { throw new UnsupportedOperationException("Not implemented"); } GridFile(String pathname, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(String parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(File parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); @Override String getName(); @Override String getPath(); @Override String getAbsolutePath(); @Override File getAbsoluteFile(); @Override String getCanonicalPath(); @Override File getCanonicalFile(); @Override boolean isAbsolute(); @Override boolean renameTo(File dest); @Override void deleteOnExit(); @Override long length(); int getChunkSize(); @Override boolean createNewFile(); @Override boolean delete(); @Override boolean mkdir(); @Override boolean mkdirs(); @Override boolean exists(); @Override String getParent(); @Override File getParentFile(); @Override long lastModified(); @Override boolean setLastModified(long time); @Override String[] list(); @Override String[] list(FilenameFilter filter); @Override File[] listFiles(); @Override File[] listFiles(FilenameFilter filter); @Override File[] listFiles(FileFilter filter); @Override boolean isDirectory(); @Override boolean isFile(); @Override boolean equals(Object obj); @Override boolean canRead(); @Override boolean canWrite(); @Override boolean isHidden(); @Override boolean canExecute(); @Override int compareTo(File file); @Override int hashCode(); @Override String toString(); @Override URL toURL(); @Override URI toURI(); @Override boolean setReadOnly(); @Override boolean setWritable(boolean writable, boolean ownerOnly); @Override boolean setWritable(boolean writable); @Override boolean setReadable(boolean readable, boolean ownerOnly); @Override boolean setReadable(boolean readable); @Override boolean setExecutable(boolean executable, boolean ownerOnly); @Override boolean setExecutable(boolean executable); @Override long getTotalSpace(); @Override long getFreeSpace(); @Override long getUsableSpace(); }
GridFile extends File { @Override public long getTotalSpace() { throw new UnsupportedOperationException("Not implemented"); } GridFile(String pathname, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(String parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(File parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); @Override String getName(); @Override String getPath(); @Override String getAbsolutePath(); @Override File getAbsoluteFile(); @Override String getCanonicalPath(); @Override File getCanonicalFile(); @Override boolean isAbsolute(); @Override boolean renameTo(File dest); @Override void deleteOnExit(); @Override long length(); int getChunkSize(); @Override boolean createNewFile(); @Override boolean delete(); @Override boolean mkdir(); @Override boolean mkdirs(); @Override boolean exists(); @Override String getParent(); @Override File getParentFile(); @Override long lastModified(); @Override boolean setLastModified(long time); @Override String[] list(); @Override String[] list(FilenameFilter filter); @Override File[] listFiles(); @Override File[] listFiles(FilenameFilter filter); @Override File[] listFiles(FileFilter filter); @Override boolean isDirectory(); @Override boolean isFile(); @Override boolean equals(Object obj); @Override boolean canRead(); @Override boolean canWrite(); @Override boolean isHidden(); @Override boolean canExecute(); @Override int compareTo(File file); @Override int hashCode(); @Override String toString(); @Override URL toURL(); @Override URI toURI(); @Override boolean setReadOnly(); @Override boolean setWritable(boolean writable, boolean ownerOnly); @Override boolean setWritable(boolean writable); @Override boolean setReadable(boolean readable, boolean ownerOnly); @Override boolean setReadable(boolean readable); @Override boolean setExecutable(boolean executable, boolean ownerOnly); @Override boolean setExecutable(boolean executable); @Override long getTotalSpace(); @Override long getFreeSpace(); @Override long getUsableSpace(); }
@Test(expectedExceptions = UnsupportedOperationException.class) public void testGetFreeSpace() { fs.getFile("nonsuch.txt").getFreeSpace(); }
@Override public long getFreeSpace() { throw new UnsupportedOperationException("Not implemented"); }
GridFile extends File { @Override public long getFreeSpace() { throw new UnsupportedOperationException("Not implemented"); } }
GridFile extends File { @Override public long getFreeSpace() { throw new UnsupportedOperationException("Not implemented"); } GridFile(String pathname, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(String parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(File parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); }
GridFile extends File { @Override public long getFreeSpace() { throw new UnsupportedOperationException("Not implemented"); } GridFile(String pathname, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(String parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(File parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); @Override String getName(); @Override String getPath(); @Override String getAbsolutePath(); @Override File getAbsoluteFile(); @Override String getCanonicalPath(); @Override File getCanonicalFile(); @Override boolean isAbsolute(); @Override boolean renameTo(File dest); @Override void deleteOnExit(); @Override long length(); int getChunkSize(); @Override boolean createNewFile(); @Override boolean delete(); @Override boolean mkdir(); @Override boolean mkdirs(); @Override boolean exists(); @Override String getParent(); @Override File getParentFile(); @Override long lastModified(); @Override boolean setLastModified(long time); @Override String[] list(); @Override String[] list(FilenameFilter filter); @Override File[] listFiles(); @Override File[] listFiles(FilenameFilter filter); @Override File[] listFiles(FileFilter filter); @Override boolean isDirectory(); @Override boolean isFile(); @Override boolean equals(Object obj); @Override boolean canRead(); @Override boolean canWrite(); @Override boolean isHidden(); @Override boolean canExecute(); @Override int compareTo(File file); @Override int hashCode(); @Override String toString(); @Override URL toURL(); @Override URI toURI(); @Override boolean setReadOnly(); @Override boolean setWritable(boolean writable, boolean ownerOnly); @Override boolean setWritable(boolean writable); @Override boolean setReadable(boolean readable, boolean ownerOnly); @Override boolean setReadable(boolean readable); @Override boolean setExecutable(boolean executable, boolean ownerOnly); @Override boolean setExecutable(boolean executable); @Override long getTotalSpace(); @Override long getFreeSpace(); @Override long getUsableSpace(); }
GridFile extends File { @Override public long getFreeSpace() { throw new UnsupportedOperationException("Not implemented"); } GridFile(String pathname, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(String parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(File parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); @Override String getName(); @Override String getPath(); @Override String getAbsolutePath(); @Override File getAbsoluteFile(); @Override String getCanonicalPath(); @Override File getCanonicalFile(); @Override boolean isAbsolute(); @Override boolean renameTo(File dest); @Override void deleteOnExit(); @Override long length(); int getChunkSize(); @Override boolean createNewFile(); @Override boolean delete(); @Override boolean mkdir(); @Override boolean mkdirs(); @Override boolean exists(); @Override String getParent(); @Override File getParentFile(); @Override long lastModified(); @Override boolean setLastModified(long time); @Override String[] list(); @Override String[] list(FilenameFilter filter); @Override File[] listFiles(); @Override File[] listFiles(FilenameFilter filter); @Override File[] listFiles(FileFilter filter); @Override boolean isDirectory(); @Override boolean isFile(); @Override boolean equals(Object obj); @Override boolean canRead(); @Override boolean canWrite(); @Override boolean isHidden(); @Override boolean canExecute(); @Override int compareTo(File file); @Override int hashCode(); @Override String toString(); @Override URL toURL(); @Override URI toURI(); @Override boolean setReadOnly(); @Override boolean setWritable(boolean writable, boolean ownerOnly); @Override boolean setWritable(boolean writable); @Override boolean setReadable(boolean readable, boolean ownerOnly); @Override boolean setReadable(boolean readable); @Override boolean setExecutable(boolean executable, boolean ownerOnly); @Override boolean setExecutable(boolean executable); @Override long getTotalSpace(); @Override long getFreeSpace(); @Override long getUsableSpace(); }
@Test(expectedExceptions = UnsupportedOperationException.class) public void testGetUsableSpace() { fs.getFile("nonsuch.txt").getUsableSpace(); }
@Override public long getUsableSpace() { throw new UnsupportedOperationException("Not implemented"); }
GridFile extends File { @Override public long getUsableSpace() { throw new UnsupportedOperationException("Not implemented"); } }
GridFile extends File { @Override public long getUsableSpace() { throw new UnsupportedOperationException("Not implemented"); } GridFile(String pathname, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(String parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(File parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); }
GridFile extends File { @Override public long getUsableSpace() { throw new UnsupportedOperationException("Not implemented"); } GridFile(String pathname, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(String parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(File parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); @Override String getName(); @Override String getPath(); @Override String getAbsolutePath(); @Override File getAbsoluteFile(); @Override String getCanonicalPath(); @Override File getCanonicalFile(); @Override boolean isAbsolute(); @Override boolean renameTo(File dest); @Override void deleteOnExit(); @Override long length(); int getChunkSize(); @Override boolean createNewFile(); @Override boolean delete(); @Override boolean mkdir(); @Override boolean mkdirs(); @Override boolean exists(); @Override String getParent(); @Override File getParentFile(); @Override long lastModified(); @Override boolean setLastModified(long time); @Override String[] list(); @Override String[] list(FilenameFilter filter); @Override File[] listFiles(); @Override File[] listFiles(FilenameFilter filter); @Override File[] listFiles(FileFilter filter); @Override boolean isDirectory(); @Override boolean isFile(); @Override boolean equals(Object obj); @Override boolean canRead(); @Override boolean canWrite(); @Override boolean isHidden(); @Override boolean canExecute(); @Override int compareTo(File file); @Override int hashCode(); @Override String toString(); @Override URL toURL(); @Override URI toURI(); @Override boolean setReadOnly(); @Override boolean setWritable(boolean writable, boolean ownerOnly); @Override boolean setWritable(boolean writable); @Override boolean setReadable(boolean readable, boolean ownerOnly); @Override boolean setReadable(boolean readable); @Override boolean setExecutable(boolean executable, boolean ownerOnly); @Override boolean setExecutable(boolean executable); @Override long getTotalSpace(); @Override long getFreeSpace(); @Override long getUsableSpace(); }
GridFile extends File { @Override public long getUsableSpace() { throw new UnsupportedOperationException("Not implemented"); } GridFile(String pathname, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(String parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(File parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); @Override String getName(); @Override String getPath(); @Override String getAbsolutePath(); @Override File getAbsoluteFile(); @Override String getCanonicalPath(); @Override File getCanonicalFile(); @Override boolean isAbsolute(); @Override boolean renameTo(File dest); @Override void deleteOnExit(); @Override long length(); int getChunkSize(); @Override boolean createNewFile(); @Override boolean delete(); @Override boolean mkdir(); @Override boolean mkdirs(); @Override boolean exists(); @Override String getParent(); @Override File getParentFile(); @Override long lastModified(); @Override boolean setLastModified(long time); @Override String[] list(); @Override String[] list(FilenameFilter filter); @Override File[] listFiles(); @Override File[] listFiles(FilenameFilter filter); @Override File[] listFiles(FileFilter filter); @Override boolean isDirectory(); @Override boolean isFile(); @Override boolean equals(Object obj); @Override boolean canRead(); @Override boolean canWrite(); @Override boolean isHidden(); @Override boolean canExecute(); @Override int compareTo(File file); @Override int hashCode(); @Override String toString(); @Override URL toURL(); @Override URI toURI(); @Override boolean setReadOnly(); @Override boolean setWritable(boolean writable, boolean ownerOnly); @Override boolean setWritable(boolean writable); @Override boolean setReadable(boolean readable, boolean ownerOnly); @Override boolean setReadable(boolean readable); @Override boolean setExecutable(boolean executable, boolean ownerOnly); @Override boolean setExecutable(boolean executable); @Override long getTotalSpace(); @Override long getFreeSpace(); @Override long getUsableSpace(); }
@Test public void testHealthyStatus() { CacheImpl<Object, Object> cache = spy(new CacheImpl<>("test")); DistributionManager distributionManagerMock = mock(DistributionManager.class); doReturn(false).when(distributionManagerMock).isRehashInProgress(); doReturn(distributionManagerMock).when(cache).getDistributionManager(); doReturn(ComponentStatus.RUNNING).when(cache).getStatus(); doReturn(AvailabilityMode.AVAILABLE).when(cache).getAvailability(); CacheHealth cacheHealth = new CacheHealthImpl(cache); HealthStatus status = cacheHealth.getStatus(); assertEquals(status, HealthStatus.HEALTHY); }
@Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); @Override String getCacheName(); @Override HealthStatus getStatus(); }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); @Override String getCacheName(); @Override HealthStatus getStatus(); }
@Test public void testUnhealthyStatusWithFailedComponent() { CacheImpl<Object, Object> cache = spy(new CacheImpl<>("test")); doReturn(ComponentStatus.FAILED).when(cache).getStatus(); CacheHealth cacheHealth = new CacheHealthImpl(cache); HealthStatus status = cacheHealth.getStatus(); assertEquals(status, HealthStatus.DEGRADED); }
@Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); @Override String getCacheName(); @Override HealthStatus getStatus(); }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); @Override String getCacheName(); @Override HealthStatus getStatus(); }
@Test public void testIntSpliteratorForEachRemaining() { Set<Integer> results = new HashSet<>(); es.intSpliterator().forEachRemaining((IntConsumer) results::add); assertEquals(0, results.size()); }
@Override public int size() { return 0; }
EmptyIntSet extends AbstractImmutableIntSet { @Override public int size() { return 0; } }
EmptyIntSet extends AbstractImmutableIntSet { @Override public int size() { return 0; } }
EmptyIntSet extends AbstractImmutableIntSet { @Override public int size() { return 0; } static IntSet getInstance(); @Override boolean contains(int i); @Override boolean containsAll(IntSet set); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override PrimitiveIterator.OfInt iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean containsAll(Collection<?> c); @Override IntStream intStream(); @Override boolean equals(Object obj); @Override String toString(); }
EmptyIntSet extends AbstractImmutableIntSet { @Override public int size() { return 0; } static IntSet getInstance(); @Override boolean contains(int i); @Override boolean containsAll(IntSet set); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override PrimitiveIterator.OfInt iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean containsAll(Collection<?> c); @Override IntStream intStream(); @Override boolean equals(Object obj); @Override String toString(); }
@Test public void testUnhealthyStatusWithTerminatedComponent() { CacheImpl<Object, Object> cache = spy(new CacheImpl<>("test")); doReturn(ComponentStatus.TERMINATED).when(cache).getStatus(); CacheHealth cacheHealth = new CacheHealthImpl(cache); HealthStatus status = cacheHealth.getStatus(); assertEquals(status, HealthStatus.DEGRADED); }
@Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); @Override String getCacheName(); @Override HealthStatus getStatus(); }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); @Override String getCacheName(); @Override HealthStatus getStatus(); }
@Test public void testUnhealthyStatusWithStoppingComponent() { CacheImpl<Object, Object> cache = spy(new CacheImpl<>("test")); doReturn(ComponentStatus.STOPPING).when(cache).getStatus(); CacheHealth cacheHealth = new CacheHealthImpl(cache); HealthStatus status = cacheHealth.getStatus(); assertEquals(status, HealthStatus.DEGRADED); }
@Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); @Override String getCacheName(); @Override HealthStatus getStatus(); }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); @Override String getCacheName(); @Override HealthStatus getStatus(); }
@Test public void testUnhealthyStatusWithDegradedPartition() { CacheImpl<Object, Object> cache = spy(new CacheImpl<>("test")); doReturn(ComponentStatus.RUNNING).when(cache).getStatus(); doReturn(AvailabilityMode.DEGRADED_MODE).when(cache).getAvailability(); CacheHealth cacheHealth = new CacheHealthImpl(cache); HealthStatus status = cacheHealth.getStatus(); assertEquals(status, HealthStatus.DEGRADED); }
@Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); @Override String getCacheName(); @Override HealthStatus getStatus(); }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); @Override String getCacheName(); @Override HealthStatus getStatus(); }
@Test public void testRebalancingStatusOnRebalance() { CacheImpl<Object, Object> cache = spy(new CacheImpl<>("test")); DistributionManager distributionManagerMock = mock(DistributionManager.class); doReturn(true).when(distributionManagerMock).isRehashInProgress(); doReturn(distributionManagerMock).when(cache).getDistributionManager(); doReturn(ComponentStatus.RUNNING).when(cache).getStatus(); doReturn(AvailabilityMode.AVAILABLE).when(cache).getAvailability(); CacheHealth cacheHealth = new CacheHealthImpl(cache); HealthStatus status = cacheHealth.getStatus(); assertEquals(status, HealthStatus.HEALTHY_REBALANCING); }
@Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); @Override String getCacheName(); @Override HealthStatus getStatus(); }
CacheHealthImpl implements CacheHealth { @Override public HealthStatus getStatus() { if (!isComponentHealthy() || cache.getAdvancedCache().getAvailability() == AvailabilityMode.DEGRADED_MODE) { return HealthStatus.DEGRADED; } DistributionManager distributionManager = SecurityActions.getDistributionManager(cache); if (distributionManager != null && distributionManager.isRehashInProgress()) { return HealthStatus.HEALTHY_REBALANCING; } return HealthStatus.HEALTHY; } CacheHealthImpl(Cache<?, ?> cache); @Override String getCacheName(); @Override HealthStatus getStatus(); }
@Test(dataProvider = "offsets") public void testExpandCapacity(int splitOffset) throws Throwable { CompletableFuture<Object> future = new CompletableFuture<>(); QueueAsyncInvocationStage stage = new QueueAsyncInvocationStage(null, null, future, makeCallback(0)); assertCallback(0, stage.queuePoll()); addAndPoll(stage, splitOffset); int count = 2 * QueueAsyncInvocationStage.QUEUE_INITIAL_CAPACITY; addAndPoll(stage, count); }
InvocationCallback queuePoll() { InvocationCallback element; synchronized (this) { if (tail != head) { element = elements[head & mask]; head++; } else { element = null; frozen = true; } } return element; }
QueueAsyncInvocationStage extends SimpleAsyncInvocationStage implements BiConsumer<Object, Throwable>, InvocationCallback { InvocationCallback queuePoll() { InvocationCallback element; synchronized (this) { if (tail != head) { element = elements[head & mask]; head++; } else { element = null; frozen = true; } } return element; } }
QueueAsyncInvocationStage extends SimpleAsyncInvocationStage implements BiConsumer<Object, Throwable>, InvocationCallback { InvocationCallback queuePoll() { InvocationCallback element; synchronized (this) { if (tail != head) { element = elements[head & mask]; head++; } else { element = null; frozen = true; } } return element; } QueueAsyncInvocationStage(InvocationContext ctx, VisitableCommand command, CompletableFuture<?> valueFuture, InvocationCallback function); }
QueueAsyncInvocationStage extends SimpleAsyncInvocationStage implements BiConsumer<Object, Throwable>, InvocationCallback { InvocationCallback queuePoll() { InvocationCallback element; synchronized (this) { if (tail != head) { element = elements[head & mask]; head++; } else { element = null; frozen = true; } } return element; } QueueAsyncInvocationStage(InvocationContext ctx, VisitableCommand command, CompletableFuture<?> valueFuture, InvocationCallback function); @Override Object addCallback(InvocationContext ctx, VisitableCommand command, InvocationCallback function); @Override void accept(Object rv, Throwable throwable); @Override Object apply(InvocationContext rCtx, VisitableCommand rCommand, Object rv, Throwable throwable); @Override String toString(); }
QueueAsyncInvocationStage extends SimpleAsyncInvocationStage implements BiConsumer<Object, Throwable>, InvocationCallback { InvocationCallback queuePoll() { InvocationCallback element; synchronized (this) { if (tail != head) { element = elements[head & mask]; head++; } else { element = null; frozen = true; } } return element; } QueueAsyncInvocationStage(InvocationContext ctx, VisitableCommand command, CompletableFuture<?> valueFuture, InvocationCallback function); @Override Object addCallback(InvocationContext ctx, VisitableCommand command, InvocationCallback function); @Override void accept(Object rv, Throwable throwable); @Override Object apply(InvocationContext rCtx, VisitableCommand rCommand, Object rv, Throwable throwable); @Override String toString(); }
@Test(dataProvider = "roundings") public void testRoundings(long original, long expected) { assertEquals(expected, UnpooledOffHeapMemoryAllocator.estimateSizeOverhead(original)); }
public static long estimateSizeOverhead(long size) { return (size + 8 + 15) & ~15; }
UnpooledOffHeapMemoryAllocator implements OffHeapMemoryAllocator { public static long estimateSizeOverhead(long size) { return (size + 8 + 15) & ~15; } }
UnpooledOffHeapMemoryAllocator implements OffHeapMemoryAllocator { public static long estimateSizeOverhead(long size) { return (size + 8 + 15) & ~15; } }
UnpooledOffHeapMemoryAllocator implements OffHeapMemoryAllocator { public static long estimateSizeOverhead(long size) { return (size + 8 + 15) & ~15; } @Override long allocate(long memoryLength); @Override void deallocate(long memoryAddress, long size); @Override long getAllocatedAmount(); static long estimateSizeOverhead(long size); static long offHeapEntrySize(boolean evictionEnabled, boolean writeMetadataSize, int keySize, int valueSize); static long offHeapEntrySize(boolean evictionEnabled, boolean writeMetadataSize, int keySize, int valueSize, int metadataSize, int internalMetadataSize); }
UnpooledOffHeapMemoryAllocator implements OffHeapMemoryAllocator { public static long estimateSizeOverhead(long size) { return (size + 8 + 15) & ~15; } @Override long allocate(long memoryLength); @Override void deallocate(long memoryAddress, long size); @Override long getAllocatedAmount(); static long estimateSizeOverhead(long size); static long offHeapEntrySize(boolean evictionEnabled, boolean writeMetadataSize, int keySize, int valueSize); static long offHeapEntrySize(boolean evictionEnabled, boolean writeMetadataSize, int keySize, int valueSize, int metadataSize, int internalMetadataSize); }
@Test public void testDefaultConfigurationDataContainer() { dataContainerFactory.configuration = new ConfigurationBuilder().build(); assertEquals(DefaultDataContainer.class, dataContainerFactory.construct(COMPONENT_NAME).getClass()); }
@Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
@Test public void testOffHeap() { dataContainerFactory.configuration = new ConfigurationBuilder() .memory().storageType(StorageType.OFF_HEAP).build(); assertEquals(OffHeapDataContainer.class, dataContainerFactory.construct(COMPONENT_NAME).getClass()); }
@Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
@Test public void testSegmentedOffHeap() { dataContainerFactory.configuration = new ConfigurationBuilder().clustering().cacheMode(CacheMode.DIST_ASYNC) .memory().storageType(StorageType.OFF_HEAP).build(); Object component = dataContainerFactory.construct(COMPONENT_NAME); assertEquals(DefaultSegmentedDataContainer.class, component.getClass()); }
@Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
@Test public void testDefaultSegmented() { dataContainerFactory.configuration = new ConfigurationBuilder().clustering() .cacheMode(CacheMode.DIST_ASYNC).build(); Object component = dataContainerFactory.construct(COMPONENT_NAME); assertEquals(DefaultSegmentedDataContainer.class, component.getClass()); }
@Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
@Test public void testIntSpliteratorSplitTryAdvance() { Set<Integer> results = new HashSet<>(); Spliterator.OfInt spliterator = es.intSpliterator(); Spliterator.OfInt split = spliterator.trySplit(); assertNull(split); IntConsumer consumer = results::add; while (spliterator.tryAdvance(consumer)) { } assertEquals(0, results.size()); }
@Override public int size() { return 0; }
EmptyIntSet extends AbstractImmutableIntSet { @Override public int size() { return 0; } }
EmptyIntSet extends AbstractImmutableIntSet { @Override public int size() { return 0; } }
EmptyIntSet extends AbstractImmutableIntSet { @Override public int size() { return 0; } static IntSet getInstance(); @Override boolean contains(int i); @Override boolean containsAll(IntSet set); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override PrimitiveIterator.OfInt iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean containsAll(Collection<?> c); @Override IntStream intStream(); @Override boolean equals(Object obj); @Override String toString(); }
EmptyIntSet extends AbstractImmutableIntSet { @Override public int size() { return 0; } static IntSet getInstance(); @Override boolean contains(int i); @Override boolean containsAll(IntSet set); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override PrimitiveIterator.OfInt iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean containsAll(Collection<?> c); @Override IntStream intStream(); @Override boolean equals(Object obj); @Override String toString(); }
@Test public void testSegmentedL1() { dataContainerFactory.configuration = new ConfigurationBuilder().clustering() .cacheMode(CacheMode.DIST_ASYNC) .l1().enable().build(); Object component = dataContainerFactory.construct(COMPONENT_NAME); assertEquals(L1SegmentedDataContainer.class, component.getClass()); }
@Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
@Test public void testEvictionRemoveNotSegmented() { dataContainerFactory.configuration = new ConfigurationBuilder().clustering() .memory().evictionStrategy(EvictionStrategy.REMOVE).size(1000).build(); assertEquals(DefaultDataContainer.class, this.dataContainerFactory.construct(COMPONENT_NAME).getClass()); }
@Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
@Test public void testEvictionRemoveSegmented() { dataContainerFactory.configuration = new ConfigurationBuilder().clustering() .memory().evictionStrategy(EvictionStrategy.REMOVE).size(1000) .clustering().cacheMode(CacheMode.DIST_ASYNC).build(); Object component = dataContainerFactory.construct(COMPONENT_NAME); assertEquals(BoundedSegmentedDataContainer.class, component.getClass()); }
@Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
@Test public void testEvictionRemoveNotSegmentedOffHeap() { dataContainerFactory.configuration = new ConfigurationBuilder().clustering() .memory().storageType(StorageType.OFF_HEAP).evictionStrategy(EvictionStrategy.REMOVE).size(1000) .build(); assertEquals(BoundedOffHeapDataContainer.class, this.dataContainerFactory.construct(COMPONENT_NAME).getClass()); }
@Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
@Test public void testEvictionRemoveSegmentedOffHeap() { dataContainerFactory.configuration = new ConfigurationBuilder().clustering() .memory().storageType(StorageType.OFF_HEAP).evictionStrategy(EvictionStrategy.REMOVE).size(1000) .clustering().cacheMode(CacheMode.DIST_ASYNC).build(); Object component = dataContainerFactory.construct(COMPONENT_NAME); assertEquals(SegmentedBoundedOffHeapDataContainer.class, component.getClass()); }
@Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
DataContainerFactory extends AbstractNamedCacheComponentFactory implements AutoInstantiableFactory { @Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfiguration memoryConfiguration = configuration.memory(); boolean offHeap = memoryConfiguration.isOffHeap(); EvictionStrategy strategy = memoryConfiguration.whenFull(); if (strategy.isExceptionBased() || !strategy.isEnabled()) { if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); Supplier<PeekableTouchableMap<WrappedBytes, WrappedBytes>> mapSupplier = this::createAndStartOffHeapConcurrentMap; if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return new OffHeapDataContainer(); } } else if (shouldSegment) { Supplier<PeekableTouchableMap<Object, Object>> mapSupplier = PeekableTouchableContainerMap::new; int segments = clusteringConfiguration.hash().numSegments(); if (clusteringConfiguration.l1().enabled()) { return new L1SegmentedDataContainer<>(mapSupplier, segments); } return new DefaultSegmentedDataContainer<>(mapSupplier, segments); } else { return DefaultDataContainer.unBoundedDataContainer(level); } } boolean sizeInBytes = memoryConfiguration.maxSize() != null; long thresholdSize = sizeInBytes ? memoryConfiguration.maxSizeBytes() : memoryConfiguration.maxCount(); DataContainer<?, ?> dataContainer; if (offHeap) { if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new SegmentedBoundedOffHeapDataContainer(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = new BoundedOffHeapDataContainer(thresholdSize, memoryConfiguration.evictionType()); } } else if (shouldSegment) { int segments = clusteringConfiguration.hash().numSegments(); dataContainer = new BoundedSegmentedDataContainer<>(segments, thresholdSize, memoryConfiguration.evictionType()); } else { dataContainer = DefaultDataContainer.boundedDataContainer(level, thresholdSize, memoryConfiguration.evictionType()); } if (sizeInBytes) { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_SIZE) .addListener((newSize, old) -> dataContainer.resize(memoryConfiguration.maxSizeBytes())); } else { memoryConfiguration.attributes().attribute(MemoryConfiguration.MAX_COUNT) .addListener((newSize, old) -> dataContainer.resize(newSize.get())); } return dataContainer; } @Override Object construct(String componentName); }
@Test public void testIntegerKeysXmlToTextValues() { Integer key = 123; String keyContentType = "application/x-java-object;type=java.lang.Integer"; String valueContentType = "application/xml; charset=UTF-8"; String value = "<root>test</root>"; putInCache("default", key, keyContentType, value, valueContentType); RestResponse response = get("default", key, keyContentType, "text/plain"); ResponseAssertion.assertThat(response).hasReturnedText(value); }
private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } BaseCacheResource(InvocationHelper invocationHelper); }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } BaseCacheResource(InvocationHelper invocationHelper); }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } BaseCacheResource(InvocationHelper invocationHelper); }
@Test public void testIntKeysAndJSONToTextValues() { Integer key = 1234; String keyContentType = "application/x-java-object;type=java.lang.Integer"; String value = "{\"a\": 1}"; putInCache("default", key, keyContentType, value, APPLICATION_JSON_TYPE); RestResponse response = get("default", key, keyContentType, TEXT_PLAIN_TYPE); ResponseAssertion.assertThat(response).hasReturnedText(value); }
private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } BaseCacheResource(InvocationHelper invocationHelper); }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } BaseCacheResource(InvocationHelper invocationHelper); }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } BaseCacheResource(InvocationHelper invocationHelper); }
@Test public void testIntKeysTextToXMLValues() { Integer key = 12345; String keyContentType = "application/x-java-object;type=java.lang.Integer"; String value = "<foo>bar</foo>"; putInCache("default", key, keyContentType, value, TEXT_PLAIN_TYPE); RestResponse response = get("default", key, keyContentType, APPLICATION_XML_TYPE); ResponseAssertion.assertThat(response).hasReturnedText(value); }
private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } BaseCacheResource(InvocationHelper invocationHelper); }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } BaseCacheResource(InvocationHelper invocationHelper); }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } BaseCacheResource(InvocationHelper invocationHelper); }
@Test public void testInvalidXMLConversion() throws Exception { String key = "invalid-xml-key"; String invalidXML = "foo"; putInCache("default", key, invalidXML, TEXT_PLAIN_TYPE); CompletionStage<RestResponse> response = client.cache("default").get(key, APPLICATION_XML_TYPE); ResponseAssertion.assertThat(response).containsReturnedText("<string>foo</string>"); }
private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } BaseCacheResource(InvocationHelper invocationHelper); }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } BaseCacheResource(InvocationHelper invocationHelper); }
BaseCacheResource { private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder, AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl, Long idleTime) { Configuration config = SecurityActions.getCacheConfiguration(cache); final Metadata metadata = CacheOperationsHelper.createMetadata(config, ttl, idleTime); responseBuilder.header("etag", calcETAG(data)); CompletionStage<Object> stage; if (config.indexing().enabled()) { stage = CompletableFuture.supplyAsync(() -> cache.putAsync(key, data, metadata), invocationHelper.getExecutor()) .thenCompose(Function.identity()); } else { stage = cache.putAsync(key, data, metadata); } return stage.thenApply(o -> responseBuilder.build()); } BaseCacheResource(InvocationHelper invocationHelper); }
@Test public void testWeakCounterLifecycle() { CounterConfiguration counterConfig = CounterConfiguration.builder(CounterType.WEAK) .initialValue(5).storage(Storage.VOLATILE).concurrencyLevel(6).build(); createCounter("sample-counter", counterConfig); RestCounterClient counterClient = client.counter("sample-counter"); RestResponse response = join(counterClient.configuration(APPLICATION_JSON_TYPE)); Json jsonNode = Json.read(response.getBody()); Json config = jsonNode.at("weak-counter"); assertEquals(config.at("initial-value").asInteger(), 5); assertEquals(config.at("storage").asString(), "VOLATILE"); assertEquals(config.at("concurrency-level").asInteger(), 6); response = join(counterClient.delete()); assertThat(response).isOk(); response = join(counterClient.configuration()); assertThat(response).isNotFound(); }
private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); }
CounterResource implements ResourceHandler { private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); } }
CounterResource implements ResourceHandler { private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); } CounterResource(InvocationHelper invocationHelper); }
CounterResource implements ResourceHandler { private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); } CounterResource(InvocationHelper invocationHelper); @Override Invocations getInvocations(); }
CounterResource implements ResourceHandler { private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); } CounterResource(InvocationHelper invocationHelper); @Override Invocations getInvocations(); }
@Test public void testReplaceProperties() { Properties properties = new Properties(); properties.put("one", "1"); properties.put("two", "2"); assertEquals("V1", StringPropertyReplacer.replaceProperties("V${one}", properties)); assertEquals("VX", StringPropertyReplacer.replaceProperties("V${void:X}", properties)); assertEquals("V1", StringPropertyReplacer.replaceProperties("V${void,one}", properties)); assertEquals("VX", StringPropertyReplacer.replaceProperties("V${void1,void2:X}", properties)); assertEquals(System.getenv("PATH"), StringPropertyReplacer.replaceProperties("${env.PATH}", properties)); assertEquals(File.separator, StringPropertyReplacer.replaceProperties("${/}")); assertEquals(File.pathSeparator, StringPropertyReplacer.replaceProperties("${:}")); }
public static String replaceProperties(final String string) { return replaceProperties(string, null); }
StringPropertyReplacer { public static String replaceProperties(final String string) { return replaceProperties(string, null); } }
StringPropertyReplacer { public static String replaceProperties(final String string) { return replaceProperties(string, null); } }
StringPropertyReplacer { public static String replaceProperties(final String string) { return replaceProperties(string, null); } static String replaceProperties(final String string); static String replaceProperties(final String string, final Properties props); static void replaceProperties(Map<String, String> map, Properties properties); }
StringPropertyReplacer { public static String replaceProperties(final String string) { return replaceProperties(string, null); } static String replaceProperties(final String string); static String replaceProperties(final String string, final Properties props); static void replaceProperties(Map<String, String> map, Properties properties); static final String NEWLINE; }
@Test public void testWeakCounterOps() { String name = "weak-test"; createCounter(name, CounterConfiguration.builder(CounterType.WEAK).initialValue(5).build()); RestCounterClient counterClient = client.counter(name); CompletionStage<RestResponse> response = counterClient.increment(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 6); response = counterClient.increment(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 7); response = counterClient.decrement(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 6); response = counterClient.decrement(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 5); response = counterClient.add(10); assertThat(response).hasNoContent(); waitForCounterToReach(name, 15); response = counterClient.reset(); assertThat(response).hasNoContent(); waitForCounterToReach(name, 5); }
private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); }
CounterResource implements ResourceHandler { private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); } }
CounterResource implements ResourceHandler { private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); } CounterResource(InvocationHelper invocationHelper); }
CounterResource implements ResourceHandler { private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); } CounterResource(InvocationHelper invocationHelper); @Override Invocations getInvocations(); }
CounterResource implements ResourceHandler { private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); } CounterResource(InvocationHelper invocationHelper); @Override Invocations getInvocations(); }
@Test public void testStrongCounterOps() { String name = "strong-test"; createCounter(name, CounterConfiguration.builder(CounterType.BOUNDED_STRONG).lowerBound(0).upperBound(100) .initialValue(0).build()); RestCounterClient counterClient = client.counter(name); CompletionStage<RestResponse> response = counterClient.increment(); assertThat(response).hasReturnedText("1"); response = counterClient.increment(); assertThat(response).hasReturnedText("2"); response = counterClient.decrement(); assertThat(response).hasReturnedText("1"); response = counterClient.decrement(); assertThat(response).hasReturnedText("0"); response = counterClient.add(35); assertThat(response).hasReturnedText("35"); waitForCounterToReach(name, 35); response = counterClient.compareAndSet(5, 32); assertThat(response).hasReturnedText("false"); response = counterClient.compareAndSet(35, 50); assertThat(response).hasReturnedText("true"); waitForCounterToReach(name, 50); response = counterClient.compareAndSwap(50, 90); assertThat(response).hasReturnedText("50"); response = counterClient.get(); assertThat(response).hasReturnedText("90"); }
private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); }
CounterResource implements ResourceHandler { private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); } }
CounterResource implements ResourceHandler { private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); } CounterResource(InvocationHelper invocationHelper); }
CounterResource implements ResourceHandler { private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); } CounterResource(InvocationHelper invocationHelper); @Override Invocations getInvocations(); }
CounterResource implements ResourceHandler { private CompletionStage<RestResponse> createCounter(RestRequest request) throws RestResponseException { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); String counterName = request.variables().get("counterName"); String contents = request.contents().asString(); if (contents == null || contents.length() == 0) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST); responseBuilder.entity("Configuration not provided"); return completedFuture(responseBuilder.build()); } CounterConfiguration configuration = createCounterConfiguration(contents); if (configuration == null) { responseBuilder.status(HttpResponseStatus.BAD_REQUEST).entity("Invalid configuration"); return completedFuture(responseBuilder.build()); } return counterManager.defineCounterAsync(counterName, configuration).thenApply(r -> responseBuilder.build()); } CounterResource(InvocationHelper invocationHelper); @Override Invocations getInvocations(); }
@Test public void testInvalidSite() { RestClient client = clientPerSite.get(LON); RestCacheClient cache = client.cache(CACHE_1); assertStatus(404, cache.backupStatus("invalid-site")); }
private CompletionStage<RestResponse> backupStatus(RestRequest request) { return statusOperation(request, SITES_STATUS); }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> backupStatus(RestRequest request) { return statusOperation(request, SITES_STATUS); } }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> backupStatus(RestRequest request) { return statusOperation(request, SITES_STATUS); } XSiteResource(InvocationHelper invocationHelper); }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> backupStatus(RestRequest request) { return statusOperation(request, SITES_STATUS); } XSiteResource(InvocationHelper invocationHelper); @Override Invocations getInvocations(); }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> backupStatus(RestRequest request) { return statusOperation(request, SITES_STATUS); } XSiteResource(InvocationHelper invocationHelper); @Override Invocations getInvocations(); static final String AFTER_FAILURES_FIELD; static final String MIN_WAIT_FIELD; }
@Test public void testPushState() { RestCacheClient cache = getCacheClient(LON); RestCacheClient backupCache = getCacheClient(NYC); String key = "key"; String value = "value"; Function<String, Integer> keyOnBackup = k -> responseStatus(backupCache.get(key)); takeBackupOffline(LON, NYC); assertEquals(OFFLINE, getBackupStatus(LON, NYC)); assertEquals(ONLINE, getBackupStatus(LON, SFO)); assertNoContent(cache.put(key, value)); assertEquals(404, (int) keyOnBackup.apply(key)); assertSuccessful(cache.pushSiteState(NYC)); assertEquals(ONLINE, getBackupStatus(LON, NYC)); eventuallyEquals("OK", () -> pushStateStatus(cache, NYC)); assertEquals(200, responseStatus(backupCache.get(key))); }
private CompletionStage<RestResponse> pushStateStatus(RestRequest request) { return statusOperation(request, PUSH_STATE_STATUS); }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> pushStateStatus(RestRequest request) { return statusOperation(request, PUSH_STATE_STATUS); } }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> pushStateStatus(RestRequest request) { return statusOperation(request, PUSH_STATE_STATUS); } XSiteResource(InvocationHelper invocationHelper); }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> pushStateStatus(RestRequest request) { return statusOperation(request, PUSH_STATE_STATUS); } XSiteResource(InvocationHelper invocationHelper); @Override Invocations getInvocations(); }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> pushStateStatus(RestRequest request) { return statusOperation(request, PUSH_STATE_STATUS); } XSiteResource(InvocationHelper invocationHelper); @Override Invocations getInvocations(); static final String AFTER_FAILURES_FIELD; static final String MIN_WAIT_FIELD; }
@Test public void testCancelPushState() throws Exception { RestCacheClient cache = getCacheClient(LON); RestCacheClient backupCache = getCacheClient(NYC); takeBackupOffline(LON, NYC); assertEquals(OFFLINE, getBackupStatus(LON, NYC)); int entries = 50; IntStream.range(0, entries).forEach(i -> assertNoContent(cache.put(String.valueOf(i), "value"))); assertEquals(entries, getCacheSize(cache)); assertEquals(0, getCacheSize(backupCache)); ControlledTransport controllerTransport = ControlledTransport.replace(cache(LON, 0)); controllerTransport.blockBefore(XSiteStatePushCommand.class); assertSuccessful(cache.pushSiteState(NYC)); controllerTransport.waitForCommandToBlock(); assertSuccessful(cache.cancelPushState(NYC)); controllerTransport.stopBlocking(); Json status = jsonResponseBody(cache.pushStateStatus()); assertEquals("CANCELED", status.at(NYC).asString()); assertSuccessful(cache.clearPushStateStatus()); status = jsonResponseBody(cache.pushStateStatus()); assertTrue(status.asMap().isEmpty()); assertSuccessful(cache.cancelReceiveState(NYC)); }
private CompletionStage<RestResponse> cancelPushState(RestRequest restRequest) { return executeXSiteCacheOp(restRequest, CANCEL_PUSH_STATE); }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> cancelPushState(RestRequest restRequest) { return executeXSiteCacheOp(restRequest, CANCEL_PUSH_STATE); } }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> cancelPushState(RestRequest restRequest) { return executeXSiteCacheOp(restRequest, CANCEL_PUSH_STATE); } XSiteResource(InvocationHelper invocationHelper); }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> cancelPushState(RestRequest restRequest) { return executeXSiteCacheOp(restRequest, CANCEL_PUSH_STATE); } XSiteResource(InvocationHelper invocationHelper); @Override Invocations getInvocations(); }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> cancelPushState(RestRequest restRequest) { return executeXSiteCacheOp(restRequest, CANCEL_PUSH_STATE); } XSiteResource(InvocationHelper invocationHelper); @Override Invocations getInvocations(); static final String AFTER_FAILURES_FIELD; static final String MIN_WAIT_FIELD; }
@Test public void testPushAllCaches() { RestClient restClientLon = clientPerSite.get(LON); RestClient restClientSfo = clientPerSite.get(SFO); RestCacheClient cache1Lon = restClientLon.cache(CACHE_1); RestCacheClient cache2Lon = restClientLon.cache(CACHE_2); RestCacheClient cache1Sfo = restClientSfo.cache(CACHE_1); RestCacheClient cache2Sfo = restClientSfo.cache(CACHE_2); assertSuccessful(restClientLon.cacheManager(CACHE_MANAGER).takeOffline(SFO)); Json backupStatuses = jsonResponseBody(restClientLon.cacheManager(CACHE_MANAGER).backupStatuses()); assertEquals("offline", backupStatuses.at(SFO).at("status").asString()); int entries = 10; IntStream.range(0, entries).forEach(i -> { String key = String.valueOf(i); String value = "value"; assertNoContent(cache1Lon.put(key, value)); assertNoContent(cache2Lon.put(key, value)); }); assertEquals(0, getCacheSize(cache1Sfo)); assertEquals(0, getCacheSize(cache2Sfo)); assertSuccessful(restClientLon.cacheManager(CACHE_MANAGER).pushSiteState(SFO)); assertEquals(ONLINE, getBackupStatus(LON, SFO)); eventuallyEquals("OK", () -> pushStateStatus(cache1Lon, SFO)); eventuallyEquals("OK", () -> pushStateStatus(cache2Lon, SFO)); assertEquals(entries, getCacheSize(cache1Sfo)); assertEquals(entries, getCacheSize(cache2Sfo)); }
private CompletionStage<RestResponse> pushStateStatus(RestRequest request) { return statusOperation(request, PUSH_STATE_STATUS); }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> pushStateStatus(RestRequest request) { return statusOperation(request, PUSH_STATE_STATUS); } }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> pushStateStatus(RestRequest request) { return statusOperation(request, PUSH_STATE_STATUS); } XSiteResource(InvocationHelper invocationHelper); }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> pushStateStatus(RestRequest request) { return statusOperation(request, PUSH_STATE_STATUS); } XSiteResource(InvocationHelper invocationHelper); @Override Invocations getInvocations(); }
XSiteResource implements ResourceHandler { private CompletionStage<RestResponse> pushStateStatus(RestRequest request) { return statusOperation(request, PUSH_STATE_STATUS); } XSiteResource(InvocationHelper invocationHelper); @Override Invocations getInvocations(); static final String AFTER_FAILURES_FIELD; static final String MIN_WAIT_FIELD; }
@Test public void testSingleVariable() { Map<String, String> res = resolveVariables("{id}", "5435"); assertEquals(1, res.size()); assertEquals(res.get("id"), "5435"); }
static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
@Test public void testSingleVariable2() { Map<String, String> res = resolveVariables("{variable_name}", "a"); assertEquals(1, res.size()); assertEquals(res.get("variable_name"), "a"); }
static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
@Test public void testDualVariables() { Map<String, String> res = resolveVariables("{cachemanager}-{cache}", "default-mycache"); assertEquals(2, res.size()); assertEquals(res.get("cachemanager"), "default"); assertEquals(res.get("cache"), "mycache"); }
static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
@Test public void testDualVariables2() { Map<String, String> res = resolveVariables("{cachemanager}{cache}", "defaultmycache"); assertEquals(0, res.size()); }
static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
@Test public void testSize() { RangeSet rs = new RangeSet(4); assertEquals(4, rs.size()); }
@Override public int size() { return size; }
RangeSet implements IntSet { @Override public int size() { return size; } }
RangeSet implements IntSet { @Override public int size() { return size; } RangeSet(int size); }
RangeSet implements IntSet { @Override public int size() { return size; } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
RangeSet implements IntSet { @Override public int size() { return size; } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
@Test public void testDualVariables3() { Map<String, String> res = resolveVariables("{a}:{b}", "value1:value2"); assertEquals(2, res.size()); assertEquals(res.get("a"), "value1"); assertEquals(res.get("b"), "value2"); }
static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
@Test public void testPrefixSufix() { Map<String, String> res = resolveVariables("prefix_{variable1}_{variable2}_suffix", "prefix_value1_value2_suffix"); assertEquals(2, res.size()); assertEquals(res.get("variable1"), "value1"); assertEquals(res.get("variable2"), "value2"); }
static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
@Test public void testSingleVariableWithPrefix() { Map<String, String> res = resolveVariables("counter-{id}", "counter-2345"); assertEquals(1, res.size()); assertEquals(res.get("id"), "2345"); }
static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
@Test public void testNull() { Map<String, String> res1 = resolveVariables(null, "whatever"); Map<String, String> res2 = resolveVariables("{hello}", null); assertEquals(0, res1.size()); assertEquals(0, res2.size()); }
static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
@Test public void testNonConformantPath() { Map<String, String> res = resolveVariables("{cachemanager}-{cache}", "default"); assertEquals(0, res.size()); }
static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
@Test public void testMalformedExpression() { Map<String, String> res = resolveVariables("{counter {id}}", "whatever"); assertEquals(0, res.size()); }
static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
@Test public void testMalformedExpression2() { Map<String, String> res = resolveVariables("{counter }id}-", "whatever"); assertEquals(0, res.size()); }
static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
PathInterpreter { static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j = 0; int expressionLength = expression.length(); for (int i = 0; i < expressionLength; i++) { char e = expression.charAt(i); switch (e) { case '{': if (state == END_VAR) return Collections.emptyMap(); state = VAR; break; case '}': if (state != VAR) return Collections.emptyMap(); state = END_VAR; if (i != expressionLength - 1) break; default: switch (state) { case VAR: variableBuilder.append(e); break; case END_VAR: String replacement; boolean ec = i == expressionLength - 1; if (ec) { replacement = str.substring(j); } else { int k = str.indexOf(e, j); if (k == -1) return Collections.emptyMap(); replacement = str.substring(j, str.indexOf(e, j)); } resolvedVariables.put(variableBuilder.toString(), replacement); j += replacement.length(); if (j == str.length() && ec) return resolvedVariables; variableBuilder.setLength(0); state = TEXT; case TEXT: if (str.charAt(j) != e) return Collections.emptyMap(); j++; } } } return resolvedVariables; } }
@Test public void testLookupHandler() { registerHandler("root", "CompaniesHandler", "/companies", "/companies/{company}", "/companies/{company}/{id}"); registerHandler("root", "StocksHandler", "/stocks/{stock}", "/stocks/{stock}/{currency}"); registerHandler("root", "DirectorsHandler", "/directors", "/directors/director", "/directors/director/{personId}"); registerHandler("root", "InfoHandler", "/info", "/info/jvm", "/info/jvm/{format}", "/info/{format}/{encoding}"); assertEquals(NOT_FOUND, resourceManager.lookupResource(GET, "/root/dummy").getStatus()); assertEquals(NOT_FOUND, resourceManager.lookupResource(GET, "/fake/").getStatus()); assertEquals(NOT_FOUND, resourceManager.lookupResource(GET, "/").getStatus()); assertEquals(NOT_FOUND, resourceManager.lookupResource(GET, "/root/stocks").getStatus()); assertEquals(NOT_FOUND, resourceManager.lookupResource(GET, "/root/stocks/2/USD/1").getStatus()); assertInvocation(resourceManager.lookupResource(GET, "/root/stocks/2"), "StocksHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/stocks/2/USD"), "StocksHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/directors"), "DirectorsHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/directors/director"), "DirectorsHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/directors/director/John"), "DirectorsHandler"); assertEquals(NOT_FOUND, resourceManager.lookupResource(GET, "/root/directors/1345").getStatus()); assertEquals(NOT_FOUND, resourceManager.lookupResource(GET, "/root/directors/director/Tim/123").getStatus()); assertInvocation(resourceManager.lookupResource(GET, "/root/companies"), "CompaniesHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/info"), "InfoHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/info/jvm"), "InfoHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/info/jvm/json"), "InfoHandler"); assertInvocation(resourceManager.lookupResource(GET, "/root/info/json/zip"), "InfoHandler"); }
@Override public LookupResult lookupResource(Method method, String path, String action) { List<PathItem> pathItems = Arrays.stream(path.replaceAll(" .map(s -> s.isEmpty() ? "/" : s).map(QueryStringDecoder::decodeComponent).map(PathItem::fromString).collect(Collectors.toList()); return resourceTree.find(method, pathItems, action); }
ResourceManagerImpl implements ResourceManager { @Override public LookupResult lookupResource(Method method, String path, String action) { List<PathItem> pathItems = Arrays.stream(path.replaceAll(" .map(s -> s.isEmpty() ? "/" : s).map(QueryStringDecoder::decodeComponent).map(PathItem::fromString).collect(Collectors.toList()); return resourceTree.find(method, pathItems, action); } }
ResourceManagerImpl implements ResourceManager { @Override public LookupResult lookupResource(Method method, String path, String action) { List<PathItem> pathItems = Arrays.stream(path.replaceAll(" .map(s -> s.isEmpty() ? "/" : s).map(QueryStringDecoder::decodeComponent).map(PathItem::fromString).collect(Collectors.toList()); return resourceTree.find(method, pathItems, action); } ResourceManagerImpl(); }
ResourceManagerImpl implements ResourceManager { @Override public LookupResult lookupResource(Method method, String path, String action) { List<PathItem> pathItems = Arrays.stream(path.replaceAll(" .map(s -> s.isEmpty() ? "/" : s).map(QueryStringDecoder::decodeComponent).map(PathItem::fromString).collect(Collectors.toList()); return resourceTree.find(method, pathItems, action); } ResourceManagerImpl(); @Override void registerResource(String context, ResourceHandler handler); @Override LookupResult lookupResource(Method method, String path, String action); }
ResourceManagerImpl implements ResourceManager { @Override public LookupResult lookupResource(Method method, String path, String action) { List<PathItem> pathItems = Arrays.stream(path.replaceAll(" .map(s -> s.isEmpty() ? "/" : s).map(QueryStringDecoder::decodeComponent).map(PathItem::fromString).collect(Collectors.toList()); return resourceTree.find(method, pathItems, action); } ResourceManagerImpl(); @Override void registerResource(String context, ResourceHandler handler); @Override LookupResult lookupResource(Method method, String path, String action); }
@Test public void testLookupStatuses() { registerHandler("ctx", "handler1", "/items/{item}"); registerHandlerWithAction("ctx", new Method[]{GET}, "handler2", "clear", "/items/{item}/{sub}"); LookupResult lookupResult = resourceManager.lookupResource(GET, "/invalid"); assertEquals(NOT_FOUND, lookupResult.getStatus()); lookupResult = resourceManager.lookupResource(GET, "/ctx/items/1"); assertEquals(FOUND, lookupResult.getStatus()); lookupResult = resourceManager.lookupResource(DELETE, "/ctx/items/1"); assertEquals(INVALID_METHOD, lookupResult.getStatus()); lookupResult = resourceManager.lookupResource(GET, "/ctx/items/1/1", "clear"); assertEquals(FOUND, lookupResult.getStatus()); lookupResult = resourceManager.lookupResource(GET, "/ctx/items/1/1"); assertEquals(INVALID_ACTION, lookupResult.getStatus()); lookupResult = resourceManager.lookupResource(GET, "/ctx/items/1/1", "invalid"); assertEquals(INVALID_ACTION, lookupResult.getStatus()); lookupResult = resourceManager.lookupResource(GET, "/ctx/items/1", "invalid"); assertEquals(INVALID_ACTION, lookupResult.getStatus()); }
@Override public LookupResult lookupResource(Method method, String path, String action) { List<PathItem> pathItems = Arrays.stream(path.replaceAll(" .map(s -> s.isEmpty() ? "/" : s).map(QueryStringDecoder::decodeComponent).map(PathItem::fromString).collect(Collectors.toList()); return resourceTree.find(method, pathItems, action); }
ResourceManagerImpl implements ResourceManager { @Override public LookupResult lookupResource(Method method, String path, String action) { List<PathItem> pathItems = Arrays.stream(path.replaceAll(" .map(s -> s.isEmpty() ? "/" : s).map(QueryStringDecoder::decodeComponent).map(PathItem::fromString).collect(Collectors.toList()); return resourceTree.find(method, pathItems, action); } }
ResourceManagerImpl implements ResourceManager { @Override public LookupResult lookupResource(Method method, String path, String action) { List<PathItem> pathItems = Arrays.stream(path.replaceAll(" .map(s -> s.isEmpty() ? "/" : s).map(QueryStringDecoder::decodeComponent).map(PathItem::fromString).collect(Collectors.toList()); return resourceTree.find(method, pathItems, action); } ResourceManagerImpl(); }
ResourceManagerImpl implements ResourceManager { @Override public LookupResult lookupResource(Method method, String path, String action) { List<PathItem> pathItems = Arrays.stream(path.replaceAll(" .map(s -> s.isEmpty() ? "/" : s).map(QueryStringDecoder::decodeComponent).map(PathItem::fromString).collect(Collectors.toList()); return resourceTree.find(method, pathItems, action); } ResourceManagerImpl(); @Override void registerResource(String context, ResourceHandler handler); @Override LookupResult lookupResource(Method method, String path, String action); }
ResourceManagerImpl implements ResourceManager { @Override public LookupResult lookupResource(Method method, String path, String action) { List<PathItem> pathItems = Arrays.stream(path.replaceAll(" .map(s -> s.isEmpty() ? "/" : s).map(QueryStringDecoder::decodeComponent).map(PathItem::fromString).collect(Collectors.toList()); return resourceTree.find(method, pathItems, action); } ResourceManagerImpl(); @Override void registerResource(String context, ResourceHandler handler); @Override LookupResult lookupResource(Method method, String path, String action); }
@Test public void shouldReuseEncodedCaches() { EmbeddedCacheManager embeddedCacheManager = Mockito.spy(cacheManager); RestCacheManager<Object> restCacheManager = new RestCacheManager<>(embeddedCacheManager, c -> Boolean.FALSE); Map<String, Cache<String, ?>> knownCaches = TestingUtil.extractField(restCacheManager, "knownCaches"); SimpleRequest request = new SimpleRequest.Builder().setPath("/test").build(); restCacheManager.getCache("cache1", request); restCacheManager.getCache("cache2", request); assertEquals(knownCaches.size(), 2); Mockito.reset(embeddedCacheManager); restCacheManager.getCache("cache1", request); restCacheManager.getCache("cache2", request); Mockito.verify(embeddedCacheManager, never()).getCache("cache1"); Mockito.verify(embeddedCacheManager, never()).getCache("cache2"); restCacheManager.getCache("cache2", MediaType.MATCH_ALL, MediaType.APPLICATION_JSON, request); restCacheManager.getCache("cache2", MediaType.MATCH_ALL, MediaType.TEXT_PLAIN, request); assertEquals(knownCaches.size(), 4); Mockito.reset(embeddedCacheManager); restCacheManager.getCache("cache2", MediaType.MATCH_ALL, MediaType.TEXT_PLAIN, request); restCacheManager.getCache("cache2", MediaType.MATCH_ALL, MediaType.fromString("text/plain; charset=UTF-8"), request); restCacheManager.getCache("cache2", MediaType.MATCH_ALL, MediaType.fromString("text/plain; charset=SHIFT-JIS"), request); assertEquals(knownCaches.keySet().size(), 4); Mockito.verify(embeddedCacheManager, never()).getCache("cache1"); Mockito.verify(embeddedCacheManager, never()).getCache("cache2"); }
@SuppressWarnings("unchecked") public AdvancedCache<Object, V> getCache(String name, MediaType keyContentType, MediaType valueContentType, RestRequest request) { Subject subject = request.getSubject(); Flag[] flags = request.getFlags(); if (isCacheIgnored.test(name)) { throw logger.cacheUnavailable(name); } if (keyContentType == null || valueContentType == null) { throw logger.missingRequiredMediaType(name); } checkCacheAvailable(name); String cacheKey = name + "-" + keyContentType.getTypeSubtype() + valueContentType.getTypeSubtype(); AdvancedCache<Object, V> cache = knownCaches.get(cacheKey); if (cache == null) { cache = instance.<Object, V>getCache(name).getAdvancedCache(); tryRegisterMigrationManager(cache); cache = (AdvancedCache<Object, V>) cache.getAdvancedCache() .withMediaType(keyContentType.toString(), valueContentType.toString()) .withFlags(IGNORE_RETURN_VALUES); knownCaches.putIfAbsent(cacheKey, cache); } if (flags != null && flags.length > 0) cache = cache.withFlags(flags); return subject == null ? cache : cache.withSubject(subject); }
RestCacheManager { @SuppressWarnings("unchecked") public AdvancedCache<Object, V> getCache(String name, MediaType keyContentType, MediaType valueContentType, RestRequest request) { Subject subject = request.getSubject(); Flag[] flags = request.getFlags(); if (isCacheIgnored.test(name)) { throw logger.cacheUnavailable(name); } if (keyContentType == null || valueContentType == null) { throw logger.missingRequiredMediaType(name); } checkCacheAvailable(name); String cacheKey = name + "-" + keyContentType.getTypeSubtype() + valueContentType.getTypeSubtype(); AdvancedCache<Object, V> cache = knownCaches.get(cacheKey); if (cache == null) { cache = instance.<Object, V>getCache(name).getAdvancedCache(); tryRegisterMigrationManager(cache); cache = (AdvancedCache<Object, V>) cache.getAdvancedCache() .withMediaType(keyContentType.toString(), valueContentType.toString()) .withFlags(IGNORE_RETURN_VALUES); knownCaches.putIfAbsent(cacheKey, cache); } if (flags != null && flags.length > 0) cache = cache.withFlags(flags); return subject == null ? cache : cache.withSubject(subject); } }
RestCacheManager { @SuppressWarnings("unchecked") public AdvancedCache<Object, V> getCache(String name, MediaType keyContentType, MediaType valueContentType, RestRequest request) { Subject subject = request.getSubject(); Flag[] flags = request.getFlags(); if (isCacheIgnored.test(name)) { throw logger.cacheUnavailable(name); } if (keyContentType == null || valueContentType == null) { throw logger.missingRequiredMediaType(name); } checkCacheAvailable(name); String cacheKey = name + "-" + keyContentType.getTypeSubtype() + valueContentType.getTypeSubtype(); AdvancedCache<Object, V> cache = knownCaches.get(cacheKey); if (cache == null) { cache = instance.<Object, V>getCache(name).getAdvancedCache(); tryRegisterMigrationManager(cache); cache = (AdvancedCache<Object, V>) cache.getAdvancedCache() .withMediaType(keyContentType.toString(), valueContentType.toString()) .withFlags(IGNORE_RETURN_VALUES); knownCaches.putIfAbsent(cacheKey, cache); } if (flags != null && flags.length > 0) cache = cache.withFlags(flags); return subject == null ? cache : cache.withSubject(subject); } RestCacheManager(EmbeddedCacheManager instance, Predicate<? super String> isCacheIgnored); }
RestCacheManager { @SuppressWarnings("unchecked") public AdvancedCache<Object, V> getCache(String name, MediaType keyContentType, MediaType valueContentType, RestRequest request) { Subject subject = request.getSubject(); Flag[] flags = request.getFlags(); if (isCacheIgnored.test(name)) { throw logger.cacheUnavailable(name); } if (keyContentType == null || valueContentType == null) { throw logger.missingRequiredMediaType(name); } checkCacheAvailable(name); String cacheKey = name + "-" + keyContentType.getTypeSubtype() + valueContentType.getTypeSubtype(); AdvancedCache<Object, V> cache = knownCaches.get(cacheKey); if (cache == null) { cache = instance.<Object, V>getCache(name).getAdvancedCache(); tryRegisterMigrationManager(cache); cache = (AdvancedCache<Object, V>) cache.getAdvancedCache() .withMediaType(keyContentType.toString(), valueContentType.toString()) .withFlags(IGNORE_RETURN_VALUES); knownCaches.putIfAbsent(cacheKey, cache); } if (flags != null && flags.length > 0) cache = cache.withFlags(flags); return subject == null ? cache : cache.withSubject(subject); } RestCacheManager(EmbeddedCacheManager instance, Predicate<? super String> isCacheIgnored); @SuppressWarnings("unchecked") AdvancedCache<Object, V> getCache(String name, MediaType keyContentType, MediaType valueContentType, RestRequest request); AdvancedCache<Object, V> getCache(String name, RestRequest restRequest); boolean cacheExists(String name); boolean isCacheQueryable(Cache<?, ?> cache); Collection<String> getCacheNames(); CompletionStage<CacheEntry<Object, V>> getInternalEntry(String cacheName, Object key, MediaType keyContentType, MediaType mediaType, RestRequest request); CompletionStage<V> remove(String cacheName, Object key, MediaType keyContentType, RestRequest restRequest); CompletionStage<CacheEntry<Object, V>> getPrivilegedInternalEntry(AdvancedCache<Object, V> cache, Object key, boolean skipListener); MediaType getValueConfiguredFormat(String cacheName, RestRequest restRequest); String getNodeName(); String getServerAddress(); String getPrimaryOwner(String cacheName, Object key, RestRequest restRequest); String getBackupOwners(String cacheName, Object key, RestRequest restRequest); EmbeddedCacheManager getInstance(); EmbeddedCacheManagerAdmin getCacheManagerAdmin(RestRequest restRequest); void stop(); }
RestCacheManager { @SuppressWarnings("unchecked") public AdvancedCache<Object, V> getCache(String name, MediaType keyContentType, MediaType valueContentType, RestRequest request) { Subject subject = request.getSubject(); Flag[] flags = request.getFlags(); if (isCacheIgnored.test(name)) { throw logger.cacheUnavailable(name); } if (keyContentType == null || valueContentType == null) { throw logger.missingRequiredMediaType(name); } checkCacheAvailable(name); String cacheKey = name + "-" + keyContentType.getTypeSubtype() + valueContentType.getTypeSubtype(); AdvancedCache<Object, V> cache = knownCaches.get(cacheKey); if (cache == null) { cache = instance.<Object, V>getCache(name).getAdvancedCache(); tryRegisterMigrationManager(cache); cache = (AdvancedCache<Object, V>) cache.getAdvancedCache() .withMediaType(keyContentType.toString(), valueContentType.toString()) .withFlags(IGNORE_RETURN_VALUES); knownCaches.putIfAbsent(cacheKey, cache); } if (flags != null && flags.length > 0) cache = cache.withFlags(flags); return subject == null ? cache : cache.withSubject(subject); } RestCacheManager(EmbeddedCacheManager instance, Predicate<? super String> isCacheIgnored); @SuppressWarnings("unchecked") AdvancedCache<Object, V> getCache(String name, MediaType keyContentType, MediaType valueContentType, RestRequest request); AdvancedCache<Object, V> getCache(String name, RestRequest restRequest); boolean cacheExists(String name); boolean isCacheQueryable(Cache<?, ?> cache); Collection<String> getCacheNames(); CompletionStage<CacheEntry<Object, V>> getInternalEntry(String cacheName, Object key, MediaType keyContentType, MediaType mediaType, RestRequest request); CompletionStage<V> remove(String cacheName, Object key, MediaType keyContentType, RestRequest restRequest); CompletionStage<CacheEntry<Object, V>> getPrivilegedInternalEntry(AdvancedCache<Object, V> cache, Object key, boolean skipListener); MediaType getValueConfiguredFormat(String cacheName, RestRequest restRequest); String getNodeName(); String getServerAddress(); String getPrimaryOwner(String cacheName, Object key, RestRequest restRequest); String getBackupOwners(String cacheName, Object key, RestRequest restRequest); EmbeddedCacheManager getInstance(); EmbeddedCacheManagerAdmin getCacheManagerAdmin(RestRequest restRequest); void stop(); }
@Test public void testIsEmpty() { RangeSet rs = new RangeSet(0); assertTrue(rs.isEmpty()); rs = new RangeSet(3); assertFalse(rs.isEmpty()); }
@Override public boolean isEmpty() { return size <= 0; }
RangeSet implements IntSet { @Override public boolean isEmpty() { return size <= 0; } }
RangeSet implements IntSet { @Override public boolean isEmpty() { return size <= 0; } RangeSet(int size); }
RangeSet implements IntSet { @Override public boolean isEmpty() { return size <= 0; } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
RangeSet implements IntSet { @Override public boolean isEmpty() { return size <= 0; } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
@Test public void testDuplicateServiceFinder() { ClassLoader mainClassLoader = this.getClass().getClassLoader(); ClassLoader otherClassLoader = new ClonedClassLoader(mainClassLoader); Collection<SampleSPI> spis = ServiceFinder.load(SampleSPI.class, mainClassLoader, otherClassLoader); assertEquals(1, spis.size()); }
public static <T> Collection<T> load(Class<T> contract, ClassLoader... loaders) { Map<String, T> services = new LinkedHashMap<>(); if (loaders.length == 0) { try { ServiceLoader<T> loadedServices = ServiceLoader.load(contract); addServices(loadedServices, services); } catch (Exception e) { } } else { for (ClassLoader loader : loaders) { if (loader == null) throw new NullPointerException(); try { ServiceLoader<T> loadedServices = ServiceLoader.load(contract, loader); addServices(loadedServices, services); } catch (Exception e) { } } } if (services.isEmpty()) { LOG.debugf("No service impls found: %s", contract.getSimpleName()); } return services.values(); }
ServiceFinder { public static <T> Collection<T> load(Class<T> contract, ClassLoader... loaders) { Map<String, T> services = new LinkedHashMap<>(); if (loaders.length == 0) { try { ServiceLoader<T> loadedServices = ServiceLoader.load(contract); addServices(loadedServices, services); } catch (Exception e) { } } else { for (ClassLoader loader : loaders) { if (loader == null) throw new NullPointerException(); try { ServiceLoader<T> loadedServices = ServiceLoader.load(contract, loader); addServices(loadedServices, services); } catch (Exception e) { } } } if (services.isEmpty()) { LOG.debugf("No service impls found: %s", contract.getSimpleName()); } return services.values(); } }
ServiceFinder { public static <T> Collection<T> load(Class<T> contract, ClassLoader... loaders) { Map<String, T> services = new LinkedHashMap<>(); if (loaders.length == 0) { try { ServiceLoader<T> loadedServices = ServiceLoader.load(contract); addServices(loadedServices, services); } catch (Exception e) { } } else { for (ClassLoader loader : loaders) { if (loader == null) throw new NullPointerException(); try { ServiceLoader<T> loadedServices = ServiceLoader.load(contract, loader); addServices(loadedServices, services); } catch (Exception e) { } } } if (services.isEmpty()) { LOG.debugf("No service impls found: %s", contract.getSimpleName()); } return services.values(); } }
ServiceFinder { public static <T> Collection<T> load(Class<T> contract, ClassLoader... loaders) { Map<String, T> services = new LinkedHashMap<>(); if (loaders.length == 0) { try { ServiceLoader<T> loadedServices = ServiceLoader.load(contract); addServices(loadedServices, services); } catch (Exception e) { } } else { for (ClassLoader loader : loaders) { if (loader == null) throw new NullPointerException(); try { ServiceLoader<T> loadedServices = ServiceLoader.load(contract, loader); addServices(loadedServices, services); } catch (Exception e) { } } } if (services.isEmpty()) { LOG.debugf("No service impls found: %s", contract.getSimpleName()); } return services.values(); } static Collection<T> load(Class<T> contract, ClassLoader... loaders); }
ServiceFinder { public static <T> Collection<T> load(Class<T> contract, ClassLoader... loaders) { Map<String, T> services = new LinkedHashMap<>(); if (loaders.length == 0) { try { ServiceLoader<T> loadedServices = ServiceLoader.load(contract); addServices(loadedServices, services); } catch (Exception e) { } } else { for (ClassLoader loader : loaders) { if (loader == null) throw new NullPointerException(); try { ServiceLoader<T> loadedServices = ServiceLoader.load(contract, loader); addServices(loadedServices, services); } catch (Exception e) { } } } if (services.isEmpty()) { LOG.debugf("No service impls found: %s", contract.getSimpleName()); } return services.values(); } static Collection<T> load(Class<T> contract, ClassLoader... loaders); }
@Test(expected = IllegalArgumentException.class) public void shouldValidatePath() { new RestRouteSource(null).validate(); }
@Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } RestRouteSource(String pathPrefix); }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } RestRouteSource(String pathPrefix); @Override String getRoutePrefix(); @Override String toString(); @Override void validate(); }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } RestRouteSource(String pathPrefix); @Override String getRoutePrefix(); @Override String toString(); @Override void validate(); }
@Test(expected = IllegalArgumentException.class) public void shouldValidateWithWhiteCharacters() { new RestRouteSource("12312 234").validate(); }
@Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } RestRouteSource(String pathPrefix); }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } RestRouteSource(String pathPrefix); @Override String getRoutePrefix(); @Override String toString(); @Override void validate(); }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } RestRouteSource(String pathPrefix); @Override String getRoutePrefix(); @Override String toString(); @Override void validate(); }
@Test(expected = IllegalArgumentException.class) public void shouldValidateStartingSlash() { new RestRouteSource("/test").validate(); }
@Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } RestRouteSource(String pathPrefix); }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } RestRouteSource(String pathPrefix); @Override String getRoutePrefix(); @Override String toString(); @Override void validate(); }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } RestRouteSource(String pathPrefix); @Override String getRoutePrefix(); @Override String toString(); @Override void validate(); }
@Test public void shouldPassOnCorrectPath() { new RestRouteSource("correctPath").validate(); }
@Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } RestRouteSource(String pathPrefix); }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } RestRouteSource(String pathPrefix); @Override String getRoutePrefix(); @Override String toString(); @Override void validate(); }
RestRouteSource implements PrefixedRouteSource { @Override public void validate() { if (pathPrefix == null || !pathPrefix.matches("\\w+")) { throw new IllegalArgumentException("Path is incorrect"); } } RestRouteSource(String pathPrefix); @Override String getRoutePrefix(); @Override String toString(); @Override void validate(); }
@Test(expected = IllegalArgumentException.class) public void shouldValidateName() { new RestServerRouteDestination(null, new RestServer()).validate(); }
@Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (restServer == null) { throw new IllegalArgumentException("REST resource can not be null"); } }
RestServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (restServer == null) { throw new IllegalArgumentException("REST resource can not be null"); } } }
RestServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (restServer == null) { throw new IllegalArgumentException("REST resource can not be null"); } } RestServerRouteDestination(String name, RestServer restServer); }
RestServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (restServer == null) { throw new IllegalArgumentException("REST resource can not be null"); } } RestServerRouteDestination(String name, RestServer restServer); String getName(); RestServer getRestServer(); @Override String toString(); @Override void validate(); }
RestServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (restServer == null) { throw new IllegalArgumentException("REST resource can not be null"); } } RestServerRouteDestination(String name, RestServer restServer); String getName(); RestServer getRestServer(); @Override String toString(); @Override void validate(); }
@Test(expected = IllegalArgumentException.class) public void shouldValidateRestResource() { new RestServerRouteDestination("test", null).validate(); }
@Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (restServer == null) { throw new IllegalArgumentException("REST resource can not be null"); } }
RestServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (restServer == null) { throw new IllegalArgumentException("REST resource can not be null"); } } }
RestServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (restServer == null) { throw new IllegalArgumentException("REST resource can not be null"); } } RestServerRouteDestination(String name, RestServer restServer); }
RestServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (restServer == null) { throw new IllegalArgumentException("REST resource can not be null"); } } RestServerRouteDestination(String name, RestServer restServer); String getName(); RestServer getRestServer(); @Override String toString(); @Override void validate(); }
RestServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (restServer == null) { throw new IllegalArgumentException("REST resource can not be null"); } } RestServerRouteDestination(String name, RestServer restServer); String getName(); RestServer getRestServer(); @Override String toString(); @Override void validate(); }
@Test(expected = IllegalArgumentException.class) public void shouldValidateSniHostName() throws Exception { new SniNettyRouteSource(null, SSLContext.getDefault()).validate(); }
@Override public void validate() { if (sniHostName == null || "".equals(sniHostName)) { throw new IllegalArgumentException("SNI Host name can not be null"); } if (jdkContext == null) { throw new IllegalArgumentException("JDK SSL Context must not be null"); } }
SniNettyRouteSource implements SniRouteSource { @Override public void validate() { if (sniHostName == null || "".equals(sniHostName)) { throw new IllegalArgumentException("SNI Host name can not be null"); } if (jdkContext == null) { throw new IllegalArgumentException("JDK SSL Context must not be null"); } } }
SniNettyRouteSource implements SniRouteSource { @Override public void validate() { if (sniHostName == null || "".equals(sniHostName)) { throw new IllegalArgumentException("SNI Host name can not be null"); } if (jdkContext == null) { throw new IllegalArgumentException("JDK SSL Context must not be null"); } } SniNettyRouteSource(String sniHostName, SSLContext sslContext); SniNettyRouteSource(String sniHostName, String keyStoreFileName, char[] keyStorePassword); }
SniNettyRouteSource implements SniRouteSource { @Override public void validate() { if (sniHostName == null || "".equals(sniHostName)) { throw new IllegalArgumentException("SNI Host name can not be null"); } if (jdkContext == null) { throw new IllegalArgumentException("JDK SSL Context must not be null"); } } SniNettyRouteSource(String sniHostName, SSLContext sslContext); SniNettyRouteSource(String sniHostName, String keyStoreFileName, char[] keyStorePassword); @Override SSLContext getSslContext(); @Override String getSniHostName(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override void validate(); }
SniNettyRouteSource implements SniRouteSource { @Override public void validate() { if (sniHostName == null || "".equals(sniHostName)) { throw new IllegalArgumentException("SNI Host name can not be null"); } if (jdkContext == null) { throw new IllegalArgumentException("JDK SSL Context must not be null"); } } SniNettyRouteSource(String sniHostName, SSLContext sslContext); SniNettyRouteSource(String sniHostName, String keyStoreFileName, char[] keyStorePassword); @Override SSLContext getSslContext(); @Override String getSniHostName(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override void validate(); }
@Test(expected = IllegalArgumentException.class) public void shouldValidateSSLContext() throws Exception { new SniNettyRouteSource("test", null).validate(); }
@Override public void validate() { if (sniHostName == null || "".equals(sniHostName)) { throw new IllegalArgumentException("SNI Host name can not be null"); } if (jdkContext == null) { throw new IllegalArgumentException("JDK SSL Context must not be null"); } }
SniNettyRouteSource implements SniRouteSource { @Override public void validate() { if (sniHostName == null || "".equals(sniHostName)) { throw new IllegalArgumentException("SNI Host name can not be null"); } if (jdkContext == null) { throw new IllegalArgumentException("JDK SSL Context must not be null"); } } }
SniNettyRouteSource implements SniRouteSource { @Override public void validate() { if (sniHostName == null || "".equals(sniHostName)) { throw new IllegalArgumentException("SNI Host name can not be null"); } if (jdkContext == null) { throw new IllegalArgumentException("JDK SSL Context must not be null"); } } SniNettyRouteSource(String sniHostName, SSLContext sslContext); SniNettyRouteSource(String sniHostName, String keyStoreFileName, char[] keyStorePassword); }
SniNettyRouteSource implements SniRouteSource { @Override public void validate() { if (sniHostName == null || "".equals(sniHostName)) { throw new IllegalArgumentException("SNI Host name can not be null"); } if (jdkContext == null) { throw new IllegalArgumentException("JDK SSL Context must not be null"); } } SniNettyRouteSource(String sniHostName, SSLContext sslContext); SniNettyRouteSource(String sniHostName, String keyStoreFileName, char[] keyStorePassword); @Override SSLContext getSslContext(); @Override String getSniHostName(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override void validate(); }
SniNettyRouteSource implements SniRouteSource { @Override public void validate() { if (sniHostName == null || "".equals(sniHostName)) { throw new IllegalArgumentException("SNI Host name can not be null"); } if (jdkContext == null) { throw new IllegalArgumentException("JDK SSL Context must not be null"); } } SniNettyRouteSource(String sniHostName, SSLContext sslContext); SniNettyRouteSource(String sniHostName, String keyStoreFileName, char[] keyStorePassword); @Override SSLContext getSslContext(); @Override String getSniHostName(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override void validate(); }
@Test(expected = IllegalArgumentException.class) public void shouldValidateName() { new HotRodServerRouteDestination(null, new HotRodServer()).validate(); }
@Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (hotrodServer == null) { throw new IllegalArgumentException("Channels can not be null"); } }
HotRodServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (hotrodServer == null) { throw new IllegalArgumentException("Channels can not be null"); } } }
HotRodServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (hotrodServer == null) { throw new IllegalArgumentException("Channels can not be null"); } } HotRodServerRouteDestination(String name, HotRodServer hotRodServer); }
HotRodServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (hotrodServer == null) { throw new IllegalArgumentException("Channels can not be null"); } } HotRodServerRouteDestination(String name, HotRodServer hotRodServer); HotRodServer getHotrodServer(); @Override String toString(); @Override void validate(); }
HotRodServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (hotrodServer == null) { throw new IllegalArgumentException("Channels can not be null"); } } HotRodServerRouteDestination(String name, HotRodServer hotRodServer); HotRodServer getHotrodServer(); @Override String toString(); @Override void validate(); }
@Test(expected = IllegalArgumentException.class) public void shouldValidateChannelInitializer() { new HotRodServerRouteDestination("test", null).validate(); }
@Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (hotrodServer == null) { throw new IllegalArgumentException("Channels can not be null"); } }
HotRodServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (hotrodServer == null) { throw new IllegalArgumentException("Channels can not be null"); } } }
HotRodServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (hotrodServer == null) { throw new IllegalArgumentException("Channels can not be null"); } } HotRodServerRouteDestination(String name, HotRodServer hotRodServer); }
HotRodServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (hotrodServer == null) { throw new IllegalArgumentException("Channels can not be null"); } } HotRodServerRouteDestination(String name, HotRodServer hotRodServer); HotRodServer getHotrodServer(); @Override String toString(); @Override void validate(); }
HotRodServerRouteDestination implements RouteDestination { @Override public void validate() { if (name == null || "".equals(name)) { throw new IllegalArgumentException("Name can not be null"); } if (hotrodServer == null) { throw new IllegalArgumentException("Channels can not be null"); } } HotRodServerRouteDestination(String name, HotRodServer hotRodServer); HotRodServer getHotrodServer(); @Override String toString(); @Override void validate(); }
@Test public void contains() throws Exception { RangeSet rs = new RangeSet(4); assertFalse(rs.contains(5)); assertTrue(rs.contains(1)); }
@Override public boolean contains(Object o) { if (!(o instanceof Integer)) return false; int i = (int) o; return contains(i); }
RangeSet implements IntSet { @Override public boolean contains(Object o) { if (!(o instanceof Integer)) return false; int i = (int) o; return contains(i); } }
RangeSet implements IntSet { @Override public boolean contains(Object o) { if (!(o instanceof Integer)) return false; int i = (int) o; return contains(i); } RangeSet(int size); }
RangeSet implements IntSet { @Override public boolean contains(Object o) { if (!(o instanceof Integer)) return false; int i = (int) o; return contains(i); } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
RangeSet implements IntSet { @Override public boolean contains(Object o) { if (!(o instanceof Integer)) return false; int i = (int) o; return contains(i); } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
@Test public void testEmptyContent() { byte[] empty = Util.EMPTY_BYTE_ARRAY; assertArrayEquals(empty, (byte[]) transcoder.transcode(empty, APPLICATION_JSON, APPLICATION_JSON.withCharset(US_ASCII))); assertArrayEquals(empty, (byte[]) transcoder.transcode(empty, APPLICATION_UNKNOWN, APPLICATION_JSON)); assertArrayEquals(empty, (byte[]) transcoder.transcode(empty, APPLICATION_OCTET_STREAM, APPLICATION_JSON)); assertArrayEquals(empty, (byte[]) transcoder.transcode(empty, TEXT_PLAIN, APPLICATION_JSON)); assertArrayEquals(empty, (byte[]) transcoder.transcode(empty, APPLICATION_OBJECT, APPLICATION_JSON)); }
@Override public Object transcode(Object content, MediaType contentType, MediaType destinationType) { if (destinationType.match(APPLICATION_OCTET_STREAM) || destinationType.match(APPLICATION_UNKNOWN)) { return StandardConversions.convertTextToOctetStream(content, contentType); } boolean outputString = destinationType.hasStringType(); Charset contentCharset = contentType.getCharset(); Charset destinationCharset = destinationType.getCharset(); if (destinationType.match(APPLICATION_JSON)) { if (contentType.match(APPLICATION_JSON)) { return convertCharset(content, contentCharset, destinationCharset, outputString); } try { if (content instanceof String || content instanceof byte[]) { return convertTextToJson(content, contentCharset, destinationCharset, outputString); } logger.jsonObjectConversionDeprecated(); if (outputString) { return objectMapper.writeValueAsString(content); } try (ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(out, destinationCharset)) { objectMapper.writeValue(osw, content); return out.toByteArray(); } } catch (IOException e) { throw logger.cannotConvertContent(content, contentType, destinationType); } } if (destinationType.match(APPLICATION_OBJECT)) { logger.jsonObjectConversionDeprecated(); try { String destinationClassName = destinationType.getClassType(); Class<?> destinationClass = Object.class; if (destinationClassName != null) destinationClass = Class.forName(destinationClassName); if (content instanceof byte[]) { return objectMapper.readValue((byte[]) content, destinationClass); } return objectMapper.readValue((String) content, destinationClass); } catch (IOException | ClassNotFoundException e) { throw new CacheException(e); } } if (destinationType.match(TEXT_PLAIN)) { return convertCharset(content, contentCharset, destinationCharset, outputString); } throw logger.unsupportedContent(JsonTranscoder.class.getSimpleName(), content); }
JsonTranscoder extends OneToManyTranscoder { @Override public Object transcode(Object content, MediaType contentType, MediaType destinationType) { if (destinationType.match(APPLICATION_OCTET_STREAM) || destinationType.match(APPLICATION_UNKNOWN)) { return StandardConversions.convertTextToOctetStream(content, contentType); } boolean outputString = destinationType.hasStringType(); Charset contentCharset = contentType.getCharset(); Charset destinationCharset = destinationType.getCharset(); if (destinationType.match(APPLICATION_JSON)) { if (contentType.match(APPLICATION_JSON)) { return convertCharset(content, contentCharset, destinationCharset, outputString); } try { if (content instanceof String || content instanceof byte[]) { return convertTextToJson(content, contentCharset, destinationCharset, outputString); } logger.jsonObjectConversionDeprecated(); if (outputString) { return objectMapper.writeValueAsString(content); } try (ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(out, destinationCharset)) { objectMapper.writeValue(osw, content); return out.toByteArray(); } } catch (IOException e) { throw logger.cannotConvertContent(content, contentType, destinationType); } } if (destinationType.match(APPLICATION_OBJECT)) { logger.jsonObjectConversionDeprecated(); try { String destinationClassName = destinationType.getClassType(); Class<?> destinationClass = Object.class; if (destinationClassName != null) destinationClass = Class.forName(destinationClassName); if (content instanceof byte[]) { return objectMapper.readValue((byte[]) content, destinationClass); } return objectMapper.readValue((String) content, destinationClass); } catch (IOException | ClassNotFoundException e) { throw new CacheException(e); } } if (destinationType.match(TEXT_PLAIN)) { return convertCharset(content, contentCharset, destinationCharset, outputString); } throw logger.unsupportedContent(JsonTranscoder.class.getSimpleName(), content); } }
JsonTranscoder extends OneToManyTranscoder { @Override public Object transcode(Object content, MediaType contentType, MediaType destinationType) { if (destinationType.match(APPLICATION_OCTET_STREAM) || destinationType.match(APPLICATION_UNKNOWN)) { return StandardConversions.convertTextToOctetStream(content, contentType); } boolean outputString = destinationType.hasStringType(); Charset contentCharset = contentType.getCharset(); Charset destinationCharset = destinationType.getCharset(); if (destinationType.match(APPLICATION_JSON)) { if (contentType.match(APPLICATION_JSON)) { return convertCharset(content, contentCharset, destinationCharset, outputString); } try { if (content instanceof String || content instanceof byte[]) { return convertTextToJson(content, contentCharset, destinationCharset, outputString); } logger.jsonObjectConversionDeprecated(); if (outputString) { return objectMapper.writeValueAsString(content); } try (ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(out, destinationCharset)) { objectMapper.writeValue(osw, content); return out.toByteArray(); } } catch (IOException e) { throw logger.cannotConvertContent(content, contentType, destinationType); } } if (destinationType.match(APPLICATION_OBJECT)) { logger.jsonObjectConversionDeprecated(); try { String destinationClassName = destinationType.getClassType(); Class<?> destinationClass = Object.class; if (destinationClassName != null) destinationClass = Class.forName(destinationClassName); if (content instanceof byte[]) { return objectMapper.readValue((byte[]) content, destinationClass); } return objectMapper.readValue((String) content, destinationClass); } catch (IOException | ClassNotFoundException e) { throw new CacheException(e); } } if (destinationType.match(TEXT_PLAIN)) { return convertCharset(content, contentCharset, destinationCharset, outputString); } throw logger.unsupportedContent(JsonTranscoder.class.getSimpleName(), content); } JsonTranscoder(); JsonTranscoder(ClassAllowList allowList); JsonTranscoder(ClassLoader classLoader, ClassAllowList allowList); }
JsonTranscoder extends OneToManyTranscoder { @Override public Object transcode(Object content, MediaType contentType, MediaType destinationType) { if (destinationType.match(APPLICATION_OCTET_STREAM) || destinationType.match(APPLICATION_UNKNOWN)) { return StandardConversions.convertTextToOctetStream(content, contentType); } boolean outputString = destinationType.hasStringType(); Charset contentCharset = contentType.getCharset(); Charset destinationCharset = destinationType.getCharset(); if (destinationType.match(APPLICATION_JSON)) { if (contentType.match(APPLICATION_JSON)) { return convertCharset(content, contentCharset, destinationCharset, outputString); } try { if (content instanceof String || content instanceof byte[]) { return convertTextToJson(content, contentCharset, destinationCharset, outputString); } logger.jsonObjectConversionDeprecated(); if (outputString) { return objectMapper.writeValueAsString(content); } try (ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(out, destinationCharset)) { objectMapper.writeValue(osw, content); return out.toByteArray(); } } catch (IOException e) { throw logger.cannotConvertContent(content, contentType, destinationType); } } if (destinationType.match(APPLICATION_OBJECT)) { logger.jsonObjectConversionDeprecated(); try { String destinationClassName = destinationType.getClassType(); Class<?> destinationClass = Object.class; if (destinationClassName != null) destinationClass = Class.forName(destinationClassName); if (content instanceof byte[]) { return objectMapper.readValue((byte[]) content, destinationClass); } return objectMapper.readValue((String) content, destinationClass); } catch (IOException | ClassNotFoundException e) { throw new CacheException(e); } } if (destinationType.match(TEXT_PLAIN)) { return convertCharset(content, contentCharset, destinationCharset, outputString); } throw logger.unsupportedContent(JsonTranscoder.class.getSimpleName(), content); } JsonTranscoder(); JsonTranscoder(ClassAllowList allowList); JsonTranscoder(ClassLoader classLoader, ClassAllowList allowList); @Override Object transcode(Object content, MediaType contentType, MediaType destinationType); }
JsonTranscoder extends OneToManyTranscoder { @Override public Object transcode(Object content, MediaType contentType, MediaType destinationType) { if (destinationType.match(APPLICATION_OCTET_STREAM) || destinationType.match(APPLICATION_UNKNOWN)) { return StandardConversions.convertTextToOctetStream(content, contentType); } boolean outputString = destinationType.hasStringType(); Charset contentCharset = contentType.getCharset(); Charset destinationCharset = destinationType.getCharset(); if (destinationType.match(APPLICATION_JSON)) { if (contentType.match(APPLICATION_JSON)) { return convertCharset(content, contentCharset, destinationCharset, outputString); } try { if (content instanceof String || content instanceof byte[]) { return convertTextToJson(content, contentCharset, destinationCharset, outputString); } logger.jsonObjectConversionDeprecated(); if (outputString) { return objectMapper.writeValueAsString(content); } try (ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(out, destinationCharset)) { objectMapper.writeValue(osw, content); return out.toByteArray(); } } catch (IOException e) { throw logger.cannotConvertContent(content, contentType, destinationType); } } if (destinationType.match(APPLICATION_OBJECT)) { logger.jsonObjectConversionDeprecated(); try { String destinationClassName = destinationType.getClassType(); Class<?> destinationClass = Object.class; if (destinationClassName != null) destinationClass = Class.forName(destinationClassName); if (content instanceof byte[]) { return objectMapper.readValue((byte[]) content, destinationClass); } return objectMapper.readValue((String) content, destinationClass); } catch (IOException | ClassNotFoundException e) { throw new CacheException(e); } } if (destinationType.match(TEXT_PLAIN)) { return convertCharset(content, contentCharset, destinationCharset, outputString); } throw logger.unsupportedContent(JsonTranscoder.class.getSimpleName(), content); } JsonTranscoder(); JsonTranscoder(ClassAllowList allowList); JsonTranscoder(ClassLoader classLoader, ClassAllowList allowList); @Override Object transcode(Object content, MediaType contentType, MediaType destinationType); static final String TYPE_PROPERTY; }
@Test public void testUrlWithCredentials() { RestConnector connector = new RestConnector(); RestConnection connection = (RestConnection) connector.getConnection("http: RestClientConfigurationBuilder builder = connection.getBuilder(); RestClientConfiguration configuration = builder.build(); assertEquals(11222, configuration.servers().get(0).port()); assertEquals("localhost", configuration.servers().get(0).host()); assertTrue(configuration.security().authentication().enabled()); assertEquals("user", configuration.security().authentication().username()); assertArrayEquals("password".toCharArray(), configuration.security().authentication().password()); }
@Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } @Override Connection getConnection(String connectionString, SSLContextSettings sslContextSettings); }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } @Override Connection getConnection(String connectionString, SSLContextSettings sslContextSettings); }
@Test public void testUrlWithoutCredentials() { RestConnector connector = new RestConnector(); RestConnection connection = (RestConnection) connector.getConnection("http: RestClientConfigurationBuilder builder = connection.getBuilder(); RestClientConfiguration configuration = builder.build(); assertEquals(11222, configuration.servers().get(0).port()); assertEquals("localhost", configuration.servers().get(0).host()); assertFalse(configuration.security().authentication().enabled()); }
@Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } @Override Connection getConnection(String connectionString, SSLContextSettings sslContextSettings); }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } @Override Connection getConnection(String connectionString, SSLContextSettings sslContextSettings); }
@Test public void testUrlWithoutPort() { RestConnector connector = new RestConnector(); RestConnection connection = (RestConnection) connector.getConnection("http: RestClientConfigurationBuilder builder = connection.getBuilder(); RestClientConfiguration configuration = builder.build(); assertEquals(80, configuration.servers().get(0).port()); assertEquals("localhost", configuration.servers().get(0).host()); assertFalse(configuration.security().authentication().enabled()); }
@Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } @Override Connection getConnection(String connectionString, SSLContextSettings sslContextSettings); }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } @Override Connection getConnection(String connectionString, SSLContextSettings sslContextSettings); }
@Test public void testUrlWithSSL() throws NoSuchAlgorithmException { RestConnector connector = new RestConnector(); RestConnection connection = (RestConnection) connector.getConnection("https: RestClientConfigurationBuilder builder = connection.getBuilder(); builder.security().ssl().sslContext(SSLContext.getDefault()).trustManagers(new TrustManager[]{new ZeroSecurityTrustManager()}); RestClientConfiguration configuration = builder.build(); assertEquals(443, configuration.servers().get(0).port()); assertEquals("localhost", configuration.servers().get(0).host()); assertFalse(configuration.security().authentication().enabled()); assertTrue(configuration.security().ssl().enabled()); }
@Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } @Override Connection getConnection(String connectionString, SSLContextSettings sslContextSettings); }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } @Override Connection getConnection(String connectionString, SSLContextSettings sslContextSettings); }
@Test public void testEmptyUrl() { RestConnector connector = new RestConnector(); RestConnection connection = (RestConnection) connector.getConnection("", null); RestClientConfigurationBuilder builder = connection.getBuilder(); RestClientConfiguration configuration = builder.build(); assertEquals(11222, configuration.servers().get(0).port()); assertEquals("localhost", configuration.servers().get(0).host()); }
@Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } @Override Connection getConnection(String connectionString, SSLContextSettings sslContextSettings); }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } @Override Connection getConnection(String connectionString, SSLContextSettings sslContextSettings); }
@Test public void testPlainHostPort() { RestConnector connector = new RestConnector(); RestConnection connection = (RestConnection) connector.getConnection("my.host.com:12345", null); RestClientConfigurationBuilder builder = connection.getBuilder(); RestClientConfiguration configuration = builder.build(); assertEquals(12345, configuration.servers().get(0).port()); assertEquals("my.host.com", configuration.servers().get(0).host()); }
@Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } @Override Connection getConnection(String connectionString, SSLContextSettings sslContextSettings); }
RestConnector implements Connector { @Override public Connection getConnection(String connectionString, SSLContextSettings sslContextSettings) { try { RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder(); if (connectionString == null || connectionString.isEmpty() || "-".equals(connectionString)) { builder.addServer().host("localhost").port(11222); } else { Matcher matcher = HOST_PORT.matcher(connectionString); if (matcher.matches()) { String host = matcher.group(1); String port = matcher.group(2); builder.addServer().host(host).port(port != null ? Integer.parseInt(port) : 11222); } else { URL url = new URL(connectionString); if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { throw new IllegalArgumentException(); } int port = url.getPort(); builder.addServer().host(url.getHost()).port(port > 0 ? port : url.getDefaultPort()); String userInfo = url.getUserInfo(); if (userInfo != null) { String[] split = userInfo.split(":"); builder.security().authentication().username(split[0]).password(split[1]); } if (url.getProtocol().equals("https")) { SslConfigurationBuilder ssl = builder.security().ssl().enable(); if (sslContextSettings != null) { ssl.sslContext(sslContextSettings.getSslContext()) .trustManagers(sslContextSettings.getTrustManagers()) .hostnameVerifier(sslContextSettings.getHostnameVerifier()); } } } } return new RestConnection(builder); } catch (Exception e) { return null; } } @Override Connection getConnection(String connectionString, SSLContextSettings sslContextSettings); }
@Test public final void getNativeCacheShouldReturnTheEmbeddedCacheManagerSuppliedAtConstructionTime() { withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager()) { @Override public void call() { final SpringEmbeddedCacheManager objectUnderTest = new SpringEmbeddedCacheManager(cm); final EmbeddedCacheManager nativeCacheManagerReturned = objectUnderTest.getNativeCacheManager(); assertSame( "getNativeCacheManager() should have returned the EmbeddedCacheManager supplied at construction time. However, it retuned a different one.", cm, nativeCacheManagerReturned); } }); }
public EmbeddedCacheManager getNativeCacheManager() { return this.nativeCacheManager; }
SpringEmbeddedCacheManager implements CacheManager { public EmbeddedCacheManager getNativeCacheManager() { return this.nativeCacheManager; } }
SpringEmbeddedCacheManager implements CacheManager { public EmbeddedCacheManager getNativeCacheManager() { return this.nativeCacheManager; } SpringEmbeddedCacheManager(final EmbeddedCacheManager nativeCacheManager); }
SpringEmbeddedCacheManager implements CacheManager { public EmbeddedCacheManager getNativeCacheManager() { return this.nativeCacheManager; } SpringEmbeddedCacheManager(final EmbeddedCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); EmbeddedCacheManager getNativeCacheManager(); void stop(); }
SpringEmbeddedCacheManager implements CacheManager { public EmbeddedCacheManager getNativeCacheManager() { return this.nativeCacheManager; } SpringEmbeddedCacheManager(final EmbeddedCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); EmbeddedCacheManager getNativeCacheManager(); void stop(); }
@Test public final void getCacheShouldReturnSameInstanceForSameName() { withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager()) { @Override public void call() { cm.defineConfiguration("same", new ConfigurationBuilder().build()); final SpringEmbeddedCacheManager objectUnderTest = new SpringEmbeddedCacheManager(cm); final String sameCacheName = "same"; final SpringCache firstObtainedSpringCache = objectUnderTest.getCache(sameCacheName); final SpringCache secondObtainedSpringCache = objectUnderTest.getCache(sameCacheName); assertSame( "getCache() should have returned the same SpringCache instance for the same name", firstObtainedSpringCache, secondObtainedSpringCache); } }); }
@Override public SpringCache getCache(final String name) { return springCaches.computeIfAbsent(name, n -> { final Cache<Object, Object> nativeCache = this.nativeCacheManager.getCache(n); return new SpringCache(nativeCache); }); }
SpringEmbeddedCacheManager implements CacheManager { @Override public SpringCache getCache(final String name) { return springCaches.computeIfAbsent(name, n -> { final Cache<Object, Object> nativeCache = this.nativeCacheManager.getCache(n); return new SpringCache(nativeCache); }); } }
SpringEmbeddedCacheManager implements CacheManager { @Override public SpringCache getCache(final String name) { return springCaches.computeIfAbsent(name, n -> { final Cache<Object, Object> nativeCache = this.nativeCacheManager.getCache(n); return new SpringCache(nativeCache); }); } SpringEmbeddedCacheManager(final EmbeddedCacheManager nativeCacheManager); }
SpringEmbeddedCacheManager implements CacheManager { @Override public SpringCache getCache(final String name) { return springCaches.computeIfAbsent(name, n -> { final Cache<Object, Object> nativeCache = this.nativeCacheManager.getCache(n); return new SpringCache(nativeCache); }); } SpringEmbeddedCacheManager(final EmbeddedCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); EmbeddedCacheManager getNativeCacheManager(); void stop(); }
SpringEmbeddedCacheManager implements CacheManager { @Override public SpringCache getCache(final String name) { return springCaches.computeIfAbsent(name, n -> { final Cache<Object, Object> nativeCache = this.nativeCacheManager.getCache(n); return new SpringCache(nativeCache); }); } SpringEmbeddedCacheManager(final EmbeddedCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); EmbeddedCacheManager getNativeCacheManager(); void stop(); }
@Test public final void getCacheShouldReturnDifferentInstancesForDifferentNames() { withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager()) { @Override public void call() { cm.defineConfiguration("thisCache", new ConfigurationBuilder().build()); cm.defineConfiguration("thatCache", new ConfigurationBuilder().build()); final SpringEmbeddedCacheManager objectUnderTest = new SpringEmbeddedCacheManager(cm); final String firstCacheName = "thisCache"; final String secondCacheName = "thatCache"; final SpringCache firstObtainedSpringCache = objectUnderTest.getCache(firstCacheName); final SpringCache secondObtainedSpringCache = objectUnderTest.getCache(secondCacheName); assertNotSame( "getCache() should have returned different SpringCache instances for different names", firstObtainedSpringCache, secondObtainedSpringCache); } }); }
@Override public SpringCache getCache(final String name) { return springCaches.computeIfAbsent(name, n -> { final Cache<Object, Object> nativeCache = this.nativeCacheManager.getCache(n); return new SpringCache(nativeCache); }); }
SpringEmbeddedCacheManager implements CacheManager { @Override public SpringCache getCache(final String name) { return springCaches.computeIfAbsent(name, n -> { final Cache<Object, Object> nativeCache = this.nativeCacheManager.getCache(n); return new SpringCache(nativeCache); }); } }
SpringEmbeddedCacheManager implements CacheManager { @Override public SpringCache getCache(final String name) { return springCaches.computeIfAbsent(name, n -> { final Cache<Object, Object> nativeCache = this.nativeCacheManager.getCache(n); return new SpringCache(nativeCache); }); } SpringEmbeddedCacheManager(final EmbeddedCacheManager nativeCacheManager); }
SpringEmbeddedCacheManager implements CacheManager { @Override public SpringCache getCache(final String name) { return springCaches.computeIfAbsent(name, n -> { final Cache<Object, Object> nativeCache = this.nativeCacheManager.getCache(n); return new SpringCache(nativeCache); }); } SpringEmbeddedCacheManager(final EmbeddedCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); EmbeddedCacheManager getNativeCacheManager(); void stop(); }
SpringEmbeddedCacheManager implements CacheManager { @Override public SpringCache getCache(final String name) { return springCaches.computeIfAbsent(name, n -> { final Cache<Object, Object> nativeCache = this.nativeCacheManager.getCache(n); return new SpringCache(nativeCache); }); } SpringEmbeddedCacheManager(final EmbeddedCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); EmbeddedCacheManager getNativeCacheManager(); void stop(); }
@Test public void contains1() throws Exception { RangeSet rs = new RangeSet(4); assertFalse(rs.contains(Integer.valueOf(5))); assertTrue(rs.contains(Integer.valueOf(1))); }
@Override public boolean contains(Object o) { if (!(o instanceof Integer)) return false; int i = (int) o; return contains(i); }
RangeSet implements IntSet { @Override public boolean contains(Object o) { if (!(o instanceof Integer)) return false; int i = (int) o; return contains(i); } }
RangeSet implements IntSet { @Override public boolean contains(Object o) { if (!(o instanceof Integer)) return false; int i = (int) o; return contains(i); } RangeSet(int size); }
RangeSet implements IntSet { @Override public boolean contains(Object o) { if (!(o instanceof Integer)) return false; int i = (int) o; return contains(i); } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
RangeSet implements IntSet { @Override public boolean contains(Object o) { if (!(o instanceof Integer)) return false; int i = (int) o; return contains(i); } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
@Test public void testIfSpringEmbeddedCacheManagerFactoryBeanCreatesACacheManagerEvenIfNoDefaultConfigurationLocationHasBeenSet() throws Exception { objectUnderTest = SpringEmbeddedCacheManagerFactoryBeanBuilder .defaultBuilder().build(); final SpringEmbeddedCacheManager springEmbeddedCacheManager = objectUnderTest.getObject(); assertNotNull( "getObject() should have returned a valid SpringEmbeddedCacheManager, even if no defaulConfigurationLocation " + "has been specified. However, it returned null.", springEmbeddedCacheManager); }
@Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } @Override void afterPropertiesSet(); @Override SpringEmbeddedCacheManager getObject(); @Override Class<? extends SpringEmbeddedCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } @Override void afterPropertiesSet(); @Override SpringEmbeddedCacheManager getObject(); @Override Class<? extends SpringEmbeddedCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
@Test public void testIfSpringEmbeddedCacheManagerFactoryBeanCreatesACustomizedCacheManagerIfGivenADefaultConfigurationLocation() throws Exception { objectUnderTest = SpringEmbeddedCacheManagerFactoryBeanBuilder .defaultBuilder().fromFile(NAMED_ASYNC_CACHE_CONFIG_LOCATION, getClass()).build(); final SpringEmbeddedCacheManager springEmbeddedCacheManager = objectUnderTest.getObject(); assertNotNull( "getObject() should have returned a valid SpringEmbeddedCacheManager, configured using the configuration file " + "set on SpringEmbeddedCacheManagerFactoryBean. However, it returned null.", springEmbeddedCacheManager); final SpringCache cacheDefinedInCustomConfiguration = springEmbeddedCacheManager .getCache(CACHE_NAME_FROM_CONFIGURATION_FILE); final org.infinispan.configuration.cache.Configuration configuration = ((Cache) cacheDefinedInCustomConfiguration.getNativeCache()) .getCacheConfiguration(); assertEquals( "The cache named [" + CACHE_NAME_FROM_CONFIGURATION_FILE + "] is configured to have asynchonous replication cache mode. Yet, the cache returned from getCache(" + CACHE_NAME_FROM_CONFIGURATION_FILE + ") has a different cache mode. Obviously, SpringEmbeddedCacheManagerFactoryBean did not use " + "the configuration file when instantiating SpringEmbeddedCacheManager.", org.infinispan.configuration.cache.CacheMode.REPL_ASYNC, configuration.clustering().cacheMode()); }
@Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } @Override void afterPropertiesSet(); @Override SpringEmbeddedCacheManager getObject(); @Override Class<? extends SpringEmbeddedCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } @Override void afterPropertiesSet(); @Override SpringEmbeddedCacheManager getObject(); @Override Class<? extends SpringEmbeddedCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
@Test public void testIfSpringEmbeddedCacheManagerFactoryBeanDeclaresItselfToOnlyProduceSingletons() { objectUnderTest = new SpringEmbeddedCacheManagerFactoryBean(); assertTrue("isSingleton() should always return true. However, it returned false", objectUnderTest.isSingleton()); }
@Override public boolean isSingleton() { return true; }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } @Override void afterPropertiesSet(); @Override SpringEmbeddedCacheManager getObject(); @Override Class<? extends SpringEmbeddedCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } @Override void afterPropertiesSet(); @Override SpringEmbeddedCacheManager getObject(); @Override Class<? extends SpringEmbeddedCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
@Test public void testIfSpringEmbeddedCacheManagerFactoryBeanAllowesOverridingGlobalConfiguration() throws Exception { GlobalConfigurationBuilder overriddenConfiguration = new GlobalConfigurationBuilder(); overriddenConfiguration.transport().rackId("r2"); objectUnderTest = SpringEmbeddedCacheManagerFactoryBeanBuilder .defaultBuilder().fromFile(NAMED_ASYNC_CACHE_CONFIG_LOCATION, getClass()) .withGlobalConfiguration(overriddenConfiguration).build(); final SpringEmbeddedCacheManager springEmbeddedCacheManager = objectUnderTest.getObject(); assertEquals( "Transport for cache configured in" + CACHE_NAME_FROM_CONFIGURATION_FILE + "is assigned to r1 rack. But later Global Configuration overrides " + "this setting to r2. Obviously created SpringEmbeddedCacheManagerFactoryBean does not support this kind " + "of overriding.", "r2", springEmbeddedCacheManager.getNativeCacheManager().getCacheManagerConfiguration().transport().rackId()); }
@Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } @Override void afterPropertiesSet(); @Override SpringEmbeddedCacheManager getObject(); @Override Class<? extends SpringEmbeddedCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } @Override void afterPropertiesSet(); @Override SpringEmbeddedCacheManager getObject(); @Override Class<? extends SpringEmbeddedCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
@Test public void testIfSpringEmbeddedCacheManagerFactoryBeanAllowesOverridingConfigurationBuilder() throws Exception { ConfigurationBuilder overriddenBuilder = new ConfigurationBuilder(); overriddenBuilder.locking().concurrencyLevel(100); objectUnderTest = SpringEmbeddedCacheManagerFactoryBeanBuilder .defaultBuilder().fromFile(NAMED_ASYNC_CACHE_CONFIG_LOCATION, getClass()) .withConfigurationBuilder(overriddenBuilder).build(); final SpringEmbeddedCacheManager springEmbeddedCacheManager = objectUnderTest.getObject(); assertEquals( "Concurrency value of LockingLocking for cache configured in" + CACHE_NAME_FROM_CONFIGURATION_FILE + "is equal to 5000. But later Configuration Builder overrides " + "this setting to 100. Obviously created SpringEmbeddedCacheManagerFactoryBean does not support " + "this kind of overriding.", 100, springEmbeddedCacheManager.getNativeCacheManager().getDefaultCacheConfiguration().locking() .concurrencyLevel()); }
@Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } @Override void afterPropertiesSet(); @Override SpringEmbeddedCacheManager getObject(); @Override Class<? extends SpringEmbeddedCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
SpringEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<SpringEmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public SpringEmbeddedCacheManager getObject() throws Exception { return this.cacheManager; } @Override void afterPropertiesSet(); @Override SpringEmbeddedCacheManager getObject(); @Override Class<? extends SpringEmbeddedCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
@Test public final void infinispanNamedEmbeddedCacheFactoryBeanShouldDeclareItselfToBeSingleton() { final InfinispanNamedEmbeddedCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanNamedEmbeddedCacheFactoryBean<Object, Object>(); assertTrue( "InfinispanNamedEmbeddedCacheFactoryBean should declare itself to produce a singleton. However, it didn't.", objectUnderTest.isSingleton()); }
@Override public boolean isSingleton() { return true; }
InfinispanNamedEmbeddedCacheFactoryBean implements FactoryBean<Cache<K, V>>, BeanNameAware, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } }
InfinispanNamedEmbeddedCacheFactoryBean implements FactoryBean<Cache<K, V>>, BeanNameAware, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } }
InfinispanNamedEmbeddedCacheFactoryBean implements FactoryBean<Cache<K, V>>, BeanNameAware, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } @Override void afterPropertiesSet(); @Override Cache<K, V> getObject(); @Override Class<? extends Cache> getObjectType(); @Override boolean isSingleton(); @Override void setBeanName(final String name); @Override void destroy(); void setCacheName(final String cacheName); void setInfinispanEmbeddedCacheManager( final EmbeddedCacheManager infinispanEmbeddedCacheManager); void setConfigurationTemplateMode(final String configurationTemplateMode); void addCustomConfiguration(final ConfigurationBuilder builder); }
InfinispanNamedEmbeddedCacheFactoryBean implements FactoryBean<Cache<K, V>>, BeanNameAware, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } @Override void afterPropertiesSet(); @Override Cache<K, V> getObject(); @Override Class<? extends Cache> getObjectType(); @Override boolean isSingleton(); @Override void setBeanName(final String name); @Override void destroy(); void setCacheName(final String cacheName); void setInfinispanEmbeddedCacheManager( final EmbeddedCacheManager infinispanEmbeddedCacheManager); void setConfigurationTemplateMode(final String configurationTemplateMode); void addCustomConfiguration(final ConfigurationBuilder builder); }
@Test public final void infinispanEmbeddedCacheManagerFactoryBeanShouldDeclareItselfToOnlyProduceSingletons() { final InfinispanEmbeddedCacheManagerFactoryBean objectUnderTest = new InfinispanEmbeddedCacheManagerFactoryBean(); assertTrue("isSingleton() should always return true. However, it returned false", objectUnderTest.isSingleton()); }
@Override public boolean isSingleton() { return true; }
InfinispanEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<EmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } }
InfinispanEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<EmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } }
InfinispanEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<EmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } @Override void afterPropertiesSet(); @Override EmbeddedCacheManager getObject(); @Override Class<? extends EmbeddedCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
InfinispanEmbeddedCacheManagerFactoryBean extends AbstractEmbeddedCacheManagerFactory implements FactoryBean<EmbeddedCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } @Override void afterPropertiesSet(); @Override EmbeddedCacheManager getObject(); @Override Class<? extends EmbeddedCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
@Test(expectedExceptions = IllegalStateException.class) public final void shouldThrowAnIllegalStateExceptionIfBothConfigurationPropertiesAndConfifurationPropertiesFileLocationAreSet() throws Exception { objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setConfigurationProperties(new Properties()); objectUnderTest.setConfigurationPropertiesFileLocation(new ClassPathResource("dummy", getClass())); objectUnderTest.afterPropertiesSet(); }
@Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); long readTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)) readTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)); else readTimeout = 0; long writeTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)) writeTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)); else writeTimeout = 0; final RemoteCacheManager nativeRemoteCacheManager = new RemoteCacheManager( clientBuilder.build(), this.startAutomatically); this.springRemoteCacheManager = new SpringRemoteCacheManager(nativeRemoteCacheManager, readTimeout, writeTimeout); this.logger.info("Finished creating new instance of RemoteCacheManager"); }
SpringRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<SpringRemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); long readTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)) readTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)); else readTimeout = 0; long writeTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)) writeTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)); else writeTimeout = 0; final RemoteCacheManager nativeRemoteCacheManager = new RemoteCacheManager( clientBuilder.build(), this.startAutomatically); this.springRemoteCacheManager = new SpringRemoteCacheManager(nativeRemoteCacheManager, readTimeout, writeTimeout); this.logger.info("Finished creating new instance of RemoteCacheManager"); } }
SpringRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<SpringRemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); long readTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)) readTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)); else readTimeout = 0; long writeTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)) writeTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)); else writeTimeout = 0; final RemoteCacheManager nativeRemoteCacheManager = new RemoteCacheManager( clientBuilder.build(), this.startAutomatically); this.springRemoteCacheManager = new SpringRemoteCacheManager(nativeRemoteCacheManager, readTimeout, writeTimeout); this.logger.info("Finished creating new instance of RemoteCacheManager"); } }
SpringRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<SpringRemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); long readTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)) readTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)); else readTimeout = 0; long writeTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)) writeTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)); else writeTimeout = 0; final RemoteCacheManager nativeRemoteCacheManager = new RemoteCacheManager( clientBuilder.build(), this.startAutomatically); this.springRemoteCacheManager = new SpringRemoteCacheManager(nativeRemoteCacheManager, readTimeout, writeTimeout); this.logger.info("Finished creating new instance of RemoteCacheManager"); } @Override void afterPropertiesSet(); @Override SpringRemoteCacheManager getObject(); @Override Class<? extends SpringRemoteCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
SpringRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<SpringRemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); long readTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)) readTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)); else readTimeout = 0; long writeTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)) writeTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)); else writeTimeout = 0; final RemoteCacheManager nativeRemoteCacheManager = new RemoteCacheManager( clientBuilder.build(), this.startAutomatically); this.springRemoteCacheManager = new SpringRemoteCacheManager(nativeRemoteCacheManager, readTimeout, writeTimeout); this.logger.info("Finished creating new instance of RemoteCacheManager"); } @Override void afterPropertiesSet(); @Override SpringRemoteCacheManager getObject(); @Override Class<? extends SpringRemoteCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
@Test(expectedExceptions = IllegalStateException.class) public final void shouldThrowAnIllegalStateExceptionIfConfigurationPropertiesAsWellAsSettersAreUsedToConfigureTheRemoteCacheManager() throws Exception { objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setConfigurationProperties(new Properties()); objectUnderTest.setMarshaller("test.Marshaller"); objectUnderTest.afterPropertiesSet(); }
@Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); long readTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)) readTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)); else readTimeout = 0; long writeTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)) writeTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)); else writeTimeout = 0; final RemoteCacheManager nativeRemoteCacheManager = new RemoteCacheManager( clientBuilder.build(), this.startAutomatically); this.springRemoteCacheManager = new SpringRemoteCacheManager(nativeRemoteCacheManager, readTimeout, writeTimeout); this.logger.info("Finished creating new instance of RemoteCacheManager"); }
SpringRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<SpringRemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); long readTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)) readTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)); else readTimeout = 0; long writeTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)) writeTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)); else writeTimeout = 0; final RemoteCacheManager nativeRemoteCacheManager = new RemoteCacheManager( clientBuilder.build(), this.startAutomatically); this.springRemoteCacheManager = new SpringRemoteCacheManager(nativeRemoteCacheManager, readTimeout, writeTimeout); this.logger.info("Finished creating new instance of RemoteCacheManager"); } }
SpringRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<SpringRemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); long readTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)) readTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)); else readTimeout = 0; long writeTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)) writeTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)); else writeTimeout = 0; final RemoteCacheManager nativeRemoteCacheManager = new RemoteCacheManager( clientBuilder.build(), this.startAutomatically); this.springRemoteCacheManager = new SpringRemoteCacheManager(nativeRemoteCacheManager, readTimeout, writeTimeout); this.logger.info("Finished creating new instance of RemoteCacheManager"); } }
SpringRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<SpringRemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); long readTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)) readTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)); else readTimeout = 0; long writeTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)) writeTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)); else writeTimeout = 0; final RemoteCacheManager nativeRemoteCacheManager = new RemoteCacheManager( clientBuilder.build(), this.startAutomatically); this.springRemoteCacheManager = new SpringRemoteCacheManager(nativeRemoteCacheManager, readTimeout, writeTimeout); this.logger.info("Finished creating new instance of RemoteCacheManager"); } @Override void afterPropertiesSet(); @Override SpringRemoteCacheManager getObject(); @Override Class<? extends SpringRemoteCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
SpringRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<SpringRemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); long readTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)) readTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)); else readTimeout = 0; long writeTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)) writeTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)); else writeTimeout = 0; final RemoteCacheManager nativeRemoteCacheManager = new RemoteCacheManager( clientBuilder.build(), this.startAutomatically); this.springRemoteCacheManager = new SpringRemoteCacheManager(nativeRemoteCacheManager, readTimeout, writeTimeout); this.logger.info("Finished creating new instance of RemoteCacheManager"); } @Override void afterPropertiesSet(); @Override SpringRemoteCacheManager getObject(); @Override Class<? extends SpringRemoteCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
@Test public final void isSingletonShouldAlwaysReturnTrue() { objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); assertTrue( "isSingleton() should always return true since each SpringRemoteCacheManagerFactoryBean will always produce " + "the same SpringRemoteCacheManager instance. However,it returned false.", objectUnderTest.isSingleton()); }
@Override public boolean isSingleton() { return true; }
SpringRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<SpringRemoteCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } }
SpringRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<SpringRemoteCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } }
SpringRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<SpringRemoteCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } @Override void afterPropertiesSet(); @Override SpringRemoteCacheManager getObject(); @Override Class<? extends SpringRemoteCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
SpringRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<SpringRemoteCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } @Override void afterPropertiesSet(); @Override SpringRemoteCacheManager getObject(); @Override Class<? extends SpringRemoteCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
@Test public void iterator() throws Exception { RangeSet rs = new RangeSet(4); PrimitiveIterator.OfInt iterator = rs.iterator(); assertEquals(0, iterator.nextInt()); assertEquals(1, iterator.nextInt()); assertEquals(2, iterator.nextInt()); assertEquals(3, iterator.nextInt()); }
@Override public PrimitiveIterator.OfInt iterator() { return new RangeSetIterator(size); }
RangeSet implements IntSet { @Override public PrimitiveIterator.OfInt iterator() { return new RangeSetIterator(size); } }
RangeSet implements IntSet { @Override public PrimitiveIterator.OfInt iterator() { return new RangeSetIterator(size); } RangeSet(int size); }
RangeSet implements IntSet { @Override public PrimitiveIterator.OfInt iterator() { return new RangeSetIterator(size); } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
RangeSet implements IntSet { @Override public PrimitiveIterator.OfInt iterator() { return new RangeSetIterator(size); } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
@Test public final void springRemoteCacheManagerShouldProperlyCreateCache() { final Cache defaultCache = objectUnderTest.getCache(TEST_CACHE_NAME); assertNotNull("getCache(" + TEST_CACHE_NAME + ") should have returned a default cache. However, it returned null.", defaultCache); assertEquals("getCache(" + TEST_CACHE_NAME + ") should have returned a cache name \"" + TEST_CACHE_NAME + "\". However, the returned cache has a different name.", TEST_CACHE_NAME, defaultCache.getName()); }
@Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
@Test public final void getCacheNamesShouldReturnAllCachesDefinedInConfigurationFile() { final Collection<String> cacheNames = objectUnderTest.getCacheNames(); assertTrue("SpringRemoteCacheManager should load all named caches found in the " + "native cache manager. However, it does not know about the cache named " + TEST_CACHE_NAME + " defined in said cache manager.", cacheNames.contains(TEST_CACHE_NAME)); }
@Override public Collection<String> getCacheNames() { return this.nativeCacheManager.getCacheNames(); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public Collection<String> getCacheNames() { return this.nativeCacheManager.getCacheNames(); } }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public Collection<String> getCacheNames() { return this.nativeCacheManager.getCacheNames(); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public Collection<String> getCacheNames() { return this.nativeCacheManager.getCacheNames(); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public Collection<String> getCacheNames() { return this.nativeCacheManager.getCacheNames(); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
@Test public final void startShouldStartTheNativeRemoteCacheManager() throws IOException { objectUnderTest.start(); assertTrue("Calling start() on SpringRemoteCacheManager should start the enclosed " + "Infinispan RemoteCacheManager. However, it is still not running.", remoteCacheManager.isStarted()); }
public void start() { this.nativeCacheManager.start(); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { public void start() { this.nativeCacheManager.start(); } }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { public void start() { this.nativeCacheManager.start(); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { public void start() { this.nativeCacheManager.start(); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { public void start() { this.nativeCacheManager.start(); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
@Test public final void stopShouldStopTheNativeRemoteCacheManager() throws IOException { objectUnderTest.stop(); assertFalse("Calling stop() on SpringRemoteCacheManager should stop the enclosed " + "Infinispan RemoteCacheManager. However, it is still running.", remoteCacheManager.isStarted()); }
public void stop() { this.nativeCacheManager.stop(); this.springCaches.clear(); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { public void stop() { this.nativeCacheManager.stop(); this.springCaches.clear(); } }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { public void stop() { this.nativeCacheManager.stop(); this.springCaches.clear(); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { public void stop() { this.nativeCacheManager.stop(); this.springCaches.clear(); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { public void stop() { this.nativeCacheManager.stop(); this.springCaches.clear(); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
@Test public final void getNativeCacheShouldReturnTheRemoteCacheManagerSuppliedAtConstructionTime() { final RemoteCacheManager nativeCacheManagerReturned = objectUnderTest.getNativeCacheManager(); assertSame( "getNativeCacheManager() should have returned the RemoteCacheManager supplied at construction time. However, it retuned a different one.", remoteCacheManager, nativeCacheManagerReturned); }
public RemoteCacheManager getNativeCacheManager() { return this.nativeCacheManager; }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { public RemoteCacheManager getNativeCacheManager() { return this.nativeCacheManager; } }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { public RemoteCacheManager getNativeCacheManager() { return this.nativeCacheManager; } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { public RemoteCacheManager getNativeCacheManager() { return this.nativeCacheManager; } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { public RemoteCacheManager getNativeCacheManager() { return this.nativeCacheManager; } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
@Test public final void getCacheShouldReturnSameInstanceForSameName() { final SpringCache firstObtainedSpringCache = objectUnderTest.getCache(TEST_CACHE_NAME); final SpringCache secondObtainedSpringCache = objectUnderTest.getCache(TEST_CACHE_NAME); assertSame( "getCache() should have returned the same SpringCache instance for the same name", firstObtainedSpringCache, secondObtainedSpringCache); }
@Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
@Test public final void getCacheShouldReturnDifferentInstancesForDifferentNames() { final SpringCache firstObtainedSpringCache = objectUnderTest.getCache(TEST_CACHE_NAME); final SpringCache secondObtainedSpringCache = objectUnderTest.getCache(OTHER_TEST_CACHE_NAME); assertNotSame( "getCache() should have returned different SpringCache instances for different names", firstObtainedSpringCache, secondObtainedSpringCache); }
@Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
@Test public final void getCacheShouldReturnNullItWasChangedByRemoteCacheManager() { objectUnderTest.getCache(TEST_CACHE_NAME); remoteCacheManager.administration().removeCache(TEST_CACHE_NAME); assertNull(objectUnderTest.getCache(TEST_CACHE_NAME)); }
@Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
SpringRemoteCacheManager implements org.springframework.cache.CacheManager { @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout); SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager); @Override SpringCache getCache(final String name); @Override Collection<String> getCacheNames(); RemoteCacheManager getNativeCacheManager(); long getReadTimeout(); long getWriteTimeout(); void setReadTimeout(final long readTimeout); void setWriteTimeout(final long writeTimeout); void start(); void stop(); }
@Test public final void testIfIsEmptyRecognizesThatConfigurationPropertiesOverridesAreEmpty() { final ConfigurationPropertiesOverrides objectUnderTest = new ConfigurationPropertiesOverrides(); assertTrue( "isEmpty() should have noticed that the ConfigurationPropertiesOverrides instance is indeed empty. However, it didn't.", objectUnderTest.isEmpty()); }
public boolean isEmpty() { return this.overridingProperties.isEmpty(); }
ConfigurationPropertiesOverrides { public boolean isEmpty() { return this.overridingProperties.isEmpty(); } }
ConfigurationPropertiesOverrides { public boolean isEmpty() { return this.overridingProperties.isEmpty(); } }
ConfigurationPropertiesOverrides { public boolean isEmpty() { return this.overridingProperties.isEmpty(); } boolean isEmpty(); @Deprecated void setTransportFactory(final String TransportFactory); void setServerList(final Collection<InetSocketAddress> serverList); void setMarshaller(final String marshaller); void setClassAllowList(final String allowListRegex); void setAsyncExecutorFactory(final String asyncExecutorFactory); void setTcpNoDelay(final boolean tcpNoDelay); void setTcpKeepAlive(final boolean tcpKeepAlive); void setRequestBalancingStrategy(final String requestBalancingStrategy); @Deprecated void setKeySizeEstimate(final int keySizeEstimate); @Deprecated void setValueSizeEstimate(final int valueSizeEstimate); void setForceReturnValues(final boolean forceReturnValues); void setReadTimeout(long readTimeout); void setWriteTimeout(long writeTimeout); void setNearCacheMode(String mode); void setNearCacheMaxEntries(int maxEntries); void setNearCacheNamePattern(String pattern); Properties override(final Properties configurationPropertiesToOverride); }
ConfigurationPropertiesOverrides { public boolean isEmpty() { return this.overridingProperties.isEmpty(); } boolean isEmpty(); @Deprecated void setTransportFactory(final String TransportFactory); void setServerList(final Collection<InetSocketAddress> serverList); void setMarshaller(final String marshaller); void setClassAllowList(final String allowListRegex); void setAsyncExecutorFactory(final String asyncExecutorFactory); void setTcpNoDelay(final boolean tcpNoDelay); void setTcpKeepAlive(final boolean tcpKeepAlive); void setRequestBalancingStrategy(final String requestBalancingStrategy); @Deprecated void setKeySizeEstimate(final int keySizeEstimate); @Deprecated void setValueSizeEstimate(final int valueSizeEstimate); void setForceReturnValues(final boolean forceReturnValues); void setReadTimeout(long readTimeout); void setWriteTimeout(long writeTimeout); void setNearCacheMode(String mode); void setNearCacheMaxEntries(int maxEntries); void setNearCacheNamePattern(String pattern); Properties override(final Properties configurationPropertiesToOverride); static final String OPERATION_READ_TIMEOUT; static final String OPERATION_WRITE_TIMEOUT; }
@Test(expectedExceptions = IllegalStateException.class) public final void shouldThrowAnIllegalStateExceptionIfBothConfigurationPropertiesAndConfigurationPropertiesFileLocationAreSet() throws Exception { final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setConfigurationProperties(new Properties()); objectUnderTest.setConfigurationPropertiesFileLocation(new ClassPathResource("dummy", getClass())); objectUnderTest.afterPropertiesSet(); }
@Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); this.nativeRemoteCacheManager = new RemoteCacheManager(clientBuilder.build(), this.startAutomatically); this.logger.info("Finished creating new instance of RemoteCacheManager"); }
InfinispanRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<RemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); this.nativeRemoteCacheManager = new RemoteCacheManager(clientBuilder.build(), this.startAutomatically); this.logger.info("Finished creating new instance of RemoteCacheManager"); } }
InfinispanRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<RemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); this.nativeRemoteCacheManager = new RemoteCacheManager(clientBuilder.build(), this.startAutomatically); this.logger.info("Finished creating new instance of RemoteCacheManager"); } }
InfinispanRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<RemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); this.nativeRemoteCacheManager = new RemoteCacheManager(clientBuilder.build(), this.startAutomatically); this.logger.info("Finished creating new instance of RemoteCacheManager"); } @Override void afterPropertiesSet(); @Override RemoteCacheManager getObject(); @Override Class<? extends RemoteCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
InfinispanRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<RemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); this.nativeRemoteCacheManager = new RemoteCacheManager(clientBuilder.build(), this.startAutomatically); this.logger.info("Finished creating new instance of RemoteCacheManager"); } @Override void afterPropertiesSet(); @Override RemoteCacheManager getObject(); @Override Class<? extends RemoteCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
@Test public void toArray() throws Exception { RangeSet rs = new RangeSet(4); Object[] array = rs.toArray(); assertEquals(4, array.length); assertEquals(0, array[0]); assertEquals(1, array[1]); assertEquals(2, array[2]); assertEquals(3, array[3]); }
@Override public Object[] toArray() { Object[] array = new Object[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; }
RangeSet implements IntSet { @Override public Object[] toArray() { Object[] array = new Object[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; } }
RangeSet implements IntSet { @Override public Object[] toArray() { Object[] array = new Object[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; } RangeSet(int size); }
RangeSet implements IntSet { @Override public Object[] toArray() { Object[] array = new Object[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
RangeSet implements IntSet { @Override public Object[] toArray() { Object[] array = new Object[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
@Test(expectedExceptions = IllegalStateException.class) public final void shouldThrowAnIllegalStateExceptionIfConfigurationPropertiesAsWellAsSettersAreUsedToConfigureTheRemoteCacheManager() throws Exception { final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setConfigurationProperties(new Properties()); objectUnderTest.setMarshaller("test.Marshaller"); objectUnderTest.afterPropertiesSet(); }
@Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); this.nativeRemoteCacheManager = new RemoteCacheManager(clientBuilder.build(), this.startAutomatically); this.logger.info("Finished creating new instance of RemoteCacheManager"); }
InfinispanRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<RemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); this.nativeRemoteCacheManager = new RemoteCacheManager(clientBuilder.build(), this.startAutomatically); this.logger.info("Finished creating new instance of RemoteCacheManager"); } }
InfinispanRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<RemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); this.nativeRemoteCacheManager = new RemoteCacheManager(clientBuilder.build(), this.startAutomatically); this.logger.info("Finished creating new instance of RemoteCacheManager"); } }
InfinispanRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<RemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); this.nativeRemoteCacheManager = new RemoteCacheManager(clientBuilder.build(), this.startAutomatically); this.logger.info("Finished creating new instance of RemoteCacheManager"); } @Override void afterPropertiesSet(); @Override RemoteCacheManager getObject(); @Override Class<? extends RemoteCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
InfinispanRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<RemoteCacheManager>, InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); this.nativeRemoteCacheManager = new RemoteCacheManager(clientBuilder.build(), this.startAutomatically); this.logger.info("Finished creating new instance of RemoteCacheManager"); } @Override void afterPropertiesSet(); @Override RemoteCacheManager getObject(); @Override Class<? extends RemoteCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
@Test public final void isSingletonShouldAlwaysReturnTrue() { final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); assertTrue( "isSingleton() should always return true since each AbstractRemoteCacheManagerFactory will always produce " + "the same RemoteCacheManager instance. However,it returned false.", objectUnderTest.isSingleton()); }
@Override public boolean isSingleton() { return true; }
InfinispanRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<RemoteCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } }
InfinispanRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<RemoteCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } }
InfinispanRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<RemoteCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } @Override void afterPropertiesSet(); @Override RemoteCacheManager getObject(); @Override Class<? extends RemoteCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
InfinispanRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<RemoteCacheManager>, InitializingBean, DisposableBean { @Override public boolean isSingleton() { return true; } @Override void afterPropertiesSet(); @Override RemoteCacheManager getObject(); @Override Class<? extends RemoteCacheManager> getObjectType(); @Override boolean isSingleton(); @Override void destroy(); }
@Test public final void infinispanNamedRemoteCacheFactoryBeanShouldDeclareItselfToBeSingleton() { final InfinispanNamedRemoteCacheFactoryBean<String, Object> objectUnderTest = new InfinispanNamedRemoteCacheFactoryBean<String, Object>(); assertTrue( "InfinispanNamedRemoteCacheFactoryBean should declare itself to produce a singleton. However, it didn't.", objectUnderTest.isSingleton()); }
@Override public boolean isSingleton() { return true; }
InfinispanNamedRemoteCacheFactoryBean implements FactoryBean<RemoteCache<K, V>>, BeanNameAware, InitializingBean { @Override public boolean isSingleton() { return true; } }
InfinispanNamedRemoteCacheFactoryBean implements FactoryBean<RemoteCache<K, V>>, BeanNameAware, InitializingBean { @Override public boolean isSingleton() { return true; } }
InfinispanNamedRemoteCacheFactoryBean implements FactoryBean<RemoteCache<K, V>>, BeanNameAware, InitializingBean { @Override public boolean isSingleton() { return true; } @Override void afterPropertiesSet(); @Override void setBeanName(final String name); @Override RemoteCache<K, V> getObject(); @Override Class<? extends ConcurrentMap> getObjectType(); @Override boolean isSingleton(); void setCacheName(final String cacheName); void setInfinispanRemoteCacheManager(final RemoteCacheManager infinispanRemoteCacheManager); }
InfinispanNamedRemoteCacheFactoryBean implements FactoryBean<RemoteCache<K, V>>, BeanNameAware, InitializingBean { @Override public boolean isSingleton() { return true; } @Override void afterPropertiesSet(); @Override void setBeanName(final String name); @Override RemoteCache<K, V> getObject(); @Override Class<? extends ConcurrentMap> getObjectType(); @Override boolean isSingleton(); void setCacheName(final String cacheName); void setInfinispanRemoteCacheManager(final RemoteCacheManager infinispanRemoteCacheManager); }
@Test public void toArray1() throws Exception { RangeSet rs = new RangeSet(4); Object[] array = rs.toArray(new Integer[4]); assertEquals(4, array.length); assertEquals(0, array[0]); assertEquals(1, array[1]); assertEquals(2, array[2]); assertEquals(3, array[3]); }
@Override public Object[] toArray() { Object[] array = new Object[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; }
RangeSet implements IntSet { @Override public Object[] toArray() { Object[] array = new Object[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; } }
RangeSet implements IntSet { @Override public Object[] toArray() { Object[] array = new Object[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; } RangeSet(int size); }
RangeSet implements IntSet { @Override public Object[] toArray() { Object[] array = new Object[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
RangeSet implements IntSet { @Override public Object[] toArray() { Object[] array = new Object[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
@Test public void toIntArray() throws Exception { RangeSet rs = new RangeSet(4); int[] array = rs.toIntArray(); assertArrayEquals(new int[]{0, 1, 2, 3}, array); }
@Override public int[] toIntArray() { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; }
RangeSet implements IntSet { @Override public int[] toIntArray() { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; } }
RangeSet implements IntSet { @Override public int[] toIntArray() { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; } RangeSet(int size); }
RangeSet implements IntSet { @Override public int[] toIntArray() { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }
RangeSet implements IntSet { @Override public int[] toIntArray() { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; } RangeSet(int size); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override boolean contains(int i); @Override PrimitiveIterator.OfInt iterator(); @Override int[] toIntArray(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(Integer integer); @Override boolean remove(Object o); @Override boolean remove(int i); @Override boolean containsAll(Collection<?> c); @Override boolean containsAll(IntSet set); @Override boolean add(int i); void set(int i); @Override boolean addAll(IntSet set); @Override boolean addAll(Collection<? extends Integer> c); @Override boolean retainAll(Collection<?> c); @Override boolean retainAll(IntSet c); @Override boolean removeAll(IntSet set); @Override boolean removeAll(Collection<?> c); @Override void clear(); @Override boolean equals(Object o); @Override IntStream intStream(); @Override void forEach(IntConsumer action); @Override void forEach(Consumer<? super Integer> action); @Override Spliterator.OfInt intSpliterator(); @Override boolean removeIf(IntPredicate filter); @Override int hashCode(); @Override String toString(); }