KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > juddi > registry > AbstractService


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

16 package org.apache.juddi.registry;
17
18 import java.io.IOException JavaDoc;
19 import java.util.Vector JavaDoc;
20
21 import javax.servlet.ServletException JavaDoc;
22 import javax.servlet.http.HttpServlet JavaDoc;
23 import javax.servlet.http.HttpServletRequest JavaDoc;
24 import javax.servlet.http.HttpServletResponse JavaDoc;
25 import javax.xml.parsers.DocumentBuilder JavaDoc;
26 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
27 import javax.xml.parsers.ParserConfigurationException JavaDoc;
28 import javax.xml.soap.Detail JavaDoc;
29 import javax.xml.soap.MessageFactory JavaDoc;
30 import javax.xml.soap.SOAPBody JavaDoc;
31 import javax.xml.soap.SOAPElement JavaDoc;
32 import javax.xml.soap.SOAPException JavaDoc;
33 import javax.xml.soap.SOAPFault JavaDoc;
34 import javax.xml.soap.SOAPMessage JavaDoc;
35
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38 import org.apache.juddi.IRegistry;
39 import org.apache.juddi.datatype.RegistryObject;
40 import org.apache.juddi.datatype.response.DispositionReport;
41 import org.apache.juddi.datatype.response.ErrInfo;
42 import org.apache.juddi.datatype.response.Result;
43 import org.apache.juddi.error.BusyException;
44 import org.apache.juddi.error.FatalErrorException;
45 import org.apache.juddi.error.RegistryException;
46 import org.apache.juddi.error.UnsupportedException;
47 import org.apache.juddi.handler.HandlerMaker;
48 import org.apache.juddi.handler.IHandler;
49 import org.apache.juddi.util.Config;
50 import org.w3c.dom.Document JavaDoc;
51 import org.w3c.dom.Element JavaDoc;
52
53 /**
54  * @author Steve Viens (sviens@apache.org)
55  */

56 public abstract class AbstractService extends HttpServlet JavaDoc
57 {
58   // private reference to the webapp's logger.
59
private static Log log = LogFactory.getLog(AbstractService.class);
60   
61   // XML Document Builder
62
private static DocumentBuilder JavaDoc docBuilder = null;
63
64   /**
65    *
66    */

67   public void doGet(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res)
68     throws ServletException JavaDoc, IOException JavaDoc
69   {
70     res.setHeader("Allow","POST");
71     res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED,"Use of the " +
72       "HTTP request method 'GET' is not allowed by UDDI specification.");
73   }
74
75   /**
76    *
77    */

78   public void doPost(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res)
79     throws ServletException JavaDoc, IOException JavaDoc
80   {
81     res.setContentType("text/xml; charset=utf-8");
82
83     SOAPMessage JavaDoc soapReq = null;
84     SOAPMessage JavaDoc soapRes = null;
85
86     try
87     {
88       // Create a MessageFactory, parse the XML found
89
// in the HTTP payload into a SOAP request message
90
// and create a new SOAP response message.
91

92       MessageFactory JavaDoc msgFactory = MessageFactory.newInstance();
93       soapReq = msgFactory.createMessage(null,req.getInputStream());
94       soapRes = msgFactory.createMessage();
95            
96       // Extract the UDDI request from the SOAPBody
97
// of the SOAP Request message. If a UDDI request
98
// message does not exist within the SOAP Body
99
// then throw a FatalErrorException and indicate
100
// that this is a Client-side (consumer) error.
101

102       SOAPBody JavaDoc soapReqBody = soapReq.getSOAPBody();
103       Element JavaDoc uddiReq = (Element JavaDoc)soapReqBody.getFirstChild();
104       if (uddiReq == null)
105         throw new FatalErrorException("A UDDI request was not " +
106           "found in the SOAP message.");
107       
108       // Grab the local name of the UDDI request element
109
// from the UDDI Request. If a value isn't returned
110
// (either null or an empty String is returned) then
111
// throw a FatalError exception. This is probably a
112
// configuration problem related to the XML Parser
113
// that jUDDI is using.
114

115       String JavaDoc operation = uddiReq.getLocalName();
116       if ((operation == null) || (operation.trim().length() == 0))
117         throw new FatalErrorException("The UDDI service operation " +
118           "could not be identified.");
119       
120       // Grab the generic attribute value (version value). If
121
// one isn't specified or the value specified is not "2.0"
122
// then throw an exception (this value must be specified
123
// for all UDDI requests and currently only vesion 2.0
124
// UDDI requests are supported).
125

126       String JavaDoc version = uddiReq.getAttribute("generic");
127       if (version == null)
128         throw new FatalErrorException("A UDDI generic attribute " +
129           "value was not found for UDDI request: "+operation+" (The " +
130           "'generic' attribute must be present)");
131
132       // Verify that the appropriate endpoint was targeted for
133
// this service request. The validateRequest method will
134
// throw an UnsupportedException if anything's amiss.
135

136       validateRequest(operation,version,uddiReq);
137       
138       // Lookup the appropriate XML handler. Throw an
139
// UnsupportedException if one could not be located.
140

141       HandlerMaker maker = HandlerMaker.getInstance();
142             IHandler requestHandler = maker.lookup(operation);
143       if (requestHandler == null)
144         throw new UnsupportedException("The UDDI service operation " +
145           "specified is unknown or unsupported: " +operation);
146       
147       // Unmarshal the raw xml into the appropriate jUDDI
148
// request object.
149

150       RegistryObject uddiReqObj = requestHandler.unmarshal(uddiReq);
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       
186       // Grab a reference to the 'temp' element's
187
// only child here (this has the effect of
188
// discarding the temp element) and append
189
// this child to the soap response body
190

191       document.appendChild(element.getFirstChild());
192       soapRes.getSOAPBody().addDocument(document);
193     }
194     catch(Exception JavaDoc ex) // Catch ALL exceptions
195
{
196       // SOAP Fault values
197
String JavaDoc faultCode = null;
198       String JavaDoc faultString = null;
199       String JavaDoc faultActor = null;
200       
201       // UDDI DispositionReport values
202
String JavaDoc errno = null;
203       String JavaDoc errCode = null;
204       String JavaDoc errText = null;
205       
206       // All RegistryException and subclasses of RegistryException
207
// should contain values for populating a SOAP Fault as well
208
// as a UDDI DispositionReport with specific information
209
// about the problem.
210
//
211
// We've got to dig out the dispositionReport and populate
212
// the SOAP Fault 'detail' element with this information.
213

214       if (ex instanceof RegistryException)
215       {
216         // Since we've intercepted a RegistryException type
217
// then we can assume this is a "controlled" event
218
// and simply log the error message without a stack
219
// trace.
220

221         log.error(ex.getMessage());
222
223         RegistryException rex = (RegistryException)ex;
224         
225         faultCode = rex.getFaultCode(); // SOAP Fault faultCode
226
faultString = rex.getFaultString(); // SOAP Fault faultString
227
faultActor = rex.getFaultActor(); // SOAP Fault faultActor
228

229         DispositionReport dispRpt = rex.getDispositionReport();
230         if (dispRpt != null)
231         {
232           Result result = null;
233           ErrInfo errInfo = null;
234         
235           Vector JavaDoc results = dispRpt.getResultVector();
236           if ((results != null) && (!results.isEmpty()))
237             result = (Result)results.elementAt(0);
238         
239           if (result != null)
240           {
241             errno = String.valueOf(result.getErrno()); // UDDI Result errno
242
errInfo = result.getErrInfo();
243           
244             if (errInfo != null)
245             {
246               errCode = errInfo.getErrCode(); // UDDI ErrInfo errCode
247
errText = errInfo.getErrMsg(); // UDDI ErrInfo errMsg
248
}
249           }
250         }
251       }
252       else if (ex instanceof SOAPException JavaDoc)
253       {
254         log.error(ex.getMessage());
255           
256         // Because something occured that jUDDI wasn't expecting
257
// let's set default SOAP Fault values. Since SOAPExceptions
258
// here are most likely XML validation errors let's blame the
259
// client by placing "Client" in the Fault Code and pass
260
// the Exception message back to the client.
261

262         faultCode = "Client";
263         faultString = ex.getMessage();
264         faultActor = null;
265         
266         // Let's set default values for the UDDI DispositionReport
267
// here. While we didn't catch a RegistryException (or
268
// subclass) we're going to be friendly and include a
269
// FatalError DispositionReport within the message from the
270
// SAX parsing problem in the SOAP Fault anyway.
271

272         errno = String.valueOf(Result.E_FATAL_ERROR);
273         errCode = Result.lookupErrCode(Result.E_FATAL_ERROR);
274         errText = Result.lookupErrText(Result.E_FATAL_ERROR) +
275                   " " + ex.getMessage();
276       }
277       else // anything else
278
{
279         // All other exceptions (other than SOAPException or
280
// RegistryException and subclasses) are either a result
281
// of a jUDDI configuration problem or something that
282
// we *should* be catching and converting to a
283
// RegistryException but are not (yet!).
284

285         log.error(ex.getMessage(),ex);
286
287         // Because something occured that jUDDI wasn't expecting
288
// let's set default SOAP Fault values. Since jUDDI
289
// should be catching anything significant let's blame
290
// jUDDI by placing "Server" in the Fault Code and pass
291
// the Exception message on to the client.
292

293         faultCode = "Server";
294         faultString = ex.getMessage();
295         faultActor = null;
296           
297         // Let's set default values for the UDDI DispositionReport
298
// here. While we didn't catch a RegistryException (or
299
// subclass) but we're going to be friendly and include a
300
// FatalError DispositionReport within the SOAP Fault anyway.
301

302         errno = String.valueOf(Result.E_FATAL_ERROR);
303         errCode = Result.lookupErrCode(Result.E_FATAL_ERROR);
304         errText = Result.lookupErrText(Result.E_FATAL_ERROR) +
305                   " An internal UDDI server error has " +
306                   "occurred. Please report this error " +
307                   "to the UDDI server administrator.";
308       }
309       
310       // We should have everything we need to assemble
311
// the SOAPFault so lets piece it together and
312
// send it on it's way.
313

314       try {
315         SOAPBody JavaDoc soapResBody = soapRes.getSOAPBody();
316         SOAPFault JavaDoc soapFault = soapResBody.addFault();
317         soapFault.setFaultCode(faultCode);
318         soapFault.setFaultString(faultString);
319         soapFault.setFaultActor(faultActor);
320         
321         // We're always going to include a DispositionReport (for
322
// the hell of it) so that's what we're doing here.
323

324         Detail JavaDoc faultDetail = soapFault.addDetail();
325         
326         SOAPElement JavaDoc dispRpt = faultDetail.addChildElement("dispositionReport","",IRegistry.UDDI_V2_NAMESPACE);
327         dispRpt.setAttribute("generic",IRegistry.UDDI_V2_GENERIC);
328         dispRpt.setAttribute("operator",Config.getOperator());
329         
330         SOAPElement JavaDoc result = dispRpt.addChildElement("result");
331         result.setAttribute("errno",errno);
332         
333         SOAPElement JavaDoc errInfo = result.addChildElement("errInfo");
334         errInfo.setAttribute("errCode",errCode);
335         errInfo.setValue(errText);
336       }
337       catch (Exception JavaDoc e) { // if we end up in here it's just NOT good.
338
log.error("A serious error has occured while assembling the SOAP Fault.",e);
339       }
340     }
341     finally
342     {
343       try {
344         soapRes.setProperty(SOAPMessage.WRITE_XML_DECLARATION,"true");
345         soapRes.writeTo(res.getOutputStream());
346       }
347       catch(SOAPException JavaDoc sex) {
348         log.error(sex);
349       }
350     }
351   }
352
353   /**
354    *
355    */

356   public abstract void validateRequest(String JavaDoc operation,String JavaDoc generic,Element JavaDoc uddiReq)
357     throws RegistryException;
358   
359   /**
360    *
361    */

362   private DocumentBuilder JavaDoc getDocumentBuilder()
363   {
364     if (docBuilder == null)
365       docBuilder = createDocumentBuilder();
366     return docBuilder;
367   }
368
369   /**
370    *
371    */

372   private synchronized DocumentBuilder JavaDoc createDocumentBuilder()
373   {
374     if (docBuilder != null)
375       return docBuilder;
376
377     try {
378      DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
379      //factory.setNamespaceAware(true);
380
//factory.setValidating(true);
381

382      docBuilder = factory.newDocumentBuilder();
383     }
384     catch(ParserConfigurationException JavaDoc pcex) {
385       pcex.printStackTrace();
386     }
387
388     return docBuilder;
389   }
390 }
Popular Tags