Пример #1
0
def main(i_msg, i_plr, i_latency):

    global payload
    global msgPaySize
    global plr
    global xmpp
    global results
    global latency

    ###Set the CPU measurement###
    q = Queue.Queue()
    start_new_thread(measure_cpu, (results, q))

    ###Set global variables and constants###
    payload = ET.fromstring("<test xmlns = 'test'>%s</test>" % i_msg)
    msgPaySize = len(i_msg)
    plr = i_plr
    latency = i_latency

    ###Connect to the broker and set handlers###
    xmpp = sleekxmpp.ClientXMPP(jid, pw)
    xmpp.add_event_handler("session_start", on_start)
    xmpp.add_event_handler("pubsub_publish", on_receive)

    xmpp.register_plugin('xep_0004')  ###Dataforms
    xmpp.register_plugin('xep_0060')  ###PubSub

    xmpp.connect()
    xmpp.process(block=True)

    if flagEnd == 'X':
        return results
Пример #2
0
 def set_calendar(self, node, calendar_str):
     """ Set calendar of node """
     payload = ET.fromstring(calendar_str)
     self['xep_0060'].publish(self._pubsub,
                              node,
                              id='calendar',
                              payload=payload)
Пример #3
0
    def add_command(self, command):
        """Add a command to the extension.

        Arguments:
            command (str): Command to add
        """
        self.xml.append(ET.fromstring('<command>%s</command>' % command))
Пример #4
0
 def publish(self, node, data):
     payload = ET.fromstring("<test xmlns='test'>{}</test>".format(data))
     try:
         self['xep_0060'].publish(self.pubsub_server, node, payload=payload)
     except Exception as e:
         log.error('pubsub: could not publish to: {}'.format(node))
         log.error('Exception "{}" of type {}'.format(e, type(e)))
Пример #5
0
    def broadcast(self, payload):
        """ Broadcasts via XMPP the payload. The payload can be a list
        of Item or a single item.
        """

        # Transforms all Item objects to a single XML string
        xmls = ""
        if isinstance(payload, dict):
            xmls = payload.to_xml()
        elif isinstance(payload, list):
            for elem in payload:
                xmls += elem.to_xml()

        # Transforms the XML string to a valid sleekxmpp XML element
        xml_element = ET.fromstring(xmls)

        try:
            result = self.pubsub.publish(self.config.server_host,
                                         self.config.node_name,
                                         payload=xml_element)
            id = result['pubsub']['publish']['item']['id']
            self.logger.debug('Published at item id: %s' % id)
        except:
            self.logger.error('Could not publish to: %s' %
                              self.config.node_name)
Пример #6
0
def main(i_msg, i_plr, i_latency):

	global payload
	global msgPaySize
	global plr
	global xmpp
	global latency

	###Set global variables and constants###
        payload = ET.fromstring("<test xmlns = 'test'>%s</test>" % i_msg)
        msgPaySize = len(i_msg)
        plr = i_plr
	latency = i_latency

	###Connect to the broker and set handlers###
	xmpp = sleekxmpp.ClientXMPP(jid, pw)
	xmpp.add_event_handler("session_start", on_start)
	xmpp.add_event_handler("message", on_message)

        xmpp.register_plugin('xep_0004') ###Dataforms
	xmpp.register_plugin('xep_0060') #PubSub

	xmpp.connect()
	xmpp.process(block=True)

	if flagEnd == 'X':
		return results
Пример #7
0
 def testGetItems(self):
     """Test retrieving items from a roster stanza."""
     xml_string = """
       <iq>
         <query xmlns="jabber:iq:roster">
           <item jid="*****@*****.**" name="User" subscription="both">
             <group>Friends</group>
             <group>Coworkers</group>
           </item>
           <item jid="*****@*****.**" name="Other User"
                 subscription="both" />
         </query>
       </iq>
     """
     iq = self.Iq(ET.fromstring(xml_string))
     expected = {
         '*****@*****.**': {
             'name': 'User',
             'subscription': 'both',
             'ask': '',
             'approved': '',
             'groups': ['Friends', 'Coworkers']},
         '*****@*****.**': {
             'name': 'Other User',
             'subscription': 'both',
             'ask': '',
             'approved': '',
             'groups': []}}
     debug = "Roster items don't match after retrieval."
     debug += "\nReturned: %s" % str(iq['roster']['items'])
     debug += "\nExpected: %s" % str(expected)
     self.failUnless(iq['roster']['items'] == expected, debug)
 def testGetItems(self):
     """Test retrieving items from a roster stanza."""
     xml_string = """
       <iq>
         <query xmlns="jabber:iq:roster">
           <item jid="*****@*****.**" name="User" subscription="both">
             <group>Friends</group>
             <group>Coworkers</group>
           </item>
           <item jid="*****@*****.**" name="Other User"
                 subscription="both" />
         </query>
       </iq>
     """
     iq = self.Iq(ET.fromstring(xml_string))
     expected = {
         "*****@*****.**": {
             "name": "User",
             "subscription": "both",
             "ask": "",
             "approved": "",
             "groups": ["Friends", "Coworkers"],
         },
         "*****@*****.**": {
             "name": "Other User",
             "subscription": "both",
             "ask": "",
             "approved": "",
             "groups": [],
         },
     }
     debug = "Roster items don't match after retrieval."
     debug += "\nReturned: %s" % str(iq["roster"]["items"])
     debug += "\nExpected: %s" % str(expected)
     self.failUnless(iq["roster"]["items"] == expected, debug)
Пример #9
0
 def publish(self, node, data):
     payload = ET.fromstring("<test xmlns='test'>{}</test>".format(data))
     try:
         self['xep_0060'].publish(self.pubsub_server, node, payload=payload)
     except Exception as e:
         log.error('pubsub: could not publish to: {}'.format(node))
         log.error('Exception "{}" of type {}'.format(e, type(e)))
Пример #10
0
def main(i_msg, i_plr, i_latency):

    ###Globals###
    global payload
    global msgPaySize
    global plr
    global xmpp
    global g_msg
    global latency

    payload = ET.fromstring("<test xmlns = 'test'>%s</test>" % i_msg)
    msgPaySize = len(i_msg)
    plr = i_plr
    g_msg = i_msg
    latency = i_latency

    ###Connect to the broker and set handlers###
    xmpp = sleekxmpp.ClientXMPP(jid, pw)
    xmpp.add_event_handler("session_start", on_start)
    xmpp.add_event_handler("pubsub_publish", on_receive)

    xmpp.register_plugin('xep_0004')  ###Dataforms
    xmpp.register_plugin('xep_0060')  ###PubSub

    try:
        xmpp.connect()
    except:
        print('Cannot connect to the broker. Test failed!')
        sys.exit()

    xmpp.process(block=True)

    if flagEnd == 'X':
        return results
Пример #11
0
def handle_xml(self, nodeid, itemid, elem):
    #print '-------------'

    if (nodeid not in nodes_seen):
        nodes_seen.append(nodeid)
        r = self['xep_0060'].get_item(self.pubsub, nodeid, 'storage')
        storage = ''
        if (r['pubsub']['items']['item']['payload']):
            for a in r['pubsub']['items']['item']['payload']:
                storage += tostring(a)
        if (ip not in storage):
            storage += "<address link='http://" + ip + ":4720' />"
            storage = "<addresses>" + storage + "</addresses>"
            #print "publish:", storage
            try:
                self['xep_0060'].publish(self.pubsub,
                                         nodeid,
                                         id='storage',
                                         payload=ET.fromstring(storage))
            except sleekxmpp.exceptions.IqError:
                print "IqError: Publish to storage item failed. You are probably not the owner of this node..."

    if (elem.tag.split('}', 1)[-1] == 'transducerData'):
        attr = {}
        for pair in elem.items():
            attr[pair[0]] = pair[1]
        #print attr
        dt = iso8601.parse_date(attr['timestamp'])
        t = time.mktime(dt.timetuple()) + (dt.microsecond / 1e6)
        #print attr['timestamp']
        #print("%.9f" % t)
        if ((attr['name'] != 'none') and (attr['name'] != '')):
            add_to_json(nodeid, attr['name'], t, attr['value'])
            pass
Пример #12
0
    def add_command(self, player_nick):
        """Add a command to the extension.

        Arguments:
            player_nick (str): the nick of the player the profile is about

        """
        self.xml.append(ET.fromstring('<command>%s</command>' % player_nick))
Пример #13
0
 def publish(self):
     payload = ET.fromstring("<test xmlns='test'>%s</test>" % self.data)
     try:
         result = self['xep_0060'].publish(self.pubsub_server, self.node, payload=payload)
         id = result['pubsub']['publish']['item']['id']
         print('Published at item id: %s' % id)
     except:
         logging.error('Could not publish to: %s' % self.node)
Пример #14
0
 def publish(self):
     payload = ET.fromstring("<test xmlns='test'>%s</test>" % self.data)
     try:
         result = self["xep_0060"].publish(self.pubsub_server, self.node, payload=payload)
         id = result["pubsub"]["publish"]["item"]["id"]
         print("Published at item id: %s" % id)
     except:
         logging.error("Could not publish to: %s" % self.node)
Пример #15
0
 def publish(self, node, item_id, item):
     json_xml = '<json xmlns="urn:xmpp:json:0">%s</json>' % item
     payload = ET.fromstring(json_xml)
     self['xep_0060'].publish(self.pubsub_server,
                              node,
                              id=item_id,
                              payload=payload)
     print('Published item %s to %s' % (item_id, node))
Пример #16
0
 def publish(self):
     payload = ET.fromstring("<test xmlns='test'>%s</test>" % self.data)
     try:
         result = self['xep_0060'].publish(self.pubsub_server, self.node, payload=payload)
         id = result['pubsub']['publish']['item']['id']
         print('Published at item id: %s' % id)
     except:
         logging.error('Could not publish to: %s' % self.node)
Пример #17
0
    def add_game(self, game_report):
        """Add a game to the extension.

        Arguments:
            game_report (dict): a report about a game

        """
        self.xml.append(
            ET.fromstring(str(game_report)).find('{%s}game' % self.namespace))
Пример #18
0
 def testGetBeforeVal(self):
     xml_string = """
       <set xmlns="http://jabber.org/protocol/rsm">
         <before>id</before>
       </set>
     """
     s = Set(ET.fromstring(xml_string))
     expected = 'id'
     self.failUnless(s['before'] == expected)
Пример #19
0
 def testGetFirstIndex(self):
     xml_string = """
       <set xmlns="http://jabber.org/protocol/rsm">
         <first index="10">id</first>
       </set>
     """
     s = Set(ET.fromstring(xml_string))
     expected = '10'
     self.failUnless(s['first_index'] == expected)
Пример #20
0
 def testGetBeforeVal(self):
     xml_string = """
       <set xmlns="http://jabber.org/protocol/rsm">
         <before>id</before>
       </set>
     """
     s = Set(ET.fromstring(xml_string))
     expected = 'id'
     self.failUnless(s['before'] == expected)
Пример #21
0
   def set_nick(self, nick):
      # set bla baaasa
      vcard = ET.fromstring("""
<vCard xmlns="vcard-temp">
   <FN>Dr. Mundo</FN>
   <NICKNAME>Pussy Boy</NICKNAME>
</vCard>
      """)
      self['xep_0054'].publish_vcard(vcard)
Пример #22
0
    def testMailBox(self):
        """Testing reading from Gmail mailbox result"""

        # Use the example from Google's documentation at
        # http://code.google.com/apis/talk/jep_extensions/gmail.html#notifications
        xml = ET.fromstring("""
          <iq type="result">
            <mailbox xmlns="google:mail:notify"
                     result-time='1118012394209'
                     url='http://mail.google.com/mail'
                     total-matched='95'
                     total-estimate='0'>
              <mail-thread-info tid='1172320964060972012'
                                participation='1'
                                messages='28'
                                date='1118012394209'
                                url='http://mail.google.com/mail?view=cv'>
                <senders>
                  <sender name='Me' address='*****@*****.**' originator='1' />
                  <sender name='Benvolio' address='*****@*****.**' />
                  <sender name='Mercutio' address='*****@*****.**' unread='1'/>
                </senders>
                <labels>act1scene3</labels>
                <subject>Put thy rapier up.</subject>
                <snippet>Ay, ay, a scratch, a scratch; marry, 'tis enough.</snippet>
              </mail-thread-info>
            </mailbox>
          </iq>
        """)

        iq = self.Iq(xml=xml)
        mailbox = iq['mailbox']
        self.failUnless(mailbox['result-time'] == '1118012394209', "result-time doesn't match")
        self.failUnless(mailbox['url'] == 'http://mail.google.com/mail', "url doesn't match")
        self.failUnless(mailbox['matched'] == '95', "total-matched incorrect")
        self.failUnless(mailbox['estimate'] == False, "total-estimate incorrect")
        self.failUnless(len(mailbox['threads']) == 1, "could not extract message threads")

        thread = mailbox['threads'][0]
        self.failUnless(thread['tid'] == '1172320964060972012', "thread tid doesn't match")
        self.failUnless(thread['participation'] == '1', "thread participation incorrect")
        self.failUnless(thread['messages'] == '28', "thread message count incorrect")
        self.failUnless(thread['date'] == '1118012394209', "thread date doesn't match")
        self.failUnless(thread['url'] == 'http://mail.google.com/mail?view=cv', "thread url doesn't match")
        self.failUnless(thread['labels'] == 'act1scene3', "thread labels incorrect")
        self.failUnless(thread['subject'] == 'Put thy rapier up.', "thread subject doesn't match")
        self.failUnless(thread['snippet'] == "Ay, ay, a scratch, a scratch; marry, 'tis enough.", "snippet doesn't match")
        self.failUnless(len(thread['senders']) == 3, "could not extract senders")

        sender1 = thread['senders'][0]
        self.failUnless(sender1['name'] == 'Me', "sender name doesn't match")
        self.failUnless(sender1['address'] == '*****@*****.**', "sender address doesn't match")
        self.failUnless(sender1['originator'] == True, "sender originator incorrect")
        self.failUnless(sender1['unread'] == False, "sender unread incorrectly True")

        sender2 = thread['senders'][2]
        self.failUnless(sender2['unread'] == True, "sender unread incorrectly False")
Пример #23
0
 def testGetFirstIndex(self):
     xml_string = """
       <set xmlns="http://jabber.org/protocol/rsm">
         <first index="10">id</first>
       </set>
     """
     s = Set(ET.fromstring(xml_string))
     expected = '10'
     self.failUnless(s['first_index'] == expected)
Пример #24
0
    def load_ballot(self, name, quorum):
        self.quorum = quorum
        self.current_ballot = name

        with open('%s/ballot_%s.xml' % (self.data_dir, name)) as ballot_file:
            self._ballot_data = Ballot(xml=ET.fromstring(ballot_file.read()))
        try:
            os.makedirs('%s/results/%s' % (self.data_dir, name))
        except:
            pass
Пример #25
0
    def load_ballot(self, name, quorum):
        self.quorum = quorum
        self.current_ballot = name

        with open('%s/ballot_%s.xml' % (self.data_dir, name)) as ballot_file:
            self._ballot_data = Ballot(xml=ET.fromstring(ballot_file.read()))
        try:
            os.makedirs('%s/results/%s' % (self.data_dir, name))
        except:
            pass
Пример #26
0
 def publish(self, data):
     #payload = ET.fromstring("<test xmlns='test'>%s</test>" % self.data)
     
     #--- Warning: publish will fail if data does not contain XML elements ---#
     payload = ET.fromstring(data)
     try:
         result = self['xep_0060'].publish(self.pubsub_server, self.node, id=self.itemid, payload=payload)
         id = result['pubsub']['publish']['item']['id']
         print('Published "%s" at item id: %s' % (data, id))
     except:
         logging.error('Could not publish to: %s' % self.node)
Пример #27
0
def load_config(filename):
    """
    Create a configuration stanza object from
    the given file's contents.

    Arguments:
        filename -- Name of the config file.
    """
    with open(filename, 'r+') as conf_file:
        data = "\n".join([line for line in conf_file])
        config = Config(xml=ET.fromstring(data))
        return config
Пример #28
0
 def testGetBeforeVal(self):
     xml_string = """
       <set xmlns="http://jabber.org/protocol/rsm">
         <before>id</before>
       </set>
     """
     s = Set(ET.fromstring(xml_string))
     del s['before']
     self.check(s, """
       <set xmlns="http://jabber.org/protocol/rsm">
       </set>
     """)
Пример #29
0
def load_config(filename):
    """
    Create a configuration stanza object from
    the given file's contents.

    Arguments:
        filename -- Name of the config file.
    """
    with open(filename, 'r+') as conf_file:
        data = "\n".join([line for line in conf_file])
        config = Config(xml=ET.fromstring(data))
        return config
Пример #30
0
 def testDelFirstIndex(self):
     xml_string = """
       <set xmlns="http://jabber.org/protocol/rsm">
         <first index="10">id</first>
       </set>
     """
     s = Set(ET.fromstring(xml_string))
     del s['first_index']
     self.check(s, """
       <set xmlns="http://jabber.org/protocol/rsm">
         <first>id</first>
       </set>
     """)
Пример #31
0
 def testGetBeforeVal(self):
     xml_string = """
       <set xmlns="http://jabber.org/protocol/rsm">
         <before>id</before>
       </set>
     """
     s = Set(ET.fromstring(xml_string))
     del s['before']
     self.check(
         s, """
       <set xmlns="http://jabber.org/protocol/rsm">
       </set>
     """)
Пример #32
0
 def testDelFirstIndex(self):
     xml_string = """
       <set xmlns="http://jabber.org/protocol/rsm">
         <first index="10">id</first>
       </set>
     """
     s = Set(ET.fromstring(xml_string))
     del s['first_index']
     self.check(
         s, """
       <set xmlns="http://jabber.org/protocol/rsm">
         <first>id</first>
       </set>
     """)
Пример #33
0
    def session_start(self, event):
        print('Started')
        self.send_presence()
        self.get_roster()

        node = 'node1'
        payload = ET.fromstring("<test xmlns='test'>%s</test>" % 'message')
        try:
            self['xep_0060'].create_node('raspberrypi', node)
        except:
            print("")
        self['xep_0060'].subscribe('raspberrypi', node)
        self['xep_0060'].publish('raspberrypi', node, payload=payload)
        time.sleep(10)
        self['xep_0060'].subscribe('raspberrypi', node)
Пример #34
0
    def session_start(self, event):
        print('Started')
        self.send_presence()
        self.get_roster()

        node = 'node1'
        payload = ET.fromstring("<test xmlns='test'>%s</test>" % 'message')
        try:
            self['xep_0060'].create_node('raspberrypi', node)
        except:
            print("")
        result = self['xep_0060'].subscribe('bob@raspberrypi',
                                            node,
                                            callback=self.callback)
        print(str(result))
Пример #35
0
    def set_task(self, task_id, tags, task):
        """ Publish task to teammates """
        payload = ET.fromstring(task)

        for node, project_tag in self._nodes.items():
            if project_tag in tags:
                self['xep_0060'].publish(self._pubsub, node, id=task_id,
                        payload=payload)
            else:
                # Has this node still this task?
                item_req = self['xep_0060'].get_item(self._pubsub, node,
                            task_id)
                items = item_req['pubsub']['items']['substanzas']
                if len(items) > 0:
                    self['xep_0060'].retract(self._pubsub, node, task_id)
Пример #36
0
    def parse_xml(self, xml_string):
        try:
            xml = ET.fromstring(xml_string)
            return xml
        except SyntaxError as e:
            if 'unbound' in e.msg:
                known_prefixes = {'stream': 'http://etherx.jabber.org/streams'}

                prefix = xml_string.split('<')[1].split(':')[0]
                if prefix in known_prefixes:
                    xml_string = '<fixns xmlns:%s="%s">%s</fixns>' % (
                        prefix, known_prefixes[prefix], xml_string)
                xml = self.parse_xml(xml_string)
                xml = xml.getchildren()[0]
                return xml
Пример #37
0
    def publish(self, data, node):

        # publish data in pubsub node

        #print "publish item %s in node %s on %s"	 % (data,node,self.pubsub)

        payload = ET.fromstring("<test xmlns='test'>%s</test>" % data)
        try:
            result = self['xep_0060'].publish(self.pubsub,
                                              node,
                                              payload=payload)
            id = result['pubsub']['publish']['item']['id']
            print('Published at item id: %s' % id)
        except:
            print('Could not publish to: %s on %s' % (node, self.pubsub))
Пример #38
0
    def alert(self, msg):
        """ Broadcast the msg on the pubsub node (written in the
        config file).
        """

        xml_element = ET.fromstring('<status>%s</status>' % msg)

        try:
            result = self.pubsub.publish(self.config.pubsub,
                                         self.config.node,
                                         payload=xml_element)
            id = result['pubsub']['publish']['item']['id']
            print('Published at item id: %s' % id)
        except:
            print('Could not publish to: %s' %
                  'Baboon')
Пример #39
0
    def session_start(self, event):
        print('Started')
        self.send_presence()
        self.get_roster()

        node = 'node1'
        payload = ET.fromstring("<test xmlns='test'>%s</test>" % 'message')
        try:
            self['xep_0060'].create_node('raspberrypi', node)
        except:
            print("")
        self['xep_0060'].publish('raspberrypi', node, payload=payload)
        result = self['xep_0060'].get_nodes('raspberrypi', node)
        for item in result['disco_items']['items']:
            print(str(item))
        print(str(result))
Пример #40
0
def main(i_msg):

    global xmpp
    global payload

    payload = ET.fromstring("<test xmlns = 'test'>%s</test>" % i_msg)

    xmpp = sleekxmpp.ClientXMPP(jid, pw)
    xmpp.add_event_handler("session_start", on_start)
    xmpp.add_event_handler("pubsub_publish", on_receive)

    xmpp.register_plugin('xep_0004')  ###Dataforms
    xmpp.register_plugin('xep_0060')  ###PubSub
    print('Connecting')
    xmpp.connect()
    xmpp.process(block=True)
Пример #41
0
    def publish(self, event, radius):
        from events.api.resources.jabber import EventResource

        resource = EventResource()
        event_dict = resource.full_dehydrate(resource.build_bundle(obj=event))
        event_dict.data['radius'] = radius
        str_payload = resource.serialize(None, event_dict, 'application/xml')
        payload = ET.fromstring(str_payload)

        if logger.level is logging.DEBUG:
            lxml_payload = etree.fromstring(ET.tostring(payload))
            str_payload = etree.tostring(lxml_payload, pretty_print=True)
            logger.debug('sending publish message with payload:\n%s', str_payload)

        self._pubsub.publish(self.config.pubsub_server,
                             self.config.node_name,
                             payload=payload)
Пример #42
0
    def set_task(self, task_id, tags, task):
        """ Publish task to teammates """
        payload = ET.fromstring(task)

        for node, project_tag in self._nodes.items():
            if project_tag in tags:
                self['xep_0060'].publish(self._pubsub,
                                         node,
                                         id=task_id,
                                         payload=payload)
            else:
                # Has this node still this task?
                item_req = self['xep_0060'].get_item(self._pubsub, node,
                                                     task_id)
                items = item_req['pubsub']['items']['substanzas']
                if len(items) > 0:
                    self['xep_0060'].retract(self._pubsub, node, task_id)
Пример #43
0
    def parse_xml(self, xml_string):
        try:
            xml = ET.fromstring(xml_string)
            return xml
        except SyntaxError as e:
            if 'unbound' in e.msg:
                known_prefixes = {
                        'stream': 'http://etherx.jabber.org/streams'}

                prefix = xml_string.split('<')[1].split(':')[0]
                if prefix in known_prefixes:
                    xml_string = '<fixns xmlns:%s="%s">%s</fixns>' % (
                            prefix,
                            known_prefixes[prefix],
                            xml_string)
                xml = self.parse_xml(xml_string)
                xml = xml.getchildren()[0]
                return xml
Пример #44
0
    def parse_xml(self, xml_string):
        try:
            xml = ET.fromstring(xml_string)
            return xml
        except (SyntaxError, ExpatError) as e:
            msg = e.msg if hasattr(e, 'msg') else e.message
            if 'unbound' in msg:
                known_prefixes = {'stream': 'http://etherx.jabber.org/streams'}

                prefix = xml_string.split('<')[1].split(':')[0]
                if prefix in known_prefixes:
                    xml_string = '<fixns xmlns:%s="%s">%s</fixns>' % (
                        prefix, known_prefixes[prefix], xml_string)
                xml = self.parse_xml(xml_string)
                xml = list(xml)[0]
                return xml
            else:
                self.fail("XML data was mal-formed:\n%s" % xml_string)
Пример #45
0
 def set_body(self, content, lang=None):
     if lang is None:
         lang = self.get_lang()
     self.del_body(lang)
     if lang == '*':
         for sublang, subcontent in content.items():
             self.set_body(subcontent, sublang)
     else:
         if isinstance(content, type(ET.Element('test'))):
             content = ET.tostring(content)
         else:
             content = str(content)
         header = '<body xmlns="%s"' % XHTML_NS
         if lang:
             header = '%s xml:lang="%s"' % (header, lang)
         content = '%s>%s</body>' % (header, content)
         xhtml = ET.fromstring(content)
         self.xml.append(xhtml)
Пример #46
0
 def set_body(self, content, lang=None):
     if lang is None:
         lang = self.get_lang()
     self.del_body(lang)
     if lang == '*':
         for sublang, subcontent in content.items():
             self.set_body(subcontent, sublang)
     else:
         if isinstance(content, type(ET.Element('test'))):
             content = unicode(ET.tostring(content))
         else:
             content = unicode(content)
         header = '<body xmlns="%s"' % XHTML_NS
         if lang:
             header = '%s xml:lang="%s"' % (header, lang)
         content = '%s>%s</body>' % (header, content)
         xhtml = ET.fromstring(content)
         self.xml.append(xhtml)
Пример #47
0
    def send_event(self, event: Event):
        """Send an event to other clients.

        Args:
            event (Event): Event to send
        """

        # create stanza
        stanza = EventStanza()

        # dump event to JSON and escape it
        body = xml.sax.saxutils.escape(json.dumps(event.to_json()))

        # set xml and send event
        stanza.xml = ET.fromstring('<event xmlns="pyobs:event">%s</event>' %
                                   body)
        self._xmpp['xep_0163'].publish(stanza,
                                       node='pyobs:event:%s' %
                                       event.__class__.__name__)
Пример #48
0
    def parse_xml(self, xml_string):
        try:
            xml = ET.fromstring(xml_string)
            return xml
        except (SyntaxError, ExpatError) as e:
            msg = e.msg if hasattr(e, 'msg') else e.message
            if 'unbound' in msg:
                known_prefixes = {
                        'stream': 'http://etherx.jabber.org/streams'}

                prefix = xml_string.split('<')[1].split(':')[0]
                if prefix in known_prefixes:
                    xml_string = '<fixns xmlns:%s="%s">%s</fixns>' % (
                            prefix,
                            known_prefixes[prefix],
                            xml_string)
                xml = self.parse_xml(xml_string)
                xml = xml.getchildren()[0]
                return xml
            else:
                self.fail("XML data was mal-formed:\n%s" % xml_string)
Пример #49
0
    def testInvalidBase64Alphabet(self):
        """
        Test detecting invalid base64 data with characters
        outside of the base64 alphabet.
        """
        iq = Iq(xml=ET.fromstring("""
          <iq type="set" id="0" to="tester@localhost">
            <data xmlns="http://jabber.org/protocol/ibb" seq="0">
              ABCD?EFGH
            </data>
          </iq>
        """))

        errored = False

        try:
            data = iq['ibb_data']['data']
        except XMPPError:
            errored = True

        self.assertTrue(errored, "ABCD?EFGH did not raise base64 error")
Пример #50
0
    def testInvalidBase64PrefixEqual(self):
        """
        Test detecting invalid base64 data with = as a prefix
        to the character data.
        """
        iq = Iq(xml=ET.fromstring("""
          <iq type="set" id="0" to="tester@localhost">
            <data xmlns="http://jabber.org/protocol/ibb" seq="0">
              =ABCDEFGH
            </data>
          </iq>
        """))

        errored = False

        try:
            data = iq['ibb_data']['data']
        except XMPPError:
            errored = True

        self.assertTrue(errored, "=ABCDEFGH did not raise base64 error")
Пример #51
0
    def start_sending_data(self):

        # just for test: send 1 message
        while True:

            t = datetime.datetime.now(dateutil.tz.tzlocal())
            # scale = math.sin( math.pi * t.second / 60 ) * 100
            # value = t.second
            value = 20 + math.sin(math.pi * (t.second / 60.0 * 4.0)) * 5

            print 'starting sending data'
            try:
                ts = soxtimestamp.timestamp()
                print 'ts=%s' % ts
                # payload = ET.fromstring('<data><transducerValue id="trans1" typedValue="%f" timestamp="%s"/></data>' % (value, ts))

                sd = SensorData()
                tv1 = TransducerValue(id='trans1', typed_value='%s' % value, timestamp=ts)
                sd.add_value(tv1)
                payload = ET.fromstring(sd.to_string(pretty=False))

                print 'payload built'

                self['xep_0060'].publish(
                    'pubsub.ps.ht.sfc.keio.ac.jp',
                    self.node_name,
                    id=self.gen_item_id(),
                    payload=payload
                )
            except:
                print 'except!'
                traceback.print_exc()
                etype, value, etraceback = sys.exc_info()
                raise etype, value, etraceback
            print 'requested'

            gevent.sleep(1.2)

        self.disconnect()
        print 'disconnected'
Пример #52
0
    def start(self, event):
        self.running = True
        try:
            print 'starting!'
            err_count = 0
            err_threshold = 5
            while self.running and err_count < err_threshold:
                try:
                    for sid in self.santander_ids:
                        if not self.running:
                            break
                        node_name = 'santander%d_data' % sid

                        print 'fetching for santander sensor id=%d' % sid
                        sdata = get_santander_data(sid)
                        print 'fetched for santander sensor id=%d' % sid
                        sd = santander2sensor(sdata)
                        xml_string = sd.to_string()
                        payload = ET.fromstring(xml_string)

                        try:
                            self['xep_0060'].publish(
                                'pubsub.sox.ht.sfc.keio.ac.jp',
                                node_name,
                                id=self.gen_item_id(),
                                payload=payload
                            )
                        except IqTimeout:
                            print 'caught IqTimeout, but ignoring'
                            err_count += 1
                            if err_threshold <= err_count:
                                break
                        print 'published for node \'%s\'' % node_name

                    time.sleep(3)
                except:
                    logging.exception('something bad happened!')
                    err_count += 1
        finally:
            self.disconnect()
Пример #53
0
    def start_sending_data(self):
        self.running = True
        self.debug('start_sending_data() starting')

        err_count = 0
        err_threshold = 5

        try:
            while self.running and err_count < err_threshold:
                try:
                    gevent.sleep(1.0 + 0.1 * random.randint(1, 30))
                    genova_data = get_genova_data(self.genova_id)
                    self.debug('got genova data: %s' % simplejson.dumps(genova_data))
                    # self.debug('got genova data')
                    genova_sensor_data = genova2sensor(genova_data)
                    xml_string = genova_sensor_data.to_string()
                    payload = ET.fromstring(xml_string)
                    self.debug('built payload: %s' % xml_string)
                    # self.debug('built payload')

                    try:
                        self['xep_0060'].publish(
                            'pubsub.sox.ht.sfc.keio.ac.jp',
                            self.node_name + '_data',
                            id=self.gen_item_id(),
                            payload=payload
                        )
                    except IqTimeout:
                        self.debug('caught IqTimeout')
                        err_count += 1

                    self.debug('published')

                except:
                    self.debug('except!')
                    traceback.print_exc()
                    err_count += 1
        finally:
            self.disconnect()
            self.debug('disconnected')
Пример #54
0
    def _unserialize_session(self, session):
        """
        Modify a session dictionary to undo the modifications
        made in order to pickle the session.

        Note: Modifies the session in place.
        """
        if '__JID__' in session:
            for key in session['__JID__']:
                session[key] = JID(session['__JID__'][key])
            del session['__JID__']
        if '__XML__' in session:
            for key in session['__XML__']:
                stanza_class, xml = session['__XML__'][key]
                xml = ET.fromstring(xml)
                session[key] = stanza_class(xml=xml)
            del session['__XML__']
        if '__FUNC__' in session:
            for key in session['__FUNC__']:
                func_hash = session['__FUNC__'][key]
                session[key] = self.funcs[func_hash]
            del session['__FUNC__']
Пример #55
0
    def start(self, event):
        try:
            print 'start() starting'
            for node_name, device in self.node2device_map.iteritems():
                print 'going to publish for \'%s\'' % node_name
                xml_string = str(device)
                payload = ET.fromstring(xml_string)

                self['xep_0060'].publish(
                    'pubsub.sox.ht.sfc.keio.ac.jp',
                    node_name,
                    id=self.gen_item_id(),
                    payload=payload
                )

                print 'published: %s' % node_name

            print 'finished'
        except:
            logging.exception('something bad happened')
        finally:
            print 'disconnecting'
            self.disconnect()
 def testDelItems(self):
     """Test clearing items from a roster stanza."""
     xml_string = """
       <iq>
         <query xmlns="jabber:iq:roster">
           <item jid="*****@*****.**" name="User" subscription="both">
             <group>Friends</group>
             <group>Coworkers</group>
           </item>
           <item jid="*****@*****.**" name="Other User"
                 subscription="both" />
         </query>
       </iq>
     """
     iq = self.Iq(ET.fromstring(xml_string))
     del iq["roster"]["items"]
     self.check(
         iq,
         """
       <iq>
         <query xmlns="jabber:iq:roster" />
       </iq>
     """,
     )
Пример #57
0
 def addCommand(self, command):
   commandXml = ET.fromstring("<command>%s</command>" % command)
   self.xml.append(commandXml)
Пример #58
0
 def addPlayerOnline(self, player):
   playerXml = ET.fromstring("<online>%s</online>" % player)
   self.xml.append(playerXml)