001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.commons.jcs.jcache;
020
021import java.util.Arrays;
022import java.util.Map;
023
024import javax.cache.Cache;
025import javax.cache.configuration.CacheEntryListenerConfiguration;
026import javax.cache.event.CacheEntryEvent;
027import javax.cache.event.EventType;
028
029import org.apache.commons.jcs.engine.behavior.ICacheElement;
030import org.apache.commons.jcs.engine.behavior.ICompositeCacheAttributes;
031import org.apache.commons.jcs.engine.behavior.IElementAttributes;
032import org.apache.commons.jcs.engine.control.CompositeCache;
033
034// allows us to plug some lifecycle callbacks on the core cache without impacting too much the core
035public class ExpiryAwareCache<A, B> extends CompositeCache<A, B>
036{
037    private Map<CacheEntryListenerConfiguration<A, B>, JCSListener<A, B>> listeners;
038    private Cache<A, B> cacheRef;
039
040    ExpiryAwareCache(final ICompositeCacheAttributes cattr, final IElementAttributes attr)
041    {
042        super(cattr, attr);
043    }
044
045    @Override
046    protected void doExpires(final ICacheElement<A, B> element)
047    {
048        super.doExpires(element);
049        for (final JCSListener<A, B> listener : listeners.values())
050        {
051            listener.onExpired(Arrays.<CacheEntryEvent<? extends A, ? extends B>> asList(new JCSCacheEntryEvent<A, B>(
052                    cacheRef, EventType.REMOVED, null, element.getKey(), element.getVal())));
053        }
054    }
055
056    void init(final Cache<A, B> cache, final Map<CacheEntryListenerConfiguration<A, B>, JCSListener<A, B>> listeners)
057    {
058        this.cacheRef = cache;
059        this.listeners = listeners;
060    }
061}