KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > jaxr > juddi > JUDDIServlet


1 /*
2 * JBoss, Home of Professional Open Source
3 * Copyright 2005, JBoss Inc., and individual contributors as indicated
4 * by the @authors tag. See the copyright.txt in the distribution for a
5 * full listing of individual contributors.
6 *
7 * This is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2.1 of
10 * the License, or (at your option) any later version.
11 *
12 * This software is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this software; if not, write to the Free
19 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21 */

22 package org.jboss.jaxr.juddi;
23
24 import org.apache.juddi.IRegistry;
25 import org.apache.juddi.datatype.RegistryObject;
26 import org.apache.juddi.datatype.response.DispositionReport;
27 import org.apache.juddi.datatype.response.ErrInfo;
28 import org.apache.juddi.datatype.response.Result;
29 import org.apache.juddi.error.BusyException;
30 import org.apache.juddi.error.FatalErrorException;
31 import org.apache.juddi.error.RegistryException;
32 import org.apache.juddi.error.UnsupportedException;
33 import org.apache.juddi.handler.HandlerMaker;
34 import org.apache.juddi.handler.IHandler;
35 import org.apache.juddi.registry.RegistryEngine;
36 import org.apache.juddi.registry.RegistryServlet;
37 import org.apache.juddi.util.Config;
38 import org.apache.juddi.util.xml.XMLUtils;
39 import org.jboss.logging.Logger;
40 import org.w3c.dom.Document JavaDoc;
41 import org.w3c.dom.Element JavaDoc;
42 import org.w3c.dom.NamedNodeMap JavaDoc;
43 import org.w3c.dom.Node JavaDoc;
44 import org.w3c.dom.NodeList JavaDoc;
45
46 import javax.servlet.ServletException JavaDoc;
47 import javax.servlet.http.HttpServlet JavaDoc;
48 import javax.servlet.http.HttpServletRequest JavaDoc;
49 import javax.servlet.http.HttpServletResponse JavaDoc;
50 import javax.xml.parsers.DocumentBuilder JavaDoc;
51 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
52 import javax.xml.parsers.ParserConfigurationException JavaDoc;
53 import javax.xml.soap.Detail JavaDoc;
54 import javax.xml.soap.MessageFactory JavaDoc;
55 import javax.xml.soap.Name JavaDoc;
56 import javax.xml.soap.SOAPBody JavaDoc;
57 import javax.xml.soap.SOAPBodyElement JavaDoc;
58 import javax.xml.soap.SOAPElement JavaDoc;
59 import javax.xml.soap.SOAPException JavaDoc;
60 import javax.xml.soap.SOAPFactory JavaDoc;
61 import javax.xml.soap.SOAPFault JavaDoc;
62 import javax.xml.soap.SOAPMessage JavaDoc;
63 import javax.xml.soap.SOAPPart JavaDoc;
64
65 import java.io.ByteArrayOutputStream JavaDoc;
66 import java.io.IOException JavaDoc;
67 import java.util.Vector JavaDoc;
68
69 /**
70  * Servlet that represents the JUDDI Registry
71  * Based on the JUDDI standard servlets
72  * @author <mailto:Anil.Saldhana@jboss.org>Anil Saldhana
73  * @since May 18, 2005
74  * @version $Revision: 46454 $
75  */

76 public class JUDDIServlet extends HttpServlet JavaDoc
77 {
78     /** The serialVersionUID */
79    private static final long serialVersionUID = 8768916717023791095L;
80
81    // XML Document Builder
82
private static DocumentBuilder JavaDoc docBuilder = null;
83
84     // jUDDI XML Handler maker
85
private static HandlerMaker maker = HandlerMaker.getInstance();
86
87     private static Logger log = Logger.getLogger(JUDDIServlet.class);
88
89     /**
90      *
91      */

92     public void doGet(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res)
93             throws ServletException JavaDoc, IOException JavaDoc
94     {
95         res.setHeader("Allow", "POST");
96         res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "The request " +
97                 "method 'GET' is not allowed by UDDI API.");
98     }
99
100     public void doPost(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res)
101             throws ServletException JavaDoc, IOException JavaDoc
102     {
103         res.setContentType("text/xml; charset=utf-8");
104
105         SOAPMessage JavaDoc soapReq = null;
106         SOAPMessage JavaDoc soapRes = null;
107
108         try
109         {
110             MessageFactory JavaDoc msgFactory = MessageFactory.newInstance();
111             soapReq = msgFactory.createMessage(null, req.getInputStream());
112             soapRes = msgFactory.createMessage();
113             if(log.isTraceEnabled())
114             {
115                ByteArrayOutputStream JavaDoc bs = new ByteArrayOutputStream JavaDoc();
116                soapReq.writeTo(bs);
117                log.trace("Request received::"+bs.toString());
118             }
119
120             SOAPBody JavaDoc soapReqBody = soapReq.getSOAPBody();
121             Element JavaDoc uddiReq = (Element JavaDoc) soapReqBody.getFirstChild();
122             if (uddiReq == null)
123                 throw new FatalErrorException("A UDDI request was not " +
124                         "found in the SOAP message.");
125
126             String JavaDoc function = uddiReq.getLocalName();
127             if ((function == null) || (function.trim().length() == 0))
128                 throw new FatalErrorException("The name of the UDDI request " +
129                         "could not be identified.");
130             IHandler requestHandler = maker.lookup(function);
131             if (requestHandler == null)
132                 throw new UnsupportedException("The UDDI request " +
133                         "type specified is unknown: " + function);
134
135             String JavaDoc generic = uddiReq.getAttribute("generic");
136             if (generic == null)
137                 throw new FatalErrorException("A UDDI generic attribute " +
138                         "value was not found for UDDI request: " + function + " (The " +
139                         "'generic' attribute must be present)");
140             else if (!generic.equals(IRegistry.UDDI_V2_GENERIC))
141                 throw new UnsupportedException("Currently only UDDI v2 " +
142                         "requests are supported. The generic attribute value " +
143                         "received was: " + generic);
144
145             // Unmarshal the raw xml into the appropriate jUDDI
146
// request object.
147

148             RegistryObject uddiReqObj = requestHandler.unmarshal(uddiReq);
149             if(uddiReqObj == null)
150                throw new FatalErrorException("Uddi Request is null");
151
152             // Grab a reference to the shared jUDDI registry
153
// instance (make sure it's running) and execute the
154
// requested UDDI function.
155

156             RegistryObject uddiResObj = null;
157             RegistryEngine registry = RegistryServlet.getRegistry();
158             if ((registry != null) && (registry.isAvailable()))
159                 uddiResObj = registry.execute(uddiReqObj);
160             else
161                 throw new BusyException("The Registry is currently unavailable.");
162
163             // Lookup the appropriate response handler which will
164
// be used to marshal the UDDI object into the appropriate
165
// xml format.
166

167             IHandler responseHandler = maker.lookup(uddiResObj.getClass().getName());
168             if (responseHandler == null)
169                 throw new FatalErrorException("The response object " +
170                         "type is unknown: " + uddiResObj.getClass().getName());
171
172             // Create a new 'temp' XML element to use as a container
173
// in which to marshal the UDDI response data into.
174

175             DocumentBuilder JavaDoc docBuilder = getDocumentBuilder();
176             Document JavaDoc document = docBuilder.newDocument();
177             Element JavaDoc element = document.createElement("temp");
178
179             // Lookup the appropriate response handler and marshal
180
// the juddi object into the appropriate xml format (we
181
// only support UDDI v2.0 at this time). Attach the
182
// results to the body of the SOAP response.
183

184             responseHandler.marshal(uddiResObj, element);
185             log.debug("Response that will be sent:");
186             log.debug(XMLUtils.toString((Element JavaDoc) element.getFirstChild()));
187
188             // Grab a reference to the 'temp' element's
189
// only child here (this has the effect of
190
// discarding the temp element) and append
191
// this child to the soap response body
192

193             /*document.appendChild(element.getFirstChild());
194             soapRes.getSOAPBody().addDocument(document);*/

195             Element JavaDoc el = (Element JavaDoc) element.getFirstChild();
196             soapRes = this.createSOAPMessage(el);
197         } catch (Exception JavaDoc ex) // Catch ALL exceptions
198
{
199             // SOAP Fault values
200
String JavaDoc faultCode = null;
201             String JavaDoc faultString = null;
202             String JavaDoc faultActor = null;
203
204             // UDDI DispositionReport values
205
String JavaDoc errno = null;
206             String JavaDoc errCode = null;
207             String JavaDoc errMsg = null;
208
209             if (ex instanceof RegistryException)
210             {
211
212                 log.error("RegistryException::",ex);
213
214                 RegistryException rex = (RegistryException) ex;
215
216                 faultCode = rex.getFaultCode(); // SOAP Fault faultCode
217
faultString = rex.getFaultString(); // SOAP Fault faultString
218
faultActor = rex.getFaultActor(); // SOAP Fault faultActor
219

220                 DispositionReport dispRpt = rex.getDispositionReport();
221                 if (dispRpt != null)
222                 {
223                     Result result = null;
224                     ErrInfo errInfo = null;
225
226                     Vector JavaDoc results = dispRpt.getResultVector();
227                     if ((results != null) && (!results.isEmpty()))
228                         result = (Result) results.elementAt(0);
229
230                     if (result != null)
231                     {
232                         errno = String.valueOf(result.getErrno()); // UDDI Result errno
233
errInfo = result.getErrInfo();
234
235                         if (errInfo != null)
236                         {
237                             errCode = errInfo.getErrCode(); // UDDI ErrInfo errCode
238
errMsg = errInfo.getErrMsg(); // UDDI ErrInfo errMsg
239
}
240                     }
241                 }
242             } else
243             {
244
245                 log.error(ex.getMessage(), ex);
246
247                 faultCode = "Server";
248                 faultString = ex.getMessage();
249                 faultActor = null;
250
251
252                 errno = String.valueOf(Result.E_FATAL_ERROR);
253                 errCode = Result.lookupErrCode(Result.E_FATAL_ERROR);
254                 errMsg = Result.lookupErrText(Result.E_FATAL_ERROR);
255             }
256
257             try
258             {
259                 SOAPBody JavaDoc soapResBody = soapRes.getSOAPBody();
260                 SOAPFault JavaDoc soapFault = soapResBody.addFault();
261                 if(faultCode == null)
262                    faultCode = "Unavailable";
263                 soapFault.setFaultCode(faultCode);
264                 soapFault.setFaultString(faultString);
265                 soapFault.setFaultActor(faultActor);
266
267                 Detail JavaDoc faultDetail = soapFault.addDetail();
268
269                 SOAPElement JavaDoc dispRpt = faultDetail.addChildElement("dispositionReport", "", IRegistry.UDDI_V2_NAMESPACE);
270                 dispRpt.setAttribute("generic", IRegistry.UDDI_V2_GENERIC);
271                 dispRpt.setAttribute("operator", Config.getOperator());
272
273                 SOAPElement JavaDoc result = dispRpt.addChildElement("result");
274                 result.setAttribute("errno", errno);
275
276                 SOAPElement JavaDoc errInfo = result.addChildElement("errInfo");
277                 errInfo.setAttribute("errCode", errCode);
278                 errInfo.setValue(errMsg);
279             } catch (Exception JavaDoc e)
280             { // if we end up in here it's just NOT good.
281
log.error("A serious error has occured while assembling the SOAP Fault.", e);
282             }
283         } finally
284         {
285             try
286             {
287                if(log.isTraceEnabled())
288                {
289                   ByteArrayOutputStream JavaDoc bs = new ByteArrayOutputStream JavaDoc();
290                   soapRes.writeTo(bs);
291                   log.trace("Response being sent::"+bs.toString());
292                }
293                soapRes.writeTo(res.getOutputStream());
294             } catch (SOAPException JavaDoc sex)
295             {
296                 log.error("SOAPException::",sex);
297             }
298         }
299     }
300
301     /**
302      *
303      */

304     private DocumentBuilder JavaDoc getDocumentBuilder()
305     {
306         if (docBuilder == null)
307             docBuilder = createDocumentBuilder();
308         return docBuilder;
309     }
310
311     /**
312      *
313      */

314     private synchronized DocumentBuilder JavaDoc createDocumentBuilder()
315     {
316         if (docBuilder != null)
317             return docBuilder;
318
319         try
320         {
321             DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
322             factory.setNamespaceAware(true);
323             //factory.setValidating(true);
324

325             docBuilder = factory.newDocumentBuilder();
326         } catch (ParserConfigurationException JavaDoc pcex)
327         {
328            log.error("ParserConfigurationException::",pcex);
329         }
330
331         return docBuilder;
332     }
333     
334     private SOAPMessage JavaDoc createSOAPMessage(Element JavaDoc elem) throws Exception JavaDoc
335     {
336        String JavaDoc prefix = "uddi";
337        MessageFactory JavaDoc msgFactory = MessageFactory.newInstance();
338        SOAPFactory JavaDoc factory = SOAPFactory.newInstance();
339        
340        SOAPMessage JavaDoc message = msgFactory.createMessage();
341        message.getSOAPHeader().detachNode();
342        SOAPPart JavaDoc soapPart = message.getSOAPPart();
343        SOAPBody JavaDoc soapBody = soapPart.getEnvelope().getBody();
344        //Create the outer body element
345
String JavaDoc uddins = IRegistry.UDDI_V2_NAMESPACE;
346        Name JavaDoc bodyName = factory.createName(elem.getNodeName(), prefix, uddins);
347        SOAPBodyElement JavaDoc bodyElement = soapBody.addBodyElement(bodyName);
348        bodyElement.addNamespaceDeclaration(prefix,uddins);
349        appendAttributes(bodyElement, elem.getAttributes(), factory);
350        appendElements(bodyElement,elem.getChildNodes(), factory);
351        return message;
352     }
353     
354     private void appendAttributes(SOAPElement JavaDoc bodyElement, NamedNodeMap JavaDoc nnm,
355           SOAPFactory JavaDoc factory) throws SOAPException JavaDoc
356     {
357        int len = nnm != null ? nnm.getLength() : 0;
358        for (int i = 0; i < len; i++)
359        {
360            Node JavaDoc n = nnm.item(i);
361            String JavaDoc nodename = n.getNodeName();
362            String JavaDoc nodevalue = n.getNodeValue();
363            if("xmlns".equals(nodename))
364               continue;
365            //Special case: xml:lang
366
if("xml:lang".equals(nodename))
367            {
368               Name JavaDoc xmlLang = factory.createName("lang","xml",
369                     "http://www.w3.org/TR/REC-xml/");
370               bodyElement.addAttribute(xmlLang, nodevalue);
371            }
372            else
373                bodyElement.addAttribute(factory.createName(nodename), nodevalue);
374        }
375     }
376     
377     private void appendElements(SOAPElement JavaDoc bodyElement, NodeList JavaDoc nlist,
378           SOAPFactory JavaDoc factory)
379     throws SOAPException JavaDoc
380     {
381        String JavaDoc prefix = "uddi";
382        String JavaDoc uddins = IRegistry.UDDI_V2_NAMESPACE;
383        int len = nlist != null ? nlist.getLength() : 0;
384
385        for (int i = 0; i < len; i++)
386        {
387            Node JavaDoc node = nlist.item(i);
388            short nodeType = node != null ? node.getNodeType() : -100;
389            if (Node.ELEMENT_NODE == nodeType)
390            {
391               Element JavaDoc el = (Element JavaDoc)node;
392               Name JavaDoc name = factory.createName(el.getNodeName(), prefix,uddins);
393               SOAPElement JavaDoc attachedEl = bodyElement.addChildElement(name);
394               appendAttributes(attachedEl, el.getAttributes(), factory);
395               appendElements(attachedEl, el.getChildNodes(), factory);
396            } else if (nodeType == Node.TEXT_NODE)
397            {
398                bodyElement.addTextNode(node.getNodeValue());
399            }
400        }
401     }
402 }
403
Popular Tags