Ejemplo n.º 1
0
 def handle_request(self, request):
     update_pdo = False
     response = Response(request)
     request_data = request.get_post_data_as_dictionary()
     request_data.update(request.get_query_string_as_dictionary())
     if request_data.has_key('add'):
         name = self.create_trigger()
         adapt = self.manager.get_trigger(name)
     elif request_data.has_key('remove'):
         name = urllib.unquote_plus(request_data['remove'][0])
         self.remove_trigger(name)
         adapt = self.manager
     elif request_data.has_key('edit'):
         name = urllib.unquote_plus(request_data['edit'][0])
         adapt = self.manager.get_trigger(name)
     elif request_data.has_key('configure'):
         name = urllib.unquote_plus(request_data['configure'][0])
         trigger = self.manager.get_trigger(name)
         config = {}
         for attrname in request_data.keys():
             splitname = attrname.split('.')
             if len(splitname) == 2 and splitname[0] == 'configure':
                 value = urllib.unquote_plus(request_data[attrname][0])
                 config[splitname[1]] = value
         name = self.configure_trigger(config)
         adapt = self.manager.get_trigger(name)
     else:
         adapt = self.manager
     if request_data.has_key('actionName'):
         action_target = urllib.unquote_plus(request_data.get('target')[0])
         action = urllib.unquote_plus(request_data.get('actionName')[0])
         params = map(urllib.unquote_plus, request_data.get('params'))
         self.invoke(action_target, action, *params)
     webadapter = IWebContent(adapt)
     response.send(webadapter.render())
Ejemplo n.º 2
0
 def handle_request(self, request):
     request_data = request.get_post_data_as_dictionary()
     request_data.update(request.get_query_string_as_dictionary())
     requesturi = request.get_path()
     nodeuri = requesturi[len(self.path):]
     if '%' in nodeuri:
         nodeuri = urllib.unquote(nodeuri)
     response = Response(request)
     if request_data:
         node = self.nodespace.as_node(nodeuri)
         generator = IBroadways(node)
         if request_data.has_key('dumps'):
             return response.send(generator.dumps())
         elif request_data.has_key('loads'):
             snippet = urllib.unquote(request_data['snippet'][0])
             generator.loads(snippet)
     document = HTMLgen.SimpleDocument()
     dumpform = HTMLgen.Form(requesturi)
     dumpform.submit.name = 'dumps'
     dumpform.submit.value = 'Get configuration'
     loadform = HTMLgen.Form(requesturi)
     loadinput = HTMLgen.Textarea('', name='snippet')
     loadform.append(loadinput)
     loadform.submit.name = 'loads'
     loadform.submit.value = 'Load configuration'
     document.append(dumpform)
     document.append(loadform)
     return response.send(str(document))
Ejemplo n.º 3
0
 def handle_request(self, request):
     update_pdo = False
     response = Response(request)
     request_data = request.get_post_data_as_dictionary()
     request_data.update(request.get_query_string_as_dictionary())
     if request_data.has_key('add'):
         name = self.create_trigger()
         adapt = self.manager.get_trigger(name)
     elif request_data.has_key('remove'):
         name = urllib.unquote_plus(request_data['remove'][0])
         self.remove_trigger(name)
         adapt = self.manager
     elif request_data.has_key('edit'):
         name = urllib.unquote_plus(request_data['edit'][0])
         adapt = self.manager.get_trigger(name)
     elif request_data.has_key('configure'):
         name = urllib.unquote_plus(request_data['configure'][0])
         trigger = self.manager.get_trigger(name)
         config = {}
         for attrname in request_data.keys():
             splitname = attrname.split('.')
             if len(splitname) == 2 and splitname[0] == 'configure':
                 value = urllib.unquote_plus(request_data[attrname][0])
                 config[splitname[1]] = value
         name = self.configure_trigger(config)
         adapt = self.manager.get_trigger(name)
     else: 
         adapt = self.manager
     if request_data.has_key('actionName'):
         action_target = urllib.unquote_plus(request_data.get('target')[0])
         action = urllib.unquote_plus(request_data.get('actionName')[0])
         params = map(urllib.unquote_plus, request_data.get('params'))
         self.invoke(action_target, action, *params)
     webadapter = IWebContent(adapt)
     response.send(webadapter.render())
Ejemplo n.º 4
0
 def download_backup(self, request, file):
     response = Response(request)
     response.set_header('Content-Type', 'application/octet-stream')
     response.set_header('Content-Disposition',
                         'attachment; filename="%s.tgz"' % file.f_name)
     response.push(FileProducer(file))
     response.done()
     return
Ejemplo n.º 5
0
 def handle_request(self, request):
     response = Response(request)
     try:
         h = self.find_handler(request)
         h.handle(request)
     except Exception,e:
         msglog.exception()
         response.send_error(500)
Ejemplo n.º 6
0
 def handle_request(self, request):
     response = Response(request)
     request_data = request.get_post_data_as_dictionary()
     request_data.update(request.get_query_string_as_dictionary())
     adapt = self.__handle_by_context(
        request_data.get('manage', ['/services/Value Drivers'])[0], request, request_data)
     webadapter = IWebContent(adapt)
     response.send(webadapter.render(self.path))
Ejemplo n.º 7
0
 def handle_request(self, request):
     response = Response(request)
     try:
         h = self.find_handler(request)
         h.handle(request)
     except Exception, e:
         msglog.exception()
         response.send_error(500)
Ejemplo n.º 8
0
 def handle_request(self, request):
     response = Response(request)
     request_data = request.get_post_data_as_dictionary()
     request_data.update(request.get_query_string_as_dictionary())
     adapt = self.__handle_by_context(
         request_data.get('manage', ['/services/Value Drivers'])[0],
         request, request_data)
     webadapter = IWebContent(adapt)
     response.send(webadapter.render(self.path))
Ejemplo n.º 9
0
 def handle_request(self, request):
     user = request.user_object()
     response = Response(request)
     node = self.get_node(request.get_path())
     try:
         domnode = IDomNode(node)
         webnode = IWebContent(domnode)
     except ComponentLookupError, error:
         response['Content-Type'] = 'text/plain'
         response.send_error(404, 'No adapter for requested node.')
Ejemplo n.º 10
0
 def handle(self,request):
     x = 10
     qd = request.get_query_dictionary()
     if qd.has_key('num'):
         x = int(qd['num'])
     
     response = Response(request)
     response.send('<html><body>Generating error</body></html>')
     for index in range(0,x):
         msglog.log('msglog',msglog.types.DB,'logging error: ' + str(index + 1))
Ejemplo n.º 11
0
 def handle_request(self, request):
     user = request.user_object()
     response = Response(request)
     node = self.get_node(request.get_path())
     try:
         domnode = IDomNode(node)
         webnode = IWebContent(domnode)
     except ComponentLookupError, error:
         response['Content-Type'] = 'text/plain'
         response.send_error(404, 'No adapter for requested node.')
Ejemplo n.º 12
0
    def handle(self, request):
        x = 10
        qd = request.get_query_dictionary()
        if qd.has_key('num'):
            x = int(qd['num'])

        response = Response(request)
        response.send('<html><body>Generating error</body></html>')
        for index in range(0, x):
            msglog.log('msglog', msglog.types.DB,
                       'logging error: ' + str(index + 1))
Ejemplo n.º 13
0
 def handle_request(self, request):
     response = Response(request)
     postdata = request.get_data().read_all()
     self.logdata(postdata)
     if self.delay:
         time.sleep(self.delay)
     if self.echo:
         responsedata = postdata
     else:
         responsedata = 'Read: %s bytes of content.' % len(postdata)
     response.send(html % responsedata)
Ejemplo n.º 14
0
 def handle_request(self, request):
     response = Response(request)
     postdata = request.get_data().read_all()
     self.logdata(postdata)
     if self.delay:
         time.sleep(self.delay)
     if self.echo:
         responsedata = postdata
     else:
         responsedata = 'Read: %s bytes of content.' % len(postdata)
     response.send(html % responsedata)
Ejemplo n.º 15
0
 def handle_request(self, request):
     path = request.get_path().split('/')
     # if there is a child to call, should be the
     # 3rd element path
     if len(path) < 3:
         fault_xml = xmlrpclib.dumps(xmlrpclib.Fault(1, "Invalid URL Path"))
         response = Response(request)
         response.send(fault_xml)
     else:
         c = path[2]
         handler = self.get_child(c)
         handler.handle_request(request)
Ejemplo n.º 16
0
 def download_backup(self, request, file):
     response = Response(request)
     response.set_header('Content-Type','application/octet-stream')
     response.set_header('Content-Disposition',
                         'attachment; filename="%s.tgz"' %
                          file.f_name)
     response.push(FileProducer(file))
     response.done()
     return
Ejemplo n.º 17
0
 def handle_request(self, request):
     response = Response(request)
     data = request.get_post_data_as_dictionary()
     data.update(request.get_query_string_as_dictionary())
     if data.has_key("node"):
         nodeurl = urllib.unquote_plus(data["node"][0])
     else:
         nodeurl = "/services/time/local"
     try:
         adapt = self.__handle_by_context(nodeurl, request, data)
     except TypeError, error:
         msglog.exception(prefix="handled")
         response.send_error(500, str(error))
Ejemplo n.º 18
0
 def handle_request(self, request):
     response = Response(request)
     data = request.get_post_data_as_dictionary()
     data.update(request.get_query_string_as_dictionary())
     if data.has_key("node"):
         nodeurl = urllib.unquote_plus(data["node"][0])
     else:
         nodeurl = "/services/time/local"
     try:
         adapt = self.__handle_by_context(nodeurl, request, data)
     except TypeError, error:
         msglog.exception(prefix="handled")
         response.send_error(500, str(error))
Ejemplo n.º 19
0
 def handle_request(self, request):
     response = Response(request)
     request_data = request.get_post_data_as_dictionary()
     request_data.update(request.get_query_string_as_dictionary())
     if not (request_data.has_key('type') and request_data.has_key('id')
             and request_data.has_key('method')):
         response.error(400, 'Missnig required param type, id, or method.')
         return
     id = urllib.unquote_plus(request_data.get('id')[0])
     if request_data.get('type')[0] == 'node':
         target = as_node(id)
     elif request_data.get('type')[0] == 'event':
         target = Event.get_event(id)
     else:
         response.error(400, 'Unknown type.')
         return
     methodname = urllib.unquote_plus(request_data.get('method')[0])
     method = getattr(target, methodname)
     args = urllib.unquote_plus(request_data.get('args', ['()'])[0])
     args = eval(args)
     keywords = urllib.unquote_plus(request_data.get('keywords', ['{}'])[0])
     keywords = eval(keywords)
     result = method(*args, **keywords)
     result = repr(result)
     self.message('Invoking %s on %s with %s, %s, returned %s' %
                  (methodname, id, args, keywords, result))
     response.send(result)
Ejemplo n.º 20
0
 def handle(self,request):
     response = Response(request)
     qd = request.get_query_dictionary()
     data = self.get_data(qd)   
     request_path = urllib.unquote(string.lower(request.get_path()))
     file_path = os.path.join(self.parent.http_published_root, request_path[1:])
     if os.path.isfile(file_path):
         html = open(file_path).read()
         tokens = {}
         tokens['RECORDS'] = self.get_html(data)
         html = self.replace_tokens(html,tokens)
         response.send(html)
     else:
         response.send_error(404)
Ejemplo n.º 21
0
 def download_data(self, request, log, data, formatter):
     response = Response(request)
     response.set_header('Content-Type','application/octet-stream')
     response.set_header(
         'Content-Disposition', 'attachment; filename="%s.csv"' % log.name)
     output = formatter.format(data)
     if not output:
         return request.reply(204)
     if type(output) != type(''):
         output = StreamingProducer(output)
     response.push(output)
     response.done()
     request._DynamicLogHandler__success = True
     return
Ejemplo n.º 22
0
 def handle_request(self, request):
     path = request.get_path().split('/')
     # if there is a child to call, should be the
     # 3rd element path
     if len(path) < 3:
         fault_xml = xmlrpclib.dumps(
                 xmlrpclib.Fault(1, "Invalid URL Path")
                 )
         response = Response(request)
         response.send(fault_xml)
     else:
         c = path[2]
         handler = self.get_child(c)
         handler.handle_request(request)
Ejemplo n.º 23
0
    def handle_request(self, request):
        print 'handle_request'
        if not self.running:
            return request.error(503)  #service unavailable
        try:
            self.data = data = request.get_data().read_all()
            if not data:
                raise EProtocol(
                    'could not get DATA parameter from posted data')
            ## process xmlrpc, getting the name of the method
            ## and parameters
            params, method = xmlrpclib.loads(data)
            return

            object_alias = ''
            method_name = ''
            ## get the name of the object
            ## and the name of method
            ## They are delimited by a colon.

        except:
            msglog.exception()
            raise MpxException(
                'Error occurred while processing Brivo XMLRPC command')
        # XML-RPC Call was successful.
        # Send back the XML result to client
        reply = Response(request)
        reply.set_header('Content-Length', len(response))
        reply.set_header('Content-Type', 'text/xml')
        reply.send(response)
        return
Ejemplo n.º 24
0
 def respond(result):
     if isinstance(result, Exception):
         # Package exception into XML-RPC Fault instance.
         message = getattr(result, "message", "")
         if not message:
             message = str(result)
         typename = type(result).__name__
         if typename == "instance":
             typename = result.__class__.__name__
         faultstring = "%s: %s" % (typename, message)
         if isinstance(faultstring, unicode):
             try:
                 faultstring = str(faultstring)
             except UnicodeEncodeError:
                 faultstring = faultstring.encode('utf')
         result = xmlrpclib.Fault(1, faultstring)
     else:
         # Dumps requires tuple or Fault type.
         result = (result, )
     xmlresult = xmlrpclib.dumps(result, methodresponse=True)
     response = Response(request)
     response.set_header('Content-Length', len(xmlresult))
     response.set_header('Content-Type', 'text/xml')
     response.send(xmlresult)
     self.debugout("Response sent to client.")
Ejemplo n.º 25
0
 def handle_request(self, request):
     try:
         response = Response(request)
         request_data = request.get_post_data_as_dictionary()
         request_data.update(request.get_query_string_as_dictionary())
         context = request_data['manager'][0]
         adapt = self.__handle_by_context(context, request, request_data)
         if adapt is not None:
             # Since password rejection completes request...
             webadapter = IWebContent(adapt)
             response['Content-Type'] = "text/html"
             response.send(webadapter.render(self.path))
         return
     except Unauthorized, e:
         request.error(403, "Permission Denied: %s"%e)
Ejemplo n.º 26
0
 def handle_request(self, request):
     response = Response(request)
     start_time = self.time.get_last_time()
     end_time = int(time.time())
     if request.has_query():
         query = request.get_query_dictionary()
         if query.has_key('start'):
             start_time = float(query['start'])
         if query.has_key('end'):
             end_time = float(query['end'])
     try:
         data = self.log.get_slice('timestamp', start_time, end_time)
     except ERangeError, e:
         msglog.exception(msglog.types.WARN, None, 'Handled')
         response.send('Too much data, try slice from ' +
                       '%s to %s' % (start_time,e.good_end))
Ejemplo n.º 27
0
 def handle_request(self, request):
     response = Response(request)
     manager = self.manager
     if self.secured:
         manager = self.security_manager.as_secured_node(manager)
     username = request.user_object().name()
     request_data = request.get_post_data_as_dictionary()
     request_data.update(request.get_query_string_as_dictionary())
     if request_data.has_key('reload'):
         self.redirect(request)
         return
     elif request_data.has_key('viewtrend'):
         name = request_data['viewtrend'][0]
         adapt = manager.get_trend(name)
     elif request_data.has_key('newtrend'):
         try:
             name = request_data['trendname'][0].strip()
             adapt = manager.new_trend(name)
             adapt = manager
             self.redirect(request)
         except ENameInUse:
             request.error(
                 400, "<b>%s</b> exists, Please use a different name" %
                 request_data['trendname'][0])
         except Unauthorized, e:
             request.error(403, "Permission Denied: %s" % e)
         return
Ejemplo n.º 28
0
 def handle_request(self, request):
     response = Response(request)
     start_time = self.time.get_last_time()
     end_time = int(time.time())
     if request.has_query():
         query = request.get_query_dictionary()
         if query.has_key('start'):
             start_time = float(query['start'])
         if query.has_key('end'):
             end_time = float(query['end'])
     try:
         data = self.log.get_slice('timestamp', start_time, end_time)
     except ERangeError, e:
         msglog.exception(msglog.types.WARN, None, 'Handled')
         response.send('Too much data, try slice from ' + '%s to %s' %
                       (start_time, e.good_end))
Ejemplo n.º 29
0
 def handle_request(self, request):
     response = Response(request)
     request_data = request.get_post_data_as_dictionary()
     request_data.update(request.get_query_string_as_dictionary())
     if not (request_data.has_key('type') and
             request_data.has_key('id') and
             request_data.has_key('method')):
         response.error(400, 'Missnig required param type, id, or method.')
         return
     id = urllib.unquote_plus(request_data.get('id')[0])
     if request_data.get('type')[0] == 'node':
         target = as_node(id)
     elif request_data.get('type')[0] == 'event':
         target = Event.get_event(id)
     else:
         response.error(400, 'Unknown type.')
         return
     methodname = urllib.unquote_plus(request_data.get('method')[0])
     method = getattr(target, methodname)
     args = urllib.unquote_plus(request_data.get('args', ['()'])[0])
     args = eval(args)
     keywords = urllib.unquote_plus(request_data.get('keywords', ['{}'])[0])
     keywords = eval(keywords)
     result = method(*args, **keywords)
     result = repr(result)
     self.message('Invoking %s on %s with %s, %s, returned %s' % (
                      methodname, id, args, keywords, result))
     response.send(result)
Ejemplo n.º 30
0
    def handle_request(self, request):
        print 'handle_request'
        if not self.running:
            return request.error(503) #service unavailable
        try:
            self.data = data = request.get_data().read_all()
            if not data:
                raise EProtocol('could not get DATA parameter from posted data')
            ## process xmlrpc, getting the name of the method
            ## and parameters
            params, method = xmlrpclib.loads(data)
            return

            object_alias = ''
            method_name = ''
            ## get the name of the object
            ## and the name of method
            ## They are delimited by a colon.

        except:
            msglog.exception()
            raise MpxException('Error occurred while processing Brivo XMLRPC command')
        # XML-RPC Call was successful.
        # Send back the XML result to client
        reply = Response(request)
        reply.set_header('Content-Length', len(response))
        reply.set_header('Content-Type', 'text/xml')
        reply.send(response)
        return
Ejemplo n.º 31
0
 def respond(result):
     if isinstance(result, Exception):
         # Package exception into XML-RPC Fault instance.
         message = getattr(result, "message", "")
         if not message:
             message = str(result)
         typename = type(result).__name__
         if typename == "instance":
             typename = result.__class__.__name__
         faultstring = "%s: %s" % (typename, message)
         if isinstance(faultstring, unicode):
             try:
                 faultstring = str(faultstring)
             except UnicodeEncodeError:
                 faultstring = faultstring.encode('utf')
         result = xmlrpclib.Fault(1, faultstring)
     else:
         # Dumps requires tuple or Fault type.
         result = (result,)
     xmlresult = xmlrpclib.dumps(result, methodresponse=True)
     response = Response(request)
     response.set_header('Content-Length', len(xmlresult))
     response.set_header('Content-Type', 'text/xml')
     response.send(xmlresult)
     self.debugout("Response sent to client.")
Ejemplo n.º 32
0
    def handle(self, request):
        msg_log = trimming_log('msglog')
        sort_order = 'descending'
        column = '_seq'
        end = len(msg_log)
        start = end - 25
        type = 'all'
        application = 'all'
        parameters = {}
        response = Response(request)
        parameters = request.get_query_dictionary()
        if parameters:
            if parameters.has_key('column'):
                column = parameters['column']
            if parameters.has_key('start'):
                start = parameters['start']
            if parameters.has_key('end'):
                end = parameters['end']
            if parameters.has_key('type'):
                type = parameters['type']
            if parameters.has_key('application'):
                application = parameters['application']
            if parameters.has_key('sort_order'):
                sort_order = parameters['sort_order']

        data = msg_log.get_range(column, float(start), float(end), 1)
        children = []
        index = 0
        increment = 1
        end = len(data)
        if column == '_seq':
            if string.upper(sort_order) == 'DESCENDING':
                increment = -1
                index = len(data) - 1
                end = -1
        while index != end:
            current_index = index
            child = entry_factory(data[index])
            index = child.feed(data, index, increment)
            if current_index == index:
                index += increment
            children.append(child)
        formatter = HTMLFormatter(children)
        response.send(formatter.output(type, application, sort_order))
Ejemplo n.º 33
0
 def handle_request(self, request):
     update_pdo = False
     response = Response(request)
     request_data = request.get_post_data_as_dictionary()
     request_data.update(request.get_query_string_as_dictionary())
     if request_data.has_key('add'):
         adapt = self.create_exporter("New Exporter")
     elif request_data.has_key('remove'):
         name = urllib.unquote_plus(request_data['remove'][0])
         self.remove_exporter(name)
         adapt = self.container
     elif request_data.has_key('edit'):
         name = urllib.unquote_plus(request_data['edit'][0])
         update_pdo = False
         adapt = self.container.get_exporter(name)
     elif request_data.has_key('configure'):
         name = urllib.unquote_plus(request_data['configure'][0])
         exporter = self.container.get_exporter(name)
         config = {'Exporter': {}, 'Formatter': {}, 'Transporter': {}}
         for attrname in request_data.keys():
             splitname = attrname.split('.')
             if len(splitname) == 2 and config.has_key(splitname[0]):
                 config[splitname[0]][splitname[1]] = urllib.unquote_plus(
                     request_data[attrname][0])
         exportconfig = config['Exporter']
         exportconfig['formatter'] = config['Formatter']
         exportconfig['transporter'] = config['Transporter']
         exporter.configure(exportconfig)
         update_pdo = True
         adapt = exporter
     else:
         adapt = self.container
     if request_data.has_key('actionName'):
         target = urllib.unquote_plus(request_data.get('target')[0])
         action = urllib.unquote_plus(request_data.get('actionName')[0])
         params = map(urllib.unquote_plus, request_data.get('params'))
         exporter = self.container.get_exporter(target)
         method = getattr(exporter, action)
         result = method(*params)
         update_pdo = True
     if update_pdo:
         self.updatepdo()
     webadapter = IWebContent(adapt)
     response.send(webadapter.render())
Ejemplo n.º 34
0
 def handle(self,request):
     msg_log = trimming_log('msglog')
     sort_order = 'descending'
     column = '_seq'
     end = len(msg_log)
     start = end - 25
     type = 'all'
     application = 'all'
     parameters = {}
     response = Response(request)
     parameters = request.get_query_dictionary()
     if parameters:
         if parameters.has_key('column'):
             column = parameters['column']
         if parameters.has_key('start'):
             start = parameters['start']
         if parameters.has_key('end'):
             end = parameters['end']
         if parameters.has_key('type'):
             type = parameters['type'] 
         if parameters.has_key('application'):
             application = parameters['application']
         if parameters.has_key('sort_order'):
             sort_order = parameters['sort_order']
     
     data = msg_log.get_range(column, float(start), float(end), 1)
     children = []
     index = 0
     increment = 1
     end = len(data)
     if column == '_seq':            
         if string.upper(sort_order) == 'DESCENDING':
             increment = -1
             index = len(data) -1
             end = -1
     while index != end:
         current_index = index            
         child = entry_factory(data[index])        
         index = child.feed(data,index,increment)
         if current_index == index:
             index += increment                            
         children.append(child)
     formatter = HTMLFormatter(children)
     response.send(formatter.output(type,application,sort_order))
Ejemplo n.º 35
0
    def handle_request(self, request):
        response = Response(request)
        request_data = request.get_post_data_as_dictionary()
        request_data.update(request.get_query_string_as_dictionary())
        logname = urllib.unquote_plus(request_data['log'][0])
        lognode = as_node('/services/logger/%s' % logname)
        if request_data.has_key('start'):
            startvalue = float(urllib.unquote_plus(request_data['start'][0]))
        else: startvalue = self.time.get_last_time(logname)

        if request_data.has_key('end'):
            endvalue = float(urllib.unquote_plus(request_data['end'][0]))
        else: endvalue = int(time.time())

        try: data = lognode.get_slice('timestamp', startvalue, endvalue)
        except ERangeError, e:
            msglog.exception(msglog.types.WARN, None, 'Handled')
            response.send('Too much data, try slice from ' +
                          '%s to %s' % (startvalue, e.good_end))
Ejemplo n.º 36
0
 def handle_request(self, request):
     update_pdo = False
     response = Response(request)
     request_data = request.get_post_data_as_dictionary()
     request_data.update(request.get_query_string_as_dictionary())
     if request_data.has_key('add'):
         adapt = self.create_exporter("New Exporter")
     elif request_data.has_key('remove'):
         name = urllib.unquote_plus(request_data['remove'][0])
         self.remove_exporter(name)
         adapt = self.container
     elif request_data.has_key('edit'):
         name = urllib.unquote_plus(request_data['edit'][0])
         update_pdo = False
         adapt = self.container.get_exporter(name)
     elif request_data.has_key('configure'):
         name = urllib.unquote_plus(request_data['configure'][0])
         exporter = self.container.get_exporter(name)
         config = {'Exporter': {}, 'Formatter': {}, 'Transporter': {}}
         for attrname in request_data.keys():
             splitname = attrname.split('.')
             if len(splitname) == 2 and config.has_key(splitname[0]):
                 config[splitname[0]][splitname[1]] = urllib.unquote_plus(request_data[attrname][0])
         exportconfig = config['Exporter']
         exportconfig['formatter'] = config['Formatter']
         exportconfig['transporter'] = config['Transporter']
         exporter.configure(exportconfig)
         update_pdo = True
         adapt = exporter
     else: 
         adapt = self.container
     if request_data.has_key('actionName'):
         target = urllib.unquote_plus(request_data.get('target')[0])
         action = urllib.unquote_plus(request_data.get('actionName')[0])
         params = map(urllib.unquote_plus, request_data.get('params'))
         exporter = self.container.get_exporter(target)
         method = getattr(exporter, action)
         result = method(*params)
         update_pdo = True
     if update_pdo:
         self.updatepdo()
     webadapter = IWebContent(adapt)
     response.send(webadapter.render())
Ejemplo n.º 37
0
 def handle_request(self, request):
     header_style = "color:#FFFFFF;font-size:20px;font-weight:bold;background:#898989;"
     header_style += 'text-align:center;'
     html = '<html><head>\n'
     html += '<link rel="stylesheet"  type="text/css" href="/stylesheets/main.css">'
     html += '\n</head><body>\n'
     if self.enabled:
         index = 1
         html += '<table width="100%"><tr><td bgColor="#aaaaaa">\n'
         html += '<table width="100%" cellspacing="1" cellpadding="10" border="0">'
         html += '<tr><td style="%s" ' % header_style
         html +=  'width="35%">Name</td>\n'
         html += '<td style="%s" ' % header_style
         html += 'width="65%">Value</td></tr>\n' 
         dict= properties.as_dictionary()
         props = dict.keys()
         props.sort()
         
         for p in props:
             if (index%2) > 0:
                 bgColor = "#EEEEEE"
             else:
                 bgColor = "#FFFFFF"
             index += 1
             html += '<tr><td style="color:#000000;font-weight:bold"'
             html += ' bgColor="%s" align="right">%s</td><td bgColor="%s" align="left"><font color="#000FFF">%s</font></td></tr>\n' % (bgColor,p,bgColor,dict[p])
         html += '</table>'
         html += '</td></tr></table>'
        
         
     else:
         html += '<span class="disabled_msg">Sorry, the handler for your request is currently disabled</span>'
     
     html += "</body></html>"
     response = Response(request)
     response.send(html)
Ejemplo n.º 38
0
 def _handle_request(self, request):
     response = Response(request)
     start_time = self.time.get_last_time()
     self._scheduled_time = start_time
     end_time = int(time.time())
     data = []
     try:
         if self.debug:
             msglog.log('enerwise', msglog.types.DB,
                        'slice from %s to %s' % (start_time, end_time))
         data.extend(self.log.get_slice('timestamp', start_time, end_time))
     except ERangeError, e:
         msglog.exception(msglog.types.WARN, None, 'Handled')
         end_time = e.good_end
         data.extend(self.log.get_slice('timestamp', start_time, end_time))
Ejemplo n.º 39
0
 def handle_request(self, request):
     output = StringIO()
     command = request.get_command()
     header = '-- %s request [%d] [%s] --      '
     header %= (command, id(request), time.ctime())
     output.write(header)
     output.write('\n' + '*' * len(header) + '\n')
     output.write('<<< Request >>>\n')
     output.write(' - headers - \n')
     output.write(string.join(request.get_headers(), '\n') + '\n\n')
     output.write(' - content - \n')
     data = '-- No incoming data --'
     delimlength = len(data)
     if command == 'POST':
         data = request.get_data().read_all()
     output.write(data + '\n' + '-' * delimlength + '\n\n')
     response = Response(request)
     output.write('<<< Response >>>\n')
     command_cookie = Cookie('command_id', str(UUID()))
     command_cookie.add_attribute('path', '/')
     command_cookie.add_attribute('domain', '.domain.com')
     test_cookie = Cookie('test_id', str(UUID()))
     test_cookie.add_attribute('path', '/')
     test_cookie.add_attribute('domain', '.domain.com')
     content = self.next_request()
     response.add_cookie(command_cookie)
     response.add_cookie(test_cookie)
     response.push(content)
     output.write(' - headers - \n')
     for name, value in request.response_headers.items():
         output.write("%s: %s\n" % (name, value))
     output.write(' - content - \n')
     output.write(content or '-- No outgoing data --')
     output.write('\n' + '*' * len(header) + '\n\n')
     response.done()
     self.debug_dumps(output.getvalue())
Ejemplo n.º 40
0
    def handle_request(self, request):
        header_style = "color:#FFFFFF;font-size:20px;font-weight:bold;background:#898989;"
        header_style += 'text-align:center;'
        html = '<html><head>\n'
        html += '<link rel="stylesheet"  type="text/css" href="/stylesheets/main.css">'
        html += '\n</head><body>\n'
        if self.enabled:
            index = 1
            html += '<table width="100%"><tr><td bgColor="#aaaaaa">\n'
            html += '<table width="100%" cellspacing="1" cellpadding="10" border="0">'
            html += '<tr><td style="%s" ' % header_style
            html += 'width="35%">Name</td>\n'
            html += '<td style="%s" ' % header_style
            html += 'width="65%">Value</td></tr>\n'
            dict = properties.as_dictionary()
            props = dict.keys()
            props.sort()

            for p in props:
                if (index % 2) > 0:
                    bgColor = "#EEEEEE"
                else:
                    bgColor = "#FFFFFF"
                index += 1
                html += '<tr><td style="color:#000000;font-weight:bold"'
                html += ' bgColor="%s" align="right">%s</td><td bgColor="%s" align="left"><font color="#000FFF">%s</font></td></tr>\n' % (
                    bgColor, p, bgColor, dict[p])
            html += '</table>'
            html += '</td></tr></table>'

        else:
            html += '<span class="disabled_msg">Sorry, the handler for your request is currently disabled</span>'

        html += "</body></html>"
        response = Response(request)
        response.send(html)
Ejemplo n.º 41
0
 def handle_request(self, request):
     response = Response()
     if request.has_query():
         params = request.get_query_dictionary()
         if not params.has_key('action') or params['action'] != 'ack':
             return response.send('<H1>Unknown Query</H1>')
         alarm_url = request.get_path()[len(self.request_path):]
         try:
             alarm = as_node(alarm_url)
         except ENoSuchName:
             return response.send('<H1>Unknown Alarm</H1>')
         alarm.acknowledge()
         return response.send('<H1>The alarm has been notified</H1>')
     response.send(self._build_manager_page())
Ejemplo n.º 42
0
 def handle_request(self, request):
     output = StringIO()
     command = request.get_command()
     header = '-- %s request [%d] [%s] --      ' 
     header %= (command, id(request), time.ctime())
     output.write(header)
     output.write('\n' + '*' * len(header) + '\n')
     output.write('<<< Request >>>\n')
     output.write(' - headers - \n')
     output.write(string.join(request.get_headers(), '\n') + '\n\n')
     output.write(' - content - \n')
     data = '-- No incoming data --'
     delimlength = len(data)
     if command == 'POST':
         data = request.get_data().read_all()
     output.write(data + '\n' + '-' * delimlength + '\n\n')
     response = Response(request)
     output.write('<<< Response >>>\n')
     command_cookie = Cookie('command_id', str(UUID()))
     command_cookie.add_attribute('path', '/')
     command_cookie.add_attribute('domain', '.domain.com')
     test_cookie = Cookie('test_id', str(UUID()))
     test_cookie.add_attribute('path', '/')
     test_cookie.add_attribute('domain', '.domain.com')
     content = self.next_request()
     response.add_cookie(command_cookie)
     response.add_cookie(test_cookie)
     response.push(content)
     output.write(' - headers - \n')
     for name,value in request.response_headers.items():
         output.write("%s: %s\n" % (name,value))
     output.write(' - content - \n')
     output.write(content or '-- No outgoing data --')
     output.write('\n' + '*' * len(header) + '\n\n')
     response.done()
     self.debug_dumps(output.getvalue())
Ejemplo n.º 43
0
 def handle_request(self,request):
     response = Response()
     if request.has_query():
         params = request.get_query_dictionary()
         if not params.has_key('action') or params['action'] != 'ack':
             return response.send('<H1>Unknown Query</H1>')
         alarm_url = request.get_path()[len(self.request_path):]
         try:
             alarm = as_node(alarm_url)
         except ENoSuchName:
             return response.send('<H1>Unknown Alarm</H1>')
         alarm.acknowledge()
         return response.send('<H1>The alarm has been notified</H1>')
     response.send(self._build_manager_page())
Ejemplo n.º 44
0
 def handle(self, request):
     response = Response(request)
     qd = request.get_query_dictionary()
     data = self.get_data(qd)
     request_path = urllib.unquote(string.lower(request.get_path()))
     file_path = os.path.join(self.parent.http_published_root,
                              request_path[1:])
     if os.path.isfile(file_path):
         html = open(file_path).read()
         tokens = {}
         tokens['RECORDS'] = self.get_html(data)
         html = self.replace_tokens(html, tokens)
         response.send(html)
     else:
         response.send_error(404)
Ejemplo n.º 45
0
             try:
                 urllib2.urlopen(redirect).read()
             except Exception, error:
                 message = "'%s' remote events on '%s' failed."
                 msglog.warn(message % (command, origin))
                 msglog.exception(prefix="handled")
                 exceptions.append((origin, command, error))
 if exceptions:
     messages = ["Some actions failed:"]
     for errdata in exceptions:
         messages.append("  " + str(errdata))
     request["Content-Type"] = "text/plain"
     request.error(405, "\n".join(messages))
     return
 data = ""
 response = Response(request)
 style = request_data.get("type", self.default)
 if isinstance(style, (list, tuple)):
     style = style[0]
 if style != "none":
     interface = self.interfaces.get(style)
     if interface is None:
         request["Content-Type"] = "text/plain"
         request.error(405, "Invalid or unsupported feed type.")
         return
     try:
         syndicator = interface(self._subject)
     except ComponentLookupError, error:
         request["Content-Type"] = "text/plain"
         request.error(404, "No adapter for requested node.")
         return
Ejemplo n.º 46
0
    def handle_request(self, request):
        response = Response(request)
        response.set_header('Content-Type', 'text/xml')
        try:
            path = request.get_path().split('/')
            node_path = '/%s' % string.join(path[3:], '/')
            #
            #
            #
            # just for testing right now
            #
            #
            #
            if node_path == '' and len(path) < 4:
                results = self.invoke(request)
                xml = xmlrpclib.dumps((results, ), methodresponse=1)
                response.set_header('Content-Length', len(xml))
                response.set_header('Content-Type', 'text/xml')
                response.send(xml)
            else:
                node = self._as_node(node_path)
                data = self._get_data(request)
                # process xmlrpc, getting the name of the method
                # and parameters
                params, method = xmlrpclib.loads(data)
                method_name = ''
                # get the name of the object
                # and the name of method
                m = getattr(node, method)
                if params == '':
                    params = None
                result = (apply(m, params), )
                if hasattr(result[0], 'has_key'):
                    for k in result[0].keys():
                        if hasattr(result[0][k], 'has_key') \
                           and result[0][k].has_key('value') \
                           and isinstance(result[0][k]['value'],Exception):
                            result[0][k][
                                'value'] = 'error: %s' % result[0][k]['value']
                xml = xmlrpclib.dumps(result, methodresponse=1)
                # XML-RPC Call was successful.
                # Send back the XML result to client
                response = Response(request)
                response.set_header('Content-Length', len(xml))
                response.set_header('Content-Type', 'text/xml')
                response.send(xml)
        except Exception, err:
            if self.log_n_exceptions:
                msglog.exception()
                if self.log_n_exceptions > 0:
                    self.log_n_exceptions -= 1
            try:
                faultString = """<exception>
<module>%s</module>
<class>%s.%s</class>
<str>%r</str>
</exception>""" % (err.__class__.__module__, err.__class__.__module__,
                   err.__class__.__name__, str(err))
            except:
                msglog.exception()
                faultString = "%s" % err
            fault_xml = xmlrpclib.dumps(xmlrpclib.Fault(1, faultString))
            response.set_header('Content-Length', len(fault_xml))
            response.send(fault_xml)
Ejemplo n.º 47
0
 def handle_request(self, request):
     user = request.user_object()
     if user is not None and user.name() == 'eweb':
         request.error(401)
     response = Response(request)
     response_sent = 0
     try:
         html = self._get_pre_body_tag()
         html += '<body>'
         if self.debug:
             mpx.lib.msglog.log('broadway',mpx.lib.msglog.types.INFO,
                                 'handler_request called for device_viewer')
         if not self.enabled:
             html += '<span class="disabled_msg">Sorry, the handler for your request is currently disabled.</span>\n'
         else:
             path = request.get_path()
             if path[-1] == '/':
                 path = path[0:-1]
             node_url = path[len(self.request_path):]
             if node_url=='':
                 node_url = '/'
             html += self._make_links(node_url) + '<p>\n'
             if request.has_query():
                 # This request was for an action becuause it has
                 # parameters.
                 parameters = request.get_query_dictionary()
                 if parameters['action'] == 'get_override':
                     try:
                         value = self._get(node_url)
                     except Exception,e:
                         value = self._get_exception_name(e)
                     html  += string.join(self.override_form(path,value))
                 elif parameters['action'] == 'set_override':
                     if parameters.has_key('value'):
                         value = parameters['value']
                     else:
                         value = ""
                     value = _holistic_conversion(value)
                     self._as_node(node_url).set(value)
                     html += '<h3>Your override has been sent</h3>'
                 elif parameters['action'] == 'debug_on' or parameters['action'] == 'debug_off':
                     try:
                         node = mpx.lib.node.as_internal_node(node_url)
                         if parameters['action'] == 'debug_on':
                             node.debug = 1
                             html += 'Debugging turned on'
                         else:
                             node.debug = 0
                             html += 'Debugging turned off'
                     except Exception,e:
                         msg = self._get_exception_msg(e)
                         html += msg
                 elif parameters['action'] == 'invoke':
                     args = ()
                     method = None
                     if parameters.has_key('method'):
                         method = parameters['method']
                     if parameters.has_key('Content-Type'):
                         content_type = parameters['Content-Type']
                     else:
                         content_type = 'text/plain'
                     try:
                         node = mpx.lib.node.as_internal_node(node_url)
                         if method is not None:
                             if parameters.get('parameters',0):
                                 result = getattr(node,method)(*args, **parameters)
                             else:
                                 result = getattr(node,method)(*args)
                         else:
                             result = node(*args)
                         if hasattr(result,'read'):
                             from mpx.service.network.http import producers
                             if hasattr(result,'close'):
                                 result = producers.FileProducer(result)
                             else:
                                 result = producers.StreamingProducer(
                                     result
                                     )
                         else:
                             result = str(result)
                         response['Content-Type'] = content_type
                         response.send(result)
                         response_sent = 1
                         return
                     except Exception,e:
                         message = "%s: %s" % (e.__class__, str(e))
                         response['Content-Type'] = 'text/plain'
                         response.send_error(400,message)
                         response_sent = 1
                         return
Ejemplo n.º 48
0
 def handle_request(self, request):
     update_pdo = False
     storage = None
     response = Response(request)
     username = request.user_object().name()
     request_data = request.get_post_data_as_dictionary()
     request_data.update(request.get_query_string_as_dictionary())
     if request_data.has_key('add'):
         self.synclock.acquire()
         try:
             alarm = self.create_alarm()
             #CSCte94335 - commenting following because it is temporary alarm
             #self.alarms[alarm.name] = alarm
         finally:
             self.synclock.release()
         adapt = alarm
         if self.debug:
             message = "%s.handle_request() handling add request"
             msglog.log("broadway", msglog.types.DB, message % self.name)
     elif request_data.has_key('remove'):
         self.remove_alarm(urllib.unquote_plus(request_data['remove'][0]))
         adapt = self.managernode
         if self.debug:
             message = "%s.handle_request() handling remove request"
             msglog.log("broadway", msglog.types.DB, message % self.name)
     elif request_data.has_key('edit'):
         name = urllib.unquote_plus(request_data['edit'][0])
         adapt = self.managernode.get_child(name)
         if self.debug:
             message = "%s.handle_request() handling edit request"
             msglog.log("broadway", msglog.types.DB, message % self.name)
     elif request_data.has_key('configure'):
         name = urllib.unquote_plus(request_data['configure'][0])
         # CSCte94335 - if old alarm name does not exist then add this alarm condition
         # else update the existing alarm
         if self.alarms.get(name) == None:
             # create a new alarm
             config = {}
             # CSCte94370 - strip the name string to ignore spaces.
             config['name'] = urllib.unquote_plus(
                 request_data.get('name')[0]).strip()
             config['priority'] = urllib.unquote_plus(
                 request_data.get('priority')[0])
             config['description'] = urllib.unquote_plus(
                 request_data.get('description')[0])
             config['parent'] = urllib.unquote_plus(
                 request_data.get('parent')[0])
             config['max_raised'] = urllib.unquote_plus(
                 request_data.get('max_raised')[0])
             config['max_cleared'] = urllib.unquote_plus(
                 request_data.get('max_cleared')[0])
             config['max_accepted'] = urllib.unquote_plus(
                 request_data.get('max_accepted')[0])
             self.create_alarm(config, persist=True)
         else:
             alarmnode = self.alarms[name]
             if self.secured:
                 alarm = self.as_secured_node(alarmnode)
             else:
                 alarm = alarmnode
             config = {}
             # CSCte94370 - strip the name string to ignore spaces.
             config['name'] = urllib.unquote_plus(
                 request_data.get('name', [alarm.name])[0]).strip()
             config['priority'] = urllib.unquote_plus(
                 request_data.get('priority', [alarm.priority])[0])
             config['description'] = urllib.unquote_plus(
                 request_data.get('description', [alarm.description])[0])
             config['parent'] = urllib.unquote_plus(
                 request_data.get('parent', [alarm.parent])[0])
             config['max_raised'] = urllib.unquote_plus(
                 request_data.get('max_raised', [alarm.max_raised])[0])
             config['max_cleared'] = urllib.unquote_plus(
                 request_data.get('max_cleared', [alarm.max_cleared])[0])
             config['max_accepted'] = urllib.unquote_plus(
                 request_data.get('max_accepted', [alarm.max_accepted])[0])
             self.configure_alarm(name, config)
         adapt = self.managernode
         if self.debug:
             message = "%s.handle_request() handling edit request"
             msglog.log("broadway", msglog.types.DB, message % self.name)
     else:
         if request_data.has_key('trigger'):
             name = urllib.unquote_plus(request_data['trigger'][0])
             self.trigger_alarm(name)
         elif request_data.has_key('clear'):
             name = urllib.unquote_plus(request_data['clear'][0])
             self.clear_alarm(name)
         adapt = self.managernode
     if self.secured:
         adapt = self.securitymanager.as_secured_node(adapt)
         # Throw authorization error if adaptation will fail.
         adapt.test_adaptability()
     webadapter = IWebContent(adapt)
     request['Content-Type'] = "text/html"
     html = webadapter.render()
     #CSCte94335 - deleting the alarm that was created temporarily during 'add'
     if request_data.has_key('add'):
         self.synclock.acquire()
         try:
             adapt.prune()
         finally:
             self.synclock.release()
     if self.debug:
         message = ("%s.handle_request() handling "
                    "adapting %s returning: \n\r%s\n\r")
         msglog.log("broadway", msglog.types.DB,
                    message % (self.name, adapt, html))
     response.send(html)
Ejemplo n.º 49
0
class PSPHandler(RequestHandler):
    def __init__(self):
        RequestHandler.__init__(self)
        self.security_manager = None
        self.provides_security = None
        self.filespace = None
        self.cache = {}
        self.html = ''
        self.ROOT_DIR = None

    ##
    # Configures HTTP handler.
    #
    # @param config  Dictionary containing parameters and values from
    #                the configuration tool.
    # @key request_path  Regular expression for url requests that
    #                    should be forwarded to this handler.
    # @default ^/trane/vista/
    #
    # @see mpx.lib.service.SubServiceNode#configure
    def configure(self, config):
        RequestHandler.configure(self, config)
        set_attribute(self, 'request_path', '.*\.psp$', config)
        set_attribute(self, 'provides_security', 1, config, as_boolean)
        self.secured = as_boolean(as_internal_node("/services").secured)
        self.request_regex = re.compile(self.request_path)

    ##
    # Get the configuration.
    #
    # @return Dictionary containing current configuartion.
    # @see mpx.lib.service.SubServiceNode#configuration
    #
    def configuration(self):
        config = RequestHandler.configuration(self)
        get_attribute(self, 'request_path', config)
        get_attribute(self, 'secured', config)
        get_attribute(self, 'provides_security', config)
        return config

    def start(self):
        RequestHandler.start(self)
        self.WEB_ROOT = properties.HTTP_ROOT
        if self.parent.server_type == 'HTTPS':
            self.WEB_ROOT = properties.HTTPS_ROOT
        for handler in self.parent.children_nodes():
            if isinstance(handler, FileSpace):
                self.filespace = handler
                break
        err_message = 'PSP handler not running in secured mode because \
                      no %s was found.  Config parameter "secured" \
                      being overriden to False'

        if self.secured and self.filespace:
            try:
                sm = as_node('/services/Security Manager')
            except KeyError:
                msglog.log('broadway', msglog.types.WARN,
                           err_message % 'Security Manager')
                msglog.exception(prefix='Handled')
                self.provides_security = self._secured = False
            else:
                self.security_manager = sm
                self.provides_security = self._secured = True
        else:
            if self.secured:
                # not secured because we could not locate filespace object.
                msglog.log('broadway', msglog.types.WARN,
                           err_message % 'FileSpace manager')
            self.provides_security = self._secured = False

    ##
    # @param path the path to match to see if we handle this request
    def match(self, path):
        if self.request_regex.match(path):
            return 1
        return 0

    def _use_cache(self, file):
        rt = 1
        if self.cache and self.cache.has_key(file.name):
            if os.stat(file.name)[ST_MTIME]  \
                > self.cache[file.name]['psp_last_modified'] :
                rt = 0
            if rt == 1:
                for f in self.cache[file.name]['include_files'].keys():
                    if os.stat(f)[ST_MTIME] > self.cache[
                            file.name]['include_files'][f]:
                        rt = 0
                        break
        else:
            rt = 0
        return rt

    def compile(self, file, dp, force_reload=0):
        sourcefile_name = '%spy' % file.name[:-3]
        if not self._use_cache(file):
            # Process all the directives
            dp = _DirectiveProcessor(file, self.WEB_ROOT)
            include_files = dp.get_include_filenames()
            file = dp.process()
            # Convert to psp to py file
            psp_convert = PSPConverter(file)
            psp_convert.convert()
            sourcefile = open(sourcefile_name, 'w')
            # add all the imports to the source file
            self._add_imports(sourcefile, dp.get_imports())
            sourcefile.write(psp_convert.get())
            sourcefile.close()
            targetfile = '%spyc' % file.name[:-3]
            if os.path.isfile(targetfile):
                os.remove(targetfile)
            _sdterr = sys.stderr
            stderr = StringIO.StringIO()
            sys.stderr = stderr
            py_compile.compile(sourcefile_name, targetfile)
            sys.stderr = _sdterr
            stderr.seek(0)
            err = ''
            for l in stderr.readlines():
                err += '%s<br>' % l
            if err != '':
                raise CompileError(err)
            module_name = os.tmpnam()
            psp_module = imp.load_module(module_name, open(targetfile), '',
                                         ('pyc', 'r', imp.PY_COMPILED))
            self.cache[file.name] = {
                'module': psp_module,
                'psp_last_modified': os.stat(file.name)[ST_MTIME],
                'py_last_modified': os.stat(sourcefile_name)[ST_MTIME],
                'include_files': {},
                'dp': dp
            }
            for f in include_files:
                self.cache[file.name]['include_files'][f] = os.stat(
                    f)[ST_MTIME]
        else:
            if os.stat(sourcefile_name)[ST_MTIME] > self.cache[
                    file.name]['py_last_modified']:
                targetfile = '%spyc' % file.name[:-3]
                if os.path.isfile(targetfile):
                    os.remove(targetfile)
                _sdterr = sys.stderr
                stderr = StringIO.StringIO()
                sys.stderr = stderr
                py_compile.compile(sourcefile_name, targetfile)
                sys.stderr = _sdterr
                stderr.seek(0)
                err = ''
                for l in stderr.readlines():
                    err += '%s<br>' % l
                if err != '':
                    raise CompileError(err)
                module_name = os.tmpnam()
                psp_module = imp.load_module(module_name, open(targetfile), '',
                                             ('pyc', 'r', imp.PY_COMPILED))
                self.cache[file.name]['py_last_modified'] = os.stat(
                    sourcefile_name)[ST_MTIME]

    def _add_imports(self, fp, imports):
        for ip in imports:
            fp.writelines('%s\n' % ip)

    def checkIfPspIsTobeSendWithNoCache(self, filename):
        noCachePspList = ["webexpress.psp"]
        try:
            i = noCachePspList.index(filename)
        except ValueError:
            i = -1  # no match
        return i

    def handle_request(self, request):
        path = request.get_path()[1:]
        filename = os.path.basename(path)
        if self.checkIfPspIsTobeSendWithNoCache(filename) != -1:
            request['Cache-Control'] = 'no-cache, no-store'
        response = Response(request)
        try:
            qs = request.get_query_dictionary()
            force_reload = 0
            psp = PSP(response)
            path = request.get_path()[1:]
            f = os.path.join(self.WEB_ROOT, path)
            if self.filespace:
                file_node = self.filespace.as_node(path)
                if self._secured:
                    file_node = self.security_manager.as_secured_node(
                        file_node.as_node_url())
                try:
                    file = file_node.openread()
                except Unauthorized:
                    if not request._has_minimum_authentication():
                        authenticate = request._default_authentication
                        authenticate(request._channel.server.realm)
                    else:
                        raise
                    file = file_node.openread()
            else:
                file = open(f, 'r')
            # If this is in the Query String the page will get reparsed

            if qs.has_key('PSPForceReload'):
                force_reload = 1
            self.compile(file, force_reload)
            psp_module = self.cache[f]['module']
            if qs.has_key('PSPUseNewPY'):
                sourcefile_name = '%spy' % file.name[:-3]
                targetfile = '%spyc' % file.name[:-3]
                py_compile.compile(sourcefile_name, targetfile)
                _sdterr = sys.stderr
                stderr = StringIO.StringIO()
                sys.stderr = stderr
                module_name = os.tmpnam()
                psp_module = imp.load_module(module_name, open(targetfile), '',
                                             ('pyc', 'r', imp.PY_COMPILED))
                self.cache[file.name]['module'] = psp_module
                sys.stderr = _sdterr
                stderr.seek(0)
                err = ''
                for l in stderr.readlines():
                    err += '%s<br>' % l
                if err != '':
                    raise CompileError(err)
            psp_module.run(psp, request, response)
            psp.send()
        except EAuthenticationFailed:
            raise
        except CompileError, e:
            err = '%s' % e
            if response == None:
                response = Response(request)
            response.send('<html><body>%s</body></html>' % e)
        except Exception, e:
            err = ''
            etype, value, tb = sys.exc_info()
            err = ''.join(format_exception(etype, value, tb))
            html = '<html><body style="color:red"><b>Error</b>'
            html += '<br>&nbsp;&nbsp;<pre>%s</pre></body></html>' % err
            if response == None:
                response = Response(request)
            response.send(html)
Ejemplo n.º 50
0
 def handle(self,request):
     response = Response(request)
     html = '<html><head>'
     html += '<META http-equiv="Refresh" content="0; Url=/msglog/index.html" >'
     html += '</head><body></body></html>'        
     response.send(html)
Ejemplo n.º 51
0
    def handle_request(self, request):
        response = Response(request)
        response.set_header('Content-Type', 'text/xml')
        try:
            path = request.get_path().split('/')
            node_path = '/%s' % string.join(path[3:],'/')
            #
            #
            #
            # just for testing right now
            #
            #
            #
            if node_path == '' and len(path) < 4:
                results = self.invoke(request)
                xml = xmlrpclib.dumps((results,),methodresponse=1)
                response.set_header('Content-Length', len(xml))
                response.set_header('Content-Type', 'text/xml')
                response.send(xml)
            else:
                node = self._as_node(node_path)
                data = self._get_data(request)
                # process xmlrpc, getting the name of the method
                # and parameters
                params, method = xmlrpclib.loads(data)
                method_name = ''
                # get the name of the object
                # and the name of method
                m = getattr(node, method)
                if params == '':
                    params = None
                result = (apply(m,params),)
                if hasattr(result[0],'has_key'):
                    for k in result[0].keys():
                        if hasattr(result[0][k], 'has_key') \
                           and result[0][k].has_key('value') \
                           and isinstance(result[0][k]['value'],Exception):
                            result[0][k]['value'] = 'error: %s' % result[0][k]['value']
                xml = xmlrpclib.dumps(result,methodresponse=1)
                # XML-RPC Call was successful.
                # Send back the XML result to client
                response = Response(request)
                response.set_header('Content-Length', len(xml))
                response.set_header('Content-Type', 'text/xml')
                response.send(xml)
        except Exception,err:
            if self.log_n_exceptions:
                msglog.exception()
                if self.log_n_exceptions > 0:
                    self.log_n_exceptions -= 1
            try:
                faultString = """<exception>
<module>%s</module>
<class>%s.%s</class>
<str>%r</str>
</exception>""" % (err.__class__.__module__,
                   err.__class__.__module__,
                   err.__class__.__name__,
                   str(err))                
            except:
                msglog.exception()
                faultString = "%s" % err
            fault_xml = xmlrpclib.dumps(
                    xmlrpclib.Fault(1, faultString)
                    )
            response.set_header('Content-Length', len(fault_xml))
            response.send(fault_xml)
Ejemplo n.º 52
0
    def handle_request(self, request):
        path = request.get_path()[1:]
        filename = os.path.basename(path)
        if self.checkIfPspIsTobeSendWithNoCache(filename) != -1:
            request['Cache-Control'] = 'no-cache, no-store'
        response = Response(request)
        try:
            qs = request.get_query_dictionary()
            force_reload = 0
            psp = PSP(response)
            path = request.get_path()[1:]
            f = os.path.join(self.WEB_ROOT, path)
            if self.filespace:
                file_node = self.filespace.as_node(path)
                if self._secured:
                    file_node = self.security_manager.as_secured_node(
                        file_node.as_node_url())
                try:
                    file = file_node.openread()
                except Unauthorized:
                    if not request._has_minimum_authentication():
                        authenticate = request._default_authentication
                        authenticate(request._channel.server.realm)
                    else:
                        raise
                    file = file_node.openread()
            else:
                file = open(f, 'r')
            # If this is in the Query String the page will get reparsed

            if qs.has_key('PSPForceReload'):
                force_reload = 1
            self.compile(file, force_reload)
            psp_module = self.cache[f]['module']
            if qs.has_key('PSPUseNewPY'):
                sourcefile_name = '%spy' % file.name[:-3]
                targetfile = '%spyc' % file.name[:-3]
                py_compile.compile(sourcefile_name, targetfile)
                _sdterr = sys.stderr
                stderr = StringIO.StringIO()
                sys.stderr = stderr
                module_name = os.tmpnam()
                psp_module = imp.load_module(module_name, open(targetfile), '',
                                             ('pyc', 'r', imp.PY_COMPILED))
                self.cache[file.name]['module'] = psp_module
                sys.stderr = _sdterr
                stderr.seek(0)
                err = ''
                for l in stderr.readlines():
                    err += '%s<br>' % l
                if err != '':
                    raise CompileError(err)
            psp_module.run(psp, request, response)
            psp.send()
        except EAuthenticationFailed:
            raise
        except CompileError, e:
            err = '%s' % e
            if response == None:
                response = Response(request)
            response.send('<html><body>%s</body></html>' % e)
Ejemplo n.º 53
0
 def handle(self, request):
     response = Response(request)
     html = '<html><head>'
     html += '<META http-equiv="Refresh" content="0; Url=/msglog/index.html" >'
     html += '</head><body></body></html>'
     response.send(html)
Ejemplo n.º 54
0
             try:
                 urllib2.urlopen(redirect).read()
             except Exception, error:
                 message = "'%s' remote events on '%s' failed."
                 msglog.warn(message % (command, origin))
                 msglog.exception(prefix="handled")
                 exceptions.append((origin, command, error))
 if exceptions:
     messages = ["Some actions failed:"]
     for errdata in exceptions:
         messages.append("  " + str(errdata))
     request['Content-Type'] = 'text/plain'
     request.error(405, "\n".join(messages))
     return
 data = ""
 response = Response(request)
 style = request_data.get('type', self.default)
 if isinstance(style, (list, tuple)):
     style = style[0]
 if style != "none":
     interface = self.interfaces.get(style)
     if interface is None:
         request['Content-Type'] = 'text/plain'
         request.error(405, 'Invalid or unsupported feed type.')
         return
     try:
         syndicator = interface(self._subject)
     except ComponentLookupError, error:
         request['Content-Type'] = 'text/plain'
         request.error(404, 'No adapter for requested node.')
         return
Ejemplo n.º 55
0
    def handle_request(self,request):
        path = request.get_path()[1:]
        filename = os.path.basename(path)
        if self.checkIfPspIsTobeSendWithNoCache(filename) != -1:
            request['Cache-Control'] = 'no-cache, no-store'
        response = Response(request)
        try:
            qs = request.get_query_dictionary()
            force_reload = 0
            psp = PSP(response)
            path = request.get_path()[1:]
            f = os.path.join(self.WEB_ROOT, path)
            if self.filespace:
                file_node = self.filespace.as_node(path)
                if self._secured:
                    file_node = self.security_manager.as_secured_node(
                                    file_node.as_node_url()
                                )
                try:
                    file = file_node.openread()
                except Unauthorized:
                    if not request._has_minimum_authentication():
                        authenticate = request._default_authentication
                        authenticate(request._channel.server.realm)
                    else:
                        raise
                    file = file_node.openread()
            else:
                file = open(f, 'r')
            # If this is in the Query String the page will get reparsed

            if qs.has_key('PSPForceReload'):
                force_reload = 1
            self.compile(file,force_reload)
            psp_module = self.cache[f]['module']
            if qs.has_key('PSPUseNewPY'):
                sourcefile_name = '%spy' % file.name[:-3]
                targetfile = '%spyc' % file.name[:-3]
                py_compile.compile(sourcefile_name, targetfile)
                _sdterr = sys.stderr
                stderr = StringIO.StringIO()
                sys.stderr = stderr
                module_name =os.tmpnam()
                psp_module = imp.load_module(module_name,open(targetfile),'',
                                         ('pyc','r',imp.PY_COMPILED))
                self.cache[file.name]['module'] = psp_module
                sys.stderr = _sdterr
                stderr.seek(0)
                err = ''
                for l in stderr.readlines():
                    err += '%s<br>' % l
                if err != '':
                    raise CompileError(err)
            psp_module.run(psp,request,response)
            psp.send()
        except EAuthenticationFailed:
            raise
        except CompileError,e:
            err = '%s' % e
            if response == None:
                response = Response(request)
            response.send('<html><body>%s</body></html>' % e)