@Test
 public void testAddingCacheEventListenerConfigurationAtCacheLevel() {
   CacheManagerBuilder<CacheManager> cacheManagerBuilder =
       CacheManagerBuilder.newCacheManagerBuilder();
   CacheEventListenerConfiguration cacheEventListenerConfiguration =
       CacheEventListenerConfigurationBuilder.newEventListenerConfiguration(
               ListenerObject.class, EventType.CREATED)
           .unordered()
           .asynchronous()
           .build();
   CacheManager cacheManager = cacheManagerBuilder.build(true);
   final Cache<Long, String> cache =
       cacheManager.createCache(
           "cache",
           CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class)
               .add(cacheEventListenerConfiguration)
               .withResourcePools(
                   ResourcePoolsBuilder.newResourcePoolsBuilder()
                       .heap(100, EntryUnit.ENTRIES)
                       .build())
               .build());
   Collection<ServiceConfiguration<?>> serviceConfiguration =
       cache.getRuntimeConfiguration().getServiceConfigurations();
   assertThat(
       serviceConfiguration,
       IsCollectionContaining.<ServiceConfiguration<?>>hasItem(
           instanceOf(DefaultCacheEventListenerConfiguration.class)));
   cacheManager.close();
 }
  @Test
  public void testCacheConfigUsage() {
    Set<EventType> eventTypeSet = new HashSet<EventType>();
    eventTypeSet.add(EventType.CREATED);
    eventTypeSet.add(EventType.UPDATED);

    CacheEventListenerConfigurationBuilder listenerBuilder =
        CacheEventListenerConfigurationBuilder.newEventListenerConfiguration(
                ListenerObject.class, eventTypeSet)
            .unordered()
            .asynchronous();
    final CacheManager manager =
        CacheManagerBuilder.newCacheManagerBuilder()
            .withCache(
                "foo",
                CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class)
                    .add(listenerBuilder)
                    .build())
            .build(true);
    final Collection<?> bar =
        manager
            .getCache("foo", Object.class, Object.class)
            .getRuntimeConfiguration()
            .getServiceConfigurations();
    assertThat(bar.iterator().next().getClass().toString(), is(ListenerObject.object.toString()));
  }
  @Before
  public void init() {
    CacheConfiguration<Long, String> cacheConfiguration =
        CacheConfigurationBuilder.newCacheConfigurationBuilder()
            .withResourcePools(
                ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build())
            .buildConfig(Long.class, String.class);

    service = new DefaultSharedManagementService();

    cacheManager1 =
        CacheManagerBuilder.newCacheManagerBuilder()
            .withCache("aCache1", cacheConfiguration)
            .using(service)
            .using(new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCM1"))
            .build(true);

    cacheManager2 =
        CacheManagerBuilder.newCacheManagerBuilder()
            .withCache("aCache2", cacheConfiguration)
            .withCache("aCache3", cacheConfiguration)
            .using(service)
            .using(new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCM2"))
            .build(true);

    // this serie of calls make sure the registry still works after a full init / close / init loop
    cacheManager1.close();
    cacheManager1.init();
    cacheManager2.close();
    cacheManager2.init();
  }
  @Test
  public void testThreadPoolsUsingDefaultPool() throws Exception {
    Configuration configuration =
        new XmlConfiguration(this.getClass().getResource("/configs/thread-pools.xml"));
    final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
    cacheManager.init();
    try {
      Cache<String, String> cache =
          cacheManager.createCache(
              "testThreadPools",
              newCacheConfigurationBuilder()
                  .add(
                      new DefaultCacheLoaderWriterConfiguration(
                          ThreadRememberingLoaderWriter.class))
                  .add(newUnBatchedWriteBehindConfiguration())
                  .buildConfig(String.class, String.class));

      cache.put("foo", "bar");

      ThreadRememberingLoaderWriter.USED.acquireUninterruptibly();

      assertThat(ThreadRememberingLoaderWriter.LAST_SEEN_THREAD.getName(), containsString("[big]"));
    } finally {
      cacheManager.close();
    }
  }
Ejemplo n.º 5
0
  @Test
  public void testGetAll_without_cache_loader() throws Exception {
    CacheConfigurationBuilder cacheConfigurationBuilder =
        CacheConfigurationBuilder.newCacheConfigurationBuilder(
            String.class, String.class, heap(100));
    CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

    CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
    CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

    Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

    for (int i = 0; i < 3; i++) {
      myCache.put("key" + i, "value" + i);
    }

    Set<String> fewKeysSet =
        new HashSet<String>() {
          {
            add("key0");
            add("key2");
          }
        };
    // the call to getAll
    Map<String, String> fewEntries = myCache.getAll(fewKeysSet);

    assertThat(fewEntries.size(), is(2));
    assertThat(fewEntries.get("key0"), is("value0"));
    assertThat(fewEntries.get("key2"), is("value2"));
  }
 @Test
 public void testCacheEventListener() throws Exception {
   Configuration configuration =
       new XmlConfiguration(
           this.getClass().getResource("/configs/ehcache-cacheEventListener.xml"));
   assertThat(configuration.getCacheConfigurations().containsKey("bar"), is(true));
   final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
   cacheManager.init();
   final Cache<Number, String> cache = cacheManager.getCache("bar", Number.class, String.class);
   cache.put(10, "dog");
   assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.CREATED));
   cache.put(10, "cat");
   assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.UPDATED));
   cache.remove(10);
   assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.REMOVED));
   cache.put(10, "dog");
   resetValues();
   assertThat(configuration.getCacheConfigurations().containsKey("template1"), is(true));
   final Cache<Number, String> templateCache =
       cacheManager.getCache("template1", Number.class, String.class);
   templateCache.put(10, "cat");
   assertThat(TestCacheEventListener.FIRED_EVENT, nullValue());
   templateCache.put(10, "dog");
   assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.UPDATED));
 }
Ejemplo n.º 7
0
  @Test
  public void testRemoveAll_without_cache_writer() throws Exception {
    CacheConfigurationBuilder cacheConfigurationBuilder =
        CacheConfigurationBuilder.newCacheConfigurationBuilder(
            String.class, String.class, heap(100));
    CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

    CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
    CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

    Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

    for (int i = 0; i < 3; i++) {
      myCache.put("key" + i, "value" + i);
    }

    Set<String> fewKeysSet =
        new HashSet<String>() {
          {
            add("key0");
            add("key2");
          }
        };
    // the call to removeAll
    myCache.removeAll(fewKeysSet);

    for (int i = 0; i < 3; i++) {
      if (i == 0 || i == 2) {
        assertThat(myCache.get("key" + i), is(nullValue()));
      } else {
        assertThat(myCache.get("key" + i), is("value" + i));
      }
    }
  }
  @Test
  public void testCanGetContext() {
    CacheConfiguration<Long, String> cacheConfiguration =
        CacheConfigurationBuilder.newCacheConfigurationBuilder()
            .withResourcePools(
                ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build())
            .buildConfig(Long.class, String.class);

    ManagementRegistry managementRegistry =
        new DefaultManagementRegistry(
            new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCM"));

    CacheManager cacheManager1 =
        CacheManagerBuilder.newCacheManagerBuilder()
            .withCache("aCache", cacheConfiguration)
            .using(managementRegistry)
            .build(true);

    assertThat(managementRegistry.getContext().getName(), equalTo("cacheManagerName"));
    assertThat(managementRegistry.getContext().getValue(), equalTo("myCM"));
    assertThat(managementRegistry.getContext().getSubContexts(), hasSize(1));
    assertThat(
        managementRegistry.getContext().getSubContexts().iterator().next().getName(),
        equalTo("cacheName"));
    assertThat(
        managementRegistry.getContext().getSubContexts().iterator().next().getValue(),
        equalTo("aCache"));

    cacheManager1.close();
  }
  @Test
  public void testWriteBehind()
      throws ClassNotFoundException, InstantiationException, IllegalAccessException, SAXException,
          IOException, InterruptedException {

    Configuration configuration =
        new XmlConfiguration(this.getClass().getResource("/configs/writebehind-cache.xml"));
    assertThat(configuration.getCacheConfigurations().containsKey("bar"), is(true));
    final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
    cacheManager.init();
    final Cache<Number, String> cache = cacheManager.getCache("bar", Number.class, String.class);
    assertThat(cache, notNullValue());
    assertThat(cache.get(1), notNullValue());
    final Number key = 42L;
    TestCacheLoaderWriter.latch = new CountDownLatch(1);
    cache.put(key, "Bye y'all!");
    TestCacheLoaderWriter.latch.await(2, TimeUnit.SECONDS);
    assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key));

    assertThat(configuration.getCacheConfigurations().containsKey("template1"), is(true));
    final Cache<Number, String> templateCache =
        cacheManager.getCache("template1", Number.class, String.class);
    assertThat(templateCache, notNullValue());
    assertThat(templateCache.get(1), notNullValue());
    final Number key1 = 100L;
    TestCacheLoaderWriter.latch = new CountDownLatch(2);
    templateCache.put(42L, "Howdy!");
    templateCache.put(key1, "Bye y'all!");
    TestCacheLoaderWriter.latch.await(2, TimeUnit.SECONDS);
    assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key1));
  }
  @Test
  public void testLoaderWriter()
      throws ClassNotFoundException, SAXException, InstantiationException, IOException,
          IllegalAccessException {
    Configuration configuration =
        new XmlConfiguration(this.getClass().getResource("/configs/cache-integration.xml"));
    assertThat(configuration.getCacheConfigurations().containsKey("bar"), is(true));
    final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
    cacheManager.init();
    final Cache<Number, String> cache = cacheManager.getCache("bar", Number.class, String.class);
    assertThat(cache, notNullValue());
    assertThat(cache.get(1), notNullValue());
    final Number key = new Long(42);
    cache.put(key, "Bye y'all!");
    assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key));

    assertThat(configuration.getCacheConfigurations().containsKey("template1"), is(true));
    final Cache<Number, String> templateCache =
        cacheManager.getCache("template1", Number.class, String.class);
    assertThat(templateCache, notNullValue());
    assertThat(templateCache.get(1), notNullValue());
    final Number key1 = new Long(100);
    templateCache.put(key1, "Bye y'all!");
    assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key1));
  }
Ejemplo n.º 11
0
  @Test
  public void testRemoveAll_with_cache_writer() throws Exception {
    CacheConfigurationBuilder cacheConfigurationBuilder =
        CacheConfigurationBuilder.newCacheConfigurationBuilder(
            String.class, String.class, heap(100));
    CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

    CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
    CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class);
    doThrow(new RuntimeException("We should not have called .write() but .writeAll()"))
        .when(cacheLoaderWriter)
        .delete(Matchers.anyObject());
    when(cacheLoaderWriterProvider.createCacheLoaderWriter(
            anyString(), Matchers.any(CacheConfiguration.class)))
        .thenReturn(cacheLoaderWriter);

    CacheManagerBuilder<CacheManager> managerBuilder =
        CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider);
    CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

    Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

    for (int i = 0; i < 3; i++) {
      myCache.put("key" + i, "value" + i);
    }

    Set<String> fewKeysSet =
        new HashSet<String>() {
          {
            add("key0");
            add("key2");
          }
        };

    // the call to removeAll
    myCache.removeAll(fewKeysSet);

    for (int i = 0; i < 3; i++) {
      if (i == 0 || i == 2) {
        assertThat(myCache.get("key" + i), is(nullValue()));
      } else {
        assertThat(myCache.get("key" + i), is("value" + i));
      }
    }
    Set set =
        new HashSet() {
          {
            add("key0");
          }
        };
    verify(cacheLoaderWriter).deleteAll(set);
    set =
        new HashSet() {
          {
            add("key2");
          }
        };
    verify(cacheLoaderWriter).deleteAll(set);
  }
Ejemplo n.º 12
0
  @Test
  public void testPutAll_with_cache_writer() throws Exception {
    CacheConfigurationBuilder cacheConfigurationBuilder =
        CacheConfigurationBuilder.newCacheConfigurationBuilder(
            String.class, String.class, heap(100));
    CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

    CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
    CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class);
    doThrow(new RuntimeException("We should not have called .write() but .writeAll()"))
        .when(cacheLoaderWriter)
        .write(Matchers.anyObject(), Matchers.anyObject());
    when(cacheLoaderWriterProvider.createCacheLoaderWriter(
            anyString(), Matchers.any(CacheConfiguration.class)))
        .thenReturn(cacheLoaderWriter);

    CacheManagerBuilder<CacheManager> managerBuilder =
        CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider);
    CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

    Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

    HashMap<String, String> stringStringHashMap = new HashMap<String, String>();
    for (int i = 0; i < 3; i++) {
      stringStringHashMap.put("key" + i, "value" + i);
    }

    // the call to putAll
    myCache.putAll(stringStringHashMap);

    verify(cacheLoaderWriter, times(3)).writeAll(Matchers.any(Iterable.class));
    Set set =
        new HashSet() {
          {
            add(entry("key0", "value0"));
          }
        };
    verify(cacheLoaderWriter).writeAll(set);
    set =
        new HashSet() {
          {
            add(entry("key1", "value1"));
          }
        };
    verify(cacheLoaderWriter).writeAll(set);
    set =
        new HashSet() {
          {
            add(entry("key2", "value2"));
          }
        };
    verify(cacheLoaderWriter).writeAll(set);

    for (int i = 0; i < 3; i++) {
      assertThat(myCache.get("key" + i), is("value" + i));
    }
  }
  @Test
  public void testCall() {
    List<Context> contextList =
        Arrays.asList(
            Context.create().with("cacheManagerName", "myCM1").with("cacheName", "aCache1"),
            Context.create().with("cacheManagerName", "myCM1").with("cacheName", "aCache4"),
            Context.create().with("cacheManagerName", "myCM2").with("cacheName", "aCache2"),
            Context.create().with("cacheManagerName", "myCM55").with("cacheName", "aCache55"));

    cacheManager1.getCache("aCache1", Long.class, String.class).put(1L, "1");
    cacheManager2.getCache("aCache2", Long.class, String.class).put(2L, "2");

    assertThat(cacheManager1.getCache("aCache1", Long.class, String.class).get(1L), equalTo("1"));
    assertThat(cacheManager2.getCache("aCache2", Long.class, String.class).get(2L), equalTo("2"));

    CacheConfiguration<Long, String> cacheConfiguration =
        CacheConfigurationBuilder.newCacheConfigurationBuilder()
            .withResourcePools(
                ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build())
            .buildConfig(Long.class, String.class);
    cacheManager1.createCache("aCache4", cacheConfiguration);

    cacheManager1.getCache("aCache4", Long.class, String.class).put(4L, "4");
    assertThat(cacheManager1.getCache("aCache4", Long.class, String.class).get(4L), equalTo("4"));

    ResultSet<ContextualReturn<Void>> results =
        service.withCapability("ActionsCapability").call("clear").on(contextList).build().execute();

    assertThat(results.size(), Matchers.equalTo(4));

    assertThat(results.getResult(contextList.get(0)).hasValue(), is(true));
    assertThat(results.getResult(contextList.get(1)).hasValue(), is(true));
    assertThat(results.getResult(contextList.get(2)).hasValue(), is(true));
    assertThat(results.getResult(contextList.get(3)).hasValue(), is(false));

    assertThat(results.getResult(contextList.get(0)).getValue(), is(nullValue()));
    assertThat(results.getResult(contextList.get(1)).getValue(), is(nullValue()));
    assertThat(results.getResult(contextList.get(2)).getValue(), is(nullValue()));

    try {
      results.getResult(contextList.get(3)).getValue();
      fail();
    } catch (Exception e) {
      assertThat(e, instanceOf(NoSuchElementException.class));
    }

    assertThat(
        cacheManager1.getCache("aCache1", Long.class, String.class).get(1L),
        is(Matchers.nullValue()));
    assertThat(
        cacheManager2.getCache("aCache2", Long.class, String.class).get(2L),
        is(Matchers.nullValue()));
    assertThat(
        cacheManager1.getCache("aCache4", Long.class, String.class).get(4L),
        is(Matchers.nullValue()));
  }
  @Test
  public void testCanGetStats() {
    CacheConfiguration<Long, String> cacheConfiguration =
        CacheConfigurationBuilder.newCacheConfigurationBuilder()
            .withResourcePools(
                ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build())
            .buildConfig(Long.class, String.class);

    ManagementRegistry managementRegistry =
        new DefaultManagementRegistry(
            new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCM"));

    CacheManager cacheManager1 =
        CacheManagerBuilder.newCacheManagerBuilder()
            .withCache("aCache1", cacheConfiguration)
            .withCache("aCache2", cacheConfiguration)
            .using(managementRegistry)
            .build(true);

    Map<String, String> context1 = new HashMap<String, String>();
    context1.put("cacheManagerName", "myCM");
    context1.put("cacheName", "aCache1");

    Map<String, String> context2 = new HashMap<String, String>();
    context2.put("cacheManagerName", "myCM");
    context2.put("cacheName", "aCache2");

    cacheManager1.getCache("aCache1", Long.class, String.class).put(1L, "1");
    cacheManager1.getCache("aCache1", Long.class, String.class).put(2L, "2");
    cacheManager1.getCache("aCache2", Long.class, String.class).put(3L, "3");
    cacheManager1.getCache("aCache2", Long.class, String.class).put(4L, "4");
    cacheManager1.getCache("aCache2", Long.class, String.class).put(5L, "5");

    Collection<Counter> counters =
        managementRegistry.collectStatistics(context1, "StatisticsCapability", "PutCounter");

    assertThat(counters, hasSize(1));
    assertThat(counters.iterator().next().getValue(), equalTo(2L));

    List<Collection<Counter>> allCounters =
        managementRegistry.collectStatistics(
            Arrays.asList(context1, context2), "StatisticsCapability", "PutCounter");

    assertThat(allCounters, hasSize(2));
    assertThat(allCounters.get(0), hasSize(1));
    assertThat(allCounters.get(1), hasSize(1));
    assertThat(allCounters.get(0).iterator().next().getValue(), equalTo(2L));
    assertThat(allCounters.get(1).iterator().next().getValue(), equalTo(3L));

    cacheManager1.close();
  }
Ejemplo n.º 15
0
  @Test
  public void testPutAll_store_throws_cache_exception() throws Exception {
    CacheConfigurationBuilder cacheConfigurationBuilder =
        CacheConfigurationBuilder.newCacheConfigurationBuilder(
            String.class, String.class, heap(100));
    CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

    CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
    CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class);
    doThrow(new RuntimeException("We should not have called .write() but .writeAll()"))
        .when(cacheLoaderWriter)
        .write(Matchers.anyObject(), Matchers.anyObject());
    when(cacheLoaderWriterProvider.createCacheLoaderWriter(
            anyString(), Matchers.any(CacheConfiguration.class)))
        .thenReturn(cacheLoaderWriter);

    CacheManagerBuilder<CacheManager> managerBuilder =
        CacheManagerBuilder.newCacheManagerBuilder()
            .using(cacheLoaderWriterProvider)
            .using(new CustomStoreProvider());
    CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

    Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

    Map<String, String> stringStringHashMap = new HashMap<String, String>();
    for (int i = 0; i < 3; i++) {
      stringStringHashMap.put("key" + i, "value" + i);
    }

    // the call to putAll
    myCache.putAll(stringStringHashMap);

    for (int i = 0; i < 3; i++) {
      // the store threw an exception when we call bulkCompute
      assertThat(myCache.get("key" + i), is(nullValue()));
      // but still, the cache writer could writeAll the values !
      //      assertThat(cacheWriterToHashMapMap.get("key" + i), is("value" + i));
    }
    // but still, the cache writer could writeAll the values at once !
    verify(cacheLoaderWriter, times(1)).writeAll(Matchers.any(Iterable.class));
    Set set =
        new HashSet() {
          {
            add(entry("key0", "value0"));
            add(entry("key1", "value1"));
            add(entry("key2", "value2"));
          }
        };
    verify(cacheLoaderWriter).writeAll(set);
  }
Ejemplo n.º 16
0
 private Cache<String, Object> getCacheForGroupOrCreateIt(String group) {
   Cache<String, Object> cache = cacheManager.getCache(group, String.class, Object.class);
   if (cache == null) {
     synchronized (lock) {
       cache = cacheManager.getCache(group, String.class, Object.class);
       if (cache == null) {
         cache =
             cacheManager.createCache(
                 group, cacheTemplate.buildConfig(String.class, Object.class));
       }
     }
   }
   return cache;
 }
Ejemplo n.º 17
0
  @Test
  public void testGetAll_with_cache_loader() throws Exception {
    CacheConfigurationBuilder cacheConfigurationBuilder =
        CacheConfigurationBuilder.newCacheConfigurationBuilder(
            String.class, String.class, heap(100));
    CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

    CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
    CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class);
    when(cacheLoaderWriter.load(Matchers.anyObject()))
        .thenThrow(new RuntimeException("We should not have called .load() but .loadAll()"));
    when(cacheLoaderWriterProvider.createCacheLoaderWriter(
            anyString(), Matchers.any(CacheConfiguration.class)))
        .thenReturn(cacheLoaderWriter);
    CacheManagerBuilder<CacheManager> managerBuilder =
        CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider);
    CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

    when(cacheLoaderWriter.loadAll(argThat(hasItem("key0"))))
        .thenReturn(
            new HashMap() {
              {
                put("key0", "value0");
              }
            });
    when(cacheLoaderWriter.loadAll(argThat(hasItem("key2"))))
        .thenReturn(
            new HashMap() {
              {
                put("key2", "value2");
              }
            });

    Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

    Set<String> fewKeysSet =
        new HashSet<String>() {
          {
            add("key0");
            add("key2");
          }
        };
    // the call to getAll
    Map<String, String> fewEntries = myCache.getAll(fewKeysSet);

    assertThat(fewEntries.size(), is(2));
    assertThat(fewEntries.get("key0"), is("value0"));
    assertThat(fewEntries.get("key2"), is("value2"));
  }
  @Test
  public void testCanGetCapabilities() {
    CacheConfiguration<Long, String> cacheConfiguration =
        CacheConfigurationBuilder.newCacheConfigurationBuilder()
            .withResourcePools(
                ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build())
            .buildConfig(Long.class, String.class);

    ManagementRegistry managementRegistry =
        new DefaultManagementRegistry(
            new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCM"));

    CacheManager cacheManager1 =
        CacheManagerBuilder.newCacheManagerBuilder()
            .withCache("aCache", cacheConfiguration)
            .using(managementRegistry)
            .build(true);

    assertThat(managementRegistry.getCapabilities(), hasSize(2));
    assertThat(
        new ArrayList<Capability>(managementRegistry.getCapabilities()).get(0).getName(),
        equalTo("ActionsCapability"));
    assertThat(
        new ArrayList<Capability>(managementRegistry.getCapabilities()).get(1).getName(),
        equalTo("StatisticsCapability"));

    assertThat(
        new ArrayList<Capability>(managementRegistry.getCapabilities()).get(0).getDescriptions(),
        hasSize(4));
    assertThat(
        new ArrayList<Capability>(managementRegistry.getCapabilities()).get(1).getDescriptions(),
        hasSize(16));

    assertThat(
        new ArrayList<Capability>(managementRegistry.getCapabilities())
            .get(0)
            .getCapabilityContext()
            .getAttributes(),
        hasSize(2));
    assertThat(
        new ArrayList<Capability>(managementRegistry.getCapabilities())
            .get(1)
            .getCapabilityContext()
            .getAttributes(),
        hasSize(2));

    cacheManager1.close();
  }
Ejemplo n.º 19
0
  @Test
  public void testRemoveAll_cache_writer_throws_exception() throws Exception {
    CacheConfigurationBuilder cacheConfigurationBuilder =
        CacheConfigurationBuilder.newCacheConfigurationBuilder(
            String.class, String.class, heap(100));
    CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

    CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
    CacheLoaderWriter cacheLoaderWriterThatThrows = mock(CacheLoaderWriter.class);
    doThrow(new Exception("Simulating an exception from the cache writer"))
        .when(cacheLoaderWriterThatThrows)
        .deleteAll(Matchers.any(Iterable.class));
    when(cacheLoaderWriterProvider.createCacheLoaderWriter(
            anyString(), Matchers.any(CacheConfiguration.class)))
        .thenReturn(cacheLoaderWriterThatThrows);

    CacheManagerBuilder<CacheManager> managerBuilder =
        CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider);
    CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

    Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

    for (int i = 0; i < 3; i++) {
      myCache.put("key" + i, "value" + i);
    }

    doThrow(new RuntimeException("We should not have called .write() but .writeAll()"))
        .when(cacheLoaderWriterThatThrows)
        .write(Matchers.anyObject(), Matchers.anyObject());

    Set<String> fewKeysSet =
        new HashSet<String>() {
          {
            add("key0");
            add("key2");
          }
        };

    // the call to removeAll
    try {
      myCache.removeAll(fewKeysSet);
      fail();
    } catch (BulkCacheWritingException bcwe) {
      assertThat(bcwe.getFailures().size(), is(2));
      assertThat(bcwe.getSuccesses().size(), is(0));
    }
  }
Ejemplo n.º 20
0
  @Test
  public void testGetAll_cache_loader_throws_exception() throws Exception {
    CacheConfigurationBuilder cacheConfigurationBuilder =
        CacheConfigurationBuilder.newCacheConfigurationBuilder(
            String.class, String.class, heap(100));
    CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

    CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
    CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class);
    when(cacheLoaderWriter.load(Matchers.anyObject()))
        .thenThrow(new RuntimeException("We should not have called .load() but .loadAll()"));
    when(cacheLoaderWriter.loadAll(Matchers.any(Iterable.class)))
        .thenThrow(new Exception("Simulating an exception from the cache loader"));
    when(cacheLoaderWriterProvider.createCacheLoaderWriter(
            anyString(), Matchers.any(CacheConfiguration.class)))
        .thenReturn(cacheLoaderWriter);
    CacheManagerBuilder<CacheManager> managerBuilder =
        CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider);
    CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

    Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

    Set<String> fewKeysSet =
        new HashSet<String>() {
          {
            add("key0");
            add("key2");
          }
        };

    // the call to getAll
    try {
      myCache.getAll(fewKeysSet);
      fail();
    } catch (BulkCacheLoadingException bcwe) {
      // since onHeapStore.bulkComputeIfAbsent sends batches of 1 element,
      assertThat(bcwe.getFailures().size(), is(2));
      assertThat(bcwe.getSuccesses().size(), is(0));
    }
  }
  @Test
  public void testCopiers() throws Exception {
    Configuration configuration =
        new XmlConfiguration(this.getClass().getResource("/configs/cache-copiers.xml"));
    final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
    cacheManager.init();

    Cache<Description, Person> bar = cacheManager.getCache("bar", Description.class, Person.class);
    Description desc = new Description(1234, "foo");
    Person person = new Person("Bar", 24);
    bar.put(desc, person);
    assertEquals(person, bar.get(desc));
    assertNotSame(person, bar.get(desc));

    Cache<Long, Person> baz = cacheManager.getCache("baz", Long.class, Person.class);
    baz.put(1L, person);
    assertEquals(person, baz.get(1L));
    assertNotSame(person, baz.get(1L));

    Employee empl = new Employee(1234, "foo", 23);
    Cache<Long, Employee> bak = cacheManager.getCache("bak", Long.class, Employee.class);
    bak.put(1L, empl);
    assertSame(empl, bak.get(1L));
    cacheManager.close();
  }
Ejemplo n.º 22
0
  @Test
  public void testStoreByValue() {
    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(false);
    cacheManager.init();

    DefaultCopierConfiguration<String> copierConfiguration =
        new DefaultCopierConfiguration(SerializingCopier.class, CopierConfiguration.Type.VALUE);
    final Cache<Long, String> cache1 =
        cacheManager.createCache(
            "cache1",
            CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class)
                .withResourcePools(
                    ResourcePoolsBuilder.newResourcePoolsBuilder().heap(1, EntryUnit.ENTRIES))
                .build());
    performAssertions(cache1, true);

    final Cache<Long, String> cache2 =
        cacheManager.createCache(
            "cache2",
            CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class)
                .add(copierConfiguration)
                .build());
    performAssertions(cache2, false);

    final Cache<Long, String> cache3 =
        cacheManager.createCache(
            "cache3",
            CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class)
                .build());
    performAssertions(cache3, true);

    cacheManager.close();
  }
  @Test
  public void testCall() {
    CacheConfiguration<Long, String> cacheConfiguration =
        CacheConfigurationBuilder.newCacheConfigurationBuilder()
            .withResourcePools(
                ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build())
            .buildConfig(Long.class, String.class);

    ManagementRegistry managementRegistry =
        new DefaultManagementRegistry(
            new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCM"));

    CacheManager cacheManager1 =
        CacheManagerBuilder.newCacheManagerBuilder()
            .withCache("aCache1", cacheConfiguration)
            .withCache("aCache2", cacheConfiguration)
            .using(managementRegistry)
            .build(true);

    Map<String, String> context =
        new HashMap<String, String>() {
          {
            put("cacheManagerName", "myCM");
            put("cacheName", "aCache1");
          }
        };

    cacheManager1.getCache("aCache1", Long.class, String.class).put(1L, "1");

    assertThat(cacheManager1.getCache("aCache1", Long.class, String.class).get(1L), equalTo("1"));

    Object result =
        managementRegistry.callAction(
            context, "ActionsCapability", "clear", new String[0], new Object[0]);
    assertThat(result, is(nullValue()));

    assertThat(
        cacheManager1.getCache("aCache1", Long.class, String.class).get(1L),
        is(Matchers.nullValue()));
  }
Ejemplo n.º 24
0
 @Override
 public void doFlush(CacheEvent event) {
   if (event.getType().equals(CacheEvent.CacheEventType.ALL)) {
     LOGGER.warn(
         getClass() + " does not support flushing all caches. Flush one group at the time.");
   } else if (event.getType().equals(CacheEvent.CacheEventType.GROUP)) {
     final Cache<String, Object> cache =
         cacheManager.getCache(event.getGroup(), String.class, Object.class);
     if (cache != null) {
       cache.clear();
     }
   }
 }
  @Test
  public void testStats() {
    List<Context> contextList =
        Arrays.asList(
            Context.create().with("cacheManagerName", "myCM1").with("cacheName", "aCache1"),
            Context.create().with("cacheManagerName", "myCM2").with("cacheName", "aCache2"),
            Context.create().with("cacheManagerName", "myCM2").with("cacheName", "aCache3"));

    cacheManager1.getCache("aCache1", Long.class, String.class).put(1L, "1");
    cacheManager2.getCache("aCache2", Long.class, String.class).put(2L, "2");
    cacheManager2.getCache("aCache3", Long.class, String.class).put(3L, "3");

    ResultSet<ContextualStatistics> allCounters =
        service
            .withCapability("StatisticsCapability")
            .queryStatistic("PutCounter")
            .on(contextList)
            .build()
            .execute();

    assertThat(allCounters.size(), equalTo(3));

    assertThat(allCounters.getResult(contextList.get(0)).size(), equalTo(1));
    assertThat(allCounters.getResult(contextList.get(1)).size(), equalTo(1));
    assertThat(allCounters.getResult(contextList.get(2)).size(), equalTo(1));

    assertThat(
        allCounters.getResult(contextList.get(0)).getStatistic(Counter.class).getValue(),
        equalTo(1L));
    assertThat(
        allCounters.getResult(contextList.get(1)).getStatistic(Counter.class).getValue(),
        equalTo(1L));
    assertThat(
        allCounters.getResult(contextList.get(2)).getStatistic(Counter.class).getValue(),
        equalTo(1L));
  }
Ejemplo n.º 26
0
  @Test
  public void testPutAll_without_cache_writer() throws Exception {
    CacheConfigurationBuilder cacheConfigurationBuilder =
        CacheConfigurationBuilder.newCacheConfigurationBuilder(
            String.class, String.class, heap(100));
    CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

    CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
    CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

    Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

    HashMap<String, String> stringStringHashMap = new HashMap<String, String>();
    for (int i = 0; i < 3; i++) {
      stringStringHashMap.put("key" + i, "value" + i);
    }

    // the call to putAll
    myCache.putAll(stringStringHashMap);

    for (int i = 0; i < 3; i++) {
      assertThat(myCache.get("key" + i), is("value" + i));
    }
  }
Ejemplo n.º 27
0
  public EHCache3Manager()
      throws ClassNotFoundException, SAXException, InstantiationException, IOException,
          IllegalAccessException {
    URL url = getClass().getResource("/activejdbc-ehcache.xml");
    if (url == null) {
      throw new InitException(
          "You are using "
              + getClass().getName()
              + " but failed to provide a EHCache configuration file on classpath: activejdbc-ehcache.xml");
    }

    XmlConfiguration xmlConfiguration = new XmlConfiguration(url);

    cacheTemplate =
        xmlConfiguration.newCacheConfigurationBuilderFromTemplate(
            "activejdbc", String.class, Object.class);

    if (cacheTemplate == null) {
      throw new InitException(
          "Please, provide a <cache-template name=\"activejdbc\"> element in  activejdbc-ehcache.xml file");
    }
    cacheManager = CacheManagerBuilder.newCacheManager(xmlConfiguration);
    cacheManager.init();
  }
  @Test
  public void testSerializers() throws Exception {
    Configuration configuration =
        new XmlConfiguration(this.getClass().getResource("/configs/default-serializer.xml"));
    final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
    cacheManager.init();

    Cache<Long, Double> bar = cacheManager.getCache("bar", Long.class, Double.class);
    bar.put(1L, 1.0);
    assertThat(bar.get(1L), equalTo(1.0));

    Cache<String, String> baz = cacheManager.getCache("baz", String.class, String.class);
    baz.put("1", "one");
    assertThat(baz.get("1"), equalTo("one"));

    Cache<String, Object> bam =
        cacheManager.createCache(
            "bam", newCacheConfigurationBuilder().buildConfig(String.class, Object.class));
    bam.put("1", "one");
    assertThat(bam.get("1"), equalTo((Object) "one"));

    cacheManager.close();
  }
 @After()
 public void close() {
   cacheManager2.close();
   cacheManager1.close();
 }