KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > geronimo > axis > server > AxisWebServiceContainer


1 /**
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.geronimo.axis.server;
18
19 import java.io.InputStream JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.net.URI JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.Map JavaDoc;
24 import javax.servlet.http.HttpServletResponse JavaDoc;
25 import javax.wsdl.OperationType;
26 import javax.xml.soap.MimeHeader JavaDoc;
27 import javax.xml.soap.MimeHeaders JavaDoc;
28 import javax.xml.soap.SOAPMessage JavaDoc;
29
30 import org.apache.axis.AxisFault;
31 import org.apache.axis.Constants;
32 import org.apache.axis.Message;
33 import org.apache.axis.MessageContext;
34 import org.apache.axis.SOAPPart;
35 import org.apache.axis.handlers.soap.SOAPService;
36 import org.apache.axis.message.SOAPEnvelope;
37 import org.apache.axis.soap.SOAPConstants;
38 import org.apache.axis.transport.http.HTTPConstants;
39 import org.apache.axis.utils.Messages;
40 import org.apache.commons.logging.Log;
41 import org.apache.commons.logging.LogFactory;
42 import org.apache.geronimo.webservices.WebServiceContainer;
43 import org.w3c.dom.Element JavaDoc;
44
45 /**
46  * @version $Rev: 476049 $ $Date: 2006-11-16 23:35:17 -0500 (Thu, 16 Nov 2006) $
47  */

48 public class AxisWebServiceContainer implements WebServiceContainer {
49     public static final String JavaDoc REQUEST = AxisWebServiceContainer.class.getName() + "@Request";
50     public static final String JavaDoc RESPONSE = AxisWebServiceContainer.class.getName() + "@Response";
51
52     private static Log log = LogFactory.getLog(AxisWebServiceContainer.class);
53
54     public static final String JavaDoc XSD_NS = "http://www.w3.org/2001/XMLSchema";
55
56     private final URI JavaDoc location;
57     private final URI JavaDoc wsdlLocation;
58     private final SOAPService service;
59
60     private transient final ClassLoader JavaDoc classLoader;
61     private final Map JavaDoc wsdlMap;
62
63     public AxisWebServiceContainer(URI JavaDoc location, URI JavaDoc wsdlURL, SOAPService service, Map JavaDoc wsdlMap, ClassLoader JavaDoc classLoader) {
64         this.location = location;
65         this.wsdlLocation = wsdlURL;
66         this.service = service;
67         this.wsdlMap = wsdlMap;
68         if (classLoader == null) {
69             this.classLoader = Thread.currentThread().getContextClassLoader();
70         } else {
71             this.classLoader = classLoader;
72         }
73     }
74
75     public void invoke(Request req, Response JavaDoc res) throws Exception JavaDoc {
76         org.apache.axis.MessageContext messageContext = new org.apache.axis.MessageContext(null);
77         req.setAttribute(MESSAGE_CONTEXT, messageContext);
78
79         messageContext.setClassLoader(classLoader);
80
81         Message JavaDoc responseMessage = null;
82
83         String JavaDoc contentType = req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE);
84         String JavaDoc contentLocation = req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION);
85         InputStream JavaDoc inputStream = req.getInputStream();
86         Message JavaDoc requestMessage = new Message JavaDoc(inputStream, false, contentType, contentLocation);
87
88         messageContext.setRequestMessage(requestMessage);
89         messageContext.setProperty(HTTPConstants.MC_HTTP_SERVLETPATHINFO, req.getURI().getPath());
90         messageContext.setProperty(org.apache.axis.MessageContext.TRANS_URL, req.getURI().toString());
91         messageContext.setService(service);
92         messageContext.setProperty(REQUEST, req);
93         messageContext.setProperty(RESPONSE, res);
94
95         ClassLoader JavaDoc oldClassLoader = Thread.currentThread().getContextClassLoader();
96         try {
97             try {
98                 String JavaDoc characterEncoding = (String JavaDoc) requestMessage.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
99                 if (characterEncoding != null) {
100                     messageContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, characterEncoding);
101                 } else {
102                     messageContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
103                 }
104
105
106                 String JavaDoc soapAction = req.getHeader(HTTPConstants.HEADER_SOAP_ACTION);
107                 if (soapAction != null) {
108                     messageContext.setUseSOAPAction(true);
109                     messageContext.setSOAPActionURI(soapAction);
110                 }
111
112                 SOAPEnvelope env = requestMessage.getSOAPEnvelope();
113                 if (env != null && env.getSOAPConstants() != null) {
114                     messageContext.setSOAPConstants(env.getSOAPConstants());
115                 }
116                 SOAPService service = messageContext.getService();
117
118                 Thread.currentThread().setContextClassLoader(classLoader);
119                 service.invoke(messageContext);
120
121                 responseMessage = messageContext.getResponseMessage();
122             } catch (AxisFault fault) {
123                 
124                 if(req.getMethod() == req.GET && req.getParameters().isEmpty()){
125                     String JavaDoc serviceName = req.getURI().getRawPath();
126                     serviceName = serviceName.substring(serviceName.lastIndexOf("/")+1);
127                     printServiceInfo(res,serviceName);
128                     return;
129                 }else{
130                     responseMessage = handleFault(fault, res, messageContext);
131                 }
132
133             } catch (Exception JavaDoc e) {
134                 responseMessage = handleException(messageContext, res, e);
135             }
136             //TODO investigate and fix operation == null!
137
if (messageContext.getOperation() != null) {
138                 if (messageContext.getOperation().getMep() == OperationType.ONE_WAY) {
139                     // No content, so just indicate accepted
140
res.setStatusCode(202);
141                     return;
142                 } else if (responseMessage == null) {
143                     responseMessage = handleException(messageContext, null, new RuntimeException JavaDoc("No response for non-one-way operation"));
144                 }
145             } else if (responseMessage == null) {
146                 res.setStatusCode(202);
147                 return;
148             }
149             try {
150                 SOAPConstants soapConstants = messageContext.getSOAPConstants();
151                 String JavaDoc contentType1 = responseMessage.getContentType(soapConstants);
152                 res.setContentType(contentType1);
153                 // Transfer MIME headers to HTTP headers for response message.
154
MimeHeaders JavaDoc responseMimeHeaders = responseMessage.getMimeHeaders();
155                 for (Iterator JavaDoc i = responseMimeHeaders.getAllHeaders(); i.hasNext();) {
156                     MimeHeader JavaDoc responseMimeHeader = (MimeHeader JavaDoc) i.next();
157                     res.setHeader(responseMimeHeader.getName(),
158                             responseMimeHeader.getValue());
159                 }
160                 //TODO discuss this with dims.
161
// // synchronize the character encoding of request and response
162
// String responseEncoding = (String) messageContext.getProperty(
163
// SOAPMessage.CHARACTER_SET_ENCODING);
164
// if (responseEncoding != null) {
165
// try {
166
// responseMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING,
167
// responseEncoding);
168
// } catch (SOAPException e) {
169
// log.info(Messages.getMessage("exception00"), e);
170
// }
171
// }
172
//determine content type from message response
173
contentType = responseMessage.getContentType(messageContext.
174                         getSOAPConstants());
175                 responseMessage.writeTo(res.getOutputStream());
176             } catch (Exception JavaDoc e) {
177                 log.warn(Messages.getMessage("exception00"), e);
178             }
179         } finally {
180             Thread.currentThread().setContextClassLoader(oldClassLoader);
181         }
182     }
183
184     private Message JavaDoc handleException(MessageContext context, Response JavaDoc res, Exception JavaDoc e) {
185         Message JavaDoc responseMessage;
186         //other exceptions are internal trouble
187
responseMessage = context.getResponseMessage();
188         res.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
189         Message JavaDoc responseMsg = responseMessage;
190         log.warn(Messages.getMessage("exception00"), e);
191         if (responseMsg == null) {
192             AxisFault fault = AxisFault.makeFault(e);
193             //log the fault
194
Element JavaDoc runtimeException = fault.lookupFaultDetail(Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION);
195             if (runtimeException != null) {
196                 log.debug(Messages.getMessage("axisFault00"), fault);
197                 //strip runtime details
198
fault.removeFaultDetail(Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION);
199             }
200             responseMsg = new Message JavaDoc(fault);
201         }
202         responseMessage = responseMsg;
203         SOAPPart soapPart = (SOAPPart) responseMessage.getSOAPPart();
204         soapPart.getMessage().setMessageContext(context);
205         return responseMessage;
206     }
207
208     private Message JavaDoc handleFault(AxisFault fault, Response JavaDoc res, MessageContext context) {
209         Message JavaDoc responseMessage;
210         Element JavaDoc runtimeException = fault.lookupFaultDetail(Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION);
211
212         log.warn(Messages.getMessage("axisFault00"), fault);
213         if (runtimeException != null) {
214             //strip runtime details
215
fault.removeFaultDetail(Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION);
216         }
217
218         int status = fault.getFaultCode().getLocalPart().startsWith("Server.Unauth")
219                 ? HttpServletResponse.SC_UNAUTHORIZED
220                 : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
221         if (status == HttpServletResponse.SC_UNAUTHORIZED) {
222             // unauth access results in authentication request
223
// TODO: less generic realm choice?
224
res.setHeader("WWW-Authenticate", "Basic realm=\"AXIS\"");
225         }
226         res.setStatusCode(status);
227         responseMessage = context.getResponseMessage();
228         if (responseMessage == null) {
229             responseMessage = new Message JavaDoc(fault);
230             SOAPPart soapPart = (SOAPPart) responseMessage.getSOAPPart();
231             soapPart.getMessage().setMessageContext(context);
232         }
233         return responseMessage;
234     }
235
236     public void getWsdl(Request request, Response JavaDoc response) throws Exception JavaDoc {
237         URI JavaDoc realLocation = request.getURI();
238 // log.info("Request at " + realLocation);
239
String JavaDoc query = realLocation.getQuery();
240         if (query == null || !query.toLowerCase().startsWith("wsdl")) {
241             throw new IllegalStateException JavaDoc("request must contain a wsdl or WSDL parameter: " + request.getParameters());
242         }
243         String JavaDoc locationKey;
244         if (query.length() > 4) {
245             locationKey = query.substring(5);
246         } else {
247             locationKey = wsdlLocation.toString();
248         }
249         Object JavaDoc wsdl = wsdlMap.get(locationKey);
250         if (wsdl == null) {
251             throw new IllegalStateException JavaDoc("No wsdl or schema known at location: " + locationKey);
252         }
253         URI JavaDoc updated = new URI JavaDoc(realLocation.getScheme(),
254                 realLocation.getUserInfo(),
255                 realLocation.getHost(),
256                 realLocation.getPort(),
257                 null, //try null for no path
258
null,
259                 null);
260         String JavaDoc replaced = ((String JavaDoc) wsdl).replaceAll(LOCATION_REPLACEMENT_TOKEN, updated.toString());
261         response.getOutputStream().write(replaced.getBytes());
262         response.getOutputStream().flush();
263     }
264
265     public URI JavaDoc getLocation() {
266         return location;
267     }
268
269     protected Object JavaDoc readResolve() {
270         ClassLoader JavaDoc classLoader = Thread.currentThread().getContextClassLoader();
271         if (classLoader == null) {
272             classLoader = AxisWebServiceContainer.class.getClassLoader();
273         }
274         return new AxisWebServiceContainer(location, wsdlLocation, service, wsdlMap, classLoader);
275     }
276
277     /**
278      * print a snippet of service info.
279      * @param response response
280      * @param serviceName Name of the service
281      */

282
283     private void printServiceInfo(Response JavaDoc response,String JavaDoc serviceName) throws IOException JavaDoc{
284         response.setContentType("text/html; charset=utf-8");
285         StringBuffer JavaDoc output = new StringBuffer JavaDoc("<h1>")
286                 .append(serviceName).append("</h1>\n");
287
288         output.append("<p>").append(Messages.getMessage("axisService00"))
289                 .append("</p>\n");
290         output.append(
291                 "<i>").append(
292                 Messages.getMessage("perhaps00") ).append(
293                 "</i>\n");
294         response.getOutputStream().write(output.toString().getBytes());
295     }
296
297 }
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
Popular Tags