Here are the examples of the python api twisted.words.protocols.jabber.jid.JID taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
165 Examples
3
Example 101
def test_inequality(self):
"""
Test JID inequality.
"""
j1 = jid.JID("user1@host/resource")
j2 = jid.JID("user2@host/resource")
self.assertNotEqual(j1, j2)
3
Example 102
def test_fullAll(self):
"""
Test giving a string representation of the JID.
"""
j = jid.JID(tuple=('user', 'host', 'resource'))
self.assertEqual('user@host/resource', j.full())
3
Example 103
Project: SubliminalCollaborator Source File: test_jabberxmlstream.py
def test_sendHeaderReceiving(self):
"""
Test addressing when receiving a stream.
"""
xs = self.xmlstream
xs.thisEntity = jid.JID('thisHost')
xs.otherEntity = jid.JID('otherHost')
xs.initiating = False
xs.sid = 'session01'
xs.sendHeader()
splitHeader = xs.transport.value()[0:-1].split(' ')
self.assertIn("to='otherhost'", splitHeader)
self.assertIn("from='thishost'", splitHeader)
self.assertIn("id='session01'", splitHeader)
3
Example 104
def test_equality(self):
"""
Test JID equality.
"""
j1 = jid.JID("user@host/resource")
j2 = jid.JID("user@host/resource")
self.assertNotIdentical(j1, j2)
self.assertEqual(j1, j2)
3
Example 105
def test_anonymous(self):
"""
Test setting ANONYMOUS as the authentication mechanism.
"""
self.authenticator.jid = jid.JID('example.com')
self.authenticator.password = None
name = "ANONYMOUS"
self.assertEqual(name, self._setMechanism(name))
3
Example 106
Project: SubliminalCollaborator Source File: test_jabberjid.py
def test_inequalityWithNonJIDs(self):
"""
Test JID equality.
"""
j = jid.JID("user@host/resource")
self.assertNotEqual(j, 'user@host/resource')
3
Example 107
def test_digest(self):
"""
Test setting DIGEST-MD5 as the authentication mechanism.
"""
self.authenticator.jid = jid.JID('[email protected]')
self.authenticator.password = 'secret'
name = "DIGEST-MD5"
self.assertEqual(name, self._setMechanism(name))
3
Example 108
def test_repr(self):
"""
Test representation of JID objects.
"""
j = jid.JID(tuple=('user', 'host', 'resource'))
self.assertEqual("JID(u'user@host/resource')", repr(j))
3
Example 109
def test_hashable(self):
"""
Test JID hashability.
"""
j1 = jid.JID("user@host/resource")
j2 = jid.JID("user@host/resource")
self.assertEqual(hash(j1), hash(j2))
3
Example 110
def test_unicode(self):
"""
Test unicode representation of JIDs.
"""
j = jid.JID(tuple=('user', 'host', 'resource'))
self.assertEqual("user@host/resource", unicode(j))
3
Example 111
Project: SubliminalCollaborator Source File: test_jabberjid.py
def test_equalityWithNonJIDs(self):
"""
Test JID equality.
"""
j = jid.JID("user@host/resource")
self.assertFalse(j == 'user@host/resource')
3
Example 112
Project: SubliminalCollaborator Source File: test_jabbersasl.py
def test_notAcceptableWithoutUser(self):
"""
Test using an unacceptable SASL authentication mechanism with no JID.
"""
self.authenticator.jid = jid.JID('example.com')
self.authenticator.password = 'secret'
self.assertRaises(sasl.SASLNoAcceptableMechanism,
self._setMechanism, 'SOMETHING_UNACCEPTABLE')
3
Example 113
Project: SubliminalCollaborator Source File: test_jabbersasl.py
def test_notAcceptable(self):
"""
Test using an unacceptable SASL authentication mechanism.
"""
self.authenticator.jid = jid.JID('[email protected]')
self.authenticator.password = 'secret'
self.assertRaises(sasl.SASLNoAcceptableMechanism,
self._setMechanism, 'SOMETHING_UNACCEPTABLE')
3
Example 114
def test_plain(self):
"""
Test setting PLAIN as the authentication mechanism.
"""
self.authenticator.jid = jid.JID('[email protected]')
self.authenticator.password = 'secret'
name = "PLAIN"
self.assertEqual(name, self._setMechanism(name))
3
Example 115
Project: SubliminalCollaborator Source File: test_jabberxmlstream.py
def test_sendHeaderInitiating(self):
"""
Test addressing when initiating a stream.
"""
xs = self.xmlstream
xs.thisEntity = jid.JID('thisHost')
xs.otherEntity = jid.JID('otherHost')
xs.initiating = True
xs.sendHeader()
splitHeader = xs.transport.value()[0:-1].split(' ')
self.assertIn("to='otherhost'", splitHeader)
self.assertIn("from='thishost'", splitHeader)
3
Example 116
Project: droned Source File: jabber.py
def install(self, _parentService):
"""interface requirement"""
self.parentService = _parentService
user = decrypt(self.SERVICECONFIG.JABBER_USERNAME)
server = self.SERVICECONFIG.JABBER_SERVER
resource = self.SERVICECONFIG.JABBER_RESOURCE
self.jid = JID("%(user)s@%(server)s/%(resource)s" % locals())
self.broadcastTask = LoopingCall(self.broadcastPresence)
self.sendQueue = []
self.authenticated = False
#load all jabber responders, after configuration
import droned.responders
droned.responders.loadAll()
0
Example 117
def onError(self, msg):
log.msg("Error received for %s: %s" % (msg['from'], msg.toXml()))
scheduling.unavailable_user(JID(msg['from']))
0
Example 118
Project: wokkel Source File: test_disco.py
def test_onDiscoInfoWithNoToAttribute(self):
"""
Disco info request without a to attribute has target None.
"""
xml = """<iq from='[email protected]'
type='get'>
<query xmlns='%s'/>
</iq>""" % NS_DISCO_INFO
def info(requestor, target, nodeIdentifier):
self.assertEqual(JID('[email protected]'), requestor)
return defer.succeed([
disco.DiscoIdentity('dummy', 'generic', 'Generic Dummy Entity'),
disco.DiscoFeature('jabber:iq:version')
])
self.service.info = info
d = self.handleRequest(xml)
return d
0
Example 119
Project: doubanbot Source File: scheduling.py
def bare_jids(self):
return set([JID(j).userhost() for j in self])
0
Example 120
Project: wokkel Source File: test_disco.py
def test_onDiscoItems(self):
"""
C{onDiscoItems} should process an items request and return a response.
The request should be parsed, C{items} called with the extracted
parameters, and then the result should be formatted into a proper
response element.
"""
xml = """<iq from='[email protected]' to='example.com'
type='get'>
<query xmlns='%s'/>
</iq>""" % NS_DISCO_ITEMS
def cb(element):
self.assertEqual('query', element.name)
self.assertEqual(NS_DISCO_ITEMS, element.uri)
self.assertEqual(NS_DISCO_ITEMS, element.item.uri)
self.assertEqual('example.com', element.item['jid'])
self.assertEqual('test', element.item['node'])
self.assertEqual('Test node', element.item['name'])
def items(requestor, target, nodeIdentifier):
self.assertEqual(JID('[email protected]'), requestor)
self.assertEqual(JID('example.com'), target)
self.assertEqual('', nodeIdentifier)
return defer.succeed([
disco.DiscoItem(JID('example.com'), 'test', 'Test node'),
])
self.service.items = items
d = self.handleRequest(xml)
d.addCallback(cb)
return d
0
Example 121
def _getSubscriptions(self, cursor, state):
self._checkNodeExists(cursor)
query = """SELECT jid, resource, state,
subscription_type, subscription_depth
FROM subscriptions
NATURAL JOIN nodes
NATURAL JOIN entities
WHERE node=%s"""
values = [self.nodeIdentifier]
if state:
query += " AND state=%s"
values.append(state)
cursor.execute(query, values)
rows = cursor.fetchall()
subscriptions = []
for row in rows:
subscriber = jid.JID('%s/%s' % (row.jid, row.resource))
options = {}
if row.subscription_type:
options['pubsub#subscription_type'] = row.subscription_type
if row.subscription_depth:
options['pubsub#subscription_depth'] = row.subscription_depth
subscriptions.append(Subscription(self.nodeIdentifier, subscriber,
row.state, options))
return subscriptions
0
Example 122
@staticmethod
def fromElement(element):
"""
Create an instance from a domish Element.
"""
try:
stamp = parse(element[u'stamp'])
# Assume UTC if no timezone was given
if stamp.tzinfo is None:
stamp = stamp.replace(tzinfo=tzutc())
except (KeyError, ValueError, TypeError):
stamp = None
try:
sender = JID(element[u'from'])
except (KeyError, InvalidFormat):
sender = None
delay = Delay(stamp, sender)
return delay
0
Example 123
def test_info(self):
"""
C{info} should gather disco info from sibling handlers.
"""
discoItems = [disco.DiscoIdentity('dummy', 'generic',
'Generic Dummy Entity'),
disco.DiscoFeature('jabber:iq:version')
]
@implementer(disco.IDisco)
class DiscoResponder(XMPPHandler):
def getDiscoInfo(self, requestor, target, nodeIdentifier):
if not nodeIdentifier:
return defer.succeed(discoItems)
else:
return defer.succeed([])
def cb(result):
self.assertEquals(discoItems, result)
self.service.parent = [self.service, DiscoResponder()]
d = self.service.info(JID('[email protected]'), JID('example.com'), '')
d.addCallback(cb)
return d
0
Example 124
Project: wokkel Source File: test_disco.py
def test_infoNotDeferred(self):
"""
C{info} should gather disco info from sibling handlers.
"""
discoItems = [disco.DiscoIdentity('dummy', 'generic',
'Generic Dummy Entity'),
disco.DiscoFeature('jabber:iq:version')
]
@implementer(disco.IDisco)
class DiscoResponder(XMPPHandler):
def getDiscoInfo(self, requestor, target, nodeIdentifier):
if not nodeIdentifier:
return discoItems
else:
return []
def cb(result):
self.assertEquals(discoItems, result)
self.service.parent = [self.service, DiscoResponder()]
d = self.service.info(JID('[email protected]'), JID('example.com'), '')
d.addCallback(cb)
return d
0
Example 125
def history(self, roomJID, messages):
"""
Send history to create a MUC based on a one on one chat.
See: http://xmpp.org/extensions/xep-0045.html#continue
@param roomJID: The room jabber/xmpp entity id.
@type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
@param messages: The history to send to the room as an ordered list of
message, represented by a dictionary with the keys
L{'stanza'}, holding the original stanza a
L{domish.Element}, and L{'timestamp'} with the
timestamp.
@type messages: L{list} of L{domish.Element}
"""
for message in messages:
stanza = message['stanza']
stanza['type'] = 'groupchat'
delay = Delay(stamp=message['timestamp'])
sender = stanza.getAttribute('from')
if sender is not None:
delay.sender = jid.JID(sender)
stanza.addChild(delay.toElement())
stanza['to'] = roomJID.userhost()
if stanza.hasAttribute('from'):
del stanza['from']
self.xmlstream.send(stanza)
0
Example 126
def test_items(self):
"""
C{info} should gather disco items from sibling handlers.
"""
discoItems = [disco.DiscoItem(JID('example.com'), 'test', 'Test node')]
@implementer(disco.IDisco)
class DiscoResponder(XMPPHandler):
def getDiscoItems(self, requestor, target, nodeIdentifier):
if not nodeIdentifier:
return defer.succeed(discoItems)
else:
return defer.succeed([])
def cb(result):
self.assertEquals(discoItems, result)
self.service.parent = [self.service, DiscoResponder()]
d = self.service.items(JID('[email protected]'), JID('example.com'), '')
d.addCallback(cb)
return d
0
Example 127
Project: bnw Source File: stupid_handler.py
@defer.inlineCallbacks
def idiotic(msg):
"""Suck some cocks."""
# return str(request.body)
message_from = JID(msg['from'])
message_bare_from = message_from.userhost()
message_user = (yield objs.User.find_one({'jids': message_bare_from}))
if not message_user:
message_user = (yield objs.User.find_one({'jid': message_bare_from}))
# if message.body is None:
# return ''
if msg.bnw_s2s:
bnw_s2s = msg.bnw_s2s
print 'GOT AN s2s MESSAGE', bnw_s2s
try:
s2s_type = bnw_s2s['type']
except KeyError:
s2s_type = None
handler = handlers.s2s_handlers.get(s2s_type)
if not handler:
print 'NO HANDLER FOR THIS TYPE (%s)' % (s2s_type)
else:
_ = yield handler(msg, bnw_s2s)
defer.returnValue(None)
message_body = unicode(msg.body)
if message_body is None:
defer.returnValue('')
message_body = message_body.strip()
if type(message_body) != unicode:
message_body = unicode(message_body, 'utf-8', 'replace')
xmsg = XmppMessage(
message_body, JID(msg['to']), message_from, message_user)
if message_user:
message_user.activity()
try:
iparser = 'redeye'
if message_user:
if 'interface' in message_user:
iparser = message_user['interface']
result = yield handlers.parsers[iparser].handle(xmsg)
except CommandParserException, exc:
result = yield exc.args[0]
# except pymongo.errors.AutoReconnect:
# defer.returnValue((yield 'Sorry, our database is down.'))
# except _DefGen_Return:
# raise
except:
# raise
# defer.returnValue((yield "BACKEND (CATCHED) ERROR! IMMEDIATELY
# REPORT THIS SHIT TO MY STUPID
# AUTHOR!!!\n\n"+traceback.format_exc()))
defer.returnValue("BACKEND (CAUGHT) ERROR! IMMEDIATELY REPORT THIS SHIT TO MY STUPID AUTHOR!!!\n\n" +
traceback.format_exc() + "\n" +
"Command which caused this exception: " + message_body)
defer.returnValue(result)
0
Example 128
Project: wokkel Source File: test_disco.py
def test_onDiscoInfo(self):
"""
C{onDiscoInfo} should process an info request and return a response.
The request should be parsed, C{info} called with the extracted
parameters, and then the result should be formatted into a proper
response element.
"""
xml = """<iq from='[email protected]' to='example.com'
type='get'>
<query xmlns='%s'/>
</iq>""" % NS_DISCO_INFO
def cb(element):
self.assertEqual('query', element.name)
self.assertEqual(NS_DISCO_INFO, element.uri)
self.assertEqual(NS_DISCO_INFO, element.identity.uri)
self.assertEqual('dummy', element.identity['category'])
self.assertEqual('generic', element.identity['type'])
self.assertEqual('Generic Dummy Entity', element.identity['name'])
self.assertEqual(NS_DISCO_INFO, element.feature.uri)
self.assertEqual('jabber:iq:version', element.feature['var'])
def info(requestor, target, nodeIdentifier):
self.assertEqual(JID('[email protected]'), requestor)
self.assertEqual(JID('example.com'), target)
self.assertEqual('', nodeIdentifier)
return defer.succeed([
disco.DiscoIdentity('dummy', 'generic', 'Generic Dummy Entity'),
disco.DiscoFeature('jabber:iq:version')
])
self.service.info = info
d = self.handleRequest(xml)
d.addCallback(cb)
return d
0
Example 129
def typeCheck(self):
"""
Check field properties agains the set field type.
"""
if self.var is None and self.fieldType != 'fixed':
raise FieldNameRequiredError()
if self.values:
if (self.fieldType not in ('hidden', 'jid-multi', 'list-multi',
'text-multi', None) and
len(self.values) > 1):
raise TooManyValuesError()
newValues = []
for value in self.values:
if self.fieldType == 'boolean':
if isinstance(value, (str, unicode)):
checkValue = value.lower()
if not checkValue in ('0', '1', 'false', 'true'):
raise ValueError("Not a boolean")
value = checkValue in ('1', 'true')
value = bool(value)
elif self.fieldType in ('jid-single', 'jid-multi'):
if not hasattr(value, 'full'):
value = JID(value)
newValues.append(value)
self.values = newValues
0
Example 130
Project: wokkel Source File: test_disco.py
def test_itemsNotDeferred(self):
"""
C{info} should also collect results not returned via a deferred.
"""
discoItems = [disco.DiscoItem(JID('example.com'), 'test', 'Test node')]
@implementer(disco.IDisco)
class DiscoResponder(XMPPHandler):
def getDiscoItems(self, requestor, target, nodeIdentifier):
if not nodeIdentifier:
return discoItems
else:
return []
def cb(result):
self.assertEquals(discoItems, result)
self.service.parent = [self.service, DiscoResponder()]
d = self.service.items(JID('[email protected]'), JID('example.com'), '')
d.addCallback(cb)
return d
0
Example 131
Project: idavoll Source File: gateway.py
def getServiceAndNode(uri):
"""
Given an XMPP URI, extract the publish subscribe service JID and node ID.
"""
try:
scheme, rest = uri.split(':', 1)
except ValueError:
raise XMPPURIParseError("No URI scheme component")
if scheme != 'xmpp':
raise XMPPURIParseError("Unknown URI scheme")
if rest.startswith("//"):
raise XMPPURIParseError("Unexpected URI authority component")
try:
entity, query = rest.split('?', 1)
except ValueError:
entity, query = rest, ''
if not entity:
raise XMPPURIParseError("Empty URI path component")
try:
service = JID(entity)
except Exception, e:
raise XMPPURIParseError("Invalid JID: %s" % e)
params = urlparse.parse_qs(query)
try:
nodeIdentifier = params['node'][0]
except (KeyError, ValueError):
nodeIdentifier = ''
return service, nodeIdentifier
0
Example 132
def postOptions(self):
if self['backend'] not in ['pgsql', 'memory']:
raise usage.UsageError, "Unknown backend!"
self['jid'] = JID(self['jid'])
0
Example 134
def setUp(self):
self.stub = XmlStreamStub()
self.client = FakeClient(self.stub.xmlstream, JID('[email protected]'))
self.service = xmppim.RosterClientProtocol()
self.service.setHandlerParent(self.client)
0
Example 135
Project: wokkel Source File: test_xmppim.py
def test_setItem(self):
"""
Setting a roster item renders the item and sends it out.
"""
item = xmppim.RosterItem(JID('[email protected]'),
name='Joe User',
groups=set(['Friends', 'Jabber']))
d = self.service.setItem(item)
# Inspect outgoing iq request
iq = self.stub.output[-1]
self.assertEqual('set', iq.getAttribute('type'))
self.assertNotIdentical(None, iq.query)
self.assertEqual(NS_ROSTER, iq.query.uri)
children = list(domish.generateElementsQNamed(iq.query.children,
'item', NS_ROSTER))
self.assertEqual(1, len(children))
child = children[0]
self.assertEqual('[email protected]', child['jid'])
self.assertIdentical(None, child.getAttribute('subscription'))
# Fake successful response
response = toResponse(iq, 'result')
d.callback(response)
return d
0
Example 136
def setUp(self):
self.factory = client.DeferredClientFactory(JID('[email protected]'),
'secret')
0
Example 137
Project: wokkel Source File: test_xmppim.py
def test_setItemIgnoreAttributes(self):
"""
Certain attributes should be rendered for roster set.
"""
item = xmppim.RosterItem(JID('[email protected]'),
subscriptionTo=True,
subscriptionFrom=False,
name='Joe User',
groups=set(['Friends', 'Jabber']))
item.pendingOut = True
item.approved = True
d = self.service.setItem(item)
# Inspect outgoing iq request
iq = self.stub.output[-1]
self.assertEqual('set', iq.getAttribute('type'))
self.assertNotIdentical(None, iq.query)
self.assertEqual(NS_ROSTER, iq.query.uri)
children = list(domish.generateElementsQNamed(iq.query.children,
'item', NS_ROSTER))
self.assertEqual(1, len(children))
child = children[0]
self.assertIdentical(None, child.getAttribute('ask'))
self.assertIdentical(None, child.getAttribute('approved'))
self.assertIdentical(None, child.getAttribute('subscription'))
# Fake successful response
response = toResponse(iq, 'result')
d.callback(response)
return d
0
Example 138
Project: wokkel Source File: test_xmppim.py
def test_onRosterSet(self):
"""
A roster push causes onRosterSet to be called with the parsed item.
"""
xml = """
<iq type='set'>
<query xmlns='jabber:iq:roster'>
<item jid='[email protected]'/>
</query>
</iq>
"""
items = []
def onRosterSet(item):
items.append(item)
def cb(result):
self.assertEqual(1, len(items))
self.assertEqual(JID('[email protected]'), items[0].entity)
self.service.onRosterSet = onRosterSet
d = self.assertWarns(DeprecationWarning,
"wokkel.xmppim.RosterClientProtocol.onRosterSet "
"was deprecated in Wokkel 0.7.1; "
"please use RosterClientProtocol.setReceived "
"instead.",
xmppim.__file__,
self.handleRequest, xml)
d.addCallback(cb)
return d
0
Example 139
def test_basic(self):
uri = gateway.getXMPPURI(JID(u'pubsub.example.org'), u'test')
self.assertEqual('xmpp:pubsub.example.org?;node=test', uri)
0
Example 140
Project: wokkel Source File: test_data_form.py
def test_makeField(self):
"""
Fields can be created from a dict of values and a dict of field defs.
"""
fieldDefs = {
"pubsub#persist_items":
{"type": "boolean",
"label": "Persist items to storage"},
"pubsub#deliver_payloads":
{"type": "boolean",
"label": "Deliver payloads with event notifications"},
"pubsub#creator":
{"type": "jid-single",
"label": "The JID of the node creator"},
"pubsub#description":
{"type": "text-single",
"label": "A description of the node"},
"pubsub#owner":
{"type": "jid-single",
"label": "Owner of the node"},
}
values = {'pubsub#deliver_payloads': '0',
'pubsub#persist_items': True,
'pubsub#description': 'a great node',
'pubsub#owner': jid.JID('[email protected]'),
'x-myfield': ['a', 'b']}
form = data_form.Form('submit')
form.makeFields(values, fieldDefs)
# Check that the expected fields have been created
self.assertIn('pubsub#deliver_payloads', form.fields)
self.assertIn('pubsub#persist_items', form.fields)
self.assertIn('pubsub#description', form.fields)
self.assertIn('pubsub#owner', form.fields)
# This field is not created because there is no value for it.
self.assertNotIn('pubsub#creator', form.fields)
# This field is not created because it does not appear in fieldDefs
# and filterUnknown defaults to True
self.assertNotIn('x-myfield', form.fields)
# Check properties the created fields
self.assertEqual('boolean',
form.fields['pubsub#deliver_payloads'].fieldType)
self.assertEqual('0',
form.fields['pubsub#deliver_payloads'].value)
self.assertEqual('Deliver payloads with event notifications',
form.fields['pubsub#deliver_payloads'].label)
self.assertEqual(True,
form.fields['pubsub#persist_items'].value)
0
Example 141
Project: wokkel Source File: test_xmppim.py
def test_onRosterRemove(self):
"""
A roster push causes onRosterSet to be called with the parsed item.
"""
xml = """
<iq type='set'>
<query xmlns='jabber:iq:roster'>
<item jid='[email protected]' subscription='remove'/>
</query>
</iq>
"""
entities = []
def onRosterRemove(entity):
entities.append(entity)
def cb(result):
self.assertEqual([JID('[email protected]')], entities)
self.service.onRosterRemove = onRosterRemove
d = self.assertWarns(DeprecationWarning,
"wokkel.xmppim.RosterClientProtocol.onRosterRemove "
"was deprecated in Wokkel 0.7.1; "
"please use RosterClientProtocol.removeReceived "
"instead.",
xmppim.__file__,
self.handleRequest, xml)
d.addCallback(cb)
return d
0
Example 142
Project: wokkel Source File: xmppim.py
def _onPresenceSubscribed(self, presence):
self.subscribedReceived(JID(presence["from"]))
0
Example 143
Project: wokkel Source File: test_disco.py
def test_requestItems(self):
"""
Test request sent out by C{requestItems} and parsing of response.
"""
def cb(items):
items = list(items)
self.assertEqual(2, len(items))
self.assertEqual(JID(u'test.example.org'), items[0].entity)
d = self.protocol.requestItems(JID(u'example.org'),u"foo")
d.addCallback(cb)
iq = self.stub.output[-1]
self.assertEqual(u'example.org', iq.getAttribute(u'to'))
self.assertEqual(u'get', iq.getAttribute(u'type'))
self.assertEqual(u'foo', iq.query.getAttribute(u'node'))
self.assertEqual(NS_DISCO_ITEMS, iq.query.uri)
response = toResponse(iq, u'result')
query = response.addElement((NS_DISCO_ITEMS, u'query'))
element = query.addElement(u'item')
element[u'jid'] = u'test.example.org'
element[u'node'] = u'music'
element[u'name'] = u'Music from the time of Shakespeare'
element = query.addElement(u'item')
element[u'jid'] = u"test2.example.org"
d.callback(response)
return d
0
Example 144
Project: wokkel Source File: xmppim.py
def _onPresenceUnsubscribed(self, presence):
self.unsubscribedReceived(JID(presence["from"]))
0
Example 145
Project: wokkel Source File: xmppim.py
def _onPresenceSubscribe(self, presence):
self.subscribeReceived(JID(presence["from"]))
0
Example 146
Project: vumi Source File: xmpp.py
def setup_transport(self):
self.log.msg("Starting XMPPTransport: %s" % self.transport_name)
self.jid = JID(self.username)
self.xmpp_client = self._xmpp_client(
self.jid, self.password, self.host, self.port)
self.xmpp_client.logTraffic = self.debug
self.xmpp_client.setServiceParent(self)
self.presence = TransportPresenceClientProtocol(self.announce_presence)
self.presence.setHandlerParent(self.xmpp_client)
self.pinger = PingClientProtocol()
self.pinger.setHandlerParent(self.xmpp_client)
self.ping_call.start(self.ping_interval, now=False)
roster = TransportRosterClientProtocol()
roster.setHandlerParent(self.xmpp_client)
self.xmpp_protocol = self._xmpp_protocol(
self.jid, self.publish_message, self.unpause_connectors,
connection_lost_callback=self.connection_lost)
self.xmpp_protocol.setHandlerParent(self.xmpp_client)
self.log.msg("XMPPTransport %s started." % self.transport_name)
0
Example 147
def __init__(self):
rootNode = CollectionNode('', jid.JID('localhost'),
copy.copy(self.defaultConfig['collection']))
self._nodes = {'': rootNode}
0
Example 148
def route(self, stanza):
"""
Route a stanza.
@param stanza: The stanza to be routed.
@type stanza: L{domish.Element}.
"""
destination = JID(stanza['to'])
if destination.host in self.routes:
log.msg("Routing to %s: %r" % (destination.full(),
stanza.toXml()))
self.routes[destination.host].send(stanza)
elif None in self.routes:
log.msg("Routing to %s (default route): %r" % (destination.full(),
stanza.toXml()))
self.routes[None].send(stanza)
else:
log.msg("No route to %s: %r" % (destination.full(),
stanza.toXml()))
if stanza.getAttribute('type') not in ('result', 'error'):
# No route, send back error
exc = error.StanzaError('remote-server-timeout', type='wait')
exc.code = '504'
response = exc.toResponse(stanza)
self.route(response)
0
Example 149
def test_requestInfo(self):
"""
Test request sent out by C{requestInfo} and parsing of response.
"""
def cb(info):
self.assertIn((u'conference', u'text'), info.identities)
self.assertIn(u'http://jabber.org/protocol/disco#info',
info.features)
self.assertIn(u'http://jabber.org/protocol/muc',
info.features)
d = self.protocol.requestInfo(JID(u'example.org'),'foo')
d.addCallback(cb)
iq = self.stub.output[-1]
self.assertEqual(u'example.org', iq.getAttribute(u'to'))
self.assertEqual(u'get', iq.getAttribute(u'type'))
self.assertEqual(u'foo', iq.query.getAttribute(u'node'))
self.assertEqual(NS_DISCO_INFO, iq.query.uri)
response = toResponse(iq, u'result')
query = response.addElement((NS_DISCO_INFO, u'query'))
element = query.addElement(u"identity")
element[u'category'] = u'conference' # required
element[u'type'] = u'text' # required
element[u"name"] = u'Romeo and Juliet, Act II, Scene II' # optional
element = query.addElement("feature")
element[u'var'] = u'http://jabber.org/protocol/disco#info' # required
element = query.addElement(u"feature")
element[u'var'] = u'http://jabber.org/protocol/muc'
d.callback(response)
return d
0
Example 150
Project: wokkel Source File: xmppim.py
def _onPresenceUnsubscribe(self, presence):
self.unsubscribeReceived(JID(presence["from"]))