001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.camel.processor.cache;
018    
019    import net.sf.ehcache.CacheManager;
020    import net.sf.ehcache.Ehcache;
021    
022    import org.slf4j.Logger;
023    import org.slf4j.LoggerFactory;
024    
025    public class CacheValidate {
026        private static final transient Logger LOG = LoggerFactory.getLogger(CacheValidate.class);
027    
028        public boolean isValid(CacheManager cacheManager, String cacheName, String key) {
029            LOG.trace("Cache Name: {}", cacheName);
030    
031            if (!cacheManager.cacheExists(cacheName)) {
032                LOG.debug("No existing Cache found with name: {}"
033                        + ". Please ensure a cache is first instantiated using a Cache Consumer or Cache Producer."
034                        + " Replacement will not be performed since the cache {} does not presently exist", cacheName, cacheName);
035                return false;
036            }
037    
038            LOG.debug("Found an existing cache: {}", cacheName);
039    
040            if (LOG.isTraceEnabled()) {
041                LOG.trace("Cache {} currently contains {} elements", cacheName, cacheManager.getCache(cacheName).getSize());
042            }
043            Ehcache cache = cacheManager.getCache(cacheName);
044    
045            if (!cache.isKeyInCache(key)) {
046                LOG.debug("No Key with name: {} presently exists in the cache. It is also possible that the key may have expired in the cache."
047                        + " Replacement will not be performed until an appropriate key/value pair is added to (or) found in the cache.", key);
048                return false;
049            }
050    
051            return true;
052        }
053    
054    }