View Javadoc

1   /*
2    * $Id: AutowireUMOManagerFactoryBean.java 7976 2007-08-21 14:26:13Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.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.extras.spring.config;
12  
13  import org.mule.MuleManager;
14  import org.mule.config.MuleConfiguration;
15  import org.mule.extras.spring.SpringContainerContext;
16  import org.mule.impl.model.ModelFactory;
17  import org.mule.umo.UMODescriptor;
18  import org.mule.umo.UMOException;
19  import org.mule.umo.UMOInterceptorStack;
20  import org.mule.umo.endpoint.UMOEndpoint;
21  import org.mule.umo.lifecycle.InitialisationException;
22  import org.mule.umo.lifecycle.UMOLifecycleAdapterFactory;
23  import org.mule.umo.manager.UMOAgent;
24  import org.mule.umo.manager.UMOContainerContext;
25  import org.mule.umo.manager.UMOManager;
26  import org.mule.umo.manager.UMOTransactionManagerFactory;
27  import org.mule.umo.model.UMOEntryPointResolver;
28  import org.mule.umo.model.UMOModel;
29  import org.mule.umo.provider.UMOConnector;
30  import org.mule.umo.security.UMOSecurityManager;
31  import org.mule.umo.transformer.UMOTransformer;
32  
33  import java.beans.ExceptionListener;
34  import java.util.Collection;
35  import java.util.Iterator;
36  import java.util.Map;
37  
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  import org.springframework.beans.BeansException;
41  import org.springframework.beans.factory.BeanInitializationException;
42  import org.springframework.beans.factory.DisposableBean;
43  import org.springframework.beans.factory.FactoryBean;
44  import org.springframework.beans.factory.InitializingBean;
45  import org.springframework.context.ApplicationContext;
46  import org.springframework.context.ApplicationContextAware;
47  import org.springframework.context.support.AbstractApplicationContext;
48  
49  /**
50   * <code>UMOManagerFactoryBean</code> is a MuleManager factory bean that is used to
51   * configure the MuleManager from a spring context. This factory bean is responsible
52   * for determining the instance type of UMOManager to create and then delegates
53   * configuration calls to that instance depending on what is available in the
54   * container. <p/> Apart from removing the need to explicitly wire the MuleManager
55   * instance together there another advantage to using the
56   * AutowireUMOManagerFactoryBean. There is no need to declare a UMOModel instance in
57   * the configuration. If the factory doesn't find a UMOModel implementation it
58   * creates a default one of type <i>org.mule.impl.model.seda.SedaModel</i>. The
59   * model is automatically initialised with a SpringContainercontext using the current
60   * beanFactory and defaults are used for the other Model properties. If you want to
61   * override the defaults, such as define your own exception strategy, (which you will
62   * most likely want to do) simply declare your exception strategy bean in the
63   * container and it will automatically be set on the model. <p/> Most Mule objects
64   * have explicit types and can be autowired, however some objects cannot be
65   * autowired, such as a <i>java.util.Map</i> of endpoints for example. For these
66   * objects Mule defines standard bean names that will be looked for in the container
67   * during start up. <p/> muleEnvironmentProperties A map of properties to set on the
68   * MuleManager. Accessible from your code using
69   * AutowireUMOManagerFactoryBean.MULE_ENVIRONMENT_PROPERTIES_BEAN_NAME. <p/>
70   * muleEndpointMappings A Map of logical endpointUri mappings accessible from your
71   * code using AutowireUMOManagerFactoryBean.MULE_ENDPOINT_MAPPINGS_BEAN_NAME. <p/>
72   * muleInterceptorStacks A map of interceptor stacks, where the name of the stack is
73   * the key and a list of interceptors is the value. Accessible using from your code
74   * using AutowireUMOManagerFactoryBean.MULE_INTERCEPTOR_STACK_BEAN_NAME.
75   */
76  public class AutowireUMOManagerFactoryBean
77      implements FactoryBean, InitializingBean, DisposableBean, ApplicationContextAware
78  {
79      /**
80       * logger used by this class
81       */
82      protected static final Log logger = LogFactory.getLog(AutowireUMOManagerFactoryBean.class);
83  
84      public static final String MULE_ENVIRONMENT_PROPERTIES_BEAN_NAME = "muleEnvironmentProperties";
85      public static final String MULE_ENDPOINT_IDENTIFIERS_BEAN_NAME = "muleEndpointIdentifiers";
86      public static final String MULE_INTERCEPTOR_STACK_BEAN_NAME = "muleInterceptorStacks";
87      public static final String MULE_MODEL_EXCEPTION_STRATEGY_BEAN_NAME = "muleModelExceptionStrategy";
88  
89      private UMOManager manager;
90      private UMOModel model;
91  
92      private AbstractApplicationContext context;
93  
94      public AutowireUMOManagerFactoryBean() throws Exception
95      {
96          this.manager = MuleManager.getInstance();
97      }
98  
99      public Object getObject() throws Exception
100     {
101         return manager;
102     }
103 
104     public Class getObjectType()
105     {
106         return UMOManager.class;
107     }
108 
109     public boolean isSingleton()
110     {
111         return true;
112     }
113 
114     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
115     {
116         context = (AbstractApplicationContext)applicationContext;
117         try
118         {
119             // set mule configuration
120             Map temp = context.getBeansOfType(MuleConfiguration.class, true, true);
121             if (temp.size() > 0)
122             {
123                 MuleManager.setConfiguration((MuleConfiguration)temp.values().iterator().next());
124             }
125 
126             // set environment properties
127             setProperties((Map)getBean(MULE_ENVIRONMENT_PROPERTIES_BEAN_NAME, Map.class));
128 
129             // set Connectors
130             Map connectors = context.getBeansOfType(UMOConnector.class, true, true);
131             setConnectors(connectors.values());
132 
133             // set endpoint Identifiers
134             setMessageEndpointIdentifiers((Map)getBean(MULE_ENDPOINT_IDENTIFIERS_BEAN_NAME, Map.class));
135 
136             // set mule transaction manager
137             temp = context.getBeansOfType(UMOTransactionManagerFactory.class, true, true);
138             if (temp.size() > 0)
139             {
140                 manager.setTransactionManager(((UMOTransactionManagerFactory)temp.values().iterator().next()).create());
141             }
142 
143             // set security manager
144             temp = context.getBeansOfType(UMOSecurityManager.class, true, true);
145             if (temp.size() > 0)
146             {
147                 manager.setSecurityManager((UMOSecurityManager)temp.values().iterator().next());
148             }
149 
150             // set Transformers
151             Map transformers = context.getBeansOfType(UMOTransformer.class, true, true);
152             setTransformers(transformers.values());
153 
154             // set Endpoints
155             Map endpoints = context.getBeansOfType(UMOEndpoint.class, true, true);
156             setEndpoints(endpoints.values());
157 
158             // set Agents
159             Map agents = context.getBeansOfType(UMOAgent.class, true, true);
160             setAgents(agents.values());
161 
162             // Set the container Context
163             Map containers = context.getBeansOfType(UMOContainerContext.class, true, true);
164             setContainerContext(containers);
165 
166             // interceptors
167             Map interceptors = context.getBeansOfType(UMOInterceptorStack.class, true, true);
168             setInterceptorStacks(interceptors);
169             // create the model
170             createModel();
171 
172             // set Components
173             Map components = context.getBeansOfType(UMODescriptor.class, true, true);
174             setComponents(components.values());
175         }
176         catch (Exception e)
177         {
178             throw new BeanInitializationException("Failed to wire MuleManager together: " + e.getMessage(), e);
179         }
180     }
181 
182     public void setManagerId(String managerId)
183     {
184         manager.setId(managerId);
185     }
186 
187     protected void createModel() throws UMOException
188     {
189         // set the model
190         Map temp = context.getBeansOfType(UMOModel.class, true, true);
191         if (temp.size() > 1)
192         {
193             throw new IllegalStateException("In Mule 1.x only one model can be created when using Spring");
194         }
195         else if(temp.size()==1)
196         {
197             Map.Entry entry = (Map.Entry)temp.entrySet().iterator().next();
198             model = (UMOModel)entry.getValue();
199             model.setName(entry.getKey().toString());
200         }
201         else
202         {
203             // create a defaultModel
204             model = ModelFactory.createModel(MuleManager.getConfiguration().getModelType());
205         }
206 
207         // autowire the model so any ExceptionStrategy or PoolingStrategy beans
208         // can be set
209         // context.getBeanFactory().autowireBeanProperties(model,
210         // AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
211         // RM we cant autowire the model by type as some list properties
212         // conflict with each other
213 
214         // Entry point resolver
215         Map epr = context.getBeansOfType(UMOEntryPointResolver.class, true, true);
216         if (epr.size() > 0)
217         {
218             model.setEntryPointResolver((UMOEntryPointResolver)epr.values().iterator().next());
219         }
220 
221         // Life cycle adapter factory
222         Map lcaf = context.getBeansOfType(UMOLifecycleAdapterFactory.class, true, true);
223         if (lcaf.size() > 0)
224         {
225             model.setLifecycleAdapterFactory((UMOLifecycleAdapterFactory)lcaf.values().iterator().next());
226         }
227 
228         // Model exception strategy
229         Object listener = getBean(MULE_MODEL_EXCEPTION_STRATEGY_BEAN_NAME, ExceptionListener.class);
230         if (listener != null)
231         {
232             model.setExceptionListener((ExceptionListener)listener);
233         }
234 
235         manager.registerModel(model);
236 
237     }
238 
239     private Object getBean(String name, Class clazz)
240     {
241         try
242         {
243             return context.getBean(name, clazz);
244         }
245         catch (BeansException e)
246         {
247             return null;
248         }
249 
250     }
251 
252     protected void setContainerContext(Map containers) throws UMOException
253     {
254         if (containers.size() == 0)
255         {
256             // Use this as the default container
257             SpringContainerContext container = new SpringContainerContext();
258             container.setBeanFactory(context);
259             manager.setContainerContext(container);
260         }
261         else if (containers.size() == 1)
262         {
263             manager.setContainerContext((UMOContainerContext)containers.values().iterator().next());
264         }
265         else
266         {
267             UMOContainerContext ctx = (UMOContainerContext)containers.values().iterator().next();
268             logger.warn("There are " + containers.size()
269                         + " container contexts in the spring context. Using the first one: "
270                         + ctx.getClass().getName());
271             manager.setContainerContext(ctx);
272         }
273     }
274 
275     protected void setMessageEndpointIdentifiers(Map endpoints) throws InitialisationException
276     {
277         if (endpoints == null)
278         {
279             return;
280         }
281         Map.Entry entry;
282         for (Iterator iterator = endpoints.entrySet().iterator(); iterator.hasNext();)
283         {
284             entry = (Map.Entry)iterator.next();
285             manager.registerEndpointIdentifier(entry.getKey().toString(), entry.getValue().toString());
286 
287         }
288     }
289 
290     protected void setAgents(Collection agents) throws UMOException
291     {
292         for (Iterator iterator = agents.iterator(); iterator.hasNext();)
293         {
294             manager.registerAgent((UMOAgent)iterator.next());
295         }
296     }
297 
298     protected void setProperties(Map props)
299     {
300         if (props == null)
301         {
302             return;
303         }
304         Map.Entry entry;
305         for (Iterator iterator = props.entrySet().iterator(); iterator.hasNext();)
306         {
307             entry = (Map.Entry)iterator.next();
308             manager.setProperty(entry.getKey(), entry.getValue());
309         }
310     }
311 
312     protected void setConnectors(Collection connectors) throws UMOException
313     {
314         for (Iterator iterator = connectors.iterator(); iterator.hasNext();)
315         {
316             manager.registerConnector((UMOConnector)iterator.next());
317         }
318     }
319 
320     protected void setTransformers(Collection transformers) throws InitialisationException
321     {
322         for (Iterator iterator = transformers.iterator(); iterator.hasNext();)
323         {
324             manager.registerTransformer((UMOTransformer)iterator.next());
325         }
326     }
327 
328     protected void setEndpoints(Collection endpoints) throws InitialisationException
329     {
330         for (Iterator iterator = endpoints.iterator(); iterator.hasNext();)
331         {
332             manager.registerEndpoint((UMOEndpoint)iterator.next());
333         }
334     }
335 
336     protected void setComponents(Collection components) throws UMOException
337     {
338         UMODescriptor d;
339         for (Iterator iterator = components.iterator(); iterator.hasNext();)
340         {
341             d = (UMODescriptor)iterator.next();
342             if (!model.isComponentRegistered(d.getName()))
343             {
344                 model.registerComponent(d);
345             }
346         }
347     }
348 
349     protected void setInterceptorStacks(Map stacks)
350     {
351         if (stacks == null)
352         {
353             return;
354         }
355         for (Iterator iterator = stacks.entrySet().iterator(); iterator.hasNext();)
356         {
357             Map.Entry entry = (Map.Entry)iterator.next();
358             String name = entry.getKey().toString();
359             manager.registerInterceptorStack(name, (UMOInterceptorStack)entry.getValue());
360         }
361     }
362 
363     public void afterPropertiesSet() throws Exception
364     {
365         manager.start();
366     }
367 
368     public void destroy() throws Exception
369     {
370         manager.dispose();
371     }
372 }