Пример #1
0
 def __init__(self, message=None, *args, **kwargs):
     self.message = message or self.message
     Fault.__init__(self, self.code, self.message)
Пример #2
0
 def __init__(self, message="", code=1000, *args, **kwargs):
     MyClipsServerException.__init__(self, message=message, *args, **kwargs)
     Fault.__init__(self, code, "[%s] %s"%(self.__class__.__name__, message), **kwargs)
Пример #3
0
 def __init__(self):
     Fault.__init__(self, PERMISSION_DENIED_CODE, _('Permission denied'))
Пример #4
0
	def __init__(self, message, code = 0, *args, **kwargs):
		Fault.__init__(self, code, message, *args, **kwargs)
Пример #5
0
Файл: rpc.py Проект: nictuku/nwu
 def __init__(self, method_name):
     Fault.__init__(self, RPCFault.ACCESS_DENIED, method_name)
Пример #6
0
 def __init__(self):
     Fault.__init__(self, PERMISSION_DENIED_CODE,
         _('Resource not found'))
Пример #7
0
 def __init__(self, message):
     Fault.__init__(self, SADError.CORRUPTEDFILE, message)
Пример #8
0
 def __init__(self, code, message, **extra):
     Fault.__init__(self, code, message, **extra)
     for key in extra:
         setattr(self, key, extra[key])
Пример #9
0
 def __init__(self, value):
     Fault.__init__(self, XendClient.ERROR_INVALID_DOMAIN, value)
Пример #10
0
 def __init__(self,message="Cound not handle the query"):
     Fault.__init__(self, UNHANDLED, message)
Пример #11
0
	# next we check if the source URL does indeed exist
	if not g_blog.allow_pingback:
		raise Fault(49,"Access denied.")
	try:

		g_blog.tigger_action("pre_ping",source_uri,target_uri)
		response = urlfetch.fetch(source_uri)
	except Exception ,e :
		#logging.info(e.message)
		raise Fault(16, 'The source URL does not exist.%s'%source_uri)
	# we only accept pingbacks for links below our blog URL
	blog_url = g_blog.baseurl
	if not blog_url.endswith('/'):
		blog_url += '/'
	if not target_uri.startswith(blog_url):
		raise Fault(32, 'The specified target URL does not exist.')
	path_info = target_uri[len(blog_url):]

	pingback_post(response,source_uri,target_uri,path_info)
	try:

		return "Micolog pingback succeed!"
	except:
		raise Fault(49,"Access denied.")


def get_excerpt(response, url_hint, body_limit=1024 * 512):
	"""Get an excerpt from the given `response`.  `url_hint` is the URL
	which will be used as anchor for the excerpt.  The return value is a
	tuple in the form ``(title, body)``.  If one of the two items could
	not be calculated it will be `None`.
Пример #12
0
def pingback(request, source, target):
    logger = tools.get_logger()
    logger.info("pingback started")
    source_file = urllib.urlopen(source.split('#')[0])
    if source_file.headers.get('error', '') == '404':
        raise Fault(0x0010, "Target %s not exists" % target)
    source_page = parser()
    source_page.feed(source_file.read())
    source_file.close()

    if source_page.title == "":
        source_page.title = source

    if not target in source_page.hrefs:
        raise Fault(0x0011, "%s does not point to %s" % (source, target))

    target_entry = fileFor(request, target)

    body = ''
    try:
        from rssfinder import getFeeds
        from rssparser import parse

        baseurl = source.split("#")[0]
        for feed in getFeeds(baseurl):
            for item in parse(feed)['items']:
                if item['link'] == source:
                    if 'title' in item:
                        source_page.title = item['title']
                    if 'content_encoded' in item:
                        body = item['content_encoded'].strip()
                    if 'description' in item:
                        body = item['description'].strip() or body
                    body = re.compile('<.*?>', re.S).sub('', body)
                    body = re.sub('\s+', ' ', body)
                    body = body[:body.rfind(' ', 0, 250)][:250] + " ...<br />"
    except:
        pass

    cmt = {'title': source_page.title,
           'author': 'Pingback from %s' % source_page.title,
           'pubDate': str(time.time()),
           'link': source,
           'source': '',
           'description': body}

    # run anti-spam plugins
    argdict = {"request": request, "comment": cmt}
    reject = tools.run_callback("trackback_reject",
                                argdict,
                                donefunc=lambda x: x != 0)
    if isinstance(reject, (tuple, list)) and len(reject) == 2:
        reject_code, reject_message = reject
    else:
        reject_code, reject_message = reject, "Pingback rejected."
    if reject_code == 1:
        raise Fault(0x0031, reject_message)

    from comments import writeComment
    config = request.get_configuration()
    data = request.get_data()
    data['entry_list'] = [target_entry]

    # TODO: Check if comment from the URL exists
    writeComment(request, config, data, cmt, config['blog_encoding'])

    return "success pinging %s from %s\n" % (target, source)
Пример #13
0
                if context.opts.get('KojiDebug'):
                    if tb_type == "extended":
                        faultString = koji.format_exc_plus()
                    else:
                        faultString = tb_str
                else:
                    faultString = str(e)
            else:
                if tb_type == "normal":
                    faultString = tb_str
                elif tb_type == "extended":
                    faultString = koji.format_exc_plus()
                else:
                    faultString = "%s: %s" % (e_class, e)
            self.logger.warning(tb_str)
            response = dumps(Fault(faultCode, faultString))

        return response

    def handle_upload(self, environ):
        #uploads can't be in a multicall
        context.method = None
        self.check_session()
        self.enforce_lockout()
        return kojihub.handle_upload(environ)

    def handle_rpc(self, environ):
        params, method = self._read_request(environ['wsgi.input'])
        return self._dispatch(method, params)

    def check_session(self):
Пример #14
0
 def xmlrpc_return_fault():
     return Fault(666, "Fault description")
Пример #15
0
 def __init__(self, msg='Could not handle the exception'):
     Fault.__init__(self, UNHANDLED, msg)
Пример #16
0
 def __init__(self, value):
     Fault.__init__(self, XendClient.ERROR_GENERIC, value)
     self.value = value
Пример #17
0
 def __init__(self,message="Could not handle the query"):
     Fault.__init__(self,message="Access denied"):
Пример #18
0
def s3_upload(hashkey, size=ORIGINAL_SIZE):
    """
    Upload a screenshot PNG file to Amazon S3.

    This uses httplib directly and transfers the file in small chunks,
    so we don't have to load the whole PNG file into RAM.
    """

    from shotserver04.screenshots import s3
    aws = s3.AWSAuthConnection(settings.AWS_ACCESS_KEY_ID,
                               settings.AWS_SECRET_ACCESS_KEY,
                               is_secure=False)
    s3_bucket = settings.S3_BUCKETS[str(size)]
    s3_key = hashkey + '.png'
    server = s3.DEFAULT_HOST
    method = 'PUT'
    path = '/%s/%s' % (s3_bucket, urllib.quote_plus(s3_key))

    filename = png_filename(hashkey, size)
    f = file(filename, 'rb')
    f.seek(0, 2)  # os.SEEK_END for Python < 2.5
    bytes_total = f.tell()
    f.seek(0, 0)  # os.SEEK_SET for Python < 2.5

    headers = {
        'User-Agent': 'shotserver/0.4',
        'Host': server,
        'x-amz-acl': 'public-read',
        'Content-Type': 'image/png',
        'Content-Length': str(bytes_total),
    }
    query_args = {}
    aws._add_aws_auth_header(headers, method, s3_bucket, s3_key, query_args)

    host = '%s:%d' % (server, 80)
    conn = httplib.HTTPConnection(host)
    conn.putrequest(method, path)
    for header_key, header_value in headers.iteritems():
        conn.putheader(header_key, header_value)
    conn.endheaders()

    bytes_sent = 0
    while True:
        bytes = f.read(BUFFER_SIZE)
        if not bytes:
            break
        conn.send(bytes)
        bytes_sent += len(bytes)
        # print 'sent', bytes_sent, 'of', bytes_total, 'bytes',
        # print '(%.1f%%)' % (100.0 * bytes_sent / bytes_total)
    assert bytes_sent == bytes_total
    f.close()

    response = conn.getresponse()
    if response.status != 200:
        raise Fault(response.status, response.read())
    # print 'http://%s/%s' % (s3_bucket, s3_key)

    # Write response from S3 to tempfile for debugging
    if DEBUG_HEADERS and str(size) == '160':
        tempfile = file('/tmp/%s.txt' % hashkey, 'w')
        tempfile.write('==== Request headers ====\n')
        tempfile.write('%s %s HTTP/1.1\n' % (method, path))
        for header, value in headers.iteritems():
            tempfile.write('%s: %s\n' % (header, value))
        tempfile.write('\n')
        tempfile.write('==== Response headers ====\n')
        tempfile.write('HTTP/1.1 %s %s\n' % (response.status, response.reason))
        for header, value in response.getheaders():
            tempfile.write('%s: %s\n' % (header, value))
        tempfile.write('\n')
        tempfile.write(response.read())
        # tempfile.write(response.msg)
        tempfile.close()

    conn.close()
Пример #19
0
 def __init__(self, message):
     Fault.__init__(self, SADError.EMPTYSTREAM, message)
Пример #20
0
 def test_returning_Fault(self):
     return Fault(1, 'custom Fault response')
Пример #21
0
 def __init__(self, value):
     Fault.__init__(self, XendClient.ERROR_INVALID_DOMAIN, value)
Пример #22
0
 def shutdown(self):
     if self._restartable:
         self._shutdown = True
         return
     from supervisor import xmlrpc
     raise Fault(xmlrpc.Faults.SHUTDOWN_STATE, '')
Пример #23
0
 def __init__(self):
     Fault.__init__(self, PERMISSION_DENIED_CODE, _("Permission denied"))
Пример #24
0
 def readLog(self, whence, offset):
     if self._readlog_error:
         raise Fault(self._readlog_error, '')
     return 'mainlogdata'
Пример #25
0
Файл: rpc.py Проект: nictuku/nwu
 def __init__(self, message):
     Fault.__init__(self, RPCFault.NOT_FOUND, message)
Пример #26
0
def fault():
    raise Fault(123, "ERROR")
Пример #27
0
 def __init__(self, message = "Finish list all access files!"):
     Fault.__init__(self, FINISH_LIST_FILES, message)
Пример #28
0
def on_error(*args, **kwargs):
    body = str(sys.exc_info()[1])
    from xmlrpclib import Fault, dumps
    _set_response(dumps(Fault(1, body)))
Пример #29
0

def custom_commands_main(argv):
    """custom commands.main that handle errors using XMLError"""
    import bzrlib.ui
    bzrlib.ui.ui_factory = bzrlib.ui.make_ui_for_terminal(
        sys.stdin, sys.stdout, sys.stderr)
    try:
        _argv = []
        for a in argv[1:]:
            if isinstance(a, str):
                a = a.decode(bzrlib.osutils.get_user_encoding())
            _argv.append(a)
        argv = _argv
        ret = commands.run_bzr(argv)
        return ret
    except errors.BzrError, e:
        raise Fault(42, str(XMLError(e)))
    except Exception, e:
        traceback.print_exc(file=sys.__stderr__)
        raise Fault(32, str(XMLError(e)))


def register_functions(server):
    """register functions exposed via xmlrpc."""
    server.register_function(run_bzr, 'run_bzr_command')
    server.register_function(run_bzr_xml, 'run_bzr')
    import search
    if search.is_available:
        server.register_function(search.search, 'search')
Пример #30
0
 def clearProcessStdoutLog(self, name):
     from xmlrpclib import Fault
     from supervisor import xmlrpc
     if name == 'BAD_NAME':
         raise Fault(xmlrpc.Faults.BAD_NAME, 'BAD_NAME')
     return True
Пример #31
0
 def __init__(self, code, message, **extra):
     Fault.__init__(self, code, message, **extra)
     for key in extra:
         setattr(self, key, extra[key])
Пример #32
0
 def readLog(self, whence, offset):
     if self._readlog_error:
         from xmlrpclib import Fault
         raise Fault(self._readlog_error, '')
     return 'mainlogdata'
Пример #33
0
 def __init__(self, msg='Access denied'):
     Fault.__init__(self, ACCESS_DENIED, msg)
Пример #34
0
 def __init__(self,ACCESS_DENIED,message):
     Fault.__init__(self,ACCESS_DENIED,message)
Пример #35
0
 def __init__(self, value):
     Fault.__init__(self, ERROR_GENERIC, value)
     self.value = value
Пример #36
0
 def __init__(self, errorcode=UNHANDLED, message="Interrupt when handling the query"):
     Fault.__init__(self, errorcode, message)
Пример #37
0
 def __init__(self,message):
     Fault.__init__(self, SADError.FILENOTFOUND, message)
Пример #38
0
def createFault(error, message):
    error_code = INVERSE_FAULT_CODES[error]
    return Fault(error_code, message)
Пример #39
0
 def __init__(self, message):
     Fault.__init__(self, SADError.CLIENTDISCONNECTED, message)
Пример #40
0
 def getVersion():
     raise Fault(Faults.UNKNOWN_METHOD, 'duh')
Пример #41
0
 def __init__(self, message):
     Fault.__init__(self, SADError.CONNECTIONERROR, message)
Пример #42
0
 def getPages(cls, *args):
     """Returns a user-friendly error message."""
     raise Fault(501, 'Sorry, pages are not supported at this time.')
Пример #43
0
 def __init__(self, value):
     Fault.__init__(self, XendClient.ERROR_GENERIC, value)
     self.value = value
Пример #44
0
 def _some_nonexisting_method():
     """A non-existing method raising Fault"""
     raise Fault(0, 'Testing')
Пример #45
0
 def __init__(self):
     Fault.__init__(self, AUTHENTICATION_FAILED_CODE, _("Username and/or password is incorrect"))
Пример #46
0
def decode_fault(e, encoding='UTF-8'):
    assert isinstance(e, Fault)
    if isinstance(e.faultString, bytes):
        return Fault(e.faultCode, e.faultString.decode(encoding))
    return e
Пример #47
0
Файл: rpc.py Проект: nictuku/nwu
 def __init__(self, method_name):
     Fault.__init__(self, RPCFault.UNKNOWN_METHOD, method_name)
Пример #48
0
 def __init__(self, message="Couldn't handle the query"):
     Fault.__init__(self, UNHANDlED, message)
Пример #49
0
Файл: rpc.py Проект: nictuku/nwu
 def __init__(self, message):
     Fault.__init__(self, RPCFault.NOT_POSSIBLE, message)
Пример #50
0
 def __init__(self, message="Access denied"):
     Fault.__init__(self, ACCESS_DENIED, message)
Пример #51
0
Файл: rpc.py Проект: nictuku/nwu
 def __init__(self, method_name):
     Fault.__init__(self, RPCFault.INVALID_PARAMS, method_name)
Пример #52
0
 def test_non_auth_fault(self):
     return self.verify_auth_error(Fault("blah", "some random error"))
Пример #53
0
 def __init__(self, message = "Couldn't handle the query"):
     Fault.__init__(self, UNHANDLED, message)
Пример #54
0
	def __init__(self, message="Build Error."):
		Fault.__init__(self, 10, message)
Пример #55
0
 def __init__(self, message = "Access denied"):
     Fault.__init__(self, ACCESS_DENIED, message)
Пример #56
0
 def __init__(self):
     Fault.__init__(self, AUTHENTICATION_FAILED_CODE,
                    _('Username and/or password is incorrect'))