Exemplo n.º 1
0
    def send_rpc_error(self, req, e):
        """Send an XML-RPC fault message back to the caller"""
        rpcreq = req.rpc
        fault = None
        if isinstance(e, ProtocolException):
            fault = e._exc
        elif isinstance(e, ServiceException):
            e = e._exc
        elif isinstance(e, MethodNotFound):
            fault = xmlrpclib.Fault(-32601, to_unicode(e))
        elif isinstance(e, PermissionError):
            fault = xmlrpclib.Fault(403, to_unicode(e))
        elif isinstance(e, ResourceNotFound):
            fault = xmlrpclib.Fault(404, to_unicode(e))

        if fault is not None :
            self._send_response(req, xmlrpclib.dumps(fault), rpcreq['mimetype'])
        else :
            self.log.error(e)
            import traceback
            from tracrpc.util import StringIO
            out = StringIO()
            traceback.print_exc(file = out)
            self.log.error(out.getvalue())
            err_code = hasattr(e, 'code') and e.code or 1
            method = rpcreq.get('method')
            self._send_response(req,
                    xmlrpclib.dumps(
                        xmlrpclib.Fault(err_code,
                            "'%s' while executing '%s()'" % (str(e), method))),
                    rpcreq['mimetype'])
Exemplo n.º 2
0
    def _dump_docs(self, req):
        self.log.debug("Rendering docs")

        # Dump RPC documentation
        req.perm.require('XML_RPC')  # Need at least XML_RPC
        namespaces = {}
        for method in XMLRPCSystem(self.env).all_methods(req):
            namespace = method.namespace.replace('.', '_')
            if namespace not in namespaces:
                namespaces[namespace] = {
                    'description':
                    wiki_to_oneliner(method.namespace_description,
                                     self.env,
                                     req=req),
                    'methods': [],
                    'namespace':
                    method.namespace,
                }
            try:
                namespaces[namespace]['methods'].append(
                    (method.signature,
                     wiki_to_oneliner(method.description, self.env,
                                      req=req), method.permission))
            except Exception, e:
                from tracrpc.util import StringIO
                import traceback
                out = StringIO()
                traceback.print_exc(file=out)
                raise Exception('%s: %s\n%s' %
                                (method.name, str(e), out.getvalue()))
Exemplo n.º 3
0
    def send_rpc_error(self, req, e):
        """Send an XML-RPC fault message back to the caller"""
        rpcreq = req.rpc
        fault = None
        if isinstance(e, ProtocolException):
            fault = e._exc
        elif isinstance(e, ServiceException):
            e = e._exc
        elif isinstance(e, MethodNotFound):
            fault = xmlrpclib.Fault(-32601, to_unicode(e))
        elif isinstance(e, PermissionError):
            fault = xmlrpclib.Fault(403, to_unicode(e))
        elif isinstance(e, ResourceNotFound):
            fault = xmlrpclib.Fault(404, to_unicode(e))

        if fault is not None :
            self._send_response(req, xmlrpclib.dumps(fault), rpcreq['mimetype'])
        else :
            self.log.error(e)
            import traceback
            from tracrpc.util import StringIO
            out = StringIO()
            traceback.print_exc(file = out)
            self.log.error(out.getvalue())
            err_code = hasattr(e, 'code') and e.code or 1
            method = rpcreq.get('method')
            self._send_response(req,
                    xmlrpclib.dumps(
                        xmlrpclib.Fault(err_code,
                            "'%s' while executing '%s()'" % (str(e), method))))
Exemplo n.º 4
0
    def _dump_docs(self, req):
        self.log.debug("Rendering docs")

        # Dump RPC documentation
        req.perm.require('XML_RPC') # Need at least XML_RPC
        namespaces = {}
        for method in XMLRPCSystem(self.env).all_methods(req):
            namespace = method.namespace.replace('.', '_')
            if namespace not in namespaces:
                namespaces[namespace] = {
                    'description' : wiki_to_oneliner(
                                    method.namespace_description,
                                    self.env, req=req),
                    'methods' : [],
                    'namespace' : method.namespace,
                    }
            try:
                namespaces[namespace]['methods'].append(
                        (method.signature,
                        wiki_to_oneliner(
                            method.description, self.env, req=req),
                        method.permission))
            except Exception, e:
                from tracrpc.util import StringIO
                import traceback
                out = StringIO()
                traceback.print_exc(file=out)
                raise Exception('%s: %s\n%s' % (method.name,
                                                str(e), out.getvalue()))
Exemplo n.º 5
0
 def putAttachmentEx(self,
                     req,
                     pagename,
                     filename,
                     description,
                     data,
                     replace=True):
     """ Attach a file to a Wiki page. Returns the (possibly transformed)
     filename of the attachment.
     
     Use this method if you don't care about WikiRPC compatibility. """
     if not WikiPage(self.env, pagename).exists:
         raise ResourceNotFound, 'Wiki page "%s" does not exist' % pagename
     if replace:
         try:
             attachment = Attachment(self.env, 'wiki', pagename, filename)
             req.perm(attachment.resource).require('ATTACHMENT_DELETE')
             attachment.delete()
         except TracError:
             pass
     attachment = Attachment(self.env, 'wiki', pagename)
     req.perm(attachment.resource).require('ATTACHMENT_CREATE')
     attachment.author = req.authname
     attachment.description = description
     attachment.insert(filename, StringIO(data.data), len(data.data))
     return attachment.filename
Exemplo n.º 6
0
 def test_binary(self):
     # read and write binaries values
     image_url = os.path.join(rpc_testenv.trac_src, 'trac', 'htdocs',
                              'feed.png')
     image_in = StringIO(open(image_url, 'r').read())
     data = {
         'method':
         'wiki.putAttachmentEx',
         'params': [
             'TitleIndex', "feed2.png", "test image", {
                 '__jsonclass__':
                 ['binary',
                  image_in.getvalue().encode("base64")]
             }
         ]
     }
     result = self._auth_req(data, user='******')
     self.assertEquals('feed2.png', result['result'])
     # Now try to get the attachment, and verify it is identical
     result = self._auth_req(
         {
             'method': 'wiki.getAttachment',
             'params': ['TitleIndex/feed2.png']
         },
         user='******')
     self.assertTrue(result['result'])
     image_out = StringIO(
         result['result']['__jsonclass__'][1].decode("base64"))
     self.assertEquals(image_in.getvalue(), image_out.getvalue())
Exemplo n.º 7
0
 def test_binary(self):
     # read and write binaries values
     image_url = os.path.join(rpc_testenv.trac_src, 'trac',
                          'htdocs', 'feed.png')
     image_in = StringIO(open(image_url, 'r').read())
     data = {'method': 'wiki.putAttachmentEx',
         'params': ['TitleIndex', "feed2.png", "test image",
         {'__jsonclass__': ['binary', 
                     image_in.getvalue().encode("base64")]}]}
     result = self._auth_req(data, user='******')
     self.assertEquals('feed2.png', result['result'])
     # Now try to get the attachment, and verify it is identical
     result = self._auth_req({'method': 'wiki.getAttachment',
                     'params': ['TitleIndex/feed2.png']}, user='******')
     self.assertTrue(result['result'])
     image_out = StringIO(
             result['result']['__jsonclass__'][1].decode("base64"))
     self.assertEquals(image_in.getvalue(), image_out.getvalue())
Exemplo n.º 8
0
 def test_binary(self):
     # read and write binaries values
     image_url = os.path.join(rpc_testenv.trac_src, "trac", "htdocs", "feed.png")
     image_in = StringIO(open(image_url, "r").read())
     data = {
         "method": "wiki.putAttachmentEx",
         "params": [
             "TitleIndex",
             "feed2.png",
             "test image",
             {"__jsonclass__": ["binary", image_in.getvalue().encode("base64")]},
         ],
     }
     result = self._auth_req(data, user="******")
     self.assertEquals("feed2.png", result["result"])
     # Now try to get the attachment, and verify it is identical
     result = self._auth_req({"method": "wiki.getAttachment", "params": ["TitleIndex/feed2.png"]}, user="******")
     self.assertTrue(result["result"])
     image_out = StringIO(result["result"]["__jsonclass__"][1].decode("base64"))
     self.assertEquals(image_in.getvalue(), image_out.getvalue())
Exemplo n.º 9
0
 def test_attachments(self):
     # Note: Quite similar to the tracrpc.tests.json.JsonTestCase.test_binary
     image_url = os.path.join(rpc_testenv.trac_src, 'trac', 'htdocs',
                              'feed.png')
     image_in = StringIO(open(image_url, 'r').read())
     # Create attachment
     self.admin.wiki.putAttachmentEx('TitleIndex', 'feed2.png',
                                     'test image',
                                     xmlrpclib.Binary(image_in.getvalue()))
     self.assertEquals(
         image_in.getvalue(),
         self.admin.wiki.getAttachment('TitleIndex/feed2.png').data)
     # Update attachment (adding new)
     self.admin.wiki.putAttachmentEx('TitleIndex', 'feed2.png',
                                     'test image',
                                     xmlrpclib.Binary(image_in.getvalue()),
                                     False)
     self.assertEquals(
         image_in.getvalue(),
         self.admin.wiki.getAttachment('TitleIndex/feed2.2.png').data)
     # List attachments
     self.assertEquals(['TitleIndex/feed2.2.png', 'TitleIndex/feed2.png'],
                       sorted(
                           self.admin.wiki.listAttachments('TitleIndex')))
     # Delete both attachments
     self.admin.wiki.deleteAttachment('TitleIndex/feed2.png')
     self.admin.wiki.deleteAttachment('TitleIndex/feed2.2.png')
     # List attachments again
     self.assertEquals([], self.admin.wiki.listAttachments('TitleIndex'))
Exemplo n.º 10
0
 def test_attachments(self):
     # Note: Quite similar to the tracrpc.tests.json.JsonTestCase.test_binary
     image_url = os.path.join(rpc_testenv.trac_src, 'trac',
                          'htdocs', 'feed.png')
     image_in = StringIO(open(image_url, 'r').read())
     # Create attachment
     self.admin.wiki.putAttachmentEx('TitleIndex', 'feed2.png', 'test image',
         xmlrpclib.Binary(image_in.getvalue()))
     self.assertEquals(image_in.getvalue(), self.admin.wiki.getAttachment(
                                             'TitleIndex/feed2.png').data)
     # Update attachment (adding new)
     self.admin.wiki.putAttachmentEx('TitleIndex', 'feed2.png', 'test image',
         xmlrpclib.Binary(image_in.getvalue()), False)
     self.assertEquals(image_in.getvalue(), self.admin.wiki.getAttachment(
                                             'TitleIndex/feed2.2.png').data)
     # List attachments
     self.assertEquals(['TitleIndex/feed2.2.png', 'TitleIndex/feed2.png'],
                     sorted(self.admin.wiki.listAttachments('TitleIndex')))
     # Delete both attachments
     self.admin.wiki.deleteAttachment('TitleIndex/feed2.png')
     self.admin.wiki.deleteAttachment('TitleIndex/feed2.2.png')
     # List attachments again
     self.assertEquals([], self.admin.wiki.listAttachments('TitleIndex'))
Exemplo n.º 11
0
 def putAttachment(self,
                   req,
                   ticket,
                   filename,
                   description,
                   data,
                   replace=True):
     """ Add an attachment, optionally (and defaulting to) overwriting an
     existing one. Returns filename."""
     if not model.Ticket(self.env, ticket).exists:
         raise ResourceNotFound('Ticket "%s" does not exist' % ticket)
     if replace:
         try:
             attachment = Attachment(self.env, 'ticket', ticket, filename)
             req.perm(attachment.resource).require('ATTACHMENT_DELETE')
             attachment.delete()
         except TracError:
             pass
     attachment = Attachment(self.env, 'ticket', ticket)
     req.perm(attachment.resource).require('ATTACHMENT_CREATE')
     attachment.author = req.authname
     attachment.description = description
     attachment.insert(filename, StringIO(data.data), len(data.data))
     return attachment.filename