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.apache.camel.Exchange;
023 import org.apache.camel.Processor;
024 import org.apache.camel.component.cache.CacheManagerFactory;
025 import org.apache.commons.logging.Log;
026 import org.apache.commons.logging.LogFactory;
027
028 public class CacheBasedMessageBodyReplacer extends CacheValidate implements Processor {
029 private static final transient Log LOG = LogFactory.getLog(CacheBasedMessageBodyReplacer.class);
030 CacheManager cacheManager;
031 Ehcache cache;
032 private String cacheName;
033 private String key;
034
035 public CacheBasedMessageBodyReplacer(String cacheName, String key) {
036 super();
037 if (cacheName.contains("cache://")) {
038 this.setCacheName(cacheName.replace("cache://", ""));
039 } else {
040 this.setCacheName(cacheName);
041 }
042 this.setKey(key);
043 }
044
045 public void process(Exchange exchange) throws Exception {
046 // Cache the buffer to the specified Cache against the specified key
047 cacheManager = new CacheManagerFactory().instantiateCacheManager();
048
049 if (isValid(cacheManager, cacheName, key)) {
050 cache = cacheManager.getCache(cacheName);
051 if (LOG.isDebugEnabled()) {
052 LOG.debug("Replacing Message Body from CacheName " + cacheName + " for key " + key);
053 }
054 exchange.getIn().setHeader("CACHE_KEY", key);
055 exchange.getIn().setBody(cache.get(key).getObjectValue());
056 }
057
058 }
059
060 public String getCacheName() {
061 return cacheName;
062 }
063
064 public void setCacheName(String cacheName) {
065 this.cacheName = cacheName;
066 }
067
068 public String getKey() {
069 return key;
070 }
071
072 public void setKey(String key) {
073 this.key = key;
074 }
075
076 }