View Javadoc

1   /*
2    * $Id: Rules.java 22162 2011-06-09 18:23:00Z dfeist $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.module.bpm;
12  
13  import org.mule.DefaultMuleEvent;
14  import org.mule.DefaultMuleMessage;
15  import org.mule.MessageExchangePattern;
16  import org.mule.RequestContext;
17  import org.mule.api.MuleContext;
18  import org.mule.api.MuleEvent;
19  import org.mule.api.MuleException;
20  import org.mule.api.MuleMessage;
21  import org.mule.api.construct.FlowConstruct;
22  import org.mule.api.endpoint.EndpointBuilder;
23  import org.mule.api.endpoint.OutboundEndpoint;
24  import org.mule.api.lifecycle.Disposable;
25  import org.mule.api.lifecycle.Initialisable;
26  import org.mule.api.lifecycle.InitialisationException;
27  import org.mule.api.transport.DispatchException;
28  import org.mule.api.transport.PropertyScope;
29  import org.mule.config.i18n.MessageFactory;
30  import org.mule.session.DefaultMuleSession;
31  
32  import java.util.Collection;
33  import java.util.Map;
34  
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  
38  /**
39   * Business rules.
40   */
41  public class Rules implements Initialisable, Disposable, MessageService
42  {
43      /** The underlying Rules Engine */
44      private final RulesEngine rulesEngine;
45  
46      /** The resource containing the rules definition  */
47      private final String resource;
48  
49      /** Provider-specific configuration data */
50      private final Object configuration;
51      
52      /** Entry point for event stream (used by CEP) */
53      private String entryPoint;
54      
55      /** Initial facts to be asserted at startup. */
56      private Collection initialFacts;
57      
58      /** Is the knowledge base intended to be stateless? (default = false) */
59      private boolean stateless;
60  
61      /** Are we using the knowledge base for CEP (Complex Event Processing)? (default = false) */
62      private boolean cepMode;
63  
64      /** Provider-specific object holding all stateful information about the Rules session */
65      private transient Object sessionData;
66      
67      protected transient MuleContext muleContext;
68  
69      /** Needed for exception handling. */
70      private transient FlowConstruct flowConstruct;
71  
72      protected static final Log logger = LogFactory.getLog(Rules.class);
73  
74      public Rules(RulesEngine rulesEngine, String resource, Object configuration, String entryPoint, Collection initialFacts, boolean stateless, boolean cepMode, FlowConstruct flowConstruct, MuleContext muleContext)
75      {
76          this.rulesEngine = rulesEngine;
77          this.resource = resource;
78          this.configuration = configuration;
79          this.entryPoint = entryPoint;
80          this.initialFacts = initialFacts;
81          this.stateless = stateless;
82          this.cepMode = cepMode;
83          this.flowConstruct = flowConstruct;
84          this.muleContext = muleContext;
85      }
86  
87      public void initialise() throws InitialisationException
88      {
89          try
90          {
91              sessionData = rulesEngine.createSession(this);
92              
93              // Insert any initial data into the knowledge base
94              for (Object obj : initialFacts)
95              {
96                  logger.debug("Adding initial data to the knowledge base: " + obj);
97                  rulesEngine.assertFact(this, obj);
98              }
99          }
100         catch (Exception e)
101         {
102             throw new InitialisationException(e, this);
103         }
104     }
105 
106     public void dispose()
107     {
108         if (sessionData != null)
109         {
110             try
111             {
112                 rulesEngine.disposeSession(sessionData);
113             }
114             catch (Exception e)
115             {
116                 logger.warn(e.getMessage());
117             }
118             finally
119             {
120                 sessionData = null;
121             }
122         }
123     }
124 
125     protected Object handleEvent(MuleEvent event) throws Exception
126     {
127         Object payload = event.getMessage().getPayload();
128         logger.debug("Adding message payload to the knowledge base: " + payload);
129         if (cepMode)
130         {
131             return rulesEngine.assertEvent(this, payload, entryPoint);
132         }
133         else
134         {
135             return rulesEngine.assertFact(this, payload);
136         }
137     }
138 
139     // TODO This method should probably use the LocalMuleClient instead of re-inventing the wheel
140     public MuleMessage generateMessage(String endpoint, Object payload, Map messageProperties, MessageExchangePattern exchangePattern) throws MuleException
141     {
142         MuleMessage message;
143         if (payload instanceof MuleMessage)
144         {
145             message = (MuleMessage) payload;
146         }
147         else
148         {
149             message = new DefaultMuleMessage(payload, muleContext);
150         }
151         message.addProperties(messageProperties, PropertyScope.INBOUND);
152         message.addProperties(messageProperties, PropertyScope.INVOCATION);
153 
154         //TODO should probably cache this
155         EndpointBuilder endpointBuilder = muleContext.getEndpointFactory().getEndpointBuilder(endpoint);
156         endpointBuilder.setExchangePattern(exchangePattern);
157         OutboundEndpoint ep = endpointBuilder.buildOutboundEndpoint();
158        
159         DefaultMuleEvent event = new DefaultMuleEvent(message, ep.getExchangePattern(),
160             new DefaultMuleSession(flowConstruct, muleContext));
161 
162         RequestContext.setEvent(event);
163         MuleEvent resultEvent = ep.process(event);
164         
165         MuleMessage response = null;
166         if (resultEvent != null)
167         {
168             response = resultEvent.getMessage();
169             if (response.getExceptionPayload() != null)
170             {
171                 throw new DispatchException(MessageFactory.createStaticMessage("Unable to send or route message"), event, ep, response.getExceptionPayload().getRootException());
172             }
173         }        
174         return response;
175     }
176 
177     public String getResource()
178     {
179         return resource;
180     }
181 
182     public Object getConfiguration()
183     {
184         return configuration;
185     }
186 
187     public String getEntryPointLabel()
188     {
189         return entryPoint;
190     }
191 
192     public Object getSessionData()
193     {
194         return sessionData;
195     }
196 
197     public Collection getInitialVariables()
198     {
199         return initialFacts;
200     }
201 
202     public boolean isStateless()
203     {
204         return stateless;
205     }
206 
207     public boolean isCepMode()
208     {
209         return cepMode;
210     }
211 }