1 #!/usr/bin/env python 2 3 """ 4 Java Servlet adapter. 5 6 Copyright (C) 2004, 2005 Paul Boddie <paul@boddie.org.uk> 7 8 This library is free software; you can redistribute it and/or 9 modify it under the terms of the GNU Lesser General Public 10 License as published by the Free Software Foundation; either 11 version 2.1 of the License, or (at your option) any later version. 12 13 This library is distributed in the hope that it will be useful, 14 but WITHOUT ANY WARRANTY; without even the implied warranty of 15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 Lesser General Public License for more details. 17 18 You should have received a copy of the GNU Lesser General Public 19 License along with this library; if not, write to the Free Software 20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA 21 """ 22 23 import WebStack.JavaServlet 24 from WebStack.Generic import EndOfResponse 25 26 class Dispatcher: 27 28 "A servlet helper class dispatching requests to WebStack resources." 29 30 def __init__(self, resource, authenticator=None, handle_errors=1): 31 32 """ 33 Initialise the root application-specific 'resource' and optional 34 'authenticator'. The optional 'handle_errors' parameter (if true) 35 causes handlers to deal with uncaught exceptions cleanly. 36 """ 37 38 self.webstack_resource = resource 39 self.webstack_authenticator = authenticator 40 self.handle_errors = handle_errors 41 42 def service(self, request, response): 43 44 """ 45 Handle the 'request' and 'response' presented by the servlet. 46 """ 47 48 trans = WebStack.JavaServlet.Transaction(request, response) 49 try: 50 if self.webstack_authenticator is None or self.webstack_authenticator.authenticate(trans): 51 try: 52 self.webstack_resource.respond(trans) 53 except EndOfResponse: 54 pass 55 except: 56 if self.handle_errors: 57 trans.set_response_code(500) # Internal error 58 else: 59 raise 60 else: 61 trans.set_response_code(401) # Unauthorized 62 #trans.set_header_value("WWW-Authenticate", '%s realm="%s"' % ( 63 # self.webstack_authenticator.get_auth_type(), self.webstack_authenticator.get_realm())) 64 65 finally: 66 trans.commit() 67 68 # vim: tabstop=4 expandtab shiftwidth=4