Пример #1
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.")
Пример #2
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())
Пример #3
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.")
Пример #4
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)
Пример #5
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())
Пример #6
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
Пример #7
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)
Пример #8
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))
Пример #9
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
Пример #10
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))
Пример #11
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))
Пример #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))
Пример #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)
Пример #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)
Пример #15
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))
Пример #16
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)
Пример #17
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())
Пример #18
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)
Пример #19
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)
Пример #20
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())
Пример #21
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)
Пример #22
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)
Пример #23
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))
Пример #24
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))
Пример #25
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))
Пример #26
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))
Пример #27
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())
Пример #28
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())
Пример #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())
        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))
Пример #30
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)
Пример #31
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)
Пример #32
0
        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
            clientid = request_data.get("clientid")
            if clientid is not None:
                clientid = clientid[0]
            data = syndicator.render(request.get_path(), clientid)
            response.set_header("Content-Type", "text/xml")
        response.send(data)
Пример #33
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)
Пример #34
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)
Пример #35
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)
Пример #36
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)
Пример #37
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)
Пример #38
0
        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
            clientid = request_data.get('clientid')
            if clientid is not None:
                clientid = clientid[0]
            data = syndicator.render(request.get_path(), clientid)
            response.set_header('Content-Type', 'text/xml')
        response.send(data)
Пример #39
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)
Пример #40
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)
Пример #41
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