javax.cache.configuration.MutableCacheEntryListenerConfiguration Java Examples

The following examples show how to use javax.cache.configuration.MutableCacheEntryListenerConfiguration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JCacheExpiryAndMaximumSizeTest.java    From caffeine with Apache License 2.0 6 votes vote down vote up
@Override
protected CaffeineConfiguration<Integer, Integer> getConfiguration() {
  CacheEntryRemovedListener<Integer, Integer> listener = events -> removed.incrementAndGet();

  CaffeineConfiguration<Integer, Integer> configuration = new CaffeineConfiguration<>();

  configuration.setMaximumSize(OptionalLong.of(MAXIMUM));
  CacheEntryListenerConfiguration<Integer, Integer> listenerConfiguration =
      new MutableCacheEntryListenerConfiguration<>(() -> listener,
          /* filterFactory */ null, /* isOldValueRequired */ false, /* isSynchronous */ true);
  configuration.addCacheEntryListenerConfiguration(listenerConfiguration);
  configuration.setExecutorFactory(MoreExecutors::directExecutor);

  configuration.setExpiryFactory(Optional.of(() -> expiry));
  configuration.setTickerFactory(() -> ticker::read);

  return configuration;
}
 
Example #2
Source File: CacheListenerTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Test
public void  testDeregistration() {

  assertEquals(1, getConfigurationCacheEntryListenerConfigurationSize(cache));

  MyCacheEntryListener secondListener = new MyCacheEntryListener<Long, String>();
  MutableCacheEntryListenerConfiguration<Long,
      String> secondListenerConfiguration = new
      MutableCacheEntryListenerConfiguration(FactoryBuilder.factoryOf(secondListener), null, false, true);
  cache.registerCacheEntryListener(secondListenerConfiguration);

  assertEquals(2, getConfigurationCacheEntryListenerConfigurationSize(cache));
  cache.deregisterCacheEntryListener(secondListenerConfiguration);

  assertEquals(1, getConfigurationCacheEntryListenerConfigurationSize(cache));

  //no effect if called after it has been removed
  cache.deregisterCacheEntryListener(secondListenerConfiguration);
  assertEquals(1, getConfigurationCacheEntryListenerConfigurationSize(cache));

  //Deregister the listener registered at configuration time
  cache.deregisterCacheEntryListener(listenerConfiguration);
  assertEquals(0, getConfigurationCacheEntryListenerConfigurationSize(cache));
}
 
Example #3
Source File: CacheListenerTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Override
protected MutableConfiguration<Long, String> extraSetup(MutableConfiguration<Long, String> configuration) {
  cacheEntryListenerServer = new CacheEntryListenerServer<Long, String>(10011, Long.class, String.class);
  try {
    cacheEntryListenerServer.open();
  } catch (IOException e) {
    e.printStackTrace();
  }

  //establish and open a CacheEntryListenerServer to handle cache
  //cache entry events from a CacheEntryListenerClient
  listener = new MyCacheEntryListener<Long, String>();
  cacheEntryListenerServer.addCacheEventListener(listener);

  //establish a CacheEntryListenerClient that a Cache can use for CacheEntryListening
  //(via the CacheEntryListenerServer)
  CacheEntryListenerClient<Long, String> clientListener =
    new CacheEntryListenerClient<>(cacheEntryListenerServer.getInetAddress(), cacheEntryListenerServer.getPort());
  listenerConfiguration = new MutableCacheEntryListenerConfiguration<Long, String>(FactoryBuilder.factoryOf(clientListener), null, true, true);
  return configuration.addCacheEntryListenerConfiguration(listenerConfiguration);
}
 
Example #4
Source File: AdditionalCacheListenerTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Override
protected MutableConfiguration<Integer, String> extraSetup(MutableConfiguration<Integer, String> cfg) {
  // cfg.setExpiryPolicyFactory(ModifiedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, 5)));
  cacheEntryListenerServer = new CacheEntryListenerServer<>(10011, Integer.class, String.class);
  try {
    cacheEntryListenerServer.open();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  listener = new RecordingListener<>();
  cacheEntryListenerServer.addCacheEventListener(listener);
  CacheEntryListenerClient<Integer, String> clientListener =
    new CacheEntryListenerClient<>(cacheEntryListenerServer.getInetAddress(), cacheEntryListenerServer.getPort());
  boolean _isSynchronous = false;
  listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(
    FactoryBuilder.factoryOf(clientListener), null, true, _isSynchronous);
  return cfg.addCacheEntryListenerConfiguration(listenerConfiguration);
}
 
Example #5
Source File: TypesafeConfigurator.java    From caffeine with Apache License 2.0 6 votes vote down vote up
/** Adds the entry listeners settings. */
private void addListeners() {
  for (String path : merged.getStringList("listeners")) {
    Config listener = root.getConfig(path);

    Factory<? extends CacheEntryListener<? super K, ? super V>> listenerFactory =
        factoryCreator.factoryOf(listener.getString("class"));
    Factory<? extends CacheEntryEventFilter<? super K, ? super V>> filterFactory = null;
    if (listener.hasPath("filter")) {
      filterFactory = factoryCreator.factoryOf(listener.getString("filter"));
    }
    boolean oldValueRequired = listener.getBoolean("old-value-required");
    boolean synchronous = listener.getBoolean("synchronous");
    configuration.addCacheEntryListenerConfiguration(
        new MutableCacheEntryListenerConfiguration<>(
            listenerFactory, filterFactory, oldValueRequired, synchronous));
  }
}
 
Example #6
Source File: Eh107XmlIntegrationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTemplateAddsListeners() throws Exception {
  CacheManager cacheManager = cachingProvider.getCacheManager(getClass().getResource("/ehcache-107-listeners.xml")
      .toURI(), getClass().getClassLoader());

  MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
  configuration.setTypes(String.class, String.class);
  MutableCacheEntryListenerConfiguration<String, String> listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(Test107CacheEntryListener::new, null, false, true);
  configuration.addCacheEntryListenerConfiguration(listenerConfiguration);

  Cache<String, String> cache = cacheManager.createCache("foos", configuration);
  cache.put("Hello", "Bonjour");

  assertThat(Test107CacheEntryListener.seen.size(), Matchers.is(1));
  assertThat(TestCacheEventListener.seen.size(), Matchers.is(1));
}
 
Example #7
Source File: IgniteCacheEntryListenerAbstractTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param cache Cache.
 * @param lsnrFactory Listener factory.
 * @param key Key.
 * @param create {@code True} if listens for create events.
 * @param update {@code True} if listens for update events.
 * @param rmv {@code True} if listens for remove events.
 * @param expire {@code True} if listens for expire events.
 * @throws Exception If failed.
 */
private void checkEvents(
    final IgniteCache<Object, Object> cache,
    final Factory<CacheEntryListener<Object, Object>> lsnrFactory,
    Integer key,
    boolean create,
    boolean update,
    boolean rmv,
    boolean expire) throws Exception {
    CacheEntryListenerConfiguration<Object, Object> lsnrCfg = new MutableCacheEntryListenerConfiguration<>(
        lsnrFactory,
        null,
        true,
        false
    );

    cache.registerCacheEntryListener(lsnrCfg);

    try {
        checkEvents(cache, lsnrCfg, key, create, update, rmv, expire, true);
    }
    finally {
        cache.deregisterCacheEntryListener(lsnrCfg);
    }
}
 
Example #8
Source File: IgniteCacheEntryListenerAbstractTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testConcurrentRegisterDeregister() throws Exception {
    final int THREADS = 10;

    final CyclicBarrier barrier = new CyclicBarrier(THREADS);

    final IgniteCache<Object, Object> cache = jcache(0);

    GridTestUtils.runMultiThreadedAsync(new Callable<Void>() {
        @Override public Void call() throws Exception {
            CacheEntryListenerConfiguration<Object, Object> cfg = new MutableCacheEntryListenerConfiguration<>(
                new Factory<CacheEntryListener<Object, Object>>() {
                    @Override public CacheEntryListener<Object, Object> create() {
                        return new CreateUpdateRemoveExpireListener();
                    }
                },
                null,
                true,
                false
            );

            barrier.await();

            for (int i = 0; i < 100; i++) {
                cache.registerCacheEntryListener(cfg);

                cache.deregisterCacheEntryListener(cfg);
            }

            return null;
        }
    }, THREADS, "register-thread").get();
}
 
Example #9
Source File: CacheListenerTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void  testDynamicRegistration() {

  assertEquals(1, getConfigurationCacheEntryListenerConfigurationSize(cache));

  MyCacheEntryListener secondListener = new MyCacheEntryListener<Long, String>();
  MutableCacheEntryListenerConfiguration<Long,
      String> listenerConfiguration = new
      MutableCacheEntryListenerConfiguration(FactoryBuilder.factoryOf(secondListener), null, false, true);
  cache.registerCacheEntryListener(listenerConfiguration);

  assertEquals(2,getConfigurationCacheEntryListenerConfigurationSize(cache));

  CompleteConfiguration<Long, String> cacheConfig = (CompleteConfiguration)cache.getConfiguration(CompleteConfiguration.class);
  for (CacheEntryListenerConfiguration<Long, String> config : cacheConfig.getCacheEntryListenerConfigurations()) {
    config.hashCode();
    config.isOldValueRequired();
    config.isSynchronous();
  }

  //Can only register the same configuration once
  try {
    cache.registerCacheEntryListener(listenerConfiguration);
    fail();
  } catch (IllegalArgumentException e) {
    //expected
  }
}
 
Example #10
Source File: CacheExpiryTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Override
protected MutableConfiguration<Integer, Integer> extraSetup(MutableConfiguration<Integer, Integer> configuration) {
  listener = new CacheTestSupport.MyCacheEntryListener<Integer, Integer>();

  //establish a CacheEntryListenerClient that a Cache can use for CacheEntryListening
  //(via the CacheEntryListenerServer)

  listenerConfiguration =
    new MutableCacheEntryListenerConfiguration<>(FactoryBuilder.factoryOf(cacheEntryListerClient), null, true, true);
  cacheEntryListenerServer.addCacheEventListener(listener);
  return configuration.addCacheEntryListenerConfiguration(listenerConfiguration);
}
 
Example #11
Source File: CacheContinuousQueryLostPartitionTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param cache Cache.
 * @return Event listener.
 */
private AllEventListener<Integer, String> registerCacheListener(IgniteCache<Integer, String> cache) {
    AllEventListener<Integer, String> lsnr = new AllEventListener<>();

    cache.registerCacheEntryListener(
        new MutableCacheEntryListenerConfiguration<>(factoryOf(lsnr), null, true, false));

    return lsnr;
}
 
Example #12
Source File: EventListenerIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenRunEvent_thenCorrect() throws InterruptedException {
    this.listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(FactoryBuilder.factoryOf(this.listener), null, false, true);
    this.cache.registerCacheEntryListener(this.listenerConfiguration);

    assertEquals(false, this.listener.getCreated());

    this.cache.put("key", "value");
    assertEquals(true, this.listener.getCreated());
    assertEquals(false, this.listener.getUpdated());

    this.cache.put("key", "newValue");
    assertEquals(true, this.listener.getUpdated());
}
 
Example #13
Source File: AddRemoveListenerICacheTest.java    From hazelcast-simulator with Apache License 2.0 5 votes vote down vote up
@Prepare(global = false)
public void prepare() {
    cache = cacheManager.getCache(name);

    listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(
            FactoryBuilder.factoryOf(listener),
            FactoryBuilder.factoryOf(filter),
            false, syncEvents);
}
 
Example #14
Source File: JCacheTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpiration() throws InterruptedException, IllegalArgumentException, URISyntaxException, FailedToStartRedisException, IOException {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();

    MutableConfiguration<String, String> config = new MutableConfiguration<>();
    config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 1)));
    config.setStoreByValue(true);
    
    URI configUri = getClass().getResource("redisson-jcache.json").toURI();
    Cache<String, String> cache = Caching.getCachingProvider().getCacheManager(configUri, null)
            .createCache("test", config);

    CountDownLatch latch = new CountDownLatch(1);
    
    String key = "123";
    ExpiredListener clientListener = new ExpiredListener(latch, key, "90");
    MutableCacheEntryListenerConfiguration<String, String> listenerConfiguration = 
            new MutableCacheEntryListenerConfiguration<String, String>(FactoryBuilder.factoryOf(clientListener), null, true, true);
    cache.registerCacheEntryListener(listenerConfiguration);

    cache.put(key, "90");
    Assert.assertNotNull(cache.get(key));
    
    latch.await();
    
    Assert.assertNull(cache.get(key));
    
    cache.close();
    runner.stop();
}
 
Example #15
Source File: JCacheEvictionListenerTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void before() {
  MockitoAnnotations.initMocks(this);
  statistics = new JCacheStatisticsMXBean();
  EventDispatcher<Integer, Integer> dispatcher =
      new EventDispatcher<>(MoreExecutors.directExecutor());
  listener = new JCacheEvictionListener<>(dispatcher, statistics);
  listener.setCache(cache);
  statistics.enable(true);

  dispatcher.register(new MutableCacheEntryListenerConfiguration<Integer, Integer>(
      () -> entryListener, null, false, false));
}
 
Example #16
Source File: EventDispatcherTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
/**
 * Registers (4 listeners) * (2 synchronous modes) * (3 filter modes) = 24 configurations. For
 * simplicity, an event is published and ignored if the listener is of the wrong type. For a
 * single event, it should be consumed by (2 filter) * (2 synchronous) = 4 listeners where only
 * 2 are synchronous.
 */
private void registerAll() {
  List<CacheEntryListener<Integer, Integer>> listeners = Arrays.asList(
      createdListener, updatedListener, removedListener, expiredListener);
  for (CacheEntryListener<Integer, Integer> listener : listeners) {
    for (boolean synchronous : Arrays.asList(true, false)) {
      dispatcher.register(new MutableCacheEntryListenerConfiguration<>(
          () -> listener, null, false, synchronous));
      dispatcher.register(new MutableCacheEntryListenerConfiguration<>(
          () -> listener, () -> allowFilter, false, synchronous));
      dispatcher.register(new MutableCacheEntryListenerConfiguration<>(
          () -> listener, () -> rejectFilter, false, synchronous));
    }
  }
}
 
Example #17
Source File: EventDispatcherTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@Test
public void deregister() {
  MutableCacheEntryListenerConfiguration<Integer, Integer> configuration =
      new MutableCacheEntryListenerConfiguration<>(() -> createdListener, null, false, false);
  dispatcher.register(configuration);
  dispatcher.deregister(configuration);
  assertThat(dispatcher.dispatchQueues.keySet(), is(empty()));
}
 
Example #18
Source File: EventDispatcherTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@Test
public void register_noListener() {
  MutableCacheEntryListenerConfiguration<Integer, Integer> configuration =
      new MutableCacheEntryListenerConfiguration<>(null, null, false, false);
  dispatcher.register(configuration);
  assertThat(dispatcher.dispatchQueues.keySet(), is(empty()));
}
 
Example #19
Source File: JCacheMaximumWeightTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@Override
protected CaffeineConfiguration<Integer, Integer> getConfiguration() {
  CacheEntryRemovedListener<Integer, Integer> listener = events ->
      removedWeight.addAndGet(Iterables.getOnlyElement(events).getValue());
  CaffeineConfiguration<Integer, Integer> configuration = new CaffeineConfiguration<>();
  configuration.setMaximumWeight(OptionalLong.of(MAXIMUM));
  configuration.setWeigherFactory(Optional.of(() -> (key, value) -> value));
  CacheEntryListenerConfiguration<Integer, Integer> listenerConfiguration =
      new MutableCacheEntryListenerConfiguration<Integer, Integer>(() -> listener,
          /* filterFactory */ null, /* isOldValueRequired */ true, /* isSynchronous */ true);
  configuration.addCacheEntryListenerConfiguration(listenerConfiguration);
  configuration.setExecutorFactory(MoreExecutors::directExecutor);
  return configuration;
}
 
Example #20
Source File: JCacheMaximumSizeTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@Override
protected CaffeineConfiguration<Integer, Integer> getConfiguration() {
  CacheEntryRemovedListener<Integer, Integer> listener = events -> removed.incrementAndGet();
  CaffeineConfiguration<Integer, Integer> configuration = new CaffeineConfiguration<>();
  configuration.setMaximumSize(OptionalLong.of(MAXIMUM));
  CacheEntryListenerConfiguration<Integer, Integer> listenerConfiguration =
      new MutableCacheEntryListenerConfiguration<Integer, Integer>(() -> listener,
          /* filterFactory */ null, /* isOldValueRequired */ false, /* isSynchronous */ true);
  configuration.addCacheEntryListenerConfiguration(listenerConfiguration);
  configuration.setExecutorFactory(MoreExecutors::directExecutor);
  return configuration;
}
 
Example #21
Source File: CacheConfigurationFactory.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
<K, T> Configuration<K, T> createConfiguration(final CacheSizeManager<K, T> listener) {
    return new MutableConfiguration<K, T>()
            .setStoreByValue(false)
            .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(SECONDS, cacheExpiry)))
            .setManagementEnabled(cacheManagement)
            .setStatisticsEnabled(cacheStatistics)
            .addCacheEntryListenerConfiguration(new MutableCacheEntryListenerConfiguration<>(
                    new FactoryBuilder.SingletonFactory<>(listener), null, false, false));
}
 
Example #22
Source File: GridCacheContinuousQueryConcurrentTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param key Key.
 * @param res Result.
 * @param id Listener ID.
 * @return Listener
 */
private CacheEntryListenerConfiguration<Integer, String> createCacheListener(
    Integer key,
    IgniteFuture<String> res,
    int id) {
    return new MutableCacheEntryListenerConfiguration<>(
        factoryOf(new CacheListener(res, id)),
        new SingletonFactory<>(new KeyEventFilter(key, id)), false, true);
}
 
Example #23
Source File: CacheListenersTest.java    From blazingcache with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateListenerSynch() {

    CachingProvider cachingProvider = Caching.getCachingProvider();
    Properties p = new Properties();
    try (CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), cachingProvider.getDefaultClassLoader(), p)) {
        Map<String, String> created = new HashMap<>();
        CacheEntryCreatedListener<String, String> listener = new CacheEntryCreatedListener<String, String>() {
            @Override
            public void onCreated(Iterable<CacheEntryEvent<? extends String, ? extends String>> events) throws CacheEntryListenerException {
                for (CacheEntryEvent<? extends String, ? extends String> e : events) {
                    created.put(e.getKey(), e.getValue());
                }
            }
        };

        MutableConfiguration<String, String> config
                = new MutableConfiguration<String, String>()
                .setTypes(String.class, String.class)
                .addCacheEntryListenerConfiguration(new MutableCacheEntryListenerConfiguration<>(
                        new FactoryBuilder.SingletonFactory(listener), null, true, true)
                );

        Cache<String, String> cache = cacheManager.createCache("simpleCache", config);

        String key = "key";
        cache.put(key, "value");
        assertEquals("value", created.get(key));
    }
}
 
Example #24
Source File: IgniteCacheEntryListenerExpiredEventsTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param ccfg Cache configuration.
 * @throws Exception If failed.
 */
private void checkExpiredEvents(CacheConfiguration<Object, Object> ccfg) throws Exception {
    IgniteCache<Object, Object> cache = ignite(0).createCache(ccfg);

    try {
        evtCntr = new AtomicInteger();

        CacheEntryListenerConfiguration<Object, Object> lsnrCfg = new MutableCacheEntryListenerConfiguration<>(
            new ExpiredListenerFactory(),
            null,
            true,
            false
        );

        cache.registerCacheEntryListener(lsnrCfg);

        IgniteCache<Object, Object> expiryCache =
            cache.withExpiryPolicy(new ModifiedExpiryPolicy(new Duration(MILLISECONDS, 500)));

        expiryCache.put(1, 1);

        for (int i = 0; i < 10; i++)
            cache.get(i);

        boolean wait = GridTestUtils.waitForCondition(new GridAbsPredicate() {
            @Override public boolean apply() {
                return evtCntr.get() > 0;
            }
        }, 5000);

        assertTrue(wait);

        U.sleep(100);

        assertEquals(1, evtCntr.get());
    }
    finally {
        ignite(0).destroyCache(cache.getName());
    }
}
 
Example #25
Source File: IgniteCacheEntryListenerAbstractTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testSerialization() throws Exception {
    if (cacheMode() == LOCAL)
        return;

    AtomicBoolean serialized = new AtomicBoolean();

    NonSerializableListener lsnr = new NonSerializableListener(serialized);

    jcache(0).registerCacheEntryListener(new MutableCacheEntryListenerConfiguration<>(
        FactoryBuilder.factoryOf(lsnr),
        new SerializableFactory(),
        true,
        false
    ));

    try {
        startGrid(gridCount());

        jcache(0).put(1, 1);
    }
    finally {
        stopGrid(gridCount());
    }

    jcache(0).put(2, 2);

    assertFalse(IgniteCacheEntryListenerAbstractTest.serialized.get());
    assertFalse(serialized.get());
}
 
Example #26
Source File: IgniteCacheEntryListenerAbstractTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testNoOldValue() throws Exception {
    CacheEntryListenerConfiguration<Object, Object> lsnrCfg = new MutableCacheEntryListenerConfiguration<>(
        new Factory<CacheEntryListener<Object, Object>>() {
            @Override public CacheEntryListener<Object, Object> create() {
                return new CreateUpdateRemoveExpireListener();
            }
        },
        null,
        false,
        true
    );

    IgniteCache<Object, Object> cache = jcache();

    try {
        for (Integer key : keys()) {
            log.info("Check create/update/remove/expire events, no old value [key=" + key + ']');

            cache.registerCacheEntryListener(lsnrCfg);

            checkEvents(cache, lsnrCfg, key, true, true, true, true, false);
        }
    }
    finally {
        cache.deregisterCacheEntryListener(lsnrCfg);
    }
}
 
Example #27
Source File: CacheContinuousQueryOperationP2PTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param ccfg Cache configuration.
 * @param isClient Client.
 * @param joinNode If a node should be added to topology after a query is started.
 * @param evtFilterFactoryCls Remote filter factory class.
 * @throws Exception If failed.
 */
private void testContinuousQuery(CacheConfiguration<Object, Object> ccfg,
    boolean isClient, boolean joinNode,
    Class<Factory<CacheEntryEventFilter>> evtFilterFactoryCls) throws Exception {

    ThreadLocalRandom rnd = ThreadLocalRandom.current();

    final CountDownLatch latch = new CountDownLatch(UPDATES);

    ContinuousQuery<Integer, Integer> qry = new ContinuousQuery<>();

    AtomicReference<String> err = new AtomicReference<>();

    TestLocalListener locLsnr = new TestLocalListener() {
        @Override protected void onEvent(Iterable<CacheEntryEvent<? extends Integer, ? extends Integer>> evts) {
            for (CacheEntryEvent<? extends Integer, ? extends Integer> evt : evts) {
                latch.countDown();

                log.info("Received event: " + evt);

                int key = evt.getKey();

                if (key % 2 == 0)
                    err.set("Event received on entry, that doesn't pass a filter: " + key);
            }
        }
    };

    qry.setLocalListener(locLsnr);

    qry.setRemoteFilterFactory(
        (Factory<? extends CacheEntryEventFilter<Integer, Integer>>)(Object)evtFilterFactoryCls.newInstance());

    MutableCacheEntryListenerConfiguration<Integer, Integer> lsnrCfg =
        new MutableCacheEntryListenerConfiguration<>(
            new FactoryBuilder.SingletonFactory<>(locLsnr),
            (Factory<? extends CacheEntryEventFilter<? super Integer, ? super Integer>>)
                (Object)evtFilterFactoryCls.newInstance(),
            true,
            true
        );

    IgniteCache<Integer, Integer> cache;

    cache = isClient
        ? grid(NODES - 1).cache(ccfg.getName())
        : grid(rnd.nextInt(NODES - 1)).cache(ccfg.getName());

    try (QueryCursor<?> cur = cache.query(qry)) {
        cache.registerCacheEntryListener(lsnrCfg);

        if (joinNode) {
            startGrid(NODES);
            awaitPartitionMapExchange();
        }

        for (int i = 0; i < UPDATES; i++)
            cache.put(i, i);

        assertTrue("Failed to wait for local listener invocations: " + latch.getCount(),
            latch.await(3, TimeUnit.SECONDS));

        assertNull(err.get(), err.get());
    }
}
 
Example #28
Source File: GridCacheReplicatedPreloadSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If test failed.
 */
@Test
public void testExternalClassesAtConfiguration() throws Exception {
    try {
        extClassloadingAtCfg = true;
        useExtClassLoader = true;

        Ignite g1 = startGrid(1);

        Ignite g2 = startGrid(2);  // Checks deserialization at node join.

        Ignite g3 = startClientGrid(3);

        IgniteCache<Integer, Object> cache1 = g1.cache(DEFAULT_CACHE_NAME);
        IgniteCache<Integer, Object> cache2 = g2.cache(DEFAULT_CACHE_NAME);
        IgniteCache<Integer, Object> cache3 = g3.cache(DEFAULT_CACHE_NAME);

        final Class<CacheEntryListener> cls1 = (Class<CacheEntryListener>) getExternalClassLoader().
            loadClass("org.apache.ignite.tests.p2p.CacheDeploymentCacheEntryListener");
        final Class<CacheEntryEventSerializableFilter> cls2 = (Class<CacheEntryEventSerializableFilter>) getExternalClassLoader().
            loadClass("org.apache.ignite.tests.p2p.CacheDeploymentCacheEntryEventSerializableFilter");

        CacheEntryListenerConfiguration<Integer, Object> lsnrCfg = new MutableCacheEntryListenerConfiguration<>(
            new Factory<CacheEntryListener<Integer, Object>>() {
                @Override public CacheEntryListener<Integer, Object> create() {
                    try {
                        return cls1.newInstance();
                    }
                    catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            },
            new ClassFilterFactory(cls2),
            true,
            true
        );

        cache1.registerCacheEntryListener(lsnrCfg);

        cache1.put(1, 1);

        assertEquals(1, cache2.get(1));
        assertEquals(1, cache3.get(1));
    }
    finally {
        extClassloadingAtCfg = false;
        useExtClassLoader = false;
    }
}
 
Example #29
Source File: CacheContinuousQueryFactoryFilterRandomOperationTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param cacheName Cache name.
 * @param nodeIdx Node index.
 * @param curs Cursors.
 * @param lsnrCfgs Listener configurations.
 * @return Event queue
 */
private BlockingQueue<CacheEntryEvent<?, ?>> registerListener(String cacheName,
    int nodeIdx,
    Collection<QueryCursor<?>> curs,
    Collection<T2<Integer, MutableCacheEntryListenerConfiguration>> lsnrCfgs,
    boolean sync) {
    final BlockingQueue<CacheEntryEvent<?, ?>> evtsQueue = new ArrayBlockingQueue<>(50_000);

    if (ThreadLocalRandom.current().nextBoolean()) {
        MutableCacheEntryListenerConfiguration<QueryTestKey, QueryTestValue> lsnrCfg =
            new MutableCacheEntryListenerConfiguration<>(
                FactoryBuilder.factoryOf(new LocalNonSerialiseListener() {
                    @Override protected void onEvents(Iterable<CacheEntryEvent<? extends QueryTestKey,
                        ? extends QueryTestValue>> evts) {
                        for (CacheEntryEvent<?, ?> evt : evts)
                            evtsQueue.add(evt);
                    }
                }),
                createFilterFactory(),
                true,
                sync
            );

        grid(nodeIdx).cache(cacheName).registerCacheEntryListener((CacheEntryListenerConfiguration)lsnrCfg);

        lsnrCfgs.add(new T2<Integer, MutableCacheEntryListenerConfiguration>(nodeIdx, lsnrCfg));
    }
    else {
        ContinuousQuery<QueryTestKey, QueryTestValue> qry = new ContinuousQuery<>();

        qry.setLocalListener(new CacheEntryUpdatedListener<QueryTestKey, QueryTestValue>() {
            @Override public void onUpdated(Iterable<CacheEntryEvent<? extends QueryTestKey,
                ? extends QueryTestValue>> evts) throws CacheEntryListenerException {
                for (CacheEntryEvent<?, ?> evt : evts)
                    evtsQueue.add(evt);
            }
        });

        qry.setRemoteFilterFactory(createFilterFactory());

        QueryCursor<?> cur = grid(nodeIdx).cache(cacheName).query(qry);

        curs.add(cur);
    }

    return evtsQueue;
}
 
Example #30
Source File: CacheContinuousQueryFactoryFilterRandomOperationTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override protected void doTestContinuousQuery(CacheConfiguration<Object, Object> ccfg, ContinuousDeploy deploy)
    throws Exception {
    ignite(0).createCache(ccfg);

    try {
        long seed = System.currentTimeMillis();

        Random rnd = new Random(seed);

        log.info("Random seed: " + seed);

        List<BlockingQueue<CacheEntryEvent<?, ?>>> evtsQueues = new ArrayList<>();

        Collection<QueryCursor<?>> curs = new ArrayList<>();

        Collection<T2<Integer, MutableCacheEntryListenerConfiguration>> lsnrCfgs = new ArrayList<>();

        if (deploy == CLIENT)
            evtsQueues.add(registerListener(ccfg.getName(), NODES - 1, curs, lsnrCfgs, rnd.nextBoolean()));
        else if (deploy == SERVER)
            evtsQueues.add(registerListener(ccfg.getName(), rnd.nextInt(NODES - 1), curs, lsnrCfgs,
                rnd.nextBoolean()));
        else {
            boolean isSync = rnd.nextBoolean();

            for (int i = 0; i < NODES - 1; i++)
                evtsQueues.add(registerListener(ccfg.getName(), i, curs, lsnrCfgs, isSync));
        }

        ConcurrentMap<Object, Object> expData = new ConcurrentHashMap<>();

        Map<Integer, Long> partCntr = new ConcurrentHashMap<>();

        try {
            for (int i = 0; i < ITERATION_CNT; i++) {
                if (i % 10 == 0)
                    log.info("Iteration: " + i);

                for (int idx = 0; idx < NODES; idx++)
                    randomUpdate(rnd, evtsQueues, expData, partCntr, grid(idx).cache(ccfg.getName()));
            }
        }
        finally {
            for (QueryCursor<?> cur : curs)
                cur.close();

            for (T2<Integer, MutableCacheEntryListenerConfiguration> e : lsnrCfgs)
                grid(e.get1()).cache(ccfg.getName()).deregisterCacheEntryListener(e.get2());
        }
    }
    finally {
        ignite(0).destroyCache(ccfg.getName());
    }
}