1
2
3
4
5
6
7
8
9
10
11 package org.mule.module.client;
12
13 import org.mule.DefaultMuleEvent;
14 import org.mule.DefaultMuleMessage;
15 import org.mule.MessageExchangePattern;
16 import org.mule.api.FutureMessageResult;
17 import org.mule.api.MuleContext;
18 import org.mule.api.MuleEvent;
19 import org.mule.api.MuleException;
20 import org.mule.api.MuleMessage;
21 import org.mule.api.MuleSession;
22 import org.mule.api.config.ConfigurationBuilder;
23 import org.mule.api.config.ConfigurationException;
24 import org.mule.api.config.MuleConfiguration;
25 import org.mule.api.config.MuleProperties;
26 import org.mule.api.context.MuleContextBuilder;
27 import org.mule.api.endpoint.EndpointBuilder;
28 import org.mule.api.endpoint.EndpointURI;
29 import org.mule.api.endpoint.ImmutableEndpoint;
30 import org.mule.api.endpoint.InboundEndpoint;
31 import org.mule.api.endpoint.OutboundEndpoint;
32 import org.mule.api.lifecycle.Disposable;
33 import org.mule.api.lifecycle.InitialisationException;
34 import org.mule.api.registry.RegistrationException;
35 import org.mule.api.registry.ServiceException;
36 import org.mule.api.service.Service;
37 import org.mule.api.transformer.Transformer;
38 import org.mule.api.transport.DispatchException;
39 import org.mule.api.transport.ReceiveException;
40 import org.mule.client.DefaultLocalMuleClient;
41 import org.mule.config.DefaultMuleConfiguration;
42 import org.mule.config.i18n.CoreMessages;
43 import org.mule.config.spring.SpringXmlConfigurationBuilder;
44 import org.mule.context.DefaultMuleContextBuilder;
45 import org.mule.context.DefaultMuleContextFactory;
46 import org.mule.endpoint.EndpointURIEndpointBuilder;
47 import org.mule.endpoint.MuleEndpointURI;
48 import org.mule.module.client.i18n.ClientMessages;
49 import org.mule.security.MuleCredentials;
50 import org.mule.service.ServiceCompositeMessageSource;
51 import org.mule.session.DefaultMuleSession;
52 import org.mule.transformer.TransformerUtils;
53 import org.mule.transport.NullPayload;
54 import org.mule.util.StringUtils;
55
56 import java.util.ArrayList;
57 import java.util.HashMap;
58 import java.util.Iterator;
59 import java.util.LinkedList;
60 import java.util.List;
61 import java.util.Map;
62
63 import edu.emory.mathcs.backport.java.util.concurrent.Callable;
64 import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap;
65 import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentMap;
66
67 import org.apache.commons.logging.Log;
68 import org.apache.commons.logging.LogFactory;
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98 public class MuleClient implements Disposable
99 {
100
101
102
103 protected static final Log logger = LogFactory.getLog(MuleClient.class);
104
105
106
107
108 private MuleContext muleContext;
109
110 private List dispatchers = new ArrayList();
111
112 private MuleCredentials user;
113
114 private DefaultMuleContextFactory muleContextFactory = new DefaultMuleContextFactory();
115
116 private ConcurrentMap inboundEndpointCache = new ConcurrentHashMap();
117 private ConcurrentMap outboundEndpointCache = new ConcurrentHashMap();
118
119
120
121
122
123
124
125 protected MuleClient() throws MuleException
126 {
127 this(true);
128 }
129
130 public MuleClient(boolean startContext) throws MuleException
131 {
132 init(startContext);
133 }
134
135 public MuleClient(MuleContext context) throws MuleException
136 {
137 this.muleContext = context;
138 init(false);
139 }
140
141
142
143
144
145
146
147
148
149
150
151 public MuleClient(String configResources) throws MuleException
152 {
153 this(configResources, new SpringXmlConfigurationBuilder(configResources));
154 }
155
156
157
158
159
160
161
162
163
164 public MuleClient(String user, String password) throws MuleException
165 {
166 init(
167 this.user = new MuleCredentials(user, password.toCharArray());
168 }
169
170
171
172
173
174
175
176
177
178
179
180
181 public MuleClient(String configResources, ConfigurationBuilder builder)
182 throws ConfigurationException, InitialisationException
183 {
184 if (builder == null)
185 {
186 logger.info("Builder passed in was null, using default builder: "
187 + SpringXmlConfigurationBuilder.class.getName());
188 builder = new SpringXmlConfigurationBuilder(configResources);
189 }
190 logger.info("Initializing Mule...");
191 muleContext = muleContextFactory.createMuleContext(builder);
192 }
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207 public MuleClient(String configResources, ConfigurationBuilder builder, String user, String password)
208 throws ConfigurationException, InitialisationException
209 {
210 this(configResources, builder);
211 this.user = new MuleCredentials(user, password.toCharArray());
212 }
213
214
215
216
217
218
219
220 private void init(boolean startManager) throws MuleException
221 {
222 if (muleContext == null)
223 {
224 logger.info("No existing ManagementContext found, creating a new Mule instance");
225
226 MuleContextBuilder contextBuilder = new DefaultMuleContextBuilder();
227 DefaultMuleConfiguration config = new DefaultMuleConfiguration();
228 config.setClientMode(true);
229 contextBuilder.setMuleConfiguration(config);
230 muleContext = muleContextFactory.createMuleContext(contextBuilder);
231 }
232 else
233 {
234 logger.info("Using existing MuleContext: " + muleContext);
235 }
236
237 if (!muleContext.isStarted() && startManager == true)
238 {
239 logger.info("Starting Mule...");
240 muleContext.start();
241 }
242 }
243
244
245
246
247
248
249
250
251
252
253
254
255
256 public void dispatch(String url, Object payload, Map messageProperties) throws MuleException
257 {
258 dispatch(url, new DefaultMuleMessage(payload, messageProperties, muleContext));
259 }
260
261
262
263
264
265
266
267
268
269
270 public void dispatch(String url, MuleMessage message) throws MuleException
271 {
272 OutboundEndpoint endpoint = getOutboundEndpoint(url, MessageExchangePattern.ONE_WAY, null);
273 MuleEvent event = getEvent(message, endpoint);
274 try
275 {
276 endpoint.process(event);
277 }
278 catch (MuleException e)
279 {
280 throw e;
281 }
282 catch (Exception e)
283 {
284 throw new DispatchException(ClientMessages.failedToDispatchClientEvent(), event,
285 endpoint, e);
286 }
287 }
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302 public MuleMessage sendDirect(String component, String transformers, Object payload, Map messageProperties)
303 throws MuleException
304 {
305 MuleMessage message = new DefaultMuleMessage(payload, messageProperties, muleContext);
306 return sendDirect(component, transformers, message);
307 }
308
309
310
311
312
313
314
315
316
317
318
319
320 public MuleMessage sendDirect(String componentName, String transformers, MuleMessage message)
321 throws MuleException
322 {
323 Service service = muleContext.getRegistry().lookupService(componentName);
324 if (service == null)
325 {
326 throw new ServiceException(CoreMessages.objectNotRegistered("Service", componentName));
327 }
328 List<Transformer> trans = null;
329 if (transformers != null)
330 {
331 trans = TransformerUtils.getTransformers(transformers, muleContext);
332 }
333
334 MuleSession session = new DefaultMuleSession(service, muleContext);
335 ImmutableEndpoint endpoint = getDefaultClientEndpoint(service, message.getPayload(), true);
336 MuleEvent event = new DefaultMuleEvent(message, endpoint, session);
337
338 if (logger.isDebugEnabled())
339 {
340 logger.debug("MuleClient sending event direct to: " + componentName + ". MuleEvent is: " + event);
341 }
342
343 MuleEvent resultEvent = service.sendEvent(event);
344 MuleMessage result = resultEvent == null ? null : resultEvent.getMessage();
345 if (logger.isDebugEnabled())
346 {
347 logger.debug("Result of MuleClient sendDirect is: "
348 + (result == null ? "null" : result.getPayload()));
349 }
350
351 if (result != null && trans != null)
352 {
353 result.applyTransformers(resultEvent, trans);
354 }
355 return result;
356 }
357
358
359
360
361
362
363
364
365
366
367
368 public void dispatchDirect(String component, Object payload, Map messageProperties) throws MuleException
369 {
370 dispatchDirect(component, new DefaultMuleMessage(payload, messageProperties, muleContext));
371 }
372
373
374
375
376
377
378
379
380
381 public void dispatchDirect(String componentName, MuleMessage message) throws MuleException
382 {
383 Service service = muleContext.getRegistry().lookupService(componentName);
384 if (service == null)
385 {
386 throw new ServiceException(CoreMessages.objectNotRegistered("Service", componentName));
387 }
388 MuleSession session = new DefaultMuleSession(service, muleContext);
389 ImmutableEndpoint endpoint = getDefaultClientEndpoint(service, message.getPayload(), false);
390 MuleEvent event = new DefaultMuleEvent(message, endpoint, session);
391
392 if (logger.isDebugEnabled())
393 {
394 logger.debug("MuleClient dispatching event direct to: " + componentName + ". MuleEvent is: " + event);
395 }
396
397 service.dispatchEvent(event);
398 }
399
400
401
402
403
404
405
406
407
408
409
410
411
412 public FutureMessageResult sendAsync(final String url, final Object payload, final Map messageProperties)
413 throws MuleException
414 {
415 return sendAsync(url, payload, messageProperties, 0);
416 }
417
418
419
420
421
422
423
424
425
426
427
428 public FutureMessageResult sendAsync(final String url, final MuleMessage message) throws MuleException
429 {
430 return sendAsync(url, message, MuleEvent.TIMEOUT_NOT_SET_VALUE);
431 }
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446 public FutureMessageResult sendAsync(final String url,
447 final Object payload,
448 final Map messageProperties,
449 final int timeout) throws MuleException
450 {
451 return sendAsync(url, new DefaultMuleMessage(payload, messageProperties, muleContext), timeout);
452 }
453
454
455
456
457
458
459
460
461
462
463
464
465 public FutureMessageResult sendAsync(final String url, final MuleMessage message, final int timeout)
466 throws MuleException
467 {
468 Callable call = new Callable()
469 {
470 public Object call() throws Exception
471 {
472 return send(url, message, timeout);
473 }
474 };
475
476 FutureMessageResult result = new FutureMessageResult(call, muleContext);
477
478 if (muleContext.getWorkManager() != null)
479 {
480 result.setExecutor(muleContext.getWorkManager());
481 }
482
483 result.execute();
484 return result;
485 }
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503 public FutureMessageResult sendDirectAsync(final String component,
504 String transformers,
505 final Object payload,
506 final Map messageProperties) throws MuleException
507 {
508 return sendDirectAsync(component, transformers, new DefaultMuleMessage(payload, messageProperties, muleContext));
509 }
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526 public FutureMessageResult sendDirectAsync(final String component,
527 String transformers,
528 final MuleMessage message) throws MuleException
529 {
530 Callable call = new Callable()
531 {
532 public Object call() throws Exception
533 {
534 return sendDirect(component, null, message);
535 }
536 };
537
538 FutureMessageResult result = new FutureMessageResult(call, muleContext);
539
540 if (muleContext.getWorkManager() != null)
541 {
542 result.setExecutor(muleContext.getWorkManager());
543 }
544
545 if (StringUtils.isNotBlank(transformers))
546 {
547 result.setTransformers(TransformerUtils.getTransformers(transformers, muleContext));
548 }
549
550 result.execute();
551 return result;
552 }
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568 public MuleMessage send(String url, Object payload, Map messageProperties) throws MuleException
569 {
570 return send(url, payload, messageProperties, MuleEvent.TIMEOUT_NOT_SET_VALUE);
571 }
572
573
574
575
576
577
578
579
580
581
582
583
584 public MuleMessage send(String url, MuleMessage message) throws MuleException
585 {
586 return send(url, message, MuleEvent.TIMEOUT_NOT_SET_VALUE);
587 }
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605 public MuleMessage send(String url, Object payload, Map messageProperties, int timeout)
606 throws MuleException
607 {
608 if (messageProperties == null)
609 {
610 messageProperties = new HashMap();
611 }
612 if (messageProperties.get(MuleProperties.MULE_REMOTE_SYNC_PROPERTY) == null)
613 {
614
615 messageProperties = new HashMap(messageProperties);
616 messageProperties.put(MuleProperties.MULE_REMOTE_SYNC_PROPERTY, "true");
617 }
618 MuleMessage message = new DefaultMuleMessage(payload, messageProperties, muleContext);
619 return send(url, message, timeout);
620 }
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635 public MuleMessage send(String url, MuleMessage message, int timeout) throws MuleException
636 {
637 OutboundEndpoint endpoint =
638 getOutboundEndpoint(url, MessageExchangePattern.REQUEST_RESPONSE, timeout);
639
640 MuleEvent event = getEvent(message, endpoint);
641 event.setTimeout(timeout);
642
643 MuleEvent response = endpoint.process(event);
644 if (response != null)
645 {
646
647
648 return response.getMessage();
649
650
651
652
653
654
655
656
657
658
659
660
661
662 }
663 else
664 {
665 return new DefaultMuleMessage(NullPayload.getInstance(), muleContext);
666 }
667 }
668
669
670
671
672
673
674
675
676
677
678
679
680 public MuleMessage request(String url, long timeout) throws MuleException
681 {
682 InboundEndpoint endpoint = getInboundEndpoint(url);
683 try
684 {
685 return endpoint.request(timeout);
686 }
687 catch (Exception e)
688 {
689 throw new ReceiveException(endpoint, timeout, e);
690 }
691 }
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706 public MuleMessage request(String url, String transformers, long timeout) throws MuleException
707 {
708 return request(url, TransformerUtils.getTransformers(transformers, muleContext), timeout);
709 }
710
711
712
713
714
715
716
717
718
719
720
721
722
723 public MuleMessage request(String url, List transformers, long timeout) throws MuleException
724 {
725 return request(url, timeout);
726 }
727
728 protected MuleEvent getEvent(MuleMessage message, OutboundEndpoint endpoint) throws MuleException
729 {
730 DefaultMuleSession session = new DefaultMuleSession(new DefaultLocalMuleClient.MuleClientFlowConstruct(muleContext), muleContext);
731
732 if (user != null)
733 {
734 message.setOutboundProperty(MuleProperties.MULE_USER_PROPERTY, MuleCredentials.createHeader(user.getUsername(), user.getPassword()));
735 }
736 return new DefaultMuleEvent(message, endpoint, session);
737 }
738
739 protected InboundEndpoint getInboundEndpoint(String uri) throws MuleException
740 {
741
742
743
744
745
746
747 InboundEndpoint endpoint = (InboundEndpoint) inboundEndpointCache.get(uri);
748 if (endpoint == null)
749 {
750 endpoint = muleContext.getRegistry().lookupEndpointFactory().getInboundEndpoint(uri);
751 InboundEndpoint concurrentlyAddedEndpoint = (InboundEndpoint) inboundEndpointCache.putIfAbsent(uri, endpoint);
752 if (concurrentlyAddedEndpoint != null)
753 {
754 return concurrentlyAddedEndpoint;
755 }
756 }
757 return endpoint;
758 }
759
760 protected OutboundEndpoint getOutboundEndpoint(String uri, MessageExchangePattern exchangePattern,
761 Integer responseTimeout) throws MuleException
762 {
763
764
765
766
767
768
769 String key = String.format("%1s:%2s:%3s", uri, exchangePattern, responseTimeout);
770 OutboundEndpoint endpoint = (OutboundEndpoint) outboundEndpointCache.get(key);
771 if (endpoint == null)
772 {
773 EndpointBuilder endpointBuilder =
774 muleContext.getRegistry().lookupEndpointFactory().getEndpointBuilder(uri);
775 endpointBuilder.setExchangePattern(exchangePattern);
776 if (responseTimeout != null && responseTimeout > 0)
777 {
778 endpointBuilder.setResponseTimeout(responseTimeout.intValue());
779 }
780 endpoint = muleContext.getRegistry().lookupEndpointFactory().getOutboundEndpoint(endpointBuilder);
781 OutboundEndpoint concurrentlyAddedEndpoint =
782 (OutboundEndpoint) outboundEndpointCache.putIfAbsent(key, endpoint);
783 if (concurrentlyAddedEndpoint != null)
784 {
785 return concurrentlyAddedEndpoint;
786 }
787 }
788 return endpoint;
789 }
790
791 protected ImmutableEndpoint getDefaultClientEndpoint(Service service, Object payload, boolean sync)
792 throws MuleException
793 {
794 if (!(service.getMessageSource() instanceof ServiceCompositeMessageSource))
795 {
796 throw new IllegalStateException(
797 "Only 'CompositeMessageSource' is supported with MuleClient.sendDirect() and MuleClient.dispatchDirect()");
798 }
799
800
801 ImmutableEndpoint endpoint = (ImmutableEndpoint) ((ServiceCompositeMessageSource) service.getMessageSource()).getEndpoints().get(0);
802 if (endpoint != null)
803 {
804 if (endpoint.getTransformers() != null)
805 {
806
807
808 if (TransformerUtils.isSourceTypeSupportedByFirst(endpoint.getTransformers(),
809 payload.getClass()))
810 {
811 return endpoint;
812 }
813 else
814 {
815 EndpointBuilder builder = new EndpointURIEndpointBuilder(endpoint);
816 builder.setTransformers(new LinkedList());
817 builder.setExchangePattern(MessageExchangePattern.REQUEST_RESPONSE);
818 return muleContext.getRegistry().lookupEndpointFactory().getInboundEndpoint(builder);
819 }
820 }
821 else
822 {
823 return endpoint;
824 }
825 }
826 else
827 {
828 EndpointBuilder builder = new EndpointURIEndpointBuilder("vm://mule.client", muleContext);
829 builder.setName("muleClientProvider");
830 endpoint = muleContext.getRegistry().lookupEndpointFactory().getInboundEndpoint(builder);
831 }
832 return endpoint;
833 }
834
835
836
837
838
839
840
841
842
843
844
845
846
847 public void sendNoReceive(String url, Object payload, Map<String, Object> messageProperties) throws MuleException
848 {
849 if (messageProperties == null)
850 {
851 messageProperties = new HashMap<String, Object>();
852 }
853 messageProperties.put(MuleProperties.MULE_REMOTE_SYNC_PROPERTY, "false");
854 MuleMessage message = new DefaultMuleMessage(payload, messageProperties, muleContext);
855
856 OutboundEndpoint endpoint =
857 getOutboundEndpoint(url, MessageExchangePattern.REQUEST_RESPONSE, null);
858 MuleEvent event = getEvent(message, endpoint);
859 try
860 {
861 endpoint.process(event);
862 }
863 catch (MuleException e)
864 {
865 throw e;
866 }
867 catch (Exception e)
868 {
869 throw new DispatchException(ClientMessages.failedToDispatchClientEvent(), event,
870 endpoint, e);
871 }
872 }
873
874
875
876
877
878
879 public MuleContext getMuleContext()
880 {
881 return muleContext;
882 }
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898 @Deprecated
899 public void registerComponent(Object component, String name, EndpointURI listenerEndpoint)
900 throws MuleException
901 {
902 throw new UnsupportedOperationException("registerComponent");
903
904
905 }
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922 @Deprecated
923 public void registerComponent(Object component,
924 String name,
925 MuleEndpointURI listenerEndpoint,
926 MuleEndpointURI sendEndpoint) throws MuleException
927 {
928 throw new UnsupportedOperationException("registerComponent");
929
930
931 }
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969 @Deprecated
970 public void unregisterComponent(String name) throws MuleException
971 {
972 throw new UnsupportedOperationException("registerComponent");
973
974
975 }
976
977 public RemoteDispatcher getRemoteDispatcher(String serverEndpoint) throws MuleException
978 {
979 RemoteDispatcher rd = new RemoteDispatcher(serverEndpoint, muleContext);
980 rd.setExecutor(muleContext.getWorkManager());
981 dispatchers.add(rd);
982 return rd;
983 }
984
985 public RemoteDispatcher getRemoteDispatcher(String serverEndpoint, String user, String password)
986 throws MuleException
987 {
988 RemoteDispatcher rd = new RemoteDispatcher(serverEndpoint, new MuleCredentials(user,
989 password.toCharArray()), muleContext);
990 rd.setExecutor(muleContext.getWorkManager());
991 dispatchers.add(rd);
992 return rd;
993 }
994
995
996
997
998
999 public void dispose()
1000 {
1001 synchronized (dispatchers)
1002 {
1003 for (Iterator iterator = dispatchers.iterator(); iterator.hasNext();)
1004 {
1005 RemoteDispatcher remoteDispatcher = (RemoteDispatcher) iterator.next();
1006 remoteDispatcher.dispose();
1007 remoteDispatcher = null;
1008 }
1009 dispatchers.clear();
1010 }
1011
1012
1013 if (muleContext.getConfiguration().isClientMode())
1014 {
1015 logger.info("Stopping Mule...");
1016 muleContext.dispose();
1017 }
1018 }
1019
1020 public void setProperty(String key, Object value)
1021 {
1022 try
1023 {
1024 muleContext.getRegistry().registerObject(key, value);
1025 }
1026 catch (RegistrationException e)
1027 {
1028 logger.error(e);
1029 }
1030 }
1031
1032 public Object getProperty(String key)
1033 {
1034 return muleContext.getRegistry().lookupObject(key);
1035 }
1036
1037 public MuleConfiguration getConfiguration()
1038 {
1039 return muleContext.getConfiguration();
1040 }
1041 }