def raiseError(self, err): info = err.args[0] message = toUnicode(info['desc']) if 'info' in info: message += u"; %s" % toUnicode(info['info']) if 'matched' in info: matched = toUnicode(info['matched']) message += u" (%s)" % matched raise RulesetError(tr("LDAP error: %s"), message)
def create(self, conf, logger): dbtype = conf['dbtype'] try: db_object = self.objects[dbtype] if isinstance(db_object, (str, unicode)): raise DatabaseError(tr('Unable to use %s: %s'), dbtype, toUnicode(db_object)) except KeyError, e: raise DatabaseError(tr('Unsupported database type %s'), dbtype)
def exceptionAsUnicode(err, add_type=True): r""" add_type option changes the output for KeyError and exception with an empty message (eg. AssertionError). If the option is True (default): add the type as prefix, otherwise return an empty string. >>> exceptionAsUnicode(Exception("ascii")) u'ascii' >>> exceptionAsUnicode(Exception("h\xe9 h\xe9")) u'h\xe9 h\xe9' >>> exceptionAsUnicode(UnicodeException(u"h\xe9 h\xe9")) u'h\xe9 h\xe9' >>> exceptionAsUnicode(AssertionError()) u'[AssertionError]' >>> exceptionAsUnicode(KeyError(3)) u'[KeyError] 3' >>> exceptionAsUnicode(KeyError(3), False) u'3' """ if isinstance(err, (IOError, OSError)) and err.strerror: # Get "message" instead of "(42, 'message')" return toUnicode(err.strerror) if isinstance(err, socket_error): # Get 'Connexion refus\xc3\xa9e' instead of # (111, 'Connexion refus\xc3\xa9e') args = err.args if 2 <= len(args): msg = args[1] else: msg = args[0] return toUnicode(msg) try: text = unicode(err) except (UnicodeDecodeError, UnicodeEncodeError): as_bytes = str(err) text = toUnicode(as_bytes) if add_type: if isinstance(err, KeyError): # KeyError message is the key, which is usually meaningless: # add [KeyError] prefix text = u"[%s] %s" % (err.__class__.__name__, text) elif not text: # Some errors (eg. AssertionError) have no text, so display the # exception type instead of an empty string text = u"[%s]" % err.__class__.__name__ return text
def _parseGroup(self): groups = set() with open('/etc/group') as fp: for line in fp.readlines(): line = line.rstrip() name = line.split(':')[0] name = toUnicode(name) groups.add(name) return groups
def formatTraceback(traceback): if not isinstance(traceback, str): traceback = format_exception(*traceback) if traceback == ["None\n"]: return None traceback = ''.join(traceback) traceback = traceback.rstrip() lines = traceback.splitlines() return [toUnicode(line) for line in lines]
def __init__(self, *arguments, **keywords): if isinstance(arguments[0], (str, unicode)): # Old API: raise UnicodeException("error: %s", err) # deprecationWarning( # "UnicodeException(format, arguments): " # "missing application, component and error code", # 3) self.application = 0 self.component = 0 self.error_code = 0 message = arguments[0] arguments = arguments[1:] else: # New API: UnicodeException(app, component, ...) self.application = arguments[0] self.component = arguments[1] if isinstance(arguments[2], (str, unicode)): # UnicodeException(app, component, "format", ...): missing code # deprecationWarning( # "UnicodeException(application, component, format, arguments): " # "missing error code", # 4) self.error_code = 0 message = arguments[2] arguments = arguments[3:] else: # UnicodeException(app, component, errcode, "format", ...): correct self.error_code = arguments[2] message = arguments[3] arguments = arguments[4:] self.additionals = [] # Check arguments / keywords if arguments and keywords: self.additionals.append( u"You can not use arguments *and* keywords with UnicodeException!") arguments = None keywords = None # Convert message to Unicode self.unicode_message = toUnicode(message) self.format = self.unicode_message # Make sure that arguments are serialisable, if no convert them to # serialisable type if keywords: for key, value in keywords.iteritems(): try: checkSimpleType(value) except TransportError, err: keywords[key] = self.formatArgument(value) self.additionals.append( u"The keyword argument %r is unserializable: %s" % (key, err))
def resolveHostname(self): if self.address_type == IPV6_ADDRESS: family = AF_INET6 else: family = AF_INET addresses = set() try: for family, socktype, proto, canonname, sockaddr in getaddrinfo(self.hostname, None, family): address = parseIPAddress(sockaddr[0]) addresses.add(address) except gaierror, err: message = toUnicode(err.args[1]) raise RulesetError(tr('Unable to get the address of the hostname "%s": %s!'), self.hostname, message)
def __init__(self, type, message, traceback=None, err_id=None): """id : (application, component, code)""" if message: message = toUnicode(message) else: message = u"[%s]" % type UnicodeException.__init__(self, message) self.type = type self.traceback = traceback if err_id: self.id = err_id else: self.id = (None, None, None) self.application, self.component, self.code = self.id
def success_download(self, value): self._stop_splash() encoded, components = value self.mainwindow.addToInfoArea(tr("Downloaded EdenWall configuration")) extension = "*.tar.gz" archive_description = tr("Edenwall archive file") filter = "%s (%s)" % (archive_description, extension) date = datetime.now().strftime("%c") date = toUnicode(date) date = date.replace(".", "") date = date.replace(" ", "_") date = date.replace(":", "-") host = self.mainwindow.client.host host = host.replace(".", "_") host = host.replace(":", "-") suggestion = u"edenwall-config-%s-%s.tar.gz" % (host, date) filename = QFileDialog.getSaveFileName( self, tr("Choose a filename to save under"), join(SaveRestoreWidget.last_save_position, suggestion), filter ) filename = unicode(filename) if not filename: self.mainwindow.addToInfoArea(tr("EdenWall configuration save cancelled")) return SaveRestoreWidget.last_save_position = split(filename)[0] try: with open(filename, "wb") as fd: fd.write(decodeFileContent(encoded)) except IOError, err: message_vars = (tr("An error occured while saving EdenWall configuration:"), toUnicode(strerror(err.errno))) text_message = "%s\n%s" % message_vars self.mainwindow.addToInfoArea(text_message, category=COLOR_ERROR) html_message = "<span>%s<br/><b>%s</b></span>" % message_vars QMessageBox.critical(self, tr("Save error"), html_message) return
def formatArgument(self, value): # Try as unicode characters try: text = unicode(value) checkSimpleType(text) return text except (UnicodeError, TransportError): pass # Try as byte string and then reconvert to Unicode try: text = str(value) text = toUnicode(text) checkSimpleType(text) return text except TransportError: pass # Last chance: replace the value return u"[ERROR]"
def getIP(addr, address_type): try: addr = IP(addr) except ValueError: pass else: return set((addr,)) if address_type == IPV6_ADDRESS: family = AF_INET6 else: family = AF_INET addresses = set() try: for family2, socktype, proto, canonname, sockaddr \ in getaddrinfo(addr, None, family): address = IP(unicode(sockaddr[0])) addresses.add(address) except gaierror, gai_err: raise LocalFWError( tr('Unable to get the "%s" host address: %s'), unicode(addr), toUnicode(gai_err.args[1]))
def __init__(self, message): self.unicode_message = toUnicode(message) bytes_message = self.unicode_message.encode("ASCII", "replace") Exception.__init__(self, bytes_message)
def setUsePKI(self, value): if value: self.use_pki = toUnicode(value) else: self.use_pki = u''