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
59 import org.apache.commons.logging.Log;
60 import org.apache.commons.logging.LogFactory;
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
90 public class MuleClient implements Disposable
91 {
92
93
94
95 protected static final Log logger = LogFactory.getLog(MuleClient.class);
96
97
98
99
100 private UMOManager manager;
101
102
103
104
105
106 private Executor asyncExecutor = null;
107
108 private List dispatchers = new ArrayList();
109
110
111 QuickConfigurationBuilder builder = null;
112
113 private MuleCredentials user;
114
115
116
117
118
119
120
121 public MuleClient() throws UMOException
122 {
123 init(
124 }
125
126
127
128
129
130
131
132
133 public MuleClient(boolean startManager) throws UMOException
134 {
135 init(startManager);
136 }
137
138
139
140
141
142
143
144
145
146
147
148 public MuleClient(String configResources) throws UMOException
149 {
150 this(configResources, new MuleXmlConfigurationBuilder());
151 }
152
153
154
155
156
157
158
159
160
161 public MuleClient(String user, String password) throws UMOException
162 {
163 init(
164 this.user = new MuleCredentials(user, password.toCharArray());
165 }
166
167
168
169
170
171
172
173
174
175
176
177 public MuleClient(String configResources, ConfigurationBuilder builder) throws ConfigurationException
178 {
179 if (MuleManager.isInstanciated())
180 {
181 throw new ConfigurationException(ClientMessages.managerIsAlreadyConfigured());
182 }
183 if (builder == null)
184 {
185 logger.info("Builder passed in was null, using default builder: "
186 + MuleXmlConfigurationBuilder.class.getName());
187 builder = new MuleXmlConfigurationBuilder();
188 }
189 manager = builder.configure(configResources, null);
190 }
191
192
193
194
195
196
197
198
199
200
201
202
203
204 public MuleClient(String configResources, ConfigurationBuilder builder, String user, String password)
205 throws ConfigurationException
206 {
207 this(configResources, builder);
208 this.user = new MuleCredentials(user, password.toCharArray());
209 }
210
211
212
213
214
215
216
217 private void init(boolean startManager) throws UMOException
218 {
219
220
221
222 if (MuleManager.isInstanciated())
223 {
224 if (logger.isInfoEnabled())
225 {
226 logger.info("There is already a manager locally available to this client, no need to create a new one");
227 }
228 }
229 else
230 {
231 MuleManager.getConfiguration().setClientMode(true);
232 if (logger.isInfoEnabled())
233 {
234 logger.info("There is no manager instance locally available for this client, creating a new Manager");
235 }
236 }
237
238 manager = MuleManager.getInstance();
239 asyncExecutor = manager.getWorkManager();
240 builder = new QuickConfigurationBuilder();
241
242 if (!manager.isInitialised() && startManager == true)
243 {
244 if (logger.isInfoEnabled()) logger.info("Starting Mule Manager for this client");
245 ((MuleManager)manager).start();
246 }
247 }
248
249
250
251
252
253
254
255
256
257
258
259
260
261 public void dispatch(String url, Object payload, Map messageProperties) throws UMOException
262 {
263 dispatch(url, new MuleMessage(payload, messageProperties));
264 }
265
266
267
268
269
270
271
272
273
274
275 public void dispatch(String url, UMOMessage message) throws UMOException
276 {
277 UMOEvent event = getEvent(message, url, false, false);
278 try
279 {
280 event.getSession().dispatchEvent(event);
281 }
282 catch (UMOException e)
283 {
284 throw e;
285 }
286 catch (Exception e)
287 {
288 throw new DispatchException(ClientMessages.failedToDispatchClientEvent(),
289 event.getMessage(), event.getEndpoint(), e);
290 }
291 }
292
293
294
295
296
297
298
299
300
301
302 public void dispatchStream(String 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 e)
314 {
315 throw new DispatchException(ClientMessages.failedToDispatchClientEvent(),
316 event.getMessage(), event.getEndpoint(), e);
317 }
318 }
319
320 public UMOStreamMessageAdapter sendStream(String url, UMOStreamMessageAdapter message)
321 throws UMOException
322 {
323 return sendStream(url, message, UMOEvent.TIMEOUT_NOT_SET_VALUE);
324 }
325
326
327
328
329
330
331
332
333
334
335
336
337 public UMOStreamMessageAdapter sendStream(String url, UMOStreamMessageAdapter message, int timeout)
338 throws UMOException
339 {
340 UMOEvent event = getEvent(new MuleMessage(message), url, true, true);
341 event.setTimeout(timeout);
342 try
343 {
344 UMOMessage result = event.getSession().sendEvent(event);
345 if (result != null)
346 {
347 if (result.getAdapter() instanceof UMOStreamMessageAdapter)
348 {
349 return (UMOStreamMessageAdapter)result.getAdapter();
350 }
351 else
352 {
353
354 throw new IllegalStateException(
355 "Mismatch of stream states. A stream was used for outbound channel, but a stream was not used for the response");
356 }
357 }
358 }
359 catch (UMOException e)
360 {
361 throw e;
362 }
363 catch (Exception e)
364 {
365 throw new DispatchException(ClientMessages.failedToDispatchClientEvent(),
366 event.getMessage(), event.getEndpoint(), e);
367 }
368 return null;
369 }
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384 public UMOMessage sendDirect(String component, String transformers, Object payload, Map messageProperties)
385 throws UMOException
386 {
387 UMOMessage message = new MuleMessage(payload, messageProperties);
388 return sendDirect(component, transformers, message);
389 }
390
391
392
393
394
395
396
397
398
399
400
401
402 public UMOMessage sendDirect(String component, String transformers, UMOMessage message)
403 throws UMOException
404 {
405 boolean compregistered = ModelHelper.isComponentRegistered(component);
406 if (!compregistered)
407 {
408 throw new MessagingException(
409 CoreMessages.objectNotRegisteredWithManager("Component '" + component + "'"),
410 message);
411 }
412 UMOTransformer trans = null;
413 if (transformers != null)
414 {
415 trans = MuleObjectHelper.getTransformer(transformers, ",");
416 }
417
418 if (!MuleManager.getConfiguration().isSynchronous())
419 {
420 logger.warn("The mule manager is running synchronously, a null message payload will be returned");
421 }
422 UMOSession session = new MuleSession(ModelHelper.getComponent(component));
423 UMOEndpoint endpoint = getDefaultClientEndpoint(session.getComponent().getDescriptor(),
424 message.getPayload());
425 UMOEvent event = new MuleEvent(message, endpoint, session, true);
426
427 if (logger.isDebugEnabled())
428 {
429 logger.debug("MuleClient sending event direct to: " + component + ". Event is: " + event);
430 }
431
432 UMOMessage result = event.getComponent().sendEvent(event);
433
434 if (logger.isDebugEnabled())
435 {
436 logger.debug("Result of MuleClient sendDirect is: "
437 + (result == null ? "null" : result.getPayload()));
438 }
439
440 if (result != null && trans != null)
441 {
442 return new MuleMessage(trans.transform(result.getPayload()));
443 }
444 else
445 {
446 return result;
447 }
448 }
449
450
451
452
453
454
455
456
457
458
459
460 public void dispatchDirect(String component, Object payload, Map messageProperties) throws UMOException
461 {
462 dispatchDirect(component, new MuleMessage(payload, messageProperties));
463 }
464
465
466
467
468
469
470
471
472
473 public void dispatchDirect(String component, UMOMessage message) throws UMOException
474 {
475 boolean compregistered = ModelHelper.isComponentRegistered(component);
476 if (!compregistered)
477 {
478 throw new MessagingException(
479 CoreMessages.objectNotRegisteredWithManager("Component '" + component + "'"),
480 message);
481 }
482 UMOSession session = new MuleSession(ModelHelper.getComponent(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
497
498
499
500
501
502
503
504
505
506
507 public FutureMessageResult sendAsync(final String url, final Object payload, final Map messageProperties)
508 throws UMOException
509 {
510 return sendAsync(url, payload, messageProperties, 0);
511 }
512
513
514
515
516
517
518
519
520
521
522
523 public FutureMessageResult sendAsync(final String url, final UMOMessage message) throws UMOException
524 {
525 return sendAsync(url, message, UMOEvent.TIMEOUT_NOT_SET_VALUE);
526 }
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541 public FutureMessageResult sendAsync(final String url,
542 final Object payload,
543 final Map messageProperties,
544 final int timeout) throws UMOException
545 {
546 return sendAsync(url, new MuleMessage(payload, messageProperties), timeout);
547 }
548
549
550
551
552
553
554
555
556
557
558
559
560 public FutureMessageResult sendAsync(final String url, final UMOMessage message, final int timeout)
561 throws UMOException
562 {
563 Callable call = new Callable()
564 {
565 public Object call() throws Exception
566 {
567 return send(url, message, timeout);
568 }
569 };
570
571 FutureMessageResult result = new FutureMessageResult(call);
572
573 if (asyncExecutor != null)
574 {
575 result.setExecutor(asyncExecutor);
576 }
577
578 result.execute();
579 return result;
580 }
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600 public FutureMessageResult sendDirectAsync(final String component,
601 String transformers,
602 final Object payload,
603 final Map messageProperties) throws UMOException
604 {
605 return sendDirectAsync(component, transformers, new MuleMessage(payload, messageProperties));
606 }
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624 public FutureMessageResult sendDirectAsync(final String component,
625 String transformers,
626 final UMOMessage message) throws UMOException
627 {
628 Callable call = new Callable()
629 {
630 public Object call() throws Exception
631 {
632 return sendDirect(component, null, message);
633 }
634 };
635
636 FutureMessageResult result = new FutureMessageResult(call);
637
638 if (asyncExecutor != null)
639 {
640 result.setExecutor(asyncExecutor);
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
654
655
656
657
658
659
660
661
662
663
664
665
666 public UMOMessage send(String url, Object payload, Map messageProperties) throws UMOException
667 {
668 return send(url, payload, messageProperties, UMOEvent.TIMEOUT_NOT_SET_VALUE);
669 }
670
671
672
673
674
675
676
677
678
679
680
681
682 public UMOMessage send(String url, UMOMessage message) throws UMOException
683 {
684 return send(url, message, UMOEvent.TIMEOUT_NOT_SET_VALUE);
685 }
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703 public UMOMessage send(String url, Object payload, Map messageProperties, int timeout)
704 throws UMOException
705 {
706 if (messageProperties == null)
707 {
708 messageProperties = new HashMap();
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
720
721
722
723
724
725
726
727
728
729
730
731 public UMOMessage send(String 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 e)
745 {
746 throw new DispatchException(ClientMessages.failedToDispatchClientEvent(),
747 event.getMessage(), event.getEndpoint(), e);
748 }
749 }
750
751
752
753
754
755
756
757
758
759
760
761
762 public UMOMessage receive(String url, long timeout) throws UMOException
763 {
764 UMOEndpoint endpoint = getEndpoint(url, UMOEndpoint.ENDPOINT_TYPE_RECEIVER);
765 try
766 {
767 UMOMessage message = endpoint.receive(timeout);
768 if (message != null && endpoint.getTransformer() != null)
769 {
770 if (endpoint.getTransformer().isSourceTypeSupported(message.getPayload().getClass()))
771 {
772 message = new MuleMessage(endpoint.getTransformer().transform(message.getPayload()),
773 message);
774 }
775 }
776 return message;
777 }
778 catch (Exception e)
779 {
780 throw new ReceiveException(endpoint, timeout, e);
781 }
782 }
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797 public UMOMessage receive(String url, String transformers, long timeout) throws UMOException
798 {
799 return receive(url, MuleObjectHelper.getTransformer(transformers, ","), timeout);
800 }
801
802
803
804
805
806
807
808
809
810
811
812
813
814 public UMOMessage receive(String url, UMOTransformer transformer, long timeout) throws UMOException
815 {
816 UMOMessage message = receive(url, timeout);
817 if (message != null && transformer != null)
818 {
819 return new MuleMessage(transformer.transform(message.getPayload()));
820 }
821 else
822 {
823 return message;
824 }
825 }
826
827
828
829
830
831
832
833
834
835
836
837 protected UMOEvent getEvent(UMOMessage message, String uri, boolean synchronous, boolean streaming)
838 throws UMOException
839 {
840 UMOEndpoint endpoint = getEndpoint(uri, UMOEndpoint.ENDPOINT_TYPE_SENDER);
841 if (!endpoint.getConnector().isStarted() && manager.isStarted())
842 {
843 endpoint.getConnector().startConnector();
844 }
845 endpoint.setStreaming(streaming);
846 try
847 {
848 MuleSession session = new MuleSession(message,
849 ((AbstractConnector)endpoint.getConnector()).getSessionHandler());
850
851 if (user != null)
852 {
853 message.setProperty(MuleProperties.MULE_USER_PROPERTY, MuleCredentials.createHeader(
854 user.getUsername(), user.getPassword()));
855 }
856 MuleEvent event = new MuleEvent(message, endpoint, session, synchronous);
857 return event;
858 }
859 catch (Exception e)
860 {
861 throw new DispatchException(CoreMessages.failedToCreate("Client event"), message, endpoint, e);
862 }
863 }
864
865 protected UMOEndpoint getEndpoint(String uri, String 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 payload)
876 throws UMOException
877 {
878
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 = TransportFactory.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
917
918
919
920
921
922
923
924
925
926
927 public void sendNoReceive(String url, Object payload, Map messageProperties) throws UMOException
928 {
929 if (messageProperties == null)
930 {
931 messageProperties = new HashMap();
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 e)
945 {
946 throw new DispatchException(ClientMessages.failedToDispatchClientEvent(),
947 event.getMessage(), event.getEndpoint(), e);
948 }
949 }
950
951
952
953
954
955
956 public UMOManager getManager()
957 {
958 return MuleManager.getInstance();
959 }
960
961
962
963
964
965
966
967
968
969
970
971
972
973 public void registerComponent(Object component, String name, UMOEndpointURI listenerEndpoint)
974 throws UMOException
975 {
976 builder.registerComponentInstance(component, name, listenerEndpoint, null);
977 }
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992 public void registerComponent(Object component,
993 String name,
994 MuleEndpointURI listenerEndpoint,
995 MuleEndpointURI sendEndpoint) throws UMOException
996 {
997 builder.registerComponentInstance(component, name, listenerEndpoint, sendEndpoint);
998 }
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015 public void registerComponent(UMODescriptor descriptor) throws UMOException
1016 {
1017 builder.registerComponent(descriptor);
1018 }
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032 public void unregisterComponent(String name) throws UMOException
1033 {
1034 builder.unregisterComponent(name);
1035 }
1036
1037 public RemoteDispatcher getRemoteDispatcher(String serverEndpoint) throws UMOException
1038 {
1039 RemoteDispatcher rd = new RemoteDispatcher(serverEndpoint);
1040 rd.setExecutor(asyncExecutor);
1041 dispatchers.add(rd);
1042 return rd;
1043 }
1044
1045 public RemoteDispatcher getRemoteDispatcher(String serverEndpoint, String user, String password)
1046 throws UMOException
1047 {
1048 RemoteDispatcher rd = new RemoteDispatcher(serverEndpoint, new MuleCredentials(user,
1049 password.toCharArray()));
1050 rd.setExecutor(asyncExecutor);
1051 dispatchers.add(rd);
1052 return rd;
1053 }
1054
1055
1056
1057
1058
1059 public void dispose()
1060 {
1061 synchronized (dispatchers)
1062 {
1063 for (Iterator iterator = dispatchers.iterator(); iterator.hasNext();)
1064 {
1065 RemoteDispatcher remoteDispatcher = (RemoteDispatcher)iterator.next();
1066 remoteDispatcher.dispose();
1067 remoteDispatcher = null;
1068 }
1069 dispatchers.clear();
1070 }
1071
1072 if (MuleManager.getConfiguration().isClientMode())
1073 {
1074 manager.dispose();
1075 }
1076 }
1077
1078 public void setProperty(Object key, Object value)
1079 {
1080 manager.setProperty(key, value);
1081 }
1082
1083 public Object getProperty(Object key)
1084 {
1085 return manager.getProperty(key);
1086 }
1087
1088 public MuleConfiguration getConfiguration()
1089 {
1090 return MuleManager.getConfiguration();
1091 }
1092 }