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.wiki.cache;
020
021import net.sf.ehcache.Cache;
022import net.sf.ehcache.CacheManager;
023import net.sf.ehcache.Ehcache;
024import net.sf.ehcache.Element;
025import net.sf.ehcache.event.CacheEventListenerAdapter;
026import org.apache.logging.log4j.LogManager;
027import org.apache.logging.log4j.Logger;
028import org.apache.wiki.api.core.Engine;
029import org.apache.wiki.api.engine.Initializable;
030import org.apache.wiki.api.exceptions.WikiException;
031import org.apache.wiki.util.CheckedSupplier;
032import org.apache.wiki.util.TextUtil;
033
034import java.io.Serializable;
035import java.net.URL;
036import java.util.Collections;
037import java.util.List;
038import java.util.Map;
039import java.util.Properties;
040import java.util.concurrent.ConcurrentHashMap;
041import java.util.concurrent.atomic.AtomicBoolean;
042
043
044/**
045 * Ehcache-based {@link CachingManager}.
046 */
047public class EhcacheCachingManager implements CachingManager, Initializable {
048
049    private static final Logger LOG = LogManager.getLogger( EhcacheCachingManager.class );
050    private static final int DEFAULT_CACHE_SIZE = 1_000;
051    private static final int DEFAULT_CACHE_EXPIRY_PERIOD = 24*60*60;
052
053    final Map< String, Cache > cacheMap = new ConcurrentHashMap<>();
054    final Map< String, CacheInfo > cacheStats = new ConcurrentHashMap<>();
055    CacheManager cacheManager;
056
057    /** {@inheritDoc} */
058    @Override
059    public void shutdown() {
060        if(!cacheMap.isEmpty()) {
061            CacheManager.getInstance().shutdown();
062            cacheMap.clear();
063            cacheStats.clear();
064        }
065    }
066
067    /** {@inheritDoc} */
068    @Override
069    public void initialize( final Engine engine, final Properties props ) throws WikiException {
070        final String cacheEnabled = TextUtil.getStringProperty( props, PROP_CACHE_ENABLE, PROP_USECACHE_DEPRECATED, "true" );
071        final boolean useCache = "true".equalsIgnoreCase( cacheEnabled );
072        if( useCache ) {
073            String val = TextUtil.getStringProperty( props, PROP_CACHE_CONF_FILE, "ehcache-jspwiki.xml" );
074            URL location = this.getClass().getResource( "/" + val );
075            if (location == null) {
076                location = this.getClass().getResource( val );
077            }
078            LOG.info( "Reading ehcache configuration file from classpath on /{}", location );
079            if (location == null ) {
080                LOG.error( "The ehcache configuration file from classpath on {} could not be loaded. Check setting {}", val , PROP_CACHE_CONF_FILE);
081            }
082            cacheManager = CacheManager.create( location );
083            registerCache( CACHE_ATTACHMENTS );
084            registerCache( CACHE_ATTACHMENTS_COLLECTION );
085            registerCache( CACHE_ATTACHMENTS_DYNAMIC );
086            registerCache( CACHE_DOCUMENTS );
087            registerCache( CACHE_PAGES );
088            registerCache( CACHE_PAGES_HISTORY );
089            registerCache( CACHE_PAGES_TEXT );
090        }
091    }
092
093    void registerCache( final String cacheName ) {
094        final Cache cache;
095        if( cacheManager.cacheExists( cacheName ) ) {
096            cache = cacheManager.getCache( cacheName );
097        } else {
098            LOG.info( "cache with name {} not found in ehcache configuration file, creating it with defaults.", cacheName );
099            cache = new Cache( cacheName, DEFAULT_CACHE_SIZE, false, false, DEFAULT_CACHE_EXPIRY_PERIOD, DEFAULT_CACHE_EXPIRY_PERIOD );
100            cacheManager.addCache( cache );
101        }
102        cacheMap.put( cacheName, cache );
103        cacheStats.put( cacheName, new CacheInfo( cacheName, cache.getCacheConfiguration().getMaxEntriesLocalHeap() ) );
104    }
105
106    /** {@inheritDoc} */
107    @Override
108    public boolean enabled( final String cacheName ) {
109        return cacheMap.get( cacheName ) != null;
110    }
111
112    /** {@inheritDoc} */
113    @Override
114    public CacheInfo info( final String cacheName ) {
115        if( enabled( cacheName ) ) {
116            return cacheStats.get( cacheName );
117        }
118        return null;
119    }
120
121    /**
122     * {@inheritDoc}
123     */
124    @Override
125    @SuppressWarnings( "unchecked" )
126    public List< String > keys( final String cacheName ) {
127        if( enabled( cacheName ) ) {
128            return cacheMap.get( cacheName ).getKeysWithExpiryCheck();
129        }
130        return Collections.emptyList();
131    }
132
133    /** {@inheritDoc} */
134    @Override
135    @SuppressWarnings( "unchecked" )
136    public < T, E extends Exception > T get( final String cacheName, final Serializable key, final CheckedSupplier< T, E > supplier ) throws E {
137        if( keyAndCacheAreNotNull( cacheName, key ) ) {
138            final Element element = cacheMap.get( cacheName ).get( key );
139            if( element != null ) {
140                cacheStats.get( cacheName ).hit();
141                return ( T )element.getObjectValue();
142            } else {
143                // element doesn't exist in cache, try to retrieve from the cached service instead.
144                final T value = supplier.get();
145                if( value != null ) {
146                    cacheStats.get( cacheName ).miss();
147                    cacheMap.get( cacheName ).put( new Element( key, value ) );
148                }
149                return value;
150            }
151        }
152        return null;
153    }
154
155    /** {@inheritDoc} */
156    @Override
157    public void put( final String cacheName, final Serializable key, final Object val ) {
158        if( keyAndCacheAreNotNull( cacheName, key ) ) {
159            cacheMap.get( cacheName ).put( new Element( key, val ) );
160        }
161    }
162
163    /** {@inheritDoc} */
164    @Override
165    public void remove( final String cacheName, final Serializable key ) {
166        if( keyAndCacheAreNotNull( cacheName, key ) ) {
167            cacheMap.get( cacheName ).remove( key );
168        }
169    }
170
171    /** {@inheritDoc} */
172    @Override
173    public boolean registerListener( final String cacheName, final String listener, final Object... args ) {
174        if( enabled( cacheName ) && "expired".equals( listener ) ) {
175            final AtomicBoolean allRequested = ( AtomicBoolean )args[0];
176            final CacheEventListenerAdapter expiredCacheListenerAdapter = new CacheEventListenerAdapter() {
177                @Override
178                public void notifyElementExpired( final Ehcache cache, final Element element ) {
179                    allRequested.set( false ); // signal that the cache no longer contains all elements...
180                }
181            };
182            return cacheMap.get( cacheName ).getCacheEventNotificationService().registerListener( expiredCacheListenerAdapter );
183        }
184        return false;
185    }
186
187    boolean keyAndCacheAreNotNull( final String cacheName, final Serializable key ) {
188        return enabled( cacheName ) && key != null;
189    }
190
191}