javax.cache.event.EventType Java Examples

The following examples show how to use javax.cache.event.EventType. 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: CacheContinuousQueryEntry.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param cacheId Cache ID.
 * @param evtType Event type.
 * @param key Key.
 * @param newVal New value.
 * @param oldVal Old value.
 * @param keepBinary Keep binary flag.
 * @param part Partition.
 * @param updateCntr Update partition counter.
 * @param topVer Topology version if applicable.
 * @param flags Flags.
 */
CacheContinuousQueryEntry(
    int cacheId,
    EventType evtType,
    KeyCacheObject key,
    @Nullable CacheObject newVal,
    @Nullable CacheObject oldVal,
    boolean keepBinary,
    int part,
    long updateCntr,
    @Nullable AffinityTopologyVersion topVer,
    byte flags) {
    this.cacheId = cacheId;
    this.evtType = evtType;
    this.key = key;
    this.newVal = newVal;
    this.oldVal = oldVal;
    this.part = part;
    this.updateCntr = updateCntr;
    this.topVer = topVer;
    this.flags = flags;

    if (keepBinary)
        this.flags |= KEEP_BINARY;
}
 
Example #2
Source File: ListenerCollection.java    From triava with Apache License 2.0 6 votes vote down vote up
/**
 * Rebuild the listenerPresent lookup array 
 */
private void rebuildListenerPresent()
{
	short listenerPresentXnew = 0;
	for (ListenerEntry<K, V> listener : listeners)
	{
		for (EventType eventType : EventType.values())
		{
			if (listener.isListeningFor(eventType))
			{
				listenerPresentXnew |= (1 << eventType.ordinal());
			}
		}
	}

	listenerPresentMask = listenerPresentXnew;
}
 
Example #3
Source File: ListenerCollection.java    From triava with Apache License 2.0 6 votes vote down vote up
/**
 * Enables a listener, without adding it to the Configuration. An  enabled listener can send events after this method returns.  
 * The caller must make sure that the
 * corresponding Configuration object reflects the change.
 * 
 * @param listenerConfiguration
 * @return
 */
private synchronized boolean enableCacheEntryListener(CacheEntryListenerConfiguration<K, V> listenerConfiguration)
{
	DispatchMode dispatchMode = listenerConfiguration.isSynchronous() ? DispatchMode.SYNC : DispatchMode.ASYNC_TIMED;
	ListenerEntry<K, V> newListener = new ListenerEntry<K, V>(listenerConfiguration, tcache, dispatchMode);
	boolean added = listeners.add(newListener);
	for (EventType eventType : EventType.values())
	{
		if (newListener.isListeningFor(eventType))
		{
			listenerPresentMask |= (1 << eventType.ordinal());
		}
	}

	return added;
}
 
Example #4
Source File: ListenerCollection.java    From triava with Apache License 2.0 6 votes vote down vote up
/**
 * Notifies all listeners that a given EventType has happened for all the given entries.
 * You can force all listeners to Async mode, but should only do this if it is compliant with JSR107.
 * <p>
 * <b>IMPORTANT PERFORMANCE NOTE</b>: To avoid unnecessary object creation (TCacheEntryEvent and the event
 * Iterable), you SHOULD check with {@link #hasListenerFor(EventType)} whether there is any Listener
 * interested in the given eventType. If not, do you can spare to create the TCacheEntryEvent events.
 * 
 * @param entries The key-value pairs for which to send events
 * @param eventType The event Type
 * @param forceAsync Force async mode
 */
public void dispatchEvents(Map<K, V> entries, EventType eventType, boolean forceAsync)
{
	if (!hasListenerFor(eventType))
	{
		return;
	}
	
	List<TCacheEntryEvent<K,V>> events = new ArrayList<>(entries.size());
	for (Entry<K, V> entry : entries.entrySet())
	{
		K key = entry.getKey();
		V value = entry.getValue();
		TCacheEntryEvent<K,V> event = new TCacheEntryEvent<>(jsr107cache, eventType, key, value);
		events.add(event);
	}
	dispatchEventsToListeners(events, eventType, forceAsync);
}
 
Example #5
Source File: ListenerEntry.java    From triava with Apache License 2.0 6 votes vote down vote up
/**
 * Returns whether this {@link ListenerEntry} is listening to the given eventType
 * @param eventType The event Type
 * @return true, if the listener is listening to the given eventType
 */
boolean isListeningFor(EventType eventType)
{
	switch (eventType)
	{
		case CREATED:
			return listener instanceof CacheEntryCreatedListener;
		case EXPIRED:
			return listener instanceof CacheEntryExpiredListener;
		case REMOVED:
			return listener instanceof CacheEntryRemovedListener;
		case UPDATED:
			return listener instanceof CacheEntryUpdatedListener;
	}

	return false;
}
 
Example #6
Source File: CacheContinuousQueryManager.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param evtType Type.
 * @return Flag value.
 */
private byte flag(EventType evtType) {
    switch (evtType) {
        case CREATED:
            return CREATED_FLAG;

        case UPDATED:
            return UPDATED_FLAG;

        case REMOVED:
            return REMOVED_FLAG;

        case EXPIRED:
            return EXPIRED_FLAG;

        default:
            throw new IllegalStateException("Unknown type: " + evtType);
    }
}
 
Example #7
Source File: TCacheJSR107.java    From triava with Apache License 2.0 6 votes vote down vote up
@Override
public boolean replace(K key, V oldValue, V newValue)
{
	throwISEwhenClosed();
	kvUtil.verifyKeyAndValueNotNull(key, newValue);
	kvUtil.verifyValueNotNull(oldValue);
	
	boolean replaced = false;
	Action<K, V, Object> action = new ReplaceAction<K, V, Object>(key, newValue, EventType.UPDATED);
	if (actionRunnerWriteBehind.preMutate(action))
	{
		ChangeStatus changeStatus = tcache.replace(key, oldValue, newValue);
		actionRunnerWriteBehind.postMutate(action, changeStatus);
		replaced = changeStatus == ChangeStatus.CHANGED;
	}

	return replaced;
}
 
Example #8
Source File: TCacheJSR107.java    From triava with Apache License 2.0 6 votes vote down vote up
@Override
public boolean putIfAbsent(K key, V value)
{
	throwISEwhenClosed();

	PutAction<K,V,Object> action = new PutAction<>(key, value, EventType.CREATED, false);
	boolean added = false;
	if (actionRunnerWriteBehind.preMutate(action))
	{
		Holders<V> holders = tcache.putIfAbsentH(key, value);
		// For JSR107 putIfAbsent() should return whether a value was set.
		// It is set when the old holder was null AND the new holder is not null.
		// The latter case (new holder == null) can happen if it immediately expires.
		added = holders.oldHolder == null && holders.newHolder != null;
		if (added)
			actionRunnerWriteBehind.postMutate(action);
	}

	return added;
}
 
Example #9
Source File: TCacheJSR107.java    From triava with Apache License 2.0 6 votes vote down vote up
void put0(K key, V value, boolean writeThrough)
{
	throwISEwhenClosed();
	kvUtil.verifyKeyAndValueNotNull(key, value);

	Action<K,V,Object> action = new PutAction<>(key, value, EventType.CREATED, false, writeThrough);

	if (actionRunner.preMutate(action))
	{
		Holders<V> holders = tcache.putToMapI(key, value, tcache.cacheTimeSpread(), false);
		final EventType eventType;
		if (holders == null)
			eventType = null;
		else
		{
			if (holders.newHolder == null || holders.newHolder.isInvalid())
				eventType = null; // new is invalid
			else
				eventType = holders.oldHolder == null ? EventType.CREATED : EventType.UPDATED;
		}
		action.setEventType(eventType);
		actionRunner.postMutate(action);	
	}
	action.close();
}
 
Example #10
Source File: TCacheJSR107.java    From triava with Apache License 2.0 6 votes vote down vote up
@Override
public V getAndReplace(K key, V value)
{
	throwISEwhenClosed();

	Action<K, V, Object> action = new ReplaceAction<K, V, Object>(key, value, EventType.UPDATED);
	V oldValue = null;
	if (actionRunnerWriteBehind.preMutate(action))
	{
		oldValue = tcache.getAndReplace(key, value);
		boolean replaced = oldValue != null;
		ChangeStatus changeStatus = replaced ? ChangeStatus.CHANGED : ChangeStatus.UNCHANGED;
		actionRunnerWriteBehind.postMutate(action, changeStatus);
	}
	action.close();
	return oldValue;				
}
 
Example #11
Source File: BlazingCacheCacheEntryListenerWrapper.java    From blazingcache with Apache License 2.0 5 votes vote down vote up
void onEntryUpdated(K key, V oldValue, V value) {
    if (onUpdate) {
        BlazingCacheCacheEntryEvent event = new BlazingCacheCacheEntryEvent(key, oldValue, value, parent, EventType.UPDATED, true);
        if (filter != null && !filter.evaluate(event)) {
            return;
        }
        ((CacheEntryUpdatedListener) listener).onUpdated(Arrays.asList(event));
    }
}
 
Example #12
Source File: CacheContinuousQueryManager.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param src Event source.
 * @param evtType Event type.
 * @param key Key.
 * @param val Value.
 */
public CacheEntryEventImpl(Cache src, EventType evtType, Object key, Object val) {
    super(src, evtType);

    this.key = key;
    this.val = val;
}
 
Example #13
Source File: AsyncDispatcher.java    From cache2k with Apache License 2.0 5 votes vote down vote up
boolean removeAsyncListener(CacheEntryListenerConfiguration<K,V> cfg) {
  boolean _found = false;
  for (EventType t : EventType.values()) {
    _found |= EventHandlingImpl.removeCfgMatch(cfg, asyncListenerByType.get(t));
  }
  return _found;
}
 
Example #14
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 #15
Source File: CacheContinuousQueryRandomOperationsTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param event Event.
 * @param type Event type.
 * @param val Value.
 * @param oldVal Old value.
 */
private void checkSingleEvent(
    CacheEntryEvent<? extends QueryTestKey, ? extends QueryTestValue> event,
    EventType type,
    QueryTestValue val,
    QueryTestValue oldVal) {
    assertEquals(event.getEventType(), type);
    assertEquals(event.getValue(), val);
    assertEquals(event.getOldValue(), oldVal);
}
 
Example #16
Source File: IgniteCacheEntryListenerAbstractTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param iter Received events iterator.
 * @param expKey Expected key.
 * @param expType Expected type.
 * @param expVal Expected value.
 * @param expOld Expected old value.
 */
private void checkEvent(Iterator<CacheEntryEvent<?, ?>> iter,
    Integer expKey,
    EventType expType,
    @Nullable Integer expVal,
    @Nullable Integer expOld) {
    assertTrue(iter.hasNext());

    CacheEntryEvent<?, ?> evt = iter.next();

    iter.remove();

    assertTrue(evt.getSource() instanceof IgniteCacheProxy);

    assertEquals(key(expKey), evt.getKey());

    assertEquals(expType, evt.getEventType());

    assertEquals(value(expVal), evt.getValue());

    assertEquals(value(expOld), evt.getOldValue());

    if (expOld == null)
        assertFalse(evt.isOldValueAvailable());
    else
        assertTrue(evt.isOldValueAvailable());
}
 
Example #17
Source File: Cache.java    From triava with Apache License 2.0 5 votes vote down vote up
/**
 * Releases the given holder and sends an EXPIRED notification
 * @param key
 * @param holder
 * @return
 */
boolean expireEntry(K key, AccessTimeObjectHolder<V> holder)
{
	V value = holder.peek();
	boolean removed = holder.release();
	if (removed) // SAE-150 Verify removal
	{
		listeners.dispatchEvent(EventType.EXPIRED, key, value);
	}
	
	return removed;
}
 
Example #18
Source File: EventHandlingImpl.java    From cache2k with Apache License 2.0 5 votes vote down vote up
private void fireCreated(final javax.cache.Cache<K, V> _jCache, final CacheEntry<K, V> e) {
  EntryEvent<K, V> cee =
    new EntryEvent<K, V>(_jCache, EventType.CREATED, e.getKey(), extractValue(e.getValue()));
  asyncDispatcher.deliverAsyncEvent(cee);
  for (Listener<K,V> t : createdListener) {
    t.fire(cee);
  }
}
 
Example #19
Source File: BlazingCacheCacheEntryListenerWrapper.java    From blazingcache with Apache License 2.0 5 votes vote down vote up
public BlazingCacheCacheEntryEvent(K key, V oldValue, V value, Cache source, EventType eventType, boolean oldValuePresent) {
    super(source, eventType);
    this.key = key;
    this.oldValue = oldValue;
    this.value = value;
    this.oldValuePresent = oldValuePresent && needPreviousValue;
}
 
Example #20
Source File: BlazingCacheCacheEntryListenerWrapper.java    From blazingcache with Apache License 2.0 5 votes vote down vote up
void onEntryCreated(K key, V value) {
    if (onCreate) {
        BlazingCacheCacheEntryEvent event = new BlazingCacheCacheEntryEvent(key, null, value, parent, EventType.CREATED, false);
        if (filter != null && !filter.evaluate(event)) {
            return;
        }
        ((CacheEntryCreatedListener) listener).onCreated(Arrays.asList(event));
    }
}
 
Example #21
Source File: IgniteCacheSourceTaskCQ.java    From spring-boot-akka-event-sourcing-starter with Apache License 2.0 5 votes vote down vote up
@Override
public boolean evaluate(CacheEntryEvent<?, ? extends BinaryObject> evt) throws CacheEntryListenerException {
	Affinity<Object> affinity = ignite.affinity(evt.getSource().getName());

	if (evt.getEventType().equals(EventType.CREATED) || evt.getEventType().equals(EventType.UPDATED) && affinity.isPrimary(ignite.cluster().localNode(), evt.getKey())) {
		// Process this event. Ignored on backups.
		return filter == null || !filter.apply(evt);
	}
	return false;
}
 
Example #22
Source File: BlazingCacheCacheEntryListenerWrapper.java    From blazingcache with Apache License 2.0 5 votes vote down vote up
void onEntryRemoved(K key, V oldValue) {
    if (onRemove) {
        BlazingCacheCacheEntryEvent event = new BlazingCacheCacheEntryEvent(key, oldValue, oldValue, parent, EventType.REMOVED, true);
        if (filter != null && !filter.evaluate(event)) {
            return;
        }
        ((CacheEntryRemovedListener) listener).onRemoved(Arrays.asList(event));
    }
}
 
Example #23
Source File: UnwrapTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCacheEntryEventUnwrap() {
  MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
  configuration.setTypes(String.class, String.class);
  Cache<String, String> cache = cacheManager.createCache("cache", configuration);
  org.ehcache.event.CacheEvent<String, String> ehEvent = new EhEvent();
  Eh107CacheEntryEvent<String, String> cacheEntryEvent = new Eh107CacheEntryEvent.NormalEvent<>(cache, EventType.CREATED, ehEvent, false);
  assertThat(cacheEntryEvent.unwrap(org.ehcache.event.CacheEvent.class), is(instanceOf(CacheEvent.class)));
  assertThat(cacheEntryEvent.unwrap(cacheEntryEvent.getClass()), is(instanceOf(Eh107CacheEntryEvent.NormalEvent.class)));
}
 
Example #24
Source File: JCacheEntryEvent.java    From caffeine with Apache License 2.0 5 votes vote down vote up
JCacheEntryEvent(Cache<K, V> source, EventType eventType,
    K key, boolean hasOldValue, @Nullable V oldValue, @Nullable V newValue) {
  super(source, eventType);
  this.key = requireNonNull(key);
  this.hasOldValue = hasOldValue;
  this.oldValue = oldValue;
  this.newValue = newValue;
}
 
Example #25
Source File: EventTypeAwareListener.java    From caffeine with Apache License 2.0 5 votes vote down vote up
/** Returns if the backing listener consumes this type of event. */
@SuppressWarnings("PMD.SwitchStmtsShouldHaveDefault")
public boolean isCompatible(@NonNull EventType eventType) {
  switch (eventType) {
    case CREATED:
      return (listener instanceof CacheEntryCreatedListener<?, ?>);
    case UPDATED:
      return (listener instanceof CacheEntryUpdatedListener<?, ?>);
    case REMOVED:
      return (listener instanceof CacheEntryRemovedListener<?, ?>);
    case EXPIRED:
      return (listener instanceof CacheEntryExpiredListener<?, ?>);
  }
  throw new IllegalStateException("Unknown event type: " + eventType);
}
 
Example #26
Source File: EventDispatcher.java    From caffeine with Apache License 2.0 5 votes vote down vote up
/** Broadcasts the event to all of the interested listener's dispatch queues. */
private void publish(Cache<K, V> cache, EventType eventType, K key,
    boolean hasOldValue, @Nullable V oldValue, @Nullable V newValue, boolean quiet) {
  if (dispatchQueues.isEmpty()) {
    return;
  }

  JCacheEntryEvent<K, V> event = null;
  for (Registration<K, V> registration : dispatchQueues.keySet()) {
    if (!registration.getCacheEntryListener().isCompatible(eventType)) {
      continue;
    }
    if (event == null) {
      event = new JCacheEntryEvent<>(cache, eventType, key, hasOldValue, oldValue, newValue);
    }
    if (!registration.getCacheEntryFilter().evaluate(event)) {
      continue;
    }

    JCacheEntryEvent<K, V> e = event;
    CompletableFuture<Void> future =
        dispatchQueues.computeIfPresent(registration, (k, queue) -> {
          Runnable action = () -> registration.getCacheEntryListener().dispatch(e);
          return queue.thenRunAsync(action, executor);
        });
    if ((future != null) && registration.isSynchronous() && !quiet) {
      pending.get().add(future);
    }
  }
}
 
Example #27
Source File: ExpiryAwareCache.java    From commons-jcs with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExpires(final ICacheElement<A, B> element)
{
    super.doExpires(element);
    for (final JCSListener<A, B> listener : listeners.values())
    {
        listener.onExpired(Arrays.<CacheEntryEvent<? extends A, ? extends B>> asList(new JCSCacheEntryEvent<>(
                cacheRef, EventType.REMOVED, null, element.getKey(), element.getVal())));
    }
}
 
Example #28
Source File: EventHandlingImpl.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Override
public void onEntryRemoved(final Cache<K, V> c, final CacheEntry<K, V> e) {
  if (e.getException() != null) {
    return;
  }
  javax.cache.Cache<K,V> _jCache = getCache(c);
  V val = extractValue(e.getValue());
  EntryEvent<K, V> cee =
    new EntryEventWithOldValue<K, V>(_jCache, EventType.REMOVED, e.getKey(), val, val);
  asyncDispatcher.deliverAsyncEvent(cee);
  for (Listener<K,V> t : removedListener) {
    t.fire(cee);
  }
}
 
Example #29
Source File: AdditionalCacheListenerTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
/**
 * Test whether async events arrive and are in correct order. Also test with negative key.
 */
@Test
public void testInOrder() throws Exception {
  int KEY = -123;
  cache.put(KEY, "hello");
  cache.put(KEY, "mike");
  cache.remove(KEY);
  listener.await(3, 60 * 1000);
  assertEquals(
    Arrays.asList(EventType.CREATED, EventType.UPDATED, EventType.REMOVED),
    listener.extractLogForKey(KEY));
}
 
Example #30
Source File: AdditionalCacheListenerTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
public List<EventType> extractLogForKey(K key) {
  List<EventType> l = new ArrayList<>();
  for (RecordedEvent<K> e : log) {
    if (e.key.equals(key)) {
      l.add(e.type);
    }
  }
  return l;
}