1 17 package org.apache.servicemix.components.cache; 18 19 import java.util.Map ; 20 21 import javax.jbi.JBIException; 22 import javax.jbi.messaging.Fault; 23 import javax.jbi.messaging.InOut; 24 import javax.jbi.messaging.MessageExchange; 25 import javax.jbi.messaging.MessagingException; 26 import javax.jbi.messaging.NormalizedMessage; 27 28 import org.apache.servicemix.components.util.TransformComponentSupport; 29 import org.apache.servicemix.expression.Expression; 30 import org.apache.servicemix.expression.PropertyExpression; 31 import org.apache.servicemix.jbi.NoOutMessageAvailableException; 32 33 39 public class CacheComponent extends TransformComponentSupport { 40 41 public static final PropertyExpression KEY_PROPERTY_EXPRESSION = new PropertyExpression("org.apache.servicemix.key"); 42 43 private Map cache; 44 private Expression keyExpression = KEY_PROPERTY_EXPRESSION; 45 46 public Map getCache() { 47 return cache; 48 } 49 50 public void setCache(Map cache) { 51 this.cache = cache; 52 } 53 54 public Expression getKeyExpression() { 55 return keyExpression; 56 } 57 58 public void setKeyExpression(Expression keyExpression) { 59 this.keyExpression = keyExpression; 60 } 61 62 63 protected void init() throws JBIException { 66 super.init(); 67 if (cache == null) { 68 throw new JBIException("You must specify a cache property"); 69 } 70 } 71 72 protected boolean transform(MessageExchange exchange, NormalizedMessage in, NormalizedMessage out) throws MessagingException { 73 Object key = keyExpression.evaluate(exchange, in); 74 if (key != null) { 75 NormalizedMessage message = (NormalizedMessage) cache.get(key); 76 if (message != null) { 77 getMessageTransformer().transform(exchange, message, out); 78 return true; 79 } 80 } 81 82 InOut inOut = getExchangeFactory().createInOutExchange(); 83 NormalizedMessage request = inOut.createMessage(); 84 getMessageTransformer().transform(exchange, in, request); 85 inOut.setInMessage(request); 86 getDeliveryChannel().sendSync(inOut); 87 88 NormalizedMessage response = inOut.getOutMessage(); 89 Fault fault = inOut.getFault(); 90 Exception error = inOut.getError(); 91 if (fault != null) { 92 fail(exchange, fault); 93 } 94 else if (error != null) { 95 fail(exchange, error); 96 } 97 else if (response != null) { 98 getMessageTransformer().transform(exchange, response, out); 99 100 if (key != null) { 101 cache.put(key, response); 102 } 103 } 104 else { 105 throw new NoOutMessageAvailableException(exchange); 106 } 107 return true; 108 } 109 110 } 111 | Popular Tags |