KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > config > builders > MuleXmlConfigurationBuilder


1 /*
2  * $Id: MuleXmlConfigurationBuilder.java 3798 2006-11-04 04:07:14Z aperepel $
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 MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.config.builders;
12
13 import org.apache.commons.beanutils.ConvertUtils;
14 import org.apache.commons.digester.AbstractObjectCreationFactory;
15 import org.apache.commons.digester.Digester;
16 import org.apache.commons.digester.ObjectCreateRule;
17 import org.apache.commons.digester.Rule;
18 import org.apache.commons.digester.SetNextRule;
19 import org.apache.commons.digester.SetPropertiesRule;
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22 import org.mule.MuleManager;
23 import org.mule.config.ConfigurationBuilder;
24 import org.mule.config.ConfigurationException;
25 import org.mule.config.MuleConfiguration;
26 import org.mule.config.MuleDtdResolver;
27 import org.mule.config.MuleProperties;
28 import org.mule.config.PoolingProfile;
29 import org.mule.config.QueueProfile;
30 import org.mule.config.ReaderResource;
31 import org.mule.config.ThreadingProfile;
32 import org.mule.config.converters.ConnectorConverter;
33 import org.mule.config.converters.EndpointConverter;
34 import org.mule.config.converters.EndpointURIConverter;
35 import org.mule.config.converters.TransactionFactoryConverter;
36 import org.mule.config.converters.TransformerConverter;
37 import org.mule.config.i18n.Message;
38 import org.mule.config.i18n.Messages;
39 import org.mule.config.pool.CommonsPoolFactory;
40 import org.mule.impl.DefaultLifecycleAdapter;
41 import org.mule.impl.MuleDescriptor;
42 import org.mule.impl.MuleTransactionConfig;
43 import org.mule.impl.endpoint.MuleEndpoint;
44 import org.mule.impl.model.ModelFactory;
45 import org.mule.impl.security.MuleSecurityManager;
46 import org.mule.interceptors.InterceptorStack;
47 import org.mule.model.DynamicEntryPointResolver;
48 import org.mule.providers.AbstractConnector;
49 import org.mule.providers.ConnectionStrategy;
50 import org.mule.routing.LoggingCatchAllStrategy;
51 import org.mule.routing.inbound.InboundMessageRouter;
52 import org.mule.routing.outbound.OutboundMessageRouter;
53 import org.mule.routing.response.ResponseMessageRouter;
54 import org.mule.transaction.constraints.BatchConstraint;
55 import org.mule.umo.UMODescriptor;
56 import org.mule.umo.UMOEncryptionStrategy;
57 import org.mule.umo.UMOInterceptor;
58 import org.mule.umo.UMOInterceptorStack;
59 import org.mule.umo.UMOTransactionFactory;
60 import org.mule.umo.endpoint.UMOEndpoint;
61 import org.mule.umo.endpoint.UMOEndpointURI;
62 import org.mule.umo.lifecycle.InitialisationException;
63 import org.mule.umo.manager.ContainerException;
64 import org.mule.umo.manager.UMOAgent;
65 import org.mule.umo.manager.UMOContainerContext;
66 import org.mule.umo.manager.UMOManager;
67 import org.mule.umo.manager.UMOTransactionManagerFactory;
68 import org.mule.umo.model.UMOModel;
69 import org.mule.umo.provider.UMOConnector;
70 import org.mule.umo.routing.UMOInboundMessageRouter;
71 import org.mule.umo.routing.UMOOutboundMessageRouter;
72 import org.mule.umo.routing.UMOOutboundRouter;
73 import org.mule.umo.routing.UMOResponseMessageRouter;
74 import org.mule.umo.security.UMOEndpointSecurityFilter;
75 import org.mule.umo.security.UMOSecurityManager;
76 import org.mule.umo.security.UMOSecurityProvider;
77 import org.mule.umo.transformer.UMOTransformer;
78 import org.mule.util.ClassUtils;
79 import org.mule.util.PropertiesUtils;
80 import org.mule.util.StringUtils;
81 import org.mule.util.queue.EventFilePersistenceStrategy;
82 import org.xml.sax.Attributes JavaDoc;
83
84 import java.beans.ExceptionListener JavaDoc;
85 import java.io.InputStream JavaDoc;
86 import java.io.InputStreamReader JavaDoc;
87 import java.util.ArrayList JavaDoc;
88 import java.util.HashMap JavaDoc;
89 import java.util.Iterator JavaDoc;
90 import java.util.List JavaDoc;
91 import java.util.Map JavaDoc;
92 import java.util.Properties JavaDoc;
93
94 /**
95  * <code>MuleXmlConfigurationBuilder</code> is a configuration parser that builds a
96  * MuleManager instance based on a mule xml configration file defined in the
97  * mule-configuration.dtd.
98  */

99 public class MuleXmlConfigurationBuilder extends AbstractDigesterConfiguration
100     implements ConfigurationBuilder
101 {
102     /**
103      * logger used by this class
104      */

105     protected static Log logger = LogFactory.getLog(MuleXmlConfigurationBuilder.class);
106
107     public static final String JavaDoc DEFAULT_ENTRY_POINT_RESOLVER = DynamicEntryPointResolver.class.getName();
108     public static final String JavaDoc DEFAULT_LIFECYCLE_ADAPTER = DefaultLifecycleAdapter.class.getName();
109     public static final String JavaDoc DEFAULT_ENDPOINT = MuleEndpoint.class.getName();
110     public static final String JavaDoc DEFAULT_TRANSACTION_CONFIG = MuleTransactionConfig.class.getName();
111     public static final String JavaDoc DEFAULT_DESCRIPTOR = MuleDescriptor.class.getName();
112     public static final String JavaDoc DEFAULT_SECURITY_MANAGER = MuleSecurityManager.class.getName();
113     public static final String JavaDoc DEFAULT_OUTBOUND_MESSAGE_ROUTER = OutboundMessageRouter.class.getName();
114     public static final String JavaDoc DEFAULT_INBOUND_MESSAGE_ROUTER = InboundMessageRouter.class.getName();
115     public static final String JavaDoc DEFAULT_RESPONSE_MESSAGE_ROUTER = ResponseMessageRouter.class.getName();
116     public static final String JavaDoc DEFAULT_CATCH_ALL_STRATEGY = LoggingCatchAllStrategy.class.getName();
117     public static final String JavaDoc DEFAULT_POOL_FACTORY = CommonsPoolFactory.class.getName();
118     public static final String JavaDoc THREADING_PROFILE = ThreadingProfile.class.getName();
119     public static final String JavaDoc POOLING_PROFILE = PoolingProfile.class.getName();
120     public static final String JavaDoc QUEUE_PROFILE = QueueProfile.class.getName();
121
122     public static final String JavaDoc PERSISTENCE_STRATEGY_INTERFACE = EventFilePersistenceStrategy.class.getName();
123     public static final String JavaDoc INBOUND_MESSAGE_ROUTER_INTERFACE = UMOInboundMessageRouter.class.getName();
124     public static final String JavaDoc RESPONSE_MESSAGE_ROUTER_INTERFACE = UMOResponseMessageRouter.class.getName();
125     public static final String JavaDoc OUTBOUND_MESSAGE_ROUTER_INTERFACE = UMOOutboundMessageRouter.class.getName();
126     public static final String JavaDoc TRANSFORMER_INTERFACE = UMOTransformer.class.getName();
127     public static final String JavaDoc TRANSACTION_MANAGER_FACTORY_INTERFACE = UMOTransactionManagerFactory.class.getName();
128     public static final String JavaDoc SECURITY_PROVIDER_INTERFACE = UMOSecurityProvider.class.getName();
129     public static final String JavaDoc ENCRYPTION_STRATEGY_INTERFACE = UMOEncryptionStrategy.class.getName();
130     public static final String JavaDoc ENDPOINT_SECURITY_FILTER_INTERFACE = UMOEndpointSecurityFilter.class.getName();
131     public static final String JavaDoc AGENT_INTERFACE = UMOAgent.class.getName();
132     public static final String JavaDoc TRANSACTION_FACTORY_INTERFACE = UMOTransactionFactory.class.getName();
133     public static final String JavaDoc TRANSACTION_CONSTRAINT_INTERFACE = BatchConstraint.class.getName();
134     public static final String JavaDoc CONNECTOR_INTERFACE = UMOConnector.class.getName();
135     public static final String JavaDoc INTERCEPTOR_INTERFACE = UMOInterceptor.class.getName();
136     public static final String JavaDoc ROUTER_INTERFACE = UMOOutboundRouter.class.getName();
137     public static final String JavaDoc EXCEPTION_STRATEGY_INTERFACE = ExceptionListener JavaDoc.class.getName();
138     public static final String JavaDoc CONNECTION_STRATEGY_INTERFACE = ConnectionStrategy.class.getName();
139
140     protected UMOManager manager;
141
142     private List JavaDoc transformerReferences = new ArrayList JavaDoc();
143     private List JavaDoc endpointReferences = new ArrayList JavaDoc();
144
145     public MuleXmlConfigurationBuilder() throws ConfigurationException
146     {
147         super(System.getProperty(MuleProperties.XML_VALIDATE_SYSTEM_PROPERTY, "true")
148             .equalsIgnoreCase("true"), System.getProperty(MuleProperties.XML_DTD_SYSTEM_PROPERTY,
149             MuleDtdResolver.DEFAULT_MULE_DTD));
150
151         ConvertUtils.register(new EndpointConverter(), UMOEndpoint.class);
152         ConvertUtils.register(new TransformerConverter(), UMOTransformer.class);
153         ConvertUtils.register(new ConnectorConverter(), UMOConnector.class);
154         ConvertUtils.register(new TransactionFactoryConverter(), UMOTransactionFactory.class);
155         ConvertUtils.register(new EndpointURIConverter(), UMOEndpointURI.class);
156
157         String JavaDoc path = getRootName();
158         addManagerRules(digester, path);
159         addServerPropertiesRules(path + "/environment-properties", "addProperties", 0);
160         addContainerContextRules(path + "/container-context", "setContainerContext", 0);
161
162         addMuleConfigurationRules(digester, path);
163         addTransformerRules(digester, path);
164         addSecurityManagerRules(digester, path);
165         addTransactionManagerRules(digester, path);
166         addGlobalEndpointRules(digester, path);
167         addEndpointIdentifierRules(digester, path);
168         addInterceptorStackRules(digester, path);
169         addConnectorRules(digester, path);
170         addAgentRules(digester, path);
171
172         addModelRules(digester, path);
173         // Threse rules allow for individual component configurations
174
addMuleDescriptorRules(digester, path);
175     }
176
177     public String JavaDoc getRootName()
178     {
179         return "mule-configuration";
180     }
181
182     public UMOManager configure(String JavaDoc configResources) throws ConfigurationException
183     {
184         return configure(configResources, null);
185     }
186
187     public UMOManager configure(String JavaDoc configResources, String JavaDoc startupPropertiesFile)
188         throws ConfigurationException
189     {
190         try
191         {
192             String JavaDoc[] resources = StringUtils.splitAndTrim(configResources, ",");
193             MuleManager.getConfiguration().setConfigResources(resources);
194             ReaderResource[] readers = new ReaderResource[resources.length];
195             for (int i = 0; i < resources.length; i++)
196             {
197                 InputStream JavaDoc is = loadConfig(resources[i].trim());
198                 readers[i] = new ReaderResource(resources[i].trim(),
199                     new InputStreamReader JavaDoc(is, configEncoding));
200             }
201
202             // Load startup properties if any.
203
if (startupPropertiesFile != null)
204             {
205                 return configure(readers, PropertiesUtils.loadProperties(startupPropertiesFile, getClass()));
206             }
207             else
208                 return configure(readers, null);
209
210         }
211         catch (Exception JavaDoc e)
212         {
213             throw new ConfigurationException(e);
214         }
215     }
216
217     /**
218      * @deprecated Please use configure(ReaderResource[] configResources, Properties
219      * startupProperties) instead.
220      */

221     public UMOManager configure(ReaderResource[] configResources) throws ConfigurationException
222     {
223         return configure(configResources, null);
224     }
225
226     public UMOManager configure(ReaderResource[] configResources, Properties startupProperties)
227         throws ConfigurationException
228     {
229         if (startupProperties != null)
230         {
231             ((MuleManager)MuleManager.getInstance()).addProperties(startupProperties);
232         }
233         manager = (MuleManager)process(configResources);
234         if (manager == null)
235         {
236             throw new ConfigurationException(new Message(Messages.FAILED_TO_CREATE_MANAGER_INSTANCE_X,
237                 "Are you using a correct configuration builder?"));
238         }
239         try
240         {
241             setContainerProperties();
242             setTransformers();
243             setGlobalEndpoints();
244             if (System.getProperty(MuleProperties.MULE_START_AFTER_CONFIG_SYSTEM_PROPERTY, "true")
245                 .equalsIgnoreCase("true"))
246             {
247                 manager.start();
248             }
249         }
250         catch (Exception JavaDoc e)
251         {
252             throw new ConfigurationException(new Message(Messages.X_FAILED_TO_INITIALISE, "MuleManager"), e);
253         }
254         return manager;
255     }
256
257     /**
258      * Indicate whether this ConfigurationBulder has been configured yet
259      *
260      * @return <code>true</code> if this ConfigurationBulder has been configured
261      */

262     public boolean isConfigured()
263     {
264         return manager != null;
265     }
266
267     protected void setContainerProperties() throws ContainerException
268     {
269         UMOContainerContext ctx = manager.getContainerContext();
270         try
271         {
272             for (Iterator JavaDoc iterator = containerReferences.iterator(); iterator.hasNext();)
273             {
274                 ContainerReference reference = (ContainerReference)iterator.next();
275                 reference.resolveReference(ctx);
276             }
277         }
278         finally
279         {
280             containerReferences.clear();
281         }
282     }
283
284     protected void setTransformers() throws InitialisationException
285     {
286         try
287         {
288             for (Iterator JavaDoc iterator = transformerReferences.iterator(); iterator.hasNext();)
289             {
290                 TransformerReference reference = (TransformerReference)iterator.next();
291                 reference.resolveTransformer();
292             }
293         }
294         finally
295         {
296             transformerReferences.clear();
297         }
298     }
299
300     protected void setGlobalEndpoints() throws InitialisationException
301     {
302         // because Mule Xml allows developers to overload global endpoints
303
// we need a way to initialise Global endpoints after the Xml has
304
// been processed but before the MuleManager is initialised. So we do
305
// it here.
306
UMOManager manager = MuleManager.getInstance();
307
308         // we need to take a copy of the endpoints since we're going to modify them
309
// while iterating
310
Map JavaDoc endpoints = new HashMap JavaDoc(manager.getEndpoints());
311         for (Iterator JavaDoc iterator = endpoints.values().iterator(); iterator.hasNext();)
312         {
313             UMOEndpoint ep = (UMOEndpoint)iterator.next();
314             ep.initialise();
315             manager.unregisterEndpoint(ep.getName());
316             manager.registerEndpoint(ep);
317         }
318
319         try
320         {
321             for (Iterator JavaDoc iterator = endpointReferences.iterator(); iterator.hasNext();)
322             {
323                 EndpointReference reference = (EndpointReference)iterator.next();
324                 reference.resolveEndpoint();
325             }
326         }
327         finally
328         {
329             endpointReferences.clear();
330         }
331     }
332
333     protected void addManagerRules(Digester digester, String JavaDoc path)
334     {
335         digester.addFactoryCreate(path, new AbstractObjectCreationFactory()
336         {
337             public Object JavaDoc createObject(Attributes JavaDoc attributes) throws Exception JavaDoc
338             {
339                 manager = MuleManager.getInstance();
340                 return manager;
341             }
342         });
343         digester.addSetProperties(path);
344     }
345
346     protected void addMuleConfigurationRules(Digester digester, String JavaDoc path)
347     {
348         digester.addSetProperties(path);
349         // Create mule system properties and defaults
350
path += "/mule-environment-properties";
351         digester.addObjectCreate(path, MuleConfiguration.class);
352         addSetPropertiesRule(path, digester);
353
354         // Add pooling profile rules
355
addPoolingProfileRules(digester, path);
356
357         // Add Queue Profile rules
358
addQueueProfileRules(digester, path);
359
360         // set threading profile
361
digester.addObjectCreate(path + "/threading-profile", THREADING_PROFILE);
362         SetPropertiesRule threadingRule = new SetPropertiesRule();
363         threadingRule.addAlias("poolExhaustedAction", "poolExhaustedActionString");
364         digester.addRule(path + "/threading-profile", threadingRule);
365         digester.addRule(path + "/threading-profile", new Rule()
366         {
367             private String JavaDoc id;
368
369             public void begin(String JavaDoc s, String JavaDoc s1, Attributes JavaDoc attributes) throws Exception JavaDoc
370             {
371                 id = attributes.getValue("id");
372             }
373
374             public void end(String JavaDoc s, String JavaDoc s1) throws Exception JavaDoc
375             {
376                 ThreadingProfile tp = (ThreadingProfile)digester.peek();
377                 MuleConfiguration cfg = (MuleConfiguration)digester.peek(1);
378
379                 if ("default".equals(id))
380                 {
381                     cfg.setDefaultThreadingProfile(tp);
382                     cfg.setMessageDispatcherThreadingProfile(tp);
383                     cfg.setMessageReceiverThreadingProfile(tp);
384                     cfg.setComponentThreadingProfile(tp);
385                 }
386                 else if ("messageReceiver".equals(id) || "receiver".equals(id))
387                 {
388                     cfg.setMessageReceiverThreadingProfile(tp);
389                 }
390                 else if ("messageDispatcher".equals(id) || "dispatcher".equals(id))
391                 {
392                     cfg.setMessageDispatcherThreadingProfile(tp);
393                 }
394                 else if ("component".equals(id))
395                 {
396                     cfg.setComponentThreadingProfile(tp);
397                 }
398             }
399         });
400
401         // add persistence strategy
402
digester.addObjectCreate(path + "/persistence-strategy", PERSISTENCE_STRATEGY_INTERFACE, "className");
403         addMulePropertiesRule(path + "/persistence-strategy", digester);
404         digester.addSetNext(path + "/persistence-strategy", "setPersistenceStrategy");
405
406         // Connection strategy
407
digester.addObjectCreate(path + "/connection-strategy", CONNECTION_STRATEGY_INTERFACE, "className");
408         addMulePropertiesRule(path + "/connection-strategy", digester);
409         // digester.addSetNext(path + "/connection-strategy",
410
// "setConnectionStrategy");
411
digester.addRule(path + "/connection-strategy", new SetNextRule("setConnectionStrategy")
412         {
413             public void end(String JavaDoc s, String JavaDoc s1) throws Exception JavaDoc
414             {
415                 super.end(s, s1);
416             }
417         });
418
419         digester.addRule(path, new Rule()
420         {
421             public void end(String JavaDoc s, String JavaDoc s1) throws Exception JavaDoc
422             {
423                 MuleManager.setConfiguration((MuleConfiguration)digester.peek());
424             }
425         });
426     }
427
428     protected void addSecurityManagerRules(Digester digester, String JavaDoc path) throws ConfigurationException
429     {
430         // Create container Context
431
path += "/security-manager";
432         addObjectCreateOrGetFromContainer(path, DEFAULT_SECURITY_MANAGER, "className", "ref", false);
433
434         // Add propviders
435
digester.addObjectCreate(path + "/security-provider", SECURITY_PROVIDER_INTERFACE, "className");
436         addSetPropertiesRule(path + "/security-provider", digester);
437         addMulePropertiesRule(path + "/security-provider", digester);
438         digester.addSetNext(path + "/security-provider", "addProvider");
439
440         // Add encryption strategies
441
digester.addObjectCreate(path + "/encryption-strategy", ENCRYPTION_STRATEGY_INTERFACE, "className");
442         addSetPropertiesRule(path + "/encryption-strategy", digester);
443         addMulePropertiesRule(path + "/encryption-strategy", digester);
444         digester.addRule(path + "/encryption-strategy", new Rule()
445         {
446             private String JavaDoc name;
447
448             public void begin(String JavaDoc endpointName, String JavaDoc endpointName1, Attributes JavaDoc attributes)
449                 throws Exception JavaDoc
450             {
451                 name = attributes.getValue("name");
452             }
453
454             public void end(String JavaDoc endpointName, String JavaDoc endpointName1) throws Exception JavaDoc
455             {
456                 UMOEncryptionStrategy s = (UMOEncryptionStrategy)digester.peek();
457                 ((UMOSecurityManager)digester.peek(1)).addEncryptionStrategy(name, s);
458             }
459         });
460         digester.addSetNext(path, "setSecurityManager");
461
462     }
463
464     protected void addTransformerRules(Digester digester, String JavaDoc path) throws ConfigurationException
465     {
466         // Create Transformers
467
path += "/transformers/transformer";
468         addObjectCreateOrGetFromContainer(path, TRANSFORMER_INTERFACE, "className", "ref", true);
469
470         addSetPropertiesRule(path, digester);
471
472         addMulePropertiesRule(path, digester);
473         digester.addSetRoot(path, "registerTransformer");
474     }
475
476     protected void addGlobalEndpointRules(Digester digester, String JavaDoc path) throws ConfigurationException
477     {
478         // Create global message endpoints
479
path += "/global-endpoints";
480         addEndpointRules(digester, path, "registerEndpoint");
481     }
482
483     protected void addEndpointIdentifierRules(Digester digester, String JavaDoc path) throws ConfigurationException
484     {
485         // Create and reqister endpoints
486
path += "/endpoint-identifiers/endpoint-identifier";
487         digester.addRule(path, new Rule()
488         {
489             private PlaceholderProcessor processor = new PlaceholderProcessor();
490
491             public void begin(String JavaDoc s, String JavaDoc s1, Attributes JavaDoc attributes) throws Exception JavaDoc
492             {
493                 attributes = processor.processAttributes(attributes, s1);
494                 String JavaDoc name = attributes.getValue("name");
495                 String JavaDoc value = attributes.getValue("value");
496                 ((UMOManager)digester.getRoot()).registerEndpointIdentifier(name, value);
497             }
498         });
499     }
500
501     protected void addTransactionManagerRules(Digester digester, String JavaDoc path) throws ConfigurationException
502     {
503         // Create transactionManager
504
path += "/transaction-manager";
505         addObjectCreateOrGetFromContainer(path, TRANSACTION_MANAGER_FACTORY_INTERFACE, "factory", "ref", true);
506         addMulePropertiesRule(path, digester);
507
508         digester.addSetRoot(path, "setTransactionManager");
509         digester.addRule(path, new Rule()
510         {
511             public void end(String JavaDoc s, String JavaDoc s1) throws Exception JavaDoc
512             {
513                 UMOTransactionManagerFactory txFactory = (UMOTransactionManagerFactory)digester.pop();
514                 digester.push(txFactory.create());
515             }
516         });
517     }
518
519     protected void addAgentRules(Digester digester, String JavaDoc path) throws ConfigurationException
520     {
521         // Create Agents
522
path += "/agents/agent";
523         addObjectCreateOrGetFromContainer(path, AGENT_INTERFACE, "className", "ref", true);
524         addSetPropertiesRule(path, digester);
525
526         addMulePropertiesRule(path, digester);
527
528         digester.addSetRoot(path, "registerAgent");
529     }
530
531     protected void addConnectorRules(Digester digester, String JavaDoc path) throws ConfigurationException
532     {
533         // Create connectors
534
path += "/connector";
535         addObjectCreateOrGetFromContainer(path, CONNECTOR_INTERFACE, "className", "ref", true);
536
537         addSetPropertiesRule(path, digester);
538
539         addMulePropertiesRule(path, digester);
540
541         digester.addRule(path + "/threading-profile", new Rule()
542         {
543             private String JavaDoc id;
544
545             public void begin(String JavaDoc s, String JavaDoc s1, Attributes JavaDoc attributes) throws Exception JavaDoc
546             {
547                 // use the global tp as a template
548
MuleConfiguration cfg = MuleManager.getConfiguration();
549                 id = attributes.getValue("id");
550                 if ("default".equals(id))
551                 {
552                     digester.push(cfg.getDefaultThreadingProfile());
553                 }
554                 else if ("receiver".equals(id))
555                 {
556                     digester.push(cfg.getMessageReceiverThreadingProfile());
557                 }
558                 else if ("dispatcher".equals(id))
559                 {
560                     digester.push(cfg.getMessageDispatcherThreadingProfile());
561                 }
562
563             }
564
565             public void end(String JavaDoc s, String JavaDoc s1) throws Exception JavaDoc
566             {
567                 ThreadingProfile tp = (ThreadingProfile)digester.pop();
568                 AbstractConnector cnn = (AbstractConnector)digester.peek();
569
570                 if ("default".equals(id))
571                 {
572                     cnn.setReceiverThreadingProfile(tp);
573                     cnn.setDispatcherThreadingProfile(tp);
574                 }
575                 else if ("receiver".equals(id))
576                 {
577                     cnn.setReceiverThreadingProfile(tp);
578                 }
579                 else if ("dispatcher".equals(id))
580                 {
581                     cnn.setDispatcherThreadingProfile(tp);
582                 }
583             }
584         });
585
586         SetPropertiesRule threadingRule = new SetPropertiesRule();
587         threadingRule.addAlias("setPoolExhaustedAction", "setPoolExhaustedActionString");
588         digester.addRule(path + "/threading-profile", threadingRule);
589
590         // Connection strategy
591
digester.addObjectCreate(path + "/connection-strategy", CONNECTION_STRATEGY_INTERFACE, "className");
592         addMulePropertiesRule(path + "/connection-strategy", digester);
593         digester.addSetNext(path + "/connection-strategy", "setConnectionStrategy");
594
595         addExceptionStrategyRules(digester, path);
596
597         // register conntector
598
digester.addSetRoot(path, "registerConnector");
599     }
600
601     protected void addInterceptorStackRules(Digester digester, String JavaDoc path) throws ConfigurationException
602     {
603         // Create Inteceptor stacks
604
path += "/interceptor-stack";
605         digester.addRule(path + "/interceptor", new ObjectCreateRule(INTERCEPTOR_INTERFACE, "className")
606         {
607             public void end(String JavaDoc s, String JavaDoc s1) throws Exception JavaDoc
608             {
609                 /* do not pop the result */
610             }
611         });
612
613         digester.addRule(path, new Rule()
614         {
615             public void begin(String JavaDoc s, String JavaDoc s1, Attributes JavaDoc attributes) throws Exception JavaDoc
616             {
617                 digester.push(attributes.getValue("name"));
618             }
619
620             public void end(String JavaDoc s, String JavaDoc s1) throws Exception JavaDoc
621             {
622                 List JavaDoc list = new ArrayList JavaDoc();
623                 Object JavaDoc obj = digester.peek();
624                 while (obj instanceof UMOInterceptor)
625                 {
626                     list.add(0, digester.pop());
627                     obj = digester.peek();
628                 }
629                 InterceptorStack stack = new InterceptorStack();
630                 stack.setInterceptors(list);
631                 manager.registerInterceptorStack(digester.pop().toString(), stack);
632             }
633         });
634
635         addMulePropertiesRule(path + "/interceptor", digester);
636     }
637
638     protected void addModelRules(Digester digester, String JavaDoc path) throws ConfigurationException
639     {
640         // Create Model
641
path += "/model";
642
643         digester.addRule(path, new Rule()
644         {
645             public void begin(String JavaDoc string, String JavaDoc string1, Attributes JavaDoc attributes) throws Exception JavaDoc
646             {
647                 UMOModel model = manager.getModel();
648                 // The Model is the default one created by the manager, then be can
649
// dispose it. This is a non-issue in Mule 2.0
650
if (MuleManager.DEFAULT_MODEL_NAME.equals(model.getName()))
651                 {
652                     model = null;
653                 }
654                 if (model == null)
655                 {
656                     String JavaDoc modelType = attributes.getValue("type");
657                     if (modelType == null)
658                     {
659                         modelType = MuleManager.getConfiguration().getModelType();
660                     }
661                     if (modelType.equalsIgnoreCase("custom"))
662                     {
663                         String JavaDoc className = attributes.getValue("className");
664                         if (className == null)
665                         {
666                             throw new IllegalArgumentException JavaDoc(
667                                 "Cannot use 'custom' model type without setting the 'className' for the model");
668                         }
669                         else
670                         {
671                             model = (UMOModel)ClassUtils.instanciateClass(className, ClassUtils.NO_ARGS,
672                                 getClass());
673                         }
674                     }
675                     else
676                     {
677                         model = ModelFactory.createModel(modelType);
678                     }
679                 }
680                 digester.push(model);
681             }
682         });
683
684         addSetPropertiesRule(path, digester);
685
686         digester.addSetRoot(path, "setModel");
687
688         // Create endpointUri resolver
689
digester.addObjectCreate(path + "/entry-point-resolver", DEFAULT_ENTRY_POINT_RESOLVER, "className");
690         addSetPropertiesRule(path + "/entry-point-resolver", digester);
691
692         digester.addSetNext(path + "/entry-point-resolver", "setEntryPointResolver");
693
694         // Create lifecycle adapter
695
digester.addObjectCreate(path + "/component-lifecycle-adapter-factory", DEFAULT_LIFECYCLE_ADAPTER,
696             "className");
697         addSetPropertiesRule(path, digester);
698         digester.addSetNext(path + "/component-lifecycle-adapter-factory", "setLifecycleAdapterFactory");
699
700         // Pool factory
701
addPoolingProfileRules(digester, path);
702
703         // Exception strategy
704
addExceptionStrategyRules(digester, path);
705
706         // Add Components
707
addMuleDescriptorRules(digester, path);
708     }
709
710     protected void addMuleDescriptorRules(Digester digester, String JavaDoc path) throws ConfigurationException
711     {
712         // Create Mule UMOs
713
path += "/mule-descriptor";
714         addObjectCreateOrGetFromContainer(path, DEFAULT_DESCRIPTOR, "className", "ref", "container", false);
715
716         addSetPropertiesRule(path, digester);
717
718         // Create Message Routers
719
addMessageRouterRules(digester, path, "inbound");
720         addMessageRouterRules(digester, path, "outbound");
721         addMessageRouterRules(digester, path, "response");
722
723         // Add threading profile rules
724
addThreadingProfileRules(digester, path, "component");
725
726         // Add pooling profile rules
727
addPoolingProfileRules(digester, path);
728
729         // queue profile rules
730
addQueueProfileRules(digester, path);
731
732         // Create interceptors
733
digester.addRule(path + "/interceptor", new Rule()
734         {
735             public void begin(String JavaDoc string, String JavaDoc string1, Attributes JavaDoc attributes) throws Exception JavaDoc
736             {
737                 String JavaDoc value = attributes.getValue("name");
738                 if (value == null)
739                 {
740                     value = attributes.getValue("className");
741                 }
742                 UMOManager man = (UMOManager)digester.getRoot();
743                 UMOInterceptorStack interceptorStack = man.lookupInterceptorStack(value);
744                 MuleDescriptor temp = (MuleDescriptor)digester.peek();
745                 if (interceptorStack != null)
746                 {
747                     temp.addInterceptor(interceptorStack);
748                 }
749                 else
750                 {
751                     // Instantiate the new object and push it on the context
752
// stack
753
Class JavaDoc clazz = digester.getClassLoader().loadClass(value);
754                     Object JavaDoc instance = clazz.newInstance();
755                     temp.addInterceptor((UMOInterceptor)instance);
756                     digester.push(instance);
757                 }
758             }
759
760             public void end(String JavaDoc s, String JavaDoc s1) throws Exception JavaDoc
761             {
762                 if (digester.peek() instanceof UMOInterceptor)
763                 {
764                     digester.pop();
765                 }
766             }
767         });
768
769         addMulePropertiesRule(path + "/interceptor", digester);
770
771         // Set exception strategy
772
addExceptionStrategyRules(digester, path);
773
774         addMulePropertiesRule(path, digester, "setProperties");
775         digester.addSetNext(path + "/properties", "setProperties");
776
777         // register the component
778
digester.addRule(path, new Rule()
779         {
780             public void end(String JavaDoc s, String JavaDoc s1) throws Exception JavaDoc
781             {
782                 UMODescriptor descriptor = (UMODescriptor)digester.peek();
783                 Object JavaDoc obj = digester.peek(1);
784                 final UMOModel model;
785                 if (obj instanceof UMOManager)
786                 {
787                     model = ((UMOManager)obj).getModel();
788                 }
789                 else
790                 {
791                     model = (UMOModel)obj;
792                 }
793                 model.registerComponent(descriptor);
794             }
795         });
796     }
797
798     protected void addThreadingProfileRules(Digester digester, String JavaDoc path, final String JavaDoc type)
799     {
800         // set threading profile
801
digester.addRule(path + "/threading-profile", new Rule()
802         {
803             public void begin(String JavaDoc s, String JavaDoc s1, Attributes JavaDoc attributes) throws Exception JavaDoc
804             {
805                 // use the default as a template
806
MuleConfiguration cfg = MuleManager.getConfiguration();
807                 if ("component".equals(type))
808                 {
809                     digester.push(cfg.getComponentThreadingProfile());
810                 }
811                 else if ("messageReceiver".equals(type))
812                 {
813                     digester.push(cfg.getComponentThreadingProfile());
814                 }
815                 else if ("messageDispatcher".equals(type))
816                 {
817                     digester.push(cfg.getComponentThreadingProfile());
818                 }
819                 else
820                 {
821                     digester.push(cfg.getDefaultThreadingProfile());
822                 }
823             }
824
825             public void end(String JavaDoc s, String JavaDoc s1) throws Exception JavaDoc
826             {
827                 digester.pop();
828             }
829         });
830         // set threading profile
831
SetPropertiesRule threadingRule = new SetPropertiesRule();
832         threadingRule.addAlias("setPoolExhaustedAction", "setPoolExhaustedActionString");
833         digester.addRule(path + "/threading-profile", threadingRule);
834         digester.addSetNext(path + "/threading-profile", "setThreadingProfile");
835     }
836
837     protected void addPoolingProfileRules(Digester digester, String JavaDoc path)
838     {
839         // set pooling profile
840
digester.addRule(path + "/pooling-profile", new Rule()
841         {
842             public void begin(String JavaDoc s, String JavaDoc s1, Attributes JavaDoc attributes) throws Exception JavaDoc
843             {
844                 // use the default as a template
845
MuleConfiguration cfg = MuleManager.getConfiguration();
846                 digester.push(cfg.getPoolingProfile());
847             }
848
849             public void end(String JavaDoc s, String JavaDoc s1) throws Exception JavaDoc
850             {
851                 digester.pop();
852             }
853         });
854
855         SetPropertiesRule rule = new SetPropertiesRule();
856         rule.addAlias("exhaustedAction", "exhaustedActionString");
857         rule.addAlias("initialisationPolicy", "initialisationPolicyString");
858         digester.addRule(path + "/pooling-profile", rule);
859         digester.addSetNext(path + "/pooling-profile", "setPoolingProfile");
860     }
861
862     protected void addQueueProfileRules(Digester digester, String JavaDoc path)
863     {
864         digester.addObjectCreate(path + "/queue-profile", QUEUE_PROFILE);
865         addSetPropertiesRule(path + "/queue-profile", digester);
866         digester.addSetNext(path + "/queue-profile", "setQueueProfile");
867     }
868
869     protected void addMessageRouterRules(Digester digester, String JavaDoc path, String JavaDoc type)
870         throws ConfigurationException
871     {
872         String JavaDoc defaultRouter;
873         String JavaDoc setMethod;
874         if ("inbound".equals(type))
875         {
876             defaultRouter = DEFAULT_INBOUND_MESSAGE_ROUTER;
877             setMethod = "setInboundRouter";
878             path += "/inbound-router";
879             // Add endpoints for multiple inbound endpoints
880
addEndpointRules(digester, path, "addEndpoint");
881             addGlobalReferenceEndpointRules(digester, path, "addEndpoint");
882         }
883         else if ("response".equals(type))
884         {
885             defaultRouter = DEFAULT_RESPONSE_MESSAGE_ROUTER;
886             setMethod = "setResponseRouter";
887             path += "/response-router";
888             // Add endpoints for multiple response endpoints i.e. replyTo
889
// addresses
890
addEndpointRules(digester, path, "addEndpoint");
891             addGlobalReferenceEndpointRules(digester, path, "addEndpoint");
892         }
893         else
894         {
895             defaultRouter = DEFAULT_OUTBOUND_MESSAGE_ROUTER;
896             setMethod = "setOutboundRouter";
897             path += "/outbound-router";
898         }
899         digester.addObjectCreate(path, defaultRouter, "className");
900         addSetPropertiesRule(path, digester);
901
902         // Add Catch All strategy
903
digester.addObjectCreate(path + "/catch-all-strategy", DEFAULT_CATCH_ALL_STRATEGY, "className");
904         addSetPropertiesRule(path + "/catch-all-strategy", digester);
905
906         // Add endpointUri for catch-all strategy
907
addEndpointRules(digester, path + "/catch-all-strategy", "setEndpoint");
908         addGlobalReferenceEndpointRules(digester, path + "/catch-all-strategy", "setEndpoint");
909
910         addMulePropertiesRule(path + "/catch-all-strategy", digester);
911         digester.addSetNext(path + "/catch-all-strategy", "setCatchAllStrategy");
912
913         // Add router rules
914
addRouterRules(digester, path, type);
915
916         // add the router to the descriptor
917
digester.addSetNext(path, setMethod);
918     }
919
920     protected void addRouterRules(Digester digester, String JavaDoc path, final String JavaDoc type)
921         throws ConfigurationException
922     {
923         path += "/router";
924         if ("inbound".equals(type))
925         {
926             digester.addObjectCreate(path, INBOUND_MESSAGE_ROUTER_INTERFACE, "className");
927         }
928         else if ("response".equals(type))
929         {
930             digester.addObjectCreate(path, RESPONSE_MESSAGE_ROUTER_INTERFACE, "className");
931         }
932         else
933         {
934             digester.addObjectCreate(path, OUTBOUND_MESSAGE_ROUTER_INTERFACE, "className");
935         }
936
937         addSetPropertiesRule(path, digester, new String JavaDoc[]{"enableCorrelation", "propertyExtractor"},
938             new String JavaDoc[]{"enableCorrelationAsString", "propertyExtractorAsString"});
939         addMulePropertiesRule(path, digester);
940         if ("outbound".equals(type))
941         {
942             addEndpointRules(digester, path, "addEndpoint");
943             addReplyToRules(digester, path);
944             addGlobalReferenceEndpointRules(digester, path, "addEndpoint");
945             addTransactionConfigRules(path, digester);
946         }
947         addFilterRules(digester, path);
948
949         // Set the router on the to the message router
950
digester.addSetNext(path, "addRouter");
951     }
952
953     protected void addReplyToRules(Digester digester, String JavaDoc path) throws ConfigurationException
954     {
955         // Set message endpoint
956
path += "/reply-to";
957         digester.addRule(path, new Rule()
958         {
959             public void begin(String JavaDoc s, String JavaDoc s1, Attributes JavaDoc attributes) throws Exception JavaDoc
960             {
961                 String JavaDoc replyTo = attributes.getValue("address");
962                 ((UMOOutboundRouter)digester.peek()).setReplyTo(replyTo);
963             }
964         });
965     }
966
967     protected void addEndpointRules(Digester digester, String JavaDoc path, String JavaDoc method)
968         throws ConfigurationException
969     {
970         // Set message endpoint
971
path += "/endpoint";
972         addObjectCreateOrGetFromContainer(path, DEFAULT_ENDPOINT, "className", "ref", false);
973         addCommonEndpointRules(digester, path, method);
974     }
975
976     protected void addGlobalReferenceEndpointRules(Digester digester, String JavaDoc path, final String JavaDoc method)
977         throws ConfigurationException
978     {
979         // Set message endpoint
980
path += "/global-endpoint";
981         digester.addRule(path, new Rule()
982         {
983             public void begin(String JavaDoc s, String JavaDoc s1, Attributes JavaDoc attributes) throws Exception JavaDoc
984             {
985                 String JavaDoc name = attributes.getValue("name");
986                 String JavaDoc address = attributes.getValue("address");
987                 String JavaDoc trans = attributes.getValue("transformers");
988                 String JavaDoc responseTrans = attributes.getValue("responseTransformers");
989                 String JavaDoc createConnector = attributes.getValue("createConnector");
990                 EndpointReference ref = new EndpointReference(method, name, address, trans, responseTrans,
991                     createConnector, digester.peek());
992                 // TODO encoding
993
// String encoding = attributes.getValue("encoding");
994
digester.push(ref);
995             }
996
997             public void end(String JavaDoc endpointName, String JavaDoc endpointName1) throws Exception JavaDoc
998             {
999                 endpointReferences.add(digester.pop());
1000            }
1001        });
1002        addCommonEndpointRules(digester, path, null);
1003    }
1004
1005    protected void addCommonEndpointRules(Digester digester, String JavaDoc path, String JavaDoc method)
1006        throws ConfigurationException
1007    {
1008        addSetPropertiesRule(path, digester, new String JavaDoc[]{"address", "transformers", "responseTransformers",
1009            "createConnector"}, new String JavaDoc[]{"endpointURI", "transformer", "responseTransformer",
1010            "createConnectorAsString"});
1011        // todo test
1012
addMulePropertiesRule(path, digester, "setProperties");
1013        addTransactionConfigRules(path, digester);
1014
1015        addFilterRules(digester, path);
1016        if (method != null)
1017        {
1018            digester.addSetNext(path, method);
1019        }
1020
1021        // Add security filter rules
1022
digester.addObjectCreate(path + "/security-filter", ENDPOINT_SECURITY_FILTER_INTERFACE, "className");
1023
1024        addMulePropertiesRule(path + "/security-filter", digester);
1025        digester.addSetNext(path + "/security-filter", "setSecurityFilter");
1026    }
1027
1028    protected void addTransactionConfigRules(String JavaDoc path, Digester digester)
1029    {
1030        digester.addObjectCreate(path + "/transaction", DEFAULT_TRANSACTION_CONFIG);
1031        addSetPropertiesRule(path + "/transaction", digester, new String JavaDoc[]{"action"},
1032            new String JavaDoc[]{"actionAsString"});
1033
1034        digester.addObjectCreate(path + "/transaction/constraint", TRANSACTION_CONSTRAINT_INTERFACE,
1035            "className");
1036        addSetPropertiesRule(path + "/transaction/constraint", digester);
1037
1038        digester.addSetNext(path + "/transaction/constraint", "setConstraint");
1039        digester.addSetNext(path + "/transaction", "setTransactionConfig");
1040    }
1041
1042    protected void addExceptionStrategyRules(Digester digester, String JavaDoc path) throws ConfigurationException
1043    {
1044        path += "/exception-strategy";
1045        digester.addObjectCreate(path, EXCEPTION_STRATEGY_INTERFACE, "className");
1046        addMulePropertiesRule(path, digester);
1047
1048        // Add endpoint rules
1049
addEndpointRules(digester, path, "addEndpoint");
1050        addGlobalReferenceEndpointRules(digester, path, "addEndpoint");
1051        digester.addSetNext(path, "setExceptionListener");
1052    }
1053
1054    protected void addSetPropertiesRule(String JavaDoc path, Digester digester, String JavaDoc[] s1, String JavaDoc[] s2)
1055    {
1056        digester.addRule(path, new ExtendedMuleSetPropertiesRule(s1, s2));
1057    }
1058
1059    protected void addSetPropertiesRule(String JavaDoc path, Digester digester)
1060    {
1061        digester.addRule(path, new ExtendedMuleSetPropertiesRule());
1062    }
1063
1064    private void addTransformerReference(String JavaDoc propName, String JavaDoc transName, Object JavaDoc object)
1065    {
1066        transformerReferences.add(new TransformerReference(propName, transName, object));
1067    }
1068
1069    private void addEndpointReference(String JavaDoc propName, String JavaDoc endpointName, Object JavaDoc object)
1070    {
1071        endpointReferences.add(new EndpointReference(propName, endpointName, null, null, null, null, object));
1072    }
1073
1074    /**
1075     * this rule serves 2 functions - 1. Allows for late binding of certain types of
1076     * object, namely Transformers and endpoints that need to be set on objects once
1077     * the Manager configuration has been processed 2. Allows for template parameters
1078     * to be parse on the configuration file in the form of ${param-name}. These will
1079     * get resolved against properties set in the mule-properites element
1080     */

1081    public class ExtendedMuleSetPropertiesRule extends MuleSetPropertiesRule
1082    {
1083        public ExtendedMuleSetPropertiesRule()
1084        {
1085            super();
1086        }
1087
1088        public ExtendedMuleSetPropertiesRule(PlaceholderProcessor processor)
1089        {
1090            super(processor);
1091        }
1092
1093        public ExtendedMuleSetPropertiesRule(String JavaDoc[] strings, String JavaDoc[] strings1)
1094        {
1095            super(strings, strings1);
1096        }
1097
1098        public ExtendedMuleSetPropertiesRule(String JavaDoc[] strings,
1099                                             String JavaDoc[] strings1,
1100                                             PlaceholderProcessor processor)
1101        {
1102            super(strings, strings1, processor);
1103        }
1104
1105        public void begin(String JavaDoc s1, String JavaDoc s2, Attributes JavaDoc attributes) throws Exception JavaDoc
1106        {
1107            attributes = processor.processAttributes(attributes, s2);
1108            // Add transformer references that will be bound to their objects
1109
// once all configuration has bean read
1110
String JavaDoc transformerNames = attributes.getValue("transformer");
1111            if (transformerNames != null)
1112            {
1113                addTransformerReference("transformer", transformerNames, digester.peek());
1114            }
1115            transformerNames = attributes.getValue("transformers");
1116            if (transformerNames != null)
1117            {
1118                addTransformerReference("transformer", transformerNames, digester.peek());
1119            }
1120
1121            transformerNames = attributes.getValue("responseTransformers");
1122            if (transformerNames != null)
1123            {
1124                addTransformerReference("responseTransformer", transformerNames, digester.peek());
1125            }
1126
1127            // transformerNames = attributes.getValue("responseTransformer");
1128
// if (transformerNames != null) {
1129
// addTransformerReference("responseTransformer", transformerNames,
1130
// digester.peek());
1131
// }
1132

1133            transformerNames = attributes.getValue("inboundTransformer");
1134            if (transformerNames != null)
1135            {
1136                addTransformerReference("inboundTransformer", transformerNames, digester.peek());
1137            }
1138
1139            transformerNames = attributes.getValue("outboundTransformer");
1140            if (transformerNames != null)
1141            {
1142                addTransformerReference("outboundTransformer", transformerNames, digester.peek());
1143            }
1144
1145            transformerNames = attributes.getValue("responseTransformer");
1146            if (transformerNames != null)
1147            {
1148                addTransformerReference("responseTransformer", transformerNames, digester.peek());
1149            }
1150
1151            // Special case handling of global endpoint refs on the
1152
// inboundEndpoint/
1153
// outboundendpoint attributes of the descriptor
1154
String JavaDoc endpoint = attributes.getValue("inboundEndpoint");
1155            if (endpoint != null)
1156            {
1157                Object JavaDoc o = manager.getEndpoints().get(endpoint);
1158                if (o != null)
1159                {
1160                    addEndpointReference("setInboundEndpoint", endpoint, digester.peek());
1161                }
1162            }
1163
1164            endpoint = attributes.getValue("outboundEndpoint");
1165            if (endpoint != null)
1166            {
1167                Object JavaDoc o = manager.getEndpoints().get(endpoint);
1168                if (o != null)
1169                {
1170                    addEndpointReference("setOutboundEndpoint", endpoint, digester.peek());
1171                }
1172            }
1173            super.begin(attributes);
1174        }
1175    }
1176
1177    protected void addObjectCreateOrGetFromContainer(final String JavaDoc path,
1178                                                     String JavaDoc defaultImpl,
1179                                                     final String JavaDoc classAttrib,
1180                                                     final String JavaDoc refAttrib,
1181                                                     final boolean classRefRequired)
1182    {
1183        digester.addRule(path, new ObjectGetOrCreateRule(defaultImpl, classAttrib, refAttrib, classAttrib,
1184            classRefRequired, "getContainerContext"));
1185    }
1186
1187    protected void addObjectCreateOrGetFromContainer(final String JavaDoc path,
1188                                                     String JavaDoc defaultImpl,
1189                                                     final String JavaDoc classAttrib,
1190                                                     final String JavaDoc refAttrib,
1191                                                     final String JavaDoc containerAttrib,
1192                                                     final boolean classRefRequired)
1193    {
1194        digester.addRule(path, new ObjectGetOrCreateRule(defaultImpl, classAttrib, refAttrib,
1195            containerAttrib, classAttrib, classRefRequired, "getContainerContext"));
1196    }
1197}
1198
Popular Tags