KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > providers > soap > xfire > XFireMessageDispatcher


1 /*
2  * $Id: XFireMessageDispatcher.java 4310 2006-12-19 12:34:06Z 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.providers.soap.xfire;
12
13 import java.util.ArrayList JavaDoc;
14 import java.util.Arrays JavaDoc;
15 import java.util.HashMap JavaDoc;
16 import java.util.Iterator JavaDoc;
17 import java.util.List JavaDoc;
18 import java.util.Map JavaDoc;
19 import java.util.Properties JavaDoc;
20 import java.util.Set JavaDoc;
21
22 import javax.activation.DataHandler JavaDoc;
23 import javax.xml.namespace.QName JavaDoc;
24
25 import org.apache.commons.lang.StringUtils;
26 import org.apache.commons.pool.ObjectPool;
27 import org.apache.commons.pool.impl.StackObjectPool;
28 import org.codehaus.xfire.XFire;
29 import org.codehaus.xfire.client.Client;
30 import org.codehaus.xfire.handler.Handler;
31 import org.codehaus.xfire.service.OperationInfo;
32 import org.codehaus.xfire.service.Service;
33 import org.mule.config.MuleProperties;
34 import org.mule.config.i18n.Message;
35 import org.mule.impl.MuleMessage;
36 import org.mule.providers.AbstractMessageDispatcher;
37 import org.mule.providers.FatalConnectException;
38 import org.mule.providers.soap.SoapConstants;
39 import org.mule.providers.soap.xfire.transport.MuleUniversalTransport;
40 import org.mule.umo.UMOEvent;
41 import org.mule.umo.UMOException;
42 import org.mule.umo.UMOMessage;
43 import org.mule.umo.endpoint.UMOEndpointURI;
44 import org.mule.umo.endpoint.UMOImmutableEndpoint;
45 import org.mule.umo.provider.DispatchException;
46 import org.mule.umo.transformer.TransformerException;
47 import org.mule.util.TemplateParser;
48
49 /**
50  * The XFireMessageDispatcher is used for making Soap client requests to remote
51  * services.
52  */

53 public class XFireMessageDispatcher extends AbstractMessageDispatcher
54 {
55     protected final XFireConnector connector;
56     protected volatile ObjectPool clientPool;
57     private final TemplateParser soapActionTemplateParser = TemplateParser.createAntStyleParser();
58
59     public XFireMessageDispatcher(UMOImmutableEndpoint endpoint)
60     {
61         super(endpoint);
62         this.connector = (XFireConnector)endpoint.getConnector();
63     }
64
65     protected void doConnect(final UMOImmutableEndpoint endpoint) throws Exception JavaDoc
66     {
67         if (clientPool == null)
68         {
69             final XFire xfire = connector.getXfire();
70             final String JavaDoc serviceName = getServiceName(endpoint);
71             final Service service = xfire.getServiceRegistry().getService(serviceName);
72
73             if (service == null)
74             {
75                 throw new FatalConnectException(new Message("xfire", 8, serviceName), this);
76             }
77             
78             List JavaDoc inList = connector.getServerInHandlers();
79             if(inList != null)
80             {
81                 for(int i = 0; i < inList.size(); i++)
82                 {
83                     Class JavaDoc clazz = Class.forName(inList.get(i).toString());
84                     Handler JavaDoc handler = (Handler JavaDoc)clazz.getConstructor(null).newInstance(null);
85                     service.addInHandler(handler);
86                 }
87             }
88             
89             List JavaDoc outList = connector.getServerOutHandlers();
90             if(outList != null)
91             {
92                 for(int i = 0; i < outList.size(); i++)
93                 {
94                     Class JavaDoc clazz = Class.forName(outList.get(i).toString());
95                     Handler JavaDoc handler = (Handler JavaDoc)clazz.getConstructor(null).newInstance(null);
96                     service.addOutHandler(handler);
97                 }
98             }
99
100             try
101             {
102                 clientPool = new StackObjectPool(new XFireClientPoolFactory(endpoint, service, xfire));
103                 clientPool.addObject();
104             }
105             catch (Exception JavaDoc ex)
106             {
107                 disconnect();
108                 throw ex;
109             }
110         }
111     }
112
113     protected void doDisconnect() throws Exception JavaDoc
114     {
115         if (clientPool != null)
116         {
117             clientPool.clear();
118             clientPool = null;
119         }
120     }
121
122     protected void doDispose()
123     {
124         // nothing to do
125
}
126
127     protected String JavaDoc getMethod(UMOEvent event) throws DispatchException
128     {
129         String JavaDoc method = (String JavaDoc)event.getMessage().getProperty(MuleProperties.MULE_METHOD_PROPERTY);
130                 
131         if (method == null)
132         {
133             UMOEndpointURI endpointUri = event.getEndpoint().getEndpointURI();
134             method = (String JavaDoc)endpointUri.getParams().get(MuleProperties.MULE_METHOD_PROPERTY);
135         }
136         
137         if (method == null)
138         {
139             method = (String JavaDoc)event.getEndpoint().getProperties().get(MuleProperties.MULE_METHOD_PROPERTY);
140         }
141         
142         if (method == null)
143         {
144             throw new DispatchException(new org.mule.config.i18n.Message("soap", 4), event.getMessage(),
145                event.getEndpoint());
146         }
147                 
148         return method;
149     }
150
151     protected Object JavaDoc[] getArgs(UMOEvent event) throws TransformerException
152     {
153         Object JavaDoc payload = event.getTransformedMessage();
154         Object JavaDoc[] args;
155
156         if (payload instanceof Object JavaDoc[])
157         {
158             args = (Object JavaDoc[])payload;
159         }
160         else
161         {
162             args = new Object JavaDoc[]{payload};
163         }
164
165         UMOMessage message = event.getMessage();
166         Set JavaDoc attachmentNames = message.getAttachmentNames();
167         if (attachmentNames != null && !attachmentNames.isEmpty())
168         {
169             List JavaDoc attachments = new ArrayList JavaDoc();
170             for (Iterator JavaDoc i = attachmentNames.iterator(); i.hasNext();)
171             {
172                 attachments.add(message.getAttachment((String JavaDoc)i.next()));
173             }
174             List JavaDoc temp = new ArrayList JavaDoc(Arrays.asList(args));
175             temp.add(attachments.toArray(new DataHandler JavaDoc[0]));
176             args = temp.toArray();
177         }
178
179         return args;
180     }
181
182     protected UMOMessage doSend(UMOEvent event) throws Exception JavaDoc
183     {
184         Client client = null;
185                 
186         try
187         {
188             client = (Client)clientPool.borrowObject();
189             client.setTimeout(event.getTimeout());
190             client.setProperty(MuleProperties.MULE_EVENT_PROPERTY, event);
191             String JavaDoc method = getMethod(event);
192             // Set custom soap action if set on the event or endpoint
193
String JavaDoc soapAction = (String JavaDoc)event.getMessage().getProperty(SoapConstants.SOAP_ACTION_PROPERTY);
194             if (soapAction != null)
195             {
196                 soapAction = parseSoapAction(soapAction, new QName JavaDoc(method), event);
197                 client.setProperty(org.codehaus.xfire.soap.SoapConstants.SOAP_ACTION, soapAction);
198             }
199
200             // Set Custom Headers on the client
201
Object JavaDoc[] arr = event.getMessage().getPropertyNames().toArray();
202             String JavaDoc head;
203             for (int i = 0; i < arr.length; i++){
204                 head = "";
205                 head = (String JavaDoc)arr[i];
206                 if ((head != null)&&(!head.startsWith("MULE"))){
207                     client.setProperty((String JavaDoc)arr[i], event.getMessage().getProperty((String JavaDoc)arr[i]));
208                 }
209             }
210
211             Object JavaDoc[] response = client.invoke(method, getArgs(event));
212
213             UMOMessage result = null;
214             if (response != null && response.length <= 1)
215             {
216                 if (response.length == 1)
217                 {
218                     result = new MuleMessage(response[0], event.getMessage());
219                 }
220             }
221             else
222             {
223                 result = new MuleMessage(response, event.getMessage());
224             }
225
226             return result;
227         }
228         finally
229         {
230             if (client != null)
231             {
232                 clientPool.returnObject(client);
233             }
234         }
235     }
236
237     protected void doDispatch(UMOEvent event) throws Exception JavaDoc
238     {
239         Client client = null;
240
241         try
242         {
243             client = (Client)clientPool.borrowObject();
244             client.setTimeout(event.getTimeout());
245             client.setProperty(MuleProperties.MULE_EVENT_PROPERTY, event);
246             client.invoke(getMethod(event), getArgs(event));
247         }
248         finally
249         {
250             if (client != null)
251             {
252                 clientPool.returnObject(client);
253             }
254         }
255     }
256
257     /**
258      * Make a specific request to the underlying transport
259      *
260      * @param endpoint the endpoint to use when connecting to the resource
261      * @param timeout the maximum time the operation should block before returning.
262      * The call should return immediately if there is data available. If
263      * no data becomes available before the timeout elapses, null will be
264      * returned
265      * @return the result of the request wrapped in a UMOMessage object. Null will be
266      * returned if no data was avaialable
267      * @throws Exception if the call to the underlying protocal cuases an exception
268      */

269     protected UMOMessage doReceive(UMOImmutableEndpoint endpoint, long timeout) throws Exception JavaDoc
270     {
271         String JavaDoc serviceName = getServiceName(endpoint);
272
273         XFire xfire = connector.getXfire();
274         Service service = xfire.getServiceRegistry().getService(serviceName);
275
276         Client client = new Client(new MuleUniversalTransport(), service, endpoint.getEndpointURI()
277             .toString());
278         client.setXFire(xfire);
279         client.setTimeout((int)timeout);
280         client.setEndpointUri(endpoint.getEndpointURI().toString());
281
282         String JavaDoc method = (String JavaDoc)endpoint.getProperty(MuleProperties.MULE_METHOD_PROPERTY);
283         OperationInfo op = service.getServiceInfo().getOperation(method);
284
285         Properties JavaDoc params = endpoint.getEndpointURI().getUserParams();
286         String JavaDoc args[] = new String JavaDoc[params.size()];
287         int i = 0;
288         for (Iterator JavaDoc iterator = params.values().iterator(); iterator.hasNext(); i++)
289         {
290             args[i] = iterator.next().toString();
291         }
292
293         Object JavaDoc[] response = client.invoke(op, args);
294
295         if (response != null && response.length == 1)
296         {
297             return new MuleMessage(response[0]);
298         }
299         else
300         {
301             return new MuleMessage(response);
302         }
303     }
304
305     public Object JavaDoc getDelegateSession() throws UMOException
306     {
307         return null;
308     }
309
310     /**
311      * Get the service that is mapped to the specified request.
312      */

313     protected String JavaDoc getServiceName(UMOImmutableEndpoint endpoint)
314     {
315         String JavaDoc pathInfo = endpoint.getEndpointURI().getPath();
316
317         if (StringUtils.isEmpty(pathInfo))
318         {
319             return endpoint.getEndpointURI().getHost();
320         }
321
322         String JavaDoc serviceName;
323
324         int i = pathInfo.lastIndexOf('/');
325
326         if (i > -1)
327         {
328             serviceName = pathInfo.substring(i + 1);
329         }
330         else
331         {
332             serviceName = pathInfo;
333         }
334
335         return serviceName;
336     }
337
338     public String JavaDoc parseSoapAction(String JavaDoc soapAction, QName JavaDoc method, UMOEvent event)
339     {
340
341         UMOEndpointURI endpointURI = event.getEndpoint().getEndpointURI();
342         Map JavaDoc properties = new HashMap JavaDoc();
343         UMOMessage msg = event.getMessage();
344         for (Iterator JavaDoc iterator = msg.getPropertyNames().iterator(); iterator.hasNext();)
345         {
346             String JavaDoc propertyKey = (String JavaDoc)iterator.next();
347             properties.put(propertyKey, msg.getProperty(propertyKey));
348         }
349         properties.put(MuleProperties.MULE_METHOD_PROPERTY, method.getLocalPart());
350         properties.put("methodNamespace", method.getNamespaceURI());
351         properties.put("address", endpointURI.getAddress());
352         properties.put("scheme", endpointURI.getScheme());
353         properties.put("host", endpointURI.getHost());
354         properties.put("port", String.valueOf(endpointURI.getPort()));
355         properties.put("path", endpointURI.getPath());
356         properties.put("hostInfo", endpointURI.getScheme()
357                                    + "://"
358                                    + endpointURI.getHost()
359                                    + (endpointURI.getPort() > -1
360                                                    ? ":" + String.valueOf(endpointURI.getPort()) : ""));
361         if (event.getComponent() != null)
362         {
363             properties.put("serviceName", event.getComponent().getDescriptor().getName());
364         }
365
366         soapAction = soapActionTemplateParser.parse(properties, soapAction);
367
368         if (logger.isDebugEnabled())
369         {
370             logger.debug("SoapAction for this call is: " + soapAction);
371         }
372
373         return soapAction;
374     }
375 }
376
Popular Tags