Python defusedxml.ElementTree.fromstring() Examples

The following are 30 code examples of defusedxml.ElementTree.fromstring(). 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 defusedxml.ElementTree , or try the search function .
Example #1
Source File: oob.py    From drydock with Apache License 2.0 6 votes vote down vote up
def set_node_pxe(self, node):
        """Set a node to PXE boot first."""
        ses = self.init_session(node)
        domain = ses.lookupByName(node.name)
        domain_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_SECURE
                                    | libvirt.VIR_DOMAIN_XML_INACTIVE)
        xmltree = ET.fromstring(domain_xml)

        # Delete all the current boot entries
        os_tree = xmltree.find("./os")
        boot_elements = os_tree.findall("./boot")
        for e in boot_elements:
            os_tree.remove(e)

        # Now apply our boot order which is 'network' and then 'hd'
        os_tree.append(ET.fromstring("<boot dev='network' />"))
        os_tree.append(ET.fromstring("<boot dev='hd' />"))

        # And now save the new XML def to the hypervisor
        domain_xml = ET.tostring(xmltree, encoding="utf-8")
        ses.defineXML(domain_xml.decode('utf-8'))
        ses.close() 
Example #2
Source File: podaac_test.py    From podaacpy with Apache License 2.0 6 votes vote down vote up
def test_dataset_metadata(self):
        dataset_id = 'PODAAC-CCF35-01AD5'
        dataset_short_name = 'CCMP_MEASURES_ATLAS_L4_OW_L3_5A_5DAY_WIND_VECTORS_FLK'
        dataset_md = self.podaac.dataset_metadata(
            dataset_id, dataset_short_name)
        root = ET.fromstring(dataset_md.encode('utf-8'))
        short_name = root[1][0].attrib

        assert dataset_md is not None
        assert str(short_name['id']) == dataset_short_name
        assert_raises(requests.exceptions.HTTPError,
                      self.podaac.dataset_metadata,
                      'PODAAC-CCF35-01AD5',
                      'CCMP_MEASURES_ATLAS_L4_OW_L3_5A_5DAY_WIND_VECTORS_FLK',
                      'is')
        assert_raises(Exception, self.podaac.dataset_metadata,
                      short_name='CCMP_MEASURES_ATLAS_L4_OW_L3_5A_5DAY_WIND_VECTORS_FLK')

    # test case for the fucntion granule_metadata() 
Example #3
Source File: podaac_utils.py    From podaacpy with Apache License 2.0 6 votes vote down vote up
def list_level4_dataset_short_names(self):
        '''Convenience function which returns an up-to-date \
                list of level4 dataset short names.

        :returns: a comma-seperated list of level4 dataset short names.

        '''
        podaac = p.Podaac()
        data = podaac.dataset_search(process_level='4', items_per_page='400')
        l4_dataset_short_names = []
        root = ET.fromstring(data.encode('utf-8'))

        for entry in root.findall('{http://www.w3.org/2005/Atom}entry'):
            l4_dataset_short_name = entry.find(
                '{https://podaac.jpl.nasa.gov/opensearch/}shortName').text
            l4_dataset_short_names.append(l4_dataset_short_name)

        return l4_dataset_short_names 
Example #4
Source File: podaac_utils.py    From podaacpy with Apache License 2.0 6 votes vote down vote up
def list_level4_dataset_ids(self):
        '''Convenience function which returns an up-to-date \
                list of level4 dataset id's.

        :returns: a comma-seperated list of level4 dataset id's

        '''
        podaac = p.Podaac()
        data = podaac.dataset_search(process_level='4', items_per_page='400')
        root = ET.fromstring(data.encode('utf-8'))

        dataset_ids = []
        for entry in root.findall('{http://www.w3.org/2005/Atom}entry'):
            dataset_id = entry.find(
                '{https://podaac.jpl.nasa.gov/opensearch/}datasetId').text
            dataset_ids.append(dataset_id)

        return dataset_ids 
Example #5
Source File: podaac_test.py    From podaacpy with Apache License 2.0 6 votes vote down vote up
def test_last24hours_datacasting_granule_md(self):
        dataset_id = 'PODAAC-ASOP2-25X01'
        dataset_short_name = 'ASCATA-L2-25km'
        _format = 'datacasting'
        items_per_page = 10
        granule_md = self.podaac.last24hours_datacasting_granule_md(
            dataset_id, dataset_short_name, _format, items_per_page)
        root = ET.fromstring(granule_md.encode('utf-8'))
        dataset_id_ = root[0][3].text

        assert granule_md is not None
        assert dataset_id_ == dataset_id
        assert_raises(requests.exceptions.HTTPError,
                      self.podaac.last24hours_datacasting_granule_md,
                      'PODAAC-ASOP2-25X01', 'ASCATA-L2-25km', _format='iso')
        assert_raises(Exception, self.podaac.last24hours_datacasting_granule_md,
                      short_name='ASCATA-L2-25km', _format='iso')

    # test case for the function dataset_variables 
Example #6
Source File: utils.py    From bugzilla2gitlab with MIT License 6 votes vote down vote up
def get_bugzilla_bug(bugzilla_url, bug_id):
    '''
    Read bug XML, return all fields and values in a dictionary.
    '''
    bug_xml = _fetch_bug_content(bugzilla_url, bug_id)
    tree = ElementTree.fromstring(bug_xml)

    bug_fields = {
        "long_desc": [],
        "attachment": [],
        "cc": [],
    }
    for bug in tree:
        for field in bug:
            if field.tag in ("long_desc", "attachment"):
                new = {}
                for data in field:
                    new[data.tag] = data.text
                bug_fields[field.tag].append(new)
            elif field.tag == "cc":
                bug_fields[field.tag].append(field.text)
            else:
                bug_fields[field.tag] = field.text

    return bug_fields 
Example #7
Source File: oxml.py    From plaso with Apache License 2.0 6 votes vote down vote up
def _ParseRelationshipsXMLFile(self, xml_data):
    """Parses the relationships XML file (_rels/.rels).

    Args:
      xml_data (bytes): data of a _rels/.rels XML file.

    Returns:
      list[str]: property file paths. The path is relative to the root of
          the ZIP file.

    Raises:
      zipfile.BadZipfile: if the relationship XML file cannot be read.
    """
    xml_root = ElementTree.fromstring(xml_data)

    property_files = []
    for xml_element in xml_root.iter():
      type_attribute = xml_element.get('Type')
      if 'properties' in repr(type_attribute):
        target_attribute = xml_element.get('Target')
        property_files.append(target_attribute)

    return property_files 
Example #8
Source File: client.py    From jira with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def backup_progress(self):
        """Return status of cloud backup as a dict.

        Is there a way to get progress for Server version?
        """
        epoch_time = int(time.time() * 1000)
        if self.deploymentType == "Cloud":
            url = (
                self._options["server"] + "/rest/obm/1.0/getprogress?_=%i" % epoch_time
            )
        else:
            logging.warning("This functionality is not available in Server version")
            return None
        r = self._session.get(url, headers=self._options["headers"])
        # This is weird.  I used to get xml, but now I'm getting json
        try:
            return json.loads(r.text)
        except Exception:
            import defusedxml.ElementTree as etree

            progress = {}
            try:
                root = etree.fromstring(r.text)
            except etree.ParseError as pe:
                logging.warning(
                    "Unable to find backup info.  You probably need to initiate a new backup. %s"
                    % pe
                )
                return None
            for k in root.keys():
                progress[k] = root.get(k)
            return progress 
Example #9
Source File: test_server.py    From query-server with Apache License 2.0 6 votes vote down vote up
def get_json_equivalent_from_xml_feed(feed):
    def internal_iter(tree, accum):
        if tree is None:
            return accum

        if tree.getchildren():
            accum[tree.tag] = {}
            for each in tree.getchildren():
                result = internal_iter(each, {})
                if each.tag in accum[tree.tag]:
                    if not isinstance(accum[tree.tag][each.tag], list):
                        accum[tree.tag][each.tag] = [
                            accum[tree.tag][each.tag]
                        ]
                    accum[tree.tag][each.tag].append(result[each.tag])
                else:
                    accum[tree.tag].update(result)
        else:
            accum[tree.tag] = tree.text

        return accum

    return internal_iter(ElementTree.fromstring(feed), {}) 
Example #10
Source File: node.py    From drydock with Apache License 2.0 5 votes vote down vote up
def apply_logicalnames(self, site_design, state_manager):
        """Gets the logicalnames for devices from lshw.

        :param site_design: SiteDesign object.
        :param state_manager: DrydockState object.
        :return: Returns sets a dictionary of aliases that map to logicalnames in self.logicalnames.
        """
        logicalnames = {}

        results = state_manager.get_build_data(
            node_name=self.get_name(), latest=True)
        xml_data = None
        for result in results:
            if result.generator == "lshw":
                xml_data = result.data_element
                break

        if xml_data:
            xml_root = fromstring(xml_data)
            for hardware_profile in site_design.hardware_profiles:
                for device in hardware_profile.devices:
                    logicalname = self._apply_logicalname(
                        xml_root, device.alias, device.bus_type,
                        device.address)
                    logicalnames[device.alias] = logicalname
        else:
            self.logger.info("No Build Data found for node_name %s" %
                             (self.get_name()))

        self.logicalnames = logicalnames 
Example #11
Source File: peba.py    From PEBA with GNU General Public License v3.0 5 votes vote down vote up
def authentication_required(f):
    """ This login decorator verifies that the correct username
        and password are sent over POST in the XML format.
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):
        postdata = request.data.decode('utf-8')

        if len(postdata) == 0:
            app.logger.error('Authentication: No xml post data in request')
            return abort(403)
        else:
            root = ETdefused.fromstring(postdata)
            user_data = root.find("./Authentication/username")
            pass_data = root.find("./Authentication/token")

            if user_data is None or pass_data is None:
                app.logger.error('Authentication: Invalid XML, token not present or empty')
                return abort(403)

            username = user_data.text
            password = pass_data.text

            if not authenticate(username, password):
                app.logger.error("Authentication failure for user %s", username)
                return abort(403)

            return f(*args, **kwargs)
    return decorated_function 
Example #12
Source File: scores.py    From sports.py with MIT License 5 votes vote down vote up
def _load_xml(xml_data):
    """
    Parse XML file containing match details using ElementTree

    :param xml_data: Data containing match info for a specific sport
    :type xml_data: string
    :return: ElementTree instance containing data from XML file
    :rtype: ElementTree instance
    """
    return ET.fromstring(xml_data).find('channel').findall('item') 
Example #13
Source File: peba.py    From PEBA with GNU General Public License v3.0 5 votes vote down vote up
def checkCommunityUser():
    """ Checks if community credentials are used
    """
    postdata = request.data.decode('utf-8')

    if len(postdata) == 0:
        app.logger.error('no xml post data in request')
        return abort(403)
    else:
        root = ETdefused.fromstring(postdata)
        user_data = root.find("./Authentication/username")
        pass_data = root.find("./Authentication/token")

        if user_data is None or pass_data is None:
            app.logger.error('Invalid XML: token not present or empty')
            return abort(403)

        username = user_data.text
        password = pass_data.text

        if username == app.config['COMMUNITYUSER'] and password == app.config['COMMUNITYTOKEN']:
            return True

        if not authenticate(username, password):
            app.logger.error("simplePostMessage-Authentication failure for user %s", username)
            return abort(403)

        return False 
Example #14
Source File: putservice.py    From PEBA with GNU General Public License v3.0 5 votes vote down vote up
def checkPostData(postrequest):
    """check if postdata is XML"""
    postdata = postrequest.decode('utf-8')
    try:
        return ETdefused.fromstring(postdata)
    except ETdefused.ParseError:
        app.logger.error('Invalid XML in post request')
        return False 
Example #15
Source File: message_processor.py    From symphony-api-client-python with MIT License 5 votes vote down vote up
def process(self, msg):
        msg_xml = msg['message']
        msg_root = ET.fromstring(msg_xml)
        msg_txt = msg_root[0].text

        if '/bot' in msg_txt and 'joke' in msg_txt:
            joke_client = JokeClient(self.bot_client)
            stream_id = msg['stream']['streamId']
            joke_client.send_joke(stream_id) 
Example #16
Source File: import_music_from_lastfm_xml.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def main(self):
        import requests
        from defusedxml import ElementTree

        response = requests.get(self.API_URL, params=self.params)
        if response.status_code != requests.codes.ok:
            self.stderr.write(f"Error connecting to {response.url}")
            return
        root = ElementTree.fromstring(response.content)

        pages = int(root.find("tracks").attrib.get("totalPages", 1))
        if self.max_pages > 0:
            pages = min(pages, self.max_pages)

        if self.verbosity >= self.NORMAL:
            self.stdout.write(f"=== Importing {pages} page(s) of songs ===")

        self.save_page(root)

        for page_number in range(2, pages + 1):
            self.params["page"] = page_number
            response = requests.get(self.API_URL, params=self.params)
            if response.status_code != requests.codes.ok:
                self.stderr.write(f"Error connecting to {response.url}")
                return
            root = ElementTree.fromstring(response.content)
            self.save_page(root) 
Example #17
Source File: scout_requests.py    From scout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fetch_refseq_version(refseq_acc):
    """Fetch refseq version from entrez and return refseq version

    Args:
        refseq_acc(str) example: NM_020533

    Returns
        version(str) example: NM_020533.3 or NM_020533 if no version associated is found
    """
    version = refseq_acc
    base_url = (
        "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=nuccore&"
        "term={}&idtype=acc"
    )

    try:
        resp = get_request(base_url.format(refseq_acc))
        tree = ElementTree.fromstring(resp.content)
        version = tree.find("IdList").find("Id").text or version

    except (
        requests.exceptions.HTTPError,
        requests.exceptions.MissingSchema,
        AttributeError,
    ):
        LOG.warning("refseq accession not found")

    return version 
Example #18
Source File: __init__.py    From python-connect-box with MIT License 5 votes vote down vote up
def async_get_downstream(self):
        """Get the current downstream cable modem state."""
        if self.token is None:
            await self.async_initialize_token()

        self.ds_channels.clear()
        raw = await self._async_ws_get_function(CMD_DOWNSTREAM)

        try:
            xml_root = element_tree.fromstring(raw)
            for downstream in xml_root.iter("downstream"):
                self.ds_channels.append(
                    DownstreamChannel(
                        int(downstream.find("freq").text),
                        int(downstream.find("pow").text),
                        downstream.find("mod").text,
                        downstream.find("chid").text,
                        float(downstream.find("RxMER").text),
                        int(downstream.find("PreRs").text),
                        int(downstream.find("PostRs").text),
                        downstream.find("IsQamLocked").text == "1",
                        downstream.find("IsFECLocked").text == "1",
                        downstream.find("IsMpegLocked").text == "1",
                    )
                )
        except (element_tree.ParseError, TypeError):
            _LOGGER.warning("Can't read downstream channels from %s", self.host)
            self.token = None
            raise exceptions.ConnectBoxNoDataAvailable() from None 
Example #19
Source File: __init__.py    From python-connect-box with MIT License 5 votes vote down vote up
def async_get_upstream(self):
        """Get the current upstream cable modem state."""
        if self.token is None:
            await self.async_initialize_token()

        self.us_channels.clear()
        raw = await self._async_ws_get_function(CMD_UPSTREAM)

        try:
            xml_root = element_tree.fromstring(raw)
            for upstream in xml_root.iter("upstream"):
                self.us_channels.append(
                    UpstreamChannel(
                        int(upstream.find("freq").text),
                        int(upstream.find("power").text),
                        upstream.find("srate").text,
                        upstream.find("usid").text,
                        upstream.find("mod").text,
                        upstream.find("ustype").text,
                        int(upstream.find("t1Timeouts").text),
                        int(upstream.find("t2Timeouts").text),
                        int(upstream.find("t3Timeouts").text),
                        int(upstream.find("t4Timeouts").text),
                        upstream.find("channeltype").text,
                        int(upstream.find("messageType").text),
                    )
                )
        except (element_tree.ParseError, TypeError):
            _LOGGER.warning("Can't read upstream channels from %s", self.host)
            self.token = None
            raise exceptions.ConnectBoxNoDataAvailable() from None 
Example #20
Source File: __init__.py    From python-connect-box with MIT License 5 votes vote down vote up
def async_get_ipv6_filtering(self) -> None:
        """Get the current ipv6 filter (and filters time) rules."""
        if self.token is None:
            await self.async_initialize_token()

        self.ipv6_filters.clear()
        self._ipv6_filters_time = None
        raw = await self._async_ws_get_function(CMD_GET_IPV6_FILTER_RULE)

        try:
            xml_root = element_tree.fromstring(raw)
            for instance in xml_root.iter("instance"):
                self.ipv6_filters.append(
                    Ipv6FilterInstance(
                        int(instance.find("idd").text),
                        instance.find("src_addr").text,
                        int(instance.find("src_prefix").text),
                        instance.find("dst_addr").text,
                        int(instance.find("dst_prefix").text),
                        int(instance.find("src_sport").text),
                        int(instance.find("src_eport").text),
                        int(instance.find("dst_sport").text),
                        int(instance.find("dst_eport").text),
                        int(instance.find("protocol").text),
                        int(instance.find("allow").text),
                        int(instance.find("enabled").text),
                    )
                )

            self._ipv6_filters_time = FiltersTimeMode(
                int(xml_root.find("time_mode").text),
                _parse_general_time(xml_root),
                _parse_daily_time(xml_root)
            )

        except (element_tree.ParseError, TypeError):
            _LOGGER.warning("Can't read IPv6 filter rules from %s", self.host)
            self.token = None
            raise exceptions.ConnectBoxNoDataAvailable() from None 
Example #21
Source File: doc.py    From Greynir with GNU General Public License v3.0 5 votes vote down vote up
def extract_text(self):

        zipfile = ZipFile(BytesIO(self.data), "r")

        # Verify that archive contains document.xml
        if self.DOCXML_PATH not in zipfile.namelist():
            raise MalformedDocumentError("Malformed docx file")

        # Read xml file from archive
        content = zipfile.read(self.DOCXML_PATH)
        zipfile.close()

        # Parse it
        tree = ElementTree.fromstring(content)

        # Extract text elements from all paragraphs
        # (with special handling of line breaks)
        paragraphs = []
        for p in tree.iter(self.PARAGRAPH_TAG):
            texts = []
            for node in p.iter():
                if node.tag.endswith(self.TEXT_TAG) and node.text:
                    texts.append(node.text)
                elif node.tag.endswith(self.BREAK_TAG):
                    texts.append("\n")
            if texts:
                paragraphs.append("".join(texts))

        return "\n\n".join(paragraphs)


# Map file mime type to document class 
Example #22
Source File: import_music_from_lastfm_xml.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def main(self):
        import requests
        from defusedxml import ElementTree

        response = requests.get(self.API_URL, params=self.params)
        if response.status_code != requests.codes.ok:
            self.stderr.write(f"Error connecting to {response.url}")
            return
        root = ElementTree.fromstring(response.content)

        pages = int(root.find("tracks").attrib.get("totalPages", 1))
        if self.max_pages > 0:
            pages = min(pages, self.max_pages)

        if self.verbosity >= self.NORMAL:
            self.stdout.write(f"=== Importing {pages} page(s) of songs ===")

        self.save_page(root)

        for page_number in range(2, pages + 1):
            self.params["page"] = page_number
            response = requests.get(self.API_URL, params=self.params)
            if response.status_code != requests.codes.ok:
                self.stderr.write(f"Error connecting to {response.url}")
                return
            root = ElementTree.fromstring(response.content)
            self.save_page(root) 
Example #23
Source File: import_music_from_lastfm_xml.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def main(self):
        import requests
        from defusedxml import ElementTree

        response = requests.get(self.API_URL, params=self.params)
        if response.status_code != requests.codes.ok:
            self.stderr.write(f"Error connecting to {response.url}")
            return
        root = ElementTree.fromstring(response.content)

        pages = int(root.find("tracks").attrib.get("totalPages", 1))
        if self.max_pages > 0:
            pages = min(pages, self.max_pages)

        if self.verbosity >= self.NORMAL:
            self.stdout.write(f"=== Importing {pages} page(s) of songs ===")

        self.save_page(root)

        for page_number in range(2, pages + 1):
            self.params["page"] = page_number
            response = requests.get(self.API_URL, params=self.params)
            if response.status_code != requests.codes.ok:
                self.stderr.write(f"Error connecting to {response.url}")
                return
            root = ElementTree.fromstring(response.content)
            self.save_page(root) 
Example #24
Source File: import_music_from_lastfm_xml.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def main(self):
        import requests
        from defusedxml import ElementTree

        response = requests.get(self.API_URL, params=self.params)
        if response.status_code != requests.codes.ok:
            self.stderr.write(f"Error connecting to {response.url}")
            return
        root = ElementTree.fromstring(response.content)

        pages = int(root.find("tracks").attrib.get("totalPages", 1))
        if self.max_pages > 0:
            pages = min(pages, self.max_pages)

        if self.verbosity >= self.NORMAL:
            self.stdout.write(f"=== Importing {pages} page(s) of songs ===")

        self.save_page(root)

        for page_number in range(2, pages + 1):
            self.params["page"] = page_number
            response = requests.get(self.API_URL, params=self.params)
            if response.status_code != requests.codes.ok:
                self.stderr.write(f"Error connecting to {response.url}")
                return
            root = ElementTree.fromstring(response.content)
            self.save_page(root) 
Example #25
Source File: node.py    From drydock with Apache License 2.0 5 votes vote down vote up
def apply_logicalnames(self, site_design, state_manager):
        """Gets the logicalnames for devices from lshw.

        :param site_design: SiteDesign object.
        :param state_manager: DrydockState object.
        :return: Returns sets a dictionary of aliases that map to logicalnames in self.logicalnames.
        """
        logicalnames = {}

        results = state_manager.get_build_data(
            node_name=self.get_name(), latest=True)
        xml_data = None
        for result in results:
            if result.generator == "lshw":
                xml_data = result.data_element
                break

        if xml_data:
            xml_root = fromstring(xml_data)
            try:
                hardware_profile = site_design.get_hardware_profile(
                    self.hardware_profile)
                for device in hardware_profile.devices:
                    logicalname = self._apply_logicalname(
                        xml_root, device.alias, device.bus_type,
                        device.address)
                    logicalnames[device.alias] = logicalname
            except errors.DesignError:
                self.logger.exception(
                    "Failed to load hardware profile while "
                    "resolving logical names for node %s", self.get_name())
                raise
        else:
            self.logger.info(
                "No Build Data found for node_name %s" % (self.get_name()))

        self.logicalnames = logicalnames 
Example #26
Source File: tests.py    From python-otrs with GNU General Public License v3.0 5 votes vote down vote up
def test_ticket_from_xml(self):
        xml = etree.fromstring(SAMPLE_TICKET)
        t = Ticket.from_xml(xml)
        self.assertEqual(t.TicketID, 32)
        self.assertEqual(t.CustomerUserID, 'foo@bar.tld') 
Example #27
Source File: oxml.py    From plaso with Apache License 2.0 5 votes vote down vote up
def _ParsePropertiesXMLFile(self, xml_data):
    """Parses a properties XML file.

    Args:
      xml_data (bytes): data of a _rels/.rels XML file.

    Returns:
      dict[str, object]: properties.

    Raises:
      zipfile.BadZipfile: if the properties XML file cannot be read.
    """
    xml_root = ElementTree.fromstring(xml_data)

    properties = {}
    for xml_element in xml_root.iter():
      if not xml_element.text:
        continue

      # The property name is formatted as: {URL}name
      # For example: {http://purl.org/dc/terms/}modified
      _, _, name = xml_element.tag.partition('}')

      # Do not including the 'lpstr' attribute because it is very verbose.
      if name == 'lpstr':
        continue

      property_name = self._PROPERTY_NAMES.get(name, None)
      if not property_name:
        property_name = self._FormatPropertyName(name)

      properties[property_name] = xml_element.text

    return properties 
Example #28
Source File: winevtx.py    From plaso with Apache License 2.0 5 votes vote down vote up
def _GetCreationTimeFromXMLString(
      self, parser_mediator, record_index, xml_string):
    """Retrieves the creationg time from the XML string.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      record_index (int): event record index.
      xml_string (str): event XML string.

    Returns:
      str: creation date and time formatted as ISO 8601 or None if not
          available.
    """
    xml_root = ElementTree.fromstring(xml_string)

    system_xml_element = xml_root.find(
        '{http://schemas.microsoft.com/win/2004/08/events/event}System')
    if system_xml_element is None:
      parser_mediator.ProduceExtractionWarning(
          'missing System XML element in event record: {0:d}'.format(
              record_index))
      return None

    time_created_xml_element = system_xml_element.find(
        '{http://schemas.microsoft.com/win/2004/08/events/event}TimeCreated')
    if time_created_xml_element is None:
      parser_mediator.ProduceExtractionWarning(
          'missing TimeCreated XML element in event record: {0:d}'.format(
              record_index))
      return None

    return time_created_xml_element.get('SystemTime') 
Example #29
Source File: video_calls.py    From zulip with Apache License 2.0 5 votes vote down vote up
def join_bigbluebutton(request: HttpRequest, meeting_id: str = REQ(validator=check_string),
                       password: str = REQ(validator=check_string),
                       checksum: str = REQ(validator=check_string)) -> HttpResponse:
    if settings.BIG_BLUE_BUTTON_URL is None or settings.BIG_BLUE_BUTTON_SECRET is None:
        return json_error(_("Big Blue Button is not configured."))
    else:
        response = requests.get(
            add_query_to_redirect_url(settings.BIG_BLUE_BUTTON_URL + "api/create", urlencode({
                "meetingID": meeting_id,
                "moderatorPW": password,
                "attendeePW": password + "a",
                "checksum": checksum
            })))
        try:
            response.raise_for_status()
        except Exception:
            return json_error(_("Error connecting to the Big Blue Button server."))

        payload = ElementTree.fromstring(response.text)
        if payload.find("messageKey").text == "checksumError":
            return json_error(_("Error authenticating to the Big Blue Button server."))

        if payload.find("returncode").text != "SUCCESS":
            return json_error(_("Big Blue Button server returned an unexpected error."))

        join_params = urlencode({  # type: ignore[type-var] # https://github.com/python/typeshed/issues/4234
            "meetingID": meeting_id,
            "password": password,
            "fullName": request.user.full_name
        }, quote_via=quote)

        checksum = hashlib.sha1(("join" + join_params + settings.BIG_BLUE_BUTTON_SECRET).encode()).hexdigest()
        redirect_url_base = add_query_to_redirect_url(settings.BIG_BLUE_BUTTON_URL + "api/join", join_params)
        return redirect(add_query_arg_to_redirect_url(redirect_url_base, "checksum=" + checksum)) 
Example #30
Source File: __init__.py    From insights-core with Apache License 2.0 5 votes vote down vote up
def parse_content(self, content):
        """
        All child classes inherit this function to parse XML file automatically.
        It will call the function :func:`parse_dom` by default to
        parser all necessary data to :attr:`data` and the :attr:`xmlns` (the
        default namespace) is ready for this function.
        """
        self.dom = self.xmlns = None
        self.data = {}
        # ignore empty xml file
        if len(content) > 3:
            self.raw = '\n'.join(content)
            self.dom = ET.fromstring(self.raw)
            self.xmlns = self.dom.tag.strip("{").split("}")[0] if all(c in self.dom.tag for c in ["{", "}"]) else ""
            self.data = self.parse_dom()