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