javax.cache.event.CacheEntryListener Java Examples

The following examples show how to use javax.cache.event.CacheEntryListener. 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: 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 #2
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 #3
Source File: EventListenerAdaptors.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
static <K, V> List<EventListenerAdaptor<K, V>> ehListenersFor(CacheEntryListener<? super K, ? super V> listener,
    CacheEntryEventFilter<? super K, ? super V> filter, Cache<K, V> source, boolean requestsOld) {
  List<EventListenerAdaptor<K, V>> rv = new ArrayList<>();

  if (listener instanceof CacheEntryUpdatedListener) {
    rv.add(new UpdatedAdaptor<>(source, (CacheEntryUpdatedListener<K, V>) listener,
      (CacheEntryEventFilter<K, V>) filter, requestsOld));
  }
  if (listener instanceof CacheEntryCreatedListener) {
    rv.add(new CreatedAdaptor<>(source, (CacheEntryCreatedListener<K, V>) listener,
      (CacheEntryEventFilter<K, V>) filter, requestsOld));
  }
  if (listener instanceof CacheEntryRemovedListener) {
    rv.add(new RemovedAdaptor<>(source, (CacheEntryRemovedListener<K, V>) listener,
      (CacheEntryEventFilter<K, V>) filter, requestsOld));
  }
  if (listener instanceof CacheEntryExpiredListener) {
    rv.add(new ExpiredAdaptor<>(source, (CacheEntryExpiredListener<K, V>) listener,
      (CacheEntryEventFilter<K, V>) filter, requestsOld));
  }

  return rv;
}
 
Example #4
Source File: CacheEntryListenerClient.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Override
public void onExpired(Iterable<CacheEntryEvent<? extends K, ? extends V>> cacheEntryEvents) throws CacheEntryListenerException {
  if (isDirectCallable()) {
    for (CacheEntryListener<K,V> l : listenerServer.getListeners()) {
      if (l instanceof CacheEntryExpiredListener) {
        ((CacheEntryExpiredListener<K,V>) l).onExpired(cacheEntryEvents);
      }
    }
    return;
  }
  // since ExpiryEvents are processed asynchronously, this may cause issues.
  // the test do not currently delay waiting for asynchronous expiry events to complete processing.
  // not breaking anything now, so leaving in for time being.
  for (CacheEntryEvent<? extends K, ? extends V> event : cacheEntryEvents) {
    getClient().invoke(new OnCacheEntryEventHandler<K, V>(event));
  }
}
 
Example #5
Source File: ListenerEntry.java    From triava with Apache License 2.0 6 votes vote down vote up
@Override
public void run()
{
	@SuppressWarnings("unchecked")
	CacheEntryListener<K, V> listenerRef = (CacheEntryListener<K, V>) listener;

	while (running)
	{
		try
		{
			TCacheEntryEventCollection<K, V> eventColl = dispatchQueue.take();
			sendEvents(eventColl, listenerRef);
		}
		catch (InterruptedException ie)
		{
			// Interruption policy: Only used for quitting
		}
		catch (Exception exc)
		{
			// If the thread enters this line, there was an issue wit sendEvent(). Likely it
			// is in the user provided Listener code, so we must make sure not to die if this
			// happens. For now we will silently ignore any errors.
		}
	}
}
 
Example #6
Source File: EventHandlingImpl.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Override
public void onCacheClosed(final org.cache2k.Cache cache) {
  Set<CacheEntryListener> ls = new HashSet<CacheEntryListener>();
  for (Listener l : getAllListeners()) {
    ls.add(l.entryListener);
  }
  for (CacheEntryListener cl : ls) {
    if (cl instanceof Closeable) {
      try {
        ((Closeable) cl).close();
      } catch (Exception e) {
        throw new CacheException("closing listener", e);
      }
    }
  }
}
 
Example #7
Source File: CacheEntryListenerServer.java    From cache2k with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an CacheLoaderServer.
 *
 * @param port        the port on which to accept {@link org.jsr107.tck.integration.CacheLoaderClient} request.
 * @param keyClass    the class for entry key
 * @param valueClass  the class for entry value
 */
public CacheEntryListenerServer(int port, Class keyClass, Class valueClass) {
  super(port);
  this.listeners = new HashSet<CacheEntryListener<K, V>>();

  // establish the client-server operation handlers
  for (EventType eventType : EventType.values()) {
    addOperationHandler(new CacheEntryEventOperationHandler(eventType, keyClass, valueClass));
  }
}
 
Example #8
Source File: CacheManagerTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test(expected=UnsupportedOperationException.class)
public void no_online_listener_attachment_with_cache2k_defaults() {
  CachingProvider p = Caching.getCachingProvider();
  CacheManager cm = p.getCacheManager();
  MutableConfiguration cfg = ExtendedMutableConfiguration.of(new Cache2kBuilder<Long, Double>(){});
  Cache cache = cm.createCache("mute",  cfg);
  cache.registerCacheEntryListener(new CacheEntryListenerConfiguration() {
    @Override
    public Factory<CacheEntryListener> getCacheEntryListenerFactory() {
      fail("not expected to be called");
      return null;
    }

    @Override
    public boolean isOldValueRequired() {
      return false;
    }

    @Override
    public Factory<CacheEntryEventFilter> getCacheEntryEventFilterFactory() {
      return null;
    }

    @Override
    public boolean isSynchronous() {
      return false;
    }
  });
  cache.close();
}
 
Example #9
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 #10
Source File: BlazingCacheCacheEntryListenerWrapper.java    From blazingcache with Apache License 2.0 5 votes vote down vote up
BlazingCacheCacheEntryListenerWrapper(boolean synchronous, boolean oldValueRequired, CacheEntryListener<K, V> listener, CacheEntryEventFilter<K, V> filter, CacheEntryListenerConfiguration<K, V> configuration, BlazingCacheCache<K, V> parent) {
    this.synchronous = synchronous;
    this.parent = parent;
    this.oldValueRequired = oldValueRequired;
    this.listener = listener;
    this.filter = filter;
    this.configuration = configuration;
    this.onCreate = listener instanceof CacheEntryCreatedListener;
    this.onUpdate = listener instanceof CacheEntryUpdatedListener;
    this.onRemove = listener instanceof CacheEntryRemovedListener;
    this.needPreviousValue = oldValueRequired || onRemove || onUpdate;
}
 
Example #11
Source File: CacheEntryListenerClient.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreated(Iterable<CacheEntryEvent<? extends K, ? extends V>> cacheEntryEvents) throws CacheEntryListenerException {
  if (isDirectCallable()) {
    for (CacheEntryListener<K,V> l : listenerServer.getListeners()) {
      if (l instanceof CacheEntryCreatedListener) {
        ((CacheEntryCreatedListener<K,V>) l).onCreated(cacheEntryEvents);
      }
    }
    return;
  }
  for (CacheEntryEvent<? extends K, ? extends V> event : cacheEntryEvents) {
    getClient().invoke(new OnCacheEntryEventHandler<K, V>(event));
  }
}
 
Example #12
Source File: ListenerEntry.java    From triava with Apache License 2.0 5 votes vote down vote up
/**
 * Schedules to send the events to the given listener. Scheduling means to send immediately if this
 * {@link ListenerEntry} is synchronous, or to put it in a queue if asynchronous (including the forceAsync
 * parameter. For synchronous delivery, it is guaranteed that the listener was executed when returning
 * from this method.
 * <p>
 * The given eventType must match all events
 * 
 * @param events The events to send
 * @param listener The listener to notify
 * @param eventType The event type. It must match all events to send
 * @param forceAsync
 */
private void scheduleEvents(List<CacheEntryEvent<? extends K, ? extends V>> events, CacheEntryListener<K, V> listener,
		EventType eventType, boolean forceAsync)
{
	if (eventManager == null)
		return;
	
	TCacheEntryEventCollection<K, V> eventColl = new TCacheEntryEventCollection<>(events, eventType);
	if (!(forceAsync || dispatchMode.isAsync()))
	{
		sendEvents(eventColl, listener);
	}
	else
	{
		try
		{
			dispatchQueue.put(eventColl);
		}
		catch (InterruptedException e)
		{
			/** Interruption policy:
			 * The #dispatch method can be part of client interaction like a put or get call. Or it can
			 * be from internal operations like eviction. In both cases we do not want to blindly
			 * bubble up the stack until some random code catches it. Reason is, that it could leave the
			 * Cache in an inconsistent state, e.g. a value was put() into the cache but the statistics
			 * do not reflect that. Thus, we simply mark the current thread interrupted, so any caller
			 * on any stack level may inspect the status.
			 */
			Thread.currentThread().interrupt();
			// If we come here, the event may not be in the dispatchQueue. But we will not
			// retry, as there are no guarantees when interrupting and it is safer to just go on.
			// For example if during shutdown the dispatchQueue is full, we would iterate here
			// forever as the DispatchRunnable instance could be shutdown and not read from the
			// queue any longer.
		}
	}
}
 
Example #13
Source File: CacheEntryListenerClient.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Override
public void onRemoved(Iterable<CacheEntryEvent<? extends K, ? extends V>> cacheEntryEvents) throws CacheEntryListenerException {
  if (isDirectCallable()) {
    for (CacheEntryListener<K,V> l : listenerServer.getListeners()) {
      if (l instanceof CacheEntryRemovedListener) {
        ((CacheEntryRemovedListener<K,V>) l).onRemoved(cacheEntryEvents);
      }
    }
    return;
  }
  for (CacheEntryEvent<? extends K, ? extends V> event : cacheEntryEvents) {
    getClient().invoke(new OnCacheEntryEventHandler<K, V>(event));
  }
}
 
Example #14
Source File: CacheEntryListenerClient.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Override
public void onUpdated(Iterable<CacheEntryEvent<? extends K, ? extends V>> cacheEntryEvents)
  throws CacheEntryListenerException {
  if (isDirectCallable()) {
    for (CacheEntryListener<K,V> l : listenerServer.getListeners()) {
      if (l instanceof CacheEntryUpdatedListener) {
        ((CacheEntryUpdatedListener<K,V>) l).onUpdated(cacheEntryEvents);
      }
    }
    return;
  }
  for (CacheEntryEvent<? extends K, ? extends V> event : cacheEntryEvents) {
    getClient().invoke(new OnCacheEntryEventHandler<K, V>(event));
  }
}
 
Example #15
Source File: ListenerEntry.java    From triava with Apache License 2.0 5 votes vote down vote up
private void sendEvents(TCacheEntryEventCollection<K, V> eventColl, CacheEntryListener<K, V> listener)
	{
		EventType eventType = eventColl.eventType();
//		System.out.println("sendEvents to listener " + listener + ", eventType=" + eventColl.eventType());
		switch (eventType)
        {
            case CREATED:
                if (listener instanceof CacheEntryCreatedListener)
                    eventManager.created((CacheEntryCreatedListener<K, V>)listener, eventColl);
                break;

            case EXPIRED:
                if (listener instanceof CacheEntryExpiredListener)
                    eventManager.expired((CacheEntryExpiredListener<K, V>)listener,  eventColl);
                break;

            case UPDATED:
                if (listener instanceof CacheEntryUpdatedListener)
                    eventManager.updated((CacheEntryUpdatedListener<K,V>)listener,  eventColl);
                break;

            case REMOVED:
                if (listener instanceof CacheEntryRemovedListener)
                    eventManager.removed((CacheEntryRemovedListener<K,V>)listener,  eventColl);
                break;

            default:
                // By default do nothing. If new event types are added to the Spec, they will be ignored.
        }
	}
 
Example #16
Source File: CacheEntryListenerServer.java    From cache2k with Apache License 2.0 5 votes vote down vote up
/**
 * Set the {@link javax.cache.event.CacheEntryListener} the {@link CacheEntryListenerServer} should use
 * from now on.
 *
 * @param cacheEventListener the {@link javax.cache.event.CacheEntryListener}
 */
public void addCacheEventListener(CacheEntryListener<K, V> cacheEventListener) {
  if (cacheEventListener == null) {
    throw new NullPointerException();
  }
  this.listeners.add(cacheEventListener);
}
 
Example #17
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 #18
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 #19
Source File: ConfigVariations.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public Factory<CacheEntryListener> getCacheEntryListenerFactory() {
    return new Factory<CacheEntryListener>() {
        @Override public CacheEntryListener create() {
            return new NoopCacheEntryListener();
        }
    };
}
 
Example #20
Source File: CacheContinuousQueryHandler.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Performs resource injection and checks asynchrony for the provided local listener.
 *
 * @param lsnr Local listener.
 * @param ctx Kernal context.
 * @throws IgniteCheckedException If failed to perform resource injection.
 */
private void initLocalListener(CacheEntryListener lsnr, GridKernalContext ctx) throws IgniteCheckedException {
    if (lsnr != null) {
        CacheEntryListener impl =
            lsnr instanceof JCacheQueryLocalListener
                ? ((JCacheQueryLocalListener)lsnr).impl
                : lsnr;

        ctx.resource().injectGeneric(impl);

        asyncCb = U.hasAnnotation(impl, IgniteAsyncCallback.class);
    }
}
 
Example #21
Source File: CacheContinuousQueryManager.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param impl Listener.
 * @param log Logger.
 */
JCacheQueryLocalListener(CacheEntryListener<K, V> impl, IgniteLogger log) {
    assert impl != null;
    assert log != null;

    this.impl = impl;

    this.log = log;
}
 
Example #22
Source File: CacheEntryListenerServer.java    From cache2k with Apache License 2.0 5 votes vote down vote up
private void runHandlers(EventType eventType, TestCacheEntryEvent event) {
  ArrayList events = new ArrayList(1);
  events.add(event);

  for (CacheEntryListener listener : listeners) {
    switch (eventType) {
      case CREATED :
        if (listener instanceof CacheEntryCreatedListener) {
          ((CacheEntryCreatedListener) listener).onCreated(events);
        }
        break;

      case UPDATED:
        if (listener instanceof CacheEntryUpdatedListener) {
          ((CacheEntryUpdatedListener) listener).onUpdated(events);
        }
        break;

      case REMOVED:
        if (listener instanceof CacheEntryRemovedListener) {
          ((CacheEntryRemovedListener) listener).onRemoved(events);
        }
        break;

      case EXPIRED:
        if (listener instanceof CacheEntryExpiredListener) {
          ((CacheEntryExpiredListener) listener).onExpired(events);
        }
        break;

      default:
        break;
    }
  }
}
 
Example #23
Source File: CacheEntryListenerServer.java    From cache2k with Apache License 2.0 4 votes vote down vote up
public void removeCacheEventListener(CacheEntryListener<K, V> cacheEventListener) {
  if (cacheEventListener != null) {
    listeners.remove(cacheEventListener);
  }
}
 
Example #24
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 #25
Source File: CacheEntryListenerServer.java    From cache2k with Apache License 2.0 4 votes vote down vote up
public Set<CacheEntryListener<K, V>> getListeners() {
  return listeners;
}
 
Example #26
Source File: EventTypeFilterTest.java    From caffeine with Apache License 2.0 4 votes vote down vote up
@Test
public void equals_false() {
  EventTypeFilter<Integer, Integer> other = new EventTypeFilter<>(
      Mockito.mock(CacheEntryListener.class), Mockito.mock(CacheEntryEventFilter.class));
  assertThat(filter, is(not(equalTo(other))));
}
 
Example #27
Source File: EventTypeFilter.java    From caffeine with Apache License 2.0 4 votes vote down vote up
public EventTypeFilter(CacheEntryListener<? super K, ? super V> listener,
    CacheEntryEventFilter<? super K, ? super V> filter) {
  this.listener = requireNonNull(listener);
  this.filter = requireNonNull(filter);
}
 
Example #28
Source File: EventTypeAwareListener.java    From caffeine with Apache License 2.0 4 votes vote down vote up
public EventTypeAwareListener(CacheEntryListener<? super K, ? super V> listener) {
  this.listener = requireNonNull(listener);
}
 
Example #29
Source File: Listener.java    From cache2k with Apache License 2.0 4 votes vote down vote up
public Listener(final CacheEntryListenerConfiguration<K, V> _config,
                final CacheEntryEventFilter<K, V> _filter, final CacheEntryListener<K,V> _entryListener) {
  config = _config;
  filter = _filter;
  entryListener = _entryListener;
}
 
Example #30
Source File: ConfigurationMergerTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Override
public Factory<CacheEntryListener<? super Object, ? super Object>> getCacheEntryListenerFactory() {
  throw new UnsupportedOperationException("BOOM");
}