Python xml.parsers.expat.ExpatError() Examples

The following are 30 code examples of xml.parsers.expat.ExpatError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xml.parsers.expat , or try the search function .
Example #1
Source File: xmldump.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
def setOutputFile(self):
        '''
        Initiates the xml file from the configuration.
        '''
        if (conf.xmlFile):
            try:
                self._outputFile = conf.xmlFile
                self.__root = None

                if os.path.exists(self._outputFile):
                    try:
                        self.__doc = xml.dom.minidom.parse(self._outputFile)
                        self.__root = self.__doc.childNodes[0]
                    except ExpatError:
                        self.__doc = Document()

                self._outputFP = codecs.open(self._outputFile, "w+", UNICODE_ENCODING)

                if self.__root is None:
                    self.__root = self.__doc.createElementNS(NAME_SPACE_ATTR, RESULTS_ELEM_NAME)
                    self.__root.setAttributeNode(self._createAttribute(XMLNS_ATTR, NAME_SPACE_ATTR))
                    self.__root.setAttributeNode(self._createAttribute(SCHEME_NAME_ATTR, SCHEME_NAME))
                    self.__doc.appendChild(self.__root)
            except IOError:
                raise SqlmapFilePathException("Wrong filename provided for saving the xml file: %s" % conf.xmlFile) 
Example #2
Source File: download_center.py    From cvpysdk with Apache License 2.0 6 votes vote down vote up
def _get_properties(self):
        """Get the properties of the download center."""

        request_xml = """
        <App_DCGetDataToCreatePackageReq getListOfUsers="1"
            getListOfGroups="1" getCategories="1" getSubCategories="1"
            getPlatforms="1" getDownloadTypes="1" getProductVersions="1"
            getRecutNumbers="1" getVendors="1" getDownloadedPackageUsers="1"
            packageId="1" getServerTypes="1"/>
        """

        flag, response = self._cvpysdk_object.make_request(
            'POST', self._services['GET_DC_DATA'], request_xml
        )

        if flag:
            try:
                self._response = response.json()
            except ExpatError:
                raise SDKException('DownloadCenter', '101', response.text)
        else:
            response_string = self._update_response_(response.text)
            raise SDKException('Response', '101', response_string) 
Example #3
Source File: binding.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #4
Source File: binding.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = (response.body.read()).decode()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #5
Source File: binding.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #6
Source File: binding.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = (response.body.read()).decode()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #7
Source File: binding.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #8
Source File: automation.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
def convert_result(self, result):
        if self.conversion_method == "none" or "result" not in result:
            return result
        try:
            if self.conversion_method == "text":
                result["result"] = str(result["result"])
            elif self.conversion_method == "json":
                result["result"] = loads(result["result"])
            elif self.conversion_method == "xml":
                result["result"] = parse(result["result"])
        except (ExpatError, JSONDecodeError) as exc:
            result = {
                "success": False,
                "text_response": result,
                "error": f"Conversion to {self.conversion_method} failed",
                "exception": str(exc),
            }
        return result 
Example #9
Source File: dokuwiki.py    From python-dokuwiki with MIT License 6 votes vote down vote up
def set(self, page, content, **options):
        """Set/replace the *content* of *page*.

        Valid *options* are:

            * *sum*: (str) change summary
            * *minor*: (bool) whether this is a minor change
        """
        try:
            return self._dokuwiki.send('wiki.putPage', page, content, options)
        except ExpatError as err:
            # Sometime the first line of the XML response is blank which raise
            # the 'ExpatError' exception although the change has been done. This
            # allow to ignore the error.
            if str(err) != ERR:
                raise DokuWikiError(err) 
Example #10
Source File: binding.py    From SplunkForPCAP with MIT License 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #11
Source File: dokuwiki.py    From python-dokuwiki with MIT License 6 votes vote down vote up
def send(self, command, *args, **kwargs):
        """Generic method for executing an XML-RPC *command*. *args* and
        *kwargs* are the arguments and parameters needed by the command.
        """
        args = list(args)
        if kwargs:
            args.append(kwargs)

        method = self.proxy
        for elt in command.split('.'):
            method = getattr(method, elt)

        try:
            return method(*args)
        except Fault as err:
            if err.faultCode == 121:
                return {}
            elif err.faultCode == 321:
                return []
            raise DokuWikiError(err)
        except ExpatError as err:
            if str(err) != ERR:
                raise DokuWikiError(err) 
Example #12
Source File: serializer.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def _from_xml(self, datastring):
        if datastring is None:
            return None
        plurals = set(self.metadata.get('plurals', {}))
        try:
            node = etree.fromstring(datastring)
            root_tag = self._get_key(node.tag)
            links = self._get_links(root_tag, node)
            result = self._from_xml_node(node, plurals)
            if root_tag == constants.VIRTUAL_ROOT_KEY:
                return result
            return dict({root_tag: result}, **links)
        except Exception as e:
            parseError = False
            if (hasattr(etree, 'ParseError') and
                    isinstance(e, getattr(etree, 'ParseError'))):
                parseError = True
            elif isinstance(e, expat.ExpatError):
                parseError = True
            if parseError:
                msg = _("Cannot understand XML")
                raise exception.MalformedResponseBody(reason=msg)
            else:
                raise 
Example #13
Source File: xmlutil.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def readXML(xmlfile, expectedRootTag=None):
    """
    Read in XML data from a file and parse into ElementTree. Optionally verify
    the root node is what we expect.

    @param xmlfile: file to read from
    @type xmlfile: C{File}
    @param expectedRootTag: root tag (qname) to test or C{None}
    @type expectedRootTag: C{str}
    @return: C{tuple} of C{ElementTree}, C{Element}
    """

    # Read in XML
    try:
        etree = XML.ElementTree(file=xmlfile)
    except XMLParseError, e:
        raise ValueError("Unable to parse file '%s' because: %s" % (xmlfile, e,)) 
Example #14
Source File: binding.py    From SplunkAdmins with Apache License 2.0 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #15
Source File: installinstallmacos.py    From runMacOSinVirtualBox with MIT License 6 votes vote down vote up
def parse_server_metadata(filename):
    '''Parses a softwareupdate server metadata file, looking for information
    of interest.
    Returns a dictionary containing title, version, and description.'''
    title = ''
    vers = ''
    try:
        md_plist = read_plist(filename)
    except (OSError, IOError, ExpatError) as err:
        print('Error reading %s: %s' % (filename, err), file=sys.stderr)
        return {}
    vers = md_plist.get('CFBundleShortVersionString', '')
    localization = md_plist.get('localization', {})
    preferred_localization = (localization.get('English') or
                              localization.get('en'))
    if preferred_localization:
        title = preferred_localization.get('title', '')

    metadata = {}
    metadata['title'] = title
    metadata['version'] = vers
    return metadata 
Example #16
Source File: installinstallmacos.py    From runMacOSinVirtualBox with MIT License 6 votes vote down vote up
def make_sparse_image(volume_name, output_path):
    '''Make a sparse disk image we can install a product to'''
    cmd = ['/usr/bin/hdiutil', 'create', '-size', '16g', '-fs', 'HFS+',
           '-volname', volume_name, '-type', 'SPARSE', '-plist', output_path]
    try:
        output = subprocess.check_output(cmd)
    except subprocess.CalledProcessError as err:
        print(err, file=sys.stderr)
        exit(-1)
    try:
        return read_plist_from_string(output)[0]
    except IndexError as err:
        print('Unexpected output from hdiutil: %s' % output, file=sys.stderr)
        exit(-1)
    except ExpatError as err:
        print('Malformed output from hdiutil: %s' % output, file=sys.stderr)
        print(err, file=sys.stderr)
        exit(-1) 
Example #17
Source File: binding.py    From SplunkAdmins with Apache License 2.0 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #18
Source File: binding.py    From SA-ctf_scoreboard_admin with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def __init__(self, response, _message=None):
        status = response.status
        reason = response.reason
        body = response.body.read()
        try:
            detail = XML(body).findtext("./messages/msg")
        except ParseError as err:
            detail = body
        message = "HTTP %d %s%s" % (
            status, reason, "" if detail is None else " -- %s" % detail)
        Exception.__init__(self, _message or message)
        self.status = status
        self.reason = reason
        self.headers = response.headers
        self.body = body
        self._response = response 
Example #19
Source File: nfofile.py    From script.artwork.beef with MIT License 6 votes vote down vote up
def read_nfofile(filename):
    if not xbmcvfs.exists(filename):
        return None
    with closing(xbmcvfs.File(filename)) as nfofile:
        try:
            return ET.parse(nfofile).getroot()
        except ParseError:
            pass
        # maybe it's all XML except the last line, like the wiki suggests for XML + URL
        nfofile.seek(0, 0)
        lines = nfofile.read().split('\n')
        while lines and not lines[-1].strip():
            del lines[-1] # Remove final blank lines
        if lines: # Remove the line that possibly contains the URL
            del lines[-1]
        if lines:
            try:
                return ET.XML('\n'.join(lines))
            except ParseError:
                pass 
Example #20
Source File: briefcase_client.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _upload_instances(self, path):
        instances_count = 0
        dirs, not_in_use = default_storage.listdir(path)

        for instance_dir in dirs:
            instance_dir_path = os.path.join(path, instance_dir)
            i_dirs, files = default_storage.listdir(instance_dir_path)
            xml_file = None

            if 'submission.xml' in files:
                file_obj = default_storage.open(
                    os.path.join(instance_dir_path, 'submission.xml'))
                xml_file = file_obj

            if xml_file:
                try:
                    self._upload_instance(xml_file, instance_dir_path, files)
                except ExpatError:
                    continue
                except Exception:
                    pass
                else:
                    instances_count += 1

        return instances_count 
Example #21
Source File: plaso_xmlrpc.py    From plaso with Apache License 2.0 6 votes vote down vote up
def CallFunction(self):
    """Calls the function via RPC."""
    if self._xmlrpc_proxy is None:
      return None

    rpc_call = getattr(self._xmlrpc_proxy, self._RPC_FUNCTION_NAME, None)
    if rpc_call is None:
      return None

    try:
      return rpc_call()  # pylint: disable=not-callable
    except (
        expat.ExpatError, SocketServer.socket.error,
        xmlrpclib.Fault) as exception:
      logger.warning('Unable to make RPC call with error: {0!s}'.format(
          exception))
      return None 
Example #22
Source File: __init__.py    From wechatpy with MIT License 6 votes vote down vote up
def _handle_result(self, res):
        res.encoding = "utf-8-sig"
        xml = res.text
        logger.debug("Response from WeChat API \n %s", xml)
        try:
            data = xmltodict.parse(xml)["xml"]
        except (xmltodict.ParsingInterrupted, ExpatError):
            # 解析 XML 失败
            logger.debug("WeChat payment result xml parsing error", exc_info=True)
            return xml

        return_code = data["return_code"]
        return_msg = data.get("return_msg", data.get("retmsg"))
        result_code = data.get("result_code", data.get("retcode"))
        errcode = data.get("err_code")
        errmsg = data.get("err_code_des")
        if return_code != "SUCCESS" or result_code != "SUCCESS":
            # 返回状态码不为成功
            raise WeChatPayException(
                return_code, result_code, return_msg, errcode, errmsg, client=self, request=res.request, response=res,
            )
        return data 
Example #23
Source File: xmldump.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
def setOutputFile(self):
        '''
        Initiates the xml file from the configuration.
        '''
        if (conf.xmlFile):
            try:
                self._outputFile = conf.xmlFile
                self.__root = None

                if os.path.exists(self._outputFile):
                    try:
                        self.__doc = xml.dom.minidom.parse(self._outputFile)
                        self.__root = self.__doc.childNodes[0]
                    except ExpatError:
                        self.__doc = Document()

                self._outputFP = codecs.open(self._outputFile, "w+", UNICODE_ENCODING)

                if self.__root is None:
                    self.__root = self.__doc.createElementNS(NAME_SPACE_ATTR, RESULTS_ELEM_NAME)
                    self.__root.setAttributeNode(self._createAttribute(XMLNS_ATTR, NAME_SPACE_ATTR))
                    self.__root.setAttributeNode(self._createAttribute(SCHEME_NAME_ATTR, SCHEME_NAME))
                    self.__doc.appendChild(self.__root)
            except IOError:
                raise SqlmapFilePathException("Wrong filename provided for saving the xml file: %s" % conf.xmlFile) 
Example #24
Source File: roast_api.py    From roast.vim with MIT License 5 votes vote down vote up
def render_pretty(buf, response):
    blueprint = {'commands': ['call clearmatches()']}
    content_type = response.headers['content-type'].split(';')[0] if 'content-type' in response.headers else 'text/html'
    if content_type.endswith('/json'):
        try:
            blueprint['lines'] = json.dumps(response.json(), ensure_ascii=False, indent=2).splitlines()
        except json.JSONDecodeError:
            blueprint['commands'].append('set filetype=txt')
            blueprint['commands'].append('call matchaddpos("Error", range(1, line("$")))')
        else:
            blueprint['commands'].append('set filetype=json')

    elif content_type.endswith('/xml'):
        try:
            blueprint['lines'] = minidom.parseString(response.text).toprettyxml().splitlines()
        except ExpatError:
            blueprint['commands'].append('set filetype=txt')
            blueprint['commands'].append('call matchaddpos("Error", range(1, line("$")))')
        else:
            blueprint['commands'].append('set filetype=xml')

    elif content_type.endswith('/html'):
        blueprint['commands'].append('set filetype=html')

    if not blueprint.get('lines'):
        blueprint['lines'] = response.text.splitlines()

    return blueprint 
Example #25
Source File: test_pyexpat.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test2(self):
        # \xc2\x85 is UTF-8 encoded U+0085 (NEXT LINE)
        xml = b"<?xml version\xc2\x85='1.0'?>\r\n"
        parser = expat.ParserCreate()
        try:
            parser.Parse(xml, True)
            self.fail()
        except expat.ExpatError as e:
            self.assertEqual(str(e), 'XML declaration not well-formed: line 1, column 14') 
Example #26
Source File: test_pyexpat.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test1(self):
        xml = b"\0\r\n"
        parser = expat.ParserCreate()
        try:
            parser.Parse(xml, True)
            self.fail()
        except expat.ExpatError as e:
            self.assertEqual(str(e), 'unclosed token: line 2, column 0') 
Example #27
Source File: rbfkernelup.py    From rbf with GNU General Public License v2.0 5 votes vote down vote up
def getBoardDetailsFromTemplate():
    """Gets Board Name From /etc/rbf/board.xml"""
    try:
        boardDom = parse("/etc/rbf/board.xml")
        boardName = boardDom.getElementsByTagName("board")[0].firstChild.data
        linuxDistro = boardDom.getElementsByTagName("distro")[0].firstChild.data
        return (boardName, linuxDistro)
    except (ExpatError, IndexError):
        print("Bad Board Template")
        return ("generic", "Linux") 
Example #28
Source File: yin_parser.py    From pyang with ISC License 5 votes vote down vote up
def parse(self, ctx, ref, text):
        """Parse the string `text` containing a YIN (sub)module.

        Return a Statement on success or None on failure.
        """

        self.ctx = ctx
        self.pos = error.Position(ref)
        self.top = None
        self.top_element = None

        self.uri = None
        self.nsmap = {}
        self.prefixmap = {}
        self.included = []
        self.extensions = {}

        self.data = ''
        self.element_stack = []

        try:
            self.parser.Parse(text.encode('utf-8'), True)
        except error.Abort:
            return None
        except expat.ExpatError as ex:
            self.pos.line = ex.lineno
            error.err_add(self.ctx.errors, self.pos, 'SYNTAX_ERROR',
                          str(ex).split(":")[0])
            return None

        self.look_ahead()
        self.create_statement(self.top_element, None)
        return self.top 
Example #29
Source File: configuration.py    From appstart with Apache License 2.0 5 votes vote down vote up
def _init_from_xml_config(self, xml_config):
        """Initialize from an xml file.

        Args:
            xml_config: (basestring) The absolute path to an appengine-web.xml
                file.

        Raises:
            utils.AppstartAbort: If "<vm>true</vm>" is not set in the
                configuration.
        """
        try:
            root = xml.dom.minidom.parse(xml_config).firstChild
        except expat.ExpatError:
            raise utils.AppstartAbort('Malformed xml file: '
                                      '{0}'.format(xml_config))
        try:
            vm = root.getElementsByTagName('vm')[0]
            assert vm.firstChild.nodeValue == 'true'
        except (IndexError, AttributeError, AssertionError):
            raise utils.AppstartAbort(
                '"<vm>true</vm>" must be set in '
                '{0}'.format(os.path.basename(xml_config)))

        # Assume that health checks are enabled.
        self.health_checks_enabled = True
        health = root.getElementsByTagName('health-check')
        if health:
            checks = health[0].getElementsByTagName('enable-health-check')
            if checks:
                value = checks[0].firstChild
                if value and value.nodeValue != 'true':
                    self.health_checks_enabled = False 
Example #30
Source File: svnwc.py    From scylla with Apache License 2.0 5 votes vote down vote up
def log(self, rev_start=None, rev_end=1, verbose=False):
        """ return a list of LogEntry instances for this path.
rev_start is the starting revision (defaulting to the first one).
rev_end is the last revision (defaulting to HEAD).
if verbose is True, then the LogEntry instances also know which files changed.
"""
        assert self.check()   # make it simpler for the pipe
        rev_start = rev_start is None and "HEAD" or rev_start
        rev_end = rev_end is None and "HEAD" or rev_end
        if rev_start == "HEAD" and rev_end == 1:
                rev_opt = ""
        else:
            rev_opt = "-r %s:%s" % (rev_start, rev_end)
        verbose_opt = verbose and "-v" or ""
        locale_env = fixlocale()
        # some blather on stderr
        auth_opt = self._makeauthoptions()
        #stdin, stdout, stderr  = os.popen3(locale_env +
        #                                   'svn log --xml %s %s %s "%s"' % (
        #                                    rev_opt, verbose_opt, auth_opt,
        #                                    self.strpath))
        cmd = locale_env + 'svn log --xml %s %s %s "%s"' % (
            rev_opt, verbose_opt, auth_opt, self.strpath)

        popen = subprocess.Popen(cmd,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    shell=True,
        )
        stdout, stderr = popen.communicate()
        stdout = py.builtin._totext(stdout, sys.getdefaultencoding())
        minidom,ExpatError = importxml()
        try:
            tree = minidom.parseString(stdout)
        except ExpatError:
            raise ValueError('no such revision')
        result = []
        for logentry in filter(None, tree.firstChild.childNodes):
            if logentry.nodeType == logentry.ELEMENT_NODE:
                result.append(LogEntry(logentry))
        return result