1
2
3
4
5
6
7
8
9
10
11 package org.mule.extras.client;
12
13 import org.mule.MuleManager;
14 import org.mule.config.ConfigurationBuilder;
15 import org.mule.config.ConfigurationException;
16 import org.mule.config.MuleConfiguration;
17 import org.mule.config.MuleProperties;
18 import org.mule.config.builders.MuleXmlConfigurationBuilder;
19 import org.mule.config.builders.QuickConfigurationBuilder;
20 import org.mule.config.i18n.CoreMessages;
21 import org.mule.extras.client.i18n.ClientMessages;
22 import org.mule.impl.MuleEvent;
23 import org.mule.impl.MuleMessage;
24 import org.mule.impl.MuleSession;
25 import org.mule.impl.endpoint.MuleEndpoint;
26 import org.mule.impl.endpoint.MuleEndpointURI;
27 import org.mule.impl.model.ModelHelper;
28 import org.mule.impl.security.MuleCredentials;
29 import org.mule.providers.AbstractConnector;
30 import org.mule.providers.service.TransportFactory;
31 import org.mule.umo.FutureMessageResult;
32 import org.mule.umo.MessagingException;
33 import org.mule.umo.UMODescriptor;
34 import org.mule.umo.UMOEvent;
35 import org.mule.umo.UMOException;
36 import org.mule.umo.UMOMessage;
37 import org.mule.umo.UMOSession;
38 import org.mule.umo.endpoint.UMOEndpoint;
39 import org.mule.umo.endpoint.UMOEndpointURI;
40 import org.mule.umo.lifecycle.Disposable;
41 import org.mule.umo.manager.UMOManager;
42 import org.mule.umo.provider.DispatchException;
43 import org.mule.umo.provider.ReceiveException;
44 import org.mule.umo.provider.UMOConnector;
45 import org.mule.umo.provider.UMOStreamMessageAdapter;
46 import org.mule.umo.transformer.UMOTransformer;
47 import org.mule.util.MuleObjectHelper;
48 import org.mule.util.StringUtils;
49
50 import java.util.ArrayList;
51 import java.util.HashMap;
52 import java.util.Iterator;
53 import java.util.List;
54 import java.util.Map;
55
56 import edu.emory.mathcs.backport.java.util.concurrent.Callable;
57 import edu.emory.mathcs.backport.java.util.concurrent.Executor;
58 import org.apache.commons.logging.Log;
59 import org.apache.commons.logging.LogFactory;
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89 public class MuleClient implements Disposable
90 {
91
92
93
94 protected static final Log logger = LogFactory.getLog(MuleClient.class);
95
96
97
98
99 private UMOManager manager;
100
101
102
103
104
105 private Executor asyncExecutor = null;
106
107 private List dispatchers = new ArrayList();
108
109
110 QuickConfigurationBuilder builder = null;
111
112 private MuleCredentials user;
113
114
115
116
117
118
119
120 public MuleClient() throws UMOException
121 {
122 init(
123 }
124
125
126
127
128
129
130
131
132 public MuleClient(boolean startManager) throws UMOException
133 {
134 init(startManager);
135 }
136
137
138
139
140
141
142
143
144
145
146
147 public MuleClient(String configResources) throws UMOException
148 {
149 this(configResources, new MuleXmlConfigurationBuilder());
150 }
151
152
153
154
155
156
157
158
159
160 public MuleClient(String user, String password) throws UMOException
161 {
162 init(
163 this.user = new MuleCredentials(user, password.toCharArray());
164 }
165
166
167
168
169
170
171
172
173
174
175
176 public MuleClient(String configResources, ConfigurationBuilder builder) throws ConfigurationException
177 {
178 if (MuleManager.isInstanciated())
179 {
180 throw new ConfigurationException(ClientMessages.managerIsAlreadyConfigured());
181 }
182 if (builder == null)
183 {
184 logger.info("Builder passed in was null, using default builder: "
185 + MuleXmlConfigurationBuilder.class.getName());
186 builder = new MuleXmlConfigurationBuilder();
187 }
188 manager = builder.configure(configResources, null);
189 }
190
191
192
193
194
195
196
197
198
199
200
201
202
203 public MuleClient(String configResources, ConfigurationBuilder builder, String user, String password)
204 throws ConfigurationException
205 {
206 this(configResources, builder);
207 this.user = new MuleCredentials(user, password.toCharArray());
208 }
209
210
211
212
213
214
215
216 private void init(boolean startManager) throws UMOException
217 {
218
219
220
221 if (MuleManager.isInstanciated())
222 {
223 if (logger.isInfoEnabled())
224 {
225 logger.info("There is already a manager locally available to this client, no need to create a new one");
226 }
227 }
228 else
229 {
230 MuleManager.getConfiguration().setClientMode(true);
231 if (logger.isInfoEnabled())
232 {
233 logger.info("There is no manager instance locally available for this client, creating a new Manager");
234 }
235 }
236
237 manager = MuleManager.getInstance();
238 asyncExecutor = manager.getWorkManager();
239 builder = new QuickConfigurationBuilder();
240
241 if (!manager.isInitialised() && startManager == true)
242 {
243 if (logger.isInfoEnabled()) logger.info("Starting Mule Manager for this client");
244 ((MuleManager)manager).start();
245 }
246 }
247
248
249
250
251
252
253
254
255
256
257
258
259
260 public void dispatch(String url, Object payload, Map messageProperties) throws UMOException
261 {
262 dispatch(url, new MuleMessage(payload, messageProperties));
263 }
264
265
266
267
268
269
270
271
272
273
274 public void dispatch(String url, UMOMessage message) throws UMOException
275 {
276 UMOEvent event = getEvent(message, url, false, false);
277 try
278 {
279 event.getSession().dispatchEvent(event);
280 }
281 catch (UMOException e)
282 {
283 throw e;
284 }
285 catch (Exception e)
286 {
287 throw new DispatchException(ClientMessages.failedToDispatchClientEvent(),
288 event.getMessage(), event.getEndpoint(), e);
289 }
290 }
291
292
293
294
295
296
297
298
299
300
301 public void dispatchStream(String url, UMOStreamMessageAdapter message) throws UMOException
302 {
303 UMOEvent event = getEvent(new MuleMessage(message), url, false, true);
304 try
305 {
306 event.getSession().dispatchEvent(event);
307 }
308 catch (UMOException e)
309 {
310 throw e;
311 }
312 catch (Exception e)
313 {
314 throw new DispatchException(ClientMessages.failedToDispatchClientEvent(),
315 event.getMessage(), event.getEndpoint(), e);
316 }
317 }
318
319 public UMOStreamMessageAdapter sendStream(String url, UMOStreamMessageAdapter message)
320 throws UMOException
321 {
322 return sendStream(url, message, UMOEvent.TIMEOUT_NOT_SET_VALUE);
323 }
324
325
326
327
328
329
330
331
332
333
334
335
336 public UMOStreamMessageAdapter sendStream(String 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
353 throw new IllegalStateException(
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 e)
363 {
364 throw new DispatchException(ClientMessages.failedToDispatchClientEvent(),
365 event.getMessage(), event.getEndpoint(), e);
366 }
367 return null;
368 }
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383 public UMOMessage sendDirect(String component, String transformers, Object payload, Map messageProperties)
384 throws UMOException
385 {
386 UMOMessage message = new MuleMessage(payload, messageProperties);
387 return sendDirect(component, transformers, message);
388 }
389
390
391
392
393
394
395
396
397
398
399
400
401 public UMOMessage sendDirect(String component, String transformers, UMOMessage message)
402 throws UMOException
403 {
404 boolean compregistered = ModelHelper.isComponentRegistered(component);
405 if (!compregistered)
406 {
407 throw new MessagingException(
408 CoreMessages.objectNotRegisteredWithManager("Component '" + component + "'"),
409 message, 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 = new MuleSession(ModelHelper.getComponent(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
451
452
453
454
455
456
457
458
459 public void dispatchDirect(String component, Object payload, Map messageProperties) throws UMOException
460 {
461 dispatchDirect(component, new MuleMessage(payload, messageProperties));
462 }
463
464
465
466
467
468
469
470
471
472 public void dispatchDirect(String component, UMOMessage message) throws UMOException
473 {
474 boolean compregistered = ModelHelper.isComponentRegistered(component);
475 if (!compregistered)
476 {
477 throw new MessagingException(
478 CoreMessages.objectNotRegisteredWithManager("Component '" + component + "'"),
479 message, null);
480 }
481 UMOSession session = new MuleSession(ModelHelper.getComponent(component));
482 UMOEndpoint endpoint = getDefaultClientEndpoint(session.getComponent().getDescriptor(),
483 message.getPayload());
484 UMOEvent event = new MuleEvent(message, endpoint, session, true);
485
486 if (logger.isDebugEnabled())
487 {
488 logger.debug("MuleClient dispatching event direct to: " + component + ". Event is: " + event);
489 }
490
491 event.getComponent().dispatchEvent(event);
492 }
493
494
495
496
497
498
499
500
501
502
503
504
505
506 public FutureMessageResult sendAsync(final String url, final Object payload, final Map messageProperties)
507 throws UMOException
508 {
509 return sendAsync(url, payload, messageProperties, 0);
510 }
511
512
513
514
515
516
517
518
519
520
521
522 public FutureMessageResult sendAsync(final String url, final UMOMessage message) throws UMOException
523 {
524 return sendAsync(url, message, UMOEvent.TIMEOUT_NOT_SET_VALUE);
525 }
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540 public FutureMessageResult sendAsync(final String url,
541 final Object payload,
542 final Map messageProperties,
543 final int timeout) throws UMOException
544 {
545 return sendAsync(url, new MuleMessage(payload, messageProperties), timeout);
546 }
547
548
549
550
551
552
553
554
555
556
557
558
559 public FutureMessageResult sendAsync(final String url, final UMOMessage message, final int timeout)
560 throws UMOException
561 {
562 Callable call = new Callable()
563 {
564 public Object call() throws Exception
565 {
566 return send(url, message, timeout);
567 }
568 };
569
570 FutureMessageResult result = new FutureMessageResult(call);
571
572 if (asyncExecutor != null)
573 {
574 result.setExecutor(asyncExecutor);
575 }
576
577 result.execute();
578 return result;
579 }
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599 public FutureMessageResult sendDirectAsync(final String component,
600 String transformers,
601 final Object payload,
602 final Map messageProperties) throws UMOException
603 {
604 return sendDirectAsync(component, transformers, new MuleMessage(payload, messageProperties));
605 }
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623 public FutureMessageResult sendDirectAsync(final String component,
624 String transformers,
625 final UMOMessage message) throws UMOException
626 {
627 Callable call = new Callable()
628 {
629 public Object call() throws Exception
630 {
631 return sendDirect(component, null, message);
632 }
633 };
634
635 FutureMessageResult result = new FutureMessageResult(call);
636
637 if (asyncExecutor != null)
638 {
639 result.setExecutor(asyncExecutor);
640 }
641
642 if (StringUtils.isNotBlank(transformers))
643 {
644 result.setTransformer(MuleObjectHelper.getTransformer(transformers, ","));
645 }
646
647 result.execute();
648 return result;
649 }
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665 public UMOMessage send(String url, Object payload, Map messageProperties) throws UMOException
666 {
667 return send(url, payload, messageProperties, UMOEvent.TIMEOUT_NOT_SET_VALUE);
668 }
669
670
671
672
673
674
675
676
677
678
679
680
681 public UMOMessage send(String url, UMOMessage message) throws UMOException
682 {
683 return send(url, message, UMOEvent.TIMEOUT_NOT_SET_VALUE);
684 }
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702 public UMOMessage send(String url, Object payload, Map messageProperties, int timeout)
703 throws UMOException
704 {
705 if (messageProperties == null)
706 {
707 messageProperties = new HashMap();
708 }
709 if (messageProperties.get(MuleProperties.MULE_REMOTE_SYNC_PROPERTY) == null)
710 {
711 messageProperties.put(MuleProperties.MULE_REMOTE_SYNC_PROPERTY, "true");
712 }
713 UMOMessage message = new MuleMessage(payload, messageProperties);
714 return send(url, message, timeout);
715 }
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730 public UMOMessage send(String url, UMOMessage message, int timeout) throws UMOException
731 {
732 UMOEvent event = getEvent(message, url, true, false);
733 event.setTimeout(timeout);
734
735 try
736 {
737 return event.getSession().sendEvent(event);
738 }
739 catch (UMOException e)
740 {
741 throw e;
742 }
743 catch (Exception e)
744 {
745 throw new DispatchException(ClientMessages.failedToDispatchClientEvent(),
746 event.getMessage(), event.getEndpoint(), e);
747 }
748 }
749
750
751
752
753
754
755
756
757
758
759
760
761 public UMOMessage receive(String url, long timeout) throws UMOException
762 {
763 UMOEndpoint endpoint = getEndpoint(url, UMOEndpoint.ENDPOINT_TYPE_RECEIVER);
764 try
765 {
766 UMOMessage message = endpoint.receive(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 e)
778 {
779 throw new ReceiveException(endpoint, timeout, e);
780 }
781 }
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796 public UMOMessage receive(String url, String transformers, long timeout) throws UMOException
797 {
798 return receive(url, MuleObjectHelper.getTransformer(transformers, ","), timeout);
799 }
800
801
802
803
804
805
806
807
808
809
810
811
812
813 public UMOMessage receive(String 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
828
829
830
831
832
833
834
835
836 protected UMOEvent getEvent(UMOMessage message, String 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 e)
859 {
860 throw new DispatchException(CoreMessages.failedToCreate("Client event"), message, endpoint, e);
861 }
862 }
863
864 protected UMOEndpoint getEndpoint(String uri, String type) throws UMOException
865 {
866 UMOEndpoint endpoint = manager.lookupEndpoint(uri);
867 if (endpoint == null)
868 {
869 endpoint = MuleEndpoint.getOrCreateEndpointForUri(uri, type);
870 }
871 return endpoint;
872 }
873
874 protected UMOEndpoint getDefaultClientEndpoint(UMODescriptor descriptor, Object payload)
875 throws UMOException
876 {
877
878 UMOEndpoint endpoint = descriptor.getInboundEndpoint();
879 if (endpoint != null)
880 {
881 if (endpoint.getTransformer() != null)
882 {
883 if (endpoint.getTransformer().isSourceTypeSupported(payload.getClass()))
884 {
885 return endpoint;
886 }
887 else
888 {
889 endpoint = new MuleEndpoint(endpoint);
890 endpoint.setTransformer(null);
891 return endpoint;
892 }
893 }
894 else
895 {
896 return endpoint;
897 }
898 }
899 else
900 {
901 UMOConnector connector = null;
902 UMOEndpointURI defaultEndpointUri = new MuleEndpointURI("vm://mule.client");
903 connector = TransportFactory.createConnector(defaultEndpointUri);
904 manager.registerConnector(connector);
905 connector.startConnector();
906 endpoint = new MuleEndpoint("muleClientProvider", defaultEndpointUri, connector, null,
907 UMOEndpoint.ENDPOINT_TYPE_RECEIVER, 0, null, null);
908 }
909
910 manager.registerEndpoint(endpoint);
911 return endpoint;
912 }
913
914
915
916
917
918
919
920
921
922
923
924
925
926 public void sendNoReceive(String url, Object payload, Map messageProperties) throws UMOException
927 {
928 if (messageProperties == null)
929 {
930 messageProperties = new HashMap();
931 }
932 messageProperties.put(MuleProperties.MULE_REMOTE_SYNC_PROPERTY, "false");
933 UMOMessage message = new MuleMessage(payload, messageProperties);
934 UMOEvent event = getEvent(message, url, true, false);
935 try
936 {
937 event.getSession().sendEvent(event);
938 }
939 catch (UMOException e)
940 {
941 throw e;
942 }
943 catch (Exception e)
944 {
945 throw new DispatchException(ClientMessages.failedToDispatchClientEvent(),
946 event.getMessage(), event.getEndpoint(), e);
947 }
948 }
949
950
951
952
953
954
955 public UMOManager getManager()
956 {
957 return MuleManager.getInstance();
958 }
959
960
961
962
963
964
965
966
967
968
969
970
971
972 public void registerComponent(Object component, String name, UMOEndpointURI listenerEndpoint)
973 throws UMOException
974 {
975 builder.registerComponentInstance(component, name, listenerEndpoint, null);
976 }
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991 public void registerComponent(Object component,
992 String name,
993 MuleEndpointURI listenerEndpoint,
994 MuleEndpointURI sendEndpoint) throws UMOException
995 {
996 builder.registerComponentInstance(component, name, listenerEndpoint, sendEndpoint);
997 }
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014 public void registerComponent(UMODescriptor descriptor) throws UMOException
1015 {
1016 builder.registerComponent(descriptor);
1017 }
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031 public void unregisterComponent(String name) throws UMOException
1032 {
1033 builder.unregisterComponent(name);
1034 }
1035
1036 public RemoteDispatcher getRemoteDispatcher(String serverEndpoint) throws UMOException
1037 {
1038 RemoteDispatcher rd = new RemoteDispatcher(serverEndpoint);
1039 rd.setExecutor(asyncExecutor);
1040 dispatchers.add(rd);
1041 return rd;
1042 }
1043
1044 public RemoteDispatcher getRemoteDispatcher(String serverEndpoint, String user, String password)
1045 throws UMOException
1046 {
1047 RemoteDispatcher rd = new RemoteDispatcher(serverEndpoint, new MuleCredentials(user,
1048 password.toCharArray()));
1049 rd.setExecutor(asyncExecutor);
1050 dispatchers.add(rd);
1051 return rd;
1052 }
1053
1054
1055
1056
1057
1058 public void dispose()
1059 {
1060 synchronized (dispatchers)
1061 {
1062 for (Iterator iterator = dispatchers.iterator(); iterator.hasNext();)
1063 {
1064 RemoteDispatcher remoteDispatcher = (RemoteDispatcher)iterator.next();
1065 remoteDispatcher.dispose();
1066 remoteDispatcher = null;
1067 }
1068 dispatchers.clear();
1069 }
1070
1071 if (MuleManager.getConfiguration().isClientMode())
1072 {
1073 manager.dispose();
1074 }
1075 }
1076
1077 public void setProperty(Object key, Object value)
1078 {
1079 manager.setProperty(key, value);
1080 }
1081
1082 public Object getProperty(Object key)
1083 {
1084 return manager.getProperty(key);
1085 }
1086
1087 public MuleConfiguration getConfiguration()
1088 {
1089 return MuleManager.getConfiguration();
1090 }
1091 }