KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > providers > soap > axis > AxisServiceComponent


1 /*
2  * $Id: AxisServiceComponent.java 3798 2006-11-04 04:07:14Z aperepel $
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.axis;
12
13 import org.apache.axis.AxisEngine;
14 import org.apache.axis.AxisFault;
15 import org.apache.axis.ConfigurationException;
16 import org.apache.axis.Constants;
17 import org.apache.axis.Message;
18 import org.apache.axis.MessageContext;
19 import org.apache.axis.components.logger.LogFactory;
20 import org.apache.axis.description.OperationDesc;
21 import org.apache.axis.description.ServiceDesc;
22 import org.apache.axis.handlers.soap.SOAPService;
23 import org.apache.axis.i18n.Messages;
24 import org.apache.axis.security.servlet.ServletSecurityProvider;
25 import org.apache.axis.server.AxisServer;
26 import org.apache.axis.transport.http.HTTPConstants;
27 import org.apache.axis.transport.http.ServletEndpointContextImpl;
28 import org.apache.axis.utils.Admin;
29 import org.apache.axis.utils.XMLUtils;
30 import org.apache.commons.io.output.ByteArrayOutputStream;
31 import org.apache.commons.lang.StringUtils;
32 import org.apache.commons.logging.Log;
33 import org.mule.MuleManager;
34 import org.mule.config.MuleProperties;
35 import org.mule.impl.MuleMessage;
36 import org.mule.impl.RequestContext;
37 import org.mule.impl.endpoint.MuleEndpointURI;
38 import org.mule.providers.WriterMessageAdapter;
39 import org.mule.providers.http.HttpConnector;
40 import org.mule.providers.http.HttpConstants;
41 import org.mule.providers.soap.SoapConstants;
42 import org.mule.providers.soap.axis.extensions.MuleConfigProvider;
43 import org.mule.umo.UMOEventContext;
44 import org.mule.umo.UMOException;
45 import org.mule.umo.UMOMessage;
46 import org.mule.umo.endpoint.MalformedEndpointException;
47 import org.mule.umo.endpoint.UMOEndpointURI;
48 import org.mule.umo.lifecycle.Callable;
49 import org.mule.umo.lifecycle.Initialisable;
50 import org.mule.umo.lifecycle.InitialisationException;
51 import org.w3c.dom.Document JavaDoc;
52
53 import javax.servlet.ServletException JavaDoc;
54 import javax.servlet.http.HttpServletRequest JavaDoc;
55 import javax.xml.namespace.QName JavaDoc;
56 import javax.xml.soap.SOAPException JavaDoc;
57 import java.io.ByteArrayInputStream JavaDoc;
58 import java.io.File JavaDoc;
59 import java.io.FileInputStream JavaDoc;
60 import java.io.IOException JavaDoc;
61 import java.io.StringWriter JavaDoc;
62 import java.util.ArrayList JavaDoc;
63 import java.util.Iterator JavaDoc;
64 import java.util.Map JavaDoc;
65 import java.util.Properties JavaDoc;
66
67 /**
68  * <code>AxisServiceComponent</code> is a Mule component implementation of the Axis
69  * servlet. This component supports all the features of the Axis servlet except -
70  * <ol>
71  * <li>Jws class services are not supported as they don't add any value to the Mule
72  * model</li>
73  * <li>Currently there is no HttpSession support. This will be fixed when Session
74  * support is added to the Http Connector</li>
75  * </ol>
76  *
77  * @author <a HREF="mailto:ross.mason@symphonysoft.com">Ross Mason</a>
78  * @version $Revision: 3798 $
79  */

80
81 public class AxisServiceComponent implements Initialisable, Callable
82 {
83     /**
84      * logger used by this class
85      */

86     protected static Log logger = org.apache.commons.logging.LogFactory.getLog(AxisServiceComponent.class);
87
88     private static Log exceptionLog = LogFactory.getLog("org.apache.axis.EXCEPTIONS");
89
90     public static final String JavaDoc INIT_PROPERTY_TRANSPORT_NAME = "transport.name";
91     public static final String JavaDoc INIT_PROPERTY_USE_SECURITY = "use-servlet-security";
92     public static final String JavaDoc INIT_PROPERTY_ENABLE_LIST = "axis.enableListQuery";
93     public static final String JavaDoc DEFAULT_AXIS_HOME = "/axisHome";
94
95     private String JavaDoc transportName = "http";
96     private ServletSecurityProvider securityProvider;
97     private boolean enableList;
98     private String JavaDoc homeDir;
99     private AxisServer axisServer;
100
101     public AxisServiceComponent()
102     {
103         securityProvider = null;
104         enableList = true;
105     }
106
107     /**
108      * Passes the context to the listener
109      *
110      * @param context the context to process
111      * @return Object this object can be anything. When the
112      * <code>UMOLifecycleAdapter</code> for the component receives this
113      * object it will first see if the Object is an <code>UMOEvent</code>
114      * if not and the Object is not null a new context will be created using
115      * the returned object as the payload. This new context will then get
116      * published to the configured outbound endpoint if-
117      * <ol>
118      * <li>One has been configured for the UMO.</li>
119      * <li>the <code>setStopFurtherProcessing(true)</code> wasn't called
120      * on the previous context.</li>
121      * </ol>
122      * @throws Exception if the context fails to process properly. If exceptions
123      * aren't handled by the implementation they will be handled by the
124      * exceptionListener associated with the component
125      */

126     public Object JavaDoc onCall(UMOEventContext context) throws Exception JavaDoc
127     {
128         WriterMessageAdapter response = new WriterMessageAdapter(new StringWriter JavaDoc(4096));
129         String JavaDoc method = context.getMessage().getStringProperty(HttpConnector.HTTP_METHOD_PROPERTY,
130             HttpConstants.METHOD_POST);
131         if (HttpConstants.METHOD_GET.equalsIgnoreCase(method))
132         {
133             doGet(context, response);
134         }
135         else
136         {
137             doPost(context, response);
138         }
139         response.getWriter().close();
140         return new MuleMessage(response);
141     }
142
143     public void initialise() throws InitialisationException
144     {
145         // template method
146
}
147
148     public void doGet(UMOEventContext context, WriterMessageAdapter response)
149         throws UMOException, IOException JavaDoc
150     {
151         try
152         {
153             // We parse a new uri based on the listening host and port with the
154
// request parameters appended
155
// Using the soap prefix ensures that we use a soap endpoint builder
156
UMOEndpointURI endpointUri = context.getEndpointURI();
157             if (!"servlet".equalsIgnoreCase(context.getEndpointURI().getSchemeMetaInfo()))
158             {
159                 String JavaDoc uri = SoapConstants.SOAP_ENDPOINT_PREFIX + context.getEndpointURI().getScheme()
160                              + "://" + context.getEndpointURI().getHost() + ":"
161                              + context.getEndpointURI().getPort();
162                 uri += context.getMessageAsString();
163                 endpointUri = new MuleEndpointURI(uri);
164             }
165
166             AxisEngine engine = getAxisServer();
167             String JavaDoc pathInfo = endpointUri.getPath();
168             // String realpath =
169
// servletContext.getRealPath(request.getServletPath());
170
boolean wsdlRequested = false;
171             boolean listRequested = false;
172
173             if (endpointUri.getAddress().endsWith(".jws"))
174             {
175                 throw new AxisFault("Jws not supported by the Mule Axis service");
176             }
177
178             String JavaDoc queryString = endpointUri.getQuery();
179             if (queryString != null)
180             {
181                 if (queryString.equalsIgnoreCase(SoapConstants.WSDL_PROPERTY))
182                 {
183                     wsdlRequested = true;
184                 }
185                 else
186                 {
187                     if (queryString.equalsIgnoreCase(SoapConstants.LIST_PROPERTY))
188                     {
189                         listRequested = true;
190                     }
191                 }
192             }
193
194             boolean hasNoPath = (StringUtils.isEmpty(pathInfo) || pathInfo.equals("/"));
195             if (!wsdlRequested && !listRequested && hasNoPath)
196             {
197                 reportAvailableServices(context, response);
198             }
199             else
200             {
201                 // if(realpath != null)
202
MessageContext msgContext = new MessageContext(engine);
203                 populateMessageContext(msgContext, context, endpointUri);
204
205                 msgContext.setProperty("transport.url", endpointUri.toString());
206                 if (wsdlRequested)
207                 {
208                     processWsdlRequest(msgContext, response);
209                 }
210                 else if (listRequested)
211                 {
212                     processListRequest(response);
213                 }
214                 else if (true /* hasParameters */)
215                 {
216                     processMethodRequest(msgContext, context, response, endpointUri);
217                 }
218                 else
219                 {
220                     String JavaDoc serviceName = (String JavaDoc)msgContext.getProperty("serviceName");
221                     if (pathInfo.startsWith("/"))
222                     {
223                         serviceName = pathInfo.substring(1);
224                     }
225                     else
226                     {
227                         serviceName = pathInfo;
228                     }
229                     SOAPService s = engine.getService(serviceName);
230                     if (s == null)
231                     {
232                         reportCantGetAxisService(context, response);
233                     }
234                     else
235                     {
236                         reportServiceInfo(response, s, serviceName);
237                     }
238                 }
239             }
240         }
241         catch (AxisFault fault)
242         {
243             reportTroubleInGet(fault, response);
244         }
245         catch (Exception JavaDoc e)
246         {
247             reportTroubleInGet(e, response);
248         }
249     }
250
251     private void reportTroubleInGet(Exception JavaDoc exception, WriterMessageAdapter response)
252     {
253         response.setProperty(HttpConstants.HEADER_CONTENT_TYPE, "text/html");
254         response.setProperty(HttpConnector.HTTP_STATUS_PROPERTY, "500");
255         response.write("<h2>" + Messages.getMessage("error00") + "</h2>");
256         response.write("<p>" + Messages.getMessage("somethingWrong00") + "</p>");
257         if (exception instanceof AxisFault)
258         {
259             AxisFault fault = (AxisFault)exception;
260             processAxisFault(fault);
261             writeFault(response, fault);
262         }
263         else
264         {
265             logException(exception);
266             response.write("<pre>Exception - " + exception + "<br>");
267             response.write("</pre>");
268         }
269     }
270
271     protected void processAxisFault(AxisFault fault)
272     {
273         org.w3c.dom.Element JavaDoc runtimeException = fault.lookupFaultDetail(Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION);
274         if (runtimeException != null)
275         {
276             exceptionLog.info(Messages.getMessage("axisFault00"), fault);
277             fault.removeFaultDetail(Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION);
278         }
279         else if (exceptionLog.isDebugEnabled())
280         {
281             exceptionLog.debug(Messages.getMessage("axisFault00"), fault);
282         }
283
284     }
285
286     protected void logException(Exception JavaDoc e)
287     {
288         exceptionLog.info(Messages.getMessage("exception00"), e);
289     }
290
291     private void writeFault(WriterMessageAdapter response, AxisFault axisFault)
292     {
293         String JavaDoc localizedMessage = XMLUtils.xmlEncodeString(axisFault.getLocalizedMessage());
294         response.write("<pre>Fault - " + localizedMessage + "<br>");
295         response.write(axisFault.dumpToString());
296         response.write("</pre>");
297     }
298
299     protected void processMethodRequest(MessageContext msgContext,
300                                         UMOEventContext context,
301                                         WriterMessageAdapter response,
302                                         UMOEndpointURI endpointUri) throws AxisFault
303     {
304         Properties params = endpointUri.getUserParams();
305
306         String JavaDoc method = (String JavaDoc)params.remove(MuleProperties.MULE_METHOD_PROPERTY);
307         if (method == null)
308         {
309             method = endpointUri.getPath().substring(endpointUri.getPath().lastIndexOf("/") + 1);
310         }
311         StringBuffer JavaDoc args = new StringBuffer JavaDoc(64);
312
313         Map.Entry JavaDoc entry;
314         for (Iterator JavaDoc iterator = params.entrySet().iterator(); iterator.hasNext();)
315         {
316             entry = (Map.Entry JavaDoc)iterator.next();
317             args.append("<").append(entry.getKey()).append(">");
318             args.append(entry.getValue());
319             args.append("</").append(entry.getKey()).append(">");
320         }
321
322         if (method == null)
323         {
324             response.setProperty(HttpConstants.HEADER_CONTENT_TYPE, "text/html");
325             response.setProperty(HttpConnector.HTTP_STATUS_PROPERTY, "400");
326             response.write("<h2>" + Messages.getMessage("error00") + ": "
327                            + Messages.getMessage("invokeGet00") + "</h2>");
328             response.write("<p>" + Messages.getMessage("noMethod01") + "</p>");
329         }
330         else
331         {
332             invokeEndpointFromGet(msgContext, response, method, args.toString());
333         }
334     }
335
336     protected void processWsdlRequest(MessageContext msgContext, WriterMessageAdapter response)
337         throws AxisFault
338     {
339         AxisEngine engine = getAxisServer();
340         try
341         {
342             engine.generateWSDL(msgContext);
343             Document JavaDoc doc = (Document JavaDoc)msgContext.getProperty("WSDL");
344             if (doc != null)
345             {
346                 response.setProperty(HttpConstants.HEADER_CONTENT_TYPE, "text/xml");
347                 XMLUtils.DocumentToWriter(doc, response.getWriter());
348             }
349             else
350             {
351                 if (logger.isDebugEnabled())
352                 {
353                     logger.debug("processWsdlRequest: failed to create WSDL");
354                 }
355                 reportNoWSDL(response, "noWSDL02", null);
356             }
357         }
358         catch (AxisFault axisFault)
359         {
360             if (axisFault.getFaultCode().equals(Constants.QNAME_NO_SERVICE_FAULT_CODE))
361             {
362                 processAxisFault(axisFault);
363                 response.setProperty(HttpConnector.HTTP_STATUS_PROPERTY, "404");
364                 reportNoWSDL(response, "noWSDL01", axisFault);
365             }
366             else
367             {
368                 throw axisFault;
369             }
370         }
371     }
372
373     protected void invokeEndpointFromGet(MessageContext msgContext,
374                                          WriterMessageAdapter response,
375                                          String JavaDoc method,
376                                          String JavaDoc args) throws AxisFault
377     {
378         String JavaDoc body = "<" + method + ">" + args + "</" + method + ">";
379         String JavaDoc msgtxt = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Body>"
380                         + body + "</SOAP-ENV:Body>" + "</SOAP-ENV:Envelope>";
381         Message responseMsg = null;
382         try
383         {
384             ByteArrayInputStream JavaDoc istream = new ByteArrayInputStream JavaDoc(msgtxt.getBytes("ISO-8859-1"));
385             AxisEngine engine = getAxisServer();
386             Message msg = new Message(istream, false);
387             msgContext.setRequestMessage(msg);
388             engine.invoke(msgContext);
389             responseMsg = msgContext.getResponseMessage();
390             response.setProperty(HTTPConstants.HEADER_CACHE_CONTROL, "no-cache");
391             response.setProperty(HTTPConstants.HEADER_PRAGMA, "no-cache");
392             if (responseMsg == null)
393             {
394                 throw new Exception JavaDoc(Messages.getMessage("noResponse01"));
395             }
396         }
397         catch (AxisFault fault)
398         {
399             processAxisFault(fault);
400             configureResponseFromAxisFault(response, fault);
401             responseMsg = new Message(fault);
402         }
403         catch (Exception JavaDoc e)
404         {
405             response.setProperty(HttpConnector.HTTP_STATUS_PROPERTY, "500");
406             responseMsg = convertExceptionToAxisFault(e, responseMsg);
407         }
408         response.setProperty(HTTPConstants.HEADER_CONTENT_TYPE, "text/xml");
409         response.write(responseMsg.getSOAPPartAsString());
410     }
411
412     protected void reportServiceInfo(WriterMessageAdapter response, SOAPService service, String JavaDoc serviceName)
413     {
414         response.setProperty(HttpConstants.HEADER_CONTENT_TYPE, "text/html");
415         response.write("<h1>" + service.getName() + "</h1>");
416         response.write("<p>" + Messages.getMessage("axisService00") + "</p>");
417         response.write("<i>" + Messages.getMessage("perhaps00") + "</i>");
418     }
419
420     protected void processListRequest(WriterMessageAdapter response) throws AxisFault
421     {
422         AxisEngine engine = getAxisServer();
423         response.setProperty(HTTPConstants.HEADER_CONTENT_TYPE, "text/html");
424         if (enableList)
425         {
426             Document JavaDoc doc = Admin.listConfig(engine);
427             if (doc != null)
428             {
429                 XMLUtils.DocumentToWriter(doc, response.getWriter());
430             }
431             else
432             {
433                 response.setProperty(HttpConnector.HTTP_STATUS_PROPERTY, "404");
434                 response.write("<h2>" + Messages.getMessage("error00") + "</h2>");
435                 response.write("<p>" + Messages.getMessage("noDeploy00") + "</p>");
436             }
437         }
438         else
439         {
440             response.setProperty(HttpConnector.HTTP_STATUS_PROPERTY, "403");
441             response.write("<h2>" + Messages.getMessage("error00") + "</h2>");
442             response.write("<p><i>?list</i> " + Messages.getMessage("disabled00") + "</p>");
443         }
444     }
445
446     protected void reportNoWSDL(WriterMessageAdapter response, String JavaDoc moreDetailCode, AxisFault axisFault)
447     {
448         response.setProperty(HttpConnector.HTTP_STATUS_PROPERTY, "404");
449         response.setProperty(HTTPConstants.HEADER_CONTENT_TYPE, "text/html");
450         response.write("<h2>" + Messages.getMessage("error00") + "</h2>");
451         response.write("<p>" + Messages.getMessage("noWSDL00") + "</p>");
452         if (moreDetailCode != null)
453         {
454             response.write("<p>" + Messages.getMessage(moreDetailCode) + "</p>");
455         }
456
457     }
458
459     protected void reportAvailableServices(UMOEventContext context, WriterMessageAdapter response)
460         throws ConfigurationException, AxisFault
461     {
462         AxisEngine engine = getAxisServer();
463         response.setProperty(HttpConstants.HEADER_CONTENT_TYPE, "text/html");
464         response.write("<h2>And now... Some Services</h2>");
465         String JavaDoc version = MuleManager.getConfiguration().getProductVersion();
466         if (version == null)
467         {
468             version = "Version Not Set";
469         }
470         response.write("<h5>(Mule - " + version + ")</h5>");
471         Iterator JavaDoc i;
472
473         try
474         {
475             response.write("<table width=\"400\"><tr><th>Mule Component Services</th><th>Axis Services</th></tr><tr><td width=\"200\" valign=\"top\">");
476             i = engine.getConfig().getDeployedServices();
477             listServices(i, response);
478             response.write("</td><td width=\"200\" valign=\"top\">");
479             i = ((MuleConfigProvider)engine.getConfig()).getAxisDeployedServices();
480             listServices(i, response);
481             response.write("</td></tr></table>");
482         }
483         catch (ConfigurationException configException)
484         {
485             if (configException.getContainedException() instanceof AxisFault)
486             {
487                 throw (AxisFault)configException.getContainedException();
488             }
489             else
490             {
491                 throw configException;
492             }
493         }
494
495     }
496
497     private void listServices(Iterator JavaDoc i, WriterMessageAdapter response)
498     {
499         response.write("<ul>");
500         while (i.hasNext())
501         {
502             ServiceDesc sd = (ServiceDesc)i.next();
503             StringBuffer JavaDoc sb = new StringBuffer JavaDoc(512);
504             sb.append("<li>");
505             String JavaDoc name = sd.getName();
506             sb.append(name);
507             sb.append(" <a HREF=\"");
508             if (sd.getEndpointURL() != null)
509             {
510                 sb.append(sd.getEndpointURL());
511                 if (!sd.getEndpointURL().endsWith("/"))
512                 {
513                     sb.append("/");
514                 }
515             }
516             sb.append(name);
517             sb.append("?wsdl\"><i>(wsdl)</i></a></li>");
518             response.write(sb.toString());
519             if (sd.getDocumentation() != null)
520             {
521                 response.write("<ul><h6>" + sd.getDocumentation() + "</h6></ul>");
522             }
523             ArrayList JavaDoc operations = sd.getOperations();
524             if (!operations.isEmpty())
525             {
526                 response.write("<ul>");
527                 OperationDesc desc;
528                 for (Iterator JavaDoc it = operations.iterator(); it.hasNext();)
529                 {
530                     desc = (OperationDesc)it.next();
531                     response.write("<li>" + desc.getName());
532                 }
533                 response.write("</ul>");
534             }
535         }
536         response.write("</ul>");
537     }
538
539     protected void reportCantGetAxisService(UMOEventContext context, WriterMessageAdapter response)
540     {
541         response.setProperty(HttpConnector.HTTP_STATUS_PROPERTY, "404");
542         response.setProperty(HttpConstants.HEADER_CONTENT_TYPE, "text/html");
543         response.write("<h2>" + Messages.getMessage("error00") + "</h2>");
544         response.write("<p>" + Messages.getMessage("noService06") + "</p>");
545     }
546
547     public void doPost(UMOEventContext context, WriterMessageAdapter response)
548         throws ServletException JavaDoc, IOException JavaDoc
549     {
550         String JavaDoc soapAction = null;
551         AxisEngine engine = getAxisServer();
552         if (engine == null)
553         {
554             ServletException JavaDoc se = new ServletException JavaDoc(Messages.getMessage("noEngine00"));
555             logger.debug("No Engine!", se);
556             throw se;
557         }
558         MessageContext msgContext = new MessageContext(engine);
559         if (logger.isDebugEnabled())
560         {
561             logger.debug("Enter: doPost()");
562         }
563         Message responseMsg = null;
564         String JavaDoc contentType = null;
565         try
566         {
567             UMOEndpointURI endpointUri = getEndpoint(context);
568             populateMessageContext(msgContext, context, endpointUri);
569             if (securityProvider != null)
570             {
571                 if (logger.isDebugEnabled())
572                 {
573                     logger.debug("securityProvider:" + securityProvider);
574                 }
575                 msgContext.setProperty("securityProvider", securityProvider);
576             }
577
578             Object JavaDoc request = context.getTransformedMessage();
579             if (request instanceof File JavaDoc)
580             {
581                 request = new FileInputStream JavaDoc((File JavaDoc)request);
582             }
583             else if (request instanceof byte[])
584             {
585                 request = new ByteArrayInputStream JavaDoc((byte[])request);
586             }
587
588             Message requestMsg = new Message(request, false, context.getMessage().getStringProperty(
589                 HTTPConstants.HEADER_CONTENT_TYPE, null), context.getMessage().getStringProperty(
590                 HTTPConstants.HEADER_CONTENT_LOCATION, null));
591
592             if (logger.isDebugEnabled())
593             {
594                 logger.debug("Request Message:" + requestMsg);
595             }
596             msgContext.setRequestMessage(requestMsg);
597             msgContext.setProperty("transport.url", endpointUri.toString());
598
599             soapAction = getSoapAction(context);
600             if (soapAction != null)
601             {
602                 msgContext.setUseSOAPAction(true);
603                 msgContext.setSOAPActionURI(soapAction);
604             }
605             // TODO session support
606
// msgContext.setSession(new AxisHttpSession(req));
607

608             if (logger.isDebugEnabled())
609             {
610                 logger.debug("Invoking Axis Engine.");
611             }
612             engine.invoke(msgContext);
613             if (logger.isDebugEnabled())
614             {
615                 logger.debug("Return from Axis Engine.");
616             }
617             if (RequestContext.getExceptionPayload() instanceof Exception JavaDoc)
618             {
619                 throw (Exception JavaDoc)RequestContext.getExceptionPayload().getException();
620             }
621             // remove temporary file used for soap message with attachment
622
if (request instanceof File JavaDoc)
623             {
624                 ((File JavaDoc)request).delete();
625             }
626             responseMsg = msgContext.getResponseMessage();
627             if (responseMsg == null)
628             {
629                 throw new Exception JavaDoc(Messages.getMessage("noResponse01"));
630             }
631         }
632         catch (AxisFault fault)
633         {
634             logger.error(fault.toString() + " target service is: " + msgContext.getTargetService()
635                          + ". Event is: " + context.toString(), fault);
636             processAxisFault(fault);
637             configureResponseFromAxisFault(response, fault);
638             responseMsg = msgContext.getResponseMessage();
639             if (responseMsg == null)
640             {
641                 responseMsg = new Message(fault);
642             }
643         }
644         catch (Exception JavaDoc e)
645         {
646             responseMsg = msgContext.getResponseMessage();
647             response.setProperty(HttpConnector.HTTP_STATUS_PROPERTY, "500");
648             responseMsg = convertExceptionToAxisFault(e, responseMsg);
649         }
650
651         contentType = responseMsg.getContentType(msgContext.getSOAPConstants());
652
653         sendResponse(context.getMessage().getStringProperty(HttpConnector.HTTP_STATUS_PROPERTY, null),
654             contentType, response, responseMsg);
655
656         if (logger.isDebugEnabled())
657         {
658             logger.debug("Response sent.");
659             logger.debug("Exit: doPost()");
660         }
661     }
662
663     private UMOEndpointURI getEndpoint(UMOEventContext context) throws MalformedEndpointException
664     {
665         String JavaDoc endpoint = context.getEndpointURI().getAddress();
666         String JavaDoc request = context.getMessage().getStringProperty(HttpConnector.HTTP_REQUEST_PROPERTY, null);
667         if (request != null)
668         {
669             int i = endpoint.indexOf("/", endpoint.indexOf("://") + 3);
670             if (i > -1)
671             {
672                 endpoint = endpoint.substring(0, i);
673             }
674             endpoint += request;
675             return new MuleEndpointURI(endpoint);
676         }
677         return context.getEndpointURI();
678     }
679
680     private void configureResponseFromAxisFault(WriterMessageAdapter response, AxisFault fault)
681     {
682         int status = getHttpResponseStatus(fault);
683         if (status == 401)
684         {
685             response.setProperty(HttpConstants.HEADER_WWW_AUTHENTICATE, "Basic realm=\"AXIS\"");
686         }
687         response.setProperty(HttpConnector.HTTP_STATUS_PROPERTY, String.valueOf(status));
688     }
689
690     private Message convertExceptionToAxisFault(Exception JavaDoc exception, Message responseMsg)
691     {
692         logException(exception);
693         if (responseMsg == null)
694         {
695             AxisFault fault = AxisFault.makeFault(exception);
696             processAxisFault(fault);
697             responseMsg = new Message(fault);
698         }
699         return responseMsg;
700     }
701
702     protected int getHttpResponseStatus(AxisFault af)
703     {
704         return af.getFaultCode().getLocalPart().startsWith("Server.Unauth") ? 401 : '\u01F4';
705     }
706
707     private void sendResponse(String JavaDoc clientVersion,
708                               String JavaDoc contentType,
709                               WriterMessageAdapter response,
710                               Message responseMsg) throws AxisFault, IOException JavaDoc
711     {
712         if (responseMsg == null)
713         {
714             response.setProperty(HttpConnector.HTTP_STATUS_PROPERTY, "204");
715             if (logger.isDebugEnabled())
716             {
717                 logger.debug("NO AXIS MESSAGE TO RETURN!");
718             }
719         }
720         else
721         {
722             if (logger.isDebugEnabled())
723             {
724                 logger.debug("Returned Content-Type:" + contentType);
725             }
726             try
727             {
728                 response.setProperty(HttpConstants.HEADER_CONTENT_TYPE, contentType);
729                 ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
730                 responseMsg.writeTo(baos);
731                 response.write(baos.toString());
732             }
733             catch (SOAPException JavaDoc e)
734             {
735                 logException(e);
736             }
737         }
738         // if(!res.isCommitted())
739
// res.flushBuffer();
740
}
741
742     private void populateMessageContext(MessageContext msgContext,
743                                         UMOEventContext context,
744                                         UMOEndpointURI endpointUri) throws AxisFault, ConfigurationException
745     {
746         UMOMessage msg = context.getMessage();
747
748         if (logger.isDebugEnabled())
749         {
750             logger.debug("MessageContext:" + msgContext);
751             logger.debug("HEADER_CONTENT_TYPE:"
752                          + msg.getStringProperty(HttpConstants.HEADER_CONTENT_TYPE, null));
753             logger.debug("HEADER_CONTENT_LOCATION:"
754                          + msg.getStringProperty(HttpConstants.HEADER_CONTENT_LOCATION, null));
755             logger.debug("Constants.MC_HOME_DIR:" + String.valueOf(getHomeDir()));
756             logger.debug("Constants.MC_RELATIVE_PATH:" + endpointUri.getPath());
757             // logger.debug("HTTPConstants.MC_HTTP_SERVLETLOCATION:" +
758
// String.valueOf(getWebInfPath()));
759
// logger.debug("HTTPConstants.MC_HTTP_SERVLETPATHINFO:" +
760
// req.getPathInfo());
761
logger.debug("HTTPConstants.HEADER_AUTHORIZATION:" + msg.getStringProperty("Authorization", null));
762             logger.debug("Constants.MC_REMOTE_ADDR:" + endpointUri.getHost());
763             // logger.debug("configPath:" + String.valueOf(getWebInfPath()));
764
}
765
766         msgContext.setTransportName(transportName);
767         msgContext.setProperty("home.dir", getHomeDir());
768         msgContext.setProperty("path", endpointUri.getPath());
769         msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLET, this);
770         msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETLOCATION, endpointUri.getPath());
771         // determine service name
772
String JavaDoc serviceName = getServiceName(context, endpointUri);
773         // Validate Service path against request path
774
SOAPService service = msgContext.getAxisEngine().getConfig().getService(
775             new QName JavaDoc(serviceName.substring(1)));
776
777         // Component Name is set by Mule so if its null we can skip this check
778
if (service.getOption(AxisConnector.SERVICE_PROPERTY_COMPONENT_NAME) != null)
779         {
780             String JavaDoc servicePath = (String JavaDoc)service.getOption("servicePath");
781             if (StringUtils.isEmpty(endpointUri.getPath()))
782             {
783                 if (!("/" + endpointUri.getAddress()).startsWith(servicePath + serviceName))
784                 {
785                     throw new AxisFault("Failed to find service: " + "/" + endpointUri.getAddress());
786                 }
787             }
788             else if (!endpointUri.getPath().startsWith(servicePath + serviceName))
789             {
790                 throw new AxisFault("Failed to find service: " + endpointUri.getPath());
791             }
792         }
793
794         msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETPATHINFO, serviceName);
795         msgContext.setProperty("serviceName", serviceName);
796
797         msgContext.setProperty("Authorization", msg.getStringProperty("Authorization", null));
798         msgContext.setProperty("remoteaddr", endpointUri.getHost());
799         ServletEndpointContextImpl sec = new ServletEndpointContextImpl();
800         msgContext.setProperty("servletEndpointContext", sec);
801         // String realpath =
802
// getServletConfig().getServletContext().getRealPath(req.getServletPath());
803
// if(realpath != null)
804
// msgContext.setProperty("realpath", realpath);
805
// msgContext.setProperty("configPath", getWebInfPath());
806
}
807
808     private String JavaDoc getSoapAction(UMOEventContext context) throws AxisFault
809     {
810         String JavaDoc soapAction = context.getMessage().getStringProperty("SOAPAction", null);
811         if (logger.isDebugEnabled())
812         {
813             logger.debug("Header Soap Action:" + soapAction);
814         }
815         // if (soapAction == null) {
816
// AxisFault af = new AxisFault("Client.NoSOAPAction",
817
// Messages.getMessage("noHeader00", "SOAPAction"),
818
// null,
819
// null);
820
// exceptionLog.error(Messages.getMessage("genFault00"), af);
821
// throw af;
822
// }
823
if (StringUtils.isEmpty(soapAction))
824         {
825             soapAction = context.getEndpointURI().getAddress();
826         }
827         return soapAction;
828     }
829
830     protected String JavaDoc getServiceName(UMOEventContext context, UMOEndpointURI endpointUri) throws AxisFault
831     {
832         String JavaDoc serviceName = endpointUri.getPath();
833         if (StringUtils.isEmpty(serviceName))
834         {
835             serviceName = getSoapAction(context);
836             serviceName = serviceName.replaceAll("\"", "");
837             int i = serviceName.indexOf("/", serviceName.indexOf("//"));
838             if (i < -1)
839             {
840                 serviceName = serviceName.substring(i + 2);
841             }
842
843         }
844         // int i = serviceName.lastIndexOf("/");
845
// if (i > -1) serviceName = serviceName.substring(0, i);
846

847         int i = serviceName.lastIndexOf('/');
848         if (i > -1)
849         {
850             serviceName = serviceName.substring(i);
851         }
852         i = serviceName.lastIndexOf('?');
853         if (i > -1)
854         {
855             serviceName = serviceName.substring(0, i);
856         }
857         return serviceName;
858     }
859
860     protected String JavaDoc getProtocolVersion(HttpServletRequest JavaDoc req)
861     {
862         String JavaDoc ret = HTTPConstants.HEADER_PROTOCOL_V10;
863         String JavaDoc prot = req.getProtocol();
864         if (prot != null)
865         {
866             int sindex = prot.indexOf('/');
867             if (-1 != sindex)
868             {
869                 String JavaDoc ver = prot.substring(sindex + 1);
870                 if (HTTPConstants.HEADER_PROTOCOL_V11.equals(ver.trim()))
871                 {
872                     ret = HTTPConstants.HEADER_PROTOCOL_V11;
873                 }
874             }
875         }
876         return ret;
877     }
878
879     public String JavaDoc getTransportName()
880     {
881         return transportName;
882     }
883
884     public void setTransportName(String JavaDoc transportName)
885     {
886         this.transportName = transportName;
887     }
888
889     public boolean isEnableList()
890     {
891         return enableList;
892     }
893
894     public void setEnableList(boolean enableList)
895     {
896         this.enableList = enableList;
897     }
898
899     public String JavaDoc getHomeDir()
900     {
901         if (homeDir == null)
902         {
903             homeDir = MuleManager.getConfiguration().getWorkingDirectory() + DEFAULT_AXIS_HOME;
904         }
905         return homeDir;
906     }
907
908     public void setHomeDir(String JavaDoc homeDir)
909     {
910         this.homeDir = homeDir;
911     }
912
913     public AxisServer getAxisServer()
914     {
915         return axisServer;
916     }
917
918     public void setAxisServer(AxisServer axisServer)
919     {
920         this.axisServer = axisServer;
921
922     }
923 }
924
Popular Tags