KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > extras > client > MuleClient


1 /*
2  * $Id: MuleClient.java 4219 2006-12-09 10:15:14Z lajos $
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.extras.client;
12
13 import edu.emory.mathcs.backport.java.util.concurrent.Callable;
14 import edu.emory.mathcs.backport.java.util.concurrent.ExecutorService;
15 import org.apache.commons.logging.Log;
16 import org.apache.commons.logging.LogFactory;
17 import org.mule.MuleManager;
18 import org.mule.config.ConfigurationBuilder;
19 import org.mule.config.ConfigurationException;
20 import org.mule.config.MuleConfiguration;
21 import org.mule.config.MuleProperties;
22 import org.mule.config.builders.MuleXmlConfigurationBuilder;
23 import org.mule.config.builders.QuickConfigurationBuilder;
24 import org.mule.config.i18n.Message;
25 import org.mule.config.i18n.Messages;
26 import org.mule.impl.MuleEvent;
27 import org.mule.impl.MuleMessage;
28 import org.mule.impl.MuleSession;
29 import org.mule.impl.endpoint.MuleEndpoint;
30 import org.mule.impl.endpoint.MuleEndpointURI;
31 import org.mule.impl.security.MuleCredentials;
32 import org.mule.providers.AbstractConnector;
33 import org.mule.providers.service.ConnectorFactory;
34 import org.mule.umo.FutureMessageResult;
35 import org.mule.umo.MessagingException;
36 import org.mule.umo.UMODescriptor;
37 import org.mule.umo.UMOEvent;
38 import org.mule.umo.UMOException;
39 import org.mule.umo.UMOMessage;
40 import org.mule.umo.UMOSession;
41 import org.mule.umo.endpoint.UMOEndpoint;
42 import org.mule.umo.endpoint.UMOEndpointURI;
43 import org.mule.umo.lifecycle.Disposable;
44 import org.mule.umo.manager.UMOManager;
45 import org.mule.umo.provider.DispatchException;
46 import org.mule.umo.provider.ReceiveException;
47 import org.mule.umo.provider.UMOConnector;
48 import org.mule.umo.provider.UMOStreamMessageAdapter;
49 import org.mule.umo.transformer.UMOTransformer;
50 import org.mule.util.MuleObjectHelper;
51 import org.mule.util.StringUtils;
52
53 import java.util.ArrayList JavaDoc;
54 import java.util.HashMap JavaDoc;
55 import java.util.Iterator JavaDoc;
56 import java.util.List JavaDoc;
57 import java.util.Map JavaDoc;
58
59 /**
60  * <code>MuleClient</code> is a simple interface for Mule clients to send and
61  * receive events from a Mule Server. In most Mule applications events are triggered
62  * by some external occurrence such as a message being received on a queue or file
63  * being copied to a directory. The Mule client allows the user to send and receive
64  * events programmatically through its Api.
65  * <p>
66  * The client defines a UMOEndpointURI which is used to determine how a message is
67  * sent of received. The url defines the protocol, the endpointUri destination of the
68  * message and optionally the endpoint to use when dispatching the event. For
69  * example:
70  * <p>
71  * <code>vm://my.object</code> dispatches to a <code>my.object</code> destination
72  * using the VM endpoint. There needs to be a global VM endpoint registered for the
73  * message to be sent.
74  * <p>
75  * <code>jms://jmsProvider/orders.topic</code> dispatches a JMS message via the
76  * globally registered jmsProvider over a topic destination called
77  * <code>orders.topic</code>.
78  * <p>
79  * <code>jms://orders.topic</code> is equivalent to the above except that the
80  * endpoint is determined by the protocol, so the first JMS endpoint is used.
81  * <p>
82  * Note that there must be a configured MuleManager for this client to work. It will
83  * use the one available using <code>MuleManager.getInstance()</code>
84  *
85  * @see org.mule.impl.endpoint.MuleEndpointURI
86  */

87 public class MuleClient implements Disposable
88 {
89     /**
90      * logger used by this class
91      */

92     protected static Log logger = LogFactory.getLog(MuleClient.class);
93
94     /**
95      * the local UMOManager instance
96      */

97     private UMOManager manager;
98
99     /**
100      * an ExecutorService for async messages (optional)
101      * <p>
102      * TODO MULE-732: currently always null, any async sends will transparently fall
103      * back to FutureMessageResult's executor. It will need to be created either via
104      * a MuleClient "asyncThreadingProfile" or pulled from MuleManager (part of the
105      * future ManagementContext?). Unless daeon threads are used it will be important
106      * to properly shutdown this pool in {@link #dispose()}.
107      */

108     private ExecutorService executor = null;
109
110     private List JavaDoc dispatchers = new ArrayList JavaDoc();
111
112     // configuration helper for the client
113
QuickConfigurationBuilder builder = null;
114
115     private MuleCredentials user;
116
117     /**
118      * Creates a default Mule client that will use the default serverEndpoint to
119      * connect to a remote server instance.
120      *
121      * @throws UMOException
122      */

123     public MuleClient() throws UMOException
124     {
125         init(/* startManager */true);
126     }
127
128     /**
129      * Creates a default Mule client that will use the default serverEndpoint to
130      * connect to a remote server instance.
131      *
132      * @param startManager start the Mule Manager if it has not yet been initialised
133      * @throws UMOException
134      */

135     public MuleClient(boolean startManager) throws UMOException
136     {
137         init(startManager);
138     }
139
140     /**
141      * Configures a Mule CLient instance using the the default
142      * MuleXmlConfigurationBuilder to parse the config resources
143      *
144      * @param configResources a config resource location to configure this client
145      * with
146      * @throws ConfigurationException is there is a MuleManager instance already
147      * running in this JVM or if the builder fails to configure the
148      * Manager
149      */

150     public MuleClient(String JavaDoc configResources) throws UMOException
151     {
152         this(configResources, new MuleXmlConfigurationBuilder());
153     }
154
155     /**
156      * Configures a new MuleClient and either uses an existing Manager running in
157      * this JVM or creates a new empty manager
158      *
159      * @param user the username to use when connecting to a remote server instance
160      * @param password the password for the user
161      * @throws UMOException
162      */

163     public MuleClient(String JavaDoc user, String JavaDoc password) throws UMOException
164     {
165         init(/* startManager */true);
166         this.user = new MuleCredentials(user, password.toCharArray());
167     }
168
169     /**
170      * Configures a Mule Client instance
171      *
172      * @param configResources a config resource location to configure this client
173      * with
174      * @param builder the configuration builder to use
175      * @throws ConfigurationException is there is a MuleManager instance already
176      * running in this JVM or if the builder fails to configure the
177      * Manager
178      */

179     public MuleClient(String JavaDoc configResources, ConfigurationBuilder builder) throws ConfigurationException
180     {
181         if (MuleManager.isInstanciated())
182         {
183             throw new ConfigurationException(new Message(Messages.MANAGER_IS_ALREADY_CONFIGURED));
184         }
185         if (builder == null)
186         {
187             logger.info("Builder passed in was null, using default builder: "
188                         + MuleXmlConfigurationBuilder.class.getName());
189             builder = new MuleXmlConfigurationBuilder();
190         }
191         manager = builder.configure(configResources, null);
192     }
193
194     /**
195      * Configures a Mule Client instance
196      *
197      * @param configResources a config resource location to configure this client
198      * with
199      * @param builder the configuration builder to use
200      * @param user the username to use when connecting to a remote server instance
201      * @param password the password for the user
202      * @throws ConfigurationException is there is a MuleManager instance already
203      * running in this JVM or if the builder fails to configure the
204      * Manager
205      */

206     public MuleClient(String JavaDoc configResources, ConfigurationBuilder builder, String JavaDoc user, String JavaDoc password)
207         throws ConfigurationException
208     {
209         this(configResources, builder);
210         this.user = new MuleCredentials(user, password.toCharArray());
211     }
212
213     /**
214      * Initialises a default MuleManager for use by the client.
215      *
216      * @param startManager start the Mule Manager if it has not yet been initialised
217      * @throws UMOException
218      */

219     private void init(boolean startManager) throws UMOException
220     {
221         // if we are creating a server for this client then set client mode
222
// this will disable Admin connections by default;
223
// If there is no local manager present create a default manager
224
if (MuleManager.isInstanciated())
225         {
226             if (logger.isInfoEnabled())
227             {
228                 logger.info("There is already a manager available to this client locally, no need to create a new one");
229             }
230         }
231         else
232         {
233             MuleManager.getConfiguration().setClientMode(true);
234             if (logger.isInfoEnabled())
235             {
236                 logger.info("There is no manager instance available locally for this client, Creating a new Manager");
237             }
238         }
239
240         manager = MuleManager.getInstance();
241         builder = new QuickConfigurationBuilder();
242
243         if (!manager.isInitialised() && startManager == true)
244         {
245             if (logger.isInfoEnabled()) logger.info("Starting Mule Manager for this client");
246             ((MuleManager)manager).start();
247         }
248     }
249
250     /**
251      * Dispatches an event asynchronously to a endpointUri via a mule server. the Url
252      * determines where to dispathc the event to, this can be in the form of
253      *
254      * @param url the Mule url used to determine the destination and transport of the
255      * message
256      * @param payload the object that is the payload of the event
257      * @param messageProperties any properties to be associated with the payload. In
258      * the case of Jms you could set the JMSReplyTo property in these
259      * properties.
260      * @throws org.mule.umo.UMOException
261      */

262     public void dispatch(String JavaDoc url, Object JavaDoc payload, Map JavaDoc messageProperties) throws UMOException
263     {
264         dispatch(url, new MuleMessage(payload, messageProperties));
265     }
266
267     /**
268      * Dispatches an event asynchronously to a endpointUri via a mule server. the Url
269      * determines where to dispathc the event to, this can be in the form of
270      *
271      * @param url the Mule url used to determine the destination and transport of the
272      * message
273      * @param message the message to send
274      * @throws org.mule.umo.UMOException
275      */

276     public void dispatch(String JavaDoc url, UMOMessage message) throws UMOException
277     {
278         UMOEvent event = getEvent(message, url, false, false);
279         try
280         {
281             event.getSession().dispatchEvent(event);
282         }
283         catch (UMOException e)
284         {
285             throw e;
286         }
287         catch (Exception JavaDoc e)
288         {
289             throw new DispatchException(new Message("client", 1), event.getMessage(), event.getEndpoint(), e);
290         }
291     }
292
293     /**
294      * Dispatches a Stream event asynchronously to a endpointUri via a mule server.
295      * the Url determines where to dispathc the event to, this can be in the form of
296      *
297      * @param url the Mule url used to determine the destination and transport of the
298      * message
299      * @param message the message to send
300      * @throws org.mule.umo.UMOException
301      */

302     public void dispatchStream(String JavaDoc url, UMOStreamMessageAdapter message) throws UMOException
303     {
304         UMOEvent event = getEvent(new MuleMessage(message), url, false, true);
305         try
306         {
307             event.getSession().dispatchEvent(event);
308         }
309         catch (UMOException e)
310         {
311             throw e;
312         }
313         catch (Exception JavaDoc e)
314         {
315             throw new DispatchException(new Message("client", 1), event.getMessage(), event.getEndpoint(), e);
316         }
317     }
318
319     public UMOStreamMessageAdapter sendStream(String JavaDoc url, UMOStreamMessageAdapter message)
320         throws UMOException
321     {
322         return sendStream(url, message, UMOEvent.TIMEOUT_NOT_SET_VALUE);
323     }
324
325     /**
326      * Sends a streaming event synchronously to a endpointUri via a mule server and a
327      * resulting stream is set on the passed Stream Mesage Adapter.
328      *
329      * @param url the Mule url used to determine the destination and transport of the
330      * message
331      * @param message The message to send
332      * @param timeout The time in milliseconds the the call should block waiting for
333      * a response
334      * @throws org.mule.umo.UMOException
335      */

336     public UMOStreamMessageAdapter sendStream(String JavaDoc url, UMOStreamMessageAdapter message, int timeout)
337         throws UMOException
338     {
339         UMOEvent event = getEvent(new MuleMessage(message), url, true, true);
340         event.setTimeout(timeout);
341         try
342         {
343             UMOMessage result = event.getSession().sendEvent(event);
344             if (result != null)
345             {
346                 if (result.getAdapter() instanceof UMOStreamMessageAdapter)
347                 {
348                     return (UMOStreamMessageAdapter)result.getAdapter();
349                 }
350                 else
351                 {
352                     // todo i18n (though this case should never happen...)
353
throw new IllegalStateException JavaDoc(
354                         "Mismatch of stream states. A stream was used for outbound channel, but a stream was not used for the response");
355                 }
356             }
357         }
358         catch (UMOException e)
359         {
360             throw e;
361         }
362         catch (Exception JavaDoc e)
363         {
364             throw new DispatchException(new Message("client", 1), event.getMessage(), event.getEndpoint(), e);
365         }
366         return null;
367     }
368
369     /**
370      * sends an event synchronously to a components
371      *
372      * @param component the name of the Mule components to send to
373      * @param transformers a comma separated list of transformers to apply to the
374      * result message
375      * @param payload the object that is the payload of the event
376      * @param messageProperties any properties to be associated with the payload. as
377      * null
378      * @return the result message if any of the invocation
379      * @throws org.mule.umo.UMOException if the dispatch fails or the components or
380      * transfromers cannot be found
381      */

382     public UMOMessage sendDirect(String JavaDoc component, String JavaDoc transformers, Object JavaDoc payload, Map JavaDoc messageProperties)
383         throws UMOException
384     {
385         UMOMessage message = new MuleMessage(payload, messageProperties);
386         return sendDirect(component, transformers, message);
387     }
388
389     /**
390      * sends an event synchronously to a components
391      *
392      * @param component the name of the Mule components to send to
393      * @param transformers a comma separated list of transformers to apply to the
394      * result message
395      * @param message the message to send
396      * @return the result message if any of the invocation
397      * @throws org.mule.umo.UMOException if the dispatch fails or the components or
398      * transfromers cannot be found
399      */

400     public UMOMessage sendDirect(String JavaDoc component, String JavaDoc transformers, UMOMessage message)
401         throws UMOException
402     {
403         boolean compregistered = getManager().getModel().isComponentRegistered(component);
404         if (!compregistered)
405         {
406             throw new MessagingException(new Message(Messages.X_NOT_REGISTERED_WITH_MANAGER, "Component '"
407                                                                                              + component
408                                                                                              + "'"), message,
409                 null);
410         }
411         UMOTransformer trans = null;
412         if (transformers != null)
413         {
414             trans = MuleObjectHelper.getTransformer(transformers, ",");
415         }
416
417         if (!MuleManager.getConfiguration().isSynchronous())
418         {
419             logger.warn("The mule manager is running synchronously, a null message payload will be returned");
420         }
421         UMOSession session = getManager().getModel().getComponentSession(component);
422         UMOEndpoint endpoint = getDefaultClientEndpoint(session.getComponent().getDescriptor(),
423             message.getPayload());
424         UMOEvent event = new MuleEvent(message, endpoint, session, true);
425
426         if (logger.isDebugEnabled())
427         {
428             logger.debug("MuleClient sending event direct to: " + component + ". Event is: " + event);
429         }
430
431         UMOMessage result = event.getComponent().sendEvent(event);
432
433         if (logger.isDebugEnabled())
434         {
435             logger.debug("Result of MuleClient sendDirect is: "
436                          + (result == null ? "null" : result.getPayload()));
437         }
438
439         if (result != null && trans != null)
440         {
441             return new MuleMessage(trans.transform(result.getPayload()));
442         }
443         else
444         {
445             return result;
446         }
447     }
448
449     /**
450      * dispatches an event asynchronously to the components
451      *
452      * @param component the name of the Mule components to dispatch to
453      * @param payload the object that is the payload of the event
454      * @param messageProperties any properties to be associated with the payload. as
455      * null
456      * @throws org.mule.umo.UMOException if the dispatch fails or the components or
457      * transfromers cannot be found
458      */

459     public void dispatchDirect(String JavaDoc component, Object JavaDoc payload, Map JavaDoc messageProperties) throws UMOException
460     {
461         dispatchDirect(component, new MuleMessage(payload, messageProperties));
462     }
463
464     /**
465      * dispatches an event asynchronously to the components
466      *
467      * @param component the name of the Mule components to dispatch to
468      * @param message the message to send
469      * @throws org.mule.umo.UMOException if the dispatch fails or the components or
470      * transfromers cannot be found
471      */

472     public void dispatchDirect(String JavaDoc component, UMOMessage message) throws UMOException
473     {
474         boolean compregistered = getManager().getModel().isComponentRegistered(component);
475         if (!compregistered)
476         {
477             throw new MessagingException(new Message(Messages.X_NOT_REGISTERED_WITH_MANAGER, "Component '"
478                                                                                              + component
479                                                                                              + "'"), message,
480                 null);
481         }
482         UMOSession session = getManager().getModel().getComponentSession(component);
483         UMOEndpoint endpoint = getDefaultClientEndpoint(session.getComponent().getDescriptor(),
484             message.getPayload());
485         UMOEvent event = new MuleEvent(message, endpoint, session, true);
486
487         if (logger.isDebugEnabled())
488         {
489             logger.debug("MuleClient dispatching event direct to: " + component + ". Event is: " + event);
490         }
491
492         event.getComponent().dispatchEvent(event);
493     }
494
495     /**
496      * sends an event request to a Url, making the result of the event trigger
497      * available as a Future result that can be accessed later by client code.
498      *
499      * @param url the url to make a request on
500      * @param payload the object that is the payload of the event
501      * @param messageProperties any properties to be associated with the payload. as
502      * null
503      * @return the result message if any of the invocation
504      * @throws org.mule.umo.UMOException if the dispatch fails or the components or
505      * transfromers cannot be found
506      */

507     public FutureMessageResult sendAsync(final String JavaDoc url, final Object JavaDoc payload, final Map JavaDoc messageProperties)
508         throws UMOException
509     {
510         return sendAsync(url, payload, messageProperties, 0);
511     }
512
513     /**
514      * sends an event request to a Url, making the result of the event trigger
515      * available as a Future result that can be accessed later by client code.
516      *
517      * @param url the url to make a request on
518      * @param message the message to send
519      * @return the result message if any of the invocation
520      * @throws org.mule.umo.UMOException if the dispatch fails or the components or
521      * transfromers cannot be found
522      */

523     public FutureMessageResult sendAsync(final String JavaDoc url, final UMOMessage message) throws UMOException
524     {
525         return sendAsync(url, message, UMOEvent.TIMEOUT_NOT_SET_VALUE);
526     }
527
528     /**
529      * sends an event request to a Url, making the result of the event trigger
530      * available as a Future result that can be accessed later by client code.
531      *
532      * @param url the url to make a request on
533      * @param payload the object that is the payload of the event
534      * @param messageProperties any properties to be associated with the payload. as
535      * null
536      * @param timeout how long to block in milliseconds waiting for a result
537      * @return the result message if any of the invocation
538      * @throws org.mule.umo.UMOException if the dispatch fails or the components or
539      * transfromers cannot be found
540      */

541     public FutureMessageResult sendAsync(final String JavaDoc url,
542                                          final Object JavaDoc payload,
543                                          final Map JavaDoc messageProperties,
544                                          final int timeout) throws UMOException
545     {
546         return sendAsync(url, new MuleMessage(payload, messageProperties), timeout);
547     }
548
549     /**
550      * sends an event request to a Url, making the result of the event trigger
551      * available as a Future result that can be accessed later by client code.
552      *
553      * @param url the url to make a request on
554      * @param message the message to send
555      * @param timeout how long to block in milliseconds waiting for a result
556      * @return the result message if any of the invocation
557      * @throws org.mule.umo.UMOException if the dispatch fails or the components or
558      * transfromers cannot be found
559      */

560     public FutureMessageResult sendAsync(final String JavaDoc url, final UMOMessage message, final int timeout)
561         throws UMOException
562     {
563         Callable call = new Callable()
564         {
565             public Object JavaDoc call() throws Exception JavaDoc
566             {
567                 return send(url, message, timeout);
568             }
569         };
570
571         FutureMessageResult result = new FutureMessageResult(call);
572
573         if (executor != null)
574         {
575             result.setExecutor(executor);
576         }
577
578         result.execute();
579         return result;
580     }
581
582     /**
583      * sends an event to a components on a local Mule instance, while making the
584      * result of the event trigger available as a Future result that can be accessed
585      * later by client code. If forwardDirectRequests flag s set and the components
586      * is not found on the local Mule instance it will forward to a remote server.
587      * Users can endpoint a url to a remote Mule server in the constructor of a Mule
588      * client, by default the default Mule server url tcp://localhost:60504 is used.
589      *
590      * @param component the name of the Mule components to send to
591      * @param transformers a comma separated list of transformers to apply to the
592      * result message
593      * @param payload the object that is the payload of the event
594      * @param messageProperties any properties to be associated with the payload. as
595      * null
596      * @return the result message if any of the invocation
597      * @throws org.mule.umo.UMOException if the dispatch fails or the components or
598      * transfromers cannot be found
599      */

600     public FutureMessageResult sendDirectAsync(final String JavaDoc component,
601                                                String JavaDoc transformers,
602                                                final Object JavaDoc payload,
603                                                final Map JavaDoc messageProperties) throws UMOException
604     {
605         return sendDirectAsync(component, transformers, new MuleMessage(payload, messageProperties));
606     }
607
608     /**
609      * sends an event to a components on a local Mule instance, while making the
610      * result of the event trigger available as a Future result that can be accessed
611      * later by client code. If forwardDirectRequests flag s set and the components
612      * is not found on the local Mule instance it will forward to a remote server.
613      * Users can endpoint a url to a remote Mule server in the constructor of a Mule
614      * client, by default the default Mule server url tcp://localhost:60504 is used.
615      *
616      * @param component the name of the Mule components to send to
617      * @param transformers a comma separated list of transformers to apply to the
618      * result message
619      * @param message the message to send
620      * @return the result message if any of the invocation
621      * @throws org.mule.umo.UMOException if the dispatch fails or the components or
622      * transfromers cannot be found
623      */

624     public FutureMessageResult sendDirectAsync(final String JavaDoc component,
625                                                String JavaDoc transformers,
626                                                final UMOMessage message) throws UMOException
627     {
628         Callable call = new Callable()
629         {
630             public Object JavaDoc call() throws Exception JavaDoc
631             {
632                 return sendDirect(component, null, message);
633             }
634         };
635
636         FutureMessageResult result = new FutureMessageResult(call);
637
638         if (executor != null)
639         {
640             result.setExecutor(executor);
641         }
642
643         if (StringUtils.isNotBlank(transformers))
644         {
645             result.setTransformer(MuleObjectHelper.getTransformer(transformers, ","));
646         }
647
648         result.execute();
649         return result;
650     }
651
652     /**
653      * Sends an event synchronously to a endpointUri via a mule server and a
654      * resulting message is returned.
655      *
656      * @param url the Mule url used to determine the destination and transport of the
657      * message
658      * @param payload the object that is the payload of the event
659      * @param messageProperties any properties to be associated with the payload. In
660      * the case of Jms you could set the JMSReplyTo property in these
661      * properties.
662      * @return A return message, this could be null if the the components invoked
663      * explicitly sets a return as null
664      * @throws org.mule.umo.UMOException
665      */

666     public UMOMessage send(String JavaDoc url, Object JavaDoc payload, Map JavaDoc messageProperties) throws UMOException
667     {
668         return send(url, payload, messageProperties, UMOEvent.TIMEOUT_NOT_SET_VALUE);
669     }
670
671     /**
672      * Sends an event synchronously to a endpointUri via a mule server and a
673      * resulting message is returned.
674      *
675      * @param url the Mule url used to determine the destination and transport of the
676      * message
677      * @param message the Message for the event
678      * @return A return message, this could be null if the the components invoked
679      * explicitly sets a return as null
680      * @throws org.mule.umo.UMOException
681      */

682     public UMOMessage send(String JavaDoc url, UMOMessage message) throws UMOException
683     {
684         return send(url, message, UMOEvent.TIMEOUT_NOT_SET_VALUE);
685     }
686
687     /**
688      * Sends an event synchronously to a endpointUri via a mule server and a
689      * resulting message is returned.
690      *
691      * @param url the Mule url used to determine the destination and transport of the
692      * message
693      * @param payload the object that is the payload of the event
694      * @param messageProperties any properties to be associated with the payload. In
695      * the case of Jms you could set the JMSReplyTo property in these
696      * properties.
697      * @param timeout The time in milliseconds the the call should block waiting for
698      * a response
699      * @return A return message, this could be null if the the components invoked
700      * explicitly sets a return as null
701      * @throws org.mule.umo.UMOException
702      */

703     public UMOMessage send(String JavaDoc url, Object JavaDoc payload, Map JavaDoc messageProperties, int timeout)
704         throws UMOException
705     {
706         if (messageProperties == null)
707         {
708             messageProperties = new HashMap JavaDoc();
709         }
710         if (messageProperties.get(MuleProperties.MULE_REMOTE_SYNC_PROPERTY) == null)
711         {
712             messageProperties.put(MuleProperties.MULE_REMOTE_SYNC_PROPERTY, "true");
713         }
714         UMOMessage message = new MuleMessage(payload, messageProperties);
715         return send(url, message, timeout);
716     }
717
718     /**
719      * Sends an event synchronously to a endpointUri via a mule server and a
720      * resulting message is returned.
721      *
722      * @param url the Mule url used to determine the destination and transport of the
723      * message
724      * @param message The message to send
725      * @param timeout The time in milliseconds the the call should block waiting for
726      * a response
727      * @return A return message, this could be null if the the components invoked
728      * explicitly sets a return as null
729      * @throws org.mule.umo.UMOException
730      */

731     public UMOMessage send(String JavaDoc url, UMOMessage message, int timeout) throws UMOException
732     {
733         UMOEvent event = getEvent(message, url, true, false);
734         event.setTimeout(timeout);
735
736         try
737         {
738             return event.getSession().sendEvent(event);
739         }
740         catch (UMOException e)
741         {
742             throw e;
743         }
744         catch (Exception JavaDoc e)
745         {
746             throw new DispatchException(new Message("client", 1), event.getMessage(), event.getEndpoint(), e);
747         }
748     }
749
750     /**
751      * Will receive an event from an endpointUri determined by the url
752      *
753      * @param url the Mule url used to determine the destination and transport of the
754      * message
755      * @param timeout how long to block waiting to receive the event, if set to 0 the
756      * receive will not wait at all and if set to -1 the receive will wait
757      * forever
758      * @return the message received or null if no message was received
759      * @throws org.mule.umo.UMOException
760      */

761     public UMOMessage receive(String JavaDoc url, long timeout) throws UMOException
762     {
763         UMOEndpoint endpoint = getEndpoint(url, UMOEndpoint.ENDPOINT_TYPE_RECEIVER);
764         try
765         {
766             UMOMessage message = endpoint.getConnector().getDispatcher(endpoint).receive(endpoint, timeout);
767             if (message != null && endpoint.getTransformer() != null)
768             {
769                 if (endpoint.getTransformer().isSourceTypeSupported(message.getPayload().getClass()))
770                 {
771                     message = new MuleMessage(endpoint.getTransformer().transform(message.getPayload()),
772                         message);
773                 }
774             }
775             return message;
776         }
777         catch (Exception JavaDoc e)
778         {
779             throw new ReceiveException(endpoint, timeout, e);
780         }
781     }
782
783     /**
784      * Will receive an event from an endpointUri determined by the url
785      *
786      * @param url the Mule url used to determine the destination and transport of the
787      * message
788      * @param transformers A comma separated list of transformers used to apply to
789      * the result message
790      * @param timeout how long to block waiting to receive the event, if set to 0 the
791      * receive will not wait at all and if set to -1 the receive will wait
792      * forever
793      * @return the message received or null if no message was received
794      * @throws org.mule.umo.UMOException
795      */

796     public UMOMessage receive(String JavaDoc url, String JavaDoc transformers, long timeout) throws UMOException
797     {
798         return receive(url, MuleObjectHelper.getTransformer(transformers, ","), timeout);
799     }
800
801     /**
802      * Will receive an event from an endpointUri determined by the url
803      *
804      * @param url the Mule url used to determine the destination and transport of the
805      * message
806      * @param transformer A transformer used to apply to the result message
807      * @param timeout how long to block waiting to receive the event, if set to 0 the
808      * receive will not wait at all and if set to -1 the receive will wait
809      * forever
810      * @return the message received or null if no message was received
811      * @throws org.mule.umo.UMOException
812      */

813     public UMOMessage receive(String JavaDoc url, UMOTransformer transformer, long timeout) throws UMOException
814     {
815         UMOMessage message = receive(url, timeout);
816         if (message != null && transformer != null)
817         {
818             return new MuleMessage(transformer.transform(message.getPayload()));
819         }
820         else
821         {
822             return message;
823         }
824     }
825
826     /**
827      * Packages a mule event for the current request
828      *
829      * @param message the event payload
830      * @param uri the destination endpointUri
831      * @param synchronous whether the event will be synchronously processed
832      * @param streaming
833      * @return the UMOEvent
834      * @throws UMOException
835      */

836     protected UMOEvent getEvent(UMOMessage message, String JavaDoc uri, boolean synchronous, boolean streaming)
837         throws UMOException
838     {
839         UMOEndpoint endpoint = getEndpoint(uri, UMOEndpoint.ENDPOINT_TYPE_SENDER);
840         if (!endpoint.getConnector().isStarted() && manager.isStarted())
841         {
842             endpoint.getConnector().startConnector();
843         }
844         endpoint.setStreaming(streaming);
845         try
846         {
847             MuleSession session = new MuleSession(message,
848                 ((AbstractConnector)endpoint.getConnector()).getSessionHandler());
849
850             if (user != null)
851             {
852                 message.setProperty(MuleProperties.MULE_USER_PROPERTY, MuleCredentials.createHeader(
853                     user.getUsername(), user.getPassword()));
854             }
855             MuleEvent event = new MuleEvent(message, endpoint, session, synchronous);
856             return event;
857         }
858         catch (Exception JavaDoc e)
859         {
860             throw new DispatchException(new Message(Messages.FAILED_TO_CREATE_X, "Client event"), message,
861                 endpoint, e);
862         }
863     }
864
865     protected UMOEndpoint getEndpoint(String JavaDoc uri, String JavaDoc type) throws UMOException
866     {
867         UMOEndpoint endpoint = manager.lookupEndpoint(uri);
868         if (endpoint == null)
869         {
870             endpoint = MuleEndpoint.getOrCreateEndpointForUri(uri, type);
871         }
872         return endpoint;
873     }
874
875     protected UMOEndpoint getDefaultClientEndpoint(UMODescriptor descriptor, Object JavaDoc payload)
876         throws UMOException
877     {
878         // as we are bypassing the message transport layer we need to check that
879
UMOEndpoint endpoint = descriptor.getInboundEndpoint();
880         if (endpoint != null)
881         {
882             if (endpoint.getTransformer() != null)
883             {
884                 if (endpoint.getTransformer().isSourceTypeSupported(payload.getClass()))
885                 {
886                     return endpoint;
887                 }
888                 else
889                 {
890                     endpoint = new MuleEndpoint(endpoint);
891                     endpoint.setTransformer(null);
892                     return endpoint;
893                 }
894             }
895             else
896             {
897                 return endpoint;
898             }
899         }
900         else
901         {
902             UMOConnector connector = null;
903             UMOEndpointURI defaultEndpointUri = new MuleEndpointURI("vm://mule.client");
904             connector = ConnectorFactory.createConnector(defaultEndpointUri);
905             manager.registerConnector(connector);
906             connector.startConnector();
907             endpoint = new MuleEndpoint("muleClientProvider", defaultEndpointUri, connector, null,
908                 UMOEndpoint.ENDPOINT_TYPE_RECEIVER, 0, null, null);
909         }
910
911         manager.registerEndpoint(endpoint);
912         return endpoint;
913     }
914
915     /**
916      * Sends an event synchronously to a endpointUri via a mule server without
917      * waiting for the result.
918      *
919      * @param url the Mule url used to determine the destination and transport of the
920      * message
921      * @param payload the object that is the payload of the event
922      * @param messageProperties any properties to be associated with the payload. In
923      * the case of Jms you could set the JMSReplyTo property in these
924      * properties.
925      * @throws org.mule.umo.UMOException
926      */

927     public void sendNoReceive(String JavaDoc url, Object JavaDoc payload, Map JavaDoc messageProperties) throws UMOException
928     {
929         if (messageProperties == null)
930         {
931             messageProperties = new HashMap JavaDoc();
932         }
933         messageProperties.put(MuleProperties.MULE_REMOTE_SYNC_PROPERTY, "false");
934         UMOMessage message = new MuleMessage(payload, messageProperties);
935         UMOEvent event = getEvent(message, url, true, false);
936         try
937         {
938             event.getSession().sendEvent(event);
939         }
940         catch (UMOException e)
941         {
942             throw e;
943         }
944         catch (Exception JavaDoc e)
945         {
946             throw new DispatchException(new Message("client", 1), event.getMessage(), event.getEndpoint(), e);
947         }
948     }
949
950     /**
951      * Overriding methods may want to return a custom manager here
952      *
953      * @return the UMOManager to use
954      */

955     public UMOManager getManager()
956     {
957         return MuleManager.getInstance();
958     }
959
960     /**
961      * Registers a java object as a Umo pcomponent that listens for events on the
962      * given url. By default the ThreadingProfile for the components will be set so
963      * that there will only be one thread of execution.
964      *
965      * @param component any java object, Mule will it's endpointUri discovery to
966      * determine which event to invoke based on the evnet payload type
967      * @param name The identifying name of the components. This can be used to later
968      * unregister it
969      * @param listenerEndpoint The url endpointUri to listen to
970      * @throws UMOException
971      */

972     public void registerComponent(Object JavaDoc component, String JavaDoc name, UMOEndpointURI listenerEndpoint)
973         throws UMOException
974     {
975         builder.registerComponentInstance(component, name, listenerEndpoint, null);
976     }
977
978     /**
979      * Registers a java object as a Umo pcomponent that listens for and sends events
980      * on the given urls. By default the ThreadingProfile for the components will be
981      * set so that there will only be one thread of execution.
982      *
983      * @param component any java object, Mule will it's endpointUri discovery to
984      * determine which event to invoke based on the evnet payload type
985      * @param name The identifying name of the components. This can be used to later
986      * unregister it
987      * @param listenerEndpoint The url endpointUri to listen to
988      * @param sendEndpoint The url endpointUri to dispatch to
989      * @throws UMOException
990      */

991     public void registerComponent(Object JavaDoc component,
992                                   String JavaDoc name,
993                                   MuleEndpointURI listenerEndpoint,
994                                   MuleEndpointURI sendEndpoint) throws UMOException
995     {
996         builder.registerComponentInstance(component, name, listenerEndpoint, sendEndpoint);
997     }
998
999     /**
1000     * Registers a user configured MuleDescriptor of a components to the server. If
1001     * users want to register object instances with the server rather than class
1002     * names that get created at runtime or reference to objects in the container,
1003     * the user must call the descriptors setImplementationInstance() method - <code>
1004     * MyBean implementation = new MyBean();
1005     * descriptor.setImplementationInstance(implementation);
1006     * </code>
1007     * Calling this method is equivilent to calling UMOModel.registerComponent(..)
1008     *
1009     * @param descriptor the componet descriptor to register
1010     * @throws UMOException the descriptor is invalid or cannot be initialised or
1011     * started
1012     * @see org.mule.umo.model.UMOModel
1013     */

1014    public void registerComponent(UMODescriptor descriptor) throws UMOException
1015    {
1016        builder.registerComponent(descriptor);
1017    }
1018
1019    /**
1020     * Unregisters a previously register components. This will also unregister any
1021     * listeners for the components Calling this method is equivilent to calling
1022     * UMOModel.unregisterComponent(..)
1023     *
1024     * @param name the name of the componet to unregister
1025     * @throws UMOException if unregistering the components fails, i.e. The
1026     * underlying transport fails to unregister a listener. If the
1027     * components does not exist, this method should not throw an
1028     * exception.
1029     * @see org.mule.umo.model.UMOModel
1030     */

1031    public void unregisterComponent(String JavaDoc name) throws UMOException
1032    {
1033        builder.unregisterComponent(name);
1034    }
1035
1036    public RemoteDispatcher getRemoteDispatcher(String JavaDoc serverEndpoint) throws UMOException
1037    {
1038        RemoteDispatcher rd = new RemoteDispatcher(serverEndpoint);
1039        rd.setExecutorService(executor);
1040        dispatchers.add(rd);
1041        return rd;
1042    }
1043
1044    public RemoteDispatcher getRemoteDispatcher(String JavaDoc serverEndpoint, String JavaDoc user, String JavaDoc password)
1045        throws UMOException
1046    {
1047        RemoteDispatcher rd = new RemoteDispatcher(serverEndpoint, new MuleCredentials(user,
1048            password.toCharArray()));
1049        rd.setExecutorService(executor);
1050        dispatchers.add(rd);
1051        return rd;
1052    }
1053
1054    /**
1055     * Will dispose the MuleManager instance *IF* a new instance was created for this
1056     * client. Otherwise this method only cleans up resources no longer needed
1057     */

1058    public void dispose()
1059    {
1060        synchronized (dispatchers)
1061        {
1062            for (Iterator JavaDoc iterator = dispatchers.iterator(); iterator.hasNext();)
1063            {
1064                RemoteDispatcher remoteDispatcher = (RemoteDispatcher)iterator.next();
1065                remoteDispatcher.dispose();
1066                remoteDispatcher = null;
1067            }
1068            dispatchers.clear();
1069        }
1070        // Dispose the manager only if the manager was created for this client
1071
if (MuleManager.getConfiguration().isClientMode())
1072        {
1073            manager.dispose();
1074        }
1075    }
1076
1077    public void setProperty(Object JavaDoc key, Object JavaDoc value)
1078    {
1079        manager.setProperty(key, value);
1080    }
1081
1082    public Object JavaDoc getProperty(Object JavaDoc key)
1083    {
1084        return manager.getProperty(key);
1085    }
1086
1087    public MuleConfiguration getConfiguration()
1088    {
1089        return MuleManager.getConfiguration();
1090    }
1091}
1092
Popular Tags