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.component.cache;
018    
019    import net.sf.ehcache.Cache;
020    import net.sf.ehcache.CacheManager;
021    import net.sf.ehcache.Ehcache;
022    import net.sf.ehcache.event.CacheEventListener;
023    
024    import org.apache.camel.Component;
025    import org.apache.camel.Consumer;
026    import org.apache.camel.Exchange;
027    import org.apache.camel.Message;
028    import org.apache.camel.Processor;
029    import org.apache.camel.Producer;
030    import org.apache.camel.impl.DefaultEndpoint;
031    import org.apache.camel.impl.DefaultExchange;
032    import org.apache.camel.impl.DefaultMessage;
033    import org.apache.camel.util.ObjectHelper;
034    import org.slf4j.Logger;
035    import org.slf4j.LoggerFactory;
036    
037    public class CacheEndpoint extends DefaultEndpoint {
038        private static final transient Logger LOG = LoggerFactory.getLogger(CacheEndpoint.class);
039        private CacheConfiguration config;
040        private CacheManagerFactory cacheManagerFactory;
041    
042        public CacheEndpoint() {
043        }
044    
045        public CacheEndpoint(String endpointUri, Component component,
046                CacheConfiguration config, CacheManagerFactory cacheManagerFactory) {
047            super(endpointUri, component);
048            this.config = config;
049            this.cacheManagerFactory = cacheManagerFactory;
050        }
051    
052        public Consumer createConsumer(Processor processor) throws Exception {
053            ObjectHelper.notNull(config, "config");
054            ObjectHelper.notNull(cacheManagerFactory, "cacheManagerFactory");
055            return new CacheConsumer(this, processor, config);
056        }
057    
058        public Producer createProducer() throws Exception {
059            ObjectHelper.notNull(config, "config");
060            ObjectHelper.notNull(cacheManagerFactory, "cacheManagerFactory");
061            return new CacheProducer(this, config);
062        }
063    
064        public boolean isSingleton() {
065            return true;
066        }
067    
068        public CacheConfiguration getConfig() {
069            return config;
070        }
071    
072        public void setConfig(CacheConfiguration config) {
073            this.config = config;
074        }
075    
076        public CacheManagerFactory getCacheManagerFactory() {
077            return cacheManagerFactory;
078        }
079    
080        public void setCacheManagerFactory(CacheManagerFactory cacheManagerFactory) {
081            this.cacheManagerFactory = cacheManagerFactory;
082        }
083    
084        public Exchange createCacheExchange(String operation, String key,
085                Object value) {
086            Exchange exchange = new DefaultExchange(this.getCamelContext(),
087                    getExchangePattern());
088            Message message = new DefaultMessage();
089            message.setHeader(CacheConstants.CACHE_OPERATION, operation);
090            message.setHeader(CacheConstants.CACHE_KEY, key);
091            message.setBody(value);
092            exchange.setIn(message);
093            return exchange;
094        }
095    
096        /**
097         * Returns {@link Cache} instance or create new one if not exists.
098         * 
099         * @return {@link Cache}
100         */
101        public Ehcache initializeCache() {
102            CacheManager cacheManager = getCacheManagerFactory().getInstance();
103            Cache cache;
104            if (cacheManager.cacheExists(config.getCacheName())) {
105                if (LOG.isTraceEnabled()) {
106                    LOG.trace("Found an existing cache: {}", config.getCacheName());
107                    LOG.trace("Cache {} currently contains {} elements",
108                            config.getCacheName(),
109                            cacheManager.getCache(config.getCacheName()).getSize());
110                }
111                cache = cacheManager.getCache(config.getCacheName());
112            } else {
113                cache = new Cache(config.getCacheName(),
114                        config.getMaxElementsInMemory(),
115                        config.getMemoryStoreEvictionPolicy(),
116                        config.isOverflowToDisk(),
117                        config.getDiskStorePath(),
118                        config.isEternal(),
119                        config.getTimeToLiveSeconds(),
120                        config.getTimeToIdleSeconds(),
121                        config.isDiskPersistent(),
122                        config.getDiskExpiryThreadIntervalSeconds(),
123                        null);
124    
125                for (CacheEventListener listener : config.getEventListenerRegistry().getEventListeners()) {
126                    cache.getCacheEventNotificationService().registerListener(listener);
127                }
128    
129                for (CacheLoaderWrapper loader : config.getCacheLoaderRegistry().getCacheLoaders()) {
130                    loader.init(cache);
131                    cache.registerCacheLoader(loader);
132                }
133    
134                cacheManager.addCache(cache);
135    
136                if (LOG.isDebugEnabled()) {
137                    LOG.debug("Added a new cache: " + cache.getName());
138                }
139            }
140    
141            return cache;
142        }
143    
144        @Override
145        public void stop() {
146            CacheManager cacheManager = getCacheManagerFactory().getInstance();
147            cacheManager.removeCache(config.getCacheName());
148        }
149    }