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        final String confLocation = "/" + TextUtil.getStringProperty( props, PROP_CACHE_CONF_FILE, "ehcache-jspwiki.xml" );
073        if( useCache ) {
074            final URL location = findConfiguration( confLocation );
075            LOG.info( "Reading ehcache configuration file from classpath on /{}", location );
076            cacheManager = CacheManager.create( location );
077            registerCache( CACHE_ATTACHMENTS );
078            registerCache( CACHE_ATTACHMENTS_COLLECTION );
079            registerCache( CACHE_ATTACHMENTS_DYNAMIC );
080            registerCache( CACHE_DOCUMENTS );
081            registerCache( CACHE_PAGES );
082            registerCache( CACHE_PAGES_HISTORY );
083            registerCache( CACHE_PAGES_TEXT );
084        }
085    }
086
087    /**
088     * Looks for the configuration file with the class loader of this class and, if it is not there, with the one of the
089     * thread. When this jar is in a library shared by several web applications, as in the portable builds, only the
090     * second one sees the classes folder of the web application.
091     */
092    URL findConfiguration( final String location ) {
093        URL url = this.getClass().getResource( location );
094        if( url == null ) {
095            final ClassLoader context = Thread.currentThread().getContextClassLoader();
096            if( context != null ) {
097                url = context.getResource( location.startsWith( "/" ) ? location.substring( 1 ) : location );
098            }
099        }
100        return url;
101    }
102
103    void registerCache( final String cacheName ) {
104        final Cache cache;
105        if( cacheManager.cacheExists( cacheName ) ) {
106            cache = cacheManager.getCache( cacheName );
107        } else {
108            LOG.info( "cache with name {} not found in ehcache configuration file, creating it with defaults.", cacheName );
109            cache = new Cache( cacheName, DEFAULT_CACHE_SIZE, false, false, DEFAULT_CACHE_EXPIRY_PERIOD, DEFAULT_CACHE_EXPIRY_PERIOD );
110            cacheManager.addCache( cache );
111        }
112        cacheMap.put( cacheName, cache );
113        cacheStats.put( cacheName, new CacheInfo( cacheName, cache.getCacheConfiguration().getMaxEntriesLocalHeap() ) );
114    }
115
116    /** {@inheritDoc} */
117    @Override
118    public boolean enabled( final String cacheName ) {
119        return cacheMap.get( cacheName ) != null;
120    }
121
122    /** {@inheritDoc} */
123    @Override
124    public CacheInfo info( final String cacheName ) {
125        if( enabled( cacheName ) ) {
126            return cacheStats.get( cacheName );
127        }
128        return null;
129    }
130
131    /**
132     * {@inheritDoc}
133     */
134    @Override
135    @SuppressWarnings( "unchecked" )
136    public List< String > keys( final String cacheName ) {
137        if( enabled( cacheName ) ) {
138            return cacheMap.get( cacheName ).getKeysWithExpiryCheck();
139        }
140        return Collections.emptyList();
141    }
142
143    /** {@inheritDoc} */
144    @Override
145    @SuppressWarnings( "unchecked" )
146    public < T, E extends Exception > T get( final String cacheName, final Serializable key, final CheckedSupplier< T, E > supplier ) throws E {
147        if( keyAndCacheAreNotNull( cacheName, key ) ) {
148            final Element element = cacheMap.get( cacheName ).get( key );
149            if( element != null ) {
150                cacheStats.get( cacheName ).hit();
151                return ( T )element.getObjectValue();
152            } else {
153                // element doesn't exist in cache, try to retrieve from the cached service instead.
154                final T value = supplier.get();
155                if( value != null ) {
156                    cacheStats.get( cacheName ).miss();
157                    cacheMap.get( cacheName ).put( new Element( key, value ) );
158                }
159                return value;
160            }
161        }
162        return null;
163    }
164
165    /** {@inheritDoc} */
166    @Override
167    public void put( final String cacheName, final Serializable key, final Object val ) {
168        if( keyAndCacheAreNotNull( cacheName, key ) ) {
169            cacheMap.get( cacheName ).put( new Element( key, val ) );
170        }
171    }
172
173    /** {@inheritDoc} */
174    @Override
175    public void remove( final String cacheName, final Serializable key ) {
176        if( keyAndCacheAreNotNull( cacheName, key ) ) {
177            cacheMap.get( cacheName ).remove( key );
178        }
179    }
180
181    /** {@inheritDoc} */
182    @Override
183    public boolean registerListener( final String cacheName, final String listener, final Object... args ) {
184        if( enabled( cacheName ) && "expired".equals( listener ) ) {
185            final AtomicBoolean allRequested = ( AtomicBoolean )args[0];
186            final CacheEventListenerAdapter expiredCacheListenerAdapter = new CacheEventListenerAdapter() {
187                @Override
188                public void notifyElementExpired( final Ehcache cache, final Element element ) {
189                    allRequested.set( false ); // signal that the cache no longer contains all elements...
190                }
191            };
192            return cacheMap.get( cacheName ).getCacheEventNotificationService().registerListener( expiredCacheListenerAdapter );
193        }
194        return false;
195    }
196
197    boolean keyAndCacheAreNotNull( final String cacheName, final Serializable key ) {
198        return enabled( cacheName ) && key != null;
199    }
200
201}