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    
018    package org.apache.camel.component.cache;
019    
020    import java.io.InputStream;
021    import java.io.Serializable;
022    
023    import net.sf.ehcache.Cache;
024    import net.sf.ehcache.CacheException;
025    import net.sf.ehcache.CacheManager;
026    import net.sf.ehcache.Ehcache;
027    import net.sf.ehcache.Element;
028    
029    import org.apache.camel.Endpoint;
030    import org.apache.camel.Exchange;
031    import org.apache.camel.component.cache.factory.CacheManagerFactory;
032    import org.apache.camel.impl.DefaultProducer;
033    import org.apache.commons.logging.Log;
034    import org.apache.commons.logging.LogFactory;
035    
036    public class CacheProducer extends DefaultProducer {
037        private static final transient Log LOG = LogFactory.getLog(CacheProducer.class);
038        Endpoint endpoint;
039        CacheConfiguration config;
040        CacheManager cacheManager;
041        Ehcache cache;
042        
043        public CacheProducer(Endpoint endpoint, CacheConfiguration config) throws Exception {
044            super(endpoint);
045            this.endpoint = endpoint;
046            this.config = config;
047        }
048    
049        public void process(Exchange exchange) throws Exception {
050             
051            cacheManager = new CacheManagerFactory().instantiateCacheManager();
052            
053            if (LOG.isTraceEnabled()) {
054                LOG.trace("Cache Name: " + config.getCacheName());
055            }
056            if (cacheManager.cacheExists(config.getCacheName())) {
057                if (LOG.isTraceEnabled()) {
058                    LOG.trace("Found an existing cache: " + config.getCacheName());
059                    LOG.trace("Cache " + config.getCacheName() + " currently contains " + cacheManager.getCache(config.getCacheName()).getSize() + " elements");
060                }
061                cache = cacheManager.getCache(config.getCacheName());
062            } else {
063                cache = new Cache(config.getCacheName(), 
064                        config.getMaxElementsInMemory(),
065                        config.getMemoryStoreEvictionPolicy(), 
066                        config.isOverflowToDisk(), 
067                        config.getDiskStorePath(), 
068                        config.isEternal(), 
069                        config.getTimeToLiveSeconds(), 
070                        config.getTimeToIdleSeconds(), 
071                        config.isDiskPersistent(), 
072                        config.getDiskExpiryThreadIntervalSeconds(), 
073                        null);
074                cacheManager.addCache(cache);
075                if (LOG.isDebugEnabled()) {
076                    LOG.debug("Added a new cache: " + cache.getName());
077                }
078            }
079           
080            
081            String key = (String) exchange.getIn().getHeader("CACHE_KEY");
082            String operation = (String) exchange.getIn().getHeader("CACHE_OPERATION");
083            if (operation == null) {
084                throw new CacheException("Operation property is not specified in the incoming exchange header."
085                    + "A valid Operation property must be set to ADD, UPDATE, DELETE, DELETEALL");
086            }
087            if ((key == null) && (!operation.equalsIgnoreCase("DELETEALL"))) {
088                throw new CacheException("Cache Key is not specified in exchange either header or URL. Unable to add objects to the cache without a Key");
089            }
090            
091            performCacheOperation(exchange, operation, key);
092        }
093        
094        private void performCacheOperation(Exchange exchange, String operation, String key) throws Exception {
095            Object element;
096    
097            Object body = exchange.getIn().getBody();
098            if (body instanceof Serializable) {
099                element = body;
100            } else {
101                InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, body);
102    
103                // Read InputStream into a byte[] buffer
104                byte[] buffer = new byte[is.available()];
105                int n = is.available();
106                for (int j = 0; j < n; j++) {
107                    buffer[j] = (byte)is.read();
108                }
109    
110                element = buffer;
111            }
112    
113            if (operation.equalsIgnoreCase("ADD")) {
114                if (LOG.isDebugEnabled()) {
115                    LOG.debug("Adding an element with key " + key + " into the Cache");
116                }
117                cache.put(new Element(key, element), true);
118            } else if (operation.equalsIgnoreCase("UPDATE")) {
119                if (LOG.isDebugEnabled()) {
120                    LOG.debug("Updating an element with key " + key + " into the Cache");
121                }
122                cache.put(new Element(key, element), true);
123            } else if (operation.equalsIgnoreCase("DELETEALL")) {
124                if (LOG.isDebugEnabled()) {
125                    LOG.debug("Deleting All elements from the Cache");
126                }
127                cache.removeAll();
128            } else if (operation.equalsIgnoreCase("DELETE")) {
129                if (LOG.isDebugEnabled()) {
130                    LOG.debug("Deleting an element with key " + key + " into the Cache");
131                }
132                cache.remove(key, true);
133            }
134        }
135    
136    }