KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > webapp > event > SOAPEventHandler


1 /*
2  * $Id: SOAPEventHandler.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2001-2003 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */

25 package org.ofbiz.webapp.event;
26
27 import java.io.IOException JavaDoc;
28 import java.io.Writer JavaDoc;
29 import java.io.OutputStream JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.Set JavaDoc;
35 import javax.servlet.http.HttpServletRequest JavaDoc;
36 import javax.servlet.http.HttpServletResponse JavaDoc;
37 import javax.servlet.ServletContext JavaDoc;
38 import javax.xml.soap.SOAPException JavaDoc;
39 import javax.wsdl.WSDLException;
40
41 import org.ofbiz.base.util.Debug;
42 import org.ofbiz.base.util.UtilMisc;
43 import org.ofbiz.base.util.UtilXml;
44 import org.ofbiz.service.GenericServiceException;
45 import org.ofbiz.service.LocalDispatcher;
46 import org.ofbiz.service.ModelService;
47 import org.ofbiz.service.DispatchContext;
48 import org.ofbiz.webapp.control.RequestHandler;
49
50 import org.apache.axis.AxisFault;
51 import org.apache.axis.Constants;
52 import org.apache.axis.Message;
53 import org.apache.axis.MessageContext;
54 import org.apache.axis.message.RPCElement;
55 import org.apache.axis.message.RPCParam;
56 import org.apache.axis.message.SOAPEnvelope;
57 import org.apache.axis.server.AxisServer;
58 import org.apache.log4j.Category;
59 import org.w3c.dom.Document JavaDoc;
60
61 /**
62  * SOAPEventHandler - SOAP Event Handler implementation
63  *
64  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
65  * @author <a HREF="mailto:">Andy Chen</a>
66  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
67  * @version $Rev: 5462 $
68  * @since 2.0
69  */

70 public class SOAPEventHandler implements EventHandler {
71
72     public static final String JavaDoc module = SOAPEventHandler.class.getName();
73     public static Category category = Category.getInstance(SOAPEventHandler.class.getName());
74
75     /**
76      * @see org.ofbiz.webapp.event.EventHandler#init(javax.servlet.ServletContext)
77      */

78     public void init(ServletContext JavaDoc context) throws EventHandlerException {
79     }
80     
81     /** Invoke the web event
82      *@param eventPath The path or location of this event
83      *@param eventMethod The method to invoke
84      *@param request The servlet request object
85      *@param response The servlet response object
86      *@return String Result code
87      *@throws EventHandlerException
88      */

89     public String JavaDoc invoke(String JavaDoc eventPath, String JavaDoc eventMethod, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws EventHandlerException {
90         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
91         AxisServer axisServer;
92
93         // first check for WSDL request
94
String JavaDoc wsdlReq = request.getParameter("wsdl");
95         if (wsdlReq == null) {
96             wsdlReq = request.getParameter("WSDL");
97         }
98         if (wsdlReq != null) {
99             String JavaDoc serviceName = RequestHandler.getNextPageUri(request.getPathInfo());
100             DispatchContext dctx = dispatcher.getDispatchContext();
101             String JavaDoc locationUri = this.getLocationURI(request);
102
103             if (serviceName != null) {
104                 Document JavaDoc wsdl = null;
105                 try {
106                     wsdl = dctx.getWSDL(serviceName, locationUri);
107                 } catch (GenericServiceException e) {
108                     serviceName = null;
109                 } catch (WSDLException e) {
110                     sendError(response, "Unable to obtain WSDL");
111                     throw new EventHandlerException("Unable to obtain WSDL", e);
112                 }
113
114                 if (wsdl != null) {
115                     try {
116                         OutputStream JavaDoc os = response.getOutputStream();
117                         response.setContentType("text/xml");
118                         UtilXml.writeXmlDocument(os, wsdl);
119                         response.flushBuffer();
120                     } catch (IOException JavaDoc e) {
121                         throw new EventHandlerException(e);
122                     }
123                     return null;
124                 } else {
125                     sendError(response, "Unable to obtain WSDL");
126                     throw new EventHandlerException("Unable to obtain WSDL");
127                 }
128             }
129
130             if (serviceName == null) {
131                 try {
132                     Writer JavaDoc writer = response.getWriter();
133                     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
134                     sb.append("<html><head><title>OFBiz SOAP/1.1 Services</title></head>");
135                     sb.append("<body>No such service.").append("<p>Services:<ul>");
136
137                     Iterator JavaDoc i = dctx.getAllServiceNames().iterator();
138                     while (i.hasNext()) {
139                         String JavaDoc scvName = (String JavaDoc) i.next();
140                         ModelService model = dctx.getModelService(scvName);
141                         if (model.export) {
142                             sb.append("<li><a HREF=\"").append(locationUri).append("/").append(model.name).append("?wsdl\">");
143                             sb.append(model.name).append("</a></li>");
144                         }
145                     }
146                     sb.append("</ul></p></body></html>");
147
148                     writer.write(sb.toString());
149                     writer.flush();
150                     return null;
151                 } catch (Exception JavaDoc e) {
152                     sendError(response, "Unable to obtain WSDL");
153                     throw new EventHandlerException("Unable to obtain WSDL");
154                 }
155             }
156         }
157
158         // not a wsdl request; invoke the service
159
try {
160             axisServer = AxisServer.getServer(UtilMisc.toMap("name", "OFBiz/Axis Server", "provider", null));
161         } catch (AxisFault e) {
162             sendError(response, e);
163             throw new EventHandlerException("Problems with the AXIS server", e);
164         }
165         MessageContext mctx = new MessageContext(axisServer);
166
167         // get the SOAP message
168
Message msg = null;
169
170         try {
171             msg = new Message(request.getInputStream(), false,
172                         request.getHeader("Content-Type"), request.getHeader("Content-Location"));
173         } catch (IOException JavaDoc ioe) {
174             sendError(response, "Problem processing the service");
175             throw new EventHandlerException("Cannot read the input stream", ioe);
176         }
177
178         if (msg == null) {
179             sendError(response, "No message");
180             throw new EventHandlerException("SOAP Message is null");
181         }
182
183         mctx.setRequestMessage(msg);
184
185         // new envelopes
186
SOAPEnvelope resEnv = new SOAPEnvelope();
187         SOAPEnvelope reqEnv = null;
188
189         // get the service name and parameters
190
try {
191             reqEnv = (SOAPEnvelope) msg.getSOAPPart().getEnvelope();
192         } catch (SOAPException JavaDoc e) {
193             sendError(response, "Problem processing the service");
194             throw new EventHandlerException("Cannot get the envelope", e);
195         }
196         
197         List JavaDoc bodies = null;
198
199         try {
200             bodies = reqEnv.getBodyElements();
201         } catch (AxisFault e) {
202             sendError(response, e);
203             throw new EventHandlerException(e.getMessage(), e);
204         }
205
206         Debug.logVerbose("[Processing]: SOAP Event", module);
207
208         // each is a different service call
209
Iterator JavaDoc i = bodies.iterator();
210
211         while (i.hasNext()) {
212             Object JavaDoc o = i.next();
213
214             if (o instanceof RPCElement) {
215                 RPCElement body = (RPCElement) o;
216                 String JavaDoc serviceName = body.getMethodName();
217                 List JavaDoc params = null;
218
219                 try {
220                     params = body.getParams();
221                 } catch (Exception JavaDoc e) {
222                     sendError(response, e);
223                     throw new EventHandlerException(e.getMessage(), e);
224                 }
225                 Map JavaDoc serviceContext = new HashMap JavaDoc();
226                 Iterator JavaDoc p = params.iterator();
227
228                 while (p.hasNext()) {
229                     RPCParam param = (RPCParam) p.next();
230
231                     if (Debug.verboseOn()) Debug.logVerbose("[Reading Param]: " + param.getName(), module);
232                     serviceContext.put(param.getName(), param.getObjectValue());
233                 }
234                 try {
235                     // verify the service is exported for remote execution and invoke it
236
ModelService model = dispatcher.getDispatchContext().getModelService(serviceName);
237
238                     if (model != null && model.export) {
239                         Map JavaDoc result = dispatcher.runSync(serviceName, serviceContext);
240
241                         Debug.logVerbose("[EventHandler] : Service invoked", module);
242                         RPCElement resBody = new RPCElement(serviceName + "Response");
243
244                         resBody.setPrefix(body.getPrefix());
245                         resBody.setNamespaceURI(body.getNamespaceURI());
246                         Set JavaDoc keySet = result.keySet();
247                         Iterator JavaDoc ri = keySet.iterator();
248
249                         while (ri.hasNext()) {
250                             Object JavaDoc key = ri.next();
251                             RPCParam par = new RPCParam(((String JavaDoc) key), result.get(key));
252
253                             resBody.addParam(par);
254                         }
255                         resEnv.addBodyElement(resBody);
256                         resEnv.setEncodingStyle(Constants.URI_LITERAL_ENC);
257                     } else {
258                         sendError(response, "Requested service not available");
259                         throw new EventHandlerException("Service is not exported");
260                     }
261                 } catch (GenericServiceException e) {
262                     sendError(response, "Problem processing the service");
263                     throw new EventHandlerException(e.getMessage(), e);
264                 } catch (javax.xml.soap.SOAPException JavaDoc e) {
265                     sendError(response, "Problem processing the service");
266                     throw new EventHandlerException(e.getMessage(), e);
267                 }
268             }
269         }
270
271         // setup the response
272
Debug.logVerbose("[EventHandler] : Setting up response message", module);
273         msg = new Message(resEnv);
274         mctx.setResponseMessage(msg);
275         if (msg == null) {
276             sendError(response, "No response message available");
277             throw new EventHandlerException("No response message available");
278         }
279
280         try {
281             response.setContentType(msg.getContentType(Constants.DEFAULT_SOAP_VERSION));
282             response.setContentLength(Integer.parseInt(Long.toString(msg.getContentLength())));
283         } catch (AxisFault e) {
284             sendError(response, e);
285             throw new EventHandlerException(e.getMessage(), e);
286         }
287
288         try {
289             msg.writeTo(response.getOutputStream());
290             response.flushBuffer();
291         } catch (IOException JavaDoc e) {
292             throw new EventHandlerException("Cannot write to the output stream");
293         } catch (SOAPException JavaDoc e) {
294             throw new EventHandlerException("Cannot write message to the output stream");
295         }
296
297         Debug.logVerbose("[EventHandler] : Message sent to requester", module);
298
299         return null;
300     }
301
302     private void sendError(HttpServletResponse JavaDoc res, Object JavaDoc obj) throws EventHandlerException {
303         Message msg = new Message(obj);
304
305         try {
306             res.setContentType(msg.getContentType(Constants.DEFAULT_SOAP_VERSION));
307             res.setContentLength(Integer.parseInt(Long.toString(msg.getContentLength())));
308             msg.writeTo(res.getOutputStream());
309             res.flushBuffer();
310         } catch (Exception JavaDoc e) {
311             throw new EventHandlerException(e.getMessage(), e);
312         }
313     }
314
315     private String JavaDoc getLocationURI(HttpServletRequest JavaDoc request) {
316         StringBuffer JavaDoc uri = new StringBuffer JavaDoc();
317         uri.append(request.getScheme());
318         uri.append("://");
319         uri.append(request.getServerName());
320         if (request.getServerPort() != 80 && request.getServerPort() != 443) {
321             uri.append(":");
322             uri.append(request.getServerPort());
323         }
324         uri.append(request.getContextPath());
325         uri.append(request.getServletPath());
326
327         String JavaDoc reqInfo = RequestHandler.getRequestUri(request.getPathInfo());
328         if (!reqInfo.startsWith("/")) {
329             reqInfo = "/" + reqInfo;
330         }
331
332         uri.append(reqInfo);
333         return uri.toString();
334     }
335 }
336
Popular Tags