Revision: 2253
Author: jpalanca
Date: Fri Nov 23 05:19:16 2012
Log: (1) xmppd/xmppd.py: Solved multisession_thread daemonic bug.
(2) spade/Agent.py: Solved kill issues whith daemonic threads, added
hasBehaviour method, if register fails AgentNotRegisteredError exception is
raised.
(3) spade/MessageReceiver.py: _receive is not blocked anymore, checking
periodically if was killed.
(4) test/kbTestCase.py: skipped SPARQL tests.
(5) spade/mtp/http.py: solved blocking thread. Now has a timeout.
(6) spade/peer2peer.py: P2P behavior is also no longer blocking. Uses a
timeout.
(7) spade/wui.py: another daemonic thread bug solved.
(8) configure.py: Added default admin password for WUI. The default
password is 'secret'.
(9) All files have been modified according to the PEP8 conventions.
(10) All files encoded in UTF-8.
This is the last commit using subversion. We switch to git. Pray what you
know...
http://code.google.com/p/spade2/source/detail?r=2253
Added:
/trunk/doc/manual/html/spade.basic.features.html
/trunk/test/socialTestCase.py
Modified:
/trunk/ChangeLog
/trunk/configure.py
/trunk/runspade.py
/trunk/spade/ACLMessage.py
/trunk/spade/ACLParser.py
/trunk/spade/AID.py
/trunk/spade/AMS.py
/trunk/spade/Agent.py
/trunk/spade/BasicFipaDateTime.py
/trunk/spade/Behaviour.py
/trunk/spade/DF.py
/trunk/spade/ECLiPSeKB.py
/trunk/spade/Envelope.py
/trunk/spade/FIPAMessage.py
/trunk/spade/FlexQueue.py
/trunk/spade/Flora2KB.py
/trunk/spade/MTP.py
/trunk/spade/MessageReceiver.py
/trunk/spade/Organization.py
/trunk/spade/Organization_new.py
/trunk/spade/Platform.py
/trunk/spade/RDF0Parser.py
/trunk/spade/RPC.py
/trunk/spade/ReceivedObject.py
/trunk/spade/SIMBA.py
/trunk/spade/SL0Parser.py
/trunk/spade/SPARQLKB.py
/trunk/spade/SWIKB.py
/trunk/spade/SpadeConfigParser.py
/trunk/spade/Unit.py
/trunk/spade/Unit_new.py
/trunk/spade/XMLCodec.py
/trunk/spade/XSBKB.py
/trunk/spade/__init__.py
/trunk/spade/bdi.py
/trunk/spade/colors.py
/trunk/spade/content.py
/trunk/spade/dblite.py
/trunk/spade/fipa.py
/trunk/spade/kb.py
/trunk/spade/logic.py
/trunk/spade/msgtypes.py
/trunk/spade/mtp/http.py
/trunk/spade/mtp/simba.py
/trunk/spade/odict.py
/trunk/spade/peer2peer.py
/trunk/spade/pubsub.py
/trunk/spade/pygooglechart.py
/trunk/spade/pyparsing.py
/trunk/spade/pyratemp.py
/trunk/spade/pyxf.py
/trunk/spade/socialnetwork.py
/trunk/spade/spade_backend.py
/trunk/spade/tbcbp.py
/trunk/spade/wui.py
/trunk/test/aidTestCase.py
/trunk/test/amsTestCase.py
/trunk/test/basicTestCase.py
/trunk/test/bdiTestCase.py
/trunk/test/coTestCase.py
/trunk/test/dadTestCase.py
/trunk/test/dfTestCase.py
/trunk/test/eventbehavTestCase.py
/trunk/test/factsTestCase.py
/trunk/test/httpTestCase.py
/trunk/test/jsonTestCase.py
/trunk/test/kbTestCase.py
/trunk/test/p2pTestCase.py
/trunk/test/pubsubTestCase.py
/trunk/test/rpcTestCase.py
/trunk/test/tbcbpTestCase.py
/trunk/test/xfTestCase.py
/trunk/test.py
/trunk/xmppd/generate-cert.py
/trunk/xmppd/locales.py
/trunk/xmppd/modules/__init__.py
/trunk/xmppd/modules/config.py
/trunk/xmppd/modules/db_fake.py
/trunk/xmppd/modules/dialback.py
/trunk/xmppd/modules/jep0077.py
/trunk/xmppd/modules/jep0078.py
/trunk/xmppd/modules/message.py
/trunk/xmppd/modules/muc.py
/trunk/xmppd/modules/oob.py
/trunk/xmppd/modules/pubsub.py
/trunk/xmppd/modules/roster.py
/trunk/xmppd/modules/router.py
/trunk/xmppd/modules/stream.py
/trunk/xmppd/modules/webadmin.py
/trunk/xmppd/modules/wq.py
/trunk/xmppd/socker/router.py
/trunk/xmppd/socker/socker.py
/trunk/xmppd/tools/client.py
/trunk/xmppd/tools/ping.py
/trunk/xmppd/tools/xsend.py
/trunk/xmppd/xmppd.py
=======================================
--- /dev/null
+++ /trunk/doc/manual/html/spade.basic.features.html Fri Nov 23 05:19:16
2012
@@ -0,0 +1,63 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+<title></title>
+<link rel="stylesheet" type="text/css" href="styles.css">
+<meta name="generator" content="DocBook XSL Stylesheets V1.77.1">
+<link rel="home" href="index.html" title="SPADE User's Manual">
+<link rel="up" href="spade.basic.html" title="Chapter 1. Basic Concepts">
+<link rel="prev" href="spade.basic.spadelibrary.html" title="The SPADE
Agent Library">
+<link rel="next" href="spade.basic.whatsnext.html" title="What's Next?">
+</head>
+<body bgcolor="white" text="black" link="#0000FF" vlink="#840084"
alink="#0000FF">
+<div class="navheader">
+<table width="100%" summary="Navigation header">
+<tr><th colspan="3" align="center"></th></tr>
+<tr>
+<td width="20%" align="left">
+<a accesskey="p" href="spade.basic.spadelibrary.html">Prev</a>Â </td>
+<th width="60%" align="center">Chapter 1. Basic Concepts</th>
+<td width="20%" align="right">Â <a accesskey="n"
href="spade.basic.whatsnext.html">Next</a>
+</td>
+</tr>
+</table>
+<hr>
+</div>
+<div class="section">
+<div class="titlepage"></div>
+<p>
+ The main features of SPADE are:
+ </p>
+<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type:
disc; ">
+<li class="listitem"><p>Developed using Python</p></li>
+<li class="listitem"><p>Covers the FIPA standard</p></li>
+<li class="listitem"><p>Implements four MTPs: XMPP, P2P, HTTP and
SIMBA</p></li>
+<li class="listitem"><p>Supports two content languages: FIPA-SL and
RDF</p></li>
+<li class="listitem"><p>SPADE agents do reach their goals by running
deliberative and reactive tasks</p></li>
+<li class="listitem"><p>Has a web interface to manage the platform</p></li>
+<li class="listitem"><p>Allows its execution in several platforms and
operating systems</p></li>
+<li class="listitem"><p>Presence notification allows the system to
determine the current state of the agents in real-time</p></li>
+<li class="listitem"><p>Multi-user conference allows agents to create
organizations and groups of agents</p></li>
+</ul></div>
+<p>
+ </p>
+</div>
+<div class="navfooter">
+<hr>
+<table width="100%" summary="Navigation footer">
+<tr>
+<td width="40%" align="left">
+<a accesskey="p" href="spade.basic.spadelibrary.html">Prev</a>Â </td>
+<td width="20%" align="center"><a accesskey="u"
href="spade.basic.html">Up</a></td>
+<td width="40%" align="right">Â <a accesskey="n"
href="spade.basic.whatsnext.html">Next</a>
+</td>
+</tr>
+<tr>
+<td width="40%" align="left" valign="top">The SPADE Agent Library </td>
+<td width="20%" align="center"><a accesskey="h"
href="index.html">Home</a></td>
+<td width="40%" align="right" valign="top">Â What's Next?</td>
+</tr>
+</table>
+</div>
+</body>
+</html>
=======================================
--- /dev/null
+++ /trunk/test/socialTestCase.py Fri Nov 23 05:19:16 2012
@@ -0,0 +1,64 @@
+# -*- coding: utf-8 -*-
+import os
+import sys
+import time
+import unittest
+
+import spade
+
+host = "127.0.0.1"
+
+
+class SubscribeBehaviour(spade.Behaviour.EventBehaviour):
+
+ def _process(self):
+ msg = self._receive(True)
+ self.myAgent.eventmsg = msg
+
+
+class socialTestCase(unittest.TestCase):
+
+ def setUp(self):
+
+ self.Aaid = spade.AID.aid("a@" + host, ["xmpp://a@" + host])
+ self.Baid = spade.AID.aid("b@" + host, ["xmpp://b@" + host])
+
+ self.a = spade.Agent.Agent("a@" + host, "secret")
+ self.a.start()
+ #self.a.setDebugToScreen()
+
+ self.b = spade.Agent.Agent("b@" + host, "secret")
+ self.b.start()
+
+ self.a.setSocialItem('b@' + host)
+ #self.a._socialnetwork['b@'+host].unsubscribe()
+ del self.a._socialnetwork['b@' + host]
+ self.b.setSocialItem('a@' + host)
+ #self.b._socialnetwork['a@'+host].unsubscribe()
+ del self.b._socialnetwork['a@' + host]
+
+ def tearDown(self):
+ self.a.stop()
+ self.b.stop()
+
+ def testNoSocialItem(self):
+ jid = 'b@' + host
+
+ self.assertFalse(jid in self.a._socialnetwork)
+ self.assertFalse(jid in self.a._roster)
+
+ def testSetSocialItem(self):
+ jid = 'b@' + host
+ self.a.setSocialItem(jid)
+
+ self.assertTrue(jid in self.a._socialnetwork)
+
+ assert self.a._socialnetwork[jid].getPresence() == ""
+
+ assert self.a._socialnetwork[jid]._subscription == "none"
+
+ self.assertFalse(jid in self.a._roster)
+
+if __name__ == "__main__":
+ unittest.main()
+ sys.exit()
=======================================
--- /trunk/ChangeLog Tue Jul 31 08:17:01 2012
+++ /trunk/ChangeLog Fri Nov 23 05:19:16 2012
@@ -1,3 +1,1336 @@
+2012-11-23 14:16 jpalanca
+
+ * trunk/*: (1) xmppd/xmppd.py: Solved multisession_thread daemonic bug.
+ (2) spade/Agent.py: Solved kill issues whith daemonic threads,
+ added hasBehaviour method, if register fails AgentNotRegisteredError
+ exception is raised.
+ (3) spade/MessageReceiver.py: _receive is not blocked anymore,
+ checking periodically if was killed.
+ (4) test/kbTestCase.py: skipped SPARQL tests.
+ (5) spade/mtp/http.py: solved blocking thread. Now has a timeout.
+ (6) spade/peer2peer.py: P2P behavior is also no longer blocking. Uses a
timeout.
+ (7) spade/wui.py: another daemonic thread bug solved.
+ (8) configure.py: Added default admin password for WUI. The default
password is 'secret'.
+ (9) All files have been modified according to the PEP8 conventions.
+ (10) All files encoded in UTF-8.
+ This is the last commit using subversion. We switch to git. Pray what
you know...
+
+2012-11-12 17:28 jpalanca
+
+ * trunk/doc/manual/book.xml,
+ trunk/doc/manual/ch00-introduction-to-spade.xml,
+ trunk/doc/manual/ch01-quickstart-guide.xml,
+ trunk/doc/manual/ch02-fundamental-concepts.xml,
+ trunk/doc/manual/ch03-basic-agents.xml,
+ trunk/doc/manual/ch06-bdi.xml, trunk/doc/manual/html/ch05s03.html,
+ trunk/doc/manual/html/index.html,
+ trunk/doc/manual/html/spade.advanced.eventbehaviour.html,
+ trunk/doc/manual/html/spade.advanced.fsm.html,
+ trunk/doc/manual/html/spade.advanced.html,
+ trunk/doc/manual/html/spade.basic.html,
+ trunk/doc/manual/html/spade.basic.im.html,
+ trunk/doc/manual/html/spade.basic.mas.html,
+ trunk/doc/manual/html/spade.basic.spadelibrary.html,
+ trunk/doc/manual/html/spade.basic.spadeplatform.html,
+ trunk/doc/manual/html/spade.basic.whatsnext.html,
+ trunk/doc/manual/html/spade.basicagents.agentmodel.communication.html,
+ trunk/doc/manual/html/spade.basicagents.agentmodel.html,
+ trunk/doc/manual/html/spade.basicagents.behav.html,
+ trunk/doc/manual/html/spade.basicagents.first.html,
+ trunk/doc/manual/html/spade.basicagents.html,
+ trunk/doc/manual/html/spade.basicagents.library.html,
+ trunk/doc/manual/html/spade.basicagents.whatsnext.html,
+ trunk/doc/manual/html/spade.bdi.future.html,
+ trunk/doc/manual/html/spade.bdi.goals.html,
+ trunk/doc/manual/html/spade.bdi.html,
+ trunk/doc/manual/html/spade.bdi.intro.html,
+ trunk/doc/manual/html/spade.bdi.kb.html,
+ trunk/doc/manual/html/spade.bdi.plans.html,
+ trunk/doc/manual/html/spade.bdi.running.html,
+ trunk/doc/manual/html/spade.foreword.html,
+ trunk/doc/manual/html/spade.fundamental.html,
+ trunk/doc/manual/html/spade.fundamental.platform.html,
+ trunk/doc/manual/html/spade.platform.ams.html,
+ trunk/doc/manual/html/spade.platform.df.html,
+ trunk/doc/manual/html/spade.platform.html,
+ trunk/doc/manual/html/spade.quickstart.html,
+ trunk/doc/manual/html/spade.quickstart.installation.html,
+ trunk/doc/manual/html/spade.quickstart.requirements.html,
+ trunk/setup.py, trunk/test/bdiTestCase.py,
+ trunk/test/kbTestCase.py: - Updated documentation with corrections
+ about the SPADE 2.1 release. - Rewritten the BDI chapter of the
+ documentation, now with the current implementation of the bdi
+ module. - Updated SPADE requirements. Now SPADE needs Python 2.7
+ or above (sorry old machines).
+
+2012-11-09 18:06 jpalanca
+
+ * trunk/test/httpTestCase.py, trunk/test/jsonTestCase.py: added
+ missing testcases
+
+2012-11-09 17:51 jpalanca
+
+ * trunk/configure.py, trunk/runspade.py, trunk/spade/ACLMessage.py,
+ trunk/spade/ACLParser.py, trunk/spade/AID.py,
+ trunk/spade/Agent.py, trunk/spade/Envelope.py, trunk/spade/MTP.py,
+ trunk/spade/Platform.py, trunk/spade/mtp/http.py,
+ trunk/spade/spade_backend.py, trunk/spade/wui.py, trunk/test.py,
+ trunk/test/kbTestCase.py, trunk/test/unittests_spade.xml: Version
+ 2.1: -JSON support for ACL Messages and Envelopes -HTTP protocol
+ can send both XML and JSON messages -New unittests added:
+ jsonTestCase and httpTestCase -Some minor bugs fixed -HTTP
+ transport is now activated by default -XMPPD server deals with
+ max_sockets error -AID, ACLMessage and Envelope classess can be
+ marshalled in JSON (asJSON) and unmarshalled from JSON (loadJSON)
+
+2012-10-22 21:29
schatte...@gmail.com
+
+ * trunk/xmpp/auth.py: Fixed spelling error in xmpp/auth.py
+
+2012-08-01 16:48 jpalanca
+
+ * trunk/doc/api, trunk/doc/api/api-objects.txt,
+ trunk/doc/api/class-tree.html, trunk/doc/api/crarr.png,
+ trunk/doc/api/epydoc.css, trunk/doc/api/epydoc.js,
+ trunk/doc/api/frames.html, trunk/doc/api/help.html,
+ trunk/doc/api/identifier-index-A.html,
+ trunk/doc/api/identifier-index-B.html,
+ trunk/doc/api/identifier-index-C.html,
+ trunk/doc/api/identifier-index-D.html,
+ trunk/doc/api/identifier-index-E.html,
+ trunk/doc/api/identifier-index-F.html,
+ trunk/doc/api/identifier-index-G.html,
+ trunk/doc/api/identifier-index-H.html,
+ trunk/doc/api/identifier-index-I.html,
+ trunk/doc/api/identifier-index-J.html,
+ trunk/doc/api/identifier-index-K.html,
+ trunk/doc/api/identifier-index-L.html,
+ trunk/doc/api/identifier-index-M.html,
+ trunk/doc/api/identifier-index-N.html,
+ trunk/doc/api/identifier-index-O.html,
+ trunk/doc/api/identifier-index-P.html,
+ trunk/doc/api/identifier-index-Q.html,
+ trunk/doc/api/identifier-index-R.html,
+ trunk/doc/api/identifier-index-S.html,
+ trunk/doc/api/identifier-index-T.html,
+ trunk/doc/api/identifier-index-U.html,
+ trunk/doc/api/identifier-index-V.html,
+ trunk/doc/api/identifier-index-W.html,
+ trunk/doc/api/identifier-index-X.html,
+ trunk/doc/api/identifier-index-Y.html,
+ trunk/doc/api/identifier-index-Z.html,
+ trunk/doc/api/identifier-index-_.html,
+ trunk/doc/api/identifier-index.html, trunk/doc/api/index.html,
+ trunk/doc/api/mimetools.Message-class.html,
+ trunk/doc/api/module-tree.html, trunk/doc/api/redirect.html,
+ trunk/doc/api/spade-module.html, trunk/doc/api/spade-pysrc.html,
+ trunk/doc/api/spade.ACLMessage-module.html,
+ trunk/doc/api/spade.ACLMessage-pysrc.html,
+ trunk/doc/api/spade.ACLMessage.ACLMessage-class.html,
+ trunk/doc/api/spade.ACLParser-module.html,
+ trunk/doc/api/spade.ACLParser-pysrc.html,
+ trunk/doc/api/spade.ACLParser.ACLParser-class.html,
+ trunk/doc/api/spade.ACLParser.ACLxmlParser-class.html,
+ trunk/doc/api/spade.AID-module.html,
+ trunk/doc/api/spade.AID-pysrc.html,
+ trunk/doc/api/spade.AID.aid-class.html,
+ trunk/doc/api/spade.AMS-module.html,
+ trunk/doc/api/spade.AMS-pysrc.html,
+ trunk/doc/api/spade.AMS.AMS-class.html,
+ trunk/doc/api/spade.AMS.AMS.DefaultBehaviour-class.html,
+
trunk/doc/api/spade.AMS.AMS.DefaultBehaviour.SubscribeBehaviour-class.html,
+ trunk/doc/api/spade.AMS.AMS.ModifyBehaviour-class.html,
+ trunk/doc/api/spade.AMS.AMS.PlatformBehaviour-class.html,
+ trunk/doc/api/spade.AMS.AMS.RegisterBehaviour-class.html,
+ trunk/doc/api/spade.AMS.AMS.SearchBehaviour-class.html,
+ trunk/doc/api/spade.AMS.AmsAgentDescription-class.html,
+ trunk/doc/api/spade.Agent-module.html,
+ trunk/doc/api/spade.Agent-pysrc.html,
+ trunk/doc/api/spade.Agent.AbstractAgent-class.html,
+ trunk/doc/api/spade.Agent.Agent-class.html,
+ trunk/doc/api/spade.Agent.BDIAgent-class.html,
+ trunk/doc/api/spade.Agent.PlatformAgent-class.html,
+ trunk/doc/api/spade.Agent.jabberProcess-class.html,
+ trunk/doc/api/spade.BasicFipaDateTime-module.html,
+ trunk/doc/api/spade.BasicFipaDateTime-pysrc.html,
+ trunk/doc/api/spade.BasicFipaDateTime.BasicFipaDateTime-class.html,
+ trunk/doc/api/spade.Behaviour-module.html,
+ trunk/doc/api/spade.Behaviour-pysrc.html,
+ trunk/doc/api/spade.Behaviour.ACLTemplate-class.html,
+ trunk/doc/api/spade.Behaviour.ANDTemplate-class.html,
+ trunk/doc/api/spade.Behaviour.Behaviour-class.html,
+ trunk/doc/api/spade.Behaviour.BehaviourTemplate-class.html,
+ trunk/doc/api/spade.Behaviour.EventBehaviour-class.html,
+ trunk/doc/api/spade.Behaviour.FSMBehaviour-class.html,
+ trunk/doc/api/spade.Behaviour.MessageTemplate-class.html,
+ trunk/doc/api/spade.Behaviour.NOTTemplate-class.html,
+ trunk/doc/api/spade.Behaviour.ORTemplate-class.html,
+ trunk/doc/api/spade.Behaviour.OneShotBehaviour-class.html,
+ trunk/doc/api/spade.Behaviour.PeriodicBehaviour-class.html,
+ trunk/doc/api/spade.Behaviour.TimeOutBehaviour-class.html,
+ trunk/doc/api/spade.Behaviour.XORTemplate-class.html,
+ trunk/doc/api/spade.DF-module.html,
+ trunk/doc/api/spade.DF-pysrc.html,
+ trunk/doc/api/spade.DF.DF-class.html,
+ trunk/doc/api/spade.DF.DF.DefaultBehaviour-class.html,
+ trunk/doc/api/spade.DF.DF.ModifyBehaviour-class.html,
+ trunk/doc/api/spade.DF.DF.RegisterBehaviour-class.html,
+ trunk/doc/api/spade.DF.DF.SearchBehaviour-class.html,
+ trunk/doc/api/spade.DF.DfAgentDescription-class.html,
+ trunk/doc/api/spade.DF.Service-class.html,
+ trunk/doc/api/spade.DF.ServiceDescription-class.html,
+ trunk/doc/api/spade.ECLiPSeKB-module.html,
+ trunk/doc/api/spade.ECLiPSeKB-pysrc.html,
+ trunk/doc/api/spade.ECLiPSeKB.ECLiPSeKB-class.html,
+ trunk/doc/api/spade.Envelope-module.html,
+ trunk/doc/api/spade.Envelope-pysrc.html,
+ trunk/doc/api/spade.Envelope.Envelope-class.html,
+ trunk/doc/api/spade.FIPAMessage-module.html,
+ trunk/doc/api/spade.FIPAMessage-pysrc.html,
+ trunk/doc/api/spade.FIPAMessage.FipaMessage-class.html,
+ trunk/doc/api/spade.FlexQueue-module.html,
+ trunk/doc/api/spade.FlexQueue-pysrc.html,
+ trunk/doc/api/spade.FlexQueue.FlexQueue-class.html,
+ trunk/doc/api/spade.Flora2KB-module.html,
+ trunk/doc/api/spade.Flora2KB-pysrc.html,
+ trunk/doc/api/spade.Flora2KB.Flora2KB-class.html,
+ trunk/doc/api/spade.MTP-module.html,
+ trunk/doc/api/spade.MTP-pysrc.html,
+ trunk/doc/api/spade.MTP.MTP-class.html,
+ trunk/doc/api/spade.MessageReceiver-module.html,
+ trunk/doc/api/spade.MessageReceiver-pysrc.html,
+ trunk/doc/api/spade.MessageReceiver.MessageReceiver-class.html,
+ trunk/doc/api/spade.Organization-module.html,
+ trunk/doc/api/spade.Organization-pysrc.html,
+ trunk/doc/api/spade.Organization.BanedUser-class.html,
+ trunk/doc/api/spade.Organization.CreationError-class.html,
+ trunk/doc/api/spade.Organization.DestroyError-class.html,
+ trunk/doc/api/spade.Organization.JoinError-class.html,
+ trunk/doc/api/spade.Organization.LastOwner-class.html,
+ trunk/doc/api/spade.Organization.LockedOrganization-class.html,
+ trunk/doc/api/spade.Organization.MaximumUsers-class.html,
+ trunk/doc/api/spade.Organization.MemberOfFederation-class.html,
+ trunk/doc/api/spade.Organization.MembersOnly-class.html,
+ trunk/doc/api/spade.Organization.NickNameConflict-class.html,
+ trunk/doc/api/spade.Organization.NotOwner-class.html,
+ trunk/doc/api/spade.Organization.NotSupervisor-class.html,
+ trunk/doc/api/spade.Organization.NotValidGoal-class.html,
+ trunk/doc/api/spade.Organization.NotValidName-class.html,
+ trunk/doc/api/spade.Organization.NotValidType-class.html,
+ trunk/doc/api/spade.Organization.NotValidUnit-class.html,
+ trunk/doc/api/spade.Organization.Organization-class.html,
+
trunk/doc/api/spade.Organization.Organization.CreateRoomBehaviour-class.html,
+
trunk/doc/api/spade.Organization.Organization.CreateTeamBehaviour-class.html,
+
trunk/doc/api/spade.Organization.Organization.DestroyBehaviour-class.html,
+
trunk/doc/api/spade.Organization.Organization.GetRegistrationFormBehaviour-class.html,
+
trunk/doc/api/spade.Organization.Organization.GetUnitInfoBehaviour-class.html,
+
trunk/doc/api/spade.Organization.Organization.GetUnitListBehaviour-class.html,
+
trunk/doc/api/spade.Organization.Organization.IsMemberBehaviour-class.html,
+
trunk/doc/api/spade.Organization.Organization.MyJoinRoomBehaviour-class.html,
+
trunk/doc/api/spade.Organization.Organization.SendRegistrationFormBehaviour-class.html,
+
trunk/doc/api/spade.Organization.Organization.TestRoomNameBehaviour-class.html,
+ trunk/doc/api/spade.Organization.PaswordNeeded-class.html,
+ trunk/doc/api/spade.Organization.Unavailable-class.html,
+ trunk/doc/api/spade.Organization.UnavailableFunction-class.html,
+ trunk/doc/api/spade.Organization_new-module.html,
+ trunk/doc/api/spade.Organization_new-pysrc.html,
+ trunk/doc/api/spade.Organization_new.BanedUser-class.html,
+ trunk/doc/api/spade.Organization_new.CreationError-class.html,
+ trunk/doc/api/spade.Organization_new.DestroyError-class.html,
+ trunk/doc/api/spade.Organization_new.JoinError-class.html,
+ trunk/doc/api/spade.Organization_new.LastOwner-class.html,
+ trunk/doc/api/spade.Organization_new.LockedOrganization-class.html,
+ trunk/doc/api/spade.Organization_new.MaximumUsers-class.html,
+ trunk/doc/api/spade.Organization_new.MemberOfFederation-class.html,
+ trunk/doc/api/spade.Organization_new.MembersOnly-class.html,
+ trunk/doc/api/spade.Organization_new.NickNameConflict-class.html,
+ trunk/doc/api/spade.Organization_new.NotCreatePermision-class.html,
+ trunk/doc/api/spade.Organization_new.NotSupervisor-class.html,
+ trunk/doc/api/spade.Organization_new.NotValidGoal-class.html,
+ trunk/doc/api/spade.Organization_new.NotValidName-class.html,
+ trunk/doc/api/spade.Organization_new.NotValidType-class.html,
+ trunk/doc/api/spade.Organization_new.NotValidUnit-class.html,
+ trunk/doc/api/spade.Organization_new.Organization_new-class.html,
+
trunk/doc/api/spade.Organization_new.Organization_new.CreateRoomBehaviour-class.html,
+
trunk/doc/api/spade.Organization_new.Organization_new.CreateTeamBehaviour-class.html,
+
trunk/doc/api/spade.Organization_new.Organization_new.DestroyBehaviour-class.html,
+
trunk/doc/api/spade.Organization_new.Organization_new.GetRegistrationFormBehaviour-class.html,
+
trunk/doc/api/spade.Organization_new.Organization_new.GetUnitInfoBehaviour-class.html,
+
trunk/doc/api/spade.Organization_new.Organization_new.GetUnitListBehaviour-class.html,
+
trunk/doc/api/spade.Organization_new.Organization_new.IsMemberBehaviour-class.html,
+
trunk/doc/api/spade.Organization_new.Organization_new.MyJoinRoomBehaviour-class.html,
+
trunk/doc/api/spade.Organization_new.Organization_new.SendRegistrationFormBehaviour-class.html,
+
trunk/doc/api/spade.Organization_new.Organization_new.TestRoomNameBehaviour-class.html,
+ trunk/doc/api/spade.Organization_new.PaswordNeeded-class.html,
+ trunk/doc/api/spade.Organization_new.Unavailable-class.html,
+ trunk/doc/api/spade.Organization_new.UnavailableFunction-class.html,
+ trunk/doc/api/spade.Platform-module.html,
+ trunk/doc/api/spade.Platform-pysrc.html,
+ trunk/doc/api/spade.Platform.PlatformRestart-class.html,
+ trunk/doc/api/spade.Platform.SpadePlatform-class.html,
+ trunk/doc/api/spade.Platform.SpadePlatform.GetMembersBehav-class.html,
+ trunk/doc/api/spade.Platform.SpadePlatform.RouteBehaviour-class.html,
+ trunk/doc/api/spade.RDF0Parser-module.html,
+ trunk/doc/api/spade.RDF0Parser-pysrc.html,
+ trunk/doc/api/spade.RDF0Parser.Newdict-class.html,
+ trunk/doc/api/spade.RDF0Parser.RDF0Parser-class.html,
+ trunk/doc/api/spade.RPC-module.html,
+ trunk/doc/api/spade.RPC-pysrc.html,
+ trunk/doc/api/spade.RPC.RPCClientBehaviour-class.html,
+ trunk/doc/api/spade.RPC.RPCServerBehaviour-class.html,
+ trunk/doc/api/spade.ReceivedObject-module.html,
+ trunk/doc/api/spade.ReceivedObject-pysrc.html,
+ trunk/doc/api/spade.ReceivedObject.ReceivedObject-class.html,
+ trunk/doc/api/spade.SIMBA-module.html,
+ trunk/doc/api/spade.SIMBA-pysrc.html,
+ trunk/doc/api/spade.SIMBA.SIMBA-class.html,
+ trunk/doc/api/spade.SIMBA.SIMBA.InboxBehaviour-class.html,
+
trunk/doc/api/spade.SIMBA.SIMBA.InboxBehaviour.SimbaRequestHandler-class.html,
+ trunk/doc/api/spade.SIMBA.SIMBA.OutboxBehaviour-class.html,
+ trunk/doc/api/spade.SL0Parser-module.html,
+ trunk/doc/api/spade.SL0Parser-pysrc.html,
+ trunk/doc/api/spade.SL0Parser.SL0Parser-class.html,
+ trunk/doc/api/spade.SPARQLKB-module.html,
+ trunk/doc/api/spade.SPARQLKB-pysrc.html,
+ trunk/doc/api/spade.SPARQLKB.SPARQLKB-class.html,
+ trunk/doc/api/spade.SWIKB-module.html,
+ trunk/doc/api/spade.SWIKB-pysrc.html,
+ trunk/doc/api/spade.SWIKB.SWIKB-class.html,
+ trunk/doc/api/spade.SpadeConfigParser-module.html,
+ trunk/doc/api/spade.SpadeConfigParser-pysrc.html,
+ trunk/doc/api/spade.SpadeConfigParser.ConfigParser-class.html,
+ trunk/doc/api/spade.SpadeConfigParser.ParseObject-class.html,
+ trunk/doc/api/spade.SpadeConfigParser.spadeXML-class.html,
+ trunk/doc/api/spade.SpadeConfigParser.spadeXMLHandler-class.html,
+ trunk/doc/api/spade.Unit-module.html,
+ trunk/doc/api/spade.Unit-pysrc.html,
+ trunk/doc/api/spade.Unit.BanedUser-class.html,
+ trunk/doc/api/spade.Unit.CreationError-class.html,
+ trunk/doc/api/spade.Unit.DestroyError-class.html,
+ trunk/doc/api/spade.Unit.JoinError-class.html,
+ trunk/doc/api/spade.Unit.LastOwner-class.html,
+ trunk/doc/api/spade.Unit.LockedUnit-class.html,
+ trunk/doc/api/spade.Unit.MaximumUsers-class.html,
+ trunk/doc/api/spade.Unit.MembersOnly-class.html,
+ trunk/doc/api/spade.Unit.NickNameConflict-class.html,
+ trunk/doc/api/spade.Unit.NotAdmin-class.html,
+ trunk/doc/api/spade.Unit.NotSupervisor-class.html,
+ trunk/doc/api/spade.Unit.NotValidGoal-class.html,
+ trunk/doc/api/spade.Unit.NotValidGoalChange-class.html,
+ trunk/doc/api/spade.Unit.NotValidName-class.html,
+ trunk/doc/api/spade.Unit.NotValidType-class.html,
+ trunk/doc/api/spade.Unit.NotValidUnit-class.html,
+ trunk/doc/api/spade.Unit.PaswordNeeded-class.html,
+ trunk/doc/api/spade.Unit.Unavailable-class.html,
+ trunk/doc/api/spade.Unit.Unit-class.html,
+ trunk/doc/api/spade.Unit.Unit.AddAdminBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.AddBanAgentBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.AddModeratorBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.AddOwnerBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.CreateRoomBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.DestroyBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.GetAdminListBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.GetBanAgentListBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.GetGoalBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.GetInfoBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.GetMaxAgentsBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.GetMemberListBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.GetMinAgentsBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.GetModeratorListBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.GetNumberOfAgentsBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.GetOwnerListBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.GiveVoiceBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.KickAgentBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.MyJoinRoomBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.PresenceBehaviour-class.html,
+
trunk/doc/api/spade.Unit.Unit.PresenceBehaviour.MinAgentsBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.RemoveAdminBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.RemoveBanAgentBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.RemoveModeratorBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.RemoveOwnerBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.RevokeVoiceBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.SendMessageBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.SendPrivateMessageBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.SetGoalBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.SetMaxAgentsBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.SetMinAgentsBehaviour-class.html,
+ trunk/doc/api/spade.Unit.Unit.TestRoomNameBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new-module.html,
+ trunk/doc/api/spade.Unit_new-pysrc.html,
+ trunk/doc/api/spade.Unit_new.BanedUser-class.html,
+ trunk/doc/api/spade.Unit_new.CreationError-class.html,
+ trunk/doc/api/spade.Unit_new.DestroyError-class.html,
+ trunk/doc/api/spade.Unit_new.JoinError-class.html,
+ trunk/doc/api/spade.Unit_new.LastOwner-class.html,
+ trunk/doc/api/spade.Unit_new.LockedUnit-class.html,
+ trunk/doc/api/spade.Unit_new.MaximumUsers-class.html,
+ trunk/doc/api/spade.Unit_new.MembersOnly-class.html,
+ trunk/doc/api/spade.Unit_new.NickNameConflict-class.html,
+ trunk/doc/api/spade.Unit_new.NotCreatePermision-class.html,
+ trunk/doc/api/spade.Unit_new.NotSupervisor-class.html,
+ trunk/doc/api/spade.Unit_new.NotValidGoal-class.html,
+ trunk/doc/api/spade.Unit_new.NotValidGoalChange-class.html,
+ trunk/doc/api/spade.Unit_new.NotValidName-class.html,
+ trunk/doc/api/spade.Unit_new.NotValidType-class.html,
+ trunk/doc/api/spade.Unit_new.NotValidUnit-class.html,
+ trunk/doc/api/spade.Unit_new.PaswordNeeded-class.html,
+ trunk/doc/api/spade.Unit_new.Unavailable-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.AddAdminBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.AddBanAgentBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.AddModeratorBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.CreateRoomBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.DestroyBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.GetAdminListBehaviour-class.html,
+
trunk/doc/api/spade.Unit_new.Unit_new.GetBanAgentListBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.GetGoalBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.GetInfoBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.GetMaxAgentsBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.GetMemberListBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.GetMinAgentsBehaviour-class.html,
+
trunk/doc/api/spade.Unit_new.Unit_new.GetModeratorListBehaviour-class.html,
+
trunk/doc/api/spade.Unit_new.Unit_new.GetNumberOfAgentsBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.GetOwnerListBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.GiveVoiceBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.KickAgentBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.MyJoinRoomBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.PresenceBehaviour-class.html,
+
trunk/doc/api/spade.Unit_new.Unit_new.PresenceBehaviour.MinAgentsBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.RemoveAdminBehaviour-class.html,
+
trunk/doc/api/spade.Unit_new.Unit_new.RemoveBanAgentBehaviour-class.html,
+
trunk/doc/api/spade.Unit_new.Unit_new.RemoveModeratorBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.RevokeVoiceBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.SendMessageBehaviour-class.html,
+
trunk/doc/api/spade.Unit_new.Unit_new.SendPrivateMessageBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.SetGoalBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.SetMaxAgentsBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.SetMinAgentsBehaviour-class.html,
+ trunk/doc/api/spade.Unit_new.Unit_new.TestRoomNameBehaviour-class.html,
+ trunk/doc/api/spade.XMLCodec-module.html,
+ trunk/doc/api/spade.XMLCodec-pysrc.html,
+ trunk/doc/api/spade.XMLCodec.XMLCodec-class.html,
+ trunk/doc/api/spade.XSBKB-module.html,
+ trunk/doc/api/spade.XSBKB-pysrc.html,
+ trunk/doc/api/spade.XSBKB.XSBKB-class.html,
+ trunk/doc/api/spade.bdi-module.html,
+ trunk/doc/api/spade.bdi-pysrc.html,
+ trunk/doc/api/spade.bdi.BDIBehaviour-class.html,
+ trunk/doc/api/spade.bdi.Goal-class.html,
+ trunk/doc/api/spade.bdi.PlanList-class.html,
+ trunk/doc/api/spade.bdi.PostConditionFailed-class.html,
+ trunk/doc/api/spade.bdi.PreConditionFailed-class.html,
+ trunk/doc/api/spade.bdi.ServiceFailed-class.html,
+ trunk/doc/api/spade.colors-module.html,
+ trunk/doc/api/spade.colors-pysrc.html,
+ trunk/doc/api/spade.content-module.html,
+ trunk/doc/api/spade.content-pysrc.html,
+ trunk/doc/api/spade.content.ContentObject-class.html,
+ trunk/doc/api/spade.dblite-module.html,
+ trunk/doc/api/spade.dblite-pysrc.html,
+ trunk/doc/api/spade.dblite.Base-class.html,
+ trunk/doc/api/spade.dblite.Index-class.html,
+ trunk/doc/api/spade.fipa-module.html,
+ trunk/doc/api/spade.fipa-pysrc.html,
+ trunk/doc/api/spade.fipa.ModifyAgentBehaviour-class.html,
+ trunk/doc/api/spade.fipa.SearchAgentBehaviour-class.html,
+ trunk/doc/api/spade.fipa.deregisterServiceBehaviour-class.html,
+ trunk/doc/api/spade.fipa.getPlatformInfoBehaviour-class.html,
+ trunk/doc/api/spade.fipa.modifyServiceBehaviour-class.html,
+ trunk/doc/api/spade.fipa.registerServiceBehaviour-class.html,
+ trunk/doc/api/spade.fipa.searchServiceBehaviour-class.html,
+ trunk/doc/api/spade.kb-module.html,
+ trunk/doc/api/spade.kb-pysrc.html,
+ trunk/doc/api/spade.kb.KB-class.html,
+ trunk/doc/api/spade.kb.KBConfigurationFailed-class.html,
+ trunk/doc/api/spade.kb.KBNameNotString-class.html,
+ trunk/doc/api/spade.kb.KBValueNotKnown-class.html,
+ trunk/doc/api/spade.kb.SpadeKB-class.html,
+ trunk/doc/api/spade.logic-module.html,
+ trunk/doc/api/spade.logic-pysrc.html,
+ trunk/doc/api/spade.logic.Expr-class.html,
+ trunk/doc/api/spade.logic.FolKB-class.html,
+ trunk/doc/api/spade.logic.KB-class.html,
+ trunk/doc/api/spade.logic.PropHornKB-class.html,
+ trunk/doc/api/spade.logic.PropKB-class.html,
+ trunk/doc/api/spade.logic.logicTest-class.html,
+ trunk/doc/api/spade.msgtypes-module.html,
+ trunk/doc/api/spade.msgtypes-pysrc.html,
+ trunk/doc/api/spade.odict-module.html,
+ trunk/doc/api/spade.odict-pysrc.html,
+ trunk/doc/api/spade.odict.odict-class.html,
+ trunk/doc/api/spade.peer2peer-module.html,
+ trunk/doc/api/spade.peer2peer-pysrc.html,
+ trunk/doc/api/spade.peer2peer.DiscoBehaviour-class.html,
+ trunk/doc/api/spade.peer2peer.P2PBehaviour-class.html,
+ trunk/doc/api/spade.peer2peer.P2PBehaviour.P2PRequestHandler-class.html,
+ trunk/doc/api/spade.peer2peer.RequestDiscoInfoBehav-class.html,
+ trunk/doc/api/spade.peer2peer.SendStreamInitiationBehav-class.html,
+ trunk/doc/api/spade.peer2peer.StreamInitiationBehaviour-class.html,
+ trunk/doc/api/spade.pubsub-module.html,
+ trunk/doc/api/spade.pubsub-pysrc.html,
+ trunk/doc/api/spade.pubsub.PubSub-class.html,
+ trunk/doc/api/spade.pubsub.PubSub._sendAndReceiveBehav-class.html,
+ trunk/doc/api/spade.pygooglechart-module.html,
+ trunk/doc/api/spade.pygooglechart-pysrc.html,
+ trunk/doc/api/spade.pygooglechart.AbstractClassException-class.html,
+ trunk/doc/api/spade.pygooglechart.Axis-class.html,
+ trunk/doc/api/spade.pygooglechart.BadContentTypeException-class.html,
+ trunk/doc/api/spade.pygooglechart.BarChart-class.html,
+ trunk/doc/api/spade.pygooglechart.Chart-class.html,
+ trunk/doc/api/spade.pygooglechart.ChartGrammar-class.html,
+ trunk/doc/api/spade.pygooglechart.Data-class.html,
+ trunk/doc/api/spade.pygooglechart.DataOutOfRangeException-class.html,
+ trunk/doc/api/spade.pygooglechart.ExtendedData-class.html,
+ trunk/doc/api/spade.pygooglechart.GoogleOMeterChart-class.html,
+ trunk/doc/api/spade.pygooglechart.GroupedBarChart-class.html,
+ trunk/doc/api/spade.pygooglechart.GroupedHorizontalBarChart-class.html,
+ trunk/doc/api/spade.pygooglechart.GroupedVerticalBarChart-class.html,
+ trunk/doc/api/spade.pygooglechart.InvalidParametersException-class.html,
+ trunk/doc/api/spade.pygooglechart.LabelAxis-class.html,
+ trunk/doc/api/spade.pygooglechart.LineChart-class.html,
+ trunk/doc/api/spade.pygooglechart.MapChart-class.html,
+ trunk/doc/api/spade.pygooglechart.NoDataGivenException-class.html,
+ trunk/doc/api/spade.pygooglechart.PieChart-class.html,
+ trunk/doc/api/spade.pygooglechart.PieChart2D-class.html,
+ trunk/doc/api/spade.pygooglechart.PieChart3D-class.html,
+ trunk/doc/api/spade.pygooglechart.PyGoogleChartException-class.html,
+ trunk/doc/api/spade.pygooglechart.QRChart-class.html,
+ trunk/doc/api/spade.pygooglechart.RadarChart-class.html,
+ trunk/doc/api/spade.pygooglechart.RangeAxis-class.html,
+ trunk/doc/api/spade.pygooglechart.ScatterChart-class.html,
+ trunk/doc/api/spade.pygooglechart.SimpleData-class.html,
+ trunk/doc/api/spade.pygooglechart.SimpleLineChart-class.html,
+ trunk/doc/api/spade.pygooglechart.SparkLineChart-class.html,
+ trunk/doc/api/spade.pygooglechart.SplineRadarChart-class.html,
+ trunk/doc/api/spade.pygooglechart.StackedHorizontalBarChart-class.html,
+ trunk/doc/api/spade.pygooglechart.StackedVerticalBarChart-class.html,
+ trunk/doc/api/spade.pygooglechart.TextData-class.html,
+ trunk/doc/api/spade.pygooglechart.UnknownChartType-class.html,
+ trunk/doc/api/spade.pygooglechart.UnknownDataTypeException-class.html,
+ trunk/doc/api/spade.pygooglechart.VennChart-class.html,
+ trunk/doc/api/spade.pygooglechart.XYLineChart-class.html,
+ trunk/doc/api/spade.pyparsing-module.html,
+ trunk/doc/api/spade.pyparsing-pysrc.html,
+ trunk/doc/api/spade.pyparsing.And-class.html,
+ trunk/doc/api/spade.pyparsing.CaselessLiteral-class.html,
+ trunk/doc/api/spade.pyparsing.CharsNotIn-class.html,
+ trunk/doc/api/spade.pyparsing.Combine-class.html,
+ trunk/doc/api/spade.pyparsing.Dict-class.html,
+ trunk/doc/api/spade.pyparsing.Each-class.html,
+ trunk/doc/api/spade.pyparsing.Empty-class.html,
+ trunk/doc/api/spade.pyparsing.FollowedBy-class.html,
+ trunk/doc/api/spade.pyparsing.Forward-class.html,
+ trunk/doc/api/spade.pyparsing.GoToColumn-class.html,
+ trunk/doc/api/spade.pyparsing.Group-class.html,
+ trunk/doc/api/spade.pyparsing.Keyword-class.html,
+ trunk/doc/api/spade.pyparsing.LineEnd-class.html,
+ trunk/doc/api/spade.pyparsing.LineStart-class.html,
+ trunk/doc/api/spade.pyparsing.Literal-class.html,
+ trunk/doc/api/spade.pyparsing.MatchFirst-class.html,
+ trunk/doc/api/spade.pyparsing.NoMatch-class.html,
+ trunk/doc/api/spade.pyparsing.NotAny-class.html,
+ trunk/doc/api/spade.pyparsing.OneOrMore-class.html,
+ trunk/doc/api/spade.pyparsing.Optional-class.html,
+ trunk/doc/api/spade.pyparsing.Or-class.html,
+ trunk/doc/api/spade.pyparsing.ParseBaseException-class.html,
+ trunk/doc/api/spade.pyparsing.ParseElementEnhance-class.html,
+ trunk/doc/api/spade.pyparsing.ParseException-class.html,
+ trunk/doc/api/spade.pyparsing.ParseExpression-class.html,
+ trunk/doc/api/spade.pyparsing.ParseFatalException-class.html,
+ trunk/doc/api/spade.pyparsing.ParseResults-class.html,
+ trunk/doc/api/spade.pyparsing.ParserElement-class.html,
+ trunk/doc/api/spade.pyparsing.PositionToken-class.html,
+ trunk/doc/api/spade.pyparsing.RecursiveGrammarException-class.html,
+ trunk/doc/api/spade.pyparsing.SkipTo-class.html,
+ trunk/doc/api/spade.pyparsing.StringEnd-class.html,
+ trunk/doc/api/spade.pyparsing.StringStart-class.html,
+ trunk/doc/api/spade.pyparsing.Suppress-class.html,
+ trunk/doc/api/spade.pyparsing.Token-class.html,
+ trunk/doc/api/spade.pyparsing.TokenConverter-class.html,
+ trunk/doc/api/spade.pyparsing.Upcase-class.html,
+ trunk/doc/api/spade.pyparsing.White-class.html,
+ trunk/doc/api/spade.pyparsing.Word-class.html,
+ trunk/doc/api/spade.pyparsing.ZeroOrMore-class.html,
+ trunk/doc/api/spade.pyparsing._ForwardNoRecurse-class.html,
+ trunk/doc/api/spade.pyratemp-module.html,
+ trunk/doc/api/spade.pyratemp-pysrc.html,
+ trunk/doc/api/spade.pyratemp.FileLoader-class.html,
+ trunk/doc/api/spade.pyratemp.Parser-class.html,
+ trunk/doc/api/spade.pyratemp.PseudoSandbox-class.html,
+ trunk/doc/api/spade.pyratemp.Renderer-class.html,
+ trunk/doc/api/spade.pyratemp.StringLoader-class.html,
+ trunk/doc/api/spade.pyratemp.Template-class.html,
+ trunk/doc/api/spade.pyratemp.TemplateBase-class.html,
+ trunk/doc/api/spade.pyratemp.TemplateEval-class.html,
+ trunk/doc/api/spade.pyratemp.TemplateException-class.html,
+ trunk/doc/api/spade.pyratemp.TemplateIncludeError-class.html,
+ trunk/doc/api/spade.pyratemp.TemplateParseError-class.html,
+ trunk/doc/api/spade.pyratemp.TemplateRenderError-class.html,
+ trunk/doc/api/spade.pyratemp.TemplateSyntaxError-class.html,
+ trunk/doc/api/spade.pyratemp._dontescape-class.html,
+ trunk/doc/api/spade.pyxf-module.html,
+ trunk/doc/api/spade.pyxf-pysrc.html,
+ trunk/doc/api/spade.pyxf.ECLiPSeCompileError-class.html,
+ trunk/doc/api/spade.pyxf.ECLiPSeExecutableNotFound-class.html,
+ trunk/doc/api/spade.pyxf.ECLiPSeQueryError-class.html,
+ trunk/doc/api/spade.pyxf.Flora2CompileError-class.html,
+ trunk/doc/api/spade.pyxf.Flora2ExecutableNotFound-class.html,
+ trunk/doc/api/spade.pyxf.Flora2QueryError-class.html,
+ trunk/doc/api/spade.pyxf.SWICompileError-class.html,
+ trunk/doc/api/spade.pyxf.SWIExecutableNotFound-class.html,
+ trunk/doc/api/spade.pyxf.SWIQueryError-class.html,
+ trunk/doc/api/spade.pyxf.XSBCompileError-class.html,
+ trunk/doc/api/spade.pyxf.XSBExecutableNotFound-class.html,
+ trunk/doc/api/spade.pyxf.XSBQueryError-class.html,
+ trunk/doc/api/spade.pyxf.eclipse-class.html,
+ trunk/doc/api/spade.pyxf.flora2-class.html,
+ trunk/doc/api/spade.pyxf.swipl-class.html,
+ trunk/doc/api/spade.pyxf.xsb-class.html,
+ trunk/doc/api/spade.socialnetwork-module.html,
+ trunk/doc/api/spade.socialnetwork-pysrc.html,
+ trunk/doc/api/spade.socialnetwork.PresenceBehaviour-class.html,
+ trunk/doc/api/spade.socialnetwork.RosterBehaviour-class.html,
+ trunk/doc/api/spade.socialnetwork.SocialItem-class.html,
+ trunk/doc/api/spade.spade_backend-module.html,
+ trunk/doc/api/spade.spade_backend-pysrc.html,
+ trunk/doc/api/spade.spade_backend.SpadeBackend-class.html,
+ trunk/doc/api/spade.tbcbp-module.html,
+ trunk/doc/api/spade.tbcbp-pysrc.html,
+ trunk/doc/api/spade.tbcbp.Case-class.html,
+ trunk/doc/api/spade.tbcbp.CaseDB-class.html,
+ trunk/doc/api/spade.tbcbp.Plan-class.html,
+ trunk/doc/api/spade.tbcbp.TBCBP-class.html,
+ trunk/doc/api/spade.tbcbp.TimeOut-class.html,
+ trunk/doc/api/spade.tbcbp.TooMuchPlans-class.html,
+ trunk/doc/api/spade.templates-module.html,
+ trunk/doc/api/spade.templates-pysrc.html,
+ trunk/doc/api/spade.wui-module.html,
+ trunk/doc/api/spade.wui-pysrc.html,
+ trunk/doc/api/spade.wui.HTTP_REDIRECTION-class.html,
+ trunk/doc/api/spade.wui.SessionElement-class.html,
+ trunk/doc/api/spade.wui.WUI-class.html,
+ trunk/doc/api/spade.wui.WUIHandler-class.html,
+ trunk/doc/api/spade.xmpp-module.html,
+ trunk/doc/api/spade.xmpp-pysrc.html,
+ trunk/doc/api/spade.xmpp.auth-module.html,
+ trunk/doc/api/spade.xmpp.auth-pysrc.html,
+ trunk/doc/api/spade.xmpp.auth.Bind-class.html,
+ trunk/doc/api/spade.xmpp.auth.ComponentBind-class.html,
+ trunk/doc/api/spade.xmpp.auth.NonSASL-class.html,
+ trunk/doc/api/spade.xmpp.auth.SASL-class.html,
+ trunk/doc/api/spade.xmpp.browser-module.html,
+ trunk/doc/api/spade.xmpp.browser-pysrc.html,
+ trunk/doc/api/spade.xmpp.browser.Browser-class.html,
+ trunk/doc/api/spade.xmpp.client-module.html,
+ trunk/doc/api/spade.xmpp.client-pysrc.html,
+ trunk/doc/api/spade.xmpp.client.Client-class.html,
+ trunk/doc/api/spade.xmpp.client.CommonClient-class.html,
+ trunk/doc/api/spade.xmpp.client.Component-class.html,
+ trunk/doc/api/spade.xmpp.client.PlugIn-class.html,
+ trunk/doc/api/spade.xmpp.commands-module.html,
+ trunk/doc/api/spade.xmpp.commands-pysrc.html,
+ trunk/doc/api/spade.xmpp.commands.Command_Handler_Prototype-class.html,
+ trunk/doc/api/spade.xmpp.commands.Commands-class.html,
+ trunk/doc/api/spade.xmpp.commands.TestCommand-class.html,
+ trunk/doc/api/spade.xmpp.debug-module.html,
+ trunk/doc/api/spade.xmpp.debug-pysrc.html,
+ trunk/doc/api/spade.xmpp.debug.Debug-class.html,
+ trunk/doc/api/spade.xmpp.debug.NoDebug-class.html,
+ trunk/doc/api/spade.xmpp.dispatcher-module.html,
+ trunk/doc/api/spade.xmpp.dispatcher-pysrc.html,
+ trunk/doc/api/spade.xmpp.dispatcher.Dispatcher-class.html,
+ trunk/doc/api/spade.xmpp.features-module.html,
+ trunk/doc/api/spade.xmpp.features-pysrc.html,
+ trunk/doc/api/spade.xmpp.filetransfer-module.html,
+ trunk/doc/api/spade.xmpp.filetransfer-pysrc.html,
+ trunk/doc/api/spade.xmpp.filetransfer.IBB-class.html,
+ trunk/doc/api/spade.xmpp.protocol-module.html,
+ trunk/doc/api/spade.xmpp.protocol-pysrc.html,
+ trunk/doc/api/spade.xmpp.protocol.BadFormat-class.html,
+ trunk/doc/api/spade.xmpp.protocol.BadNamespacePrefix-class.html,
+ trunk/doc/api/spade.xmpp.protocol.Conflict-class.html,
+ trunk/doc/api/spade.xmpp.protocol.ConnectionTimeout-class.html,
+ trunk/doc/api/spade.xmpp.protocol.DataField-class.html,
+ trunk/doc/api/spade.xmpp.protocol.DataForm-class.html,
+ trunk/doc/api/spade.xmpp.protocol.Error-class.html,
+ trunk/doc/api/spade.xmpp.protocol.ErrorNode-class.html,
+ trunk/doc/api/spade.xmpp.protocol.HostGone-class.html,
+ trunk/doc/api/spade.xmpp.protocol.HostUnknown-class.html,
+ trunk/doc/api/spade.xmpp.protocol.ImproperAddressing-class.html,
+ trunk/doc/api/spade.xmpp.protocol.InternalServerError-class.html,
+ trunk/doc/api/spade.xmpp.protocol.InvalidFrom-class.html,
+ trunk/doc/api/spade.xmpp.protocol.InvalidID-class.html,
+ trunk/doc/api/spade.xmpp.protocol.InvalidNamespace-class.html,
+ trunk/doc/api/spade.xmpp.protocol.InvalidXML-class.html,
+ trunk/doc/api/spade.xmpp.protocol.Iq-class.html,
+ trunk/doc/api/spade.xmpp.protocol.JID-class.html,
+ trunk/doc/api/spade.xmpp.protocol.Message-class.html,
+ trunk/doc/api/spade.xmpp.protocol.NodeProcessed-class.html,
+ trunk/doc/api/spade.xmpp.protocol.NotAuthorized-class.html,
+ trunk/doc/api/spade.xmpp.protocol.PolicyViolation-class.html,
+ trunk/doc/api/spade.xmpp.protocol.Presence-class.html,
+ trunk/doc/api/spade.xmpp.protocol.Protocol-class.html,
+ trunk/doc/api/spade.xmpp.protocol.RemoteConnectionFailed-class.html,
+ trunk/doc/api/spade.xmpp.protocol.ResourceConstraint-class.html,
+ trunk/doc/api/spade.xmpp.protocol.RestrictedXML-class.html,
+ trunk/doc/api/spade.xmpp.protocol.SeeOtherHost-class.html,
+ trunk/doc/api/spade.xmpp.protocol.StreamError-class.html,
+ trunk/doc/api/spade.xmpp.protocol.SystemShutdown-class.html,
+ trunk/doc/api/spade.xmpp.protocol.UndefinedCondition-class.html,
+ trunk/doc/api/spade.xmpp.protocol.UnsupportedEncoding-class.html,
+ trunk/doc/api/spade.xmpp.protocol.UnsupportedStanzaType-class.html,
+ trunk/doc/api/spade.xmpp.protocol.UnsupportedVersion-class.html,
+ trunk/doc/api/spade.xmpp.protocol.XMLNotWellFormed-class.html,
+ trunk/doc/api/spade.xmpp.roster-module.html,
+ trunk/doc/api/spade.xmpp.roster-pysrc.html,
+ trunk/doc/api/spade.xmpp.roster.Roster-class.html,
+ trunk/doc/api/spade.xmpp.session-module.html,
+ trunk/doc/api/spade.xmpp.session-pysrc.html,
+ trunk/doc/api/spade.xmpp.session.Session-class.html,
+ trunk/doc/api/spade.xmpp.simplexml-module.html,
+ trunk/doc/api/spade.xmpp.simplexml-pysrc.html,
+ trunk/doc/api/spade.xmpp.simplexml.NT-class.html,
+ trunk/doc/api/spade.xmpp.simplexml.Node-class.html,
+ trunk/doc/api/spade.xmpp.simplexml.NodeBuilder-class.html,
+ trunk/doc/api/spade.xmpp.simplexml.T-class.html,
+ trunk/doc/api/spade.xmpp.transports-module.html,
+ trunk/doc/api/spade.xmpp.transports-pysrc.html,
+ trunk/doc/api/spade.xmpp.transports.HTTPPROXYsocket-class.html,
+ trunk/doc/api/spade.xmpp.transports.TCPsocket-class.html,
+ trunk/doc/api/spade.xmpp.transports.TLS-class.html,
+ trunk/doc/api/spade.xmpp.transports.error-class.html,
+ trunk/doc/api/spade.xmppd-module.html,
+ trunk/doc/api/spade.xmppd-pysrc.html,
+ trunk/doc/api/spade.xmppd.locales-module.html,
+ trunk/doc/api/spade.xmppd.locales-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules-module.html,
+ trunk/doc/api/spade.xmppd.modules-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.config-module.html,
+ trunk/doc/api/spade.xmppd.modules.config-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.config.Config-class.html,
+ trunk/doc/api/spade.xmppd.modules.config.xmppdXML-class.html,
+ trunk/doc/api/spade.xmppd.modules.config.xmppdXMLHandler-class.html,
+ trunk/doc/api/spade.xmppd.modules.db_fake-module.html,
+ trunk/doc/api/spade.xmppd.modules.db_fake-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.db_fake.AUTH-class.html,
+ trunk/doc/api/spade.xmppd.modules.db_fake.DB-class.html,
+ trunk/doc/api/spade.xmppd.modules.dialback-module.html,
+ trunk/doc/api/spade.xmppd.modules.dialback-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.dialback.Dialback-class.html,
+ trunk/doc/api/spade.xmppd.modules.jep0077-module.html,
+ trunk/doc/api/spade.xmppd.modules.jep0077-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.jep0077.IBR-class.html,
+ trunk/doc/api/spade.xmppd.modules.jep0078-module.html,
+ trunk/doc/api/spade.xmppd.modules.jep0078-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.jep0078.NSA-class.html,
+ trunk/doc/api/spade.xmppd.modules.message-module.html,
+ trunk/doc/api/spade.xmppd.modules.message-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.message.MessageCatcher-class.html,
+ trunk/doc/api/spade.xmppd.modules.muc-module.html,
+ trunk/doc/api/spade.xmppd.modules.muc-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.muc.BadPassword-class.html,
+ trunk/doc/api/spade.xmppd.modules.muc.Blacklisted-class.html,
+ trunk/doc/api/spade.xmppd.modules.muc.MUC-class.html,
+ trunk/doc/api/spade.xmppd.modules.muc.MaxUsers-class.html,
+ trunk/doc/api/spade.xmppd.modules.muc.NickLockedDown-class.html,
+ trunk/doc/api/spade.xmppd.modules.muc.NoVoice-class.html,
+ trunk/doc/api/spade.xmppd.modules.muc.NotAMember-class.html,
+ trunk/doc/api/spade.xmppd.modules.muc.Participant-class.html,
+ trunk/doc/api/spade.xmppd.modules.muc.Room-class.html,
+ trunk/doc/api/spade.xmppd.modules.muc.SerializableRoom-class.html,
+ trunk/doc/api/spade.xmppd.modules.oob-module.html,
+ trunk/doc/api/spade.xmppd.modules.oob-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.oob.OOB-class.html,
+ trunk/doc/api/spade.xmppd.modules.pubsub-module.html,
+ trunk/doc/api/spade.xmppd.modules.pubsub-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.pubsub.PSNode-class.html,
+ trunk/doc/api/spade.xmppd.modules.pubsub.PubSubServer-class.html,
+ trunk/doc/api/spade.xmppd.modules.roster-module.html,
+ trunk/doc/api/spade.xmppd.modules.roster-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.roster.ROSTER-class.html,
+ trunk/doc/api/spade.xmppd.modules.router-module.html,
+ trunk/doc/api/spade.xmppd.modules.router-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.router.Router-class.html,
+ trunk/doc/api/spade.xmppd.modules.stream-module.html,
+ trunk/doc/api/spade.xmppd.modules.stream-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.stream.Bind-class.html,
+ trunk/doc/api/spade.xmppd.modules.stream.Handshake-class.html,
+ trunk/doc/api/spade.xmppd.modules.stream.SASL-class.html,
+ trunk/doc/api/spade.xmppd.modules.stream.Session-class.html,
+ trunk/doc/api/spade.xmppd.modules.stream.TLS-class.html,
+ trunk/doc/api/spade.xmppd.modules.webadmin-module.html,
+ trunk/doc/api/spade.xmppd.modules.webadmin-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.webadmin.WebAdmin-class.html,
+ trunk/doc/api/spade.xmppd.modules.webadmin.WebAdminHandler-class.html,
+ trunk/doc/api/spade.xmppd.modules.wq-module.html,
+ trunk/doc/api/spade.xmppd.modules.wq-pysrc.html,
+ trunk/doc/api/spade.xmppd.modules.wq.Conflict-class.html,
+ trunk/doc/api/spade.xmppd.modules.wq.Group-class.html,
+ trunk/doc/api/spade.xmppd.modules.wq.ItemNotFound-class.html,
+ trunk/doc/api/spade.xmppd.modules.wq.WQ-class.html,
+ trunk/doc/api/spade.xmppd.xmppd-module.html,
+ trunk/doc/api/spade.xmppd.xmppd-pysrc.html,
+ trunk/doc/api/spade.xmppd.xmppd.RPC_Client-class.html,
+ trunk/doc/api/spade.xmppd.xmppd.Server-class.html,
+ trunk/doc/api/spade.xmppd.xmppd.Session-class.html,
+ trunk/doc/api/spade.xmppd.xmppd.Session_Dummy-class.html,
+ trunk/doc/api/spade.xmppd.xmppd.Session_Dummy.Stream-class.html,
+ trunk/doc/api/spade.xmppd.xmppd.Socker_client-class.html,
+ trunk/doc/api/spade.xmppd.xmppd.fake_select-class.html,
+ trunk/doc/api/spade.xmppd.xmppd.fake_select.poll-class.html,
+ trunk/doc/api/spade.xmppd.xmppd.get_input-class.html,
+ trunk/doc/api/spade.xmppd.xmppd.localizer-class.html,
+ trunk/doc/api/spade.xmppd.xmppd.multisession_manager-class.html,
+
trunk/doc/api/spade.xmppd.xmppd.multisession_manager.multisession_thread-class.html,
+ trunk/doc/api/toc-everything.html,
+ trunk/doc/api/toc-spade-module.html,
+ trunk/doc/api/toc-spade.ACLMessage-module.html,
+ trunk/doc/api/toc-spade.ACLParser-module.html,
+ trunk/doc/api/toc-spade.AID-module.html,
+ trunk/doc/api/toc-spade.AMS-module.html,
+ trunk/doc/api/toc-spade.Agent-module.html,
+ trunk/doc/api/toc-spade.BasicFipaDateTime-module.html,
+ trunk/doc/api/toc-spade.Behaviour-module.html,
+ trunk/doc/api/toc-spade.DF-module.html,
+ trunk/doc/api/toc-spade.ECLiPSeKB-module.html,
+ trunk/doc/api/toc-spade.Envelope-module.html,
+ trunk/doc/api/toc-spade.FIPAMessage-module.html,
+ trunk/doc/api/toc-spade.FlexQueue-module.html,
+ trunk/doc/api/toc-spade.Flora2KB-module.html,
+ trunk/doc/api/toc-spade.MTP-module.html,
+ trunk/doc/api/toc-spade.MessageReceiver-module.html,
+ trunk/doc/api/toc-spade.Organization-module.html,
+ trunk/doc/api/toc-spade.Organization_new-module.html,
+ trunk/doc/api/toc-spade.Platform-module.html,
+ trunk/doc/api/toc-spade.RDF0Parser-module.html,
+ trunk/doc/api/toc-spade.RPC-module.html,
+ trunk/doc/api/toc-spade.ReceivedObject-module.html,
+ trunk/doc/api/toc-spade.SIMBA-module.html,
+ trunk/doc/api/toc-spade.SL0Parser-module.html,
+ trunk/doc/api/toc-spade.SPARQLKB-module.html,
+ trunk/doc/api/toc-spade.SWIKB-module.html,
+ trunk/doc/api/toc-spade.SpadeConfigParser-module.html,
+ trunk/doc/api/toc-spade.Unit-module.html,
+ trunk/doc/api/toc-spade.Unit_new-module.html,
+ trunk/doc/api/toc-spade.XMLCodec-module.html,
+ trunk/doc/api/toc-spade.XSBKB-module.html,
+ trunk/doc/api/toc-spade.bdi-module.html,
+ trunk/doc/api/toc-spade.colors-module.html,
+ trunk/doc/api/toc-spade.content-module.html,
+ trunk/doc/api/toc-spade.dblite-module.html,
+ trunk/doc/api/toc-spade.fipa-module.html,
+ trunk/doc/api/toc-spade.kb-module.html,
+ trunk/doc/api/toc-spade.logic-module.html,
+ trunk/doc/api/toc-spade.msgtypes-module.html,
+ trunk/doc/api/toc-spade.odict-module.html,
+ trunk/doc/api/toc-spade.peer2peer-module.html,
+ trunk/doc/api/toc-spade.pubsub-module.html,
+ trunk/doc/api/toc-spade.pygooglechart-module.html,
+ trunk/doc/api/toc-spade.pyparsing-module.html,
+ trunk/doc/api/toc-spade.pyratemp-module.html,
+ trunk/doc/api/toc-spade.pyxf-module.html,
+ trunk/doc/api/toc-spade.socialnetwork-module.html,
+ trunk/doc/api/toc-spade.spade_backend-module.html,
+ trunk/doc/api/toc-spade.tbcbp-module.html,
+ trunk/doc/api/toc-spade.templates-module.html,
+ trunk/doc/api/toc-spade.wui-module.html,
+ trunk/doc/api/toc-spade.xmpp-module.html,
+ trunk/doc/api/toc-spade.xmpp.auth-module.html,
+ trunk/doc/api/toc-spade.xmpp.browser-module.html,
+ trunk/doc/api/toc-spade.xmpp.client-module.html,
+ trunk/doc/api/toc-spade.xmpp.commands-module.html,
+ trunk/doc/api/toc-spade.xmpp.debug-module.html,
+ trunk/doc/api/toc-spade.xmpp.dispatcher-module.html,
+ trunk/doc/api/toc-spade.xmpp.features-module.html,
+ trunk/doc/api/toc-spade.xmpp.filetransfer-module.html,
+ trunk/doc/api/toc-spade.xmpp.protocol-module.html,
+ trunk/doc/api/toc-spade.xmpp.roster-module.html,
+ trunk/doc/api/toc-spade.xmpp.session-module.html,
+ trunk/doc/api/toc-spade.xmpp.simplexml-module.html,
+ trunk/doc/api/toc-spade.xmpp.transports-module.html,
+ trunk/doc/api/toc-spade.xmppd-module.html,
+ trunk/doc/api/toc-spade.xmppd.locales-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules.config-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules.db_fake-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules.dialback-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules.jep0077-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules.jep0078-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules.message-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules.muc-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules.oob-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules.pubsub-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules.roster-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules.router-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules.stream-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules.webadmin-module.html,
+ trunk/doc/api/toc-spade.xmppd.modules.wq-module.html,
+ trunk/doc/api/toc-spade.xmppd.xmppd-module.html,
+ trunk/doc/api/toc.html,
+ trunk/doc/api/uml_class_diagram_for_mimetool.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_ac.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_ag.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_ag_2.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_ag_3.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_ag_4.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_ag_5.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_am.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_am_2.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_am_3.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_am_4.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_am_5.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_am_6.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_am_7.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_bd.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_bd_2.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_bd_3.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_bd_4.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_bd_5.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be_10.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be_11.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be_12.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be_13.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be_14.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be_15.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be_2.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be_3.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be_4.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be_5.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be_6.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be_7.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be_8.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_be_9.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_co.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_df.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_df_2.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_df_3.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_df_4.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_df_5.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_ec.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_fi.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_fi_2.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_fi_3.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_fi_4.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_fi_5.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_fi_6.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_fi_7.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_fl.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_fl_2.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_kb.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_kb_2.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_kb_3.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_kb_4.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_lo.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_lo_2.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_lo_3.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_lo_4.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_me.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_me_2.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_od.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_10.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_11.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_12.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_13.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_14.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_15.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_16.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_17.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_18.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_19.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_2.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_20.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_21.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_22.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_23.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_24.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_25.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_26.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_27.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_28.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_29.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_3.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_30.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_31.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_32.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_33.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_34.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_35.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_36.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_37.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_38.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_39.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_4.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_40.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_41.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_42.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_43.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_44.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_45.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_46.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_47.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_48.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_49.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_5.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_50.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_51.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_52.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_53.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_54.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_55.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_56.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_57.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_58.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_59.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_6.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_60.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_7.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_8.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_or_9.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_pe.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_pe_2.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_pe_3.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_pe_4.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_pe_5.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_pe_6.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_pl.gif,
+ trunk/doc/api/uml_class_diagram_for_spade_pl_2.gif,
***The diff for this file has been truncated for email.***
=======================================
--- /trunk/configure.py Fri Nov 9 09:51:22 2012
+++ /trunk/configure.py Fri Nov 23 05:19:16 2012
@@ -9,17 +9,18 @@
globalhostname = ""
+
def generateCode():
# Fill the template with the correct data
-
+
global jabber_template
global globalhostname
- path=""
+ path = ""
if
os.name == "posix":
# If no hostname was previously specified, get one from the
system
- if globalhostname == "":
+ if globalhostname == "":
hostname = socket.gethostname()
else:
hostname = globalhostname
@@ -27,50 +28,49 @@
#path = os.sep+"usr"+os.sep+"share"+os.sep+"spade"
else:
# If no hostname was previously specified, get one from the system
- if globalhostname == "":
+ if globalhostname == "":
hostname = socket.gethostbyaddr(socket.gethostname())[0]
else:
hostname = globalhostname
#path = "usr"+os.sep+"share"+os.sep+"spade"
-
- if hostname == "localhost":
+
+ if hostname == "localhost":
hostname = "127.0.0.1"
print "Translating localhost DNS to IP (127.0.0.1)."
- acc_passwd
= "".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(8)])
- ams_passwd
= "".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(8)])
- df_passwd
= "".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(8)])
-
+ acc_passwd = "".join([string.ascii_letters[int(
+ random.randint(0, len(string.ascii_letters) - 1))] for a in
range(8)])
+ ams_passwd = "".join([string.ascii_letters[int(
+ random.randint(0, len(string.ascii_letters) - 1))] for a in
range(8)])
+ df_passwd = "".join([string.ascii_letters[int(
+ random.randint(0, len(string.ascii_letters) - 1))] for a in
range(8)])
spadexml = """
- <spade>
+<spade>
+ <platform>
+ <hostname>""" + hostname + """</hostname>
+ <port>5222</port>
+ <adminpasswd>secret</adminpasswd>
+ </platform>
- <platform>
- <hostname>""" + hostname + """</hostname>
- <port>5222</port>
- <path>"""+path+"""</path>
- </platform>
+ <acc>
+ <hostname>acc.""" + hostname + """</hostname>
+ <password>""" + acc_passwd + """</password>
+ <port>5222</port>
+#MTPS#
+ </acc>
+ <ams>
+ <hostname>ams.""" + hostname + """</hostname>
+ <password>""" + ams_passwd + """</password>
+ <port>5222</port>
+ </ams>
- <acc>
- <hostname>acc."""+hostname+"""</hostname>
- <password>"""+acc_passwd+"""</password>
- <port>5222</port>
- #MTPS#
- </acc>
-
- <ams>
- <hostname>ams."""+hostname+"""</hostname>
- <password>"""+ams_passwd+"""</password>
- <port>5222</port>
- </ams>
-
- <df>
- <hostname>df."""+hostname+"""</hostname>
- <password>"""+df_passwd+"""</password>
- <port>5222</port>
- </df>
-
- </spade>
+ <df>
+ <hostname>df.""" + hostname + """</hostname>
+ <password>""" + df_passwd + """</password>
+ <port>5222</port>
+ </df>
+</spade>
"""
# Now fill the MTPs information
@@ -85,14 +85,14 @@
# mtp_str = mtp_str + """\t\t\t</mtp>\n\n"""
# except Exception, e:
# print "EXCEPTION GETTING MTPS: ", str(e)
-
+
# Fill the data
- mtp_str = '''t\t\t<mtp
name="http">\n\t\t\t\t<instance>http</instance>\n'''
- mtp_str = mtp_str + """\t\t\t\t<protocol>http</protocol>\n"""
- mtp_str = mtp_str + """\t\t\t</mtp>\n\n"""
+ mtp_str = '''
+ <mtp name="http">
+ <instance>http</instance>
+ <protocol>http</protocol>
+ </mtp>'''
spadexml = spadexml.replace("#MTPS#", mtp_str)
- # GUS: By default, no MTPs, thank you
- #spadexml = spadexml.replace("#MTPS#", "")
file = open("spade.xml", "w+")
file.write(spadexml)
@@ -101,41 +101,39 @@
# Generating real xmppd.xml
if
os.name == 'posix':
xmppdxml = '''
- <server>
- <servernames>
- <name>'''+hostname+'''</name>
- </servernames>
- <certificate file="xmppd.pem"/>
- <spool
path="'''+str(os.environ['HOME'])+'''/.spade/spool"/>
- <plugins>
- <MUC jid="muc.'''+hostname+'''" name="SPADE MUC
Component"/>
- <WQ jid="wq.'''+hostname+'''" name="SPADE Workgroup
Queues"/>
- </plugins>
- <components>
- <AMS jid="ams.'''+hostname+'''" name="AMS"
username="ams" password="'''+ams_passwd+'''"/>
- <DF jid="df.'''+hostname+'''" name="DF"
username="df" password="'''+df_passwd+'''"/>
- <ACC jid="acc.'''+hostname+'''" name="ACC"
username="acc" password="'''+acc_passwd+'''"/>
- </components>
- </server>
+<server>
+ <servernames>
+ <name>''' + hostname + '''</name>
+ </servernames>
+ <certificate file="xmppd.pem"/>
+ <plugins>
+ <MUC jid="muc.''' + hostname + '''" name="SPADE MUC Component"/>
+ <WQ jid="wq.''' + hostname + '''" name="SPADE Workgroup Queues"/>
+ </plugins>
+ <components>
+ <AMS jid="ams.''' + hostname + '''" name="AMS" username="ams"
password="''' + ams_passwd + '''"/>
+ <DF jid="df.''' + hostname + '''" name="DF" username="df"
password="''' + df_passwd + '''"/>
+ <ACC jid="acc.''' + hostname + '''" name="ACC" username="acc"
password="''' + acc_passwd + '''"/>
+ </components>
+</server>
'''
else:
xmppdxml = '''
- <server>
- <servernames>
- <name>'''+hostname+'''</name>
- </servernames>
- <certificate file="xmppd.pem"/>
- <spool path="usr/share/spade/xmppd/spool"/>
- <plugins>
- <MUC jid="muc.'''+hostname+'''" name="SPADE MUC
Component"/>
- <WQ jid="wq.'''+hostname+'''" name="SPADE Workgroup
Queues"/>
- </plugins>
- <components>
- <AMS jid="ams.'''+hostname+'''" name="AMS"
username="ams" password="'''+ams_passwd+'''"/>
- <DF jid="df.'''+hostname+'''" name="DF"
username="df" password="'''+df_passwd+'''"/>
- <ACC jid="acc.'''+hostname+'''" name="ACC"
username="acc" password="'''+acc_passwd+'''"/>
- </components>
- </server>
+<server>
+ <servernames>
+ <name>''' + hostname + '''</name>
+ </servernames>
+ <certificate file="xmppd.pem"/>
+ <plugins>
+ <MUC jid="muc.''' + hostname + '''" name="SPADE MUC Component"/>
+ <WQ jid="wq.''' + hostname + '''" name="SPADE Workgroup Queues"/>
+ </plugins>
+ <components>
+ <AMS jid="ams.''' + hostname + '''" name="AMS" username="ams"
password="''' + ams_passwd + '''"/>
+ <DF jid="df.''' + hostname + '''" name="DF" username="df"
password="''' + df_passwd + '''"/>
+ <ACC jid="acc.''' + hostname + '''" name="ACC" username="acc"
password="''' + acc_passwd + '''"/>
+ </components>
+</server>
'''
file = open("xmppd.xml", "w+")
@@ -143,7 +141,6 @@
file.close()
-
if __name__ == '__main__':
# We look for a command line parameter
if len(sys.argv) > 1:
@@ -152,6 +149,5 @@
else:
# There is no parameter (i.e. macho-mode)
pass
-
+
generateCode()
-
=======================================
--- /trunk/runspade.py Fri Nov 9 09:51:22 2012
+++ /trunk/runspade.py Fri Nov 23 05:19:16 2012
@@ -1,7 +1,8 @@
#!/usr/bin/env python
-import os #, signal
+import os
+import signal
import sys
import traceback
import time
@@ -10,175 +11,180 @@
from getopt import getopt
try:
- from spade import spade_backend
- from spade import colors
+ from spade import spade_backend
+ from spade import colors
except ImportError, e:
- print "Could not import spade package!!! " + str(e)
+ print "Could not import spade package!!! " + str(e)
from xmppd.xmppd import Server
-__author__ = "Gustavo Aranda <
gus...@gmail.com> and Javier Palanca
<
jpal...@gmail.com>"
-__version__ = "2.1"
+__author__ = "Gustavo Aranda <
gus...@gmail.com> and Javier Palanca
<
jpal...@gmail.com>"
+__version__ = "2.1.1"
__copyright__ = "Copyright (C) 2006-2012"
-__license__ = "LGPL"
+__license__ = "LGPL"
def print_help():
- configfilename = "/etc/spade/spade.xml"
- jabberxml = "/etc/spade/xmppd.xml"
- if sys.platform[:6] == 'netbsd':
- configfilename = os.sep + "usr" + os.sep + "pkg" + configfilename
- jabberxml = os.sep+ "usr" + os.sep + "pkg" + jabberxml
- print
- print "Usage: %s [options]" % sys.argv[0]
- print " -h, --help display this help text and exit"
- print " -v, --version display the version and exit"
- print " -d, --debug enable the debug execution"
- print " -c, --configfile load the configuration file (use configure.py
to create one)"
- print " -j, --jabber load the jabber configuration file (use
configure.py to create one)"
- #print " -w, --web load the web interface"
- raise SystemExit
+ configfilename = "/etc/spade/spade.xml"
+ jabberxml = "/etc/spade/xmppd.xml"
+ if sys.platform[:6] == 'netbsd':
+ configfilename = os.sep + "usr" + os.sep + "pkg" + configfilename
+ jabberxml = os.sep + "usr" + os.sep + "pkg" + jabberxml
+ print
+ print "Usage: %s [options]" % sys.argv[0]
+ print " -h, --help display this help text and exit"
+ print " -v, --version display the version and exit"
+ print " -d, --debug enable the debug execution"
+ print " -c, --configfile load the configuration file (use
configure.py to create one)"
+ print " -j, --jabber load the jabber configuration file (use
configure.py to create one)"
+ #print " -w, --web load the web interface"
+ raise SystemExit
+
def print_version():
- print "SPADE "+colors.color_yellow + __version__ + colors.color_none+"
by Javier Palanca, Gustavo Aranda, Miguel Escriva and others"
- print "
gus...@gmail.com -
http://spade2.googlecode.com"
- raise SystemExit
+ print "SPADE " + colors.color_yellow + __version__ + colors.color_none
+ " by Javier Palanca, Gustavo Aranda, Miguel Escriva and others"
+ print "
gus...@gmail.com -
http://spade2.googlecode.com"
+ raise SystemExit
# Actually start the program running.
-def main():
- configfilename = "/etc/spade/spade.xml"
- jabberxml = "/etc/spade/xmppd.xml"
- if sys.platform[:6] == 'netbsd':
- configfilename = os.sep + "usr" + os.sep + "pkg" + configfilename
- jabberxml = os.sep+ "usr" + os.sep + "pkg" + jabberxml
+def main():
+ configfilename = "/etc/spade/spade.xml"
+ jabberxml = "/etc/spade/xmppd.xml"
+ if sys.platform[:6] == 'netbsd':
+ configfilename = os.sep + "usr" + os.sep + "pkg" + configfilename
+ jabberxml = os.sep + "usr" + os.sep + "pkg" + jabberxml
- web = False
- if len(sys.argv) < 2: pass
- elif sys.argv[1] in ["--help", "-h"]: print_help()
- elif sys.argv[1] in ["--version", "-v"]: print_version()
- #elif sys.argv[1] in ["--web", "-w"]: web = True
+ web = False
+ if len(sys.argv) < 2:
+ pass
+ elif sys.argv[1] in ["--help", "-h"]:
+ print_help()
+ elif sys.argv[1] in ["--version", "-v"]:
+ print_version()
+ #elif sys.argv[1] in ["--web", "-w"]: web = True
- dbg = []
+ dbg = []
- if
os.name != "posix" or not os.path.exists(jabberxml) or not
os.path.exists(configfilename):
- configfilename = "spade.xml"
- configfilename = os.path.abspath(configfilename)
- jabberxml = "xmppd.xml"
- jabberxml = os.path.abspath(jabberxml)
+ if
os.name != "posix" or not os.path.exists(jabberxml) or not
os.path.exists(configfilename):
+ configfilename = "spade.xml"
+ configfilename = os.path.abspath(configfilename)
+ jabberxml = "xmppd.xml"
+ jabberxml = os.path.abspath(jabberxml)
- try:
- for opt, arg in getopt(sys.argv[1:],
- "hvdwc:j:",
["help", "version", "debug", "web", "configfile=",
- "jabber="])[0]:
- if opt in ["-h", "--help"]: print_help()
- elif opt in ["-v", "--version"]: print_version()
- elif opt in ["-c", "--configfile"]: configfilename = arg
- elif opt in ["-j", "--jabber"]: jabberxml = arg
- #elif opt in ["-w", "--web"]: web = True
- elif opt in ["-d", "--debug"]: dbg = ['always']
- except:
- pass
+ try:
+ for opt, arg in getopt(sys.argv[1:],
+ "hvdwc:j:",
["help", "version", "debug", "web", "configfile=", "jabber="])[0]:
+ if opt in ["-h", "--help"]:
+ print_help()
+ elif opt in ["-v", "--version"]:
+ print_version()
+ elif opt in ["-c", "--configfile"]:
+ configfilename = arg
+ elif opt in ["-j", "--jabber"]:
+ jabberxml = arg
+ #elif opt in ["-w", "--web"]: web = True
+ elif opt in ["-d", "--debug"]:
+ dbg = ['always']
+ except:
+ pass
- print "SPADE ", colors.color_yellow + __version__ + colors.color_none, "
<
gus...@gmail.com> -
http://spade2.googlecode.com"
+ print "SPADE ", colors.color_yellow + __version__ +
colors.color_none, " <
gus...@gmail.com> -
http://spade2.googlecode.com"
- try:
- import psyco
- psyco.full()
- #print "Using Psyco optimizing compiler."
- #psyco.log(logfile='/tmp/psyco.log')
- #psyco.profile()
- except ImportError: pass #print "W: Psyco optimizing compiler not found."
+ try:
+ import psyco
+ psyco.full()
+ #psyco.profile()
+ except ImportError:
+ pass # print "W: Psyco optimizing compiler not found."
- sys.stdout.write("Starting SPADE")
- sys.stdout.flush()
- sys.stdout.write(".")
- sys.stdout.flush()
+ sys.stdout.write("Starting SPADE")
+ sys.stdout.flush()
+ sys.stdout.write(".")
+ sys.stdout.flush()
- jabberxml = os.path.abspath(jabberxml)
- if not os.path.exists(jabberxml):
- print '\n There is no jabber config file (xmppd.xml)'+
colors.color_red + " [failed]" + colors.color_none
+ jabberxml = os.path.abspath(jabberxml)
+ if not os.path.exists(jabberxml):
+ print '\n There is no jabber config file (xmppd.xml)' +
colors.color_red + " [failed]" + colors.color_none
print_help()
raise SystemExit
-
- if sys.platform[:6] == 'netbsd':
- pyvers= 'python'+str(numb)
- path = "/usr/pkg/lib" + os.sep + pyvers + "/site-packages/xmppd/"
- os.chdir(path)
- else:
- pass #os.chdir("xmppd")
-
- s = Server(cfgfile=jabberxml,
cmd_options={'enable_debug':dbg, 'enable_psyco':False})
- #os.chdir("..")
- sys.stdout.write(".")
- sys.stdout.flush()
-
- thread.start_new_thread(s.run,tuple())
-
- try:
- sys.stdout.write(".")
- sys.stdout.flush()
- if not os.path.exists(configfilename):
- print '\n There is no SPADE config file (spade.xml)'+
colors.color_red + " [failed]" + colors.color_none
- print_help()
- raise SystemExit
- platform = spade_backend.SpadeBackend(configfilename)
- sys.stdout.write(".")
- sys.stdout.flush()
- platform.start()
- sys.stdout.write(".")
- sys.stdout.flush()
- s.DEBUG = platform.DEBUG
+ if sys.platform[:6] == 'netbsd':
+ pyvers = 'python' + str(numb)
+ path = "/usr/pkg/lib" + os.sep + pyvers + "/site-packages/xmppd/"
+ os.chdir(path)
+ else:
+ pass # os.chdir("xmppd")
+ s = Server(cfgfile=jabberxml, cmd_options={'enable_debug': dbg,
+ 'enable_psyco': False})
sys.stdout.write(".")
sys.stdout.flush()
-
- except Exception,e:
- _exception = sys.exc_info()
- if _exception[0]:
- print '\n'+''.join(traceback.format_exception(_exception[0],
_exception[1], _exception[2])).rstrip()
- print str(e)
- print colors.color_red + " [failed]" + colors.color_none
- platform.shutdown()
- s.shutdown("Jabber server terminated...")
- raise SystemExit
-
- print colors.color_green + " [done]" + colors.color_none
- if platform.acc.wui:
- print "\n "+ colors.color_yellow + " [info] " + colors.color_none
+ "WebUserInterface serving at port " + str(platform.acc.wui.port) + "\n "
-
+ thread.start_new_thread(s.run, tuple())
- alive=True
- while alive:
try:
- time.sleep(1)
- if not platform.alive:
- #The platform died (probable restart). Let's start it over
- platform.shutdown()
- print "\n " + colors.color_green + "SPADE Platform
restarting..." + colors.color_none
- platform.start()
- print colors.color_green + " [done]" + colors.color_none
- except KeyboardInterrupt:
- sys.stdout.write("Exiting")
+ sys.stdout.write(".")
sys.stdout.flush()
- platform.shutdown()
+ if not os.path.exists(configfilename):
+ print '\n There is no SPADE config file (spade.xml)' +
colors.color_red + " [failed]" + colors.color_none
+ print_help()
+ raise SystemExit
+
+ platform = spade_backend.SpadeBackend(configfilename)
sys.stdout.write(".")
sys.stdout.flush()
- s.shutdown("SPADE Jabber server terminated...")
+ platform.start()
sys.stdout.write(".")
sys.stdout.flush()
- time.sleep(1)
- del s
+ s.DEBUG = platform.DEBUG
+
sys.stdout.write(".")
sys.stdout.flush()
- print colors.color_green + " Bye." + colors.color_none
- alive=False
- sys.exit(0)
-
- raise SystemExit
+
+ except Exception, e:
+ _exception = sys.exc_info()
+ if _exception[0]:
+ print '\n' + ''.join(traceback.format_exception(_exception[0],
_exception[1], _exception[2])).rstrip()
+ print str(e)
+ print colors.color_red + " [failed]" + colors.color_none
+ platform.shutdown()
+ s.shutdown("Jabber server terminated...")
+ raise SystemExit
+
+ print colors.color_green + " [done]" + colors.color_none
+ if platform.acc.wui:
+ print "\n " + colors.color_yellow + " [info] " + colors.color_none
+ "WebUserInterface serving at port " + str(platform.acc.wui.port) + "\n "
+
+ alive = True
+ while alive:
+ try:
+ time.sleep(1)
+ if not platform.alive:
+ #The platform died (probable restart). Let's start it over
+ platform.shutdown()
+ print "\n " + colors.color_green + "SPADE Platform
restarting..." + colors.color_none
+ platform.start()
+ print colors.color_green + " [done]" + colors.color_none
+ except KeyboardInterrupt:
+ alive = False
-if __name__ == '__main__': main()
+ sys.stdout.write("Exiting")
+ sys.stdout.flush()
+ platform.shutdown()
+ sys.stdout.write(".")
+ sys.stdout.flush()
+ s.shutdown("SPADE Jabber server terminated...")
+ sys.stdout.write(".")
+ sys.stdout.flush()
+ time.sleep(1)
+ del s
+ sys.stdout.write(".")
+ sys.stdout.flush()
+ print colors.color_green + " Bye." + colors.color_none
+ #raise SystemExit
+ sys.exit(0)
+if __name__ == '__main__':
+ main()
=======================================
--- /trunk/spade/ACLMessage.py Fri Nov 9 09:51:22 2012
+++ /trunk/spade/ACLMessage.py Fri Nov 23 05:19:16 2012
@@ -1,9 +1,8 @@
-#import time
+# -*- coding: utf-8 -*-
import AID
import random
import string
import cPickle as pickle
-#random.seed(time.time())
import content
from ACLParser import ACLxmlParser
import xml
@@ -11,575 +10,559 @@
import json
FIPA_ACL_REP_STRING = "fipa.acl.rep.string.std"
-FIPA_ACL_REP_JSON = "fipa.acl.rep.json.std"
-FIPA_ACL_REP_XML = "fipa.acl.rep.xml.std"
+FIPA_ACL_REP_JSON = "fipa.acl.rep.json.std"
+FIPA_ACL_REP_XML = "fipa.acl.rep.xml.std"
+
class ACLMessage:
- """
- ACLMessage class stores a message using the ACL language
- """
- ACCEPT_PROPOSAL = 'accept-proposal'
- AGREE = 'agree'
- CANCEL = 'cancel'
- CFP = 'cfp'
- CALL_FOR_PROPOSAL = 'call-for-proposal'
- CONFIRM = 'confirm'
- DISCONFIRM = 'disconfirm'
- FAILURE = 'failure'
- INFORM = 'inform'
- NOT_UNDERSTOOD = 'not-understood'
- PROPOSE = 'propose'
- QUERY_IF = 'query-if'
- QUERY_REF = 'query-ref'
- REFUSE = 'refuse'
- REJECT_PROPOSAL = 'reject-proposal'
- REQUEST = 'request'
- REQUEST_WHEN = 'request-when'
- REQUEST_WHENEVER = 'request-whenever'
- SUBSCRIBE = 'subscribe'
- INFORM_IF = 'inform-if'
- PROXY = 'proxy'
- PROPAGATE = 'propagate'
+ """
+ ACLMessage class stores a message using the ACL language
+ """
+ ACCEPT_PROPOSAL = 'accept-proposal'
+ AGREE = 'agree'
+ CANCEL = 'cancel'
+ CFP = 'cfp'
+ CALL_FOR_PROPOSAL = 'call-for-proposal'
+ CONFIRM = 'confirm'
+ DISCONFIRM = 'disconfirm'
+ FAILURE = 'failure'
+ INFORM = 'inform'
+ NOT_UNDERSTOOD = 'not-understood'
+ PROPOSE = 'propose'
+ QUERY_IF = 'query-if'
+ QUERY_REF = 'query-ref'
+ REFUSE = 'refuse'
+ REJECT_PROPOSAL = 'reject-proposal'
+ REQUEST = 'request'
+ REQUEST_WHEN = 'request-when'
+ REQUEST_WHENEVER = 'request-whenever'
+ SUBSCRIBE = 'subscribe'
+ INFORM_IF = 'inform-if'
+ PROXY = 'proxy'
+ PROPAGATE = 'propagate'
- cid_base =
str("".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(4)]))
- cid_autocount = 0
+ cid_base = str("".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(4)]))
+ cid_autocount = 0
- def __init__(self, performative=None, jsonstring=None):
- self._attrs = {}
- #possible FIPA communicative acts
- self.commacts = ['accept-proposal', 'agree', 'cancel', \
- 'cfp', 'call-for-proposal', 'confirm', 'disconfirm', \
- 'failure', 'inform', 'not-understood', \
- 'propose', 'query-if', 'query-ref', \
- 'refuse', 'reject-proposal', 'request', \
- 'request-when', 'request-whenever', 'subscribe', \
- 'inform-if', 'proxy', 'propagate']
+ def __init__(self, performative=None, jsonstring=None):
+ self._attrs = {}
+ #possible FIPA communicative acts
+ self.commacts = ['accept-proposal', 'agree', 'cancel',
+ 'cfp', 'call-for-proposal', 'confirm', 'disconfirm',
+ 'failure', 'inform', 'not-understood',
+ 'propose', 'query-if', 'query-ref',
+ 'refuse', 'reject-proposal', 'request',
+ 'request-when', 'request-whenever', 'subscribe',
+ 'inform-if', 'proxy', 'propagate']
- """
- if performative and (performative.lower() in self.commacts):
- self.performative = performative.lower()
- else: self.performative = None
- """
- if performative and (performative.lower() in self.commacts):
- self._attrs["performative"] = performative.lower()
+ """
+ if performative and (performative.lower() in self.commacts):
+ self.performative = performative.lower()
+ else: self.performative = None
+ """
+ if performative and (performative.lower() in self.commacts):
+ self._attrs["performative"] = performative.lower()
- self.sender = None
- self.receivers = []
- self.content = None
+ self.sender = None
+ self.receivers = []
+ self.content = None
- self._attrs["acl_representation"] = FIPA_ACL_REP_XML
+ self._attrs["acl_representation"] = FIPA_ACL_REP_XML
- """
- self.reply_to = []
- self.reply_with = None
- self.reply_by = None
- self.in_reply_to = None
- self.encoding = None
- self.language = None
- self.ontology = None
- self.protocol = None
- self.conversation_id = str(self.cid_base + str(self.cid_autocount))
- self.cid_autocount +=1
- """
+ #self._attrs['id'] = str(ACLMessage.cid_base +
str(ACLMessage.cid_autocount))
+ #ACLMessage.cid_autocount += 1
+ self._attrs['id'] = str(uuid.uuid4()).replace("-", "")
- #self._attrs['id'] = str(ACLMessage.cid_base +
str(ACLMessage.cid_autocount))
- #ACLMessage.cid_autocount += 1
- self._attrs['id'] = str(uuid.uuid4()).replace("-","")
+ #self.userDefProps = None
- #self.userDefProps = None
-
- if jsonstring: self.loadJSON(jsonstring)
+ if jsonstring:
+ self.loadJSON(jsonstring)
- def reset(self):
- """
- resets the object
- its structures are set to its initial value
- """
- self.__init__()
+ def reset(self):
+ """
+ resets the object
+ its structures are set to its initial value
+ """
+ self.__init__()
- def setSender(self, sender):
- """
- set the sender (AID class)
- """
- self.sender = sender
+ def setSender(self, sender):
+ """
+ set the sender (AID class)
+ """
+ self.sender = sender
- def getSender(self):
- """
- returns the sender (AID class)
- """
- return self.sender
+ def getSender(self):
+ """
+ returns the sender (AID class)
+ """
+ return self.sender
- def addReceiver(self, recv):
- """
- adds a receiver to the list (AID class)
- """
- self.receivers.append(recv)
+ def addReceiver(self, recv):
+ """
+ adds a receiver to the list (AID class)
+ """
+ self.receivers.append(recv)
- def removeReceiver(self, recv):
- """
- removes a receiver from the list (AID class)
- """
- if recv in self.receivers:
- self.receivers.remove(recv)
-
- def resetReceivers(self):
- """
- clears the list of receivers
- """
- self.receivers = []
+ def removeReceiver(self, recv):
+ """
+ removes a receiver from the list (AID class)
+ """
+ if recv in self.receivers:
+ self.receivers.remove(recv)
- def getReceivers(self):
- """
- returns the list of reveivers
- """
- return self.receivers
+ def resetReceivers(self):
+ """
+ clears the list of receivers
+ """
+ self.receivers = []
+ def getReceivers(self):
+ """
+ returns the list of reveivers
+ """
+ return self.receivers
- def addReplyTo(self, re):
- """
- adds a 'reply to' to the list (AID class)
- """
- if isinstance(re,AID.aid):
- #self.reply_to.append(re)
- if self._attrs.has_key('reply_to'):
- self._attrs['reply_to'].append(re)
- else:
- self._attrs['reply_to'] = [re]
+ def addReplyTo(self, re):
+ """
+ adds a 'reply to' to the list (AID class)
+ """
+ if isinstance(re, AID.aid):
+ #self.reply_to.append(re)
+ if 'reply_to' in self._attrs:
+ self._attrs['reply_to'].append(re)
+ else:
+ self._attrs['reply_to'] = [re]
- def removeReplyTo(self, re):
- """
- removes a 'reply to' from the list (AID class)
- """
- """
- if re in self.reply_to:
- self.reply_to.remove(re)
- """
- try:
- self._attrs["reply_to"].remove(re)
- except:
- return False
+ def removeReplyTo(self, re):
+ """
+ removes a 'reply to' from the list (AID class)
+ """
+ try:
+ self._attrs["reply_to"].remove(re)
+ except:
+ return False
- return True
+ return True
- def getReplyTo(self):
- """
- returns a 'reply to' from the list (AID class)
- """
- try:
- return str(self._attrs["reply_to"])
- except:
- return []
+ def getReplyTo(self):
+ """
+ returns a 'reply to' from the list (AID class)
+ """
+ try:
+ return str(self._attrs["reply_to"])
+ except:
+ return []
- def setPerformative(self, p):
- """
- sets the message performative (string)
- must be in ACLMessage.commacts
- """
- if p and (p.lower() in self.commacts):
- #self.performative = p.lower()
- self._attrs["performative"] = p.lower()
+ def setPerformative(self, p):
+ """
+ sets the message performative (string)
+ must be in ACLMessage.commacts
+ """
+ if p and (p.lower() in self.commacts):
+ #self.performative = p.lower()
+ self._attrs["performative"] = p.lower()
- def getPerformative(self):
- """
- returns the message performative (string)
- """
- try:
- return str(self._attrs["performative"])
- except:
- return None
+ def getPerformative(self):
+ """
+ returns the message performative (string)
+ """
+ try:
+ return str(self._attrs["performative"])
+ except:
+ return None
- def setContent(self,c):
- """
- sets the message content (string, bytestream, ...)
- """
- self.content = str(c)
-
- def setContentObject(self,co):
- """
- sets the message content in ContentObject format
- """
- self.content = co
+ def setContent(self, c):
+ """
+ sets the message content (string, bytestream, ...)
+ """
+ self.content = str(c)
- def getContent(self):
- """
- returns the message content
- """
- try:
- return self.content.asRDFXML()
- except:
- return str(self.content)
+ def setContentObject(self, co):
+ """
+ sets the message content in ContentObject format
+ """
+ self.content = co
- def getContentObject(self):
- """
- returns the message content in ContentObject format, if possible
- """
- if "str" in str(type(self.content)):
- try:
- return content.RDFXML2CO(self.content)
- except:
- return None
- elif "ContentObject" in str(type(self.content)):
- return self.content
- else:
- return None
+ def getContent(self):
+ """
+ returns the message content
+ """
+ try:
+ return self.content.asRDFXML()
+ except:
+ return str(self.content)
- def setReplyWith(self,rw):
- self._attrs["reply_with"] = str(rw)
- #self.reply_with = rw
+ def getContentObject(self):
+ """
+ returns the message content in ContentObject format, if possible
+ """
+ if "str" in str(type(self.content)):
+ try:
+ return content.RDFXML2CO(self.content)
+ except:
+ return None
+ elif "ContentObject" in str(type(self.content)):
+ return self.content
+ else:
+ return None
- def getReplyWith(self):
- try:
- return str(self._attrs["reply_with"])
- except:
- return None
+ def setReplyWith(self, rw):
+ self._attrs["reply_with"] = str(rw)
+ #self.reply_with = rw
- def setInReplyTo(self, reply):
- self._attrs["in_reply_to"] = str(reply)
+ def getReplyWith(self):
+ try:
+ return str(self._attrs["reply_with"])
+ except:
+ return None
- def getInReplyTo(self):
- try:
- return str(self._attrs["in_reply_to"])
- except:
- return None
+ def setInReplyTo(self, reply):
+ self._attrs["in_reply_to"] = str(reply)
- def setEncoding(self,e):
- self._attrs["encoding"] = str(e)
+ def getInReplyTo(self):
+ try:
+ return str(self._attrs["in_reply_to"])
+ except:
+ return None
- def getEncoding(self):
- try:
- return str(self._attrs["encoding"])
- except:
- return None
+ def setEncoding(self, e):
+ self._attrs["encoding"] = str(e)
- def setLanguage(self,e):
- self._attrs["language"] = str(e)
+ def getEncoding(self):
+ try:
+ return str(self._attrs["encoding"])
+ except:
+ return None
- def getLanguage(self):
- try:
- return str(self._attrs["language"])
- except:
- return None
+ def setLanguage(self, e):
+ self._attrs["language"] = str(e)
- def setAclRepresentation(self,e):
- self._attrs["acl_representation"] = str(e)
+ def getLanguage(self):
+ try:
+ return str(self._attrs["language"])
+ except:
+ return None
- def getAclRepresentation(self):
- try:
- return str(self._attrs["acl_representation"])
- except:
- return None
+ def setAclRepresentation(self, e):
+ self._attrs["acl_representation"] = str(e)
- def setOntology(self,e):
- self._attrs["ontology"] = str(e)
+ def getAclRepresentation(self):
+ try:
+ return str(self._attrs["acl_representation"])
+ except:
+ return None
- def getOntology(self):
- try:
- return str(self._attrs["ontology"])
- except:
- return None
+ def setOntology(self, e):
+ self._attrs["ontology"] = str(e)
- def setReplyBy(self,e):
- self._attrs["reply_by"] = str(e)
+ def getOntology(self):
+ try:
+ return str(self._attrs["ontology"])
+ except:
+ return None
- def getReplyBy(self):
- try:
- return str(self._attrs["reply_by"])
- except:
- return None
+ def setReplyBy(self, e):
+ self._attrs["reply_by"] = str(e)
- def setProtocol(self,e):
- self._attrs["protocol"] = str(e)
+ def getReplyBy(self):
+ try:
+ return str(self._attrs["reply_by"])
+ except:
+ return None
- def getProtocol(self):
- try:
- return str(self._attrs["protocol"])
- except:
- return None
+ def setProtocol(self, e):
+ self._attrs["protocol"] = str(e)
- def setConversationId(self,e):
- self._attrs["id"] = str(e)
+ def getProtocol(self):
+ try:
+ return str(self._attrs["protocol"])
+ except:
+ return None
- def getConversationId(self):
- try:
- return str(self._attrs["id"])
- except:
- return None
+ def setConversationId(self, e):
+ self._attrs["id"] = str(e)
- def createReply(self):
- """
- Creates a reply for the message
- Duplicates all the message structures
- exchanges the 'from' AID with the 'to' AID
- """
+ def getConversationId(self):
+ try:
+ return str(self._attrs["id"])
+ except:
+ return None
- m = ACLMessage()
+ def createReply(self):
+ """
+ Creates a reply for the message
+ Duplicates all the message structures
+ exchanges the 'from' AID with the 'to' AID
+ """
- m.setPerformative(self.getPerformative())
- #m.setSender(None)
- #m.receivers = []
- #m.reply_to = []
- #m.setContent(None)
- #m.setReplyBy(None)
- #m.setEncoding(None)
- if self.getLanguage(): m.setLanguage(self.getLanguage())
- if self.getOntology(): m.setOntology(self.getOntology())
- if self.getProtocol(): m.setProtocol(self.getProtocol())
- if self.getConversationId():
m.setConversationId(self.getConversationId())
+ m = ACLMessage()
- for i in self.getReplyTo():
- m.addReceiver(i)
+ m.setPerformative(self.getPerformative())
+ #m.setSender(None)
+ #m.receivers = []
+ #m.reply_to = []
+ #m.setContent(None)
+ #m.setReplyBy(None)
+ #m.setEncoding(None)
+ if self.getLanguage():
+ m.setLanguage(self.getLanguage())
+ if self.getOntology():
+ m.setOntology(self.getOntology())
+ if self.getProtocol():
+ m.setProtocol(self.getProtocol())
+ if self.getConversationId():
+ m.setConversationId(self.getConversationId())
- if not self.getReplyTo():
- m.addReceiver(self.sender)
+ for i in self.getReplyTo():
+ m.addReceiver(i)
- if self.getReplyWith():
- m.setInReplyTo(self.getReplyWith())
+ if not self.getReplyTo():
+ m.addReceiver(self.sender)
- #if self.getReplyWith() != None:
- # m.setConversationId(str(self.getReplyWith()))
+ if self.getReplyWith():
+ m.setInReplyTo(self.getReplyWith())
- return m
+ #if self.getReplyWith() != None:
+ # m.setConversationId(str(self.getReplyWith()))
+ return m
- def __str__(self):
- if self.getAclRepresentation() == FIPA_ACL_REP_JSON:
- return self.asJSON()
- elif self.getAclRepresentation() == FIPA_ACL_REP_STRING:
- return self.asString()
- elif self.getAclRepresentation() == FIPA_ACL_REP_XML:
- return self.asXML()
- else:
- return self.asXML()
-
- def asXML(self):
- p = ACLxmlParser()
- return p.encodeXML(self)
-
- def asString(self):
- """
- returns a printable version of the message in ACL string representation
- """
+ def __str__(self):
+ if self.getAclRepresentation() == FIPA_ACL_REP_JSON:
+ return self.asJSON()
+ elif self.getAclRepresentation() == FIPA_ACL_REP_STRING:
+ return self.asString()
+ elif self.getAclRepresentation() == FIPA_ACL_REP_XML:
+ return self.asXML()
+ else:
+ return self.asXML()
- p = '('
+ def asXML(self):
+ p = ACLxmlParser()
+ return p.encodeXML(self)
- p=p+ str(self.getPerformative()) + '\n'
- if self.sender:
- p = p + ":sender " + str(self.sender) + "\n"
+ def asString(self):
+ """
+ returns a printable version of the message in ACL string
representation
+ """
- if self.receivers:
- p = p + ":receiver\n (set\n"
- for i in self.receivers:
- p=p+ str(i) + '\n'
+ p = '('
- p = p + ")\n"
- if self.content:
- p = p + ':content "'+ str(self.content) + '"\n'
+ p = p + str(self.getPerformative()) + '\n'
+ if self.sender:
+ p = p + ":sender " + str(self.sender) + "\n"
- if self.getReplyWith():
- p = p + ":reply-with " + self.getReplyWith() + '\n'
+ if self.receivers:
+ p = p + ":receiver\n (set\n"
+ for i in self.receivers:
+ p = p + str(i) + '\n'
- if self.getReplyBy():
- p = p+ ":reply-by " + self.getReplyBy() + '\n'
+ p = p + ")\n"
+ if self.content:
+ p = p + ':content "' + str(self.content) + '"\n'
- if self.getInReplyTo():
- p = p+ ":in-reply-to " + self.getInReplyTo() + '\n'
+ if self.getReplyWith():
+ p = p + ":reply-with " + self.getReplyWith() + '\n'
- if self.getReplyTo():
- p = p+ ":reply-to \n" + '(set\n'
- for i in self.getReplyTo():
- p=p+ i + '\n'
- p = p + ")\n"
+ if self.getReplyBy():
+ p = p + ":reply-by " + self.getReplyBy() + '\n'
- if self.getLanguage():
- p = p+ ":language " + self.getLanguage() + '\n'
+ if self.getInReplyTo():
+ p = p + ":in-reply-to " + self.getInReplyTo() + '\n'
- if self.getEncoding():
- p = p+ ":encoding " + self.getEncoding() + '\n'
+ if self.getReplyTo():
+ p = p + ":reply-to \n" + '(set\n'
+ for i in self.getReplyTo():
+ p = p + i + '\n'
+ p = p + ")\n"
- if self.getOntology():
- p = p+ ":ontology " + self.getOntology() + '\n'
+ if self.getLanguage():
+ p = p + ":language " + self.getLanguage() + '\n'
- if self.getProtocol():
- p = p+ ":protocol " + self.getProtocol() + '\n'
+ if self.getEncoding():
+ p = p + ":encoding " + self.getEncoding() + '\n'
- if self.getConversationId():
- p = p+ ":conversation-id " + self.getConversationId() + '\n'
+ if self.getOntology():
+ p = p + ":ontology " + self.getOntology() + '\n'
+ if self.getProtocol():
+ p = p + ":protocol " + self.getProtocol() + '\n'
- p = p + ")\n"
+ if self.getConversationId():
+ p = p + ":conversation-id " + self.getConversationId() + '\n'
- return p
+ p = p + ")\n"
- def serialize(self):
- """
- returns a serialized version of the message
- """
- return pickle.dumps(self)
+ return p
- def asHTML(self):
- """
- returns an HTML version of the message ready to be displayed at the WUI
- """
- s = '<table class="servicesT" cellspacing="0">'
- s += '<tr><td class="servHd">Performative</td><td
class="servBodL">'+self.getPerformative()+'</td></tr>'
- if self.sender:
- sndr = self.sender.asXML()
- sndr = sndr.replace(">", ">")
- sndr = sndr.replace("<", "<")
- sndr = sndr.replace('"', """)
- s += '<tr><td class="servHd">Sender</td><td
class="servBodL"><pre>'+sndr+'</pre></td></tr>'
- recvs = ""
- for r in self.receivers:
- escaped = r.asXML()
- escaped = escaped.replace(">", ">")
- escaped = escaped.replace("<", "<")
- escaped = escaped.replace('"', """)
- recvs += escaped + "<br />"
- s += '<tr><td class="servHd">Receivers</td><td
class="servBodL"><pre>'+recvs+'</pre></td></tr>'
- if self.content:
- cont = self.getContent()
- try:
- # Try to beautify the content if it is XML
- x = xml.dom.minidom.parseString(cont)
- cont = x.toprettyxml()
- except:
- pass
- cont = cont.replace(">", ">")
- cont = cont.replace("<", "<")
- cont = cont.replace('"', """)
- s += '<tr><td class="servHd">Content</td><td
class="servBodL"><pre>'+cont+'</pre></td></tr>'
- if self.getReplyWith():
- s += '<tr><td class="servHd">Reply With</td><td
class="servBodL">'+str(self.getReplyWith())+'</td></tr>'
- if self.getReplyBy():
- s += '<tr><td class="servHd">Reply By</td><td
class="servBodL">'+str(self.getReplyBy())+'</td></tr>'
- if self.getInReplyTo():
- s += '<tr><td class="servHd">In Reply To</td><td
class="servBodL">'+str(self.getInReplyTo())+'</td></tr>'
- if self.getReplyTo():
- s += '<tr><td class="servHd">Reply To</td><td
class="servBodL">'+str(self.getReplyTo())+'</td></tr>'
- if self.getLanguage():
- s += '<tr><td class="servHd">Language</td><td
class="servBodL">'+str(self.getLanguage())+'</td></tr>'
- if self.getEncoding():
- s += '<tr><td class="servHd">Encoding</td><td
class="servBodL">'+str(self.getEncoding())+'</td></tr>'
- if self.getOntology():
- s += '<tr><td class="servHd">Ontology</td><td
class="servBodL">'+str(self.getOntology())+'</td></tr>'
- if self.getProtocol():
- s += '<tr><td class="servHd">Protocol</td><td
class="servBodL">'+str(self.getProtocol())+'</td></tr>'
- if self.getConversationId():
- s += '<tr><td class="servHd">Conversation ID</td><td
class="servBodL">'+str(self.getConversationId())+'</td></tr>'
- s += '</table>'
- return s
+ def serialize(self):
+ """
+ returns a serialized version of the message
+ """
+ return pickle.dumps(self)
+ def asHTML(self):
+ """
+ returns an HTML version of the message ready to be displayed at
the WUI
+ """
+ s = '<table class="servicesT" cellspacing="0">'
+ s += '<tr><td class="servHd">Performative</td><td
class="servBodL">' + self.getPerformative() + '</td></tr>'
+ if self.sender:
+ sndr = self.sender.asXML()
+ sndr = sndr.replace(">", ">")
+ sndr = sndr.replace("<", "<")
+ sndr = sndr.replace('"', """)
+ s += '<tr><td class="servHd">Sender</td><td
class="servBodL"><pre>' + sndr + '</pre></td></tr>'
+ recvs = ""
+ for r in self.receivers:
+ escaped = r.asXML()
+ escaped = escaped.replace(">", ">")
+ escaped = escaped.replace("<", "<")
+ escaped = escaped.replace('"', """)
+ recvs += escaped + "<br />"
+ s += '<tr><td class="servHd">Receivers</td><td
class="servBodL"><pre>' + recvs + '</pre></td></tr>'
+ if self.content:
+ cont = self.getContent()
+ try:
+ # Try to beautify the content if it is XML
+ x = xml.dom.minidom.parseString(cont)
+ cont = x.toprettyxml()
+ except:
+ pass
+ cont = cont.replace(">", ">")
+ cont = cont.replace("<", "<")
+ cont = cont.replace('"', """)
+ s += '<tr><td class="servHd">Content</td><td
class="servBodL"><pre>' + cont + '</pre></td></tr>'
+ if self.getReplyWith():
+ s += '<tr><td class="servHd">Reply With</td><td
class="servBodL">' + str(self.getReplyWith()) + '</td></tr>'
+ if self.getReplyBy():
+ s += '<tr><td class="servHd">Reply By</td><td
class="servBodL">' + str(self.getReplyBy()) + '</td></tr>'
+ if self.getInReplyTo():
+ s += '<tr><td class="servHd">In Reply To</td><td
class="servBodL">' + str(self.getInReplyTo()) + '</td></tr>'
+ if self.getReplyTo():
+ s += '<tr><td class="servHd">Reply To</td><td
class="servBodL">' + str(self.getReplyTo()) + '</td></tr>'
+ if self.getLanguage():
+ s += '<tr><td class="servHd">Language</td><td
class="servBodL">' + str(self.getLanguage()) + '</td></tr>'
+ if self.getEncoding():
+ s += '<tr><td class="servHd">Encoding</td><td
class="servBodL">' + str(self.getEncoding()) + '</td></tr>'
+ if self.getOntology():
+ s += '<tr><td class="servHd">Ontology</td><td
class="servBodL">' + str(self.getOntology()) + '</td></tr>'
+ if self.getProtocol():
+ s += '<tr><td class="servHd">Protocol</td><td
class="servBodL">' + str(self.getProtocol()) + '</td></tr>'
+ if self.getConversationId():
+ s += '<tr><td class="servHd">Conversation ID</td><td
class="servBodL">' + str(self.getConversationId()) + '</td></tr>'
+ s += '</table>'
+ return s
- def asJSON(self):
- """
- returns a JSON version of the message
- """
- p = "{"
+ def asJSON(self):
+ """
+ returns a JSON version of the message
+ """
+ p = "{"
- p+='"performative":"'+str(self.getPerformative())+'",'
+ p += '"performative":"' + str(self.getPerformative()) + '",'
- if self.sender:
- p+='"sender":' + self.sender.asJSON() + ","
+ if self.sender:
+ p += '"sender":' + self.sender.asJSON() + ","
- if self.receivers:
- p+='"receivers":['
- for i in self.receivers:
- p += i.asJSON()+","
- if p[-1:]==",":
- p = p[:-1]
- p+="],"
-
- if self.content:
- p = p + '"content":"' + str(self.content) + '",'
+ if self.receivers:
+ p += '"receivers":['
+ for i in self.receivers:
+ p += i.asJSON() + ","
+ if p[-1:] == ",":
+ p = p[:-1]
+ p += "],"
- if self.getReplyWith():
- p = p + '"reply-with":"' + str(self.getReplyWith()) + '",'
+ if self.content:
+ p = p + '"content":"' + str(self.content) + '",'
- if self.getReplyBy():
- p = p+ '"reply-by":"' + self.getReplyBy() + '",'
+ if self.getReplyWith():
+ p = p + '"reply-with":"' + str(self.getReplyWith()) + '",'
- if self.getInReplyTo():
- p = p+ '"in-reply-to":"' + self.getInReplyTo() + '",'
+ if self.getReplyBy():
+ p = p + '"reply-by":"' + self.getReplyBy() + '",'
- if self.getReplyTo():
- p = p+ '"reply-to":['
- for i in self.getReplyTo():
- p= p+ i.asJSON()+","
- if p[-1:]==",":
- p = p[:-1]
- p+="],"
+ if self.getInReplyTo():
+ p = p + '"in-reply-to":"' + self.getInReplyTo() + '",'
- if self.getLanguage():
- p = p+ '"language":"' + self.getLanguage() + '",'
+ if self.getReplyTo():
+ p = p + '"reply-to":['
+ for i in self.getReplyTo():
+ p = p + i.asJSON() + ","
+ if p[-1:] == ",":
+ p = p[:-1]
+ p += "],"
- if self.getEncoding():
- p = p+ '"encoding":"' + self.getEncoding() + '",'
+ if self.getLanguage():
+ p = p + '"language":"' + self.getLanguage() + '",'
- if self.getOntology():
- p = p+ '"ontology":"' + self.getOntology() + '",'
+ if self.getEncoding():
+ p = p + '"encoding":"' + self.getEncoding() + '",'
- if self.getProtocol():
- p = p+ '"protocol":"' + self.getProtocol() + '",'
+ if self.getOntology():
+ p = p + '"ontology":"' + self.getOntology() + '",'
- if self.getConversationId():
- p = p+ '"conversation-id":"' + self.getConversationId() + '",'
+ if self.getProtocol():
+ p = p + '"protocol":"' + self.getProtocol() + '",'
- if p[-1:]==",":
- p = p[:-1]
- p = p + "}"
+ if self.getConversationId():
+ p = p + '"conversation-id":"' + self.getConversationId() + '",'
- return p
+ if p[-1:] == ",":
+ p = p[:-1]
+ p = p + "}"
+ return p
- def loadJSON(self, jsonstring):
- """
- loads a JSON string in the message
- """
- p = json.loads(jsonstring)
+ def loadJSON(self, jsonstring):
+ """
+ loads a JSON string in the message
+ """
+ p = json.loads(jsonstring)
- if p.has_key("performative"): self.setPerformative(p["performative"])
+ if "performative" in p:
+ self.setPerformative(p["performative"])
- if p.has_key("sender"):
- s = AID.aid()
- s.loadJSON(p["sender"])
- self.setSender(s)
+ if "sender" in p:
+ s = AID.aid()
+ s.loadJSON(p["sender"])
+ self.setSender(s)
- if p.has_key("receivers"):
- for i in p["receivers"]:
- s = AID.aid()
- s.loadJSON(i)
- self.addReceiver(s)
+ if "receivers" in p:
+ for i in p["receivers"]:
+ s = AID.aid()
+ s.loadJSON(i)
+ self.addReceiver(s)
- if p.has_key("content"):
- self.setContent(p["content"])
+ if "content" in p:
+ self.setContent(p["content"])
- if p.has_key("reply-with"):
- self.setReplyWith(p["reply-with"])
+ if "reply-with" in p:
+ self.setReplyWith(p["reply-with"])
- if p.has_key("reply-by"):
- self.setReplyBy(p["reply-by"])
+ if "reply-by" in p:
+ self.setReplyBy(p["reply-by"])
***The diff for this file has been truncated for email.***
=======================================
--- /trunk/spade/ACLParser.py Fri Nov 9 09:51:22 2012
+++ /trunk/spade/ACLParser.py Fri Nov 23 05:19:16 2012
@@ -1,4 +1,4 @@
-# -*- coding: cp1252 -*-
+# -*- coding: utf-8 -*-
from pyparsing import *
import sys
import ACLMessage
@@ -8,591 +8,577 @@
import xml.sax
from xml.sax import handler
+
class ACLParser:
- """
- Parser for the ACL language
- """
+ """
+ Parser for the ACL language
+ """
- def __init__(self):
+ def __init__(self):
- lpar = Literal("(").suppress()
- rpar = Literal(")").suppress()
- digit = oneOf("0 1 2 3 4 5 6 7 8 9")
- sign = oneOf("+ -")
- dot = Literal(".")
- Exponent = oneOf("e E")
+ lpar = Literal("(").suppress()
+ rpar = Literal(")").suppress()
+ digit = oneOf("0 1 2 3 4 5 6 7 8 9")
+ sign = oneOf("+ -")
+ dot = Literal(".")
+ Exponent = oneOf("e E")
- _bslash = "\\"
- _escapables = 'tnrfbacdeghijklmopqsuvwxyz"' + _bslash
- _octDigits = "01234567"
- _escapedChar = ( Word( _bslash, _escapables, exact=2 ) | Word( _bslash,
_octDigits, min=2, max=4 ) )
+ _bslash = "\\"
+ _escapables = 'tnrfbacdeghijklmopqsuvwxyz"' + _bslash
+ _octDigits = "01234567"
+ _escapedChar = (Word(_bslash, _escapables, exact=2) |
Word(_bslash, _octDigits, min=2, max=4))
- _sglQuote = Literal("'")
- _dblQuote = Literal('"')
- StringLiteral = Combine( _dblQuote.suppress() + ZeroOrMore(
CharsNotIn('\\"\r') | _escapedChar ) + _dblQuote.suppress() ).streamline()
+ _sglQuote = Literal("'")
+ _dblQuote = Literal('"')
+ StringLiteral = Combine(_dblQuote.suppress() +
ZeroOrMore(CharsNotIn('\\"\r') | _escapedChar) +
_dblQuote.suppress()).streamline()
+ #Word = [~ "\0x00" – "\0x20", "(", ")", "#", "0" – "9", "-", "@"]
+ # [~ "\0x00" – "\0x20", "(", ")"]*
+ ACLWord = Word(alphanums + "#@.-")
+ #StringLiteral = "\"" ([ ~ "\"" ] | "\\\"")* "\""
+ #StringLiteral =
Combine(Literal('"')+OneOrMore(Word(alphanums+"#@ .:-_[]()+?'¿¡!$%&=*,,;<>/\\"))+Literal('"'))
- #Word = [~ "\0x00" – "\0x20", "(", ")", "#", "0"
– "9", "-", "@"]
- # [~ "\0x00" – "\0x20", "(", ")"]*
- ACLWord = Word(alphanums+"#@.-")
- #StringLiteral = "\"" ([ ~ "\"" ] | "\\\"")* "\""
- #StringLiteral =
Combine(Literal('"')+OneOrMore(Word(alphanums+"#@ .:-_[]()+?'¿¡!$%&=*,,;<>/\\"))+Literal('"'))
+ #ByteLengthEncodedString = "#" Digit+ "\"" <byte sequence>
+ ByteLengthEncodedString = Literal("TODO")
+ String = (StringLiteral | ByteLengthEncodedString)
- #ByteLengthEncodedString = "#" Digit+ "\"" <byte sequence>
- ByteLengthEncodedString = Literal("TODO")
- String = (StringLiteral | ByteLengthEncodedString)
+ Year = Combine(digit + digit + digit + digit)
+ Month = Combine(digit + digit)
+ Day = Combine(digit + digit)
+ Hour = Combine(digit + digit)
+ Minute = Combine(digit + digit)
+ Second = Combine(digit + digit)
+ MilliSecond = Combine(digit + digit + digit)
+ DateTime = Combine(Optional(sign) + Year + Month + Day +
Literal("T") + Hour + Minute + Second + MilliSecond)
+ FloatExponent = Combine(Exponent + Optional(sign) +
OneOrMore(digit))
+ FloatMantissa = Combine((OneOrMore(digit) + dot +
ZeroOrMore(digit)) | (ZeroOrMore(digit) + dot + OneOrMore(digit)))
+ Float = Combine((Optional(sign) + FloatMantissa +
Optional(FloatExponent)) | (Optional(sign) + OneOrMore(digit) +
FloatExponent))
- Year = Combine(digit + digit + digit + digit)
- Month = Combine(digit + digit)
- Day = Combine(digit + digit)
- Hour = Combine(digit + digit)
- Minute = Combine(digit + digit)
- Second = Combine(digit + digit)
- MilliSecond = Combine(digit + digit + digit)
- DateTime = Combine(Optional(sign) + Year + Month + Day + Literal("T") +
Hour + Minute + Second + MilliSecond)
+ Integer = Combine(Optional(sign) + OneOrMore(digit))
+ Number = Group(Integer | Float)
- FloatExponent = Combine(Exponent + Optional(sign) + OneOrMore(digit))
- FloatMantissa = Combine((OneOrMore(digit) + dot + ZeroOrMore(digit)) |
(ZeroOrMore(digit) + dot + OneOrMore(digit)) )
- Float = Combine((Optional(sign) + FloatMantissa +
Optional(FloatExponent) ) | ( Optional(sign) + OneOrMore(digit) +
FloatExponent ))
+ """
+ #bnf de una URL
+ void=empty
+ digits = nums
+ hex = nums + "abcdefABCDEF"
+ safe = "$-_@.&+-"
+ extra = "!*\"'(),"
+ escape = "%" + hex + hex
+ xalphas = Word(alphanums+safe+extra+escape)
+ ialpha = (Word(alphas) + Optional(xalphas))
+ alphanum2 = alphanums+"-"+"_"+"."+"+"
+ password = Forward()
+ password << (alphanum2+Optional(password))
+ user=Forward()
+ user << (alphanum2+Optional(user))
+ search = Forward()
+ search << (xalphas + Optional(Literal("+")+search))
+ segment = xalphas
+ path = Forward()
+ path << (void | (segment + Optional(Literal("/")+path)))
+ port = digits
+ hostname = Forward()
+ hostnumber = (digits + dot + digits + dot + digits + dot + digits)
+ hostname << ialpha + Optional(dot + hostname)
+ formcode = (Literal("N")|Literal("T")|Literal("C"))
+ ftptype = ((Literal("A")+formcode)|(Literal("E")+formcode)|
Literal("I")|(Literal("L")+digits))
+ host = (hostname|hostnumber)
+ hostport = (host + Optional(Literal(":")+port))
+ login = (Optional(user + Optional(Literal(":")+password) +
Literal("@")) + hostport )
+ mailtoaddress = Combine(Literal("mailto:")+ xalphas + Literal("@")
+ hostname)
+ ftpaddress =
Combine(Literal("ftp://")+login+Literal("/")+path+Optional(Literal(";")+ftptype))
+ httpaddress =
Combine(Literal("http://")+hostport+Optional(Literal("/")+path)
+Optional(Literal("?")+search))
+ URL = (httpaddress|ftpaddress|mailtoaddress)
+ """
- Integer = Combine(Optional(sign) + OneOrMore(digit))
- Number = Group(Integer | Float)
+ #URL = Word(alphanums+":/#@.")
+ URL = Word(alphanums + ":/#@.-")
- """
- #bnf de una URL
- void=empty
- digits = nums
- hex = nums + "abcdefABCDEF"
- safe = "$-_@.&+-"
- extra = "!*\"'(),"
- escape = "%" + hex + hex
- xalphas = Word(alphanums+safe+extra+escape)
- ialpha = (Word(alphas) + Optional(xalphas))
- alphanum2 = alphanums+"-"+"_"+"."+"+"
- password = Forward()
- password << (alphanum2+Optional(password))
- user=Forward()
- user << (alphanum2+Optional(user))
- search = Forward()
- search << (xalphas + Optional(Literal("+")+search))
- segment = xalphas
- path = Forward()
- path << (void | (segment + Optional(Literal("/")+path)))
- port = digits
- hostname = Forward()
- hostnumber = (digits + dot + digits + dot + digits + dot + digits)
- hostname << ialpha + Optional(dot + hostname)
- formcode = (Literal("N")|Literal("T")|Literal("C"))
- ftptype = ((Literal("A")+formcode)|(Literal("E")+formcode)|Literal("I")|
(Literal("L")+digits))
- host = (hostname|hostnumber)
- hostport = (host + Optional(Literal(":")+port))
- login = (Optional(user + Optional(Literal(":")+password) + Literal("@"))
+ hostport )
- mailtoaddress = Combine(Literal("mailto:")+ xalphas + Literal("@") +
hostname)
- ftpaddress =
Combine(Literal("ftp://")+login+Literal("/")+path+Optional(Literal(";")+ftptype))
- httpaddress =
Combine(Literal("http://")+hostport+Optional(Literal("/")+path)
+Optional(Literal("?")+search))
- URL = (httpaddress|ftpaddress|mailtoaddress)
- """
-
- #URL = Word(alphanums+":/#@.")
- URL = Word(alphanums+":/#@.-")
-
-
- URLSequence = (lpar + Literal("sequence").suppress() + OneOrMore(URL) +
rpar)#.setResultsName("URLseq")
+ URLSequence = (lpar + Literal("sequence").suppress() +
OneOrMore(URL) + rpar) # .setResultsName("URLseq")
- AgentIdentifier = Forward()
+ AgentIdentifier = Forward()
- AgentIdentifierSequence = Group(lpar + Literal("sequence").suppress() +
OneOrMore(AgentIdentifier) + rpar)#.setResultsName("AIDseq")
+ AgentIdentifierSequence = Group(lpar +
Literal("sequence").suppress() + OneOrMore(AgentIdentifier) + rpar)
# .setResultsName("AIDseq")
- #AddressSequence = Group(lpar + Literal("sequence").suppress() +
OneOrMore(URL)+rpar) #Word(alphanums+"/.:+?")) + rpar)
+ #AddressSequence = Group(lpar + Literal("sequence").suppress() +
OneOrMore(URL)+rpar) #Word(alphanums+"/.:+?")) + rpar)
- AgentIdentifier << Group( \
- lpar + Literal("agent-identifier").suppress() + \
- #Literal(":name").suppress() + ACLWord.setResultsName("name") + \
- Literal(":name").suppress() + URL.setResultsName("name") + \
- Optional(Literal(":addresses").suppress() +
URLSequence.setResultsName("addresses")) + \
- Optional(Literal(":resolvers").suppress() +
AgentIdentifierSequence.setResultsName("resolvers")) +\
- # This one for the X-tras (thanks Jade)
- # Make it more general-case oriented
- Optional(Literal(":X-JADE-agent-classname").suppress() +
URL.suppress()) + \
- rpar)#.setResultsName("AID")
-
- #AgentIdentifier << Group(lpar + Literal("agent-identifier").suppress()
+ Literal(":name").suppress() + Word(alphanums+"@.").setResultsName("name")
+ Optional(Literal(":addresses").suppress() +
URLSequence.setResultsName("addresses")) +
Optional(Literal(":resolvers").suppress() +
AgentIdentifierSequence.setResultsName("resolvers")) +
rpar)#.setResultsName("AID")
-
- AgentIdentifierSet = Group(lpar + Literal("set").suppress() +
OneOrMore(AgentIdentifier) + rpar)
+ AgentIdentifier << Group(
+ lpar + Literal("agent-identifier").suppress() +
+ #Literal(":name").suppress() + ACLWord.setResultsName("name") +
+ Literal(":name").suppress() + URL.setResultsName("name") +
+ Optional(Literal(":addresses").suppress() +
URLSequence.setResultsName("addresses")) +
+ Optional(Literal(":resolvers").suppress() +
AgentIdentifierSequence.setResultsName("resolvers")) +
+ # This one for the X-tras (thanks Jade)
+ # Make it more general-case oriented
+ Optional(Literal(":X-JADE-agent-classname").suppress() +
URL.suppress()) +
+ rpar) # .setResultsName("AID")
- Expression = Forward()
- Expression << (ACLWord | String | Number | DateTime | (lpar + Expression
+ rpar))
- #Expression << (Word(alphanums).setResultsName("word") |
String.setResultsName("string") | Number.setResultsName("number") |
DateTime.setResultsName("datetime") | Combine(lpar + Expression +
rpar).setResultsName("expression"))
-
-
- MessageParameter = ( \
- Literal(":sender").suppress() +
AgentIdentifier.setResultsName("sender") | \
- Literal(":receiver").suppress() +
AgentIdentifierSet.setResultsName("receiver") | \
- Literal(":content").suppress() + String.setResultsName("content") | \
- #Literal(":reply-with").suppress() +
Expression.setResultsName("reply-with") | \
- Literal(":reply-with").suppress() + URL.setResultsName("reply-with") | \
- Literal(":reply-by").suppress() + DateTime.setResultsName("reply-by") |
\
- Literal(":in-reply-to").suppress() +
Expression.setResultsName("in-reply-to") | \
- Literal(":reply-to").suppress() +
AgentIdentifierSet.setResultsName("reply-to") | \
- Literal(":language").suppress() + Expression.setResultsName("language")
| \
- Literal(":encoding").suppress() + Expression.setResultsName("encoding")
| \
- Literal(":ontology").suppress() + Expression.setResultsName("ontology")
| \
- Literal(":protocol").suppress() + ACLWord.setResultsName("protocol") | \
- #Literal(":conversation-id").suppress() +
Expression.setResultsName("conversation-id") \
- Literal(":conversation-id").suppress() +
URL.setResultsName("conversation-id") \
- )
-
- MessageType = ( \
- Literal("accept-proposal")|\
- Literal("agree")|\
- Literal("cancel")|\
- Literal("cfp")|\
- Literal("confirm")|\
- Literal("disconfirm")|\
- Literal("failure")|\
- Literal("inform")|\
- Literal("inform-if")|\
- Literal("inform-ref")|\
- Literal("not-understood")|\
- Literal("propagate")|\
- Literal("propose")|\
- Literal("proxy")|\
- Literal("query-if")|\
- Literal("query-ref")|\
- Literal("refuse")|\
- Literal("reject-proposal")|\
- Literal("request")|\
- Literal("request-when")|\
- Literal("request-whenever")|\
- Literal("subscribe")|\
- # I'm looking at you, Jade!
- Literal("ACCEPT-PROPOSAL")|\
- Literal("AGREE")|\
- Literal("CANCEL")|\
- Literal("CFP")|\
- Literal("CONFIRM")|\
- Literal("DISCONFIRM")|\
- Literal("FAILURE")|\
- Literal("INFORM")|\
- Literal("INFORM-IF")|\
- Literal("INFORM-REF")|\
- Literal("NOT-UNDERSTOOD")|\
- Literal("PROPAGATE")|\
- Literal("PROPOSE")|\
- Literal("PROXY")|\
- Literal("QUERY-IF")|\
- Literal("QUERY-REF")|\
- Literal("REFUSE")|\
- Literal("REJECT-PROPOSAL")|\
- Literal("REQUEST")|\
- Literal("REQUEST-WHEN")|\
- Literal("REQUEST-WHENEVER")|\
- Literal("SUBSCRIBE")\
- )
+ #AgentIdentifier << Group(lpar +
Literal("agent-identifier").suppress() + Literal(":name").suppress() +
Word(alphanums+"@.").setResultsName("name") +
Optional(Literal(":addresses").suppress() +
URLSequence.setResultsName("addresses")) +
Optional(Literal(":resolvers").suppress() +
AgentIdentifierSequence.setResultsName("resolvers")) +
rpar)#.setResultsName("AID")
- Message = (lpar + MessageType.setResultsName("msgtype") +
OneOrMore(MessageParameter.setResultsName("msgParameter")) +
rpar)#.setResultsName("message")
+ AgentIdentifierSet = Group(lpar + Literal("set").suppress() +
OneOrMore(AgentIdentifier) + rpar)
- ACLCommunicativeAct = Message
+ Expression = Forward()
+ Expression << (ACLWord | String | Number | DateTime | (lpar +
Expression + rpar))
+ #Expression << (Word(alphanums).setResultsName("word") |
String.setResultsName("string") | Number.setResultsName("number") |
DateTime.setResultsName("datetime") | Combine(lpar + Expression +
rpar).setResultsName("expression"))
- self.bnf = ACLCommunicativeAct
+ MessageParameter = (
+ Literal(":sender").suppress() +
AgentIdentifier.setResultsName("sender") |
+ Literal(":receiver").suppress() +
AgentIdentifierSet.setResultsName("receiver") |
+ Literal(":content").suppress() +
String.setResultsName("content") |
+ #Literal(":reply-with").suppress() +
Expression.setResultsName("reply-with") |
+ Literal(":reply-with").suppress() +
URL.setResultsName("reply-with") |
+ Literal(":reply-by").suppress() +
DateTime.setResultsName("reply-by") |
+ Literal(":in-reply-to").suppress() +
Expression.setResultsName("in-reply-to") |
+ Literal(":reply-to").suppress() +
AgentIdentifierSet.setResultsName("reply-to") |
+ Literal(":language").suppress() +
Expression.setResultsName("language") |
+ Literal(":encoding").suppress() +
Expression.setResultsName("encoding") |
+ Literal(":ontology").suppress() +
Expression.setResultsName("ontology") |
+ Literal(":protocol").suppress() +
ACLWord.setResultsName("protocol") |
+ #Literal(":conversation-id").suppress() +
Expression.setResultsName("conversation-id")
+ Literal(":conversation-id").suppress() +
URL.setResultsName("conversation-id")
+ )
- #bnf = OneOrMore(line).setResultsName("program")
+ MessageType = (
+ Literal("accept-proposal") |
+ Literal("agree") |
+ Literal("cancel") |
+ Literal("cfp") |
+ Literal("confirm") |
+ Literal("disconfirm") |
+ Literal("failure") |
+ Literal("inform") |
+ Literal("inform-if") |
+ Literal("inform-ref") |
+ Literal("not-understood") |
+ Literal("propagate") |
+ Literal("propose") |
+ Literal("proxy") |
+ Literal("query-if") |
+ Literal("query-ref") |
+ Literal("refuse") |
+ Literal("reject-proposal") |
+ Literal("request") |
+ Literal("request-when") |
+ Literal("request-whenever") |
+ Literal("subscribe") |
+ # I'm looking at you, Jade!
+ Literal("ACCEPT-PROPOSAL") |
+ Literal("AGREE") |
+ Literal("CANCEL") |
+ Literal("CFP") |
+ Literal("CONFIRM") |
+ Literal("DISCONFIRM") |
+ Literal("FAILURE") |
+ Literal("INFORM") |
+ Literal("INFORM-IF") |
+ Literal("INFORM-REF") |
+ Literal("NOT-UNDERSTOOD") |
+ Literal("PROPAGATE") |
+ Literal("PROPOSE") |
+ Literal("PROXY") |
+ Literal("QUERY-IF") |
+ Literal("QUERY-REF") |
+ Literal("REFUSE") |
+ Literal("REJECT-PROPOSAL") |
+ Literal("REQUEST") |
+ Literal("REQUEST-WHEN") |
+ Literal("REQUEST-WHENEVER") |
+ Literal("SUBSCRIBE")
+ )
- #bnf.ignore(comment)
- #bnf.ignore(directive)
+ Message = (lpar + MessageType.setResultsName("msgtype") +
OneOrMore(MessageParameter.setResultsName("msgParameter")) + rpar)
# .setResultsName("message")
- try:
- self.bnf.validate()
+ ACLCommunicativeAct = Message
- except Exception, err:
- print err
- sys.exit(-1)
-
+ self.bnf = ACLCommunicativeAct
- #bnf.setDebug()
+ #bnf = OneOrMore(line).setResultsName("program")
- def processAID(self, _aid):
- """
- parses an AID.
- returns a pyparsing.ParseResult class
- """
+ #bnf.ignore(comment)
+ #bnf.ignore(directive)
- aid = AID.aid()
+ try:
+ self.bnf.validate()
- if 'name' in _aid:
- aid.setName(_aid['name'])
+ except Exception, err:
+ print err
+ sys.exit(-1)
- if 'addresses' in _aid:
- addr = _aid['addresses']
- for i in addr:
- aid.addAddress(i)
+ #bnf.setDebug()
+ def processAID(self, _aid):
+ """
+ parses an AID.
+ returns a pyparsing.ParseResult class
+ """
- if 'resolvers' in _aid:
- res = _aid['resolvers']
- for i in res:
- aid.addResolvers(self.processAID(i))
+ aid = AID.aid()
- return aid
+ if 'name' in _aid:
+ aid.setName(_aid['name'])
- def parse(self,string):
- """
- parses a string
- returns a pyparsing.ParseResult class
- """
+ if 'addresses' in _aid:
+ addr = _aid['addresses']
+ for i in addr:
+ aid.addAddress(i)
- try:
- m = self.bnf.parseString(string)
- except ParseException, err:
- print err.line
- print " "*(err.column-1)+"^"
- print err
- sys.exit(-1)
- except Exception, err:
- print "Unkwonw Exception"
- print err
- sys.exit(-1)
+ if 'resolvers' in _aid:
+ res = _aid['resolvers']
+ for i in res:
+ aid.addResolvers(self.processAID(i))
- return self.buildACL(m)
+ return aid
- def parseFile(self,file):
- """
- parses a file
- returns an ACLMessage
- """
+ def parse(self, string):
+ """
+ parses a string
+ returns a pyparsing.ParseResult class
+ """
- try:
- m = self.bnf.parseFile(file)
- except ParseException, err:
- print err.line
- print " "*(err.column-1)+"^"
- print err
- sys.exit(-1)
- except Exception, err:
- print "Unkwonw Exception"
- print err
- sys.exit(-1)
+ try:
+ m = self.bnf.parseString(string)
+ except ParseException, err:
+ print err.line
+ print " " * (err.column - 1) + "^"
+ print err
+ sys.exit(-1)
+ except Exception, err:
+ print "Unkwonw Exception"
+ print err
+ sys.exit(-1)
- return self.buildACL(m)
+ return self.buildACL(m)
- def buildACL(self, m):
- """
- returns an ACLMessage object from a pyparsing.ParseResults object
- """
-
- #print repr(m)
- #print m.asXML()
- #print m.asList()
+ def parseFile(self, file):
+ """
+ parses a file
+ returns an ACLMessage
+ """
- msg = ACLMessage.ACLMessage()
+ try:
+ m = self.bnf.parseFile(file)
+ except ParseException, err:
+ print err.line
+ print " " * (err.column - 1) + "^"
+ print err
+ sys.exit(-1)
+ except Exception, err:
+ print "Unkwonw Exception"
+ print err
+ sys.exit(-1)
- if 'msgtype' in m:
- msg.setPerformative(m['msgtype'])
+ return self.buildACL(m)
- if 'sender' in m:
- msg.setSender(self.processAID(m['sender']))
+ def buildACL(self, m):
+ """
+ returns an ACLMessage object from a pyparsing.ParseResults object
+ """
- if 'receiver' in m:
- recv = m['receiver']
- for i in recv:
- msg.addReceiver(self.processAID(i))
+ #print repr(m)
+ #print m.asXML()
+ #print m.asList()
- if 'content' in m:
- msg.setContent(m['content'])
+ msg = ACLMessage.ACLMessage()
- if 'reply-with' in m:
- msg.setReplyWith(m['reply-with'])
+ if 'msgtype' in m:
+ msg.setPerformative(m['msgtype'])
- if 'reply-by' in m:
- msg.setReplyBy(BasicFipaDateTime(m['reply-by']))
+ if 'sender' in m:
+ msg.setSender(self.processAID(m['sender']))
- if 'in-reply-to' in m:
- msg.setInReplyTo(m['in-reply-to'])
+ if 'receiver' in m:
+ recv = m['receiver']
+ for i in recv:
+ msg.addReceiver(self.processAID(i))
- if 'reply-to' in m:
- r = m['reply-to']
- for i in r:
- msg.AddReplyTo(self.processAID(i))
+ if 'content' in m:
+ msg.setContent(m['content'])
- if 'language' in m:
- msg.setLanguage(m['language'])
+ if 'reply-with' in m:
+ msg.setReplyWith(m['reply-with'])
- if 'encoding' in m:
- msg.setEncoding(m['encoding'])
+ if 'reply-by' in m:
+ msg.setReplyBy(BasicFipaDateTime(m['reply-by']))
- if 'ontology' in m:
- msg.setOntology(m['ontology'])
+ if 'in-reply-to' in m:
+ msg.setInReplyTo(m['in-reply-to'])
- if 'protocol' in m:
- msg.setProtocol(m['protocol'])
+ if 'reply-to' in m:
+ r = m['reply-to']
+ for i in r:
+ msg.AddReplyTo(self.processAID(i))
- if 'conversation-id' in m:
- msg.setConversationId(m['conversation-id'])
+ if 'language' in m:
+ msg.setLanguage(m['language'])
-
- return msg
+ if 'encoding' in m:
+ msg.setEncoding(m['encoding'])
-class ACLxmlParser(handler.ContentHandler):
+ if 'ontology' in m:
+ msg.setOntology(m['ontology'])
- def __init__(self):
+ if 'protocol' in m:
+ msg.setProtocol(m['protocol'])
- #constants
- self.FIPA_MESSAGE_TAG = "fipa-message"
- self.ACT_TAG = "act"
- self.CONVERSATION_ID_TAG = "conversation-id"
- self.SENDER_TAG = "sender"
- self.RECEIVER_TAG = "receiver"
- self.CONTENT_TAG = "content"
- self.LANGUAGE_TAG = "language"
- self.ENCODING_TAG = "encoding"
- self.ONTOLOGY_TAG = "ontology"
- self.PROTOCOL_TAG = "protocol"
- self.REPLY_WITH_TAG = "reply-with"
- self.IN_REPLY_TO_TAG = "in-reply-to"
- self.REPLY_BY_TAG = "reply-by"
- self.REPLY_TO_TAG = "reply-to"
- self.CONVERSATION_ID_TAG = "conversation-id"
- self.AGENT_ID_TAG = "agent-identifier"
- self.NAME_TAG = "name"
- self.ADDRESSES_TAG = "addresses"
- self.URL_TAG = "url"
- self.RESOLVERS_TAG = "resolvers"
- self.USER_DEFINED_TAG = "user-defined"
- self.TIME_TAG = "time"
- self.ID_TAG = "id"
- self.HREF_TAG = "href"
- self.OT = "<"
- self.ET = "</"
- self.CT = ">"
- self.NULL = ""
+ if 'conversation-id' in m:
+ msg.setConversationId(m['conversation-id'])
- """
- ***************************************************
- * Decoding methods *
- ***************************************************
- """
+ return msg
- def startDocument(self):
- self.msg = ACLMessage.ACLMessage()
- def endDocument(self):
- pass
+class ACLxmlParser(handler.ContentHandler):
- #This method is called when exist characters in the elements
- def characters(self, buff):
- self.accumulator = self.accumulator + buff
+ def __init__(self):
- def startElement(self, localName, attributes):
+ #constants
+ self.FIPA_MESSAGE_TAG = "fipa-message"
+ self.ACT_TAG = "act"
+ self.CONVERSATION_ID_TAG = "conversation-id"
+ self.SENDER_TAG = "sender"
+ self.RECEIVER_TAG = "receiver"
+ self.CONTENT_TAG = "content"
+ self.LANGUAGE_TAG = "language"
+ self.ENCODING_TAG = "encoding"
+ self.ONTOLOGY_TAG = "ontology"
+ self.PROTOCOL_TAG = "protocol"
+ self.REPLY_WITH_TAG = "reply-with"
+ self.IN_REPLY_TO_TAG = "in-reply-to"
+ self.REPLY_BY_TAG = "reply-by"
+ self.REPLY_TO_TAG = "reply-to"
+ self.CONVERSATION_ID_TAG = "conversation-id"
+ self.AGENT_ID_TAG = "agent-identifier"
+ self.NAME_TAG = "name"
+ self.ADDRESSES_TAG = "addresses"
+ self.URL_TAG = "url"
+ self.RESOLVERS_TAG = "resolvers"
+ self.USER_DEFINED_TAG = "user-defined"
+ self.TIME_TAG = "time"
+ self.ID_TAG = "id"
+ self.HREF_TAG = "href"
+ self.OT = "<"
+ self.ET = "</"
+ self.CT = ">"
+ self.NULL = ""
- self.accumulator = ""
+ """
+ ***************************************************
+ * Decoding methods *
+ ***************************************************
+ """
- if self.FIPA_MESSAGE_TAG == localName.lower():
- self.msg.setPerformative(attributes.getValue(self.ACT_TAG))
- try:
-
self.msg.setConversationId(attributes.getValue(self.CONVERSATION_ID_TAG))
-
- except:
- pass
+ def startDocument(self):
+ self.msg = ACLMessage.ACLMessage()
- if self.SENDER_TAG == localName.lower():
- self.aid = AID.aid()
- self.aidTag = self.SENDER_TAG
+ def endDocument(self):
+ pass
- if self.RECEIVER_TAG == localName.lower():
- self.aid = AID.aid()
- self.aidTag = self.RECEIVER_TAG
+ #This method is called when exist characters in the elements
+ def characters(self, buff):
+ self.accumulator = self.accumulator + buff
- if self.REPLY_TO_TAG == localName.lower():
- self.aid = AID.aid()
- self.aidTag = self.REPLY_TO_TAG
+ def startElement(self, localName, attributes):
- if self.RESOLVERS_TAG == localName.lower():
- self.aid = AID.aid()
- self.aidTag = self.RESOLVERS_TAG
+ self.accumulator = ""
- if self.REPLY_BY_TAG == localName.lower():
-
self.msg.setReplyBy(BasicFipaDateTime(attributes.getValue(self.TIME_TAG)))
+ if self.FIPA_MESSAGE_TAG == localName.lower():
+ self.msg.setPerformative(attributes.getValue(self.ACT_TAG))
+ try:
+
self.msg.setConversationId(attributes.getValue(self.CONVERSATION_ID_TAG))
- if self.NAME_TAG == localName.lower():
- self.aid.setName(attributes.getValue(self.ID_TAG))
+ except:
+ pass
- if self.URL_TAG == localName.lower():
- self.aid.addAddress(attributes.getValue(self.HREF_TAG))
+ if self.SENDER_TAG == localName.lower():
+ self.aid = AID.aid()
+ self.aidTag = self.SENDER_TAG
+ if self.RECEIVER_TAG == localName.lower():
+ self.aid = AID.aid()
+ self.aidTag = self.RECEIVER_TAG
- def endElement(self, localName):
+ if self.REPLY_TO_TAG == localName.lower():
+ self.aid = AID.aid()
+ self.aidTag = self.REPLY_TO_TAG
- if self.CONTENT_TAG == localName.lower():
- self.msg.setContent(self.accumulator)
+ if self.RESOLVERS_TAG == localName.lower():
+ self.aid = AID.aid()
+ self.aidTag = self.RESOLVERS_TAG
- if self.LANGUAGE_TAG == localName.lower():
- self.msg.setLanguage(self.accumulator)
+ if self.REPLY_BY_TAG == localName.lower():
+
self.msg.setReplyBy(BasicFipaDateTime(attributes.getValue(self.TIME_TAG)))
- if self.ENCODING_TAG == localName.lower():
- self.msg.setEncoding(self.accumulator)
+ if self.NAME_TAG == localName.lower():
+ self.aid.setName(attributes.getValue(self.ID_TAG))
- if self.ONTOLOGY_TAG == localName.lower():
- self.msg.setOntology(self.accumulator)
+ if self.URL_TAG == localName.lower():
+ self.aid.addAddress(attributes.getValue(self.HREF_TAG))
- if self.PROTOCOL_TAG == localName.lower():
- self.msg.setProtocol(self.accumulator)
+ def endElement(self, localName):
- if self.REPLY_WITH_TAG == localName.lower():
- self.msg.setReplyWith(self.accumulator)
+ if self.CONTENT_TAG == localName.lower():
+ self.msg.setContent(self.accumulator)
- if self.IN_REPLY_TO_TAG == localName.lower():
- self.msg.setInReplyTo(self.accumulator)
+ if self.LANGUAGE_TAG == localName.lower():
+ self.msg.setLanguage(self.accumulator)
- if self.REPLY_TO_TAG == localName.lower() or \
- self.SENDER_TAG == localName.lower() or \
- self.RECEIVER_TAG == localName.lower() or \
- self.RESOLVERS_TAG == localName.lower():
- self.aidTag = ""
+ if self.ENCODING_TAG == localName.lower():
+ self.msg.setEncoding(self.accumulator)
- if self.CONVERSATION_ID_TAG == localName.lower():
- self.msg.setConversationId(self.accumulator)
+ if self.ONTOLOGY_TAG == localName.lower():
+ self.msg.setOntology(self.accumulator)
- if self.AGENT_ID_TAG == localName.lower():
- if self.aidTag == self.SENDER_TAG:
- self.msg.setSender(self.aid)
- elif self.aidTag == self.RECEIVER_TAG:
- self.msg.addReceiver(self.aid)
- elif self.aidTag == self.REPLY_TO_TAG:
- self.msg.addReplyTo(self.aid)
- elif self.aidTag == self.RESOLVERS_TAG:
- self.msg.addResolvers(self.aid)
+ if self.PROTOCOL_TAG == localName.lower():
+ self.msg.setProtocol(self.accumulator)
+ if self.REPLY_WITH_TAG == localName.lower():
+ self.msg.setReplyWith(self.accumulator)
- """
- This does the following:
- < tag >
- content
- </ tag >
- """
- def encodeTag( self, tag, content, proptag=None, propcontent=None):
- sb = self.OT + tag
- if proptag != None:
- sb = sb + " " + proptag + '="' + str(propcontent) + '"'
+ if self.IN_REPLY_TO_TAG == localName.lower():
+ self.msg.setInReplyTo(self.accumulator)
- if content == None or content == "":
- sb = sb + "/" + self.CT
- return sb
- sb = sb + self.CT
- sb = sb + content
- sb = sb + self.ET + tag + self.CT
+ if self.REPLY_TO_TAG == localName.lower() or \
+ self.SENDER_TAG == localName.lower() or \
+ self.RECEIVER_TAG == localName.lower() or \
+ self.RESOLVERS_TAG == localName.lower():
+ self.aidTag = ""
- return sb
+ if self.CONVERSATION_ID_TAG == localName.lower():
+ self.msg.setConversationId(self.accumulator)
- """ Encode the information of Agent, Tags To and From """
- def encodeAid(self, aid):
+ if self.AGENT_ID_TAG == localName.lower():
+ if self.aidTag == self.SENDER_TAG:
+ self.msg.setSender(self.aid)
+ elif self.aidTag == self.RECEIVER_TAG:
+ self.msg.addReceiver(self.aid)
+ elif self.aidTag == self.REPLY_TO_TAG:
+ self.msg.addReplyTo(self.aid)
+ elif self.aidTag == self.RESOLVERS_TAG:
+ self.msg.addResolvers(self.aid)
- sb = self.OT + self.AGENT_ID_TAG + self.CT
- sb = sb + self.encodeTag( self.NAME_TAG, None, self.ID_TAG,
aid.getName() )
+ """
+ This does the following:
+ < tag >
+ content
+ </ tag >
+ """
+ def encodeTag(self, tag, content, proptag=None, propcontent=None):
+ sb = self.OT + tag
+ if proptag is not None:
+ sb = sb + " " + proptag + '="' + str(propcontent) + '"'
- sb = sb + self.OT + self.ADDRESSES_TAG + self.CT
- addresses = aid.getAddresses()
- for addr in addresses:
- sb = sb + self.encodeTag( self.URL_TAG, "", self.HREF_TAG, addr )
- sb = sb + self.ET + self.ADDRESSES_TAG + self.CT
+ if content is None or content == "":
+ sb = sb + "/" + self.CT
+ return sb
+ sb = sb + self.CT
+ sb = sb + content
+ sb = sb + self.ET + tag + self.CT
- resolvers = aid.getResolvers()
- if len(resolvers) > 0:
- sb = sb + self.OT + self.RESOLVERS_TAG + self.CT
- for res in resolvers:
- sb = sb + self.encodeAid( res )
- sb = sb + self.ET + self.RESOLVERS_TAG + self.CT
+ return sb
- sb = sb + self.ET + self.AGENT_ID_TAG + self.CT
+ """ Encode the information of Agent, Tags To and From """
+ def encodeAid(self, aid):
- return sb
+ sb = self.OT + self.AGENT_ID_TAG + self.CT
+ sb = sb + self.encodeTag(self.NAME_TAG, None, self.ID_TAG,
aid.getName())
+ sb = sb + self.OT + self.ADDRESSES_TAG + self.CT
+ addresses = aid.getAddresses()
+ for addr in addresses:
+ sb = sb + self.encodeTag(self.URL_TAG, "", self.HREF_TAG, addr)
+ sb = sb + self.ET + self.ADDRESSES_TAG + self.CT
- def encodeXML(self, msg):
+ resolvers = aid.getResolvers()
+ if len(resolvers) > 0:
+ sb = sb + self.OT + self.RESOLVERS_TAG + self.CT
+ for res in resolvers:
+ sb = sb + self.encodeAid(res)
+ sb = sb + self.ET + self.RESOLVERS_TAG + self.CT
- sb = self.OT + self.FIPA_MESSAGE_TAG
- if msg.getPerformative():
- sb += " " + self.ACT_TAG + '="' + msg.getPerformative() + '"'
- sb += self.CT
+ sb = sb + self.ET + self.AGENT_ID_TAG + self.CT
- #sender
- if msg.getSender():
- sb += self.OT + self.SENDER_TAG + self.CT
- sb += self.encodeAid(msg.getSender())
- sb += self.ET + self.SENDER_TAG + self.CT
+ return sb
- #receivers
- if len(msg.getReceivers()) > 0:
- sb += self.OT + self.RECEIVER_TAG + self.CT
- for r in msg.getReceivers():
- sb += self.encodeAid(r)
- sb += self.ET + self.RECEIVER_TAG + self.CT
+ def encodeXML(self, msg):
-
- if msg.getContent():
- sb += self.encodeTag(self.CONTENT_TAG, str(msg.getContent()))
+ sb = self.OT + self.FIPA_MESSAGE_TAG
+ if msg.getPerformative():
+ sb += " " + self.ACT_TAG + '="' + msg.getPerformative() + '"'
+ sb += self.CT
- if msg.getLanguage():
- sb += self.encodeTag(self.LANGUAGE_TAG, msg.getLanguage())
+ #sender
+ if msg.getSender():
+ sb += self.OT + self.SENDER_TAG + self.CT
+ sb += self.encodeAid(msg.getSender())
+ sb += self.ET + self.SENDER_TAG + self.CT
- if msg.getEncoding():
- sb += self.encodeTag(self.ENCODING_TAG, msg.getEncoding())
+ #receivers
+ if len(msg.getReceivers()) > 0:
+ sb += self.OT + self.RECEIVER_TAG + self.CT
+ for r in msg.getReceivers():
+ sb += self.encodeAid(r)
+ sb += self.ET + self.RECEIVER_TAG + self.CT
- if msg.getOntology():
- sb += self.encodeTag(self.ONTOLOGY_TAG, msg.getOntology())
+ if msg.getContent():
+ sb += self.encodeTag(self.CONTENT_TAG, str(msg.getContent()))
- if msg.getProtocol():
- sb += self.encodeTag(self.PROTOCOL_TAG, msg.getProtocol())
+ if msg.getLanguage():
+ sb += self.encodeTag(self.LANGUAGE_TAG, msg.getLanguage())
- if msg.getReplyWith():
- sb += self.encodeTag(self.REPLY_WITH_TAG, msg.getReplyWith())
+ if msg.getEncoding():
+ sb += self.encodeTag(self.ENCODING_TAG, msg.getEncoding())
- if msg.getInReplyTo():
- sb += self.encodeTag(self.IN_REPLY_TO_TAG, msg.getInReplyTo())
+ if msg.getOntology():
+ sb += self.encodeTag(self.ONTOLOGY_TAG, msg.getOntology())
- if msg.getReplyBy():
- date = BasicFipaDateTime()
- date.fromString( str(msg.getReplyBy()) )
- sb += self.encodeTag(self.REPLY_BY_TAG, str(date))
+ if msg.getProtocol():
+ sb += self.encodeTag(self.PROTOCOL_TAG, msg.getProtocol())
- if len(msg.getReplyTo()) > 0:
- sb += self.OT + self.REPLY_TO_TAG + self.CT
- for e in msg.getReplyTo():
- sb += self.encodeAid(e)
- sb += self.ET + self.REPLY_TO_TAG + self.CT
+ if msg.getReplyWith():
+ sb += self.encodeTag(self.REPLY_WITH_TAG, msg.getReplyWith())
- if msg.getConversationId():
- sb += self.encodeTag(self.CONVERSATION_ID_TAG, msg.getConversationId())
+ if msg.getInReplyTo():
+ sb += self.encodeTag(self.IN_REPLY_TO_TAG, msg.getInReplyTo())
- sb += self.ET + self.FIPA_MESSAGE_TAG + self.CT
+ if msg.getReplyBy():
+ date = BasicFipaDateTime()
+ date.fromString(str(msg.getReplyBy()))
+ sb += self.encodeTag(self.REPLY_BY_TAG, str(date))
- return sb
-
+ if len(msg.getReplyTo()) > 0:
+ sb += self.OT + self.REPLY_TO_TAG + self.CT
+ for e in msg.getReplyTo():
***The diff for this file has been truncated for email.***
=======================================
--- /trunk/spade/AID.py Fri Nov 9 09:51:22 2012
+++ /trunk/spade/AID.py Fri Nov 23 05:19:16 2012
@@ -1,293 +1,295 @@
+# -*- coding: utf-8 -*-
from content import ContentObject
import copy
+
class aid:
- def __init__(self, name = None, addresses = None, resolvers = None,
userDefinedProperties= None, co = None):
- """
- Agent Identifier Class
- Optional parameters:
- String name
- String[] addresses
- String[] resolvers
- ContentObject co
- """
- if co:
- self.__name =
co.name
- if "list" in str(type(co.addresses)):
- self.__addresses = copy.copy(co.addresses)
- else:
- self.__addresses = []
- if co.addresses:
- self.__addresses.append(co.addresses)
- if "list" in str(type(co.resolvers)):
- self.__resolvers = copy.copy(co.resolvers)
- else:
- self.__resolvers = []
- if co.resolvers:
- self.__resolvers.append(co.resolvers)
- self.__userDefinedProperties = list()
- return
-
- if name != None:
- self.__name = name
- else:
- self.__name = None #string
- if addresses != None:
- self.__addresses = addresses
- else:
- self.__addresses = list() #string
- if resolvers != None:
- self.__resolvers = resolvers
- else:
- self.__resolvers = list() #aid
- if userDefinedProperties != None:
- self.__userDefinedProperties = userDefinedProperties
- else:
- self.__userDefinedProperties = list() #properties
+ def __init__(self, name=None, addresses=None, resolvers=None,
userDefinedProperties=None, co=None):
+ """
+ Agent Identifier Class
+ Optional parameters:
+ String name
+ String[] addresses
+ String[] resolvers
+ ContentObject co
+ """
+ if co:
+ self.__name =
co.name
+ if "list" in str(type(co.addresses)):
+ self.__addresses = copy.copy(co.addresses)
+ else:
+ self.__addresses = []
+ if co.addresses:
+ self.__addresses.append(co.addresses)
+ if "list" in str(type(co.resolvers)):
+ self.__resolvers = copy.copy(co.resolvers)
+ else:
+ self.__resolvers = []
+ if co.resolvers:
+ self.__resolvers.append(co.resolvers)
+ self.__userDefinedProperties = list()
+ return
- def getName(self):
- """
- returns name of the agent (string)
- """
- return self.__name
+ if name is not None:
+ self.__name = name
+ else:
+ self.__name = None # string
+ if addresses is not None:
+ self.__addresses = addresses
+ else:
+ self.__addresses = list() # string
+ if resolvers is not None:
+ self.__resolvers = resolvers
+ else:
+ self.__resolvers = list() # aid
+ if userDefinedProperties is not None:
+ self.__userDefinedProperties = userDefinedProperties
+ else:
+ self.__userDefinedProperties = list() # properties
- def setName(self,name):
- """
- sets name of the agent (string)
- """
- self.__name = name
+ def getName(self):
+ """
+ returns name of the agent (string)
+ """
+ return self.__name
- def getAddresses(self):
- """
- returns a list of addreses
- """
- return self.__addresses
+ def setName(self, name):
+ """
+ sets name of the agent (string)
+ """
+ self.__name = name
- def addAddress(self,addr):
- """
- adds a new address to the addresses list
- """
- self.__addresses.append(addr)
+ def getAddresses(self):
+ """
+ returns a list of addreses
+ """
+ return self.__addresses
- def getResolvers(self):
- """
- returns a list of resolvers
- """
- return self.__resolvers
+ def addAddress(self, addr):
+ """
+ adds a new address to the addresses list
+ """
+ self.__addresses.append(addr)
- def addResolvers(self,resolver):
- """
- adds a new resolver to the resolvers list
- """
- self.__resolvers.append(resolver)
+ def getResolvers(self):
+ """
+ returns a list of resolvers
+ """
+ return self.__resolvers
- def getProperties(self):
- return self.__userDefinedProperties
+ def addResolvers(self, resolver):
+ """
+ adds a new resolver to the resolvers list
+ """
+ self.__resolvers.append(resolver)
- def addProperty(self,prop):
- self.__userDefinedProperties.append(prop)
+ def getProperties(self):
+ return self.__userDefinedProperties
- def match(self, other):
- """
- returns True if two AIDs are similar
- else returns False
- """
+ def addProperty(self, prop):
+ self.__userDefinedProperties.append(prop)
- if other==None: return True
-
- if (self.getName() != None and other.getName() != None \
- and not (other.getName() in self.getName()) ):
- return False
- if (len(self.getAddresses())>0 and len(other.getAddresses())>0):
- for oaddr in other.getAddresses():
- found=False
- for saddr in self.getAddresses():
- if (oaddr in saddr): found=True
- if not found:
- return False
- if (len(self.getResolvers())>0 and len(other.getResolvers())>0):
- for oaddr in other.getResolvers():
- found=False
- for saddr in self.getResolvers():
- if (oaddr in saddr): found=True
- if not found:
- return False
- if (len(self.getProperties())>0 and len(other.getProperties())>0):
- for oaddr in other.getProperties():
- found=False
- for saddr in self.getProperties():
- if (oaddr in saddr): found=True
- if not found:
- return False
- return True
+ def match(self, other):
+ """
+ returns True if two AIDs are similar
+ else returns False
+ """
+ if other is None:
+ return True
- def __eq__(self, other):
- """
- Comparision operator (==)
- returns True if two AIDs are equal
- else returns False
- """
- if other==None: return False
-
- if (self.getName() != None and other.getName() != None \
- and self.getName() != other.getName()):
- return False
- addr1 = self.getAddresses()
- addr2 = other.getAddresses()
- addr1.sort()
- addr2.sort()
- if addr1 != addr2:
- return False
-
- res1 = self.getResolvers()
- res2 = other.getResolvers()
- res1.sort()
- res2.sort()
- if res1 != res2:
- return False
+ if (self.getName() is not None and other.getName() is not None
+ and not (other.getName() in self.getName())):
+ return False
+ if (len(self.getAddresses()) > 0 and len(other.getAddresses()) >
0):
+ for oaddr in other.getAddresses():
+ found = False
+ for saddr in self.getAddresses():
+ if (oaddr in saddr):
+ found = True
+ if not found:
+ return False
+ if (len(self.getResolvers()) > 0 and len(other.getResolvers()) >
0):
+ for oaddr in other.getResolvers():
+ found = False
+ for saddr in self.getResolvers():
+ if (oaddr in saddr):
+ found = True
+ if not found:
+ return False
+ if (len(self.getProperties()) > 0 and len(other.getProperties()) >
0):
+ for oaddr in other.getProperties():
+ found = False
+ for saddr in self.getProperties():
+ if (oaddr in saddr):
+ found = True
+ if not found:
+ return False
+ return True
- return True
+ def __eq__(self, other):
+ """
+ Comparision operator (==)
+ returns True if two AIDs are equal
+ else returns False
+ """
+ if other is None:
+ return False
- def __ne__(self,other):
- """
- != operator
- returns False if two AIDs are equal
- else returns True
- """
+ if (self.getName() is not None and other.getName() is not None
+ and self.getName() != other.getName()):
+ return False
+ addr1 = self.getAddresses()
+ addr2 = other.getAddresses()
+ addr1.sort()
+ addr2.sort()
+ if addr1 != addr2:
+ return False
- return not (self == other)
+ res1 = self.getResolvers()
+ res2 = other.getResolvers()
+ res1.sort()
+ res2.sort()
+ if res1 != res2:
+ return False
+ return True
- def __hash__(self):
- h = hash(self.__name)
- for i in self.__addresses:
- h = h + hash(i)
- for i in self.__resolvers:
- h = h + hash(i)
- for i in self.__userDefinedProperties:
- h = h + hash(i)
- return h
+ def __ne__(self, other):
+ """
+ != operator
+ returns False if two AIDs are equal
+ else returns True
+ """
- def __str__(self):
- """
- returns a printable version of an AID
- """
- sb = ""
- if self.getName() != None:
- sb = sb + ":name " + str(self.getName()) + "\n"
- if self.getAddresses() != []:
- sb = sb + ":addresses \n(sequence\n"
- for i in self.getAddresses():
- sb = sb + str(i) + '\n'
- sb = sb + ")\n"
- if self.getResolvers() != []:
- sb = sb + ":resolvers \n(sequence\n"
- for i in self.getResolvers():
- sb = sb + str(i) + '\n'
- sb = sb + ")\n"
- if sb != "":
- sb = "(agent-identifier\n" + sb + ")\n"
- else:
- sb = "None"
+ return not (self == other)
- return sb
-
- def asContentObject(self):
- """
- returns a version of an AID in ContentObject format
- """
- co = ContentObject()
- co["name"] = self.getName()
- if self.getAddresses()!=[]:
- co["addresses"] = []
- for addr in self.getAddresses():
- co["addresses"].append(addr)
- if self.getResolvers()!=[]:
- co["resolvers"] = []
- for r in self.getResolvers():
- co["resolvers"].append(r)
- if self.getProperties()!=[]:
- co["properties"] = []
- for p in self.getProperties():
- co["properties"].append(p)
- return co
+ def __hash__(self):
+ h = hash(self.__name)
+ for i in self.__addresses:
+ h = h + hash(i)
+ for i in self.__resolvers:
+ h = h + hash(i)
+ for i in self.__userDefinedProperties:
+ h = h + hash(i)
+ return h
- def asJSON(self):
- """
- returns a version of an AID in JSON format
- """
- import json
- return json.dumps(self.asContentObject())
+ def __str__(self):
+ """
+ returns a printable version of an AID
+ """
+ sb = ""
+ if self.getName() is not None:
+ sb = sb + ":name " + str(self.getName()) + "\n"
+ if self.getAddresses() != []:
+ sb = sb + ":addresses \n(sequence\n"
+ for i in self.getAddresses():
+ sb = sb + str(i) + '\n'
+ sb = sb + ")\n"
+ if self.getResolvers() != []:
+ sb = sb + ":resolvers \n(sequence\n"
+ for i in self.getResolvers():
+ sb = sb + str(i) + '\n'
+ sb = sb + ")\n"
+ if sb != "":
+ sb = "(agent-identifier\n" + sb + ")\n"
+ else:
+ sb = "None"
- def asXML(self):
- """
- returns a printable version of an AID in XML
- """
- sb = "<agent-identifier>\n\t" + self.encodeTag( "name", self.getName() )
+ "\n"
- sb = sb + "\t<addresses>\n"
+ return sb
- addresses = self.getAddresses()
- for addr in addresses:
- sb = sb + "\t\t" + self.encodeTag( "url", addr ) + "\n"
+ def asContentObject(self):
+ """
+ returns a version of an AID in ContentObject format
+ """
+ co = ContentObject()
+ co["name"] = self.getName()
+ if self.getAddresses() != []:
+ co["addresses"] = []
+ for addr in self.getAddresses():
+ co["addresses"].append(addr)
+ if self.getResolvers() != []:
+ co["resolvers"] = []
+ for r in self.getResolvers():
+ co["resolvers"].append(r)
+ if self.getProperties() != []:
+ co["properties"] = []
+ for p in self.getProperties():
+ co["properties"].append(p)
+ return co
- sb = sb + "\t</addresses>\n"
-
- sb = sb + "</agent-identifier>\n"
+ def asJSON(self):
+ """
+ returns a version of an AID in JSON format
+ """
+ import json
+ return json.dumps(self.asContentObject())
- return sb
+ def asXML(self):
+ """
+ returns a printable version of an AID in XML
+ """
+ sb = "<agent-identifier>\n\t" + self.encodeTag("name",
self.getName()) + "\n"
+ sb = sb + "\t<addresses>\n"
- def encodeTag( self, tag, content ):
- """
- encodes a content between 2 XML tags using the tag parameter
+ addresses = self.getAddresses()
+ for addr in addresses:
+ sb = sb + "\t\t" + self.encodeTag("url", addr) + "\n"
- <tag>content</tag>
+ sb = sb + "\t</addresses>\n"
- return string
- """
- sb = "<" + tag + ">" + content + "</" + tag + ">"
+ sb = sb + "</agent-identifier>\n"
- return sb
+ return sb
+ def encodeTag(self, tag, content):
+ """
+ encodes a content between 2 XML tags using the tag parameter
- def loadSL0(self, content):
- """
- initialices an AID class using a string content encoded in SLO
- """
+ <tag>content</tag>
- if "agent-identifier" in content:
- if "name" in content["agent-identifier"]:
- self.setName(content["agent-identifier"].name[0])
- else:
- return -1
+ return string
+ """
+ sb = "<" + tag + ">" + content + "</" + tag + ">"
- if "addresses" in content["agent-identifier"]:
- for addr in content["agent-identifier"].addresses.sequence:
- self.addAddress(addr)#[0])
+ return sb
- if "resolvers" in content["agent-identifier"]:
- for res in content["agent-identifier"].resolvers.sequence:
- self.addResolvers(res)#[0]))
+ def loadSL0(self, content):
+ """
+ initialices an AID class using a string content encoded in SLO
+ """
- else: return -1
+ if "agent-identifier" in content:
+ if "name" in content["agent-identifier"]:
+ self.setName(content["agent-identifier"].name[0])
+ else:
+ return -1
- def loadJSON(self, content):
- """
- initialices an AID class using a JSON string
- """
+ if "addresses" in content["agent-identifier"]:
+ for addr in content["agent-identifier"].addresses.sequence:
+ self.addAddress(addr) # [0])
- if content.has_key("name"):
- self.setName(content["name"])
- else:
- return -1
+ if "resolvers" in content["agent-identifier"]:
+ for res in content["agent-identifier"].resolvers.sequence:
+ self.addResolvers(res) # [0]))
- if content.has_key("addresses"):
- for addr in content["addresses"]:
- self.addAddress(addr)
+ else:
+ return -1
- if content.has_key("resolvers"):
- for res in content["resolvers"]:
- self.addResolvers(res)
+ def loadJSON(self, content):
+ """
+ initialices an AID class using a JSON string
+ """
+ if "name" in content:
+ self.setName(content["name"])
+ else:
+ return -1
+ if "addresses" in content:
+ for addr in content["addresses"]:
+ self.addAddress(addr)
+ if "resolvers" in content:
+ for res in content["resolvers"]:
+ self.addResolvers(res)
=======================================
--- /trunk/spade/AMS.py Tue Jul 10 16:56:02 2012
+++ /trunk/spade/AMS.py Fri Nov 23 05:19:16 2012
@@ -1,4 +1,4 @@
-# encoding: UTF-8
+# -*- coding: utf-8 -*-
from Agent import PlatformAgent
import AID
@@ -11,768 +11,755 @@
from spade.msgtypes import *
from content import ContentObject
+
class AMS(PlatformAgent):
- """
- Agent Management System
- """
+ """
+ Agent Management System
+ """
- class DefaultBehaviour(Behaviour.Behaviour):
- def __init__(self):
- Behaviour.Behaviour.__init__(self)
- self.sl0parser = SL0Parser()
+ class DefaultBehaviour(Behaviour.Behaviour):
+ def __init__(self):
+ Behaviour.Behaviour.__init__(self)
+ self.sl0parser = SL0Parser()
- def onStart(self):
- self.myAgent.addBehaviour(self.SubscribeBehaviour(),
Behaviour.MessageTemplate(xmpp.Presence()))
+ def onStart(self):
+ self.myAgent.addBehaviour(self.SubscribeBehaviour(),
Behaviour.MessageTemplate(xmpp.Presence()))
-# t = Behaviour.PresenceTemplate(type="subscribed")
-# self.registerPresenceHandler(t, self.subscribedCB)
-# t = Behaviour.PresenceTemplate(type="unsubscribed")
-# tt = Behaviour.PresenceTemplate(type="unavailable")
-# self.registerPresenceHandler(t, self.unsubscribedCB)
-# self.registerPresenceHandler(tt, self.unsubscribedCB)
-# t = Behaviour.PresenceTemplate(type="subscribe")
-# self.registerPresenceHandler(t, self.subscribeCB)
+ #t = Behaviour.PresenceTemplate(type="subscribed")
+ #self.registerPresenceHandler(t, self.subscribedCB)
+ #t = Behaviour.PresenceTemplate(type="unsubscribed")
+ #tt = Behaviour.PresenceTemplate(type="unavailable")
+ #self.registerPresenceHandler(t, self.unsubscribedCB)
+ #self.registerPresenceHandler(tt, self.unsubscribedCB)
+ #t = Behaviour.PresenceTemplate(type="subscribe")
+ #self.registerPresenceHandler(t, self.subscribeCB)
- class SubscribeBehaviour(Behaviour.Behaviour):
- def _process(self):
- msg = None
- msg = self._receive(block=True)
- if msg:
- self.myAgent.DEBUG("AMS received presence message "+ str(msg),"info")
- typ = msg.getType()
- frm = msg.getFrom()
- status = msg.getStatus()
- show = msg.getShow()
- reply_address = frm
- if typ == "subscribe":
- frm=AID.aid(name=str(frm), addresses=["xmpp://"+str(frm)])
- aad = AmsAgentDescription()
-
aad.name = frm
- if status: aad.state = status
- if show: aad.ownership = show
- else: aad.ownership = frm.getName()
+ class SubscribeBehaviour(Behaviour.Behaviour):
+ def _process(self):
+ msg = None
+ msg = self._receive(block=True)
+ if msg:
+ #self.myAgent.DEBUG("AMS received presence message "+
str(msg),"info", "ams")
+ typ = msg.getType()
+ frm = msg.getFrom()
+ status = msg.getStatus()
+ show = msg.getShow()
+ reply_address = frm
+ if typ == "subscribe":
+ frm = AID.aid(name=str(frm), addresses=["xmpp://"
+ str(frm)])
+ aad = AmsAgentDescription()
+
aad.name = frm
+ if status:
+ aad.state = status
+ if show:
+ aad.ownership = show
+ else:
+ aad.ownership = frm.getName()
- if not self.myAgent.agentdb.has_key(frm.getName()):
- self.myAgent.agentdb[frm.getName()] = aad
- elif self.myAgent.agentdb[frm.getName()].getOwnership() ==
aad.getOwnership():
- self.myAgent.agentdb[frm.getName()] = aad
- else:
- presence =
xmpp.Presence(reply_address,typ="unsubscribed",xmlns=xmpp.NS_CLIENT)
- presence.setFrom(self.myAgent.JID)
- self.myAgent.send(presence)
- return
+ if frm.getName() not in
self.myAgent.agentdb.keys():
+ self.myAgent.agentdb[frm.getName()] = aad
+ elif
self.myAgent.agentdb[frm.getName()].getOwnership() == aad.getOwnership():
+ self.myAgent.agentdb[frm.getName()] = aad
+ else:
+ presence = xmpp.Presence(reply_address,
typ="unsubscribed", xmlns=xmpp.NS_CLIENT)
+ presence.setFrom(self.myAgent.JID)
+ self.myAgent.send(presence)
+ return
- self.myAgent.DEBUG("AMS succesfully registered agent " +
frm.getName(),"ok")
- presence = xmpp.Presence(reply_address,typ="subscribed")
- presence.setFrom(self.myAgent.JID)
- self.myAgent.DEBUG("AMS sends "+str(presence),"info")
- self.myAgent.send(presence)
- elif typ == "unsubscribe":
- if self.myAgent.agentdb.has_key(str(frm)):
- del self.myAgent.agentdb[str(frm)]
- self.myAgent.DEBUG("Agent " + str(frm) + " deregistered from
AMS","ok")
- else:
- self.myAgent.DEBUG("Agent " + str(frm) + " deregistered from
AMS","error")
- return
+ self.myAgent.DEBUG("AMS succesfully registered
agent " + frm.getName(), "ok", "ams")
+ presence = xmpp.Presence(reply_address,
typ="subscribed")
+ presence.setFrom(self.myAgent.JID)
+ self.myAgent.DEBUG("AMS sends " +
str(presence), "info")
+ self.myAgent.send(presence)
+ elif typ == "unsubscribe":
+ if str(frm) in self.myAgent.agentdb.keys():
+ del self.myAgent.agentdb[str(frm)]
+ self.myAgent.DEBUG("Agent " + str(frm) + "
deregistered from AMS", "ok", "ams")
+ else:
+ self.myAgent.DEBUG("Agent " + str(frm) + "
deregistered from AMS", "error", "ams")
+ return
+ def _process(self):
+ error = False
+ msg = self._receive(True)
+ if msg is not None:
+ self.myAgent.DEBUG("AMS received message " +
str(msg), "info", "ams")
+ if msg.getPerformative().lower() == 'request':
+ if msg.getOntology() and msg.getOntology().lower()
== "fipa-agent-management":
+ if msg.getLanguage().lower() == "fipa-sl0":
+ content =
self.sl0parser.parse(msg.getContent())
+ ACLtemplate = Behaviour.ACLTemplate()
+
ACLtemplate.setConversationId(msg.getConversationId())
+ ACLtemplate.setSender(msg.getSender())
+ template =
(Behaviour.MessageTemplate(ACLtemplate))
- def _process(self):
- error = False
- msg = self._receive(True)
- if msg != None:
- if msg.getPerformative().lower() == 'request':
- if msg.getOntology() and msg.getOntology().lower()
== "fipa-agent-management":
- if msg.getLanguage().lower() == "fipa-sl0":
- content = self.sl0parser.parse(msg.getContent())
- ACLtemplate = Behaviour.ACLTemplate()
- ACLtemplate.setConversationId(msg.getConversationId())
- ACLtemplate.setSender(msg.getSender())
- template = (Behaviour.MessageTemplate(ACLtemplate))
+ if "action" in content:
+ self.myAgent.DEBUG("AMS: " +
str(content.action) + " request. " + str(content), "info", "ams")
+ if "register" in content.action \
+ or "deregister" in content.action:
+
self.myAgent.addBehaviour(AMS.RegisterBehaviour(msg, content), template)
+ elif "get-description" in content.action:
+
self.myAgent.addBehaviour(AMS.PlatformBehaviour(msg, content), template)
+ elif "search" in content.action:
+
self.myAgent.addBehaviour(AMS.SearchBehaviour(msg, content), template)
+ elif "modify" in content.action:
+
self.myAgent.addBehaviour(AMS.ModifyBehaviour(msg, content), template)
+ else:
+ reply = msg.createReply()
+ reply.setSender(self.myAgent.getAID())
+ reply.setPerformative("refuse")
+ reply.setContent("( " + msg.getContent()
+ "(unsuported-function " + content.keys()[0] + "))")
+ self.myAgent.send(reply)
- if "action" in content:
- self.myAgent.DEBUG("AMS: "+str(content.action)+ " request. " +
str(content),"info")
- if "register" in content.action \
- or "deregister" in content.action:
- self.myAgent.addBehaviour(AMS.RegisterBehaviour(msg,content),
template)
- elif "get-description" in content.action:
- self.myAgent.addBehaviour(AMS.PlatformBehaviour(msg,content),
template)
- elif "search" in content.action:
- self.myAgent.addBehaviour(AMS.SearchBehaviour(msg,content),
template)
- elif "modify" in content.action:
- self.myAgent.addBehaviour(AMS.ModifyBehaviour(msg,content),
template)
- else:
- reply = msg.createReply()
- reply.setSender(self.myAgent.getAID())
- reply.setPerformative("refuse")
- reply.setContent("( "+msg.getContent() +"(unsuported-function "+
content.keys()[0] +"))")
- self.myAgent.send(reply)
+ return -1
- return -1
+ elif msg.getLanguage().lower() == "rdf":
+ # Content in RDF
+ co = msg.getContentObject()
+ content = msg.getContent()
+ ACLtemplate = Behaviour.ACLTemplate()
+
ACLtemplate.setConversationId(msg.getConversationId())
+ ACLtemplate.setSender(msg.getSender())
+ template =
(Behaviour.MessageTemplate(ACLtemplate))
- elif msg.getLanguage().lower() == "rdf":
- # Content in RDF
- co = msg.getContentObject()
- content = msg.getContent()
- ACLtemplate = Behaviour.ACLTemplate()
- ACLtemplate.setConversationId(msg.getConversationId())
- ACLtemplate.setSender(msg.getSender())
- template = (Behaviour.MessageTemplate(ACLtemplate))
-
- if co.has_key("fipa:action") and
co["fipa:action"].has_key("fipa:act"):
- self.myAgent.DEBUG("AMS: "+str(co["fipa:action"]["fipa:act"])+ "
request. " + str(co.asRDFXML()),"info")
- if co["fipa:action"]["fipa:act"] in ["register","deregister"]:
- self.myAgent.addBehaviour(AMS.RegisterBehaviour(msg,content),
template)
- elif co["fipa:action"]["fipa:act"] == "get-description":
- self.myAgent.addBehaviour(AMS.PlatformBehaviour(msg,content),
template)
- elif co["fipa:action"]["fipa:act"] == "search":
- self.myAgent.addBehaviour(AMS.SearchBehaviour(msg,content),
template)
- elif co["fipa:action"]["fipa:act"] == "modify":
- self.myAgent.addBehaviour(AMS.ModifyBehaviour(msg,content),
template)
- else:
- reply = msg.createReply()
- reply.setSender(self.myAgent.getAID())
- reply.setPerformative("refuse")
- co["unsuported-function"] = "true"
- reply.setContentObject(co)
- self.myAgent.send(reply)
- return -1
+ if "fipa:action" in co.keys() and "fipa:act"
in co["fipa:action"].keys():
+ self.myAgent.DEBUG("AMS: " +
str(co["fipa:action"]["fipa:act"]) + " request. " +
str(co.asRDFXML()), "info", "ams")
+ if co["fipa:action"]["fipa:act"] in
["register", "deregister"]:
+
self.myAgent.addBehaviour(AMS.RegisterBehaviour(msg, content), template)
+ elif co["fipa:action"]["fipa:act"]
== "get-description":
+
self.myAgent.addBehaviour(AMS.PlatformBehaviour(msg, content), template)
+ elif co["fipa:action"]["fipa:act"]
== "search":
+
self.myAgent.addBehaviour(AMS.SearchBehaviour(msg, content), template)
+ elif co["fipa:action"]["fipa:act"]
== "modify":
+
self.myAgent.addBehaviour(AMS.ModifyBehaviour(msg, content), template)
+ else:
+ reply = msg.createReply()
+ reply.setSender(self.myAgent.getAID())
+ reply.setPerformative("refuse")
+ co["unsuported-function"] = "true"
+ reply.setContentObject(co)
+ self.myAgent.send(reply)
+ return -1
+ else:
+ error = "(unsupported-language " +
msg.getLanguage() + ")"
+ else:
+ error = "(unsupported-ontology " +
msg.getOntology() + ")"
+ # By adding 'not-understood' to the following list of
unsupported acts, we prevent an
+ # infinite loop of counter-answers between the AMS and the
registering agents
+ elif msg.getPerformative().lower() not in
['failure', 'refuse', 'not-understood']:
+ error = "(unsupported-act " +
msg.getPerformative() + ")"
+ if error:
+ reply = msg.createReply()
+ reply.setSender(self.myAgent.getAID())
+ reply.setPerformative("not-understood")
+ reply.setContent("( " + msg.getContent() + error + ")")
+ self.myAgent.send(reply)
+ return -1
- else: error = "(unsupported-language "+msg.getLanguage()+")"
- else: error = "(unsupported-ontology "+msg.getOntology()+")"
+ return 1
+ class RegisterBehaviour(Behaviour.OneShotBehaviour):
- # By adding 'not-understood' to the following list of unsupported
acts, we prevent an
- # infinite loop of counter-answers between the AMS and the registering
agents
- elif msg.getPerformative().lower() not in
['failure','refuse','not-understood']:
- error = "(unsupported-act " + msg.getPerformative() + ")"
- if error:
- reply = msg.createReply()
- reply.setSender(self.myAgent.getAID())
- reply.setPerformative("not-understood")
- reply.setContent("( "+msg.getContent() + error+")")
- self.myAgent.send(reply)
- return -1
+ def __init__(self, msg, content):
+ Behaviour.OneShotBehaviour.__init__(self)
+ self.msg = msg
+ self.content = content
+ def _process(self):
- return 1
+ #The AMS agrees and then informs dummy of the successful
execution of the action
+ error = False
- class RegisterBehaviour(Behaviour.OneShotBehaviour):
+ try:
+ if "register" in self.content.action:
+ aad =
AmsAgentDescription(self.content.action.register['ams-agent-description'])
+ else:
+ aad =
AmsAgentDescription(self.content.action.deregister['ams-agent-description'])
+ except KeyError: # Exception,err:
+ error = "(missing-argument ams-agent-description)"
- def __init__(self,msg,content):
- Behaviour.OneShotBehaviour.__init__(self)
- self.msg = msg
- self.content = content
+ if error:
+ reply = self.msg.createReply()
+ reply.setSender(self.myAgent.getAID())
+ reply.setPerformative("refuse")
+ reply.setContent("( " + self.msg.getContent() + error
+ ")")
+ self.myAgent.send(reply)
- def _process(self):
+ return -1
- #The AMS agrees and then informs dummy of the successful execution of
the action
- error = False
+ else:
+ reply = self.msg.createReply()
+ reply.setSender(self.myAgent.getAID())
+ reply.setPerformative("agree")
+ reply.setContent("(" + str(self.msg.getContent()) + "
true)")
+ self.myAgent.send(reply)
- try:
- if "register" in self.content.action:
- aad =
AmsAgentDescription(self.content.action.register['ams-agent-description'])
- else:
- aad =
AmsAgentDescription(self.content.action.deregister['ams-agent-description'])
- except KeyError: #Exception,err:
- error = "(missing-argument ams-agent-description)"
+ if "register" in self.content.action:
+ if aad.getAID().getName() not in
self.myAgent.agentdb.keys():
+ try:
+ self.myAgent.agentdb[aad.getAID().getName()] = aad
+ except Exception, err:
+ reply.setPerformative("failure")
+ reply.setContent("(" + self.msg.getContent()
+ "(internal-error))")
+ self.myAgent.send(reply)
+ return -1
- if error:
- reply = self.msg.createReply()
- reply.setSender(self.myAgent.getAID())
- reply.setPerformative("refuse")
- reply.setContent("( "+self.msg.getContent() + error + ")")
- self.myAgent.send(reply)
+ reply.setPerformative("inform")
+ reply.setContent("(done " + self.msg.getContent()
+ ")")
+ self.myAgent.send(reply)
- return -1
+ return 1
- else:
- reply = self.msg.createReply()
- reply.setSender(self.myAgent.getAID())
- reply.setPerformative("agree")
- reply.setContent("(" + str(self.msg.getContent()) + " true)")
- self.myAgent.send(reply)
+ else:
+ reply.setPerformative("failure")
+ reply.setContent("(" + self.msg.getContent()
+ "(already-registered))")
+ self.myAgent.send(reply)
+ return -1
+ elif "deregister" in self.content.action:
+ if aad.getAID().getName() in self.myAgent.agentdb.keys():
+ try:
+ del self.myAgent.agentdb[aad.getAID().getName()]
+ except Exception, err:
+ reply.setPerformative("failure")
+ reply.setContent("(" + self.msg.getContent()
+ '(internal-error "could not deregister agent"))')
+ self.myAgent.send(reply)
+ return -1
+ reply.setPerformative("inform")
+ reply.setContent("(done " + self.msg.getContent()
+ ")")
+ self.myAgent.send(reply)
- if "register" in self.content.action:
- if not self.myAgent.agentdb.has_key(aad.getAID().getName()):
+ return 1
- try:
- self.myAgent.agentdb[aad.getAID().getName()] = aad
- except Exception, err:
- reply.setPerformative("failure")
- reply.setContent("("+self.msg.getContent() + "(internal-error))")
- self.myAgent.send(reply)
- return -1
+ else:
+ reply.setPerformative("failure")
+ reply.setContent("(" + self.msg.getContent()
+ "(not-registered))")
+ self.myAgent.send(reply)
+ return -1
+ class PlatformBehaviour(Behaviour.OneShotBehaviour):
+ def __init__(self, msg, content):
+ Behaviour.OneShotBehaviour.__init__(self)
+ self.msg = msg
+ self.content = content
- reply.setPerformative("inform")
- reply.setContent("(done "+self.msg.getContent() + ")")
- self.myAgent.send(reply)
+ def _process(self):
+ # Create an AGREE reply
+ reply = self.msg.createReply()
+ reply.setSender(self.myAgent.getAID())
+ reply.setPerformative("agree")
- return 1
+ if "rdf" in self.msg.getLanguage().lower():
+ # The content language is RDF
+ rdf = True
+ co = self.msg.getContentObject()
+ co["fipa:done"] = "true"
+ reply.setContentObject(co)
+ else:
+ rdf = False
+ reply.setContent("(" + str(self.msg.getContent()) + "
true)")
- else:
- reply.setPerformative("failure")
- reply.setContent("("+self.msg.getContent() + "(already-registered))")
- self.myAgent.send(reply)
- return -1
+ # Send the AGREE reply
+ self.myAgent.send(reply)
- elif "deregister" in self.content.action:
+ # Set up the content of the actual reply
+ if rdf:
+ co_rep = ContentObject()
+ co_rep["ap-description"] = ContentObject()
+ co_rep["ap-description"]["name"] = "xmpp://" +
self.myAgent.getSpadePlatformJID()
+ co_rep["ap-description"]["ap-services"] = []
+ co_serv = ContentObject()
+ co_serv["ap-service"] = ContentObject()
+ co_serv["ap-service"]["name"] = "xmpp://" +
str(self.myAgent.getAMS().getName())
+ co_serv["ap-service"]["type"] = "fipa.agent-management.ams"
+ co_serv["ap-service"]["addresses"] = []
+
co_serv["ap-service"]["addresses"].append(self.myAgent.getSpadePlatformJID())
+ co_rep["ap-description"]["ap-services"].append(co_serv)
+ reply.setContentObject(co_rep)
+ else:
+ # Write the content in old ugly SL0
+ content = "(ap-description :name xmpp://" +
self.myAgent.getSpadePlatformJID() + " :ap-services (set "
- if self.myAgent.agentdb.has_key(aad.getAID().getName()):
- try:
- del self.myAgent.agentdb[aad.getAID().getName()]
- except Exception, err:
- reply.setPerformative("failure")
- reply.setContent("("+self.msg.getContent() + '(internal-error "could
not deregister agent"))')
- self.myAgent.send(reply)
- return -1
+ #TODO access the platform name and offered services (df,
ams, etc...)
+ """
+ for s in "TODO_SERVICES":
+ content += "(ap-service :name " +
s.name
+ content += " :type " + s.type
+ content += " :addresses (sequence "
+ for ad in s.addresses:
+ content += ad + " "
+ content += "))"
+ """
+ content += "(ap-service :name xmpp://" +
str(self.myAgent.getAMS().getName())
+ content += " :type fipa.agent-management.ams " # TODO
+ content += " :addresses (sequence " +
str(self.myAgent.getSpadePlatformJID()) + ")"
+ content + " ) )"
+ content += ")"
+ reply.setContent(content)
- reply.setPerformative("inform")
- reply.setContent("(done "+self.msg.getContent() + ")")
- self.myAgent.send(reply)
+ # Send the actual INFORM reply
+ reply.setPerformative("inform")
+ self.myAgent.send(reply)
- return 1
+ return 1
- else:
- reply.setPerformative("failure")
- reply.setContent("("+self.msg.getContent() + "(not-registered))")
- self.myAgent.send(reply)
- return -1
+ class SearchBehaviour(Behaviour.OneShotBehaviour):
- class PlatformBehaviour(Behaviour.OneShotBehaviour):
+ def __init__(self, msg, content):
+ Behaviour.OneShotBehaviour.__init__(self)
+ self.msg = msg
+ self.content = content
- def __init__(self,msg,content):
- Behaviour.OneShotBehaviour.__init__(self)
- self.msg = msg
- self.content = content
+ def _process(self):
- def _process(self):
- # Create an AGREE reply
- reply = self.msg.createReply()
- reply.setSender(self.myAgent.getAID())
- reply.setPerformative("agree")
+ error = False
+ rdf = True
+ max = 1000
- if "rdf" in self.msg.getLanguage().lower():
- # The content language is RDF
- rdf = True
- co = self.msg.getContentObject()
- co["fipa:done"] = "true"
- reply.setContentObject(co)
- else:
- rdf = False
- reply.setContent("(" + str(self.msg.getContent()) + " true)")
+ reply = self.msg.createReply()
+ reply.setSender(self.myAgent.getAID())
+ reply.setPerformative("agree")
- # Send the AGREE reply
- self.myAgent.send(reply)
+ if "rdf" in self.msg.getLanguage().lower():
+ rdf = True
+ co = self.msg.getContentObject()
+ co["fipa:done"] = "true"
+ reply.setContentObject(co)
- # Set up the content of the actual reply
- if rdf:
- co_rep = ContentObject()
- co_rep["ap-description"] = ContentObject()
- co_rep["ap-description"]["name"]
= "xmpp://"+self.myAgent.getSpadePlatformJID()
- co_rep["ap-description"]["ap-services"] = []
- co_serv = ContentObject()
- co_serv["ap-service"] = ContentObject()
- co_serv["ap-service"]["name"] = "xmpp://" +
str(self.myAgent.getAMS().getName())
- co_serv["ap-service"]["type"] = "fipa.agent-management.ams"
- co_serv["ap-service"]["addresses"] = []
-
co_serv["ap-service"]["addresses"].append(self.myAgent.getSpadePlatformJID())
- co_rep["ap-description"]["ap-services"].append(co_serv)
- reply.setContentObject(co_rep)
- else:
- # Write the content in old ugly SL0
- content = "(ap-description :name
xmpp://"+self.myAgent.getSpadePlatformJID()+ " :ap-services (set "
+ else:
+ # Old ugly SL0
+ rdf = False
+ reply.setContent("(" + str(self.msg.getContent()) + "
true)")
- #TODO acceso al nombre de la plataforma y los servicios ofertados (df,
ams, etc...)
- """
- for s in "TODO_SERVICES":
- content += "(ap-service :name " +
s.name
- content += " :type " + s.type
- content += " :addresses (sequence "
- for ad in s.addresses:
- content += ad + " "
- content += "))"
- """
+ self.myAgent.send(reply)
- content += "(ap-service :name xmpp://"+
str(self.myAgent.getAMS().getName())
- content += " :type fipa.agent-management.ams " #TODO
- content += " :addresses (sequence " +
str(self.myAgent.getSpadePlatformJID()) + ")"
- content + " ) )"
+ if not rdf:
+ if "search-constraints" in self.content.action.search:
+ if "max-results" in
self.content.action.search["search-constraints"]:
+ try:
+ max =
int(self.content.action.search["search-constraints"]["max-results"])
+ except Exception, err:
+ error = '(internal-error "max-results is not
an integer")'
+ if error:
+ reply = self.msg.createReply()
+ reply.setSender(self.myAgent.getAID())
+ reply.setPerformative("failure")
+ reply.setContent("( " + self.msg.getContent() + error
+ ")")
+ self.myAgent.send(reply)
+ return -1
- content += ")"
- reply.setContent(content)
+ result = []
+ if "ams-agent-description" in self.content.action.search:
+ aad =
AmsAgentDescription(self.content.action.search['ams-agent-description'])
+ for a in self.myAgent.agentdb.values():
+ if max >= 0:
+ if a.match(aad):
+ result.append(a)
+ max -= 1
+ else:
+ break
- # Send the actual INFORM reply
- reply.setPerformative("inform")
- self.myAgent.send(reply)
+ else:
+ result = self.myAgent.agentdb.values()
- return 1
+ content = "((result " # TODO: + self.msg.getContent()
+ if len(result) > 0:
+ content += " (set "
+ for i in result:
+ content += str(i) + " "
+ content += ")"
+ else:
+ content += 'None'
+ content += "))"
- class SearchBehaviour(Behaviour.OneShotBehaviour):
+ reply.setContent(content)
- def __init__(self,msg,content):
- Behaviour.OneShotBehaviour.__init__(self)
- self.msg = msg
- self.content = content
+ else:
+ # The RDF way of things, baby
+ # Delete done (from previous reply)
+ del co["fipa:done"]
+ # Look for search constraints
+ if "constraints" in co["fipa:action"].keys():
+ try:
+ max = int(co["fipa:action"]["constraints"])
+ except:
+ error = 'constraints-error'
+ if error:
+ reply = self.msg.createReply()
+ reply.setSender(self.myAgent.getAID())
+ reply.setPerformative("failure")
+ co["fipa:error"] = error
+ reply.setContentObject(co)
+ self.myAgent.send(reply)
+ return -1
- def _process(self):
+ #Â Search for the results
+ result = []
+ if "fipa:argument" in co["fipa:action"].keys() and
co["fipa:action"]["fipa:argument"]:
+ aad =
AmsAgentDescription(co=co["fipa:action"]["fipa:argument"])
+ for a in self.myAgent.agentdb.values():
+ if max >= 0:
+ if a.match(aad):
+ result.append(a)
+ max -= 1
+ else:
+ break
+ else:
+ result = self.myAgent.agentdb.values()
- error = False
- rdf = True
- max = 1000
+ co2 =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
+ co2["fipa:result"] = []
+ for i in result:
+ co2["fipa:result"].append(i.asContentObject())
+ reply.setContentObject(co2)
- reply = self.msg.createReply()
- reply.setSender(self.myAgent.getAID())
- reply.setPerformative("agree")
+ reply.setPerformative("inform")
+ self.myAgent.send(reply)
- if "rdf" in self.msg.getLanguage().lower():
- rdf = True
- co = self.msg.getContentObject()
- co["fipa:done"] = "true"
- reply.setContentObject(co)
+ return 1
- else:
- # Old ugly SL0
- rdf = False
- reply.setContent("(" + str(self.msg.getContent()) + " true)")
+ class ModifyBehaviour(Behaviour.OneShotBehaviour):
- self.myAgent.send(reply)
+ def __init__(self, msg, content):
+ Behaviour.OneShotBehaviour.__init__(self)
+ self.msg = msg
+ self.content = content
- if not rdf:
- if "search-constraints" in self.content.action.search:
- if "max-results" in self.content.action.search["search-constraints"]:
- try:
- max =
int(self.content.action.search["search-constraints"]["max-results"])
- except Exception, err:
- error = '(internal-error "max-results is not an integer")'
- if error:
- reply = self.msg.createReply()
- reply.setSender(self.myAgent.getAID())
- reply.setPerformative("failure")
- reply.setContent("( "+self.msg.getContent() + error+")")
- self.myAgent.send(reply)
- return -1
+ def _process(self):
+ #The AMS agrees and then informs dummy of the successful
execution of the action
+ error = False
+ aad = None
+ if "rdf" in self.msg.getLanguage().lower():
+ rdf = True
+ else:
+ # Old ugly SL0
+ rdf = False
- result = []
- if "ams-agent-description" in self.content.action.search:
- aad =
AmsAgentDescription(self.content.action.search['ams-agent-description'])
- for a in self.myAgent.agentdb.values():
- if max >= 0:
- if a.match(aad):
- result.append(a)
- max -= 1
- else: break
+ if not rdf:
- else:
- result = self.myAgent.agentdb.values()
+ try:
+ aad =
AmsAgentDescription(self.content.action.modify['ams-agent-description'])
+ except Exception, err:
+ error = "(missing-argument ams-agent-description)"
+ self.myAgent.DEBUG("Modify: Missing argument in
ams-agent-description", 'error', "ams")
+ #print "aad: " + str(aad.getAID().getName())
+ #print "aid: " + str(self.msg.getSender())
- content = "((result " #TODO: + self.msg.getContent()
- if len(result)>0:
- content += " (set "
- for i in result:
- content += str(i) + " "
- content += ")"
- else:
- content+= 'None'
- content += "))"
+ # If there is no AID in the AAD, fill it with the sender
of the message
+ if aad.getAID() and aad.getAID().getName() is None:
+ aad.setAID(self.msg.getSender())
+ self.myAgent.DEBUG("Modify: Overwriting missing AID
with sender AID " + str(self.msg.getSender()), 'warn', "ams")
- reply.setContent(content)
+ if aad and (not aad.getAID() == self.msg.getSender()):
+ error = "(unauthorised)"
+ self.myAgent.DEBUG("Modify: Unauthorised. AID does not
match with sender", 'error', "ams")
- else:
- # The RDF way of things, baby
- # Delete done (from previous reply)
- del co["fipa:done"]
- # Look for search constraints
- if co["fipa:action"].has_key("constraints"):
- try:
- max = int(co["fipa:action"]["constraints"])
- except:
- error = 'constraints-error'
- if error:
- reply = self.msg.createReply()
- reply.setSender(self.myAgent.getAID())
- reply.setPerformative("failure")
- co["fipa:error"] = error
- reply.setContentObject(co)
- self.myAgent.send(reply)
- return -1
+ if error:
+ reply = self.msg.createReply()
+ reply.setSender(self.myAgent.getAID())
+ reply.setPerformative("refuse")
+ reply.setContent("( " + self.msg.getContent() + error
+ ")")
+ self.myAgent.send(reply)
- #Â Search for the results
- result = []
- if co["fipa:action"].has_key("fipa:argument") and
co["fipa:action"]["fipa:argument"]:
- aad = AmsAgentDescription(co=co["fipa:action"]["fipa:argument"])
- for a in self.myAgent.agentdb.values():
- if max >= 0:
- if a.match(aad):
- result.append(a)
- max -= 1
- else: break
- else:
- result = self.myAgent.agentdb.values()
+ return -1
- co2 =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
- co2["fipa:result"] = []
- for i in result:
- co2["fipa:result"].append(i.asContentObject())
- reply.setContentObject(co2)
+ else:
+ reply = self.msg.createReply()
+ reply.setSender(self.myAgent.getAID())
+ reply.setPerformative("agree")
+ reply.setContent("(" + str(self.msg.getContent()) + "
true)")
+ self.myAgent.send(reply)
+ if aad.getAID().getName() in self.myAgent.agentdb.keys():
- reply.setPerformative("inform")
- self.myAgent.send(reply)
+ try:
+ self.myAgent.agentdb[aad.getAID().getName()] = aad
+ except Exception, err:
+ reply.setPerformative("failure")
+ reply.setContent("(" + self.msg.getContent()
+ "(internal-error))")
+ self.myAgent.send(reply)
+ return -1
- return 1
+ reply.setPerformative("inform")
+ reply.setContent("(done " + self.msg.getContent()
+ ")")
+ self.myAgent.send(reply)
- class ModifyBehaviour(Behaviour.OneShotBehaviour):
+ return 1
- def __init__(self,msg,content):
- Behaviour.OneShotBehaviour.__init__(self)
- self.msg = msg
- self.content = content
+ else:
+ reply.setPerformative("failure")
+ reply.setContent("(" + self.msg.getContent()
+ "(not-registered))")
+ self.myAgent.send(reply)
+ #print aad.getAID().getName()
+ #print self.myAgent.agentdb
+ return -1
- def _process(self):
- #The AMS agrees and then informs dummy of the successful execution of
the action
- error = False
- aad = None
+ else:
+ #Language is RDF
+ co = self.msg.getContentObject()
+ if "fipa:argument" in co["fipa:action"].keys() and
co["fipa:action"]["fipa:argument"]:
+ aad =
AmsAgentDescription(co=co["fipa:action"]["fipa:argument"])
+ else:
+ error = "missing-argument ams-agent-description"
+ self.myAgent.DEBUG("Modify: Missing argument in
ams-agent-description", 'error', "ams")
+ #print "aad: " + str(aad.getAID().getName())
+ #print "aid: " + str(self.msg.getSender())
- if "rdf" in self.msg.getLanguage().lower():
- rdf = True
- else:
- # Old ugly SL0
- rdf = False
+ # If there is no AID in the AAD, fill it with the sender
of the message
+ if aad.getAID() and aad.getAID().getName() is None:
+ self.myAgent.DEBUG("Modify: Overwriting missing AID
with sender AID " + str(self.msg.getSender()), 'warn', "ams")
+ aad.setAID(self.msg.getSender())
- if not rdf:
+ #An agent is only allowed to modify itself
+ if aad and (not aad.getAID() == self.msg.getSender()):
+ error = "unauthorised"
+ self.myAgent.DEBUG("Modify: Unauthorised. AID does not
match with sender", 'error', "ams")
- try:
- aad =
AmsAgentDescription(self.content.action.modify['ams-agent-description'])
- except Exception,err:
- error = "(missing-argument ams-agent-description)"
- self.myAgent.DEBUG("Modify: Missing argument in
ams-agent-description",'error')
- #print "aad: " + str(aad.getAID().getName())
- #print "aid: " + str(self.msg.getSender())
+ if error:
+ reply = self.msg.createReply()
+ reply.setSender(self.myAgent.getAID())
+ reply.setPerformative("refuse")
+ co["fipa:error"] = error
+ reply.setContentObject(co)
+ self.myAgent.send(reply)
- # If there is no AID in the AAD, fill it with the sender of the message
- if aad.getAID() and aad.getAID().getName() == None:
- aad.setAID(self.msg.getSender())
- self.myAgent.DEBUG("Modify: Overwriting missing AID with sender
AID "+ str(self.msg.getSender()),'warn')
+ return -1
- if aad and (not aad.getAID() == self.msg.getSender()):
- error = "(unauthorised)"
- self.myAgent.DEBUG("Modify: Unauthorised. AID does not match with
sender",'error')
+ else:
+ reply = self.msg.createReply()
+ reply.setSender(self.myAgent.getAID())
+ reply.setPerformative("agree")
+ co["fipa:done"] = "true"
+ reply.setContentObject(co)
+ self.myAgent.send(reply)
- if error:
- reply = self.msg.createReply()
- reply.setSender(self.myAgent.getAID())
- reply.setPerformative("refuse")
- reply.setContent("( "+self.msg.getContent() + error + ")")
- self.myAgent.send(reply)
+ del co["fipa:done"]
- return -1
+ if aad.getAID().getName() in self.myAgent.agentdb.keys():
- else:
- reply = self.msg.createReply()
- reply.setSender(self.myAgent.getAID())
- reply.setPerformative("agree")
- reply.setContent("(" + str(self.msg.getContent()) + " true)")
- self.myAgent.send(reply)
+ try:
+ self.myAgent.agentdb[aad.getAID().getName()] = aad
+ except Exception, err:
+ reply.setPerformative("failure")
+ co["fipa:error"] = "internal-error"
+ reply.setContentObject(co)
+ self.myAgent.send(reply)
+ return -1
- if self.myAgent.agentdb.has_key(aad.getAID().getName()):
+ reply.setPerformative("inform")
+ co["fipa:done"] = "true"
+ reply.setContentObject(co)
+ self.myAgent.send(reply)
- try:
- self.myAgent.agentdb[aad.getAID().getName()] = aad
- except Exception, err:
- reply.setPerformative("failure")
- reply.setContent("("+self.msg.getContent() + "(internal-error))")
- self.myAgent.send(reply)
- return -1
+ return 1
- reply.setPerformative("inform")
- reply.setContent("(done "+self.msg.getContent() + ")")
- self.myAgent.send(reply)
+ else:
+ reply.setPerformative("failure")
+ co["fipa:error"] = "not-registered"
+ reply.setContentObject(co)
+ self.myAgent.send(reply)
+ #print aad.getAID().getName()
+ #print self.myAgent.agentdb
+ return -1
- return 1
+ def __init__(self, node, passw, server="localhost", port=5347,
config={}):
+ PlatformAgent.__init__(self, node, passw, server, port, config)
- else:
- reply.setPerformative("failure")
- reply.setContent("("+self.msg.getContent() + "(not-registered))")
- self.myAgent.send(reply)
- #print aad.getAID().getName()
- #print self.myAgent.agentdb
- return -1
+ def _setup(self):
- else:
- #Language is RDF
- co = self.msg.getContentObject()
- if co["fipa:action"].has_key("fipa:argument") and
co["fipa:action"]["fipa:argument"]:
- aad = AmsAgentDescription(co=co["fipa:action"]["fipa:argument"])
- else:
- error = "missing-argument ams-agent-description"
- self.myAgent.DEBUG("Modify: Missing argument in
ams-agent-description",'error')
- #print "aad: " + str(aad.getAID().getName())
- #print "aid: " + str(self.msg.getSender())
+ self.agentdb = dict()
- # If there is no AID in the AAD, fill it with the sender of the message
- if aad.getAID() and aad.getAID().getName() == None:
- self.myAgent.DEBUG("Modify: Overwriting missing AID with sender
AID "+ str(self.msg.getSender()),'warn')
- aad.setAID(self.msg.getSender())
+ AAD = AmsAgentDescription()
+ AAD.name = self.getAID()
+ AAD.ownership = "SPADE"
***The diff for this file has been truncated for email.***
=======================================
--- /trunk/spade/Agent.py Fri Nov 9 09:51:22 2012
+++ /trunk/spade/Agent.py Fri Nov 23 05:19:16 2012
@@ -1,10 +1,10 @@
-# -*- coding: cp1252 -*-
+# -*- coding: utf-8 -*-
try:
import psyco
psyco.full()
except ImportError:
- pass #self.DEBUG("Psyco optimizing compiler not found","warn")
+ pass # self.DEBUG("Psyco optimizing compiler not found","warn")
import sys
import xml.dom.minidom
@@ -52,40 +52,43 @@
from xmpp import *
# Taken from xmpp debug
-color_none = chr(27) + "[0m"
-color_black = chr(27) + "[30m"
-color_red = chr(27) + "[31m"
-color_green = chr(27) + "[32m"
-color_brown = chr(27) + "[33m"
-color_blue = chr(27) + "[34m"
-color_magenta = chr(27) + "[35m"
-color_cyan = chr(27) + "[36m"
-color_light_gray = chr(27) + "[37m"
-color_dark_gray = chr(27) + "[30;1m"
-color_bright_red = chr(27) + "[31;1m"
+color_none = chr(27) + "[0m"
+color_black = chr(27) + "[30m"
+color_red = chr(27) + "[31m"
+color_green = chr(27) + "[32m"
+color_brown = chr(27) + "[33m"
+color_blue = chr(27) + "[34m"
+color_magenta = chr(27) + "[35m"
+color_cyan = chr(27) + "[36m"
+color_light_gray = chr(27) + "[37m"
+color_dark_gray = chr(27) + "[30;1m"
+color_bright_red = chr(27) + "[31;1m"
color_bright_green = chr(27) + "[32;1m"
-color_yellow = chr(27) + "[33;1m"
-color_bright_blue = chr(27) + "[34;1m"
-color_purple = chr(27) + "[35;1m"
-color_bright_cyan = chr(27) + "[36;1m"
-color_white = chr(27) + "[37;1m"
+color_yellow = chr(27) + "[33;1m"
+color_bright_blue = chr(27) + "[34;1m"
+color_purple = chr(27) + "[35;1m"
+color_bright_cyan = chr(27) + "[36;1m"
+color_white = chr(27) + "[37;1m"
try:
threading.stack_size(64 * 1024) # 64k compo
-except: pass
+except:
+ pass
def require_login(func):
'''decorator for requiring login in wui controllers'''
self = func.__class__
+
def wrap(self, *args, **kwargs):
- if (not hasattr(self.session,"user_authenticated") or
getattr(self.session,"user_authenticated")==False) and
self.wui.passwd!=None:
- name = self.getName().split(".")[0].upper()
- if name=="ACC": name="SPADE"
- return "login.pyra",
{"name":name,'message':"Authentication is
required.", "forward_url":self.session.url}
- return func(self,*args,**kwargs)
- wrap.__doc__=func.__doc__
- wrap.__name__=func.__name__
+ if (not hasattr(self.session, "user_authenticated") or
getattr(self.session, "user_authenticated") is False) and self.wui.passwd
is not None:
+ name = self.getName().split(".")[0].upper()
+ if name == "ACC":
+ name = "SPADE"
+ return "login.pyra", {"name": name, 'message': "Authentication
is required.", "forward_url": self.session.url}
+ return func(self, *args, **kwargs)
+ wrap.__doc__ = func.__doc__
+ wrap.__name__ = func.__name__
return wrap
@@ -102,7 +105,7 @@
"""
MessageReceiver.MessageReceiver.__init__(self)
self._agent_log = [] # Log system
- self._aid = AID.aid(name=agentjid, addresses=["xmpp://"+agentjid])
+ self._aid = AID.aid(name=agentjid, addresses=["xmpp://" +
agentjid])
self._jabber = None
self._serverplatform = serverplatform
self.server = serverplatform
@@ -112,45 +115,44 @@
self._alivemutex = mutex.mutex()
self._forceKill = threading.Event()
self._forceKill.clear()
- self.JID=agentjid
+ self.JID = agentjid
self.setName(str(agentjid))
-
+
self._debug = False
self._debug_filename = ""
self._debug_file = None
self._debug_mutex = thread.allocate_lock()
-
- self._messages=[]
+
+ self._messages = []
self._messages_mutex = thread.allocate_lock()
-
+
self.wui = WUI(self)
- self.wui.registerController("index",self.WUIController_admin)
- self.wui.registerController("login",self.WUIController_login)
- self.wui.registerController("logout",self.WUIController_logout)
+ self.wui.registerController("index", self.WUIController_admin)
+ self.wui.registerController("login", self.WUIController_login)
+ self.wui.registerController("logout", self.WUIController_logout)
self.wui.registerController("admin", self.WUIController_admin)
self.wui.registerController("log", self.WUIController_log)
- self.wui.registerController("messages",self.WUIController_messages)
- self.wui.registerController("search",self.WUIController_search)
- self.wui.registerController("send",self.WUIController_sendmsg)
- self.wui.registerController("sent",self.WUIController_sent)
+ self.wui.registerController("messages",
self.WUIController_messages)
+ self.wui.registerController("search", self.WUIController_search)
+ self.wui.registerController("send", self.WUIController_sendmsg)
+ self.wui.registerController("sent", self.WUIController_sent)
self.wui.passwd = None
-
+
self._aclparser = ACLParser.ACLxmlParser()
#self._friend_list = [] # Legacy
#self._muc_list= {}
self._roster = {}
self._socialnetwork = {}
- self._subscribeHandler = lambda frm,typ,stat,show: False
- self._unsubscribeHandler = lambda frm,typ,stat,show: False
+ self._subscribeHandler = lambda frm, typ, stat, show: False
+ self._unsubscribeHandler = lambda frm, typ, stat, show: False
#PubSub
self._pubsub = pubsub.PubSub(self)
self._events = {}
-
+
#Knowledge base
- self.kb = KB() # knowledge base
-
+ self.kb = KB() # knowledge base
self._waitingForRoster = False # Indicates that a request for the
roster is in progress
@@ -175,92 +177,96 @@
self._p2p_failures = 0 # Counter for failed attempts to send p2p
messages
if p2p:
self.registerLogComponent("p2p")
- self.P2PPORT = random.randint(1025,65535) # Random P2P port
number
+ self.P2PPORT = random.randint(1025, 65535) # Random P2P port
number
p2pb = P2P.P2PBehaviour()
self.addBehaviour(p2pb)
-
+
#Remote Procedure Calls support
self.RPC = {}
- self.addBehaviour(RPC.RPCServerBehaviour(),
Behaviour.MessageTemplate(Iq(typ='set',queryNS=NS_RPC)))
-
+ self.addBehaviour(RPC.RPCServerBehaviour(),
Behaviour.MessageTemplate(Iq(typ='set', queryNS=NS_RPC)))
def setAdminPasswd(self, passwd):
self.wui.passwd = str(passwd)
def WUIController_login(self, password=None, forward_url="index"):
- if hasattr(self.session, "user_authenticated") and
getattr(self.session,"user_authenticated")==True:
- raise HTTP_REDIRECTION, 'index'
+ if hasattr(self.session, "user_authenticated") and
getattr(self.session, "user_authenticated") is True:
+ raise HTTP_REDIRECTION('index')
name = self.getName().split(".")[0].upper()
- if name=="ACC": name="SPADE"
+ if name == "ACC":
+ name = "SPADE"
- if password==None:
- return "login.pyra", {"name":name, "message":"Authentication
is required.","forward_url":forward_url}
- if password!=self.wui.passwd:
- return "login.pyra", {"name":name, "message":"Password is
incorrect. Try again.","forward_url":forward_url}
+ if password is None:
+ return "login.pyra", {"name": name, "message": "Authentication
is required.", "forward_url": forward_url}
+ if password != self.wui.passwd:
+ return "login.pyra", {"name": name, "message": "Password is
incorrect. Try again.", "forward_url": forward_url}
else:
- setattr(self.session,"user_authenticated",True)
- raise HTTP_REDIRECTION, forward_url
+ setattr(self.session, "user_authenticated", True)
+ raise HTTP_REDIRECTION(forward_url)
def WUIController_logout(self):
if hasattr(self.session, "user_authenticated"):
- delattr(self.session,"user_authenticated")
- raise HTTP_REDIRECTION, "index"
+ delattr(self.session, "user_authenticated")
+ raise HTTP_REDIRECTION("index")
@require_login
def WUIController_admin(self):
import types
behavs = {}
attrs = {}
- sorted_attrs = []
+ sorted_attrs = []
for k in self._behaviourList.keys():
- behavs[id(k)]=k
+ behavs[id(k)] = k
for attribute in self.__dict__:
- if eval( "type(self."+attribute+") not in [types.MethodType,
types.BuiltinFunctionType, types.BuiltinMethodType, types.FunctionType]" ):
+ if eval("type(self." + attribute + ") not in
[types.MethodType, types.BuiltinFunctionType, types.BuiltinMethodType,
types.FunctionType]"):
if attribute not in ["_agent_log"]:
- attrs[attribute] = eval( "str(self."+attribute+")" )
+ attrs[attribute] = eval("str(self." + attribute + ")")
sorted_attrs = attrs.keys()
sorted_attrs.sort()
import pygooglechart
- chart=pygooglechart.QRChart(125,125)
+ chart = pygooglechart.QRChart(125, 125)
chart.add_data(self.getAID().asXML())
- chart.set_ec('H',0)
- return "admin.pyra",
{"name":self.getName(),"aid":self.getAID(), "qrcode":chart.get_url(), "defbehav":(id(self._defaultbehaviour),self._defaultbehaviour), "behavs":behavs, "p2pready":self.p2p_ready, "p2proutes":self.p2p_routes, "attrs":attrs, "sorted_attrs":sorted_attrs}
-
+ chart.set_ec('H', 0)
+ return "admin.pyra", {"name": self.getName(), "aid":
self.getAID(), "qrcode": chart.get_url(), "defbehav":
(id(self._defaultbehaviour), self._defaultbehaviour), "behavs":
behavs, "p2pready": self.p2p_ready, "p2proutes": self.p2p_routes, "attrs":
attrs, "sorted_attrs": sorted_attrs}
+
@require_login
def WUIController_log(self):
- return "log.pyra", {"name":self.getName(), "log":self.getLog()}
+ return "log.pyra", {"name": self.getName(), "log": self.getLog()}
@require_login
- def WUIController_messages(self,agents=None):
- index=0
+ def WUIController_messages(self, agents=None):
+ index = 0
mess = {}
msc = ""
- agentslist=[]
- for ts,m in self._messages:
- if isinstance(m,ACLMessage.ACLMessage):
- strm=self._aclparser.encodeXML(m)
+ agentslist = []
+ for ts, m in self._messages:
+ if isinstance(m, ACLMessage.ACLMessage):
+ strm = self._aclparser.encodeXML(m)
x = xml.dom.minidom.parseString(strm)
#strm = x.toprettyxml()
strm = m.asHTML()
frm = m.getSender()
- if frm!=None: frm = str(frm.getName())
- else: frm = "Unknown"
- if "/" in frm: frm=frm.split("/")[0]
+ if frm is not None:
+ frm = str(frm.getName())
+ else:
+ frm = "Unknown"
+ if "/" in frm:
+ frm = frm.split("/")[0]
r = m.getReceivers()
- if len(r)>=1:
+ if len(r) >= 1:
to = r[0].getName()
else:
to = "Unknown"
- if "/" in to: to=to.split("/")[0]
+ if "/" in to:
+ to = to.split("/")[0]
if agents:
if to in agents or frm in agents:
- msc +=
frm+"->"+to+':'+str(index)+" "+str(m.getPerformative())+'\n'
+ msc += frm + "->" + to + ':' + str(index) + " " +
str(m.getPerformative()) + '\n'
else:
- msc +=
frm+"->"+to+':'+str(index)+" "+str(m.getPerformative())+'\n'
+ msc += frm + "->" + to + ':' + str(index) + " " +
str(m.getPerformative()) + '\n'
else:
- strm=str(m)
+ strm = str(m)
"""strm = strm.replace(">",">")
strm = strm.replace("<","<")
strm = strm.replace(""",'"')"""
@@ -272,42 +278,58 @@
strm = strm.replace("<", "<")
strm = strm.replace('"', """)
frm = m.getFrom()
- if frm==None: frm = "Unknown"
- else: frm = str(frm)
- if "/" in frm: frm=frm.split("/")[0]
+ if frm is None:
+ frm = "Unknown"
+ else:
+ frm = str(frm)
+ if "/" in frm:
+ frm = frm.split("/")[0]
to = m.getTo()
- if to==None: to = "Unknown"
- else: to = str(to)
- if "/" in to: to=to.split("/")[0]
+ if to is None:
+ to = "Unknown"
+ else:
+ to = str(to)
+ if "/" in to:
+ to = to.split("/")[0]
if agents:
if to in agents or frm in agents:
- msc +=
frm+"-->"+to+':'+str(index)+' '+str(m.getName())
- if m.getType(): msc+=" " + str(m.getType())+'\n'
- elif m.getName()=="message":
- if m.getAttr("performative"): msc+=" " +
str(m.getAttr("performative"))+'\n'
- else: msc+='\n'
- else: msc+='\n'
+ msc += frm + "-->" + to + ':' + str(index) + ' ' +
str(m.getName())
+ if m.getType():
+ msc += " " + str(m.getType()) + '\n'
+ elif m.getName() == "message":
+ if m.getAttr("performative"):
+ msc += " " +
str(m.getAttr("performative")) + '\n'
+ else:
+ msc += '\n'
+ else:
+ msc += '\n'
else:
- msc += frm+"-->"+to+':'+str(index)+' '+str(m.getName())
- if m.getType(): msc+=" " + str(m.getType())+'\n'
- elif m.getName()=="message":
- if m.getAttr("performative"): msc+=" " +
str(m.getAttr("performative"))+'\n'
- else: msc+='\n'
- else: msc+='\n'
-
- if frm not in agentslist: agentslist.append(frm)
- if to not in agentslist: agentslist.append(to)
+ msc += frm + "-->" + to + ':' + str(index) + ' ' +
str(m.getName())
+ if m.getType():
+ msc += " " + str(m.getType()) + '\n'
+ elif m.getName() == "message":
+ if m.getAttr("performative"):
+ msc += " " + str(m.getAttr("performative"))
+ '\n'
+ else:
+ msc += '\n'
+ else:
+ msc += '\n'
+
+ if frm not in agentslist:
+ agentslist.append(frm)
+ if to not in agentslist:
+ agentslist.append(to)
- mess[index]=(ts,strm)
- index+=1
+ mess[index] = (ts, strm)
+ index += 1
- return "messages.pyra",
{"name":self.getName(), "messages":mess, "diagram":
msc, "agentslist":agentslist}
+ return "messages.pyra", {"name": self.getName(), "messages":
mess, "diagram": msc, "agentslist": agentslist}
@require_login
def WUIController_search(self, query):
-
+
#FIRST SEARCH AGENTS
- from AMS import AmsAgentDescription
+ from AMS import AmsAgentDescription
agentslist = []
#search by name
@@ -332,7 +354,7 @@
res = self.searchAgent(aad)
if res:
for a in res:
- if not a in agentslist:
+ if not a in agentslist:
agentslist.append(a)
#search by state
@@ -343,7 +365,7 @@
for a in res:
if not a in agentslist:
agentslist.append(a)
-
+
# Build AWUIs dict
awuis = {}
if agentslist:
@@ -351,26 +373,26 @@
for agent in agentslist:
if agent.getAID():
aw = "#"
- for addr in agent.getAID().getAddresses():
+ for addr in agent.getAID().getAddresses():
if "awui://" in addr:
aw = addr.replace("awui://", "http://")
break
awuis[agent.getAID().getName()] = aw
- self.DEBUG("AWUIs: "+str(awuis))
-
+ self.DEBUG("AWUIs: " + str(awuis))
+
#NOW SEARCH SERVICES
- from DF import Service,DfAgentDescription, ServiceDescription
+ from DF import Service, DfAgentDescription, ServiceDescription
servs = {}
-
+
#search by name
s = Service(name=query)
search = self.searchService(s)
for service in search:
- if service.getDAD().getServices()[0].getType() not in
servs.keys():
- servs[service.getDAD().getServices()[0].getType()] = []
- if service not in
servs[service.getDAD().getServices()[0].getType()]:
-
servs[service.getDAD().getServices()[0].getType()].append(service)
+ if service.getDAD().getServices()[0].getType() not in
servs.keys():
+ servs[service.getDAD().getServices()[0].getType()] = []
+ if service not in
servs[service.getDAD().getServices()[0].getType()]:
+
servs[service.getDAD().getServices()[0].getType()].append(service)
#search by type
s = Service()
@@ -382,20 +404,20 @@
search = self.searchService(s)
for service in search:
- if service.getDAD().getServices()[0].getType() not in
servs.keys():
- servs[service.getDAD().getServices()[0].getType()] = []
- if service not in
servs[service.getDAD().getServices()[0].getType()]:
-
servs[service.getDAD().getServices()[0].getType()].append(service)
-
+ if service.getDAD().getServices()[0].getType() not in
servs.keys():
+ servs[service.getDAD().getServices()[0].getType()] = []
+ if service not in
servs[service.getDAD().getServices()[0].getType()]:
+
servs[service.getDAD().getServices()[0].getType()].append(service)
+
#search by owner
s = Service(owner=AID.aid(name=query))
search = self.searchService(s)
for service in search:
- if service.getDAD().getServices()[0].getType() not in
servs.keys():
- servs[service.getDAD().getServices()[0].getType()] = []
- if service not in
servs[service.getDAD().getServices()[0].getType()]:
-
servs[service.getDAD().getServices()[0].getType()].append(service)
+ if service.getDAD().getServices()[0].getType() not in
servs.keys():
+ servs[service.getDAD().getServices()[0].getType()] = []
+ if service not in
servs[service.getDAD().getServices()[0].getType()]:
+
servs[service.getDAD().getServices()[0].getType()].append(service)
#search by ontology
s = Service()
@@ -406,10 +428,10 @@
search = self.searchService(s)
for service in search:
- if service.getDAD().getServices()[0].getType() not in
servs.keys():
- servs[service.getDAD().getServices()[0].getType()] = []
- if service not in
servs[service.getDAD().getServices()[0].getType()]:
-
servs[service.getDAD().getServices()[0].getType()].append(service)
+ if service.getDAD().getServices()[0].getType() not in
servs.keys():
+ servs[service.getDAD().getServices()[0].getType()] = []
+ if service not in
servs[service.getDAD().getServices()[0].getType()]:
+
servs[service.getDAD().getServices()[0].getType()].append(service)
#search by description
'''s = Service()
@@ -423,50 +445,58 @@
print "found by description:" +str(service)
servs[service.getDAD().getServices()[0].getType()].append(service)'''
-
- return "search.pyra", {"name":self.getName(), "agentslist":
agentslist, "awuis":awuis, "services":servs}
+ return "search.pyra", {"name": self.getName(), "agentslist":
agentslist, "awuis": awuis, "services": servs}
@require_login
def WUIController_sendmsg(self, to=None):
- from AMS import AmsAgentDescription
+ from AMS import AmsAgentDescription
agentslist = []
aad = AmsAgentDescription()
res = self.searchAgent(aad)
- if res==None: res=[self]
+ if res is None:
+ res = [self]
for a in res:
agentslist.append(a.getAID().getName())
- return "message.pyra",
{"name":self.getName(), "keys":agentslist, "to":to}
-
+ return "message.pyra", {"name": self.getName(), "keys":
agentslist, "to": to}
+
@require_login
- def WUIController_sent(self,
receivers=[],performative=None,sender=None,reply_with=None,reply_by=None,reply_to=None,in_reply_to=None,encoding=None,language=None,ontology=None,protocol=None,conversation_id=None,content=""):
+ def WUIController_sent(self, receivers=[], performative=None,
sender=None, reply_with=None, reply_by=None, reply_to=None,
in_reply_to=None, encoding=None, language=None, ontology=None,
protocol=None, conversation_id=None, content=""):
msg = ACLMessage.ACLMessage()
import types
- if type(receivers)==types.StringType:
- a = AID.aid(name=receivers,addresses=["xmpp://"+receivers])
+ if isinstance(receivers, types.StringType):
+ a = AID.aid(name=receivers, addresses=["xmpp://" + receivers])
msg.addReceiver(a)
- elif type(receivers)==types.ListType:
+ elif isinstance(receivers, types.ListType):
for r in receivers:
- a = AID.aid(name=r,addresses=["xmpp://"+r])
+ a = AID.aid(name=r, addresses=["xmpp://" + r])
msg.addReceiver(a)
- if performative: msg.setPerformative(performative)
+ if performative:
+ msg.setPerformative(performative)
if sender:
- a = AID.aid(name=sender,addresses=["xmpp://"+sender])
+ a = AID.aid(name=sender, addresses=["xmpp://" + sender])
msg.setSender(a)
- if reply_to: msg.setReplyTo(reply_to)
- if reply_with: msg.setReplyWith(reply_with)
- if reply_by: msg.setReplyBy(reply_by)
- if in_reply_to: msg.setInReplyTo(in_reply_to)
- if encoding: msg.setEncoding(encoding)
- if language: msg.setLanguage(language)
- if ontology: msg.setOntology(ontology)
- if conversation_id: msg.setConversationId(conversation_id)
- if content: msg.setContent(content)
-
+ if reply_to:
+ msg.setReplyTo(reply_to)
+ if reply_with:
+ msg.setReplyWith(reply_with)
+ if reply_by:
+ msg.setReplyBy(reply_by)
+ if in_reply_to:
+ msg.setInReplyTo(in_reply_to)
+ if encoding:
+ msg.setEncoding(encoding)
+ if language:
+ msg.setLanguage(language)
+ if ontology:
+ msg.setOntology(ontology)
+ if conversation_id:
+ msg.setConversationId(conversation_id)
+ if content:
+ msg.setContent(content)
+
self.send(msg)
-
- return "sentmsg.pyra", {"name":self.getName(), "msg":msg}
-
+ return "sentmsg.pyra", {"name": self.getName(), "msg": msg}
def registerLogComponent(self, component):
#self._agent_log[component] = {}
@@ -475,12 +505,12 @@
def DEBUG(self, dmsg, typ="info", component="spade"):
# Record at log
t = time.ctime()
- dmsg = dmsg.replace(">",">")
- dmsg = dmsg.replace("<","<")
- dmsg = dmsg.replace(""",'"')
+ dmsg = dmsg.replace(">", ">")
+ dmsg = dmsg.replace("<", "<")
+ dmsg = dmsg.replace(""", '"')
self._debug_mutex.acquire()
- self._agent_log.append((typ,dmsg,component,t))
+ self._agent_log.append((typ, dmsg, component, t))
self._debug_mutex.release()
if self._debug:
@@ -497,23 +527,23 @@
# Log to file
if self._debug_file:
if typ == "info":
- self._debug_file.write( t + ": [" + component + "] " +
dmsg + " , info\n")
+ self._debug_file.write(t + ": [" + component + "] " + dmsg
+ " , info\n")
elif typ == "err":
- self._debug_file.write( t + ": [" + component + "] " +
dmsg + " , error\n")
+ self._debug_file.write(t + ": [" + component + "] " + dmsg
+ " , error\n")
elif typ == "ok":
- self._debug_file.write( t + ": [" + component + "] " +
dmsg + " , ok\n")
+ self._debug_file.write(t + ": [" + component + "] " + dmsg
+ " , ok\n")
elif typ == "warn":
- self._debug_file.write( t + ": [" + component + "] " +
dmsg + " , warn\n")
+ self._debug_file.write(t + ": [" + component + "] " + dmsg
+ " , warn\n")
self._debug_file.flush()
- def setDebug(self, activate = True):
+ def setDebug(self, activate=True):
self.setDebugToScreen(activate)
self.setDebugToFile(activate)
- def setDebugToScreen(self, activate = True):
+ def setDebugToScreen(self, activate=True):
self._debug = activate
- def setDebugToFile(self, activate = True, fname = "" ):
+ def setDebugToFile(self, activate=True, fname=""):
if not fname:
self._debug_filename = self.getName() + ".log"
else:
@@ -530,15 +560,6 @@
l = copy.copy(self._agent_log)
l.reverse()
return l
- '''
- keys = self._agent_log.keys()
- keys.sort()
- keys.reverse()
- l = list()
- for k in keys:
- l.append(self._agent_log[k])
- return l
- '''
def newMessage(self):
"""Creates and returns an empty ACL message"""
@@ -561,35 +582,35 @@
role = None
affiliation = None
- children =
mess.getTags(name='x',namespace='
http://jabber.org/protocol/muc#user')
+ children = mess.getTags(name='x',
namespace='
http://jabber.org/protocol/muc#user')
for x in children:
for item in x.getTags(name='item'):
role = item.getAttr('role')
affiliation = item.getAttr('affiliation')
try:
- # Pass the FIPA-message to the behaviours
+ # Pass the FIPA-message to all the behaviours
for b in self._behaviourList.keys():
b.managePresence(frm, typ, status, show, role, affiliation)
self._defaultbehaviour.managePresence(frm, typ, status, show,
role, affiliation)
except Exception, e:
#There is not a default behaviour yet
- self.DEBUG(str(e),"err")
+ self.DEBUG(str(e), "err")
def _jabber_messageCB(self, conn, mess, raiseFlag=True):
"""
message callback
read the message envelope and post the message to the agent
"""
-
+
for child in mess.getChildren():
if (child.getNamespace() == "jabber:x:fipa") or
(child.getNamespace() == u"jabber:x:fipa"):
# It is a jabber-fipa message
ACLmsg = ACLMessage.ACLMessage()
ACLmsg._attrs.update(mess.attrs)
try:
- #Â Clean
+ #Â Clean
del ACLmsg._attrs["from"]
except:
pass
@@ -612,28 +633,29 @@
except:
ACLmsg.setSender(envelope.getFrom())
else:
-
ACLmsg.setSender(AID.aid(str(mess.getFrom().getStripped()),
["xmpp://"+str(mess.getFrom().getStripped())]))
+
ACLmsg.setSender(AID.aid(str(mess.getFrom().getStripped()), ["xmpp://" +
str(mess.getFrom().getStripped())]))
if envelope.getIntendedReceiver():
for ir in envelope.getIntendedReceiver():
ACLmsg.addReceiver(ir)
else:
-
ACLmsg.addReceiver(AID.aid(str(mess.getTo().getStripped()),
["xmpp://"+str(mess.getTo())]))
+
ACLmsg.addReceiver(AID.aid(str(mess.getTo().getStripped()), ["xmpp://" +
str(mess.getTo())]))
else:
-
ACLmsg.setSender(AID.aid(str(mess.getFrom().getStripped()),
["xmpp://"+str(mess.getFrom().getStripped())]))
-
ACLmsg.addReceiver(AID.aid(str(mess.getTo().getStripped()),
["xmpp://"+str(mess.getTo().getStripped())]))
+
ACLmsg.setSender(AID.aid(str(mess.getFrom().getStripped()), ["xmpp://" +
str(mess.getFrom().getStripped())]))
+
ACLmsg.addReceiver(AID.aid(str(mess.getTo().getStripped()), ["xmpp://" +
str(mess.getTo().getStripped())]))
self._messages_mutex.acquire()
timestamp = time.time()
- self._messages.append((timestamp,ACLmsg))
+ self._messages.append((timestamp, ACLmsg))
self._messages_mutex.release()
self.postMessage(ACLmsg)
- if raiseFlag: raise xmpp.NodeProcessed # Forced by
xmpp.py for not returning an error stanza
+ if raiseFlag:
+ raise xmpp.NodeProcessed # Forced by xmpp.py for not
returning an error stanza
return True
# Not a jabber-fipa message
self._messages_mutex.acquire()
timestamp = time.time()
- self._messages.append((timestamp,mess))
+ self._messages.append((timestamp, mess))
self._messages_mutex.release()
#Â Check wether is an offline action
@@ -643,14 +665,15 @@
if mess.getAttr("type") == "get":
q = mess.getTag("query")
if q and q.getNamespace() == NS_DISCO_INFO:
- self.DEBUG("DISCO Behaviour called
(offline)","info")
+ self.DEBUG("DISCO Behaviour called
(offline)", "info")
# Inform of services
reply = mess.buildReply("result")
if self.p2p_ready:
- reply.getTag("query").addChild("feature",
{"var":"
http://jabber.org/protocol/si"})
- reply.getTag("query").addChild("feature",
{"var":"
http://jabber.org/protocol/si/profile/spade-p2p-messaging"})
+ reply.getTag("query").addChild("feature",
{"var": "
http://jabber.org/protocol/si"})
+ reply.getTag("query").addChild("feature",
{"var": "
http://jabber.org/protocol/si/profile/spade-p2p-messaging"})
self.send(reply)
- if raiseFlag: raise xmpp.NodeProcessed
+ if raiseFlag:
+ raise xmpp.NodeProcessed
return True
# Check if it's an offline stream initiation request
if mess.getAttr("type") == "set":
@@ -663,11 +686,11 @@
# Take note of sender's p2p address if
any
if mess.getTag("si").getTag("p2p"):
remote_address =
str(mess.getTag("si").getTag("p2p").getData())
- d =
{"url":remote_address, "p2p":True}
+ d = {"url": remote_address, "p2p":
True}
self.p2p_lock.acquire()
- if
self.p2p_routes.has_key(str(mess.getFrom().getStripped())):
+ if
str(mess.getFrom().getStripped()) in self.p2p_routes.keys():
self.p2p_routes[str(mess.getFrom().getStripped())].update(d)
- if
self.p2p_routes[str(mess.getFrom().getStripped())].has_key("socket"):
+ if "socket" in
self.p2p_routes[str(mess.getFrom().getStripped())].keys():
self.p2p_routes[str(mess.getFrom().getStripped())]["socket"].close()
else:
self.p2p_routes[str(mess.getFrom().getStripped())] = d
@@ -684,25 +707,26 @@
else:
# Refuse offer
reply = mess.buildReply("error")
- err = reply.addChild("error",
attrs={"code":"403","type":"cancel"})
+ err = reply.addChild("error",
attrs={"code": "403", "type": "cancel"})
err.addChild("forbidden")
err.setNamespace("urn:ietf:params:xml:ns:xmpp-stanzas")
self.send(reply)
- if raiseFlag: raise xmpp.NodeProcessed
+ if raiseFlag:
+ raise xmpp.NodeProcessed
return True
self.DEBUG("Posting message " + str(mess), "info", "msg")
self.postMessage(mess)
- if raiseFlag: raise xmpp.NodeProcessed # Forced by xmpp.py for
not returning an error stanza
+ if raiseFlag:
+ raise xmpp.NodeProcessed # Forced by xmpp.py for not
returning an error stanza
return True
-
def _other_messageCB(self, conn, mess):
"""
non jabber:x:fipa chat messages callback
"""
- pass
-
+ self.DEBUG("Arrived an unknown message " + str(mess), "warn")
+
def _jabber_iqCB(self, conn, mess):
"""
IQ callback
@@ -710,8 +734,7 @@
"""
# We post every jabber iq
self.postMessage(mess)
- self.DEBUG("Jabber Iq posted to agent " +
str(self.getAID().getName()),"info")
-
+ self.DEBUG("Jabber Iq posted to agent " +
str(self.getAID().getName()), "info")
def getAID(self):
"""
@@ -735,13 +758,13 @@
"""
returns the AMS aid
"""
- return AID.aid(name="ams." + self._serverplatform,
addresses=[ "xmpp://ams."+self._serverplatform ])
+ return AID.aid(name="ams." + self._serverplatform,
addresses=["xmpp://ams." + self._serverplatform])
def getDF(self):
"""
returns the DF aid
"""
- return AID.aid(name="df." + self._serverplatform,
addresses=[ "xmpp://df."+self._serverplatform ])
+ return AID.aid(name="df." + self._serverplatform,
addresses=["xmpp://df." + self._serverplatform])
def getMUC(self):
"""
@@ -762,11 +785,10 @@
return self._serverplatform
def getP2PUrl(self):
- return
str("spade://"+socket.gethostbyname(socket.gethostname())+":"+str(self.P2PPORT))
+ return str("spade://" + socket.gethostbyname(socket.gethostname())
+ ":" + str(self.P2PPORT))
+ def requestDiscoInfo(self, to):
- def requestDiscoInfo(self, to):
-
self.DEBUG("Request Disco Info called by " + str(self.getName()))
rdif = P2P.RequestDiscoInfoBehav(to)
t = Behaviour.MessageTemplate(rdif.temp_iq)
@@ -782,14 +804,12 @@
self.runBehaviourOnce(rdif, t)
return rdif.result
-
def initiateStream(self, to):
"""
Perform a Stream Initiation with another agent
in order to stablish a P2P communication channel
"""
-
self.DEBUG("Initiate Stream called by " + str(self.getName()))
# First deal with Disco Info request
services = self.requestDiscoInfo(to)
@@ -805,27 +825,26 @@
return sib.result
else:
# Offline way
- self.DEBUG("Initiate Stream OFFLINE","warn")
- self.runBehaviourOnce(sib,t)
+ self.DEBUG("Initiate Stream OFFLINE", "warn")
+ self.runBehaviourOnce(sib, t)
return sib.result
-
def send(self, ACLmsg, method="jabber"):
"""
sends an ACLMessage
"""
self._messages_mutex.acquire()
timestamp = time.time()
- self._messages.append((timestamp,ACLmsg))
+ self._messages.append((timestamp, ACLmsg))
self._messages_mutex.release()
-
+
#if it is a jabber Iq or Presence message just send it
- if isinstance(ACLmsg,xmpp.Iq) or isinstance(ACLmsg,xmpp.Presence)
or isinstance(ACLmsg,xmpp.Message):
+ if isinstance(ACLmsg, xmpp.Iq) or isinstance(ACLmsg,
xmpp.Presence) or isinstance(ACLmsg, xmpp.Message):
self.jabber.send(ACLmsg)
return
-
- ACLmsg._attrs.update({"method":method})
- if ACLmsg.getAclRepresentation()==None:
+
+ ACLmsg._attrs.update({"method": method})
+ if ACLmsg.getAclRepresentation() is None:
ACLmsg.setAclRepresentation(ACLMessage.FIPA_ACL_REP_XML)
# Check for the sender field!!! (mistake #1)
if not ACLmsg.getSender():
@@ -837,7 +856,7 @@
"""
sends an ACLMessage to a specific JabberID
"""
-
+
#First, try Ultra-Fast(tm) python cPickle way of things
try:
if method in ["auto", "p2ppy"]:
@@ -858,7 +877,7 @@
#There is no one left to send the message to
return
except Exception, e:
- self.DEBUG("Could not send through P2PPY: "+str(e), "warn")
+ self.DEBUG("Could not send through P2PPY: " + str(e), "warn")
method = "jabber"
#Â Second, try it the old way
@@ -869,12 +888,12 @@
#the only address is not an xmpp address,
#we need the full sender AID field
try:
- if method=="xmppfipa" or
len(ACLmsg.getSender().getAddresses()) > 1 or \
- "xmpp" not in ACLmsg.getSender().getAddresses()[0]:
+ if method == "xmppfipa" or
len(ACLmsg.getSender().getAddresses()) > 1 or \
+ "xmpp" not in ACLmsg.getSender().getAddresses()[0]:
envelope.setFrom(ACLmsg.getSender())
generate_envelope = True
except Exception, e:
- self.DEBUG("Error setting sender: "+ str(e), "err")
+ self.DEBUG("Error setting sender: " + str(e), "err")
try:
for i in ACLmsg.getReceivers():
@@ -883,12 +902,11 @@
#the only address is not an xmpp address,
#we need the full receiver AID field
if len(i.getAddresses()) > 1 or \
- "xmpp" not in i.getAddresses()[0]:
+ "xmpp" not in i.getAddresses()[0]:
envelope.addTo(i)
generate_envelope = True
except Exception, e:
- self.DEBUG("Error setting receivers: " + str(e),"err")
-
+ self.DEBUG("Error setting receivers: " + str(e), "err")
try:
#The same for 'reply_to'
@@ -898,18 +916,18 @@
#the only address is not an xmpp address,
#we need the full receiver AID field
if len(i.getAddresses()) > 1 or \
- "xmpp" not in i.getAddresses()[0]:
+ "xmpp" not in i.getAddresses()[0]:
envelope.addIntendedReceiver(i)
generate_envelope = True
except Exception, e:
- self.DEBUG("Error setting reply-to: " + str(e),"err")
+ self.DEBUG("Error setting reply-to: " + str(e), "err")
#Generate the envelope ONLY if it is needed
if generate_envelope:
envelope.setAclRepresentation(ACLmsg.getAclRepresentation())
xc = XMLCodec.XMLCodec()
envxml = xc.encodeXML(envelope)
- xenv['content-type']='fipa.mts.env.rep.xml.std'
+ xenv['content-type'] = 'fipa.mts.env.rep.xml.std'
xenv.addChild(node=simplexml.NodeBuilder(envxml).getDom())
#For each of the receivers, try to send the message
@@ -925,7 +943,7 @@
jabber_msg = xmpp.protocol.Message(jabber_id, xmlns="")
jabber_msg.attrs.update(ACLmsg._attrs)
jabber_msg.addChild(node=xenv)
- jabber_msg["from"]=self.getAID().getName()
+ jabber_msg["from"] = self.getAID().getName()
jabber_msg.setBody(ACLmsg.getContent())
else:
#I don't understand this address, relay the message to the
platform
@@ -933,10 +951,10 @@
jabber_id = self.getSpadePlatformJID()
jabber_msg.attrs.update(ACLmsg._attrs)
jabber_msg.addChild(node=xenv)
- jabber_msg["from"]=self.getAID().getName()
+ jabber_msg["from"] = self.getAID().getName()
jabber_msg.setBody(ACLmsg.getContent())
- if (not self._running and method=="auto") or method=="jabber"
or method=="xmppfipa":
+ if (not self._running and method == "auto") or method
== "jabber" or method == "xmppfipa":
self.jabber.send(jabber_msg)
continue
@@ -951,29 +969,35 @@
try:
sent = self.send_p2p(jabber_msg, jabber_id,
method=method, ACLmsg=ACLmsg)
except Exception, e:
- self.DEBUG("P2P Connection
to "+str(self.p2p_routes)+jabber_id+" prevented. Falling
back. "+str(e), "warn")
+ self.DEBUG("P2P Connection to " + str(self.p2p_routes)
+ jabber_id + " prevented. Falling back. " + str(e), "warn")
sent = False
self.p2p_send_lock.release()
if not sent:
#P2P failed, try to send it through jabber
- self.DEBUG("P2P failed, try to send it through
jabber","warn")
- jabber_msg.attrs.update({"method":"jabber"})
- if method in ["auto","p2p","p2ppy"]:
self.jabber.send(jabber_msg)
+ self.DEBUG("P2P failed, try to send it through
jabber", "warn")
+ jabber_msg.attrs.update({"method": "jabber"})
+ if method in ["auto", "p2p", "p2ppy"]:
+ self.jabber.send(jabber_msg)
else:
#P2P is not available / not supported
#Try to send it through jabber
- self.DEBUG("P2P is not available/supported, try to send it
through jabber","warn")
- jabber_msg.attrs.update({"method":"jabber"})
- if method in ["auto","p2p","p2ppy"]:
self.jabber.send(jabber_msg)
-
+ self.DEBUG("P2P is not available/supported, try to send it
through jabber", "warn")
+ jabber_msg.attrs.update({"method": "jabber"})
+ if method in ["auto", "p2p", "p2ppy"]:
+ self.jabber.send(jabber_msg)
def send_p2p(self, jabber_msg=None, to="", method="p2ppy",
ACLmsg=None):
- #If this agent supports P2P, wait for P2PBEhaviour to properly
start
+ #If this agent supports P2P, wait for P2PBehaviour to properly
start
if self.p2p:
- while not self.p2p_ready:
+ counter = 50
+ while not self.p2p_ready and counter > 0:
time.sleep(0.1)
+ counter -= 1
+ if not self.p2p_ready:
+ self.DEBUG("This agent could not activate p2p messages
behaviour", "err")
+ return False
else:
# send_p2p should not be called in a P2P-disabled agent !
self.DEBUG("This agent does not support sending p2p
messages", "warn")
@@ -989,19 +1013,18 @@
self.DEBUG("Trying to send Jabber msg through P2P")
***The diff for this file has been truncated for email.***
=======================================
--- /trunk/spade/BasicFipaDateTime.py Wed Jun 21 11:10:23 2006
+++ /trunk/spade/BasicFipaDateTime.py Fri Nov 23 05:19:16 2012
@@ -1,130 +1,126 @@
+# -*- coding: utf-8 -*-
from datetime import datetime
+
class BasicFipaDateTime:
- """
- Help class to operate dates and times
- """
+ """
+ Help class to operate dates and times
+ """
- def __init__(self,date = None):
- """
- constructor
- date parameter can be suplied
- """
- if (date == None):
- self.fromDateTime(datetime.now())
- else:
- if (isinstance(date,str) == True):
- self.fromString(date)
- elif (isinstance(date, datetime) == True):
- self.fromDateTime(date)
-
-
- def fromDateTime(self, dt):
- """
- inits the object with another BasicFipaDateTime class
- """
- self.calendar = dt
+ def __init__(self, date=None):
+ """
+ constructor
+ date parameter can be suplied
+ """
+ if (date is None):
+ self.fromDateTime(datetime.now())
+ else:
+ if isinstance(date, str) is True:
+ self.fromString(date)
+ elif isinstance(date, datetime) is True:
+ self.fromDateTime(date)
- def fromString(self, string):
- """
- loads the date and time from a string
- """
- if string != None and string != "":
- #print "string: " + str(string)
-
- year = int(string[0:4])
- month = int(string[4:6])
- day = int(string[6:8])
- #tz = str[8]
- hour = int(string[9:11])
- minute = int(string[11:13])
- second = int(string[13:15])
- milli = int(string[15:18])
+ def fromDateTime(self, dt):
+ """
+ inits the object with another BasicFipaDateTime class
+ """
+ self.calendar = dt
- self.calendar = datetime(year,month,day,hour,minute,second,milli)
-
- return True
- else:
- return False
+ def fromString(self, string):
+ """
+ loads the date and time from a string
+ """
+ if string is not None and string != "":
+ #print "string: " + str(string)
+ year = int(string[0:4])
+ month = int(string[4:6])
+ day = int(string[6:8])
+ #tz = str[8]
+ hour = int(string[9:11])
+ minute = int(string[11:13])
+ second = int(string[13:15])
+ milli = int(string[15:18])
+ self.calendar = datetime(year, month, day, hour, minute,
second, milli)
+ return True
+ else:
+ return False
- def getYear(self):
- return self.calendar.year
+ def getYear(self):
+ return self.calendar.year
- def setYear(self,year):
- self.calendar = datetime(year,self.getMonth(),
self.getDay(),self.getHour(),self.getMinutes(),self.getSeconds(),self.getMilliseconds(),self.getTypeDesignator())
+ def setYear(self, year):
+ self.calendar = datetime(year, self.getMonth(), self.getDay(),
self.getHour(), self.getMinutes(), self.getSeconds(),
self.getMilliseconds(), self.getTypeDesignator())
- def getMonth(self):
- return self.calendar.month
+ def getMonth(self):
+ return self.calendar.month
- def setMonth(self,month):
- self.calendar = datetime(self.calendar.year,month,
self.calendar.day,self.calendar.hour,self.calendar.minute,self.calendar.second,self.calendar.microsecond,self.calendar.tzinfo)
-
- def getDay(self):
- return self.calendar.day
+ def setMonth(self, month):
+ self.calendar = datetime(self.calendar.year, month,
self.calendar.day, self.calendar.hour, self.calendar.minute,
self.calendar.second, self.calendar.microsecond, self.calendar.tzinfo)
- def setDay(self,day):
- self.calendar =
datetime(self.calendar.year,self.calendar.month,day,self.calendar.hour,self.calendar.minute,self.calendar.second,self.calendar.microsecond,self.calendar.tzinfo)
+ def getDay(self):
+ return self.calendar.day
+
+ def setDay(self, day):
+ self.calendar = datetime(self.calendar.year, self.calendar.month,
day, self.calendar.hour, self.calendar.minute, self.calendar.second,
self.calendar.microsecond, self.calendar.tzinfo)
+
+ def getHour(self):
+ return self.calendar.hour
+
+ def setHour(self, hour):
+ self.calendar = datetime(self.calendar.year, self.calendar.month,
self.calendar.day, hour, self.calendar.minute, self.calendar.second,
self.calendar.microsecond, self.calendar.tzinfo)
+
+ def getMinutes(self):
+ return self.calendar.minute
+
+ def setMinutes(self, minute):
+ self.calendar = datetime(self.calendar.year, self.calendar.month,
self.calendar.day, self.calendar.hour, minute, self.calendar.second,
self.calendar.microsecond, self.calendar.tzinfo)
- def getHour(self):
- return self.calendar.hour
-
- def setHour(self,hour):
- self.calendar = datetime(self.calendar.year,self.calendar.month,
self.calendar.day,hour,self.calendar.minute,self.calendar.second,self.calendar.microsecond,self.calendar.tzinfo)
+ def getSeconds(self):
+ return self.calendar.second
- def getMinutes(self):
- return self.calendar.minute
-
- def setMinutes(self,minute):
- self.calendar = datetime(self.calendar.year,self.calendar.month,
self.calendar.day,self.calendar.hour,minute,self.calendar.second,self.calendar.microsecond,self.calendar.tzinfo)
+ def setSeconds(self, second):
+ self.calendar = datetime(self.calendar.year, self.calendar.month,
self.calendar.day, self.calendar.hour, self.calendar.minute, second,
self.calendar.microsecond, self.calendar.tzinfo)
- def getSeconds(self):
- return self.calendar.second
+ def getMilliseconds(self):
+ return self.calendar.microsecond
- def setSeconds(self,second):
- self.calendar = datetime(self.calendar.year,self.calendar.month,
self.calendar.day,self.calendar.hour,self.calendar.minute,second,self.calendar.microsecond,self.calendar.tzinfo)
+ def setMilliseconds(self, milli):
+ self.calendar = datetime(self.calendar.year, self.calendar.month,
self.calendar.day, self.calendar.hour, self.calendar.minute,
self.calendat.second, microsecond, self.calendar.tzinfo)
- def getMilliseconds(self):
- return self.calendar.microsecond
+ def getTypeDesignator(self):
+ return self.calendar.tzinfo
- def setMilliseconds(self,milli):
- self.calendar = datetime(self.calendar.year,self.calendar.month,
self.calendar.day,self.calendar.hour,self.calendar.minute,self.calendat.second,microsecond,self.calendar.tzinfo)
+ def setTypeDesignator(self, tzinfo):
+ #self.calendar = datetime(self.calendar.year,self.calendar.month,
self.calendar.day,self.calendar.hour,self.calendar.minute,self.calendat.second,self.calendar.microsecond,tzinfo)
+ pass
- def getTypeDesignator(self):
- return self.calendar.tzinfo
+ def paddedInt(self, size, val):
+ res = str(val)
+ while len(res) < size:
+ res = '0' + res
+ return str(res)
- def setTypeDesignator(self,tzinfo):
- #self.calendar = datetime(self.calendar.year,self.calendar.month,
self.calendar.day,self.calendar.hour,self.calendar.minute,self.calendat.second,self.calendar.microsecond,tzinfo)
- pass
+ def __str__(self):
+ """
+ returns a printable version of the object
+ """
+ str_date = str(self.getYear()) + self.paddedInt(2,
self.getMonth()) + self.paddedInt(2, self.getDay()) + "T"
+ str_date = str_date + str(self.paddedInt(2, self.getHour()))
+ str_date = str_date + str(self.paddedInt(2, self.getMinutes())) +
str(self.paddedInt(2, self.getSeconds())) + str(self.paddedInt(3,
self.getMilliseconds()))
- def paddedInt( self, size, val ):
- res = str(val)
- while len(res) < size:
- res = '0' + res
- return str(res)
+ return str_date
- def __str__(self):
- """
- returns a printable version of the object
- """
- str_date = str(self.getYear()) + self.paddedInt(2,self.getMonth()) +
self.paddedInt(2,self.getDay())+"T"
- str_date = str_date + str(self.paddedInt(2,self.getHour()))
- str_date = str_date + str(self.paddedInt(2,self.getMinutes())) +
str(self.paddedInt(2,self.getSeconds())) +
str(self.paddedInt(3,self.getMilliseconds()))
-
- return str_date;
+ def getTime(self):
+ """
+ returns a printable version of the object
+ """
+ return self.__str__()
- def getTime(self):
- """
- returns a printable version of the object
- """
- return self.__str__()
-
- def getDate(self):
- """
- returns a printable version of the object
- """
- return self.__str__()
-
-
+ def getDate(self):
+ """
+ returns a printable version of the object
+ """
+ return self.__str__()
=======================================
--- /trunk/spade/Behaviour.py Wed Nov 16 08:33:39 2011
+++ /trunk/spade/Behaviour.py Fri Nov 23 05:19:16 2012
@@ -1,4 +1,4 @@
-# -*- coding: UTF8 -*-
+# -*- coding: utf-8 -*-
import time
import ACLMessage
import MessageReceiver
@@ -18,16 +18,17 @@
"""
Template operators
"""
-
+
def __init__(self, regex=False):
- self.regex=regex
-
+ self.regex = regex
+
def match(self, message):
return False
def __and__(self, other):
"""Implementation of & operator"""
return ANDTemplate(self, other)
+
def __rand__(self, other):
"""Implementation of &= operator"""
return (self & other)
@@ -35,6 +36,7 @@
def __or__(self, other):
"""Implementation of | operator"""
return ORTemplate(self, other)
+
def __ror__(self, other):
"""Implementation of |= operator"""
return (self | other)
@@ -42,9 +44,11 @@
def __xor__(self, other):
"""Implementation of ^ operator"""
return XORTemplate(self, other)
+
def __rxor__(self, other):
"""Implementation of ^= operator"""
return (self ^ other)
+
def __invert__(self):
"""Implementation of ~ operator"""
return NOTTemplate(self)
@@ -69,9 +73,9 @@
self.protocol = None
self.conversation_id = None
#self.userDefProps = None
-
+
def __str__(self):
- return
str({"performative":self.performative,"sender":str(self.sender),"receivers":str(self.receivers),"reply_to":self.reply_to, "content":self.content,"reply_with":self.reply_with, "reply_by":self.reply_by, "in_reply_to":self.in_reply_to,"encoding":self.encoding, "language":self.language, "ontology":self.ontology,"protocol":self.protocol, "conversation_id":self.conversation_id})
+ return str({"performative": self.performative, "sender":
str(self.sender), "receivers": str(self.receivers), "reply_to":
self.reply_to, "content": self.content, "reply_with":
self.reply_with, "reply_by": self.reply_by, "in_reply_to":
self.in_reply_to, "encoding": self.encoding, "language":
self.language, "ontology": self.ontology, "protocol":
self.protocol, "conversation_id": self.conversation_id})
def reset(self):
self.__init__()
@@ -92,9 +96,8 @@
def getReceivers(self):
return self.receivers
-
def addReplyTo(self, re):
- if isinstance(re,AID.aid):
+ if isinstance(re, AID.aid):
self.reply_to.append(re)
def removeReplyTo(self, re):
@@ -110,13 +113,13 @@
def getPerformative(self):
return self.performative
- def setContent(self,c):
+ def setContent(self, c):
self.content = c
def getContent(self):
return self.content
- def setReplyWith(self,rw):
+ def setReplyWith(self, rw):
self.reply_with = rw
def getReplyWith(self):
@@ -128,34 +131,37 @@
def getInReplyTo(self):
return self.in_reply_to
- def setEncoding(self,e):
+ def setEncoding(self, e):
self.encoding = e
def getEncoding(self):
return self.encoding
- def setLanguage(self,e):
+ def setLanguage(self, e):
self.language = e
def getLanguage(self):
return self.language
- def setOntology(self,e):
+
+ def setOntology(self, e):
self.ontology = e
def getOntology(self):
return self.ontology
- def setReplyBy(self,e):
+
+ def setReplyBy(self, e):
self.reply_by = e
def getReplyBy(self):
return self.reply_by
- def setProtocol(self,e):
+ def setProtocol(self, e):
self.protocol = e
def getProtocol(self):
return self.protocol
- def setConversationId(self,e):
+
+ def setConversationId(self, e):
self.conversation_id = e
def getConversationId(self):
@@ -165,27 +171,34 @@
class NOTTemplate(BehaviourTemplate):
def __init__(self, expr):
self.expr = expr
+
def match(self, message):
return (not(self.expr.match(message)))
+
class ORTemplate(BehaviourTemplate):
def __init__(self, expr1, expr2):
self.expr1 = expr1
self.expr2 = expr2
+
def match(self, message):
return (self.expr1.match(message) | self.expr2.match(message))
+
class ANDTemplate(BehaviourTemplate):
def __init__(self, expr1, expr2):
self.expr1 = expr1
self.expr2 = expr2
+
def match(self, message):
return (self.expr1.match(message) & self.expr2.match(message))
+
class XORTemplate(BehaviourTemplate):
def __init__(self, expr1, expr2):
self.expr1 = expr1
self.expr2 = expr2
+
def match(self, message):
return (self.expr1.match(message) ^ self.expr2.match(message))
@@ -204,7 +217,7 @@
def __init__(self, Template, regex=False):
# Discriminate Template class
BehaviourTemplate.__init__(self, regex)
- if type(Template) == types.InstanceType:
+ if isinstance(Template, types.InstanceType):
if Template.__class__ == ACLTemplate:
self.match = self.acl_match
else:
@@ -213,135 +226,139 @@
self.template = copy.copy(Template)
-
def acl_match(self, message):
-# print "acl_match called with \n +Template:" + str(self.template)
+ "\n +Messange: " + str(message)
- if message.__class__ != ACLMessage.ACLMessage: return False
- if (self.template.getPerformative() != None):
- if (self.template.getPerformative() !=
message.getPerformative()): return False
- if (self.template.getConversationId() != None):
+ if message.__class__ != ACLMessage.ACLMessage:
+ return False
+ if (self.template.getPerformative() is not None):
+ if (self.template.getPerformative() !=
message.getPerformative()):
+ return False
+ if (self.template.getConversationId() is not None):
if (str(self.template.getConversationId()) !=
str(message.getConversationId())):
return False
- if (self.template.sender != None):
- if not message.sender.match(self.template.sender): return False
+ if (self.template.sender is not None):
+ if not message.sender.match(self.template.sender):
+ return False
if (self.template.receivers != []):
for tr in self.template.receivers:
- found=False
+ found = False
for mr in message.receivers:
- if mr.match(tr): found=True
- break
- if not found: return False
+ if mr.match(tr):
+ found = True
+ break
+ if not found:
+ return False
if (self.template.getReplyTo() != []):
- if (self.template.getReplyTo() != message.getReplyTo()):
return False
- if (self.template.content != None):
- if (self.template.content != message.content): return False
- if (self.template.getReplyWith() != None):
- if (self.template.getReplyWith() != message.getReplyWith()):
return False
- if (self.template.getReplyBy() != None):
- if (self.template.getReplyBy() != message.getReplyBy()):
return False
- if (self.template.getInReplyTo() != None):
- if (self.template.getInReplyTo() != message.getInReplyTo()):
return False
- if (self.template.getEncoding() != None):
- if (self.template.getEncoding() != message.getEncoding()):
return False
- if (self.template.getLanguage() != None):
- if (self.template.getLanguage() != message.getLanguage()):
return False
- if (self.template.getOntology() != None):
- if (self.template.getOntology() != message.getOntology()):
return False
- if (self.template.getProtocol() != None):
- if (self.template.getProtocol() != message.getProtocol()):
return False
+ if (self.template.getReplyTo() != message.getReplyTo()):
+ return False
+ if (self.template.content is not None):
+ if (self.template.content != message.content):
+ return False
+ if (self.template.getReplyWith() is not None):
+ if (self.template.getReplyWith() != message.getReplyWith()):
+ return False
+ if (self.template.getReplyBy() is not None):
+ if (self.template.getReplyBy() != message.getReplyBy()):
+ return False
+ if (self.template.getInReplyTo() is not None):
+ if (self.template.getInReplyTo() != message.getInReplyTo()):
+ return False
+ if (self.template.getEncoding() is not None):
+ if (self.template.getEncoding() != message.getEncoding()):
+ return False
+ if (self.template.getLanguage() is not None):
+ if (self.template.getLanguage() != message.getLanguage()):
+ return False
+ if (self.template.getOntology() is not None):
+ if (self.template.getOntology() != message.getOntology()):
+ return False
+ if (self.template.getProtocol() is not None):
+ if (self.template.getProtocol() != message.getProtocol()):
+ return False
return True
-
def node_match(self, other):
"""
Function that matches a xmpp Node with another one
"""
-# print "node_match called with \n %s \n AND\n %s" %
(str(self.template), str(other))
try:
# Check types and classes
- if type(self.template) != types.InstanceType:
-# print "node_match: First node not an instance"
+ if not isinstance(self.template, types.InstanceType):
return False
#if not issubclass(self.template.__class__, Node) and not
issubclass(self.template.__class__, Protocol) and :
if "Message" not in str(self.template.__class__)
and "Presence" not in str(self.template.__class__) and "Iq" not in
str(self.template.__class__) and "Node" not in str(self.template.__class__):
-# print "node_match: First node not a node:",
str(self.template.__class__)
return False
- if type(other) != types.InstanceType:
-# print "node_match: Second node not an instance"
+ if not isinstance(other, types.InstanceType):
return False
#if not issubclass(other.__class__ , Node):
if "Message" not in str(other.__class__) and "Presence" not in
str(other.__class__) and "Iq" not in str(other.__class__) and "Node" not in
str(self.template.__class__):
-# print "node_match: Second node not a node"
return False
- if
self.template.name != None:
+ if
self.template.name is not None:
if
self.template.name !=
other.name:
-# print "node_match: Different names: ",
str(
self.template.name), str(
other.name)
return False
- if self.template.attrs != None and self.template.attrs != {}:
-# for i in self.template.attrs.items():
-# if i not in other.attrs.items():
- for i,j in self.template.attrs.items():
-# print "****Comparing: i=%s (%s),%s (%s),other=%s
(%s)" % (i,type(i),j,type(j),other.attrs[i],type(other.attrs[i]))
- if (i,j) not in (other.attrs.items()): # not in
other.attrs.items():
-# print "node_match: Different attrs:",
str(self.template.attrs), str(other.attrs)
+ if self.template.attrs is not None and self.template.attrs !=
{}:
+ for i, j in self.template.attrs.items():
+ if (i, j) not in (other.attrs.items()): # not in
other.attrs.items():
if not self.regex:
return False
- if not re.match(str(j),str(other.attrs[i])):
+ if not re.match(str(j), str(other.attrs[i])):
return False
- if self.template.data != None and self.template.data != []:
+ if self.template.data is not None and self.template.data != []:
if self.template.data != other.data:
-# print "node_match: Different data:",
str(self.template.data), str(other.data),
re.match(str(self.template.data),str(other.data))
- if not self.regex:
- return False
- if not
re.match(str(self.template.data[0]),str(other.data[0])):
- return False
-# print "node_match: Matched regex:",
str(self.template.data), str(other.data),
re.match(str(self.template.data),str(other.data))
-
+ if not self.regex:
+ return False
+ if not re.match(str(self.template.data[0]),
str(other.data[0])):
+ return False
if self.template.namespace:
if self.template.namespace != other.namespace:
-# print "node_match: Different namespace:",
str(self.template.namespace), str(other.namespace)
- return False
+ return False
for kid in self.template.kids:
# Assemble a list of similar kids from the other node
suspects = other.getTags(kid.getName())
- if not suspects: return False
+ if not suspects:
+ return False
value = False
for s in suspects:
- value =
MessageTemplate(kid,regex=self.regex).node_match(s)
+ value = MessageTemplate(kid,
regex=self.regex).node_match(s)
#value = self.node_match(kid, s)
- if value == True:
- # There is a match among the supects
+ if value is True:
+ # There is a match among the supects
break
if not value:
# If we reach this point, there is no hope left . . .
(no match among the suspects)
return False
except Exception, e:
-# print "Exception in node_match:", e
+ #print "Exception in node_match:", e
return False
# Arriving here means this is a perfect match
return True
- def presence_match(self, message): #frm=None, type=None, status=None,
show=None):
+ def presence_match(self, message): # frm=None, type=None,
status=None, show=None):
- frm,type,status,show,role,affiliation =
message.frm,message.type,message.status,message.show,message.role,message.affiliation
+ frm, type, status, show, role, affiliation = message.frm,
message.type, message.status, message.show, message.role,
message.affiliation
#if self._frm !=None and frm != self._frm: return False
- if self._type !=None and type != self._type:
return False
- if self._status !=None and status != self._status:
return False
- if self._show !=None and show != self._show:
return False
- if self._role !=None and role != self._role:
return False
- if self._affiliation != None and affiliation != self._affiliation:
return False
+ if self._type is not None and type != self._type:
+ return False
+ if self._status is not None and status != self._status:
+ return False
+ if self._show is not None and show != self._show:
+ return False
+ if self._role is not None and role != self._role:
+ return False
+ if self._affiliation is not None and affiliation !=
self._affiliation:
+ return False
if self._frm:
if not JID(self._frm).getResource():
if self._frm != JID(frm).getBareJID():
return False
else:
- if self._frm != frm: return False
+ if self._frm != frm:
+ return False
return True
@@ -352,9 +369,6 @@
return self.node_match(iq)
-
-
-
class Behaviour(MessageReceiver.MessageReceiver):
def __init__(self):
MessageReceiver.MessageReceiver.__init__(self)
@@ -363,7 +377,7 @@
self._forceKill = threading.Event()
self._presenceHandlers = dict()
- self._exitcode = 0
+ self._exitcode = 0
"""
def __getattr__(self, aname):
@@ -381,10 +395,15 @@
self.__dict__[aname] = value
"""
+ def __str__(self):
+ return self.getName()
+
def setParent(self, parent):
self.myParent = parent
+
def getParent(self):
return self.myParent
+
def setAgent(self, agent):
"""
sets the agent which controls the behavior
@@ -392,7 +411,7 @@
self.myAgent = agent
self.DEBUG = self.myAgent.DEBUG
try:
- self.setName(str(self.myAgent.getName()) + " Behaviour")
+ self.setName(str(self.myAgent.getName()) + " " +
str(self.__class__.__name__))
except:
pass
@@ -401,8 +420,9 @@
returns the agent which controls the behavior
"""
return self.myAgent
+
def root(self):
- if (self.myParent != None):
+ if (self.myParent is not None):
return self.myParent.root()
else:
return self
@@ -427,20 +447,23 @@
"""
try:
self._forceKill.set()
+ self.myAgent.DEBUG("Stoping Behavior " + str(self), "info")
except:
#Behavior is already dead
- self.myAgent.DEBUG("Behavior " +str(self)+ " is already
dead","warn/")
+ self.myAgent.DEBUG("Behavior " + str(self) + " is already
dead", "warn")
def onStart(self):
"""
this method runs when the behavior starts
"""
pass
+
def onEnd(self):
"""
this method runs when the behavior stops
"""
pass
+
def exitCode(self):
"""
returns the default exit code for the behavior
@@ -466,15 +489,17 @@
try:
while (not self.done()) and (not self._forceKill.isSet()):
self._exitcode = self._process()
- except Exception,e:
- self.myAgent.DEBUG("Exception in
Behaviour "+str(self)+": "+str(e), "err")
+ except Exception, e:
+ self.myAgent.DEBUG("Exception in Behaviour " + str(self)
+ ": " + str(e), "err")
self.onEnd()
#if issubclass(self.__class__, EventBehaviour):
# self.myAgent.removeBehaviour(self.__class__)
#else:
if not issubclass(self.__class__, EventBehaviour):
self.myAgent.removeBehaviour(self)
-
+
+ self.myAgent.DEBUG("Behavior " + str(self.getName()) + "
finished.", "info")
+
def registerPresenceHandler(self, template, handler):
"""
DEPRECATED
@@ -488,14 +513,14 @@
manage a FIPA-formed presence message
"""
class struct:
- def __init__(self,frm,type,status,show,role,affiliation):
-
self.frm,self.type,self.status,self.show,self.role,self.affiliation=frm,type,status,show,role,affiliation
+ def __init__(self, frm, type, status, show, role, affiliation):
+ self.frm, self.type, self.status, self.show, self.role,
self.affiliation = frm, type, status, show, role, affiliation
# Check every handler template to see which ones match
for handler in self._presenceHandlers:
t = self._presenceHandlers[handler]
if t:
- if t.match(struct(frm,type,status,show,role,affiliation)):
- handler(frm,type,status,show,role,affiliation)
+ if t.match(struct(frm, type, status, show, role,
affiliation)):
+ handler(frm, type, status, show, role, affiliation)
def setTemplate(self, template):
"""
@@ -512,29 +537,29 @@
def __init__(self):
Behaviour.__init__(self)
self._firsttime = True
+
def done(self):
- if (self._firsttime == True):
+ if self._firsttime is True:
self._firsttime = False
return False
return True
-
-
class PeriodicBehaviour(Behaviour):
"""
this behavior runs periodically with a period
"""
- def __init__(self, period, timestart = None):
+ def __init__(self, period, timestart=None):
Behaviour.__init__(self)
self._period = period
- if (timestart == None):
+ if (timestart is None):
self._nextActivation = time.time()
else:
self._nextActivation = timestart
def getPeriod(self):
return self._period
+
def setPeriod(self, period):
self._period = period
@@ -547,7 +572,7 @@
t = self._nextActivation - time.time()
if t > 0:
time.sleep(t)
- return self._exitcode
+ return self._exitcode
def _onTick(self):
"""
@@ -562,21 +587,23 @@
this behavior is executed only once after a timeout
"""
def __init__(self, timeout):
- PeriodicBehaviour.__init__(self, timeout, time.time()+timeout)
+ PeriodicBehaviour.__init__(self, timeout, time.time() + timeout)
self._stop = False
def getTimeOut(self):
return self.getPeriod()
+
def stop(self):
"""
cancels the programmed execution
"""
self._stop = True
+
def done(self):
return self._stop
def _onTick(self):
- if (self._stop == False):
+ if self._stop is False:
self.timeOut()
self.stop()
@@ -588,9 +615,6 @@
raise NotImplementedError
-
-
-
class FSMBehaviour(Behaviour):
"""
this behavior is executed according to a Finite State Machine
@@ -622,8 +646,8 @@
if not issubclass(behaviour.__class__, OneShotBehaviour):
print "WARNING! Registering not-OneShot as FSM state"
behaviour.setParent(self)
- self._states[name]=behaviour
- self._transitions[name]=dict()
+ self._states[name] = behaviour
+ self._transitions[name] = dict()
behaviour._receive = self._receive
behaviour.setTemplate = self.setTemplate
behaviour._stateName = name
@@ -665,16 +689,17 @@
def done(self):
if self._actualState in self._lastStatesNames:
- if self._firsttime == True:
+ if self._firsttime is True:
# The first time "done" is called while in a final state,
return False
# The next time, return True
self._firsttime = False
return False
else:
return True
- else: return False
+ else:
+ return False
- def _transitionTo(self,newState):
+ def _transitionTo(self, newState):
try:
b = self._states[self._actualState]
b.onEnd()
@@ -688,24 +713,22 @@
pass
def _process(self):
- if (self._actualState == None):
+ if (self._actualState is None):
self._transitionTo(self._firstStateName)
#msg = self._receive(False)
b = self._states[self._actualState]
#if msg: buede .postMessage(msg)
self._lastexitcode = b._process()
if (b.done() or b._forceKill.isSet()):
- if not self._lastexitcode: self._lastexitcode = b.exitCode()
+ if not self._lastexitcode:
+ self._lastexitcode = b.exitCode()
self._transitionTo(self._transitions[b._stateName][self._lastexitcode])
self._lastexitcode = None
-
def getCurrentState(self):
return self._states[self._actualState]
-
-
class EventBehaviour(OneShotBehaviour):
"""
A behaviour that is executed in response to a certain event.
@@ -715,20 +738,16 @@
the template arrives. This can be changed by setting 'onetime'
to True, which renders the behaviour for one use only
"""
- #onetime = False
- def __init__(self, onetime=False):
+ def __init__(self, onetime=False):
OneShotBehaviour.__init__(self)
self.onetime = onetime
- #def run(self):
-
-
-
if __name__ == "__main__":
class TestBehaviour(PeriodicBehaviour):
def __init__(self, time):
PeriodicBehaviour.__init__(self, time)
+
def _onTick(self):
print "Tick: " + str(time.time())
=======================================
--- /trunk/spade/DF.py Tue Jul 31 06:58:54 2012
+++ /trunk/spade/DF.py Fri Nov 23 05:19:16 2012
@@ -1,5 +1,4 @@
-
-# encoding: utf-8
+# -*- coding: utf-8 -*-
from Agent import PlatformAgent
import AID
@@ -11,6 +10,7 @@
import copy
import thread
+
class DF(PlatformAgent):
"""
Directory Facilitator Agent
@@ -25,7 +25,7 @@
def _process(self):
error = False
msg = self._receive(True)
- if msg != None:
+ if msg is not None:
if msg.getPerformative().lower() == 'request':
if msg.getOntology().lower()
== "fipa-agent-management":
if msg.getLanguage().lower() == "fipa-sl0":
@@ -37,25 +37,24 @@
if "action" in content:
if "register" in content.action
or "deregister" in content.action:
-
self.myAgent.addBehaviour(DF.RegisterBehaviour(msg,content), template)
- self.myAgent.DEBUG("Received REGISTER
action: "+str(content))
+
self.myAgent.addBehaviour(DF.RegisterBehaviour(msg, content), template)
+ self.myAgent.DEBUG("Received REGISTER
action: " + str(content))
elif "search" in content.action:
-
self.myAgent.addBehaviour(DF.SearchBehaviour(msg,content), template)
- self.myAgent.DEBUG("Received SEARCH
action: "+str(content))
+
self.myAgent.addBehaviour(DF.SearchBehaviour(msg, content), template)
+ self.myAgent.DEBUG("Received SEARCH
action: " + str(content))
elif "modify" in content.action:
-
self.myAgent.addBehaviour(DF.ModifyBehaviour(msg,content), template)
- self.myAgent.DEBUG("Received MODIFY
action: "+str(content))
+
self.myAgent.addBehaviour(DF.ModifyBehaviour(msg, content), template)
+ self.myAgent.DEBUG("Received MODIFY
action: " + str(content))
else:
reply = msg.createReply()
reply.setSender(self.myAgent.getAID())
reply.setPerformative("refuse")
- reply.setContent("( "+msg.getContent()
+"(unsuported-function "+ content.keys()[0] +"))")
+ reply.setContent("( " + msg.getContent()
+ "(unsuported-function " + content.keys()[0] + "))")
self.myAgent.send(reply)
- self.myAgent.DEBUG("Received message with
no action. Refusing: "+str(content),'warn')
+ self.myAgent.DEBUG("Received message with
no action. Refusing: " + str(content), 'warn')
return -1
-
elif "rdf" in msg.getLanguage().lower():
co = msg.getContentObject()
ACLtemplate = Behaviour.ACLTemplate()
@@ -63,49 +62,48 @@
#ACLtemplate.setSender(msg.getSender())
template =
(Behaviour.MessageTemplate(ACLtemplate))
- if co and co.has_key("fipa:action") and
co["fipa:action"].has_key("fipa:act"):
- if co["fipa:action"]["fipa:act"] in
["register","deregister"]:
-
self.myAgent.addBehaviour(DF.RegisterBehaviour(msg,co), template)
- self.myAgent.DEBUG("Received REGISTER
action: "+str(co))
+ if co and "fipa:action" in co.keys()
and "fipa:act" in co["fipa:action"].keys():
+ if co["fipa:action"]["fipa:act"] in
["register", "deregister"]:
+
self.myAgent.addBehaviour(DF.RegisterBehaviour(msg, co), template)
+ self.myAgent.DEBUG("Received REGISTER
action: " + str(co))
elif co["fipa:action"]["fipa:act"]
== "search":
-
self.myAgent.addBehaviour(DF.SearchBehaviour(msg,co), template)
- self.myAgent.DEBUG("Received SEARCH
action: "+str(co))
+
self.myAgent.addBehaviour(DF.SearchBehaviour(msg, co), template)
+ self.myAgent.DEBUG("Received SEARCH
action: " + str(co))
elif co["fipa:action"]["fipa:act"]
== "modify":
-
self.myAgent.addBehaviour(DF.ModifyBehaviour(msg,co), template)
- self.myAgent.DEBUG("Received MODIFY
action: "+str(co))
+
self.myAgent.addBehaviour(DF.ModifyBehaviour(msg, co), template)
+ self.myAgent.DEBUG("Received MODIFY
action: " + str(co))
else:
reply = msg.createReply()
reply.setSender(self.myAgent.getAID())
reply.setPerformative("refuse")
- co2 =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ co2 =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
co2["unsuported-function"] =
co["fipa:action"]["fipa:act"]
reply.setContentObject(co2)
self.myAgent.send(reply)
- self.myAgent.DEBUG("Received message
with no action. Refusing: "+str(co),'warn')
+ self.myAgent.DEBUG("Received message
with no action. Refusing: " + str(co), 'warn')
return -1
+ else:
+ error = "(unsupported-language " +
msg.getLanguage() + ")"
+ else:
+ error = "(unsupported-ontology " +
msg.getOntology() + ")"
- else: error
= "(unsupported-language "+msg.getLanguage()+")"
- else: error
= "(unsupported-ontology "+msg.getOntology()+")"
-
-
- elif msg.getPerformative().lower() not in
['failure','refuse']:
+ elif msg.getPerformative().lower() not in
['failure', 'refuse']:
error = "(unsupported-act " +
msg.getPerformative() + ")"
if error:
reply = msg.createReply()
reply.setSender(self.myAgent.getAID())
reply.setPerformative("not-understood")
- reply.setContent("( "+msg.getContent() + error+")")
+ reply.setContent("( " + msg.getContent() + error + ")")
self.myAgent.send(reply)
- self.myAgent.DEBUG("NOT-UNDERSTOOD: Could not process
message. Error is:"+str(error),'error')
+ self.myAgent.DEBUG("NOT-UNDERSTOOD: Could not process
message. Error is:" + str(error), 'error')
return -1
#TODO: delete old services
-
class RegisterBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,msg,content):
+ def __init__(self, msg, content):
Behaviour.OneShotBehaviour.__init__(self)
self.msg = msg
self.content = content
@@ -122,16 +120,15 @@
dad =
DfAgentDescription(self.content.action.register['df-agent-description'])
else:
dad =
DfAgentDescription(self.content.action.deregister['df-agent-description'])
- except KeyError: #Exception,err:
+ except KeyError: # Exception,err:
error = "(missing-argument df-agent-description)"
- self.myAgent.DEBUG("REFUSE: Register Behaviour could
not extract DfAgentDescription "+error,'error')
-
+ self.myAgent.DEBUG("REFUSE: Register Behaviour could
not extract DfAgentDescription " + error, 'error')
if error:
reply = self.msg.createReply()
reply.setSender(self.myAgent.getAID())
reply.setPerformative("refuse")
- reply.setContent("( "+self.msg.getContent() + error
+ ")")
+ reply.setContent("( " + self.msg.getContent() + error
+ ")")
self.myAgent.send(reply)
return -1
@@ -143,76 +140,72 @@
reply.setContent("(" + str(self.msg.getContent()) + "
true)")
self.myAgent.send(reply)
+ if self.content.action == "register":
- if self.content.action == "register":
-
- if not
self.myAgent.servicedb.has_key(dad.getAID().getName()):
+ if dad.getAID().getName() not in
self.myAgent.servicedb.keys():
self.myAgent.db_mutex.acquire()
self.myAgent.servicedb[dad.getAID().getName()] =
dad
self.myAgent.db_mutex.release()
else:
- #check if already-registered
+ #check if already-registered
for ss in dad.getServices():
found = False
- for s in
self.myAgent.servicedb[dad.getAID().getName()].getServices():
+ for s in
self.myAgent.servicedb[dad.getAID().getName()].getServices():
if s.match(ss):
- found=True
+ found = True
if found:
reply.setPerformative("failure")
- reply.setContent("("+self.msg.getContent()
+ "(already-registered))")
+ reply.setContent("(" +
self.msg.getContent() + "(already-registered))")
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: Service was
already registered! Could not register "+str(dad),'warn')
+ self.myAgent.DEBUG("FAILURE: Service was
already registered! Could not register " + str(dad), 'warn')
return -1
-
try:
for s in dad.getServices():
self.myAgent.db_mutex.acquire()
self.myAgent.servicedb[dad.getAID().getName()].addService(s)
self.myAgent.db_mutex.release()
- self.myAgent.DEBUG("Service successfully
registered: "+str(s),'ok')
+ self.myAgent.DEBUG("Service successfully
registered: " + str(s), 'ok')
except Exception, err:
reply.setPerformative("failure")
- reply.setContent("("+self.msg.getContent()
+ "(internal-error))")
+ reply.setContent("(" + self.msg.getContent()
+ "(internal-error))")
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: Service could not
be registered: "+str(err),'error')
+ self.myAgent.DEBUG("FAILURE: Service could not
be registered: " + str(err), 'error')
return -1
-
- self.DEBUG("Service succesfully deregistered: "+
str(dad),'ok')
+ self.DEBUG("Service succesfully deregistered: " +
str(dad), 'ok')
reply.setPerformative("inform")
- reply.setContent("(done "+self.msg.getContent() + ")")
+ reply.setContent("(done " + self.msg.getContent()
+ ")")
self.myAgent.send(reply)
-
+
#publish event
s = Service(dad=dad).asContentObject()
node = xmpp.Node(node=str(s))
- self.myAgent.publishEvent("DF:Service:Register",node)
+ self.myAgent.publishEvent("DF:Service:Register", node)
return 1
-
elif self.content.action == "deregister":
-
- if not
self.myAgent.servicedb.has_key(dad.getAID().getName()):
+
+ if dad.getAID().getName() not in
self.myAgent.servicedb.keys():
reply.setPerformative("failure")
- reply.setContent("("+self.msg.getContent()
+ "(not-registered))")
+ reply.setContent("(" + self.msg.getContent()
+ "(not-registered))")
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: Agent has no
registered services! Could not deregister "+str(dad),'warn')
+ self.myAgent.DEBUG("FAILURE: Agent has no
registered services! Could not deregister " + str(dad), 'warn')
return -1
-
- #check if service is not registered
+
+ #check if service is not registered
for ss in dad.getServices():
- found=False
+ found = False
for s in
self.myAgent.servicedb[dad.getAID().getName()].getServices():
if s.match(ss):
found = True
if not found:
reply.setPerformative("failure")
- reply.setContent("("+self.msg.getContent()
+ "(not-registered))")
+ reply.setContent("(" + self.msg.getContent()
+ "(not-registered))")
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: Service is not
registered! Could not deregister "+str(dad),'warn')
- return -1
+ self.myAgent.DEBUG("FAILURE: Service is not
registered! Could not deregister " + str(dad), 'warn')
+ return -1
try:
services =
copy.copy(self.myAgent.servicedb[dad.getAID().getName()])
@@ -229,37 +222,36 @@
self.myAgent.db_mutex.release()
except Exception, err:
reply.setPerformative("failure")
- reply.setContent("("+self.msg.getContent()
+ '(internal-error "could not deregister service"))')
+ reply.setContent("(" + self.msg.getContent()
+ '(internal-error "could not deregister service"))')
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: Service could not be
deregistered: "+str(err),'error')
+ self.myAgent.DEBUG("FAILURE: Service could not be
deregistered: " + str(err), 'error')
return -1
- self.DEBUG("Service succesfully deregistered: "+
str(dad),'ok')
+ self.DEBUG("Service succesfully deregistered: " +
str(dad), 'ok')
reply.setPerformative("inform")
- reply.setContent("(done "+self.msg.getContent() + ")")
+ reply.setContent("(done " + self.msg.getContent()
+ ")")
self.myAgent.send(reply)
#publish event
s = Service(dad=dad).asContentObject()
node = xmpp.Node(node=str(s))
- self.myAgent.publishEvent("DF:Service:UnRegister",node)
+ self.myAgent.publishEvent("DF:Service:UnRegister",
node)
return 1
-
elif "rdf" in self.msg.getLanguage():
# Content in RDF/XML (ContentObject capable)
rdf = True
co_error = None
try:
co = self.msg.getContentObject()
- self.myAgent.DEBUG("Content processed "+str(co),'info')
- dad = DfAgentDescription(co = co.action.argument)
- self.myAgent.DEBUG("DfAgentDescription
extracted "+str(dad.asRDFXML()),'info')
- except KeyboardInterrupt,err:
- co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ self.myAgent.DEBUG("Content processed " +
str(co), 'info')
+ dad = DfAgentDescription(co=co.action.argument)
+ self.myAgent.DEBUG("DfAgentDescription extracted " +
str(dad.asRDFXML()), 'info')
+ except KeyboardInterrupt, err:
+ co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
co_error["fipa:error"] = "missing-argument
df-agent-description"
- self.myAgent.DEBUG("REFUSE: "+str(co_error)
+ ": "+str(err),'error')
+ self.myAgent.DEBUG("REFUSE: " + str(co_error) + ": " +
str(err), 'error')
if co_error:
reply = self.msg.createReply()
@@ -278,91 +270,89 @@
self.myAgent.send(reply)
if co["fipa:action"]["fipa:act"] == "register":
- if not
self.myAgent.servicedb.has_key(dad.getAID().getName()):
+ if dad.getAID().getName() not in
self.myAgent.servicedb.keys():
self.myAgent.db_mutex.acquire()
self.myAgent.servicedb[dad.getAID().getName()] =
dad
self.myAgent.db_mutex.release()
else:
- #check if already-registered
+ #check if already-registered
for ss in dad.getServices():
found = False
- for s in
self.myAgent.servicedb[dad.getAID().getName()].getServices():
+ for s in
self.myAgent.servicedb[dad.getAID().getName()].getServices():
if s.match(ss):
- found=True
+ found = True
break
if found:
reply.setPerformative("failure")
- co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
co_error["fipa:error"]
= "already-registered"
reply.setContentObject(co_error)
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: Service
already registered! ",'warn')
+ self.myAgent.DEBUG("FAILURE: Service
already registered! ", 'warn')
return -1
-
try:
for s in dad.getServices():
self.myAgent.db_mutex.acquire()
self.myAgent.servicedb[dad.getAID().getName()].addService(s)
self.myAgent.db_mutex.release()
- self.myAgent.DEBUG("Service successfully
registered: "+str(s),'ok')
+ self.myAgent.DEBUG("Service successfully
registered: " + str(s), 'ok')
except Exception, err:
reply.setPerformative("failure")
- co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
co_error["fipa:error"] = "internal-error"
reply.setContentObject(co_error)
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: Service could not
be registered: "+str(err),'error')
+ self.myAgent.DEBUG("FAILURE: Service could not
be registered: " + str(err), 'error')
return -1
-
- self.DEBUG("Service succesfully registered: "+
str(dad),'ok')
+ self.DEBUG("Service succesfully registered: " +
str(dad), 'ok')
reply.setPerformative("inform")
- co_rep =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ co_rep =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
co_rep["fipa:done"] = "true"
reply.setContentObject(co_rep)
self.myAgent.send(reply)
#publish event
- self.myAgent.DEBUG("Publishing Event: "+str(dad))
+ self.myAgent.DEBUG("Publishing Event: " + str(dad))
s = Service(dad=dad).asContentObject()
node = xmpp.Node(node=str(s))
- self.myAgent.publishEvent("DF:Service:Register",node)
-
+ self.myAgent.publishEvent("DF:Service:Register", node)
+
return 1
elif co["fipa:action"]["fipa:act"] == "deregister":
- if not
self.myAgent.servicedb.has_key(dad.getAID().getName()):
+ if dad.getAID().getName() not in
self.myAgent.servicedb.keys():
reply.setPerformative("failure")
- co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
co_error["fipa:error"] = 'not-registered'
reply.setContentObject(co_error)
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: Agent has no
registered services",'warn')
+ self.myAgent.DEBUG("FAILURE: Agent has no
registered services", 'warn')
return -1
-
- #check if service is not registered
+
+ #check if service is not registered
for ss in dad.getServices():
- found=False
+ found = False
for s in
self.myAgent.servicedb[dad.getAID().getName()].getServices():
if s.match(ss):
found = True
if not found:
reply.setPerformative("failure")
- co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
co_error["fipa:error"] = 'not-registered'
reply.setContentObject(co_error)
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: Service is not
registered! Could not deregister "+str(dad),'warn')
- return -1
+ self.myAgent.DEBUG("FAILURE: Service is not
registered! Could not deregister " + str(dad), 'warn')
+ return -1
try:
services =
copy.copy(self.myAgent.servicedb[dad.getAID().getName()])
- self.myAgent.DEBUG("Deregistering "+str(services)
+ " AND " + str(dad.getServices()))
+ self.myAgent.DEBUG("Deregistering " +
str(services) + " AND " + str(dad.getServices()))
if dad.getServices() == []:
self.myAgent.db_mutex.acquire()
del
self.myAgent.servicedb[dad.getAID().getName()]
- self.DEBUG("Deleting all agent entries: " +
str(not self.myAgent.servicedb.has_key(dad.getAID().getName())))
+ self.DEBUG("Deleting all agent entries: " +
str(dad.getAID().getName() not in self.myAgent.servicedb.keys()))
self.myAgent.db_mutex.release()
else:
for ss in dad.getServices():
@@ -373,16 +363,16 @@
self.myAgent.db_mutex.release()
except Exception, err:
reply.setPerformative("failure")
- co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
co_error["fipa:error"] = 'internal-error "could
not deregister service"'
reply.setContentObject(co_error)
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: internal-error 'could
not deregister service': "+str(err),'error')
+ self.myAgent.DEBUG("FAILURE: internal-error 'could
not deregister service': " + str(err), 'error')
return -1
- self.DEBUG("Service succesfully deregistered: "+
str(dad),'ok')
+ self.DEBUG("Service succesfully deregistered: " +
str(dad), 'ok')
reply.setPerformative("inform")
- co_rep =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ co_rep =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
co_rep["fipa:done"] = "true"
reply.setContentObject(co_rep)
self.myAgent.send(reply)
@@ -390,15 +380,13 @@
#publish event
s = Service(dad=dad).asContentObject()
node = xmpp.Node(node=str(s))
- self.myAgent.publishEvent("DF:Service:UnRegister",node)
-
+ self.myAgent.publishEvent("DF:Service:UnRegister",
node)
+
return 1
-
-
class SearchBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,msg,content):
+ def __init__(self, msg, content):
Behaviour.OneShotBehaviour.__init__(self)
self.msg = msg
self.content = content
@@ -426,34 +414,33 @@
max = int(max_str)
except Exception, err:
error = '(internal-error "max-results is not
an integer")'
- self.myAgent.DEBUG("FAILURE:
internal-error 'max-results is not an integer' "+str(err),'error')
+ self.myAgent.DEBUG("FAILURE:
internal-error 'max-results is not an integer' " + str(err), 'error')
if error:
reply = self.msg.createReply()
reply.setSender(self.myAgent.getAID())
reply.setPerformative("failure")
- reply.setContent("( "+self.msg.getContent() +
error+")")
+ reply.setContent("( " + self.msg.getContent() + error
+ ")")
self.myAgent.send(reply)
return -1
-
result = []
if "df-agent-description" in self.content.action.search:
try:
dad =
DfAgentDescription(self.content.action.search["df-agent-description"])
except Exception, err:
- self.myAgent.DEBUG("FAILURE: Could not extract
DfAgentDescription from content: "+str(err),'error')
+ self.myAgent.DEBUG("FAILURE: Could not extract
DfAgentDescription from content: " + str(err), 'error')
self.myAgent.db_mutex.acquire()
if max in [-1, 0]:
# No limit
- for agentid,dads in self.myAgent.servicedb.items():
+ for agentid, dads in self.myAgent.servicedb.items():
if dads.match(dad):
d = copy.copy(dads)
if dad.services == []:
d.services = dads.getServices()
else:
- d.services=[]
+ d.services = []
for ss in dad.getServices():
for s in dads.getServices():
if s.match(ss):
@@ -461,25 +448,26 @@
result.append(d)
else:
max = abs(max)
- for agentid,dads in self.myAgent.servicedb.items():
+ for agentid, dads in self.myAgent.servicedb.items():
if max >= 0:
if dads.match(dad):
d = copy.copy(dads)
if dad.services == []:
d.services = dads.getServices()
else:
- d.services=[]
+ d.services = []
for ss in dad.getServices():
for s in dads.getServices():
if s.match(ss):
d.addService(s)
result.append(d)
max -= 1
- else: break
+ else:
+ break
self.myAgent.db_mutex.release()
content = "((result " +
self.msg.getContent().strip("\n")[1:-1]
- if len(result)>0:
+ if len(result) > 0:
content += " (sequence "
for i in result:
content += str(i) + " "
@@ -487,10 +475,9 @@
else:
pass
content += "))"
- self.myAgent.DEBUG("Found " +str(len(result)) + "
services",'ok')
+ self.myAgent.DEBUG("Found " + str(len(result)) + "
services", 'ok')
for d in result:
- self.myAgent.DEBUG(str(d),'ok')
-
+ self.myAgent.DEBUG(str(d), 'ok')
reply.setPerformative("inform")
reply.setContent(content)
@@ -503,7 +490,7 @@
return 1
else:
- # Content is in RDF/XML
+ # Content is in RDF/XML
max = 50
if self.content.action.argument.max_results:
try:
@@ -511,7 +498,7 @@
max = int(max_str)
except Exception, err:
# Ignoring the exception
- self.myAgent.DEBUG("FAILURE: (internal-error)
max-results is not an integer! ",'error')
+ self.myAgent.DEBUG("FAILURE: (internal-error)
max-results is not an integer! ", 'error')
#co_error = ContentObject()
#co_error["error"] = '(internal-error "max-results
is not an integer")'
@@ -519,22 +506,22 @@
if self.content.action.argument.df_agent_description:
try:
- dad = DfAgentDescription(co =
self.content.action.argument.df_agent_description)
- self.myAgent.DEBUG("Searching for: " +str(dad)
+ " in ServiceDB: " + str(map(lambda s: str(s),
self.myAgent.servicedb.values())) )
+ dad =
DfAgentDescription(co=self.content.action.argument.df_agent_description)
+ self.myAgent.DEBUG("Searching for: " +
str(dad) + " in ServiceDB: " + str(map(lambda s: str(s),
self.myAgent.servicedb.values())))
except Exception, err:
- self.myAgent.DEBUG("FAILURE: Could not extract
DfAgentDescription from content: "+str(err),'error')
-
+ self.myAgent.DEBUG("FAILURE: Could not extract
DfAgentDescription from content: " + str(err), 'error')
+
self.myAgent.db_mutex.acquire()
if max in [-1, 0]:
# No limit
- for agentid,dads in
self.myAgent.servicedb.items():
- self.myAgent.DEBUG("Comparing " + str(dad)
+ " WITH " + str(dads) + " ==> " + str(dads.match(dad)),'ok')
+ for agentid, dads in
self.myAgent.servicedb.items():
+ self.myAgent.DEBUG("Comparing " + str(dad)
+ " WITH " + str(dads) + " ==> " + str(dads.match(dad)), 'ok')
if dads.match(dad):
d = copy.copy(dads)
if dad.services == []:
d.services = dads.getServices()
else:
- d.services=[]
+ d.services = []
for ss in dad.getServices():
for s in dads.getServices():
if s.match(ss):
@@ -542,29 +529,30 @@
result.append(d)
else:
max = abs(max)
- for agentid,dads in
self.myAgent.servicedb.items():
+ for agentid, dads in
self.myAgent.servicedb.items():
if max >= 0:
if dads.match(dad):
d = copy.copy(dads)
if dad.services == []:
d.services = dads.getServices()
else:
- d.services=[]
+ d.services = []
for ss in dad.getServices():
for s in dads.getServices():
if s.match(ss):
d.addService(s)
result.append(d)
max -= 1
- else: break
+ else:
+ break
self.myAgent.db_mutex.release()
- content =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ content =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
content["fipa:result"] = []
for i in result:
content["fipa:result"].append(i.asContentObject())
- self.myAgent.DEBUG(str(i),'ok')
- self.myAgent.DEBUG("Found "+str(len(result)) + "
services.",'ok')
+ self.myAgent.DEBUG(str(i), 'ok')
+ self.myAgent.DEBUG("Found " + str(len(result)) + "
services.", 'ok')
reply.setPerformative("inform")
reply.setContentObject(content)
self.myAgent.send(reply)
@@ -575,11 +563,9 @@
return 1
-
-
class ModifyBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,msg,content):
+ def __init__(self, msg, content):
Behaviour.OneShotBehaviour.__init__(self)
self.msg = msg
self.content = content
@@ -594,9 +580,9 @@
try:
co = self.msg.getContentObject()
- dad = DfAgentDescription(co = co.action.argument)
- except KeyboardInterrupt,err:
- co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ dad = DfAgentDescription(co=co.action.argument)
+ except KeyboardInterrupt, err:
+ co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
co_error["fipa:error"] = "missing-argument
df-agent-description"
reply = self.msg.createReply()
@@ -604,11 +590,11 @@
reply.setPerformative("refuse")
reply.setContentObject(co_error)
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: Could not extract
DfAgentDescription from content: "+str(err),'error')
+ self.myAgent.DEBUG("FAILURE: Could not extract
DfAgentDescription from content: " + str(err), 'error')
return -1
if dad and (dad.getAID().getName() !=
self.msg.getSender().getName()):
- co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
co_error["fipa:error"] = "unauthorised"
if co_error:
@@ -617,11 +603,10 @@
reply.setPerformative("refuse")
reply.setContentObject(co_error)
self.myAgent.send(reply)
-
self.myAgent.DEBUG("FAILURE: "+self.msg.getSender().getName()+" is
UNAUTHORISED to modify service "+str(dad),'warn')
+ self.myAgent.DEBUG("FAILURE: " +
self.msg.getSender().getName() + " is UNAUTHORISED to modify service " +
str(dad), 'warn')
return -1
-
reply = self.msg.createReply()
reply.setSender(self.myAgent.getAID())
reply.setPerformative("agree")
@@ -629,33 +614,30 @@
co["fipa:done"] = "true"
reply.setContentObject(co)
self.myAgent.send(reply)
-
- if self.myAgent.servicedb.has_key(dad.getAID().getName()):
+ if dad.getAID().getName() in self.myAgent.servicedb.keys():
try:
for ss in dad.getServices():
self.myAgent.db_mutex.acquire()
-
result=self.myAgent.servicedb[dad.getAID().getName()].updateService(ss)
+ result =
self.myAgent.servicedb[dad.getAID().getName()].updateService(ss)
self.myAgent.db_mutex.release()
if not result:
reply.setPerformative("failure")
- co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
co_error["fipa:error"] = "not-registered"
reply.setContentObject(co_error)
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: Could not
modify service "+str(ss)+". Service is NOT registered.",'warn')
+ self.myAgent.DEBUG("FAILURE: Could not
modify service " + str(ss) + ". Service is NOT registered.", 'warn')
except Exception, err:
reply.setPerformative("failure")
- co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
co_error["fipa:error"] = "internal-error"
reply.setContentObject(co_error)
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE:
internal-error: "+str(err),'error')
+ self.myAgent.DEBUG("FAILURE: internal-error: " +
str(err), 'error')
return -1
-
-
reply.setPerformative("inform")
co = self.msg.getContentObject()
co["fipa:done"] = "true"
@@ -666,30 +648,30 @@
else:
reply.setPerformative("failure")
- co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ co_error =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
co_error["fipa:error"] = "not-registered"
reply.setContentObject(co_error)
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: Could not modify
service "+str(dad)+". Agent has no registered services.",'warn')
+ self.myAgent.DEBUG("FAILURE: Could not modify
service " + str(dad) + ". Agent has no registered services.", 'warn')
return -1
else:
#language is sl-0
try:
dad =
DF.DfAgentDescription(self.content.action.modify[0][1])
- except Exception,err:
+ except Exception, err:
error = "(missing-argument ams-agent-description)"
- self.myAgent.DEBUG("FAILURE: Could not extract
DfAgentDescription from content: "+str(err),'error')
+ self.myAgent.DEBUG("FAILURE: Could not extract
DfAgentDescription from content: " + str(err), 'error')
if dad and (dad.getAID().getName() !=
self.msg.getSender().getName()):
error = "(unauthorised)"
-
self.myAgent.DEBUG("REFUSE: "+self.msg.getSender().getName()+" is not
AUTHORISED to modify service "+str(dad),'warn')
+ self.myAgent.DEBUG("REFUSE: " +
self.msg.getSender().getName() + " is not AUTHORISED to modify service " +
str(dad), 'warn')
if error:
reply = self.msg.createReply()
reply.setSender(self.myAgent.getAID())
reply.setPerformative("refuse")
- reply.setContent("( "+self.msg.getContent() + error
+ ")")
+ reply.setContent("( " + self.msg.getContent() + error
+ ")")
self.myAgent.send(reply)
return -1
@@ -702,43 +684,40 @@
reply.setContent("(" + str(self.msg.getContent()) + "
true)")
self.myAgent.send(reply)
- if self.myAgent.servicedb.has_key(dad.getAID().getName()):
+ if dad.getAID().getName() in self.myAgent.servicedb.keys():
try:
for ss in dad.getServices():
self.myAgent.db_mutex.acquire()
-
result=self.myAgent.servicedb[dad.getAID().getName()].updateService(ss)
+ result =
self.myAgent.servicedb[dad.getAID().getName()].updateService(ss)
self.myAgent.db_mutex.release()
if not result:
reply.setPerformative("failure")
- reply.setContent("("+self.msg.getContent()
+ "(not-registered))")
+ reply.setContent("(" +
self.msg.getContent() + "(not-registered))")
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: Could not
modify service "+str(ss)+". Service is NOT registered.",'warn')
+ self.myAgent.DEBUG("FAILURE: Could not
modify service " + str(ss) + ". Service is NOT registered.", 'warn')
except Exception, err:
reply.setPerformative("failure")
- reply.setContent("("+self.msg.getContent()
+ "(internal-error))")
+ reply.setContent("(" + self.msg.getContent()
+ "(internal-error))")
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: (internal-error)
Modifying service: "+str(err),'error')
+ self.myAgent.DEBUG("FAILURE: (internal-error)
Modifying service: " + str(err), 'error')
return -1
-
-
reply.setPerformative("inform")
- reply.setContent("(done "+self.msg.getContent() + ")")
+ reply.setContent("(done " + self.msg.getContent()
+ ")")
self.myAgent.send(reply)
return 1
else:
reply.setPerformative("failure")
- reply.setContent("("+self.msg.getContent()
+ "(not-registered))")
+ reply.setContent("(" + self.msg.getContent()
+ "(not-registered))")
self.myAgent.send(reply)
- self.myAgent.DEBUG("FAILURE: Could not modify
service "+str(dad)+". Agent has no registered services.",'warn')
+ self.myAgent.DEBUG("FAILURE: Could not modify
service " + str(dad) + ". Agent has no registered services.", 'warn')
return -1
-
- def __init__(self,node,passw,server="localhost",port=5347, config={}):
- PlatformAgent.__init__(self,node,passw,server,port, config)
+ def __init__(self, node, passw, server="localhost", port=5347,
config={}):
+ PlatformAgent.__init__(self, node, passw, server, port, config)
#self.addAddress("http://"+self.getDomain()+":2099/acc") #Â HACK
def _setup(self):
@@ -753,8 +732,8 @@
mt.setOntology("FIPA-Agent-Management")
mt.setPerformative("request")
mt.setProtocol('fipa-request')
- self.addBehaviour(db,Behaviour.MessageTemplate(mt))
-
+ self.addBehaviour(db, Behaviour.MessageTemplate(mt))
+
#create service events
self.createEvent("DF:Service:Register")
self.createEvent("DF:Service:UnRegister")
@@ -762,7 +741,7 @@
class DfAgentDescription:
- def __init__(self, content = None, co = None):
+ def __init__(self, content=None, co=None):
#
self.name = AID.aid()
self.name = None
self.services = []
@@ -776,21 +755,21 @@
self.loadSL0(content)
if co:
- if co.has_key("df-agent-description"):
+ if "df-agent-description" in co.keys():
co = co["df-agent-description"]
if
co.name:
-
self.name = AID.aid(co =
co.name)
+
self.name = AID.aid(co=
co.name)
if co.services:
self.services = []
if "ContentObject" in str(type(co.services)):
- self.services.append(ServiceDescription(co =
co.services))
+
self.services.append(ServiceDescription(co=co.services))
else:
# List
for s in co.services:
- self.services.append(ServiceDescription(co = s))
+ self.services.append(ServiceDescription(co=s))
if co.lease_time:
self.lease_time = co.lease_time
- if co.has_key("lease-time"):
+ if "lease-time" in co.keys():
self.lease_time = co["lease-time"]
if co.protocols:
self.protocols = copy.copy(co.protocols)
@@ -801,12 +780,11 @@
if co.scope:
self.scope = copy.copy(co.scope)
-
def asContentObject(self):
"""
Returns a version of the DAD in ContentObject format
"""
- co =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ co =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
if
self.name:
co["name"] = self.name.asContentObject()
else:
@@ -825,10 +803,9 @@
co["languages"] = copy.copy(self.languages)
if self.scope:
co["scope"] = copy.copy(self.scope)
-
+
return co
-
def asRDFXML(self):
"""
returns a printable version of the DAD in RDF/XML format
@@ -837,11 +814,12 @@
def getAID(self):
return
self.name
-
+
def getName(self):
- if
self.name != None:
+ if
self.name is not None:
return self.name.getName()
- else: return AID.aid()
+ else:
+ return AID.aid()
def setAID(self, a):
self.name = a
@@ -855,50 +833,62 @@
assert not ss.match(s)
self.services.append(s)
for p in s.getProtocols():
- if p not in self.protocols: self.addProtocol(p)
+ if p not in self.protocols:
+ self.addProtocol(p)
for o in s.getOntologies():
- if o not in self.ontologies: self.addOntologies(o)
+ if o not in self.ontologies:
+ self.addOntologies(o)
for l in s.getLanguages():
- if l not in self.languages: self.addLanguage(l)
-
- def delService(self,s):
- index=None
+ if l not in self.languages:
+ self.addLanguage(l)
+
+ def delService(self, s):
+ index = None
for i in range(len(self.services)):
if self.services[i].match(s):
index = i
break
- if index!=None: self.services.pop(i)
- else: return False
+ if index is not None:
+ self.services.pop(i)
+ else:
+ return False
for p in s.getProtocols():
if p in self.protocols:
self.protocols.remove(p)
for p in s.getOntologies():
- if p in self.ontologies: self.ontologies.remove(p)
+ if p in self.ontologies:
+ self.ontologies.remove(p)
for p in s.getLanguages():
- if p in self.languages: self.languages.remove(p)
+ if p in self.languages:
+ self.languages.remove(p)
return True
-
- def updateService(self,s):
+
+ def updateService(self, s):
found = False
for ss in self.services:
if s.getName() == ss.getName():
found = True
- if s.getType(): ss.setType(s.getType())
- if s.getProtocols():
+ if s.getType():
+ ss.setType(s.getType())
+ if s.getProtocols():
ss.protocols = s.getProtocols()
for p in s.getProtocols():
- if p not in self.protocols: self.addProtocol(p)
+ if p not in self.protocols:
+ self.addProtocol(p)
if s.getOntologies():
ss.ontologies = s.getOntologies()
for o in s.getOntologies():
- if o not in self.ontologies: self.addOntologies(o)
+ if o not in self.ontologies:
+ self.addOntologies(o)
if s.getLanguages():
ss.languages = s.getLanguages()
for l in s.getLanguages():
- if l not in self.languages: self.addLanguage(l)
- if s.getOwnership(): ss.setOwnership(s.getOwnership())
- for k,v in s.getProperties().items():
- ss.addProperty(k,v)
+ if l not in self.languages:
+ self.addLanguage(l)
+ if s.getOwnership():
+ ss.setOwnership(s.getOwnership())
+ for k, v in s.getProperties().items():
+ ss.addProperty(k, v)
return found
def getProtocols(self):
@@ -935,7 +925,7 @@
self.scope = s
#def __eq__(self,y):
- def match(self,y):
+ def match(self, y):
if
y.name:
if not self.getAID().match(
y.name):
@@ -959,31 +949,32 @@
if self.scope != y.getScope():
return False
- if len(self.services)>0 and len(y.getServices())>0:
+ if len(self.services) > 0 and len(y.getServices()) > 0:
for i in y.services:
matched = False
for j in self.getServices():
#if i == j:
if j.match(i):
***The diff for this file has been truncated for email.***
=======================================
--- /trunk/spade/ECLiPSeKB.py Tue Jul 10 16:56:02 2012
+++ /trunk/spade/ECLiPSeKB.py Fri Nov 23 05:19:16 2012
@@ -1,48 +1,49 @@
+# -*- coding: utf-8 -*-
from logic import KB
from pyxf import eclipse
-class ECLiPSeKB( KB ):
- '''ECLiPSe Prolog knowledge base'''
- def __init__( self, sentence=None, path='eclipse' ):
- '''Constructor method
- Usage: ECLiPSeKB( sentence, path )
- sentence - Prolog sentence to be added to the KB (default: None)
- path - path to ECLiPSe Prolog executable (default: 'eclipse')'''
- self.eclipse = eclipse( path )
- if sentence:
- self.tell( sentence )
- def tell( self, sentence ):
- '''Adds sentence to KB'''
- sentence = sentence.strip()
- if sentence[ -1 ] == '.':
- sentence = sentence[ :-1 ]
- return self.eclipse.query( 'assert(' + sentence + ')' )
+class ECLiPSeKB(KB):
+ '''ECLiPSe Prolog knowledge base'''
+ def __init__(self, sentence=None, path='eclipse'):
+ '''Constructor method
+ Usage: ECLiPSeKB( sentence, path )
+ sentence - Prolog sentence to be added to the KB (default: None)
+ path - path to ECLiPSe Prolog executable (default: 'eclipse')'''
+ self.eclipse = eclipse(path)
+ if sentence:
+ self.tell(sentence)
- def ask( self, query ):
- '''Queries the KB'''
- return self.eclipse.query( query )
+ def tell(self, sentence):
+ '''Adds sentence to KB'''
+ sentence = sentence.strip()
+ if sentence[-1] == '.':
+ sentence = sentence[:-1]
+ return self.eclipse.query('assert(' + sentence + ')')
+
+ def ask(self, query):
+ '''Queries the KB'''
+ return self.eclipse.query(query)
+
+ def retract(self, sentence):
+ '''Deletes sentence from KB'''
+ sentence = sentence.strip()
+ if sentence[-1] == '.':
+ sentence = sentence[:-1]
+ return self.eclipse.query('retract(' + sentence + ')')
- def retract( self, sentence ):
- '''Deletes sentence from KB'''
- sentence = sentence.strip()
- if sentence[ -1 ] == '.':
- sentence = sentence[ :-1 ]
- return self.eclipse.query( 'retract(' + sentence + ')' )
+ def loadModule(self, module):
+ '''Loads module to KB
+ Usage: instance.loadModule( path )
+ path - path to module'''
+ self.eclipse.load(module)
- def loadModule( self, module ):
- '''Loads module to KB
- Usage: instance.loadModule( path )
- path - path to module'''
- self.eclipse.load( module )
-
if __name__ == '__main__':
- kb = ECLiPSeKB()
- kb.tell( 'a(b,c)' )
- kb.tell( 'a(c,d)' )
- kb.tell( '( p(_X,_Y) :- a(_X,_Y) )' )
- kb.tell( '( p(_X,_Y) :- a(_X,_Z), p(_Z,_Y) )' )
- for result in kb.ask( 'p(X,Y)' ):
- print result
- kb.retract( 'a(b,c)' )
-
+ kb = ECLiPSeKB()
+ kb.tell('a(b,c)')
+ kb.tell('a(c,d)')
+ kb.tell('( p(_X,_Y) :- a(_X,_Y) )')
+ kb.tell('( p(_X,_Y) :- a(_X,_Z), p(_Z,_Y) )')
+ for result in kb.ask('p(X,Y)'):
+ print result
+ kb.retract('a(b,c)')
=======================================
--- /trunk/spade/Envelope.py Fri Nov 9 09:51:22 2012
+++ /trunk/spade/Envelope.py Fri Nov 23 05:19:16 2012
@@ -1,287 +1,289 @@
+# -*- coding: utf-8 -*-
import types
import AID
import json
+
class Envelope:
"""
FIPA envelope
"""
- def
__init__(self,to=None,_from=None,comments=None,aclRepresentation=None,payloadLength=None,payloadEncoding=None,date=None,encrypted=None,intendedReceiver=None,received=None,transportBehaviour=None,userDefinedProperties=None,
jsonstring=None):
+ def __init__(self, to=None, _from=None, comments=None,
aclRepresentation=None, payloadLength=None, payloadEncoding=None,
date=None, encrypted=None, intendedReceiver=None, received=None,
transportBehaviour=None, userDefinedProperties=None, jsonstring=None):
self.to = list()
- if to != None:
+ if to is not None:
for i in to:
- if isinstance(i,AID.aid):
- self.to.append(i) #aid
+ if isinstance(i, AID.aid):
+ self.to.append(i) # aid
self._from = None
- if _from != None and isinstance(_from,AID.aid):
- self._from = _from #aid
+ if _from is not None and isinstance(_from, AID.aid):
+ self._from = _from # aid
- if comments != None:
- self.comments= comments #str
+ if comments is not None:
+ self.comments = comments # str
else:
self.comments = None
- if aclRepresentation != None:
- self.aclRepresentation = aclRepresentation #str
+ if aclRepresentation is not None:
+ self.aclRepresentation = aclRepresentation # str
else:
self.aclRepresentation = None
- if payloadLength != None:
- self.payloadLength = payloadLength #int
+ if payloadLength is not None:
+ self.payloadLength = payloadLength # int
else:
self.payloadLength = None
- if payloadEncoding != None:
- self.payloadEncoding = payloadEncoding #str
+ if payloadEncoding is not None:
+ self.payloadEncoding = payloadEncoding # str
else:
self.payloadEncoding = None
- if date != None:
- self.date = date #list(datetime)
+ if date is not None:
+ self.date = date # list(datetime)
else:
self.date = None
- if encrypted != None:
- self.encrypted = encrypted #list(str)
+ if encrypted is not None:
+ self.encrypted = encrypted # list(str)
else:
self.encrypted = list()
- if intendedReceiver != None:
- self.intendedReceiver = intendedReceiver #list(aid)
+ if intendedReceiver is not None:
+ self.intendedReceiver = intendedReceiver # list(aid)
else:
self.intendedReceiver = list()
- if received != None:
- self.received = received #list(ReceivedObject)
+ if received is not None:
+ self.received = received # list(ReceivedObject)
else:
self.received = None
- if transportBehaviour != None:
- self.transportBehaviour = transportBehaviour #list(?)
+ if transportBehaviour is not None:
+ self.transportBehaviour = transportBehaviour # list(?)
else:
self.transportBehaviour = list()
- if userDefinedProperties != None:
- self.userDefinedProperties = userDefinedProperties
#list(properties)
+ if userDefinedProperties is not None:
+ self.userDefinedProperties = userDefinedProperties #
list(properties)
else:
self.userDefinedProperties = list()
- if jsonstring: self.loadJSON(jsonstring)
+ if jsonstring:
+ self.loadJSON(jsonstring)
def getTo(self):
return
self.to
- def addTo(self,to):
+ def addTo(self, to):
self.to.append(to)
self.addIntendedReceiver(to)
def getFrom(self):
return self._from
- def setFrom(self,_from):
+ def setFrom(self, _from):
self._from = _from
def getComments(self):
return self.comments
- def setComments(self,comments):
+ def setComments(self, comments):
self.comments = comments
def getAclRepresentation(self):
return self.aclRepresentation
- def setAclRepresentation(self,acl):
+ def setAclRepresentation(self, acl):
self.aclRepresentation = acl
def getPayloadLength(self):
return self.payloadLength
- def setPayloadLength(self,pl):
+ def setPayloadLength(self, pl):
self.payloadLength = pl
def getPayloadEncoding(self):
return self.payloadEncoding
- def setPayloadEncoding(self,pe):
+ def setPayloadEncoding(self, pe):
self.payloadEncoding = pe
def getDate(self):
return self.date
- def setDate(self,date):
+ def setDate(self, date):
self.date = date
def getEncryted(self):
return self.encrypted
- def setEncryted(self,encrypted):
+ def setEncryted(self, encrypted):
self.encrypted = encrypted
def getIntendedReceiver(self):
return self.intendedReceiver
- def addIntendedReceiver(self,intended):
+ def addIntendedReceiver(self, intended):
if not intended in self.intendedReceiver:
self.intendedReceiver.append(intended)
def getReceived(self):
return self.received
- def setReceived(self,received):
+ def setReceived(self, received):
self.received = received
def __str__(self):
return self.asXML()
-
- def asXML(self):
+
+ def asXML(self):
"""
returns a printable version of the envelope in XML
"""
- r = '<?xml version="1.0"?>' +"\n"
- r=r+"\t\t<envelope> \n"
- r=r+'\t\t\t<params index="1">'+"\n"
- r=r+"\t\t\t\t<to>\n"
+ r = '<?xml version="1.0"?>' + "\n"
+ r = r + "\t\t<envelope> \n"
+ r = r + '\t\t\t<params index="1">' + "\n"
+ r = r + "\t\t\t\t<to>\n"
for aid in
self.to:
- r=r+"\t\t\t\t\t<agent-identifier> \n"
- r=r+"\t\t\t\t\t\t<name>" + aid.getName() + "</name> \n"
- r=r+"\t\t\t\t\t\t<addresses>\n"
+ r = r + "\t\t\t\t\t<agent-identifier> \n"
+ r = r + "\t\t\t\t\t\t<name>" + aid.getName() + "</name> \n"
+ r = r + "\t\t\t\t\t\t<addresses>\n"
for addr in aid.getAddresses():
- r=r+ "\t\t\t\t\t\t\t<url>" + addr + "</url>\n"
- r=r+"\t\t\t\t\t\t</addresses> \n"
- r=r+"\t\t\t\t\t</agent-identifier>\n"
- r=r+"\t\t\t\t</to> \n"
+ r = r + "\t\t\t\t\t\t\t<url>" + addr + "</url>\n"
+ r = r + "\t\t\t\t\t\t</addresses> \n"
+ r = r + "\t\t\t\t\t</agent-identifier>\n"
+ r = r + "\t\t\t\t</to> \n"
if self._from:
- r=r+"\t\t\t\t<from> \n"
- r=r+"\t\t\t\t\t<agent-identifier> \n"
- r=r+"\t\t\t\t\t\t<name>" + self._from.getName() + "</name> \n"
- r=r+"\t\t\t\t\t\t<addresses>\n"
+ r = r + "\t\t\t\t<from> \n"
+ r = r + "\t\t\t\t\t<agent-identifier> \n"
+ r = r + "\t\t\t\t\t\t<name>" + self._from.getName() + "</name>
\n"
+ r = r + "\t\t\t\t\t\t<addresses>\n"
for addr in self._from.getAddresses():
- r=r+ "\t\t\t\t\t\t\t<url>" + addr + "</url>\n"
- r=r+"\t\t\t\t\t\t</addresses> \n"
- r=r+"\t\t\t\t\t</agent-identifier> \n"
- r=r+"\t\t\t\t</from>\n"
+ r = r + "\t\t\t\t\t\t\t<url>" + addr + "</url>\n"
+ r = r + "\t\t\t\t\t\t</addresses> \n"
+ r = r + "\t\t\t\t\t</agent-identifier> \n"
+ r = r + "\t\t\t\t</from>\n"
if self.aclRepresentation:
- r=r+ "\t\t\t\t<acl-representation>"+ self.aclRepresentation
+ "</acl-representation>\n"
+ r = r + "\t\t\t\t<acl-representation>" +
self.aclRepresentation + "</acl-representation>\n"
if self.payloadLength:
-
r=r+ "\t\t\t\t<payload-length>"+str(self.payloadLength)+"</payload-length>\n"
+ r = r + "\t\t\t\t<payload-length>" + str(self.payloadLength)
+ "</payload-length>\n"
if self.payloadEncoding:
-
r=r+ "\t\t\t\t<payload-encoding>"+self.payloadEncoding+"</payload-encoding>\n"
+ r = r + "\t\t\t\t<payload-encoding>" + self.payloadEncoding
+ "</payload-encoding>\n"
if self.date:
- r=r+ "\t\t\t\t<date>"+str(self.date)+"</date>\n"
+ r = r + "\t\t\t\t<date>" + str(self.date) + "</date>\n"
if self.intendedReceiver:
- r=r+ "\t\t\t\t<intended-receiver>\n"
+ r = r + "\t\t\t\t<intended-receiver>\n"
for aid in self.intendedReceiver:
- r=r+"\t\t\t\t\t<agent-identifier> \n"
- r=r+"\t\t\t\t\t\t<name>" + aid.getName() + "</name> \n"
- r=r+"\t\t\t\t\t\t<addresses>\n"
+ r = r + "\t\t\t\t\t<agent-identifier> \n"
+ r = r + "\t\t\t\t\t\t<name>" + aid.getName() + "</name> \n"
+ r = r + "\t\t\t\t\t\t<addresses>\n"
for addr in aid.getAddresses():
- r=r+ "\t\t\t\t\t\t\t<url>" + addr + "</url>\n"
- r=r+"\t\t\t\t\t\t</addresses> \n"
- r=r+"\t\t\t\t\t</agent-identifier>\n"
- r=r+"\t\t\t\t</intended-receiver> \n"
+ r = r + "\t\t\t\t\t\t\t<url>" + addr + "</url>\n"
+ r = r + "\t\t\t\t\t\t</addresses> \n"
+ r = r + "\t\t\t\t\t</agent-identifier>\n"
+ r = r + "\t\t\t\t</intended-receiver> \n"
if self.received:
- r=r+ "\t\t\t\t<received>\n"
+ r = r + "\t\t\t\t<received>\n"
if self.received.getBy():
- r=r+ '\t\t\t\t\t<received-by
value="'+self.received.getBy() +'"/>\n'
+ r = r + '\t\t\t\t\t<received-by value="' +
self.received.getBy() + '"/>\n'
if self.received.getDate():
- r=r+ '\t\t\t\t\t<received-date value="'+
str(self.received.getDate()) +'"/>\n'
+ r = r + '\t\t\t\t\t<received-date value="' +
str(self.received.getDate()) + '"/>\n'
if self.received.getId():
- r=r+ '\t\t\t\t\t<received-id value="' +
self.received.getId() +'"/>\n'
- r=r+ "\t\t\t\t</received>\n"
+ r = r + '\t\t\t\t\t<received-id value="' +
self.received.getId() + '"/>\n'
+ r = r + "\t\t\t\t</received>\n"
- r=r+"\t\t\t</params> \n"
- r=r+"\t\t</envelope>\n"
+ r = r + "\t\t\t</params> \n"
+ r = r + "\t\t</envelope>\n"
return r
-
- def asJSON(self):
+ def asJSON(self):
"""
returns a printable version of the envelope in JSON
"""
r = "{"
- r=r+'"to":['
+ r = r + '"to":['
for aid in
self.to:
- r=r+'{'
- r=r+'"name":"' + aid.getName() + '",'
- r=r+'"addresses":['
+ r = r + '{'
+ r = r + '"name":"' + aid.getName() + '",'
+ r = r + '"addresses":['
for addr in aid.getAddresses():
- r=r+ '"' + addr + '",'
- if r[-1:]==",": r = r[:-1]
- r=r+"]"
- r=r+"},"
- if r[-1:]==",": r = r[:-1]
- r=r+"],"
+ r = r + '"' + addr + '",'
+ if r[-1:] == ",": r = r[:-1]
+ r = r + "]"
+ r = r + "},"
+ if r[-1:] == ",": r = r[:-1]
+ r = r + "],"
if self._from:
- r=r+'"from":{'
- r=r+'"name":"' + self._from.getName() + '",'
- r=r+'"addresses":['
+ r = r + '"from":{'
+ r = r + '"name":"' + self._from.getName() + '",'
+ r = r + '"addresses":['
for addr in self._from.getAddresses():
- r=r+ '"' + addr + '",'
- if r[-1:]==",": r = r[:-1]
- r=r+"]},"
+ r = r + '"' + addr + '",'
+ if r[-1:] == ",": r = r[:-1]
+ r = r + "]},"
if self.aclRepresentation:
- r=r+ '"acl-representation":"'+ self.aclRepresentation + '",'
+ r = r + '"acl-representation":"' + self.aclRepresentation
+ '",'
if self.payloadLength:
- r=r+ '"payload-length":"'+str(self.payloadLength)+'",'
+ r = r + '"payload-length":"' + str(self.payloadLength) + '",'
if self.payloadEncoding:
- r=r+ '"payload-encoding":"'+self.payloadEncoding+'",'
+ r = r + '"payload-encoding":"' + self.payloadEncoding + '",'
if self.date:
- r=r+ '"date":"'+str(self.date)+'",'
+ r = r + '"date":"' + str(self.date) + '",'
if self.intendedReceiver:
- r=r+ '"intended-receiver":['
+ r = r + '"intended-receiver":['
for aid in self.intendedReceiver:
- r=r+"{"
- r=r+'"name":"' + aid.getName() + '",'
- r=r+'"addresses":['
+ r = r + "{"
+ r = r + '"name":"' + aid.getName() + '",'
+ r = r + '"addresses":['
for addr in aid.getAddresses():
- r=r+ '"' + addr + '",'
- if r[-1:]==",": r = r[:-1]
- r=r+"],"
- if r[-1:]==",": r = r[:-1]
- r=r+"},"
- if r[-1:]==",": r = r[:-1]
- r=r+"],"
+ r = r + '"' + addr + '",'
+ if r[-1:] == ",": r = r[:-1]
+ r = r + "],"
+ if r[-1:] == ",": r = r[:-1]
+ r = r + "},"
+ if r[-1:] == ",": r = r[:-1]
+ r = r + "],"
if self.received:
- r=r+ '"received":{'
+ r = r + '"received":{'
if self.received.getBy():
- r=r+ '"received-by":"'+self.received.getBy() +'",'
+ r = r + '"received-by":"' + self.received.getBy() + '",'
if self.received.getDate():
- r=r+ '"received-date":"'+ str(self.received.getDate())
+'",'
+ r = r + '"received-date":"' + str(self.received.getDate())
+ '",'
if self.received.getId():
- r=r+ '"received-id":"'+ self.received.getId() +'"'
- if r[-1:]==",": r = r[:-1]
- r=r+ "}"
+ r = r + '"received-id":"' + self.received.getId() + '"'
+ if r[-1:] == ",": r = r[:-1]
+ r = r + "}"
- if r[-1:]==",": r = r[:-1]
- r=r+"}"
+ if r[-1:] == ",": r = r[:-1]
+ r = r + "}"
return r
- def loadJSON(self, jsonstring):
+ def loadJSON(self, jsonstring):
"""
loads a JSON string in the envelope
"""
r = json.loads(jsonstring)
-
- if r.has_key("to"):
+
+ if "to" in r:
for a in r["to"]:
aid = AID.aid()
aid.setName(a["name"])
for addr in a["addresses"]:
aid.addAddress(addr)
self.addTo(aid)
- if r.has_key("from"):
+ if "from" in r:
aid = AID.aid()
aid.setName(r["from"]["name"])
for addr in r["from"]["addresses"]:
aid.addAddress(addr)
self.setFrom(aid)
-
- if r.has_key("acl-representation"):
+
+ if "acl-representation" in r:
self.setAclRepresentation(r["acl-representation"])
- if r.has_key("payload-length"):
+ if "payload-length" in r:
self.setPayloadLength(r["payload-length"])
- if r.has_key("payload-encoding"):
+ if "payload-encoding" in r:
self.setPayloadEncoding(r["payload-encoding"])
- if r.has_key("date"):
+ if "date" in r:
self.setDate(r["date"])
- if r.has_key("intended-receiver"):
+ if "intended-receiver" in r:
for ag in r["intended-receiver"]:
aid = AID.aid()
- aid.setName(ag["name"])
+ aid.setName(ag["name"])
for addr in ag["addresses"]:
- aid.addAddress(addr)
+ aid.addAddress(addr)
self.addIntendedReceiver(aid)
=======================================
--- /trunk/spade/FIPAMessage.py Thu May 22 09:41:47 2008
+++ /trunk/spade/FIPAMessage.py Fri Nov 23 05:19:16 2012
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
class FipaMessage:
"""
@@ -14,4 +15,3 @@
def getBody(self):
return self.__messageBody
-
=======================================
--- /trunk/spade/FlexQueue.py Tue Jul 31 06:58:54 2012
+++ /trunk/spade/FlexQueue.py Fri Nov 23 05:19:16 2012
@@ -1,11 +1,13 @@
+# -*- coding: utf-8 -*-
class FlexQueue(list):
-
+
def empty(self):
- if len(self)==0: return True
+ if len(self) == 0:
+ return True
return False
def qsize(self):
- return len(self)
+ return len(self)
def get(self):
if not self.empty():
@@ -19,4 +21,4 @@
def remove(self, item):
if item in self:
- list.remove(self,item)
+ list.remove(self, item)
=======================================
--- /trunk/spade/Flora2KB.py Tue Jul 10 16:56:02 2012
+++ /trunk/spade/Flora2KB.py Fri Nov 23 05:19:16 2012
@@ -1,54 +1,53 @@
+# -*- coding: utf-8 -*-
from logic import KB
from pyxf import flora2
-class Flora2KB( KB ):
- '''Flora2 knowledge base'''
- def __init__( self, sentence=None, path='runflora' ):
- '''Constructor method
- Usage: Flora2KB( sentence, path )
- sentence - F-logic sentence to be added to the KB (default: None)
- path - path to Flora2 executable (default: 'runflora')'''
- self.flora2 = flora2( path )
- if sentence:
- self.tell( sentence )
- def tell( self, sentence, type='insert' ):
- '''Adds sentence to KB
- Usage: instance.tell( sentence, type )
- sentence - frame logic sentence to be added to KB
- type - insertion type (one of insert, insertall, t_insert,
t_insertall, insertrule, newmodule; default: 'insert')'''
- sentence = sentence.strip()
- if sentence[ -1 ] == '.':
- sentence = sentence[ :-1 ]
- return self.flora2.query( type + '{' + sentence + '}' )
+class Flora2KB(KB):
+ '''Flora2 knowledge base'''
+ def __init__(self, sentence=None, path='runflora'):
+ '''Constructor method
+ Usage: Flora2KB( sentence, path )
+ sentence - F-logic sentence to be added to the KB (default: None)
+ path - path to Flora2 executable (default: 'runflora')'''
+ self.flora2 = flora2(path)
+ if sentence:
+ self.tell(sentence)
- def ask( self, query ):
- '''Queries the KB'''
- return self.flora2.query( query )
+ def tell(self, sentence, type='insert'):
+ '''Adds sentence to KB
+ Usage: instance.tell( sentence, type )
+ sentence - frame logic sentence to be added to KB
+ type - insertion type (one of insert, insertall, t_insert,
t_insertall, insertrule, newmodule; default: 'insert')'''
+ sentence = sentence.strip()
+ if sentence[-1] == '.':
+ sentence = sentence[:-1]
+ return self.flora2.query(type + '{' + sentence + '}')
+
+ def ask(self, query):
+ '''Queries the KB'''
+ return self.flora2.query(query)
- def retract( self, sentence, type='delete' ):
- '''Deletes sentence from KB
- Usage: instance.retract( sentence, type )
- sentence - frame logic sentence to be deleted from KB
- type - deletion type (one of delete, deleteall, erase, eraseall,
t_delete, t_deleteall, t_erase, t_eraseall, deletetrule, erasemodule;
default: 'delete')'''
- sentence = sentence.strip()
- if sentence[ -1 ] == '.':
- sentence = sentence[ :-1 ]
- return self.flora2.query( type + '{' + sentence + '}' )
+ def retract(self, sentence, type='delete'):
+ '''Deletes sentence from KB
+ Usage: instance.retract( sentence, type )
+ sentence - frame logic sentence to be deleted from KB
+ type - deletion type (one of delete, deleteall, erase, eraseall,
t_delete, t_deleteall, t_erase, t_eraseall, deletetrule, erasemodule;
default: 'delete')'''
+ sentence = sentence.strip()
+ if sentence[-1] == '.':
+ sentence = sentence[:-1]
+ return self.flora2.query(type + '{' + sentence + '}')
- def loadModule( self, module ):
- '''Loads module to KB
- Usage: instance.loadModule( path )
- path - path to module'''
- self.flora2.load( module )
+ def loadModule(self, module):
+ '''Loads module to KB
+ Usage: instance.loadModule( path )
+ path - path to module'''
+ self.flora2.load(module)
if __name__ == '__main__':
- kb = Flora2KB()
- kb.tell( 'a[ b->c ]' )
- kb.tell( '( ?x[ c->?y ] :- ?x[ b->?y ] )', 'insertrule' )
- for result in kb.ask( '?x[ ?y->?z ]' ):
- print result
- kb.retract( 'a[ b->c ]' )
-
-
-
+ kb = Flora2KB()
+ kb.tell('a[ b->c ]')
+ kb.tell('( ?x[ c->?y ] :- ?x[ b->?y ] )', 'insertrule')
+ for result in kb.ask('?x[ ?y->?z ]'):
+ print result
+ kb.retract('a[ b->c ]')
=======================================
--- /trunk/spade/MTP.py Fri Nov 9 09:51:22 2012
+++ /trunk/spade/MTP.py Fri Nov 23 05:19:16 2012
@@ -1,9 +1,10 @@
-# encoding: utf-8
+# -*- coding: utf-8 -*-
from spade import SpadeConfigParser
from spade import XMLCodec
from spade import ACLParser
from xmpp import *
+
class MTP:
def __init__(self, name, config, acc):
@@ -17,7 +18,8 @@
try:
self.protocol = self.config.acc.mtp[name].protocol
- except: pass
+ except:
+ pass
#self.instance = self.config.acc.mtp[name].instance
self.setup()
@@ -34,7 +36,6 @@
#raise NotImplemented
pass
-
def dispatch(self, envelope, msg):
# Try to send message through XMPP
#Â If no xmpp address is found, try to come uo with one
@@ -46,7 +47,7 @@
jabber_id = addr
break
if not jabber_id:
- jabber_id = "xmpp://"+str(recv.getName())
+ jabber_id = "xmpp://" + str(recv.getName())
# Figuring out the XMPP address
recv.addAddress(jabber_id)
@@ -71,8 +72,6 @@
# s.push_queue()
"""
-
-
-PROTOCOL = None #This must be overriden
-INSTANCE = None #This must be overriden
+PROTOCOL = None # This must be overriden
+INSTANCE = None # This must be overriden
=======================================
--- /trunk/spade/MessageReceiver.py Thu Jul 12 10:08:45 2007
+++ /trunk/spade/MessageReceiver.py Fri Nov 23 05:19:16 2012
@@ -1,97 +1,120 @@
+# -*- coding: utf-8 -*-
import threading
import sys
from Queue import *
import time
-#from munkware.mwQueue import *
-# Changed to be a 'daemonic' python Thread
class MessageReceiver(threading.Thread):
- def __init__(self):
- try:
- import psyco
- psyco.full()
- except ImportError:
- pass
- threading.Thread.__init__(self)
- self.post_mutex = threading.Lock()
- self.mutex = threading.Lock()
- self.not_empty = threading.Condition(self.mutex)
- self.not_full = threading.Condition(self.mutex)
- self.setDaemon(True)
- #self.__messages = MessageList(0)
- self.__messages = Queue(0)
+ def __init__(self):
+ try:
+ import psyco
+ psyco.full()
+ except ImportError:
+ pass
+ threading.Thread.__init__(self)
+ self.post_mutex = threading.Lock()
+ self.mutex = threading.Lock()
+ self.not_empty = threading.Condition(self.mutex)
+ self.not_full = threading.Condition(self.mutex)
+ self.setDaemon(False)
+ #self.__messages = MessageList(0)
+ self.__messages = Queue(0)
- def __getMessage(self, block, tout):
- try:
- #if block:
- # block_int = 1
- #else:
- # block_int = 0
- #item = self.__messages.get(block_int)#, tout)
- message = self.__messages.get(block, tout)
- #self.__messages.get_commit(item[0])
- #message = item[1]
- #print ">>> __getMessage: SUCCESS "
- except Empty:
- message = None
- #print "MESSAGE = None - Empty "+str(tout)
- #print ">>> __getMessage: EMPTY"
- except:
- message = None
- #time.sleep(1)
- #print "MESSAGE = None - otra.", sys.exc_info()[0]
- #print ">>> __getMessage: FUCKING EXCEPTION"
+ '''def __getMessage(self, block, tout):
+ try:
+ message = self.__messages.get(block, tout)
+ except Empty:
+ message = None
+ #print "MESSAGE = None - Empty "+str(tout)
+ #print ">>> __getMessage: EMPTY"
+ except:
+ message = None
+ #time.sleep(1)
+ #print "MESSAGE = None - otra.", sys.exc_info()[0]
+ #print ">>> __getMessage: FUCKING EXCEPTION"
- return message
- """
- def receive(self):
- #returns a message if available
- #else returns None
- return self.__getMessage(False, None)
- """
- def _receive(self, block = False, timeout = None, template = None):
- """
- waits for a message during timeout
- if timeout == None waits until a message is received
- if no message is received returns None
- """
- #print ">>> blockingReceive time_seg = " + str(time_seg)
- if not template:
- return self.__getMessage(block, timeout)
- else:
- self.not_empty.acquire()
- for msg in self.__messages.queue:
- if template.match(msg):
- self.not_empty.release()
- self.__messages.queue.remove(msg)
- return msg
- self.not_empty.release()
- if not block: return None
- else:
- endtime = time.time()+timeout
- self.not_empty.acquire()
- while True:
- for msg in self.__messages.queue:
- if template.match(msg):
- self.not_empty.release()
- self.__messages.queue.remove(msg)
- return msg
- remaining = endtime - time.time()
- if timeout and remaining <= 0.0:
- self.not_empty.release()
- return None
- self.not_empty.wait(remaining)
+ return message
+ '''
- def postMessage(self, message):
- if (message != None):
- self.post_mutex.acquire()
- #self.__messages.put_commit(self.__messages.put(message,block=True))
- self.not_full.acquire()
- self.__messages.put(message,block=True)
- self.not_empty.notify()
- self.not_full.release()
- #print ">>>>>MSG posteado DE VERDAD: " + str(message.getContent())
- self.post_mutex.release()
- return True
+ def __getMessage(self, block, tout):
+ t_sleep = 0.01
+ message = None
+ if not block:
+ try:
+ message = self.__messages.get_nowait() # (block, tout)
+ except Empty:
+ message = None
+ else:
+ while not self._forceKill.isSet():
+ if tout is not None:
+ t = tout
+ while t > 0.0:
+ try:
+ message = self.__messages.get_nowait()
+ except Empty:
+ message = None
+ if message is not None:
+ return message
+ t -= t_sleep
+ time.sleep(t_sleep)
+ else:
+ try:
+ message = self.__messages.get_nowait()
+ except Empty:
+ message = None
+ if message is not None:
+ return message
+ time.sleep(t_sleep)
+ return message
+
+ """
+ def receive(self):
+ #returns a message if available
+ #else returns None
+ return self.__getMessage(False, None)
+ """
+ def _receive(self, block=False, timeout=None, template=None):
+ """
+ waits for a message during timeout
+ if timeout == None waits until a message is received
+ if no message is received returns None
+ """
+ if not template:
+ return self.__getMessage(block, timeout)
+ else:
+ self.not_empty.acquire()
+ for msg in self.__messages.queue:
+ if template.match(msg):
+ self.not_empty.release()
+ self.__messages.queue.remove(msg)
+ return msg
+ self.not_empty.release()
+ if not block:
+ return None
+ else:
+ endtime = time.time() + timeout
+ self.not_empty.acquire()
+ while True:
+ for msg in self.__messages.queue:
+ if template.match(msg):
+ self.not_empty.release()
+ self.__messages.queue.remove(msg)
+ return msg
+ remaining = endtime - time.time()
+ if timeout and remaining <= 0.0:
+ self.not_empty.release()
+ return None
+ self.not_empty.wait(remaining)
+
+ def postMessage(self, message):
+ if (message is not None):
+ self.post_mutex.acquire()
+
#self.__messages.put_commit(self.__messages.put(message,block=True))
+ self.not_full.acquire()
+ self.__messages.put(message, block=True)
+ self.not_empty.notify()
+ self.not_full.release()
+ self.post_mutex.release()
+ return True
=======================================
--- /trunk/spade/Organization.py Thu Jun 7 01:00:33 2007
+++ /trunk/spade/Organization.py Fri Nov 23 05:19:16 2012
@@ -1,4 +1,4 @@
-# -*- coding: UTF8 -*-
+# -*- coding: utf-8 -*-
import random
import string
@@ -12,936 +12,937 @@
class CreationError(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class NotValidName(CreationError):
def __init__(self):
Exception.__init__(self)
+
+
class NotValidType(CreationError):
def __init__(self):
Exception.__init__(self)
+
+
class NotValidGoal(CreationError):
def __init__(self):
Exception.__init__(self)
+
+
class NotOwner(CreationError):
def __init__(self):
Exception.__init__(self)
+
+
class NotSupervisor(CreationError):
def __init__(self):
Exception.__init__(self)
+
+
class JoinError(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class PaswordNeeded(JoinError):
def __init__(self):
pass
+
+
class MembersOnly(JoinError):
def __init__(self):
Exception.__init__(self)
+
+
class BanedUser(JoinError):
def __init__(self):
Exception.__init__(self)
+
+
class NickNameConflict(JoinError):
def __init__(self):
Exception.__init__(self)
+
+
class MaximumUsers(JoinError):
def __init__(self):
pass
+
+
class LockedOrganization(JoinError):
def __init__(self):
Exception.__init__(self)
+
+
class MemberOfFederation(JoinError):
def __init__(self):
Exception.__init__(self)
+
+
class Unavailable(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class UnavailableFunction(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class DestroyError(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class NotValidUnit(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class LastOwner(Exception):
def __init__(self):
Exception.__init__(self)
+
class Organization(Unit.Unit):
- def __init__(self,agent, nick, name, type=None, goalList=None,
agentList=[], contentLanguage="sl",create=True):
- Behaviour.OneShotBehaviour.__init__(self)
- self.myAgent=agent
-
self.name = name
- self.type = type
- self.goalList = goalList
- self.agentList = agentList
- self.contentLanguage = contentLanguage
- self.ownerList = ownerList
- self.platform = self.myAgent.getSpadePlatformJID()
- self.muc_name = self.myAgent.getMUC()
- self._roster = {}
- self.nick=nick
- self.create=create
- id_base
= "".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)]) #@UnusedVariable
- self.ID = str(name) + str(self.myAgent.getAID().getName()) + id_base
- self.state="unavailable"
- self.UnavailableMsg="Organization"
- self.members=[]
- self.owner_admin=False
+ def __init__(self, agent, nick, name, type=None, goalList=None,
agentList=[], contentLanguage="sl", create=True):
+ Behaviour.OneShotBehaviour.__init__(self)
+ self.myAgent = agent
+
self.name = name
+ self.type = type
+ self.goalList = goalList
+ self.agentList = agentList
+ self.contentLanguage = contentLanguage
+ self.ownerList = ownerList
+ self.platform = self.myAgent.getSpadePlatformJID()
+ self.muc_name = self.myAgent.getMUC()
+ self._roster = {}
+ self.nick = nick
+ self.create = create
+ id_base = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)]) # @UnusedVariable
+ self.ID = str(name) + str(self.myAgent.getAID().getName()) +
id_base
+ self.state = "unavailable"
+ self.UnavailableMsg = "Organization"
+ self.members = []
+ self.owner_admin = False
+ def setup(self):
+ pass
- def setup(self):
- pass
-
- def myCreate(self):
- if not self.checkGoal(self.goalList):
- raise NotValidGoal
- elif not self.checkType():
- raise NotVvalidType
- elif not self.testRoomName():
- raise NotValidName
- elif not self.createRoom():
- raise CreationError
- else:
- self.state="available"
- if self.agentList!=[]:
+ def myCreate(self):
+ if not self.checkGoal(self.goalList):
+ raise NotValidGoal
+ elif not self.checkType():
+ raise NotVvalidType
+ elif not self.testRoomName():
+ raise NotValidName
+ elif not self.createRoom():
+ raise CreationError
+ else:
+ self.state = "available"
+ if self.agentList != []:
#enviando invitaciones
- self.invite(self.agentList)
- #registrando en el DF
- # dad = DF.DfAgentDescription()
- # ds = DF.ServiceDescription()
- # ds.setType("ORGANIZATION")
- # ds.setName(
self.name)
- # dad.setAID(self.myAgent.getAID())
- # dad.addService(ds)
- # res = self.myAgent.registerService(dad)
+ self.invite(self.agentList)
+ #registrando en el DF
+ # dad = DF.DfAgentDescription()
+ # ds = DF.ServiceDescription()
+ # ds.setType("ORGANIZATION")
+ # ds.setName(
self.name)
+ # dad.setAID(self.myAgent.getAID())
+ # dad.addService(ds)
+ # res = self.myAgent.registerService(dad)
- self.owner_admin=True
- p = Presence()
- t = Behaviour.MessageTemplate(p)
-
self.presenceBehaviour=self.PresenceBehaviour(self.muc_name,
self.name,self.nick,self)
- self.myAgent.addBehaviour(self.presenceBehaviour, t)
- if self.type=="Matrix" or self.type=="Federation":
- self.createTeam()
+ self.owner_admin = True
+ p = Presence()
+ t = Behaviour.MessageTemplate(p)
+ self.presenceBehaviour = self.PresenceBehaviour(self.muc_name,
self.name, self.nick, self)
+ self.myAgent.addBehaviour(self.presenceBehaviour, t)
+ if self.type == "Matrix" or self.type == "Federation":
+ self.createTeam()
-
- def myJoin(self):
+ def myJoin(self):
#The Organization exists
- if not self.testOrganizationName():
+ if not self.testOrganizationName():
#The room no existe
- raise NotValidName
- elif not self.myJoinRoom():
- #No es una organizacion
- #raise JoinError
- pass
- else:
- info=self.getInfo()
- if info:
- self.type = info["type"]
- self.contentLanguage = info["contentLanguage"]
- self.parent=info["parent"]
- self.goal=info["goal"]
- self.state="available"
- p = Presence()
- t = Behaviour.MessageTemplate(p)
-
self.presenceBehaviour=self.PresenceBehaviour(self.muc_name,
self.name,self.nick,self)
- self.myAgent.addBehaviour(self.presenceBehaviour, t)
-
-
- def testRoomName(self):
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- iq = Iq(frm=self.muc_name, attrs={"id":ID})
- t = Behaviour.MessageTemplate(iq)
- b=self.TestRoomNameBehaviour(ID,self.muc_name,
self.name)
- self.myAgent.addBehaviour(b, t)
- b.join()
- return b.result
-
-
-
-
+ raise NotValidName
+ elif not self.myJoinRoom():
+ #No es una organizacion
+ #raise JoinError
+ pass
+ else:
+ info = self.getInfo()
+ if info:
+ self.type = info["type"]
+ self.contentLanguage = info["contentLanguage"]
+ self.parent = info["parent"]
+ self.goal = info["goal"]
+ self.state = "available"
+ p = Presence()
+ t = Behaviour.MessageTemplate(p)
+ self.presenceBehaviour = self.PresenceBehaviour(self.muc_name,
self.name, self.nick, self)
+ self.myAgent.addBehaviour(self.presenceBehaviour, t)
+ def testRoomName(self):
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ iq = Iq(frm=self.muc_name, attrs={"id": ID})
+ t = Behaviour.MessageTemplate(iq)
+ b = self.TestRoomNameBehaviour(ID, self.muc_name,
self.name)
+ self.myAgent.addBehaviour(b, t)
+ b.join()
+ return b.result
- class TestRoomNameBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,ID,muc_name,roomname):
+ class TestRoomNameBehaviour(Behaviour.OneShotBehaviour):
+ def __init__(self, ID, muc_name, roomname):
Behaviour.OneShotBehaviour.__init__(self)
- self.ID=ID
+ self.ID = ID
self.result = False
- self.muc_name=muc_name
- self.roomname=roomname
+ self.muc_name = muc_name
+ self.roomname = roomname
def _process(self):
- iq = Iq(to=self.muc_name,typ='get', attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/disco#items")
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
- if msg:
- if query:
- self.result = True
- items = msg.getQueryChildren()
- for item in items:
- if item.getAttr("jid") ==
str(self.roomname+"@"+self.muc_name):
- self.result = False
- else:
- self.result = False
+ iq = Iq(to=self.muc_name, typ='get', attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/disco#items")
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ msg = self._receive(True, 10)
+ if msg:
+ if query:
+ self.result = True
+ items = msg.getQueryChildren()
+ for item in items:
+ if item.getAttr("jid") == str(self.roomname + "@"
+ self.muc_name):
+ self.result = False
+ else:
+ self.result = False
- def testOrganizationName(self):
- info=self.getInfo()
+ def testOrganizationName(self):
+ info = self.getInfo()
if info:
- if info["parent"]=="Organization":
+ if info["parent"] == "Organization":
return True
return False
-
-
-
-
-
-
- def createRoom(self):
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Presence(frm=
self.name+"@"+self.muc_name+"/"+self.nick)
- t1 = Behaviour.MessageTemplate(p)
-
b=self.CreateRoomBehaviour(ID,self.muc_name,
self.name,self.nick,self.contentLanguage,self.type,self.goalList)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
+ def createRoom(self):
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Presence(frm=
self.name + "@" + self.muc_name + "/" + self.nick)
+ t1 = Behaviour.MessageTemplate(p)
+ b = self.CreateRoomBehaviour(ID, self.muc_name,
self.name,
self.nick, self.contentLanguage, self.type, self.goalList)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
- class CreateRoomBehaviour(Behaviour.OneShotBehaviour):
- def
__init__(self,ID,muc_name,roomname,nick,contentLanguage,type,goal):
+ class CreateRoomBehaviour(Behaviour.OneShotBehaviour):
+ def __init__(self, ID, muc_name, roomname, nick, contentLanguage,
type, goal):
Behaviour.OneShotBehaviour.__init__(self)
self.result = False
- self.ID=ID
- self.nick=nick
- self.muc_name=muc_name
-
self.name=roomname
- self.contentLanguage=contentLanguage
- self.type=type
- self.goal=goal
+ self.ID = ID
+ self.nick = nick
+ self.muc_name = muc_name
+
self.name = roomname
+ self.contentLanguage = contentLanguage
+ self.type = type
+ self.goal = goal
def _process(self):
- p = Presence(to=
self.name+"@"+self.muc_name+"/"+self.nick)
+ p = Presence(to=
self.name + "@" + self.muc_name + "/" +
self.nick)
x = Protocol("x", xmlns="
http://jabber.org/protocol/muc")
p.addChild(node=x)
self.myAgent.jabber.send(p)
- msg=self._receive(True,10)
+ msg = self._receive(True, 10)
if msg:
- if msg.getAttr("type")=="error":
+ if msg.getAttr("type") == "error":
print "Room creation is restricted"
- self.result= False
+ self.result = False
return
else:
- self.result= False
- return
- template= Iq(frm=
self.name+"@"+self.muc_name,
attrs={"id":self.ID})
+ self.result = False
+ return
+ template = Iq(frm=
self.name + "@" + self.muc_name,
attrs={"id": self.ID})
t = Behaviour.MessageTemplate(template)
self.setTemplate(t)
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='get',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#owner")
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='get',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#owner")
iq.addChild(node=query)
self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
+ msg = self._receive(True, 10)
#para descartar los presence anteriores
- while msg and msg.getName()!="iq":
- msg = self._receive(True,10)
+ while msg and msg.getName() != "iq":
+ msg = self._receive(True, 10)
- #setting room configuration
- if not msg or msg.getAttr("type")=="error":
+ #setting room configuration
+ if not msg or msg.getAttr("type") == "error":
print "No configuration is possible: "
- self.result= False
+ self.result = False
return
#falta por revisar!!!!
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='set',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#owner")
- x=Node(tag="x", attrs={"xmlns":"jabber:x:data","
type":"submit"})
- resquery=msg.getQueryChildren()[0] #nos quedamos con el hijo
de query
- if resquery: items = resquery.getTags("field")
- if resquery==None:
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='set',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#owner")
+ x = Node(tag="x", attrs={"xmlns": "jabber:x:data", "
type": "submit"})
+ resquery = msg.getQueryChildren()[0] # nos quedamos con el
hijo de query
+ if resquery:
+ items = resquery.getTags("field")
+ if resquery is None:
print "No configuration is possible"
- self.result= False
+ self.result = False
for item in items:
- value=None
+ value = None
if item.getAttr("var"):
- value=item.getAttr("value") #tomamos el valor
+ value = item.getAttr("value") # tomamos el valor
if item.getAttr("var") == "muc#roomconfig_lang":
- value=self.contentLanguage
+ value = self.contentLanguage
if item.getAttr("var") == "muc#roomconfig_roomdesc":
- value=self.type
+ value = self.type
if item.getAttr("var") == "muc#roomconfig_roomtype":
- value="Organization"
+ value = "Organization"
if item.getAttr("var") == "muc#roomconfig_roomname":
- value=
self.name
+ value =
self.name
if item.getAttr("var")
== "muc#roomconfig_presencebroadcast":
- value="moderator"
+ value = "moderator"
if item.getAttr("var") == "muc#roomconfig_persistentroom":
- value="1"
+ value = "1"
if item.getAttr("var") == "muc#roomconfig_publicroom":
- value="1"
+ value = "1"
if item.getAttr("var") == "muc#roomconfig_moderatedroom":
- value="1"
+ value = "1"
if item.getAttr("var") == "muc#roomconfig_membersonly":
- value="0"
+ value = "0"
if item.getAttr("var")
== "muc#roomconfig_passwordprotectedroom":
- value="0"
+ value = "0"
if item.getAttr("var") == "muc#roomconfig_whois":
- value="moderators" #como es esto??
+ value = "moderators" # como es esto??
if item.getAttr("var") == "muc#roomconfig_changeSubject":
- value="0"
+ value = "0"
if value:
- node=Node(tag="field",
attrs={"var":item.getAttr("var")})
- valnode=Node(tag="value")
+ node = Node(tag="field", attrs={"var":
item.getAttr("var")})
+ valnode = Node(tag="value")
valnode.addData(value)
node.addChild(node=valnode)
x.addChild(node=node)
query.addChild(node=x)
iq.addChild(node=query)
self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
- if msg and msg.getAttr("type")=="result": #comprobar mejor el
mensaje que se devuelve
+ msg = self._receive(True, 10)
+ if msg and msg.getAttr("type") == "result": # comprobar mejor
el mensaje que se devuelve
#modifying the Room Subject
- m = Message(to=
self.name+"@"+self.muc_name,
typ="groupchat")
+ m = Message(to=
self.name + "@" + self.muc_name,
typ="groupchat")
sub = Node(tag="subject")
sub.addData(str(self.goal))
m.addChild(node=sub)
self.myAgent.jabber.send(m)
- self.result= True
+ self.result = True
else:
- self.result= False
+ self.result = False
- def createTeam(self):
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Presence(frm="Team:"+
self.name+"@"+self.muc_name+"/"+self.nick)
- t1 = Behaviour.MessageTemplate(p)
-
b=self.CreateTeamBehaviour(ID,self.muc_name,
self.name,self.nick,self.contentLanguage,self.goalList,self.agentList)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
+ def createTeam(self):
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Presence(frm="Team:" +
self.name + "@" + self.muc_name + "/" +
self.nick)
+ t1 = Behaviour.MessageTemplate(p)
+ b = self.CreateTeamBehaviour(ID, self.muc_name,
self.name,
self.nick, self.contentLanguage, self.goalList, self.agentList)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
- class CreateTeamBehaviour(Behaviour.OneShotBehaviour):
- def
__init__(self,ID,muc_name,roomname,nick,contentLanguage,goal,agentList):
+ class CreateTeamBehaviour(Behaviour.OneShotBehaviour):
+ def __init__(self, ID, muc_name, roomname, nick, contentLanguage,
goal, agentList):
Behaviour.OneShotBehaviour.__init__(self)
self.result = False
- self.ID=ID
- self.nick=nick
- self.muc_name=muc_name
-
self.name="Team:"+roomname
- self.parent=roomname
- self.contentLanguage=contentLanguage
- self.type="Team"
- self.goal=goal
- self.agentList=agentList
+ self.ID = ID
+ self.nick = nick
+ self.muc_name = muc_name
+
self.name = "Team:" + roomname
+ self.parent = roomname
+ self.contentLanguage = contentLanguage
+ self.type = "Team"
+ self.goal = goal
+ self.agentList = agentList
def _process(self):
- p = Presence(to=
self.name+"@"+self.muc_name+"/"+self.nick)
+ p = Presence(to=
self.name + "@" + self.muc_name + "/" +
self.nick)
x = Protocol("x", xmlns="
http://jabber.org/protocol/muc")
p.addChild(node=x)
self.myAgent.jabber.send(p)
- msg=self._receive(True,10)
+ msg = self._receive(True, 10)
if msg:
- if msg.getAttr("type")=="error":
+ if msg.getAttr("type") == "error":
print "Room creation is restricted"
- self.result= False
+ self.result = False
return
else:
- self.result= False
- return
- template= Iq(frm=
self.name+"@"+self.muc_name,
attrs={"id":self.ID})
+ self.result = False
+ return
+ template = Iq(frm=
self.name + "@" + self.muc_name,
attrs={"id": self.ID})
t = Behaviour.MessageTemplate(template)
self.setTemplate(t)
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='get',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#owner")
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='get',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#owner")
iq.addChild(node=query)
self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
+ msg = self._receive(True, 10)
#para descartar los presence anteriores
- while msg and msg.getName()!="iq":
- msg = self._receive(True,10)
+ while msg and msg.getName() != "iq":
+ msg = self._receive(True, 10)
- #setting room configuration
- if not msg or msg.getAttr("type")=="error":
+ #setting room configuration
+ if not msg or msg.getAttr("type") == "error":
print "No configuration is possible: "
- self.result= False
+ self.result = False
return
#falta por revisar!!!!
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='set',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#owner")
- x=Node(tag="x", attrs={"xmlns":"jabber:x:data","
type":"submit"})
- resquery=msg.getQueryChildren()[0] #nos quedamos con el hijo
de query
- if resquery: items = resquery.getTags("field")
- if resquery==None:
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='set',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#owner")
+ x = Node(tag="x", attrs={"xmlns": "jabber:x:data", "
type": "submit"})
+ resquery = msg.getQueryChildren()[0] # nos quedamos con el
hijo de query
+ if resquery:
+ items = resquery.getTags("field")
+ if resquery is None:
print "No configuration is possible"
- self.result= False
+ self.result = False
for item in items:
- value=None
+ value = None
if item.getAttr("var"):
- value=item.getAttr("value") #tomamos el valor
+ value = item.getAttr("value") # tomamos el valor
if item.getAttr("var") == "muc#roomconfig_lang":
- value=self.contentLanguage
+ value = self.contentLanguage
if item.getAttr("var") == "muc#roomconfig_roomdesc":
- value=self.type
+ value = self.type
if item.getAttr("var") == "muc#roomconfig_roomtype":
- value="Unit:"+self.parent
+ value = "Unit:" + self.parent
if item.getAttr("var") == "muc#roomconfig_roomname":
- value=
self.name
+ value =
self.name
if item.getAttr("var")
== "muc#roomconfig_presencebroadcast":
- value="moderator"
+ value = "moderator"
if item.getAttr("var") == "muc#roomconfig_persistentroom":
- value="1"
+ value = "1"
if item.getAttr("var") == "muc#roomconfig_publicroom":
- value="1"
+ value = "1"
if item.getAttr("var") == "muc#roomconfig_moderatedroom":
- value="0"
+ value = "0"
if item.getAttr("var") == "muc#roomconfig_membersonly":
- value="1"
+ value = "1"
if item.getAttr("var")
== "muc#roomconfig_passwordprotectedroom":
- value="0"
+ value = "0"
if item.getAttr("var") == "muc#roomconfig_whois":
- value="anyone" #como es esto??
+ value = "anyone" # como es esto??
if item.getAttr("var") == "muc#roomconfig_changeSubject":
- value="0"
+ value = "0"
if value:
- node=Node(tag="field",
attrs={"var":item.getAttr("var")})
- valnode=Node(tag="value")
+ node = Node(tag="field", attrs={"var":
item.getAttr("var")})
+ valnode = Node(tag="value")
valnode.addData(value)
node.addChild(node=valnode)
x.addChild(node=node)
query.addChild(node=x)
iq.addChild(node=query)
self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
- if msg and msg.getAttr("type")=="result": #comprobar mejor el
mensaje que se devuelve
- #añadiendo los members invitacion
+ msg = self._receive(True, 10)
+ if msg and msg.getAttr("type") == "result": # comprobar mejor
el mensaje que se devuelve
+ #añadiendo los members invitacion
for agent in self.agentList:
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='set',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#admin")
- item= Node(tag="item",
attrs={"affiliation":"owner","jid":agent})
- query.addChild(node=item)
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- m = Message(to=
self.name+"@"+self.muc_name,
typ="groupchat")
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='set',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#admin")
+ item = Node(tag="item",
attrs={"affiliation": "owner", "jid": agent})
+ query.addChild(node=item)
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ m = Message(to=
self.name + "@" + self.muc_name,
typ="groupchat")
sub = Node(tag="subject")
sub.addData(str(self.goal))
m.addChild(node=sub)
self.myAgent.jabber.send(m)
- self.result= True
+ self.result = True
else:
- self.result= False
+ self.result = False
- def checkGoal(self,goalList):
- #falta por implementar
- if goalList!=None:
- return True
- else:
- return False
+ def checkGoal(self, goalList):
+ #falta por implementar
+ if goalList is not None:
+ return True
+ else:
+ return False
+ def checkType(self):
+ types =
("Flat", "Team", "Hierarchy", "Bureaucracy", "Matrix", "Federation", "Coalition", "Congregation")
+ if self.type in types:
+ return True
+ return False
- def checkType(self):
-
types=("Flat","Team","Hierarchy","Bureaucracy","Matrix","Federation","Coalition","Congregation")
- if self.type in types:
- return True
- return False
+ def invite(self, agentList):
+ if self.state == "unavailable":
+ raise Unavailable
+ return
+ for agent in agentList:
+ message = Node(tag="message", attrs={"to":
self.name + "@" +
self.muc_name})
+ x = Node(tag="x",
attrs={"xmlns": "
http://jabber.org/protocol/muc#user"})
+ y = Node(tag="invite", attrs={"to": agent})
+ r = Node(tag="reason")
+ r.addData("Inivitation to the Organization " +
self.name)
+ y.addChild(node=r)
+ x.addChild(node=y)
+ message.addChild(node=x)
+ self.myAgent.jabber.send(message)
- def invite(self,agentList):
- if self.state=="unavailable":
- raise Unavailable
- return
- for agent in agentList:
- message = Node(tag="message",
attrs={"to":
self.name+"@"+self.muc_name})
-
x=Node(tag="x",attrs={"xmlns":"
http://jabber.org/protocol/muc#user"})
- y=Node(tag="invite",attrs={"to":agent})
- r=Node(tag="reason")
- r.addData("Inivitation to the Organization "+
self.name)
- y.addChild(node=r)
- x.addChild(node=y)
- message.addChild(node=x)
- self.myAgent.jabber.send(message)
+ def myJoinRoom(self):
+ p = Presence(frm=
self.name + "@" + self.muc_name + "/" +
self.nick, attrs={"type": "error"})
+ t1 = Behaviour.MessageTemplate(p)
+ b = self. MyJoinRoomBehaviour(self.muc_name,
self.name, self.nick)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
- def myJoinRoom(self):
- p =
Presence(frm=
self.name+"@"+self.muc_name+"/"+self.nick,attrs={"type":"error"})
- t1 = Behaviour.MessageTemplate(p)
- b=self. MyJoinRoomBehaviour(self.muc_name,
self.name,self.nick)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
-
- class MyJoinRoomBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,roomname,nick):
+ class MyJoinRoomBehaviour(Behaviour.OneShotBehaviour):
+ def __init__(self, muc_name, roomname, nick):
Behaviour.OneShotBehaviour.__init__(self)
self.result = False
- self.nick=nick
- self.muc_name=muc_name
-
self.name=roomname
-
+ self.nick = nick
+ self.muc_name = muc_name
+
self.name = roomname
def _process(self):
- p = Presence(to=
self.name+"@"+self.muc_name+"/"+self.nick)
+ p = Presence(to=
self.name + "@" + self.muc_name + "/" +
self.nick)
x = Protocol("x", xmlns="
http://jabber.org/protocol/muc")
p.addChild(node=x)
self.myAgent.jabber.send(p)
- msg=self._receive(True,10)
+ msg = self._receive(True, 10)
if msg:
- error=msg.getTag("error")
- if error.getAttr("code")=="401":
- raise PaswordNeeded
- if error.getAttr("code")=="407":
- raise MembersOnly
- if error.getAttr("code")=="403":
- raise BanedUser
- if error.getAttr("code")=="409":
- raise NickNameConflict
- if error.getAttr("code")=="503":
- raise MaximumUsers
- if error.getAttr("code")=="404":
- raise LockedOrganization
- self.result = False
- return
+ error = msg.getTag("error")
+ if error.getAttr("code") == "401":
+ raise PaswordNeeded
+ if error.getAttr("code") == "407":
+ raise MembersOnly
+ if error.getAttr("code") == "403":
+ raise BanedUser
+ if error.getAttr("code") == "409":
+ raise NickNameConflict
+ if error.getAttr("code") == "503":
+ raise MaximumUsers
+ if error.getAttr("code") == "404":
+ raise LockedOrganization
+ self.result = False
+ return
self.result = True
- def getRegistrationForm(self,unitName):
- """
- Returns a dataform with all requested information for joining
- """
- if self.state=="unavailable":
- raise Unavailable
- return
- if unitName not in self.getUnitList():
- raise NotValidUnit
- return
+ def getRegistrationForm(self, unitName):
+ """
+ Returns a dataform with all requested information for joining
+ """
+ if self.state == "unavailable":
+ raise Unavailable
+ return
+ if unitName not in self.getUnitList():
+ raise NotValidUnit
+ return
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Iq(frm=unitName+"@"+self.muc_name, attrs={"id":ID})
- t1 = Behaviour.MessageTemplate(p)
- b=self.GetRegistrationFormBehaviour(self.muc_name,ID,unitName)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Iq(frm=unitName + "@" + self.muc_name, attrs={"id": ID})
+ t1 = Behaviour.MessageTemplate(p)
+ b = self.GetRegistrationFormBehaviour(self.muc_name, ID, unitName)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
- class GetRegistrationFormBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,ID,unitName):
+ class GetRegistrationFormBehaviour(Behaviour.OneShotBehaviour):
+ def __init__(self, muc_name, ID, unitName):
Behaviour.OneShotBehaviour.__init__(self)
- self.ID=ID
- self.muc_name=muc_name
- self.unitName=unitName
- self.result=None
+ self.ID = ID
+ self.muc_name = muc_name
+ self.unitName = unitName
+ self.result = None
def _process(self):
- iq = Iq(to=self.unitName+"@"+self.muc_name,typ='get',
attrs={"id":self.ID})
- query = Protocol('query',xmlns="jabber:iq:register")
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
- if msg:
- if msg.getAttr("type")!="result":
- error=msg.getError()
- print error
- return
- else:
- if msg.getTag("register")!=None:
- print "The agent has yet registered in the
Unit "+self.unitName
+ iq = Iq(to=self.unitName + "@" + self.muc_name, typ='get',
attrs={"id": self.ID})
+ query = Protocol('query', xmlns="jabber:iq:register")
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ msg = self._receive(True, 10)
+ if msg:
+ if msg.getAttr("type") != "result":
+ error = msg.getError()
+ print error
+ return
else:
- self.result=msg.getChildren()[0]
+ if msg.getTag("register") is not None:
+ print "The agent has yet registered in the Unit "
+ self.unitName
+ else:
+ self.result = msg.getChildren()[0]
#cambiar
- def sendRegistrationForm(self,unitName,dataForm):
- """
- Sends a dataform for a specific unit. If valid, agent is registered
and allowed to join
- """
- if self.state=="unavailable":
- raise Unavailable
- return
- #comprobando que es una unidad de la organizacion
- if unitName not in self.getUnitList():
- raise NotValidUnit
- return
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Iq(frm=unitName+"@"+self.muc_name, attrs={"id":ID})
- t1 = Behaviour.MessageTemplate(p)
-
b=self.GetRegistrationFormBehaviour(self.muc_name,
self.name,ID,unitName,dataForm)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
- class SendRegistrationFormBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,roomname,ID,unitName,dataForm):
+ def sendRegistrationForm(self, unitName, dataForm):
+ """
+ Sends a dataform for a specific unit. If valid, agent is
registered and allowed to join
+ """
+ if self.state == "unavailable":
+ raise Unavailable
+ return
+ #comprobando que es una unidad de la organizacion
+ if unitName not in self.getUnitList():
+ raise NotValidUnit
+ return
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Iq(frm=unitName + "@" + self.muc_name, attrs={"id": ID})
+ t1 = Behaviour.MessageTemplate(p)
+ b = self.GetRegistrationFormBehaviour(self.muc_name,
self.name,
ID, unitName, dataForm)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
+
+ class SendRegistrationFormBehaviour(Behaviour.OneShotBehaviour):
+ def __init__(self, muc_name, roomname, ID, unitName, dataForm):
Behaviour.OneShotBehaviour.__init__(self)
- self.ID=ID
- self.muc_name=muc_name
-
self.name=roomname
- self.unitName=unitName
- self.dataForm=dataForm
- self.result=None
+ self.ID = ID
+ self.muc_name = muc_name
+
self.name = roomname
+ self.unitName = unitName
+ self.dataForm = dataForm
+ self.result = None
def _process(self):
- iq = Iq(to=self.unitName+"@"+self.muc_name,typ='set',
attrs={"id":self.ID})
- query = Protocol('query',xmlns="jabber:iq:register")
- query.addNode(node=self.dataForm)
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
- if msg:
- if msg.getAttr("type")!="result":
- error=msg.getTag("error")
- if error.getAttr("code")=="409":
- print "Error: Conflict, this nickname is already
reserved"
- if error.getAttr("code")=="503":
- print "Error: Resgistration Not Supported"
- if error.getAttr("code")=="400":
- print "Error: Bad Request"
+ iq = Iq(to=self.unitName + "@" + self.muc_name, typ='set',
attrs={"id": self.ID})
+ query = Protocol('query', xmlns="jabber:iq:register")
+ query.addNode(node=self.dataForm)
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ msg = self._receive(True, 10)
+ if msg:
+ if msg.getAttr("type") != "result":
+ error = msg.getTag("error")
+ if error.getAttr("code") == "409":
+ print "Error: Conflict, this nickname is already
reserved"
+ if error.getAttr("code") == "503":
+ print "Error: Resgistration Not Supported"
+ if error.getAttr("code") == "400":
+ print "Error: Bad Request"
- def getUnitList(self):
- """
- Returns a dataform with all requested information for joining
- """
- if self.state=="unavailable":
- raise Unavailable
- return
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- iq = Iq(frm=self.muc_name, attrs={"id":ID})
- t = Behaviour.MessageTemplate(iq)
- b=self.GetUnitListBehaviour(ID,self.muc_name,
self.name)
- self.myAgent.addBehaviour(b, t)
***The diff for this file has been truncated for email.***
=======================================
--- /trunk/spade/Organization_new.py Thu Jun 7 02:55:43 2007
+++ /trunk/spade/Organization_new.py Fri Nov 23 05:19:16 2012
@@ -1,4 +1,4 @@
-# -*- coding: UTF8 -*-
+# -*- coding: utf-8 -*-
import random
import string
@@ -12,938 +12,937 @@
class CreationError(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class NotValidName(CreationError):
def __init__(self):
Exception.__init__(self)
+
+
class NotValidType(CreationError):
def __init__(self):
Exception.__init__(self)
+
+
class NotValidGoal(CreationError):
def __init__(self):
Exception.__init__(self)
+
+
class NotCreatePermision(CreationError):
def __init__(self):
Exception.__init__(self)
+
+
class NotSupervisor(CreationError):
def __init__(self):
Exception.__init__(self)
+
+
class JoinError(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class PaswordNeeded(JoinError):
def __init__(self):
pass
+
+
class MembersOnly(JoinError):
def __init__(self):
Exception.__init__(self)
+
+
class BanedUser(JoinError):
def __init__(self):
Exception.__init__(self)
+
+
class NickNameConflict(JoinError):
def __init__(self):
Exception.__init__(self)
+
+
class MaximumUsers(JoinError):
def __init__(self):
pass
+
+
class LockedOrganization(JoinError):
def __init__(self):
Exception.__init__(self)
+
+
class MemberOfFederation(JoinError):
def __init__(self):
Exception.__init__(self)
+
+
class Unavailable(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class UnavailableFunction(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class DestroyError(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class NotValidUnit(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class LastOwner(Exception):
def __init__(self):
Exception.__init__(self)
+
class Organization_new(Unit_new.Unit_new):
- def __init__(self,agent, nick, name, type=None, goalList=None,
agentList=[], contentLanguage="sl",create=True):
- Behaviour.OneShotBehaviour.__init__(self)
- self.myAgent=agent
-
self.name = name
- self.type = type
- self.goalList = goalList
- self.agentList = agentList
- self.contentLanguage = contentLanguage
- self.platform = self.myAgent.getSpadePlatformJID()
- self.muc_name = self.myAgent.getMUC()
- self._roster = {}
- self.nick=nick
- self.create=create
- id_base
= "".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)]) #@UnusedVariable
- self.ID = str(name) + str(self.myAgent.getAID().getName()) + id_base
- self.state="unavailable"
- self.UnavailableMsg="Organization"
- self.members=[]
- self.owner=False
- self.orgOwner=None
+ def __init__(self, agent, nick, name, type=None, goalList=None,
agentList=[], contentLanguage="sl", create=True):
+ Behaviour.OneShotBehaviour.__init__(self)
+ self.myAgent = agent
+
self.name = name
+ self.type = type
+ self.goalList = goalList
+ self.agentList = agentList
+ self.contentLanguage = contentLanguage
+ self.platform = self.myAgent.getSpadePlatformJID()
+ self.muc_name = self.myAgent.getMUC()
+ self._roster = {}
+ self.nick = nick
+ self.create = create
+ id_base = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)]) # @UnusedVariable
+ self.ID = str(name) + str(self.myAgent.getAID().getName()) +
id_base
+ self.state = "unavailable"
+ self.UnavailableMsg = "Organization"
+ self.members = []
+ self.owner = False
+ self.orgOwner = None
+ def setup(self):
+ pass
- def setup(self):
- pass
-
- def myCreate(self):
- if not self.checkGoal(self.goalList):
- raise NotValidGoal
- elif not self.checkType():
- raise NotVvalidType
- elif not self.testRoomName():
- raise NotValidName
- elif not self.createRoom():
- raise CreationError
- else:
- self.state="available"
- if self.agentList!=[]:
+ def myCreate(self):
+ if not self.checkGoal(self.goalList):
+ raise NotValidGoal
+ elif not self.checkType():
+ raise NotVvalidType
+ elif not self.testRoomName():
+ raise NotValidName
+ elif not self.createRoom():
+ raise CreationError
+ else:
+ self.state = "available"
+ if self.agentList != []:
#enviando invitaciones
- self.invite(self.agentList)
- #registrando en el DF
- # dad = DF.DfAgentDescription()
- # ds = DF.ServiceDescription()
- # ds.setType("ORGANIZATION")
- # ds.setName(
self.name)
- # dad.setAID(self.myAgent.getAID())
- # dad.addService(ds)
- # res = self.myAgent.registerService(dad)
+ self.invite(self.agentList)
+ #registrando en el DF
+ # dad = DF.DfAgentDescription()
+ # ds = DF.ServiceDescription()
+ # ds.setType("ORGANIZATION")
+ # ds.setName(
self.name)
+ # dad.setAID(self.myAgent.getAID())
+ # dad.addService(ds)
+ # res = self.myAgent.registerService(dad)
- self.owner=True
- self.orgOwner=self.myAgent.JID
- p = Presence()
- t = Behaviour.MessageTemplate(p)
-
self.presenceBehaviour=self.PresenceBehaviour(self.muc_name,
self.name,self.nick,self)
- self.myAgent.addBehaviour(self.presenceBehaviour, t)
- if self.type=="Matrix" or self.type=="Federation":
- self.createTeam()
+ self.owner = True
+ self.orgOwner = self.myAgent.JID
+ p = Presence()
+ t = Behaviour.MessageTemplate(p)
+ self.presenceBehaviour = self.PresenceBehaviour(self.muc_name,
self.name, self.nick, self)
+ self.myAgent.addBehaviour(self.presenceBehaviour, t)
+ if self.type == "Matrix" or self.type == "Federation":
+ self.createTeam()
-
- def myJoin(self):
+ def myJoin(self):
#The Organization exists
- if not self.testOrganizationName():
+ if not self.testOrganizationName():
#The room no existe
- raise NotValidName
- elif not self.myJoinRoom():
- #No es una organizacion
- #raise JoinError
- pass
- else:
- info=self.getInfo()
- if info:
- self.type = info["type"]
- self.contentLanguage = info["contentLanguage"]
- self.parent=info["parent"]
- self.goal=info["goal"]
- self.state="available"
- p = Presence()
- t = Behaviour.MessageTemplate(p)
-
self.presenceBehaviour=self.PresenceBehaviour(self.muc_name,
self.name,self.nick,self)
- self.myAgent.addBehaviour(self.presenceBehaviour, t)
-
-
- def testRoomName(self):
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- iq = Iq(frm=self.muc_name, attrs={"id":ID})
- t = Behaviour.MessageTemplate(iq)
- b=self.TestRoomNameBehaviour(ID,self.muc_name,
self.name)
- self.myAgent.addBehaviour(b, t)
- b.join()
- return b.result
-
-
-
-
+ raise NotValidName
+ elif not self.myJoinRoom():
+ #No es una organizacion
+ #raise JoinError
+ pass
+ else:
+ info = self.getInfo()
+ if info:
+ self.type = info["type"]
+ self.contentLanguage = info["contentLanguage"]
+ self.parent = info["parent"]
+ self.goal = info["goal"]
+ self.state = "available"
+ p = Presence()
+ t = Behaviour.MessageTemplate(p)
+ self.presenceBehaviour = self.PresenceBehaviour(self.muc_name,
self.name, self.nick, self)
+ self.myAgent.addBehaviour(self.presenceBehaviour, t)
+ def testRoomName(self):
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ iq = Iq(frm=self.muc_name, attrs={"id": ID})
+ t = Behaviour.MessageTemplate(iq)
+ b = self.TestRoomNameBehaviour(ID, self.muc_name,
self.name)
+ self.myAgent.addBehaviour(b, t)
+ b.join()
+ return b.result
- class TestRoomNameBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,ID,muc_name,roomname):
+ class TestRoomNameBehaviour(Behaviour.OneShotBehaviour):
+ def __init__(self, ID, muc_name, roomname):
Behaviour.OneShotBehaviour.__init__(self)
- self.ID=ID
+ self.ID = ID
self.result = False
- self.muc_name=muc_name
- self.roomname=roomname
+ self.muc_name = muc_name
+ self.roomname = roomname
def _process(self):
- iq = Iq(to=self.muc_name,typ='get', attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/disco#items")
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
- if msg:
- if query:
- self.result = True
- items = msg.getQueryChildren()
- for item in items:
- if item.getAttr("jid") ==
str(self.roomname+"@"+self.muc_name):
- self.result = False
- else:
- self.result = False
+ iq = Iq(to=self.muc_name, typ='get', attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/disco#items")
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ msg = self._receive(True, 10)
+ if msg:
+ if query:
+ self.result = True
+ items = msg.getQueryChildren()
+ for item in items:
+ if item.getAttr("jid") == str(self.roomname + "@"
+ self.muc_name):
+ self.result = False
+ else:
+ self.result = False
- def testOrganizationName(self):
- info=self.getInfo()
+ def testOrganizationName(self):
+ info = self.getInfo()
if info:
- if info["parent"]=="Organization":
+ if info["parent"] == "Organization":
return True
return False
-
-
-
-
-
-
- def createRoom(self):
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Presence(frm=
self.name+"@"+self.muc_name+"/"+self.nick)
- t1 = Behaviour.MessageTemplate(p)
-
b=self.CreateRoomBehaviour(ID,self.muc_name,
self.name,self.nick,self.contentLanguage,self.type,self.goalList)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
+ def createRoom(self):
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Presence(frm=
self.name + "@" + self.muc_name + "/" + self.nick)
+ t1 = Behaviour.MessageTemplate(p)
+ b = self.CreateRoomBehaviour(ID, self.muc_name,
self.name,
self.nick, self.contentLanguage, self.type, self.goalList)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
- class CreateRoomBehaviour(Behaviour.OneShotBehaviour):
- def
__init__(self,ID,muc_name,roomname,nick,contentLanguage,type,goal):
+ class CreateRoomBehaviour(Behaviour.OneShotBehaviour):
+ def __init__(self, ID, muc_name, roomname, nick, contentLanguage,
type, goal):
Behaviour.OneShotBehaviour.__init__(self)
self.result = False
- self.ID=ID
- self.nick=nick
- self.muc_name=muc_name
-
self.name=roomname
- self.contentLanguage=contentLanguage
- self.type=type
- self.goal=goal
+ self.ID = ID
+ self.nick = nick
+ self.muc_name = muc_name
+
self.name = roomname
+ self.contentLanguage = contentLanguage
+ self.type = type
+ self.goal = goal
def _process(self):
- p = Presence(to=
self.name+"@"+self.muc_name+"/"+self.nick)
+ p = Presence(to=
self.name + "@" + self.muc_name + "/" +
self.nick)
x = Protocol("x", xmlns="
http://jabber.org/protocol/muc")
p.addChild(node=x)
self.myAgent.jabber.send(p)
- msg=self._receive(True,10)
+ msg = self._receive(True, 10)
if msg:
- if msg.getAttr("type")=="error":
+ if msg.getAttr("type") == "error":
print "Room creation is restricted"
- self.result= False
+ self.result = False
return
else:
- self.result= False
- return
- template= Iq(frm=
self.name+"@"+self.muc_name,
attrs={"id":self.ID})
+ self.result = False
+ return
+ template = Iq(frm=
self.name + "@" + self.muc_name,
attrs={"id": self.ID})
t = Behaviour.MessageTemplate(template)
self.setTemplate(t)
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='get',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#owner")
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='get',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#owner")
iq.addChild(node=query)
self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
+ msg = self._receive(True, 10)
#para descartar los presence anteriores
- while msg and msg.getName()!="iq":
- msg = self._receive(True,10)
+ while msg and msg.getName() != "iq":
+ msg = self._receive(True, 10)
- #setting room configuration
- if not msg or msg.getAttr("type")=="error":
+ #setting room configuration
+ if not msg or msg.getAttr("type") == "error":
print "No configuration is possible: "
- self.result= False
+ self.result = False
return
#falta por revisar!!!!
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='set',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#owner")
- x=Node(tag="x", attrs={"xmlns":"jabber:x:data","
type":"submit"})
- resquery=msg.getQueryChildren()[0] #nos quedamos con el hijo
de query
- if resquery: items = resquery.getTags("field")
- if resquery==None:
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='set',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#owner")
+ x = Node(tag="x", attrs={"xmlns": "jabber:x:data", "
type": "submit"})
+ resquery = msg.getQueryChildren()[0] # nos quedamos con el
hijo de query
+ if resquery:
+ items = resquery.getTags("field")
+ if resquery is None:
print "No configuration is possible"
- self.result= False
+ self.result = False
for item in items:
- value=None
+ value = None
if item.getAttr("var") == "muc#roomconfig_lang":
- value=self.contentLanguage
+ value = self.contentLanguage
if item.getAttr("var") == "muc#roomconfig_roomdesc":
- value=self.type
+ value = self.type
if item.getAttr("var") == "muc#roomconfig_roomtype":
- value="Organization"
+ value = "Organization"
if item.getAttr("var") == "muc#roomconfig_roomname":
- value=
self.name
+ value =
self.name
if item.getAttr("var")
== "muc#roomconfig_presencebroadcast":
- value="moderator"
+ value = "moderator"
if item.getAttr("var") == "muc#roomconfig_persistentroom":
- value="1"
+ value = "1"
if item.getAttr("var") == "muc#roomconfig_publicroom":
- value="1"
+ value = "1"
if item.getAttr("var") == "muc#roomconfig_moderatedroom":
- value="1"
+ value = "1"
if item.getAttr("var") == "muc#roomconfig_membersonly":
- value="0"
+ value = "0"
if item.getAttr("var")
== "muc#roomconfig_passwordprotectedroom":
- value="0"
+ value = "0"
if item.getAttr("var") == "muc#roomconfig_whois":
- value="moderators" #como es esto??
+ value = "moderators" # como es esto??
###CAMBIA############################################3
if item.getAttr("var") == "muc#roomconfig_changesubject":
- value="1"
+ value = "1"
if value:
- node=Node(tag="field",
attrs={"var":item.getAttr("var")})
- valnode=Node(tag="value")
+ node = Node(tag="field", attrs={"var":
item.getAttr("var")})
+ valnode = Node(tag="value")
valnode.addData(value)
node.addChild(node=valnode)
x.addChild(node=node)
query.addChild(node=x)
iq.addChild(node=query)
self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
- if msg and msg.getAttr("type")=="result": #comprobar mejor el
mensaje que se devuelve
+ msg = self._receive(True, 10)
+ if msg and msg.getAttr("type") == "result": # comprobar mejor
el mensaje que se devuelve
#modifying the Room Subject
- m = Message(to=
self.name+"@"+self.muc_name,
typ="groupchat")
+ m = Message(to=
self.name + "@" + self.muc_name,
typ="groupchat")
sub = Node(tag="subject")
sub.addData(str(self.goal))
m.addChild(node=sub)
self.myAgent.jabber.send(m)
- self.result= True
+ self.result = True
else:
- self.result= False
+ self.result = False
- def createTeam(self):
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Presence(frm="Team:"+
self.name+"@"+self.muc_name+"/"+self.nick)
- t1 = Behaviour.MessageTemplate(p)
-
b=self.CreateTeamBehaviour(ID,self.muc_name,
self.name,self.nick,self.contentLanguage,self.goalList,self.agentList)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
+ def createTeam(self):
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Presence(frm="Team:" +
self.name + "@" + self.muc_name + "/" +
self.nick)
+ t1 = Behaviour.MessageTemplate(p)
+ b = self.CreateTeamBehaviour(ID, self.muc_name,
self.name,
self.nick, self.contentLanguage, self.goalList, self.agentList)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
- class CreateTeamBehaviour(Behaviour.OneShotBehaviour):
- def
__init__(self,ID,muc_name,roomname,nick,contentLanguage,goal,agentList):
+ class CreateTeamBehaviour(Behaviour.OneShotBehaviour):
+ def __init__(self, ID, muc_name, roomname, nick, contentLanguage,
goal, agentList):
Behaviour.OneShotBehaviour.__init__(self)
self.result = False
- self.ID=ID
- self.nick=nick
- self.muc_name=muc_name
-
self.name="Team:"+roomname
- self.parent=roomname
- self.contentLanguage=contentLanguage
- self.type="Team"
- self.goal=goal
- self.agentList=agentList
+ self.ID = ID
+ self.nick = nick
+ self.muc_name = muc_name
+
self.name = "Team:" + roomname
+ self.parent = roomname
+ self.contentLanguage = contentLanguage
+ self.type = "Team"
+ self.goal = goal
+ self.agentList = agentList
def _process(self):
- p = Presence(to=
self.name+"@"+self.muc_name+"/"+self.nick)
+ p = Presence(to=
self.name + "@" + self.muc_name + "/" +
self.nick)
x = Protocol("x", xmlns="
http://jabber.org/protocol/muc")
p.addChild(node=x)
self.myAgent.jabber.send(p)
- msg=self._receive(True,10)
+ msg = self._receive(True, 10)
if msg:
- if msg.getAttr("type")=="error":
+ if msg.getAttr("type") == "error":
print "Room creation is restricted"
- self.result= False
+ self.result = False
return
else:
- self.result= False
- return
- template= Iq(frm=
self.name+"@"+self.muc_name,
attrs={"id":self.ID})
+ self.result = False
+ return
+ template = Iq(frm=
self.name + "@" + self.muc_name,
attrs={"id": self.ID})
t = Behaviour.MessageTemplate(template)
self.setTemplate(t)
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='get',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#owner")
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='get',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#owner")
iq.addChild(node=query)
self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
+ msg = self._receive(True, 10)
#para descartar los presence anteriores
- while msg and msg.getName()!="iq":
- msg = self._receive(True,10)
+ while msg and msg.getName() != "iq":
+ msg = self._receive(True, 10)
- #setting room configuration
- if not msg or msg.getAttr("type")=="error":
+ #setting room configuration
+ if not msg or msg.getAttr("type") == "error":
print "No configuration is possible: "
- self.result= False
+ self.result = False
return
#falta por revisar!!!!
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='set',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#owner")
- x=Node(tag="x", attrs={"xmlns":"jabber:x:data","
type":"submit"})
- resquery=msg.getQueryChildren()[0] #nos quedamos con el hijo
de query
- if resquery: items = resquery.getTags("field")
- if resquery==None:
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='set',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#owner")
+ x = Node(tag="x", attrs={"xmlns": "jabber:x:data", "
type": "submit"})
+ resquery = msg.getQueryChildren()[0] # nos quedamos con el
hijo de query
+ if resquery:
+ items = resquery.getTags("field")
+ if resquery is None:
print "No configuration is possible"
- self.result= False
+ self.result = False
for item in items:
- value=None
+ value = None
if item.getAttr("var"):
- value=item.getAttr("value") #tomamos el valor
+ value = item.getAttr("value") # tomamos el valor
if item.getAttr("var") == "muc#roomconfig_lang":
- value=self.contentLanguage
+ value = self.contentLanguage
if item.getAttr("var") == "muc#roomconfig_roomdesc":
- value=self.type
+ value = self.type
if item.getAttr("var") == "muc#roomconfig_roomtype":
- value="Unit:"+self.parent
+ value = "Unit:" + self.parent
if item.getAttr("var") == "muc#roomconfig_roomname":
- value=
self.name
+ value =
self.name
if item.getAttr("var")
== "muc#roomconfig_presencebroadcast":
- value="moderator"
+ value = "moderator"
if item.getAttr("var") == "muc#roomconfig_persistentroom":
- value="1"
+ value = "1"
if item.getAttr("var") == "muc#roomconfig_publicroom":
- value="1"
+ value = "1"
if item.getAttr("var") == "muc#roomconfig_moderatedroom":
- value="0"
+ value = "0"
if item.getAttr("var") == "muc#roomconfig_membersonly":
- value="1"
+ value = "1"
if item.getAttr("var")
== "muc#roomconfig_passwordprotectedroom":
- value="0"
+ value = "0"
if item.getAttr("var") == "muc#roomconfig_whois":
- value="anyone" #como es esto??
+ value = "anyone" # como es esto??
if item.getAttr("var") == "muc#roomconfig_changeSubject":
- value="0"
+ value = "0"
if value:
- node=Node(tag="field",
attrs={"var":item.getAttr("var")})
- valnode=Node(tag="value")
+ node = Node(tag="field", attrs={"var":
item.getAttr("var")})
+ valnode = Node(tag="value")
valnode.addData(value)
node.addChild(node=valnode)
x.addChild(node=node)
query.addChild(node=x)
iq.addChild(node=query)
self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
- if msg and msg.getAttr("type")=="result": #comprobar mejor el
mensaje que se devuelve
- #añadiendo los members invitacion
+ msg = self._receive(True, 10)
+ if msg and msg.getAttr("type") == "result": # comprobar mejor
el mensaje que se devuelve
+ #añadiendo los members invitacion
for agent in self.agentList:
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='set',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#admin")
- item= Node(tag="item",
attrs={"affiliation":"owner","jid":agent})
- query.addChild(node=item)
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- m = Message(to=
self.name+"@"+self.muc_name,
typ="groupchat")
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='set',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#admin")
+ item = Node(tag="item",
attrs={"affiliation": "owner", "jid": agent})
+ query.addChild(node=item)
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ m = Message(to=
self.name + "@" + self.muc_name,
typ="groupchat")
sub = Node(tag="subject")
sub.addData(str(self.goal))
m.addChild(node=sub)
self.myAgent.jabber.send(m)
- self.result= True
+ self.result = True
else:
- self.result= False
+ self.result = False
- def checkGoal(self,goalList):
- #falta por implementar
- if goalList!=None:
- return True
- else:
- return False
+ def checkGoal(self, goalList):
+ #falta por implementar
+ if goalList is not None:
+ return True
+ else:
+ return False
+ def checkType(self):
+ types =
("Flat", "Team", "Hierarchy", "Bureaucracy", "Matrix", "Federation", "Coalition", "Congregation")
+ if self.type in types:
+ return True
+ return False
- def checkType(self):
-
types=("Flat","Team","Hierarchy","Bureaucracy","Matrix","Federation","Coalition","Congregation")
- if self.type in types:
- return True
- return False
+ def invite(self, agentList):
+ if self.state == "unavailable":
+ raise Unavailable
+ return
+ for agent in agentList:
+ message = Node(tag="message", attrs={"to":
self.name + "@" +
self.muc_name})
+ x = Node(tag="x",
attrs={"xmlns": "
http://jabber.org/protocol/muc#user"})
+ y = Node(tag="invite", attrs={"to": agent})
+ r = Node(tag="reason")
+ r.addData("Inivitation to the Organization " +
self.name)
+ y.addChild(node=r)
+ x.addChild(node=y)
+ message.addChild(node=x)
+ self.myAgent.jabber.send(message)
- def invite(self,agentList):
- if self.state=="unavailable":
- raise Unavailable
- return
- for agent in agentList:
- message = Node(tag="message",
attrs={"to":
self.name+"@"+self.muc_name})
-
x=Node(tag="x",attrs={"xmlns":"
http://jabber.org/protocol/muc#user"})
- y=Node(tag="invite",attrs={"to":agent})
- r=Node(tag="reason")
- r.addData("Inivitation to the Organization "+
self.name)
- y.addChild(node=r)
- x.addChild(node=y)
- message.addChild(node=x)
- self.myAgent.jabber.send(message)
+ def myJoinRoom(self):
+ p = Presence(frm=
self.name + "@" + self.muc_name + "/" +
self.nick, attrs={"type": "error"})
+ t1 = Behaviour.MessageTemplate(p)
+ b = self. MyJoinRoomBehaviour(self.muc_name,
self.name, self.nick)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
- def myJoinRoom(self):
- p =
Presence(frm=
self.name+"@"+self.muc_name+"/"+self.nick,attrs={"type":"error"})
- t1 = Behaviour.MessageTemplate(p)
- b=self. MyJoinRoomBehaviour(self.muc_name,
self.name,self.nick)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
-
- class MyJoinRoomBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,roomname,nick):
+ class MyJoinRoomBehaviour(Behaviour.OneShotBehaviour):
+ def __init__(self, muc_name, roomname, nick):
Behaviour.OneShotBehaviour.__init__(self)
self.result = False
- self.nick=nick
- self.muc_name=muc_name
-
self.name=roomname
-
+ self.nick = nick
+ self.muc_name = muc_name
+
self.name = roomname
def _process(self):
- p = Presence(to=
self.name+"@"+self.muc_name+"/"+self.nick)
+ p = Presence(to=
self.name + "@" + self.muc_name + "/" +
self.nick)
x = Protocol("x", xmlns="
http://jabber.org/protocol/muc")
p.addChild(node=x)
self.myAgent.jabber.send(p)
- msg=self._receive(True,10)
+ msg = self._receive(True, 10)
if msg:
- error=msg.getTag("error")
- if error.getAttr("code")=="401":
- raise PaswordNeeded
- if error.getAttr("code")=="407":
- raise MembersOnly
- if error.getAttr("code")=="403":
- raise BanedUser
- if error.getAttr("code")=="409":
- raise NickNameConflict
- if error.getAttr("code")=="503":
- raise MaximumUsers
- if error.getAttr("code")=="404":
- raise LockedOrganization
- self.result = False
- return
+ error = msg.getTag("error")
+ if error.getAttr("code") == "401":
+ raise PaswordNeeded
+ if error.getAttr("code") == "407":
+ raise MembersOnly
+ if error.getAttr("code") == "403":
+ raise BanedUser
+ if error.getAttr("code") == "409":
+ raise NickNameConflict
+ if error.getAttr("code") == "503":
+ raise MaximumUsers
+ if error.getAttr("code") == "404":
+ raise LockedOrganization
+ self.result = False
+ return
self.result = True
- def getRegistrationForm(self,unitName):
- """
- Returns a dataform with all requested information for joining
- """
- if self.state=="unavailable":
- raise Unavailable
- return
- if unitName not in self.getUnitList():
- raise NotValidUnit
- return
+ def getRegistrationForm(self, unitName):
+ """
+ Returns a dataform with all requested information for joining
+ """
+ if self.state == "unavailable":
+ raise Unavailable
+ return
+ if unitName not in self.getUnitList():
+ raise NotValidUnit
+ return
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Iq(frm=unitName+"@"+self.muc_name, attrs={"id":ID})
- t1 = Behaviour.MessageTemplate(p)
- b=self.GetRegistrationFormBehaviour(self.muc_name,ID,unitName)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Iq(frm=unitName + "@" + self.muc_name, attrs={"id": ID})
+ t1 = Behaviour.MessageTemplate(p)
+ b = self.GetRegistrationFormBehaviour(self.muc_name, ID, unitName)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
- class GetRegistrationFormBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,ID,unitName):
+ class GetRegistrationFormBehaviour(Behaviour.OneShotBehaviour):
+ def __init__(self, muc_name, ID, unitName):
Behaviour.OneShotBehaviour.__init__(self)
- self.ID=ID
- self.muc_name=muc_name
- self.unitName=unitName
- self.result=None
+ self.ID = ID
+ self.muc_name = muc_name
+ self.unitName = unitName
+ self.result = None
def _process(self):
- iq = Iq(to=self.unitName+"@"+self.muc_name,typ='get',
attrs={"id":self.ID})
- query = Protocol('query',xmlns="jabber:iq:register")
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
- if msg:
- if msg.getAttr("type")!="result":
- error=msg.getError()
- print error
- return
- else:
- if msg.getTag("register")!=None:
- print "The agent has yet registered in the
Unit "+self.unitName
+ iq = Iq(to=self.unitName + "@" + self.muc_name, typ='get',
attrs={"id": self.ID})
+ query = Protocol('query', xmlns="jabber:iq:register")
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ msg = self._receive(True, 10)
+ if msg:
+ if msg.getAttr("type") != "result":
+ error = msg.getError()
+ print error
+ return
else:
- self.result=msg.getChildren()[0]
+ if msg.getTag("register") is not None:
+ print "The agent has yet registered in the Unit "
+ self.unitName
+ else:
+ self.result = msg.getChildren()[0]
#cambiar
- def sendRegistrationForm(self,unitName,dataForm):
- """
- Sends a dataform for a specific unit. If valid, agent is registered
and allowed to join
- """
- if self.state=="unavailable":
- raise Unavailable
- return
- #comprobando que es una unidad de la organizacion
- if unitName not in self.getUnitList():
- raise NotValidUnit
- return
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Iq(frm=unitName+"@"+self.muc_name, attrs={"id":ID})
- t1 = Behaviour.MessageTemplate(p)
-
b=self.GetRegistrationFormBehaviour(self.muc_name,
self.name,ID,unitName,dataForm)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
- class SendRegistrationFormBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,roomname,ID,unitName,dataForm):
+ def sendRegistrationForm(self, unitName, dataForm):
+ """
+ Sends a dataform for a specific unit. If valid, agent is
registered and allowed to join
+ """
+ if self.state == "unavailable":
+ raise Unavailable
+ return
+ #comprobando que es una unidad de la organizacion
+ if unitName not in self.getUnitList():
+ raise NotValidUnit
+ return
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Iq(frm=unitName + "@" + self.muc_name, attrs={"id": ID})
+ t1 = Behaviour.MessageTemplate(p)
+ b = self.GetRegistrationFormBehaviour(self.muc_name,
self.name,
ID, unitName, dataForm)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
+
+ class SendRegistrationFormBehaviour(Behaviour.OneShotBehaviour):
+ def __init__(self, muc_name, roomname, ID, unitName, dataForm):
Behaviour.OneShotBehaviour.__init__(self)
- self.ID=ID
- self.muc_name=muc_name
-
self.name=roomname
- self.unitName=unitName
- self.dataForm=dataForm
- self.result=None
+ self.ID = ID
+ self.muc_name = muc_name
+
self.name = roomname
+ self.unitName = unitName
+ self.dataForm = dataForm
+ self.result = None
def _process(self):
- iq = Iq(to=self.unitName+"@"+self.muc_name,typ='set',
attrs={"id":self.ID})
- query = Protocol('query',xmlns="jabber:iq:register")
- query.addNode(node=self.dataForm)
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
- if msg:
- if msg.getAttr("type")!="result":
- error=msg.getTag("error")
- if error.getAttr("code")=="409":
- print "Error: Conflict, this nickname is already
reserved"
- if error.getAttr("code")=="503":
- print "Error: Resgistration Not Supported"
- if error.getAttr("code")=="400":
- print "Error: Bad Request"
+ iq = Iq(to=self.unitName + "@" + self.muc_name, typ='set',
attrs={"id": self.ID})
+ query = Protocol('query', xmlns="jabber:iq:register")
+ query.addNode(node=self.dataForm)
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ msg = self._receive(True, 10)
+ if msg:
+ if msg.getAttr("type") != "result":
+ error = msg.getTag("error")
+ if error.getAttr("code") == "409":
+ print "Error: Conflict, this nickname is already
reserved"
+ if error.getAttr("code") == "503":
+ print "Error: Resgistration Not Supported"
+ if error.getAttr("code") == "400":
+ print "Error: Bad Request"
- def getUnitList(self):
- """
- Returns a dataform with all requested information for joining
- """
- if self.state=="unavailable":
- raise Unavailable
- return
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- iq = Iq(frm=self.muc_name, attrs={"id":ID})
- t = Behaviour.MessageTemplate(iq)
- b=self.GetUnitListBehaviour(ID,self.muc_name,
self.name)
- self.myAgent.addBehaviour(b, t)
***The diff for this file has been truncated for email.***
=======================================
--- /trunk/spade/Platform.py Fri Nov 9 09:51:22 2012
+++ /trunk/spade/Platform.py Fri Nov 23 05:19:16 2012
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
from AMS import AmsAgentDescription
from DF import DfAgentDescription, ServiceDescription, Service
from Agent import PlatformAgent, require_login
@@ -26,10 +27,13 @@
from wui import *
from os.path import *
+
class PlatformRestart(Exception):
- def __init__(self): pass
- def __str__(self): return
+ def __init__(self):
+ pass
+ def __str__(self):
+ return
class SpadePlatform(PlatformAgent):
@@ -42,8 +46,8 @@
def _process(self):
msg = self._receive(True)
- if (msg != None):
- self.myAgent.DEBUG("SPADE Platform Received a message: " +
str(msg),'info')
+ if (msg is not None):
+ self.myAgent.DEBUG("SPADE Platform Received a message: " +
str(msg), 'info')
if msg.getSender() == self.myAgent.getAID():
# Prevent self-loopholes
self.myAgent.DEBUG("ACC LOOP HOLE", "warn")
@@ -55,15 +59,15 @@
for to in to_list:
if (self.myAgent.getAID().getName() != to.getName()):
if not to.getAddresses()[0] in d:
- d[to.getAddresses()[0]]=list()
+ d[to.getAddresses()[0]] = list()
d[to.getAddresses()[0]].append(to)
- for k,v in d.items():
+ for k, v in d.items():
newmsg = msg
newmsg.to = v
try:
protocol, receiver_URI = k.split("://")
except:
- self.myAgent.DEBUG("Malformed Agent Address URI: "
+ str(k),"error")
+ self.myAgent.DEBUG("Malformed Agent Address URI: "
+ str(k), "error")
break
# Check if one of our MTPs handles this protocol
@@ -86,15 +90,15 @@
self.myAgent.mtps[protocol].send(envelope, payload)
else:
# Default case: it's an XMPP message
- self.myAgent.DEBUG("Message through protocol
XMPP",'info')
- platform =
self.myAgent.getSpadePlatformJID().split(".",1)[1]
+ self.myAgent.DEBUG("Message through protocol
XMPP", 'info')
+ platform =
self.myAgent.getSpadePlatformJID().split(".", 1)[1]
if not platform in receiver_URI:
# Outside platform
- self.myAgent.DEBUG("Message for another
platform",'info')
+ self.myAgent.DEBUG("Message for another
platform", 'info')
self.myAgent.send(newmsg, "jabber")
else:
# THIS platform
- self.myAgent.DEBUG("Message for current
platform",'info')
+ self.myAgent.DEBUG("Message for current
platform", 'info')
for recv in v:
#self.myAgent._sendTo(newmsg,
recv.getName(), "jabber")
self.myAgent.send(newmsg, "jabber")
@@ -110,7 +114,8 @@
#print "Message to", to.getName(), "... Posting!"
"""
else:
- self.myAgent.DEBUG("ACC::dying... this shouldn't
happen", 'err')
+ pass
+ ##self.myAgent.DEBUG("ACC::dying... this shouldn't
happen", 'err')
def __init__(self, node, password, server, port, config=None):
PlatformAgent.__init__(self, node, password, server, port,
config=config, debug=[])
@@ -119,54 +124,52 @@
def _setup(self):
self.setDefaultBehaviour(self.RouteBehaviour())
- self.wui.registerController("index",self.index)
+ self.wui.registerController("index", self.index)
self.wui.registerController("agents", self.agents)
self.wui.registerController("services", self.services)
self.wui.setPort(8008)
self.wui.start()
-
+
# Load MTPs
- for name,mtp in self.config.acc.mtp.items():
+ for name, mtp in self.config.acc.mtp.items():
#self.mtps[mtp.protocol] = mtp.instance(name)
try:
- mtp_path = "."+os.sep+"spade"+os.sep+"mtp"
- if os.path.exists(mtp_path):
- sys.path.append(mtp_path)
- else:
+ mtp_path = "." + os.sep + "spade" + os.sep + "mtp"
+ if os.path.exists(mtp_path):
+ sys.path.append(mtp_path)
+ else:
# This path should come from the config file . . .
- mtp_path =
os.sep+"usr"+os.sep+"share"+os.sep+"spade"+os.sep+"mtp"
- sys.path.append(mtp_path)
+ mtp_path = os.sep + "usr" + os.sep + "share" + os.sep
+ "spade" + os.sep + "mtp"
+ sys.path.append(mtp_path)
- mod = __import__(name)
- self.mtps[mtp['protocol']] =
mod.INSTANCE(name,self.config,self)
+ mod = __import__(name)
+ self.mtps[mtp['protocol']] = mod.INSTANCE(name,
self.config, self)
except Exception, e:
- print "EXCEPTION IMPORTING MTPS: ",str(e)
+ print "EXCEPTION IMPORTING MTPS: ", str(e)
_exception = sys.exc_info()
if _exception[0]:
-
msg='\n'+''.join(traceback.format_exception(_exception[0], _exception[1],
_exception[2])).rstrip()
- print msg
+ msg = '\n'
+ ''.join(traceback.format_exception(_exception[0], _exception[1],
_exception[2])).rstrip()
+ print msg
def takeDown(self):
- for k,mtp in self.mtps.items():
+ for k, mtp in self.mtps.items():
try:
mtp.stop()
del self.mtps[k]
except:
pass
-
-
#Controllers
def index(self):
import sys
import time
servername = self.getDomain()
- platform = self.getName()
+ platform = self.getName()
version = str(sys.version)
the_time = str(time.ctime())
doc_path = abspath('.')
- return "webadmin_indigo.pyra",
dict(name=platform,servername=servername, platform=platform,
version=version, time=the_time, doc_path=doc_path)
+ return "webadmin_indigo.pyra", dict(name=platform,
servername=servername, platform=platform, version=version, time=the_time,
doc_path=doc_path)
@require_login
def agents(self):
@@ -174,7 +177,7 @@
import time
so = self.session
servername = self.getDomain()
- platform = self.getName()
+ platform = self.getName()
version = str(sys.version)
the_time = str(time.ctime())
search = self.searchAgent(AmsAgentDescription())
@@ -189,23 +192,23 @@
for agent in search:
if agent.getAID():
aw = "#"
- for addr in agent.getAID().getAddresses():
+ for addr in agent.getAID().getAddresses():
if "awui://" in addr:
aw = addr.replace("awui://", "http://")
break
awuis[agent.getAID().getName()] = aw
- self.DEBUG("AWUIs: "+str(awuis))
- return "agents.pyra", dict(name=platform,servername=servername,
platform=platform, version=version, time=the_time, agents=search,
awuis=awuis)
+ self.DEBUG("AWUIs: " + str(awuis))
+ return "agents.pyra", dict(name=platform, servername=servername,
platform=platform, version=version, time=the_time, agents=search,
awuis=awuis)
@require_login
def services(self):
import sys
import time
servername = self.getDomain()
- platform = self.getName()
+ platform = self.getName()
version = str(sys.version)
the_time = str(time.ctime())
- try:
+ try:
search = self.searchService(DfAgentDescription())
except Exception, e:
print "Exception: " + str(e)
@@ -219,27 +222,9 @@
s = Service(dad=new_dad)
servs[service.getType()].append(s)
self.DEBUG("Services: " + str(servs))
- return "services.pyra", dict(name=platform,servername=servername,
platform=platform, version=version, time=the_time, services=servs)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ return "services.pyra", dict(name=platform, servername=servername,
platform=platform, version=version, time=the_time, services=servs)
- def getMembers(self,aname):
+ def getMembers(self, aname):
msg = ACLMessage.ACLMessage()
msg.setOntology("spade:x:organization")
template = Behaviour.ACLTemplate()
@@ -248,23 +233,18 @@
b = self.GetMembersBehav()
b.msg = msg
b.aname = aname
- self.addBehaviour(b,t)
+ self.addBehaviour(b, t)
b.join()
return b.result
class GetMembersBehav(Behaviour.OneShotBehaviour):
def _process(self):
self.result = []
- self.msg.addReceiver(AID.aid(self.aname,
addresses=["xmpp://"+self.aname]))
- self.msg.setContent("MEMBERS")
- self.myAgent.send(self.msg)
- rep = None
- rep = self._receive(True, 20)
- if rep:
- print "The members list arrived"
- self.result = rep.getContent().split(",")
-
-
-
-
-
+ self.msg.addReceiver(AID.aid(self.aname, addresses=["xmpp://"
+ self.aname]))
+ self.msg.setContent("MEMBERS")
+ self.myAgent.send(self.msg)
+ rep = None
+ rep = self._receive(True, 20)
+ if rep:
+ print "The members list arrived"
+ self.result = rep.getContent().split(",")
=======================================
--- /trunk/spade/RDF0Parser.py Wed Apr 15 15:38:31 2009
+++ /trunk/spade/RDF0Parser.py Fri Nov 23 05:19:16 2012
@@ -1,487 +1,453 @@
-# -*- coding: cp1252 -*-
+# -*- coding: utf-8 -*-
import xml.sax
from xml.sax import handler
import cStringIO
+
class Newdict(dict):
- def __getattr__(self, name): return self[name]
- def pprint(self, ind=0):
- s = ""
- for k,v in self.items():
- try:
- s = s + ('\t'*ind)+str(k)+":\n"+v.pprint(ind+1) + '\n'
- except:
- s = s + ('\t'*ind)+str(k)+": " + str(v) + '\n'
- return s
+ def __getattr__(self, name):
+ return self[name]
+
+ def pprint(self, ind=0):
+ s = ""
+ for k, v in self.items():
+ try:
+ s = s + ('\t' * ind) + str(k) + ":\n" + v.pprint(ind + 1)
+ '\n'
+ except:
+ s = s + ('\t' * ind) + str(k) + ": " + str(v) + '\n'
+ return s
# build a shorthand tag
-def btag(n1,n2):
- return str(n1)+":"+str(n2)
+
+
+def btag(n1, n2):
+ return str(n1) + ":" + str(n2)
+
class RDF0Parser(handler.ContentHandler):
- """
- FIPA RDF Content Language Parser
- """
- def __init__(self):
+ """
+ FIPA RDF Content Language Parser
+ """
+ def __init__(self):
+ #Constants
+ self.OT = "<"
+ self.ET = "</"
+ self.CT = ">"
+ self.NULL = ""
+ self.TYPE_SEP = "^^"
- #Constants
- self.OT = "<"
- self.ET = "</"
- self.CT = ">"
- self.NULL = ""
- self.TYPE_SEP = "^^"
-
+ #RDF syntax namespace constants
+ self.XML_VERSION = '<?xml version="1.0"?>'
+ self.RDF_PREF = "rdf"
+ self.RDF = "RDF"
+ self.RDF_NS = "
http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ self.ID = "ID"
+ self.RESOURCE = "resource"
+ self.DESCRIPTION = "Description"
+ self.ABOUT = "about"
+ self.SUBJECT = "subject"
+ self.PREDICATE = "predicate"
+ self.OBJECT = "object"
+ self.BAG = "Bag"
+ self.SEQ = "Seq"
+ self.ALT = "Alt"
+ self.LI = "li"
+ self.DATATYPE = "datatype"
- #RDF syntax namespace constants
- self.XML_VERSION = '<?xml version="1.0"?>'
- self.RDF_PREF = "rdf"
- self.RDF = "RDF"
- self.RDF_NS = "
http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- self.ID = "ID"
- self.RESOURCE = "resource"
- self.DESCRIPTION = "Description"
- self.ABOUT = "about"
- self.SUBJECT = "subject"
- self.PREDICATE = "predicate"
- self.OBJECT = "object"
- self.BAG = "Bag"
- self.SEQ = "Seq"
- self.ALT = "Alt"
- self.LI = "li"
- self.DATATYPE = "datatype"
-
- #Fipa namespace constants
- self.FIPA_PREF = "fipa"
- self.FIPA_NS = "
http://www.fipa.org/schemas/fipa-rdf0#"
- self.PROPOSITION = "Proposition"
- self.BELIEF = "belief"
- self.ACTION = "Action"
- self.ACTOR = "actor"
- self.ACT = "act"
- self.ARGUMENT = "argument"
- self.ACTOR = "actor"
- self.DONE = "done"
- self.RESULT = "result"
- self.IMPLBY = "implementedBy"
- self.CODE = "Code"
- self.LANGUAGE = "language"
- self.BINDING = "binding"
- self.CODE_URI = "code-uri"
- self.SCRIPT = "script"
+ #Fipa namespace constants
+ self.FIPA_PREF = "fipa"
+ self.FIPA_NS = "
http://www.fipa.org/schemas/fipa-rdf0#"
+ self.PROPOSITION = "Proposition"
+ self.BELIEF = "belief"
+ self.ACTION = "Action"
+ self.ACTOR = "actor"
+ self.ACT = "act"
+ self.ARGUMENT = "argument"
+ self.ACTOR = "actor"
+ self.DONE = "done"
+ self.RESULT = "result"
+ self.IMPLBY = "implementedBy"
+ self.CODE = "Code"
+ self.LANGUAGE = "language"
+ self.BINDING = "binding"
+ self.CODE_URI = "code-uri"
+ self.SCRIPT = "script"
+ self.content = Newdict()
+ # ***************************************************
+ # * Encoding methods *
+ # ***************************************************
+ def encodeTag(self, tag, content):
- self.content = Newdict()
+ if isinstance(content, dict):
+ # encoding a RDF resource
+ sb = self.encodeOneLineTag(tag, btag(self.RDF_PREF,
self.RESOURCE), content[self.RESOURCE])
+ else:
+ if self.TYPE_SEP in content:
+ #encoding value with type
+ value, type = content.split(self.TYPE_SEP)
+ sb = self.encodeInitTagAttr(tag, btag(self.RDF_PREF,
self.DATATYPE), type)
+ sb = sb + value.strip('"')
+ else:
+ sb = self.OT + tag + self.CT
+ sb = sb + content
+ sb = sb + self.ET + tag + self.CT + '\n'
+ return sb
- # ***************************************************
- # * Encoding methods *
- # ***************************************************
+ def encodeInitTag(self, tag):
+ sb = self.OT + tag + self.CT
+ return sb + '\n'
- def encodeTag( self, tag, content ):
-
- if isinstance(content,dict):
- # encoding a RDF resource
- sb = self.encodeOneLineTag( tag, btag(self.RDF_PREF,self.RESOURCE),
content[self.RESOURCE])
- else:
- if self.TYPE_SEP in content:
- #encoding value with type
- value, type = content.split(self.TYPE_SEP)
- sb = self.encodeInitTagAttr( tag, btag(self.RDF_PREF,self.DATATYPE),
type)
- sb = sb + value.strip('"')
-
- else:
- sb = self.OT + tag + self.CT
- sb = sb + content
+ def encodeEndTag(self, tag):
+ sb = self.ET + tag + self.CT
+ return sb + '\n'
- sb = sb + self.ET + tag + self.CT + '\n'
+ def encodeInitTagAttr(self, tag, attr, value):
+ sb = self.OT + tag + " " + attr + '="' + value + '"' + self.CT
+ return sb
- return sb
-
- def encodeInitTag( self, tag):
- sb = self.OT + tag + self.CT
- return sb + '\n'
+ def encodeOneLineTag(self, tag1, tag2, value):
+ sb = self.OT + tag1 + " "
+ sb = sb + tag2 + '="' + value + '"/>'
+ return sb + '\n'
- def encodeEndTag( self, tag):
- sb = self.ET + tag + self.CT
- return sb + '\n'
+ def encode(self, content):
+ """
+ Content Encoding
+ """
+ #version encoding
+ sb = self.XML_VERSION + '\n'
- def encodeInitTagAttr( self, tag, attr, value):
- sb = self.OT + tag + " " + attr + '="' + value + '"' + self.CT
- return sb
-
- def encodeOneLineTag( self, tag1, tag2, value ):
- sb = self.OT + tag1 + " "
- sb = sb + tag2 + '="' + value + '"/>'
- return sb + '\n'
-
- def encode(self, content):
- """
- Content Encoding
- """
- #version encoding
- sb = self.XML_VERSION+'\n'
-
- #namespaces encoding
- sb = sb + self.OT + btag(self.RDF_PREF,self.RDF)+ ' ' +
btag("xmlns",self.RDF_PREF) + '="' + self.RDF_NS + '"'
- sb = sb +'\n ' + btag("xmlns",self.FIPA_PREF) + '="' + self.FIPA_NS
+ '"' + self.CT + '\n\n'
-
+ #namespaces encoding
+ sb = sb + self.OT + btag(self.RDF_PREF, self.RDF) + ' ' +
btag("xmlns", self.RDF_PREF) + '="' + self.RDF_NS + '"'
+ sb = sb + '\n ' + btag("xmlns", self.FIPA_PREF) + '="' +
self.FIPA_NS + '"' + self.CT + '\n\n'
- # Action encoding
- if self.ACTION in content:
- if self.ID in content[self.ACTION]:
- sb_action =
self.encodeInitTagAttr(btag(self.FIPA_PREF,self.ACTION),btag(self.RDF_PREF,self.ID),content[self.ACTION][self.ID])
+ # Action encoding
+ if self.ACTION in content:
+ if self.ID in content[self.ACTION]:
+ sb_action = self.encodeInitTagAttr(btag(self.FIPA_PREF,
self.ACTION), btag(self.RDF_PREF, self.ID), content[self.ACTION][self.ID])
- elif self.ABOUT in content[self.ACTION]:
- sb_action =
self.encodeInitTagAttr(btag(self.FIPA_PREF,self.ACTION),btag(self.RDF_PREF,self.ABOUT),content[self.ACTION][self.ABOUT])
+ elif self.ABOUT in content[self.ACTION]:
+ sb_action = self.encodeInitTagAttr(btag(self.FIPA_PREF,
self.ACTION), btag(self.RDF_PREF, self.ABOUT),
content[self.ACTION][self.ABOUT])
- else:
- sb_action = self.encodeInitTag(btag(self.FIPA_PREF,self.ACTION))
+ else:
+ sb_action = self.encodeInitTag(btag(self.FIPA_PREF,
self.ACTION))
-
-
- if self.ACTOR in content[self.ACTION]:
- sb_action = sb_action +
self.encodeTag(btag(self.FIPA_PREF,self.ACTOR),content[self.ACTION][self.ACTOR])
+ if self.ACTOR in content[self.ACTION]:
+ sb_action = sb_action +
self.encodeTag(btag(self.FIPA_PREF, self.ACTOR),
content[self.ACTION][self.ACTOR])
- if self.ACT in content[self.ACTION]:
- sb_action = sb_action +
self.encodeTag(btag(self.FIPA_PREF,self.ACT),content[self.ACTION][self.ACT])
+ if self.ACT in content[self.ACTION]:
+ sb_action = sb_action +
self.encodeTag(btag(self.FIPA_PREF, self.ACT),
content[self.ACTION][self.ACT])
- if self.ARGUMENT in content[self.ACTION]:
- container = None
- if self.BAG in content[self.ACTION][self.ARGUMENT]:
- container = self.BAG
- elif self.SEQ in content[self.ACTION][self.ARGUMENT]:
- container = self.SEQ
- elif self.ALT in content[self.ACTION][self.ARGUMENT]:
- container = self.ALT
-
- accum = ""
- if container == None:
- accum = content[self.ACTION][self.ARGUMENT]
- else:
- for literal in content[self.ACTION][self.ARGUMENT][container]:
- accum = accum + self.encodeTag(btag(self.RDF_PREF,self.LI),literal)
- accum = self.encodeTag(btag(self.RDF_PREF,container),accum)
-
- sb_action = sb_action +
self.encodeTag(btag(self.FIPA_PREF,self.ARGUMENT),accum)
+ if self.ARGUMENT in content[self.ACTION]:
+ container = None
+ if self.BAG in content[self.ACTION][self.ARGUMENT]:
+ container = self.BAG
+ elif self.SEQ in content[self.ACTION][self.ARGUMENT]:
+ container = self.SEQ
+ elif self.ALT in content[self.ACTION][self.ARGUMENT]:
+ container = self.ALT
-
- if self.IMPLBY in content[self.ACTION]:
- container = None
- # An action can be performed following alternative implementations
- if self.ALT in content[self.ACTION][self.IMPLBY]:
- container = self.ALT
-
- keys = [self.LANGUAGE, self.BINDING, self.CODE_URI, self.SCRIPT]
-
- if container == None:
- if self.CODE in content[self.ACTION][self.IMPLBY]:
- accum = ""
-
- for key in keys:
- if key in content[self.ACTION][self.IMPLBY][self.CODE]:
- accum = accum +
self.encodeTag(btag(self.FIPA_PREF,key),content[self.ACTION][self.IMPLBY][self.CODE][key])
- accum = self.encodeTag(btag(self.FIPA_PREF,self.CODE),accum)
-
- else:
- accum = ""
- for code in content[self.ACTION][self.IMPLBY][self.ALT]:
- accum2 = ""
- for key in keys:
- if key in code[self.CODE].keys():
- accum2 = accum2 +
self.encodeTag(btag(self.FIPA_PREF,key),code[self.CODE][key])
- accum = accum +
self.encodeTag(btag(self.FIPA_PREF,self.CODE),accum2)
-
- accum = self.encodeTag(btag(self.RDF_PREF,container),accum)
+ accum = ""
+ if container is None:
+ accum = content[self.ACTION][self.ARGUMENT]
+ else:
+ for literal in
content[self.ACTION][self.ARGUMENT][container]:
+ accum = accum + self.encodeTag(btag(self.RDF_PREF,
self.LI), literal)
+ accum = self.encodeTag(btag(self.RDF_PREF, container),
accum)
+ sb_action = sb_action +
self.encodeTag(btag(self.FIPA_PREF, self.ARGUMENT), accum)
- sb_action = sb_action +
self.encodeTag(btag(self.FIPA_PREF,self.IMPLBY),accum)
+ if self.IMPLBY in content[self.ACTION]:
+ container = None
+ # An action can be performed following alternative
implementations
+ if self.ALT in content[self.ACTION][self.IMPLBY]:
+ container = self.ALT
+ keys = [self.LANGUAGE, self.BINDING, self.CODE_URI,
self.SCRIPT]
+ if container is None:
+ if self.CODE in content[self.ACTION][self.IMPLBY]:
+ accum = ""
- if self.DONE in content[self.ACTION]:
- sb_action = sb_action +
self.encodeTag(btag(self.FIPA_PREF,self.DONE),content[self.ACTION][self.DONE])
+ for key in keys:
+ if key in
content[self.ACTION][self.IMPLBY][self.CODE]:
+ accum = accum +
self.encodeTag(btag(self.FIPA_PREF, key),
content[self.ACTION][self.IMPLBY][self.CODE][key])
+ accum = self.encodeTag(btag(self.FIPA_PREF,
self.CODE), accum)
-
- if self.RESULT in content[self.ACTION]:
- sb_action = sb_action +
self.encodeTag(btag(self.FIPA_PREF,self.RESULT),content[self.ACTION][self.RESULT])
+ else:
+ accum = ""
+ for code in
content[self.ACTION][self.IMPLBY][self.ALT]:
+ accum2 = ""
+ for key in keys:
+ if key in code[self.CODE].keys():
+ accum2 = accum2 +
self.encodeTag(btag(self.FIPA_PREF, key), code[self.CODE][key])
+ accum = accum +
self.encodeTag(btag(self.FIPA_PREF, self.CODE), accum2)
-
+ accum = self.encodeTag(btag(self.RDF_PREF, container),
accum)
- sb = sb + sb_action +
self.encodeEndTag(btag(self.FIPA_PREF,self.ACTION))
-
-
+ sb_action = sb_action +
self.encodeTag(btag(self.FIPA_PREF, self.IMPLBY), accum)
- # Proposition Encoding
- if self.PROPOSITION in content:
- accum = ""
- if self.SUBJECT in content[self.PROPOSITION]:
- accum = accum +
self.encodeTag(btag(self.RDF_PREF,self.SUBJECT),content[self.PROPOSITION][self.SUBJECT])
- if self.PREDICATE in content[self.PROPOSITION]:
- accum = accum +
self.encodeTag(btag(self.RDF_PREF,self.PREDICATE),content[self.PROPOSITION][self.PREDICATE])
- if self.OBJECT in content[self.PROPOSITION]:
- accum = accum +
self.encodeTag(btag(self.RDF_PREF,self.OBJECT),content[self.PROPOSITION][self.OBJECT])
- if self.BELIEF in content[self.PROPOSITION]:
- accum = accum +
self.encodeTag(btag(self.FIPA_PREF,self.BELIEF),content[self.PROPOSITION][self.BELIEF])
-
- sb = sb + self.encodeTag(btag(self.FIPA_PREF,self.PROPOSITION),accum)
+ if self.DONE in content[self.ACTION]:
+ sb_action = sb_action +
self.encodeTag(btag(self.FIPA_PREF, self.DONE),
content[self.ACTION][self.DONE])
+ if self.RESULT in content[self.ACTION]:
+ sb_action = sb_action +
self.encodeTag(btag(self.FIPA_PREF, self.RESULT),
content[self.ACTION][self.RESULT])
- sb = sb + self.encodeEndTag(btag(self.RDF_PREF,self.RDF))
-
- return sb
+ sb = sb + sb_action + self.encodeEndTag(btag(self.FIPA_PREF,
self.ACTION))
- # Description Encoding
- if self.DESCRIPTION in content:
- sb = sb +
self.encodeInitTagAttr(btag(self.RDF_PREF,self.DESCRIPTION),btag(self.RDF_PREF,self.ABOUT),content[self.DESCRIPTION][self.ABOUT])
- if self.DONE in content[self.DESCRIPTION]:
- sb = sb +
self.encodeTag(btag(self.FIPA_PREF,self.DONE),content[self.DESCRIPTION][self.DONE])
+ # Proposition Encoding
+ if self.PROPOSITION in content:
+ accum = ""
+ if self.SUBJECT in content[self.PROPOSITION]:
+ accum = accum + self.encodeTag(btag(self.RDF_PREF,
self.SUBJECT), content[self.PROPOSITION][self.SUBJECT])
+ if self.PREDICATE in content[self.PROPOSITION]:
+ accum = accum + self.encodeTag(btag(self.RDF_PREF,
self.PREDICATE), content[self.PROPOSITION][self.PREDICATE])
+ if self.OBJECT in content[self.PROPOSITION]:
+ accum = accum + self.encodeTag(btag(self.RDF_PREF,
self.OBJECT), content[self.PROPOSITION][self.OBJECT])
+ if self.BELIEF in content[self.PROPOSITION]:
+ accum = accum + self.encodeTag(btag(self.FIPA_PREF,
self.BELIEF), content[self.PROPOSITION][self.BELIEF])
-
- if self.RESULT in content[self.DESCRIPTION]:
- sb = sb_action +
self.encodeTag(btag(self.FIPA_PREF,self.RESULT),content[self.DESCRIPTION][self.RESULT])
+ sb = sb + self.encodeTag(btag(self.FIPA_PREF,
self.PROPOSITION), accum)
+
+ sb = sb + self.encodeEndTag(btag(self.RDF_PREF, self.RDF))
+
+ return sb
+
+ # Description Encoding
+ if self.DESCRIPTION in content:
+ sb = sb + self.encodeInitTagAttr(btag(self.RDF_PREF,
self.DESCRIPTION), btag(self.RDF_PREF, self.ABOUT),
content[self.DESCRIPTION][self.ABOUT])
+ if self.DONE in content[self.DESCRIPTION]:
+ sb = sb + self.encodeTag(btag(self.FIPA_PREF, self.DONE),
content[self.DESCRIPTION][self.DONE])
+
+ if self.RESULT in content[self.DESCRIPTION]:
+ sb = sb_action + self.encodeTag(btag(self.FIPA_PREF,
self.RESULT), content[self.DESCRIPTION][self.RESULT])
+ sb = sb + self.encodeEndTag(btag(self.FIPA_PREF, self.ACTION))
+ """
+ ***************************************************
+ * Decoding methods *
+ ***************************************************
+ """
- sb = sb + self.encodeEndTag(btag(self.FIPA_PREF,self.ACTION))
-
+ #This method is called when start the document XML
+ def startDocument(self):
+ self.prefixs = Newdict()
+ self.content = Newdict()
+ self.resource = {}
+ self.datatype = {}
+ self.container = None
+ self.accumulator = ""
+ self.s = ""
+ self.p = ""
+ def startPrefixMapping(self, prefix, uri):
+ if uri == self.RDF_NS:
+ self.prefixs['rdf'] = prefix
+ elif uri == self.FIPA_NS:
+ self.prefixs['fipa'] = prefix
+ else:
+ print "RDFParser: Not recognized URI"
+ #excepcio sino peta despres la clau
+ def startElementNS(self, name, qname, attributes):
+ print "RDF0: seNS" + str(name) + " " + str(qname) + " " +
str(attributes)
+ self.accumulator = ""
- """
- ***************************************************
- * Decoding methods *
- ***************************************************
- """
-
- #This method is called when start the document XML
- def startDocument(self):
- self.prefixs = Newdict()
- self.content = Newdict()
- self.resource = {}
- self.datatype = {}
- self.container = None
- self.accumulator = ""
- self.s = ""
- self.p = ""
-
+ # Fix "lower" bug
+ if qname is None:
+ qname = ""
- def startPrefixMapping(self,prefix,uri):
- if uri == self.RDF_NS:
- self.prefixs['rdf']=prefix
- elif uri == self.FIPA_NS:
- self.prefixs['fipa']=prefix
- else:
- print "RDFParser: Not recognized URI"
- #excepcio sino peta despres la clau
-
+ #fipa Actions
+ if str(self.FIPA_NS + self.ACTION).lower() == str(name[0] +
name[1]).lower():
+ #if btag(self.prefixs.fipa,self.ACTION).lower() == qname.lower():
+ print "MATCH ACTION"
+ self.content[self.ACTION] = Newdict()
+ self.s = self.ACTION
+ if btag(self.prefixs.rdf, self.ID) in attributes.getQNames():
+ self.content[self.ACTION][self.ID] =
attributes.getValueByQName(btag(self.prefixs.rdf, self.ID))
+ elif btag(self.prefixs.rdf, self.ABOUT) in
attributes.getQNames():
+ self.content[self.ACTION][self.ABOUT] =
attributes.getValueByQName(btag(self.prefixs.rdf, self.ABOUT))
- def startElementNS(self, name, qname, attributes):
-
- print "RDF0: seNS"+str(name)+" "+str(qname)+" "+str(attributes)
-
- self.accumulator = ""
-
- # Fix "lower" bug
- if qname == None:
- qname = ""
+ elif str(self.FIPA_NS + self.ARGUMENT).lower() == str(name[0] +
name[1]).lower():
+ #elif btag(self.prefixs.fipa,self.ARGUMENT).lower() ==
qname.lower():
+ self.content[self.s][self.ARGUMENT] = Newdict()
+ self.p = self.ARGUMENT
- #fipa Actions
- if str(self.FIPA_NS+self.ACTION).lower() == str(name[0]+name[1]).lower():
- #if btag(self.prefixs.fipa,self.ACTION).lower() == qname.lower():
- print "MATCH ACTION"
- self.content[self.ACTION] = Newdict()
- self.s = self.ACTION
- if btag(self.prefixs.rdf,self.ID) in attributes.getQNames():
- self.content[self.ACTION][self.ID] =
attributes.getValueByQName(btag(self.prefixs.rdf,self.ID))
- elif btag(self.prefixs.rdf,self.ABOUT) in attributes.getQNames():
- self.content[self.ACTION][self.ABOUT] =
attributes.getValueByQName(btag(self.prefixs.rdf,self.ABOUT))
+ elif str(self.FIPA_NS + self.IMPLBY).lower() == str(name[0] +
name[1]).lower():
+ #elif btag(self.prefixs.fipa,self.IMPLBY).lower() == qname.lower():
+ self.content[self.s][self.IMPLBY] = Newdict()
+ self.p = self.IMPLBY
+ elif str(self.FIPA_NS + self.CODE).lower() == str(name[0] +
name[1]).lower():
+ #elif btag(self.prefixs.fipa,self.CODE).lower() == qname.lower():
+ self.code = Newdict()
- elif str(self.FIPA_NS+self.ARGUMENT).lower() ==
str(name[0]+name[1]).lower():
- #elif btag(self.prefixs.fipa,self.ARGUMENT).lower() == qname.lower():
- self.content[self.s][self.ARGUMENT] = Newdict()
- self.p = self.ARGUMENT
+ elif str(self.RDF_NS + self.BAG).lower() == str(name[0] +
name[1]).lower():
+ #elif btag(self.prefixs.rdf,self.BAG).lower() == qname.lower():
+ self.content[self.s][self.p][self.BAG] = []
+ self.container = self.BAG
- elif str(self.FIPA_NS+self.IMPLBY).lower() ==
str(name[0]+name[1]).lower():
- #elif btag(self.prefixs.fipa,self.IMPLBY).lower() == qname.lower():
- self.content[self.s][self.IMPLBY] = Newdict()
- self.p = self.IMPLBY
-
- elif str(self.FIPA_NS+self.CODE).lower() == str(name[0]+name[1]).lower():
- #elif btag(self.prefixs.fipa,self.CODE).lower() == qname.lower():
- self.code = Newdict()
+ elif str(self.RDF_NS + self.SEQ).lower() == str(name[0] +
name[1]).lower():
+ #elif btag(self.prefixs.rdf,self.SEQ).lower() == qname.lower():
+ self.content[self.s][self.p][self.SEQ] = []
+ self.container = self.SEQ
- elif str(self.RDF_NS+self.BAG).lower() == str(name[0]+name[1]).lower():
- #elif btag(self.prefixs.rdf,self.BAG).lower() == qname.lower():
- self.content[self.s][self.p][self.BAG] = []
- self.container = self.BAG
+ elif str(self.RDF_NS + self.ALT).lower() == str(name[0] +
name[1]).lower():
+ #elif btag(self.prefixs.rdf,self.ALT).lower() == qname.lower():
+ self.content[self.s][self.p][self.ALT] = []
+ self.container = self.ALT
- elif str(self.RDF_NS+self.SEQ).lower() == str(name[0]+name[1]).lower():
- #elif btag(self.prefixs.rdf,self.SEQ).lower() == qname.lower():
- self.content[self.s][self.p][self.SEQ] = []
- self.container = self.SEQ
+ #fipa Propositions
+ elif str(self.FIPA_NS + self.PROPOSITION).lower() == str(name[0] +
name[1]).lower():
+ #elif btag(self.prefixs.fipa,self.PROPOSITION).lower() ==
qname.lower():
+ self.content[self.PROPOSITION] = Newdict()
+ self.s = self.PROPOSITION
- elif str(self.RDF_NS+self.ALT).lower() == str(name[0]+name[1]).lower():
- #elif btag(self.prefixs.rdf,self.ALT).lower() == qname.lower():
- self.content[self.s][self.p][self.ALT] = []
- self.container = self.ALT
-
+ #rdf Descriptions
+ elif str(self.RDF_NS + self.DESCRIPTION).lower() == str(name[0] +
name[1]).lower():
+ #elif btag(self.prefixs.rdf,self.DESCRIPTION).lower() ==
qname.lower():
+ self.content[self.DESCRIPTION] = Newdict()
+ self.s = self.DESCRIPTION
+ if btag(self.prefixs.rdf, self.ABOUT) in
attributes.getQNames():
+ self.content[self.DESCRIPTION][self.ABOUT] =
attributes.getValueByQName(btag(self.prefixs.rdf, self.ABOUT))
- #fipa Propositions
- elif str(self.FIPA_NS+self.PROPOSITION).lower() ==
str(name[0]+name[1]).lower():
- #elif btag(self.prefixs.fipa,self.PROPOSITION).lower() == qname.lower():
- self.content[self.PROPOSITION]=Newdict()
- self.s = self.PROPOSITION
+ else:
+ print "NO FIPA MATCH"
+ #self.content[name[1]] = None
- #rdf Descriptions
- elif str(self.RDF_NS+self.DESCRIPTION).lower() ==
str(name[0]+name[1]).lower():
- #elif btag(self.prefixs.rdf,self.DESCRIPTION).lower() == qname.lower():
- self.content[self.DESCRIPTION]=Newdict()
- self.s = self.DESCRIPTION
- if btag(self.prefixs.rdf,self.ABOUT) in attributes.getQNames():
- self.content[self.DESCRIPTION][self.ABOUT] =
attributes.getValueByQName(btag(self.prefixs.rdf,self.ABOUT))
+ print "SELF.S " + str(self.s)
- else:
- print "NO FIPA MATCH"
- #self.content[name[1]] = None
-
- print "SELF.S "+str(self.s)
+ # if tag refers to a resource
+ if str(self.RDF_NS + self.RESOURCE).lower() == str(name[0] +
name[1]).lower():
+ #if btag(self.prefixs.rdf,self.RESOURCE) in attributes.getQNames():
+ self.resource[name] =
attributes.getValueByQName(btag(self.prefixs.rdf, self.RESOURCE))
- # if tag refers to a resource
- if str(self.RDF_NS+self.RESOURCE).lower() ==
str(name[0]+name[1]).lower():
- #if btag(self.prefixs.rdf,self.RESOURCE) in attributes.getQNames():
- self.resource[name] =
attributes.getValueByQName(btag(self.prefixs.rdf,self.RESOURCE))
+ # catching datatype
+ if str(self.RDF_NS + self.DATATYPE).lower() == str(name[0] +
name[1]).lower():
+ #if btag(self.prefixs.rdf,self.DATATYPE) in attributes.getQNames():
+ self.datatype[name] =
attributes.getValueByQName(btag(self.prefixs.rdf, self.DATATYPE))
- # catching datatype
- if str(self.RDF_NS+self.DATATYPE).lower() ==
str(name[0]+name[1]).lower():
- #if btag(self.prefixs.rdf,self.DATATYPE) in attributes.getQNames():
- self.datatype[name] =
attributes.getValueByQName(btag(self.prefixs.rdf,self.DATATYPE))
+ print "RDF0: seNS: self.s " + str(self.s)
- print "RDF0: seNS: self.s "+str(self.s)
+ def endElementNS(self, name, qname):
-
-
-
-
- def endElementNS(self, name, qname):
+ print "RDF0: eeNS" + str(name) + " " + str(qname)
+ print "RDF0: eeNS: self.s " + str(self.s)
- print "RDF0: eeNS"+str(name)+" "+str(qname)
- print "RDF0: eeNS: self.s "+str(self.s)
+ # tags with resource don't need any value
+ if name in self.resource:
+ self.accumulator = {self.RESOURCE: self.resource[name]}
+ self.resource.clear()
- # tags with resource don't need any value
- if self.resource.has_key(name):
- self.accumulator = {self.RESOURCE:self.resource[name]}
- self.resource.clear()
+ # Adding datatype to tag with value
+ if name in self.datatype:
+ self.accumulator = '"' + self.accumulator + '"' +
self.TYPE_SEP + self.datatype[name]
+ self.datatype.clear()
- # Adding datatype to tag with value
- if self.datatype.has_key(name):
- self.accumulator = '"'+ self.accumulator + '"' + self.TYPE_SEP +
self.datatype[name]
- self.datatype.clear()
-
+ # start name check
+ if self.ACTOR.lower() == name[1].lower():
+ self.content[self.s][self.ACTOR] = self.accumulator
- # start name check
-
- if self.ACTOR.lower() == name[1].lower():
- self.content[self.s][self.ACTOR] = self.accumulator
+ elif self.ACT.lower() == name[1].lower():
+ self.content[self.s][self.ACT] = self.accumulator
- elif self.ACT.lower() == name[1].lower():
- self.content[self.s][self.ACT] = self.accumulator
-
- elif self.ARGUMENT.lower() == name[1].lower():
- if self.content[self.s][self.ARGUMENT].keys() == []:
- self.content[self.s][self.ARGUMENT] = self.accumulator
+ elif self.ARGUMENT.lower() == name[1].lower():
+ if self.content[self.s][self.ARGUMENT].keys() == []:
+ self.content[self.s][self.ARGUMENT] = self.accumulator
- elif self.BAG.lower() == name[1].lower() or self.SEQ.lower() ==
name[1].lower() or self.ALT.lower() == name[1].lower():
- self.container = None
+ elif self.BAG.lower() == name[1].lower() or self.SEQ.lower() ==
name[1].lower() or self.ALT.lower() == name[1].lower():
+ self.container = None
-
- elif self.LI.lower() == name[1].lower():
- if self.container != None:
- self.content[self.s][self.p][self.container].append(self.accumulator)
- else: pass
+ elif self.LI.lower() == name[1].lower():
+ if self.container is not None:
+
self.content[self.s][self.p][self.container].append(self.accumulator)
+ else:
+ pass
- elif self.SUBJECT.lower() == name[1].lower():
- self.content[self.s][self.SUBJECT] = self.accumulator
+ elif self.SUBJECT.lower() == name[1].lower():
+ self.content[self.s][self.SUBJECT] = self.accumulator
- elif self.PREDICATE.lower() == name[1].lower():
- self.content[self.s][self.PREDICATE] = self.accumulator
+ elif self.PREDICATE.lower() == name[1].lower():
+ self.content[self.s][self.PREDICATE] = self.accumulator
- elif self.OBJECT.lower() == name[1].lower():
- self.content[self.s][self.OBJECT] = self.accumulator
+ elif self.OBJECT.lower() == name[1].lower():
+ self.content[self.s][self.OBJECT] = self.accumulator
- elif self.BELIEF.lower() == name[1].lower():
- self.content[self.s][self.BELIEF] = self.accumulator
+ elif self.BELIEF.lower() == name[1].lower():
+ self.content[self.s][self.BELIEF] = self.accumulator
- elif self.DONE.lower() == name[1].lower():
- self.content[self.s][self.DONE] = self.accumulator
+ elif self.DONE.lower() == name[1].lower():
+ self.content[self.s][self.DONE] = self.accumulator
- elif self.RESULT.lower() == name[1].lower():
- self.content[self.s][self.RESULT] = self.accumulator
+ elif self.RESULT.lower() == name[1].lower():
+ self.content[self.s][self.RESULT] = self.accumulator
- elif self.CODE.lower() == name[1].lower():
- if self.container != None:
-
self.content[self.s][self.p][self.container].append({self.CODE:self.code})
- else: self.content[self.s][self.p][self.CODE] = self.code
-
- elif self.LANGUAGE.lower() == name[1].lower():
- self.code[self.LANGUAGE] = self.accumulator
+ elif self.CODE.lower() == name[1].lower():
+ if self.container is not None:
+
self.content[self.s][self.p][self.container].append({self.CODE: self.code})
+ else:
+ self.content[self.s][self.p][self.CODE] = self.code
- elif self.BINDING.lower() == name[1].lower():
- self.code[self.BINDING] = self.accumulator
+ elif self.LANGUAGE.lower() == name[1].lower():
+ self.code[self.LANGUAGE] = self.accumulator
- elif self.CODE_URI.lower() == name[1].lower():
- self.code[self.CODE_URI] = self.accumulator
+ elif self.BINDING.lower() == name[1].lower():
+ self.code[self.BINDING] = self.accumulator
- elif self.SCRIPT.lower() == name[1].lower():
- self.code[self.SCRIPT] = self.accumulator
+ elif self.CODE_URI.lower() == name[1].lower():
+ self.code[self.CODE_URI] = self.accumulator
-
- self.accumulator=""
+ elif self.SCRIPT.lower() == name[1].lower():
+ self.code[self.SCRIPT] = self.accumulator
+ self.accumulator = ""
+ def characters(self, buff):
+ self.accumulator = self.accumulator + buff
- def characters(self, buff):
- self.accumulator = self.accumulator + buff
+ # Main decoding method #
+ def parse(self, s):
+ parser = xml.sax.make_parser()
+
parser.start_namespace_decl("xml", "
http://www.w3.org/XML/1998/namespace")
+ #enabling namespaces
+ try:
+ parser.setFeature(xml.sax.handler.feature_namespaces, 1)
+ #parser.setFeature(xml.sax.handler.feature_namespace_prefixes,
1)
+ #parser.setFeature(xml.sax.handler.feature_string_interning, 1)
+ except xml.sax._exceptions.SAXNotSupportedException:
+ pass
+ except xml.sax._exceptions.SAXNotRecognizedException:
+ pass
-
- # Main decoding method #
- def parse(self, s):
- parser = xml.sax.make_parser()
-
parser.start_namespace_decl("xml", "
http://www.w3.org/XML/1998/namespace")
- #enabling namespaces
- try:
- parser.setFeature(xml.sax.handler.feature_namespaces, 1)
- #parser.setFeature(xml.sax.handler.feature_namespace_prefixes, 1)
- #parser.setFeature(xml.sax.handler.feature_string_interning, 1)
- except xml.sax._exceptions.SAXNotSupportedException: pass
- except xml.sax._exceptions.SAXNotRecognizedException:pass
+ #setting handler and start parsing
+ parser.setContentHandler(self)
+ parser.parse(cStringIO.StringIO(str(s)))
- #setting handler and start parsing
- parser.setContentHandler(self)
- parser.parse(cStringIO.StringIO(str(s)))
-
- #return generated content
- return self.content
+ #return generated content
+ return self.content
if __name__ == "__main__":
- f=open("example7.rdf","r")
- s=f.read()
- rdfparser=RDF0Parser()
- content=rdfparser.parse(s)
- print "#################################"
- #print content
- print content.pprint()
- #result=rdfparser.encode(content)
- #print result
- #print "#################################"
- #print rdfparser.parse(result)
+ f = open("example7.rdf", "r")
+ s = f.read()
+ rdfparser = RDF0Parser()
+ content = rdfparser.parse(s)
+ print "#################################"
+ #print content
+ print content.pprint()
+ #result=rdfparser.encode(content)
+ #print result
+ #print "#################################"
+ #print rdfparser.parse(result)
"""
=======================================
--- /trunk/spade/RPC.py Tue Jul 31 06:58:54 2012
+++ /trunk/spade/RPC.py Fri Nov 23 05:19:16 2012
@@ -1,65 +1,67 @@
+# -*- coding: utf-8 -*-
import Behaviour
import xmlrpclib
import xmpp
import types
+
class RPCServerBehaviour(Behaviour.EventBehaviour):
def _process(self):
- self.result=None
+ self.result = None
self.msg = self._receive(False)
- if self.msg != None:
+ if self.msg is not None:
if self.msg.getType() == "set":
-
- self.myAgent.DEBUG("RPC request
received: "+str(self.msg),'info',"rpc")
-
+
+ self.myAgent.DEBUG("RPC request received: " +
str(self.msg), 'info', "rpc")
+
mc = self.msg.getTag('query')
params, name = xmlrpclib.loads("<?xml version='1.0'?>%s" %
str(mc))
- name=name.lower()
- self.myAgent.DEBUG("Params processed: name="+name+"
params="+str(params) + " in " + str(self.myAgent.RPC.keys()),"info","rpc")
+ name = name.lower()
+ self.myAgent.DEBUG("Params processed: name=" + name + "
params=" + str(params) + " in " +
str(self.myAgent.RPC.keys()), "info", "rpc")
- if not self.myAgent.RPC.has_key(name):
- self.myAgent.DEBUG("RPC: 404 method not
found",'error',"rpc")
- xmlrpc_res = xmlrpclib.dumps(
xmlrpclib.Fault(404, "method not found"))
+ if name not in self.myAgent.RPC:
+ self.myAgent.DEBUG("RPC: 404 method not
found", 'error', "rpc")
+ xmlrpc_res =
xmlrpclib.dumps(xmlrpclib.Fault(404, "method not found"))
reply = self.msg.buildReply("error")
reply.setQueryPayload([xmpp.simplexml.XML2Node(xmlrpc_res)])
reply.setType("result")
reply.setFrom(self.myAgent.JID)
self.myAgent.send(reply)
return
-
- service,methodCall = self.myAgent.RPC[name]
-
- self.myAgent.DEBUG("service and method: "+ str(service)
+ " --> " + str(methodCall),"info","rpc")
-
- self.myAgent.DEBUG("Comparing service.getInputs(): "+
str(service.getInputs()) + " with params--> " + str(params),"info","rpc")
+
+ service, methodCall = self.myAgent.RPC[name]
+
+ self.myAgent.DEBUG("service and method: " + str(service)
+ " --> " + str(methodCall), "info", "rpc")
+
+ self.myAgent.DEBUG("Comparing service.getInputs(): " +
str(service.getInputs()) + " with params--> " + str(params), "info", "rpc")
ps = params[0].keys()
- for p in eval(str(service.getInputs())): #service.getP():
- self.myAgent.DEBUG("Comparing input "+str(p)+ "
with "+str(ps))
+ for p in eval(str(service.getInputs())): # service.getP():
+ self.myAgent.DEBUG("Comparing input " + str(p) + "
with " + str(ps))
if str(p) not in ps:
- self.myAgent.DEBUG("RPC: 500 missing
input: "+str(p)+ " is not in "+str(params),'error',"rpc")
- xmlrpc_res = xmlrpclib.dumps(
xmlrpclib.Fault(500, "missing input"))
+ self.myAgent.DEBUG("RPC: 500 missing input: " +
str(p) + " is not in " + str(params), 'error', "rpc")
+ xmlrpc_res =
xmlrpclib.dumps(xmlrpclib.Fault(500, "missing input"))
reply = self.msg.buildReply("error")
reply.setQueryPayload([xmpp.simplexml.XML2Node(xmlrpc_res)])
reply.setType("result")
reply.setFrom(self.myAgent.JID)
self.myAgent.send(reply)
return
-
+
try:
- self.myAgent.DEBUG("Calling method "+str(methodCall)+"
with params "+str(params),"info","rpc")
+ self.myAgent.DEBUG("Calling method " + str(methodCall)
+ " with params " + str(params), "info", "rpc")
if params == (None,):
result = methodCall()
else:
- args=""
- for k,v in params[0].items():
- args+=str(k)+"="+str(v)+","
- args=args[:-1]
- result = eval("methodCall("+args+")")
- except Exception,e:
- self.myAgent.DEBUG("RPC: 500 method
error: "+str(e),'error',"rpc")
- xmlrpc_res = xmlrpclib.dumps(
xmlrpclib.Fault(500, "method error: "+str(e)))
+ args = ""
+ for k, v in params[0].items():
+ args += str(k) + "=" + str(v) + ","
+ args = args[:-1]
+ result = eval("methodCall(" + args + ")")
+ except Exception, e:
+ self.myAgent.DEBUG("RPC: 500 method error: " +
str(e), 'error', "rpc")
+ xmlrpc_res =
xmlrpclib.dumps(xmlrpclib.Fault(500, "method error: " + str(e)))
reply = self.msg.buildReply("error")
reply.setQueryPayload([xmpp.simplexml.XML2Node(xmlrpc_res)])
reply.setType("result")
@@ -69,23 +71,24 @@
#Check outputs
try:
- fail=False
- outputs={}
- if type(result) == types.DictType:
- for q in eval(str(service.getOutputs())):
#service.getQ():
+ fail = False
+ outputs = {}
+ if isinstance(result, types.DictType):
+ for q in eval(str(service.getOutputs())): #
service.getQ():
if q not in result.keys():
- fail=True
+ fail = True
break
- else: outputs[q]=result[q]
+ else:
+ outputs[q] = result[q]
params = (outputs,)
else:
- self.myAgent.DEBUG("RPC method MUST return a
dict.",'error',"rpc")
- fail=True
+ self.myAgent.DEBUG("RPC method MUST return a
dict.", 'error', "rpc")
+ fail = True
except:
- fail=True
+ fail = True
if fail:
- self.myAgent.DEBUG("RPC: 500 missing
output: "+str(service.getQ()),'error',"rpc")
- xmlrpc_res = xmlrpclib.dumps(
xmlrpclib.Fault(500, "missing output"))
+ self.myAgent.DEBUG("RPC: 500 missing output: " +
str(service.getQ()), 'error', "rpc")
+ xmlrpc_res =
xmlrpclib.dumps(xmlrpclib.Fault(500, "missing output"))
reply = self.msg.buildReply("error")
reply.setQueryPayload([xmpp.simplexml.XML2Node(xmlrpc_res)])
reply.setType("result")
@@ -94,18 +97,18 @@
return
#Everything was ok. Return results
- xmlrpc_res = xmlrpclib.dumps( params ,
methodresponse=True,allow_none=True)
+ xmlrpc_res = xmlrpclib.dumps(params, methodresponse=True,
allow_none=True)
reply = self.msg.buildReply("result")
reply.setQueryPayload([xmpp.simplexml.XML2Node(xmlrpc_res)])
self.myAgent.send(reply)
- self.myAgent.DEBUG("RPC: method succesfully served: "+
str(reply),'ok',"rpc")
+ self.myAgent.DEBUG("RPC: method succesfully served: " +
str(reply), 'ok', "rpc")
-
else:
- self.myAgent.DEBUG("RPCServerBehaviour returned with no
message", "warn","rpc")
-
+ self.myAgent.DEBUG("RPCServerBehaviour returned with no
message", "warn", "rpc")
+
+
class RPCClientBehaviour(Behaviour.OneShotBehaviour):
-
+
def __init__(self, service, inputs, num):
'''
This behaviour makes the Remote Procedure Call to the server
@@ -120,23 +123,23 @@
self.num = num
def _process(self):
- self.result=None
-
+ self.result = None
+
#send IQ methodCall
params = self.inputs
- ps = None
- ps = self.service.getP()
#self.service.getDAD().getServices()[0].getProperty("P")
- for p in ps: #check all Preconditions are True
+ ps = None
+ ps = self.service.getP() #
self.service.getDAD().getServices()[0].getProperty("P")
+ for p in ps: # check all Preconditions are True
#if not p in self.inputs.keys():
if not self.myAgent.askBelieve(p):
- self.myAgent.DEBUG("Precondition "+ str(p) + " is not
satisfied. Can't call method "+self.service.getName(),'error',"rpc")
- self.result=False
+ self.myAgent.DEBUG("Precondition " + str(p) + " is not
satisfied. Can't call method " + self.service.getName(), 'error', "rpc")
+ self.result = False
return
#else: params[p] = self.inputs[p]
-
+
#params = tuple(ps)
- self.myAgent.DEBUG("Params processed: "+str(params),"info","rpc")
-
+ self.myAgent.DEBUG("Params processed: " +
str(params), "info", "rpc")
+
#if agent is a BDIAgent check preconditions
#if "askBelieve" in dir(self.myAgent):
# for p in params:
@@ -144,35 +147,35 @@
# self.result=False
# self.myAgent.DEBUG("Precondition "+ str(p) + " is not
satisfied. Can't call method "+self.service.getName(),'error',"rpc")
# return
-
- payload = xmlrpclib.dumps( (params,) ,
methodname=self.service.getName(),allow_none=True)
- self.myAgent.DEBUG("Marshalled "+payload,"info","rpc")
+
+ payload = xmlrpclib.dumps((params,),
methodname=self.service.getName(), allow_none=True)
+ self.myAgent.DEBUG("Marshalled " + payload, "info", "rpc")
payload_node = xmpp.simplexml.XML2Node(payload)
to = xmpp.protocol.JID(self.service.getOwner().getName())
- iq =
xmpp.protocol.Iq(typ='set',queryNS="jabber:iq:rpc",frm=self.myAgent.JID,to=to,attrs={'id':self.num})
+ iq =
xmpp.protocol.Iq(typ='set', queryNS="jabber:iq:rpc",
frm=self.myAgent.JID, to=to, attrs={'id': self.num})
iq.setQueryPayload([payload_node])
- self.myAgent.DEBUG("Calling method with: "+str(iq),"info","rpc")
+ self.myAgent.DEBUG("Calling method with: " +
str(iq), "info", "rpc")
self.myAgent.send(iq)
- self.myAgent.DEBUG(self.service.getName() + " method called.
Waiting for response",'ok',"rpc")
-
+ self.myAgent.DEBUG(self.service.getName() + " method called.
Waiting for response", 'ok', "rpc")
+
#receive IQ methodResponse
self.msg = self._receive(True)
- if self.msg != None:
- self.myAgent.DEBUG("Response received for
method "+self.service.getName()+":" +str(self.msg),'ok',"rpc")
+ if self.msg is not None:
+ self.myAgent.DEBUG("Response received for method " +
self.service.getName() + ":" + str(self.msg), 'ok', "rpc")
if self.msg.getType() == "result":
try:
params, method = xmlrpclib.loads("<?xml
version='1.0'?>%s" % self.msg)
- self.DEBUG("Returned params "+str(params),'ok',"rpc")
+ self.DEBUG("Returned params " +
str(params), 'ok', "rpc")
self.result = params[0]
#if agent is a BDIAgent add result params as
postconditions
- for k,v in self.result.items(): #[0]:
- self.myAgent.kb.set(k,v)
+ for k, v in self.result.items(): # [0]:
+ self.myAgent.kb.set(k, v)
for q in self.service.getQ():
if not self.myAgent.askBelieve(q):
- raise Exception("PostCondition "+str(q)+ " not
satisfied.")
+ raise Exception("PostCondition " + str(q) + "
not satisfied.")
return self.result
- except Exception,e:
- self.myAgent.DEBUG("Error executing RPC
service: "+str(e),"error","rpc")
+ except Exception, e:
+ self.myAgent.DEBUG("Error executing RPC service: " +
str(e), "error", "rpc")
self.result = False
return False
else:
@@ -181,5 +184,3 @@
else:
self.result = False
return False
-
-
=======================================
--- /trunk/spade/ReceivedObject.py Wed Jun 21 11:10:23 2006
+++ /trunk/spade/ReceivedObject.py Fri Nov 23 05:19:16 2012
@@ -1,39 +1,39 @@
+# -*- coding: utf-8 -*-
class ReceivedObject:
- def __init__(self, by=None, _from=None, date=None, id=None, via=None):
-
self.by = by
- self._from = _from
- self.date = date
-
self.id = id
- self.via = via
+ def __init__(self, by=None, _from=None, date=None, id=None, via=None):
+
self.by = by
+ self._from = _from
+ self.date = date
+
self.id = id
+ self.via = via
- def getBy(self):
- return
self.by
-
- def setBy(self,by):
-
self.by = by
+ def getBy(self):
+ return
self.by
- def getFrom(self):
- return self._from
-
- def setFrom(self,_from):
- self._from = _from
+ def setBy(self, by):
+
self.by = by
- def getDate(self):
- return self.date
-
- def setDate(self,date):
- self.date = date
+ def getFrom(self):
+ return self._from
+
+ def setFrom(self, _from):
+ self._from = _from
+
+ def getDate(self):
+ return self.date
+
+ def setDate(self, date):
+ self.date = date
+
+ def getId(self):
+ return
self.id
- def getId(self):
- return
self.id
-
- def setId(self,id):
-
self.id = id
+ def setId(self, id):
+
self.id = id
- def getVia(self):
- return self.via
-
- def setVia(self,via):
- self.via = via
+ def getVia(self):
+ return self.via
+ def setVia(self, via):
+ self.via = via
=======================================
--- /trunk/spade/SIMBA.py Wed Jun 21 11:10:23 2006
+++ /trunk/spade/SIMBA.py Fri Nov 23 05:19:16 2012
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
import xmpp
import threading
import Agent
@@ -11,61 +12,59 @@
SIMBAPORT = 20001
+
class SIMBA(Agent.PlatformAgent):
- class OutboxBehaviour(Behaviour.Behaviour):
- '''
- Behaviour that routes outgoing SIMBA messages
- '''
-
- def __init__(self):
- Behaviour.Behaviour.__init__(self)
+ class OutboxBehaviour(Behaviour.Behaviour):
+ '''
+ Behaviour that routes outgoing SIMBA messages
+ '''
- def sendToSimba(self, msg, to):
- '''Sends a message to a SIMBA receiver'''
-
- # Socket work
- ip = to.strip("simba://")
- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- try:
- s.connect((ip, SIMBAPORT))
- except:
- print "Could not connect to SIMBA socket on " + str(ip)
- s.send(str(msg))
- s.close()
-
- def _process(self):
- msg = self._receive(True)
- if (msg != None):
- to_list = msg.getReceivers()
- d = {}
- for to in to_list:
- self.sendToSimba(msg, to)
- else:
- print "SIMBA::dying... it shouldn't happen"
-
- class InboxBehaviour(Behaviour.Behaviour):
- '''
- Behaviour that routes incoming SIMBA messages
- '''
-
- class SimbaRequestHandler(SocketServer.DatagramRequestHandler):
- '''
- Request handler for SIMBA messages
- '''
- def handle(self):
- print "SIMBA SS: New incoming message"
+ def __init__(self):
+ Behaviour.Behaviour.__init__(self)
+
+ def sendToSimba(self, msg, to):
+ '''Sends a message to a SIMBA receiver'''
+
+ # Socket work
+ ip = to.strip("simba://")
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ try:
+ s.connect((ip, SIMBAPORT))
+ except:
+ print "Could not connect to SIMBA socket on " + str(ip)
+ s.send(str(msg))
+ s.close()
- def onStart(self):
- self.SS = SocketServer.ThreadingUDPServer(("", SIMBAPORT),
SimbaRequestHandler)
- print "SIMBA SS listening on port ", SIMBAPORT
- self.SS.serve_forever()
+ def _process(self):
+ msg = self._receive(True)
+ if (msg is not None):
+ to_list = msg.getReceivers()
+ d = {}
+ for to in to_list:
+ self.sendToSimba(msg, to)
+ else:
+ print "SIMBA::dying... it shouldn't happen"
- def __init__(self, node, password, server, port):
- Agent.PlatformAgent.__init__(self, node, password, server, port,
debug=[])
+ class InboxBehaviour(Behaviour.Behaviour):
+ '''
+ Behaviour that routes incoming SIMBA messages
+ '''
- def _setup(self):
- self.addBehaviour(self.InboxBehaviour(), None)
- self.setDefaultBehaviour(self.OutboxBehaviour())
+ class SimbaRequestHandler(SocketServer.DatagramRequestHandler):
+ '''
+ Request handler for SIMBA messages
+ '''
+ def handle(self):
+ print "SIMBA SS: New incoming message"
+ def onStart(self):
+ self.SS = SocketServer.ThreadingUDPServer(("", SIMBAPORT),
SimbaRequestHandler)
+ print "SIMBA SS listening on port ", SIMBAPORT
+ self.SS.serve_forever()
+ def __init__(self, node, password, server, port):
+ Agent.PlatformAgent.__init__(self, node, password, server, port,
debug=[])
+ def _setup(self):
+ self.addBehaviour(self.InboxBehaviour(), None)
+ self.setDefaultBehaviour(self.OutboxBehaviour())
=======================================
--- /trunk/spade/SL0Parser.py Sun Jul 11 16:13:46 2010
+++ /trunk/spade/SL0Parser.py Fri Nov 23 05:19:16 2012
@@ -1,81 +1,82 @@
+# -*- coding: utf-8 -*-
from pyparsing import *
import sys
+
class SL0Parser:
- """
- SL parser
- """
+ """
+ SL parser
+ """
- def __init__(self):
+ def __init__(self):
- lpar = Literal("(").suppress()
- rpar = Literal(")").suppress()
-
+ lpar = Literal("(").suppress()
+ rpar = Literal(")").suppress()
- word = ~Literal(":")+ Word(alphanums+"-_@./\\:")
- StringLiteral = Combine( Literal('"') + ZeroOrMore( CharsNotIn('\"') | (
Literal('\\"') ) ) + Literal('"') ).streamline()
- String = ( word | StringLiteral ) #| ByteLengthEncodedString )
- Constant = String
-
- Key = String
- Expr = Forward()
- Parameter = Dict(Group(Literal(":").suppress() + Key + Group(Constant|
Expr)))
- Expr << Dict(Group( lpar + Key + Group(OneOrMore(Parameter)|
OneOrMore(Constant)|OneOrMore(Expr)) + rpar ))
- Content = ( lpar + OneOrMore(Expr) + rpar )
-
- self.bnf = Content
+ word = ~Literal(":") + Word(alphanums + "-_@./\\:")
+ StringLiteral = Combine(Literal('"') + ZeroOrMore(CharsNotIn('\"')
| (Literal('\\"'))) + Literal('"')).streamline()
+ String = (word | StringLiteral) # | ByteLengthEncodedString )
+ Constant = String
- #self.bnf.setDebug()
+ Key = String
+ Expr = Forward()
+ Parameter = Dict(Group(Literal(":").suppress() + Key +
Group(Constant | Expr)))
+ Expr << Dict(Group(lpar + Key + Group(OneOrMore(Parameter) |
OneOrMore(Constant) | OneOrMore(Expr)) + rpar))
+ Content = (lpar + OneOrMore(Expr) + rpar)
- try:
- self.bnf.validate()
- #print "BNF VALID!!!"
+ self.bnf = Content
- except Exception, err:
- print "ERROR: BNF NOT VALID!!!"
- print err
- #sys.exit(-1)
+ #self.bnf.setDebug()
- def parse(self,string):
- """
- parses a string
- returns a pyparsing.ParseResults
- """
+ try:
+ self.bnf.validate()
+ #print "BNF VALID!!!"
- m = None
- try:
- m = self.bnf.parseString(str(string))
- except ParseException, err:
- print err.line
- print " "*(err.column-1)+"|"
- print err
- #sys.exit(-1)
- except Exception, err:
- print "Unknown Parsing Exception"
- print err
- #sys.exit(-1)
+ except Exception, err:
+ print "ERROR: BNF NOT VALID!!!"
+ print err
+ #sys.exit(-1)
- return m
+ def parse(self, string):
+ """
+ parses a string
+ returns a pyparsing.ParseResults
+ """
+
+ m = None
+ try:
+ m = self.bnf.parseString(str(string))
+ except ParseException, err:
+ print err.line
+ print " " * (err.column - 1) + "|"
+ print err
+ #sys.exit(-1)
+ except Exception, err:
+ print "Unknown Parsing Exception"
+ print err
+ #sys.exit(-1)
+
+ return m
- def parseFile(self,file):
- """
- parses a file
- returns a pyparsing.ParseResults
- """
+ def parseFile(self, file):
+ """
+ parses a file
+ returns a pyparsing.ParseResults
+ """
- try:
- m = self.bnf.parseFile(file)
- except ParseException, err:
- print err.line
- print " "*(err.column-1)+"|"
- print err
- sys.exit(-1)
- except Exception, err:
- print "Unkwonw Exception"
- print err
- sys.exit(-1)
+ try:
+ m = self.bnf.parseFile(file)
+ except ParseException, err:
+ print err.line
+ print " " * (err.column - 1) + "|"
+ print err
+ sys.exit(-1)
+ except Exception, err:
+ print "Unkwonw Exception"
+ print err
+ sys.exit(-1)
- return m
+ return m
if __name__ == "__main__":
p = SL0Parser()
@@ -100,9 +101,9 @@
print msg.prueba.name.set.values()
"""
print "--"
-
+
slgrande = """((result
- (search
+ (search
(set
(df-agent-description
:name
@@ -118,10 +119,10 @@
(service-description
:name profiling
:type user-profiling-service)))))))"""
- slgrande="""((result (set (ams-agent-description
+ slgrande = """((result (set (ams-agent-description
:name (agent-identifier
:name
ag...@alien3.dsic.upv.es
-:addresses
+:addresses
(sequence
xmpp://
ag...@alien3.dsic.upv.es
)
@@ -132,7 +133,7 @@
(ams-agent-description
:name (agent-identifier
:name
ams.alien3.dsic.upv.es
-:addresses
+:addresses
(sequence
xmpp://
ams.alien3.dsic.upv.es
)
@@ -143,7 +144,7 @@
(ams-agent-description
:name (agent-identifier
:name
df.alien3.dsic.upv.es
-:addresses
+:addresses
(sequence
xmpp://
df.alien3.dsic.upv.es
)
@@ -156,7 +157,6 @@
msg = p.parse(slgrande)
print msg
for dfd in msg.result.search.set:
- d = DfAgentDescription()
- d.loadSL0(dfd[1])
- print str(d)
-
+ d = DfAgentDescription()
+ d.loadSL0(dfd[1])
+ print str(d)
=======================================
--- /trunk/spade/SPARQLKB.py Tue Jul 10 16:56:02 2012
+++ /trunk/spade/SPARQLKB.py Fri Nov 23 05:19:16 2012
@@ -1,39 +1,40 @@
+# -*- coding: utf-8 -*-
from logic import KB
from SPARQLWrapper import SPARQLWrapper, JSON, XML
from exceptions import NotImplementedError
-class SPARQLKB( KB ):
- '''SPARQL endpoint knowledge base'''
- def __init__( self, sentence=None, endpoint=None ):
- '''Constructor method
- Usage:
- sentence - RDF triple to be added to KB (not implemented; default:None)
- endpoint - URL of endpoint to query'''
- self.sparql = SPARQLWrapper( endpoint )
- if sentence:
- self.tell( sentence )
- def tell( self, sentence ):
- '''Adding triples to RDF store - not implemented'''
- raise NotImplementedError, 'Adding sentences to RDF knowledge bases is
not implemented'
+class SPARQLKB(KB):
+ '''SPARQL endpoint knowledge base'''
+ def __init__(self, sentence=None, endpoint=None):
+ '''Constructor method
+ Usage:
+ sentence - RDF triple to be added to KB (not implemented;
default:None)
+ endpoint - URL of endpoint to query'''
+ self.sparql = SPARQLWrapper(endpoint)
+ if sentence:
+ self.tell(sentence)
- def ask( self, query ):
- '''Queries the endpoint'''
- self.sparql.setQuery( query )
- self.sparql.setReturnFormat( XML )
- res = self.sparql.query().convert().getElementsByTagName( 'result' )
- res = [ dict( [ ( bin.attributes[ 'name' ].nodeValue,
bin.firstChild.firstChild.nodeValue ) for bin in
node.getElementsByTagName( 'binding' ) ] ) for node in res ]
- return res
-
+ def tell(self, sentence):
+ '''Adding triples to RDF store - not implemented'''
+ raise NotImplementedError('Adding sentences to RDF knowledge bases
is not implemented')
+
+ def ask(self, query):
+ '''Queries the endpoint'''
+ self.sparql.setQuery(query)
+ self.sparql.setReturnFormat(XML)
+ res = self.sparql.query().convert().getElementsByTagName('result')
+ res = [dict([(bin.attributes['name'].nodeValue,
bin.firstChild.firstChild.nodeValue) for bin in
node.getElementsByTagName('binding')]) for node in res]
+ return res
- def retract( self, sentence ):
- '''Removing triples from RDF store - not implemented'''
- raise NotImplementedError, 'Removing sentences to RDF knowledge bases
is not implemented'
+ def retract(self, sentence):
+ '''Removing triples from RDF store - not implemented'''
+ raise NotImplementedError('Removing sentences to RDF knowledge
bases is not implemented')
if __name__ == '__main__':
- s = SPARQLKB( endpoint='
http://lod.openlinksw.com/sparql' )
- for result in s.ask( '''
+ s = SPARQLKB(endpoint='
http://lod.openlinksw.com/sparql')
+ for result in s.ask('''
PREFIX gr:<
http://purl.org/goodrelations/v1#>
PREFIX rdfs: <
http://www.w3.org/2000/01/rdf-schema#>
@@ -45,16 +46,16 @@
?ps gr:hasCurrencyValue ?p.
?ps gr:hasCurrency ?c
FILTER( regex( ?l, "yoghurt", "i" ) )
-} ORDER BY ?p LIMIT 500 ''' ):
- print result[ 'l' ], result[ 'p' ], result[ 'c' ]
+} ORDER BY ?p LIMIT 500 '''):
+ print result['l'], result['p'], result['c']
- s = SPARQLKB( endpoint='
http://dbpedia.org/sparql' )
- for result in s.ask( '''
+ s = SPARQLKB(endpoint='
http://dbpedia.org/sparql')
+ for result in s.ask('''
PREFIX rdfs: <
http://www.w3.org/2000/01/rdf-schema#>
SELECT ?label
- WHERE {
- <
http://dbpedia.org/resource/Croatia>
- rdfs:label
- ?label
- }''' ):
- print result[ 'label' ]
+ WHERE {
+ <
http://dbpedia.org/resource/Croatia>
+ rdfs:label
+ ?label
+ }'''):
+ print result['label']
=======================================
--- /trunk/spade/SWIKB.py Tue Jul 10 16:56:02 2012
+++ /trunk/spade/SWIKB.py Fri Nov 23 05:19:16 2012
@@ -1,48 +1,49 @@
+# -*- coding: utf-8 -*-
from logic import KB
from pyxf import swipl
-class SWIKB( KB ):
- '''SWI Prolog knowledge base'''
- def __init__( self, sentence=None, path='swipl' ):
- '''Constructor method
- Usage: SWIKB( sentence, path )
- sentence - Prolog sentence to be added to the KB (default: None)
- path - path to SWI Prolog executable (default: 'swipl')'''
- self.swi = swipl( path )
- if sentence:
- self.tell( sentence )
- def tell( self, sentence ):
- '''Adds sentence to KB'''
- sentence = sentence.strip()
- if sentence[ -1 ] == '.':
- sentence = sentence[ :-1 ]
- return self.swi.query( 'assert(' + sentence + ')' )
+class SWIKB(KB):
+ '''SWI Prolog knowledge base'''
+ def __init__(self, sentence=None, path='swipl'):
+ '''Constructor method
+ Usage: SWIKB( sentence, path )
+ sentence - Prolog sentence to be added to the KB (default: None)
+ path - path to SWI Prolog executable (default: 'swipl')'''
+ self.swi = swipl(path)
+ if sentence:
+ self.tell(sentence)
- def ask( self, query ):
- '''Queries the KB'''
- return self.swi.query( query )
+ def tell(self, sentence):
+ '''Adds sentence to KB'''
+ sentence = sentence.strip()
+ if sentence[-1] == '.':
+ sentence = sentence[:-1]
+ return self.swi.query('assert(' + sentence + ')')
+
+ def ask(self, query):
+ '''Queries the KB'''
+ return self.swi.query(query)
+
+ def retract(self, sentence):
+ '''Deletes sentence from KB'''
+ sentence = sentence.strip()
+ if sentence[-1] == '.':
+ sentence = sentence[:-1]
+ return self.swi.query('retract(' + sentence + ')')
- def retract( self, sentence ):
- '''Deletes sentence from KB'''
- sentence = sentence.strip()
- if sentence[ -1 ] == '.':
- sentence = sentence[ :-1 ]
- return self.swi.query( 'retract(' + sentence + ')' )
+ def loadModule(self, module):
+ '''Loads module to KB
+ Usage: instance.loadModule( path )
+ path - path to module'''
+ self.swi.load(module)
- def loadModule( self, module ):
- '''Loads module to KB
- Usage: instance.loadModule( path )
- path - path to module'''
- self.swi.load( module )
-
if __name__ == '__main__':
- kb = SWIKB()
- kb.tell( 'a(b,c)' )
- kb.tell( 'a(c,d)' )
- kb.tell( '( p(_X,_Y) :- a(_X,_Y) )' )
- kb.tell( '( p(_X,_Y) :- a(_X,_Z), p(_Z,_Y) )' )
- for result in kb.ask( 'p(X,Y)' ):
- print result
- kb.retract( 'a(b,c)' )
-
+ kb = SWIKB()
+ kb.tell('a(b,c)')
+ kb.tell('a(c,d)')
+ kb.tell('( p(_X,_Y) :- a(_X,_Y) )')
+ kb.tell('( p(_X,_Y) :- a(_X,_Z), p(_Z,_Y) )')
+ for result in kb.ask('p(X,Y)'):
+ print result
+ kb.retract('a(b,c)')
=======================================
--- /trunk/spade/SpadeConfigParser.py Tue Jul 10 16:56:02 2012
+++ /trunk/spade/SpadeConfigParser.py Fri Nov 23 05:19:16 2012
@@ -1,4 +1,4 @@
-#! python
+# -*- coding: utf-8 -*-
#import sys
from string import *
@@ -8,165 +8,146 @@
from xml.sax import make_parser
from xml.sax.handler import *
-"""
-spade = dict()
-domain = dict()
-acc = dict()
-acc["mtp"] = dict()
-ams = dict()
-df = dict()
-jabber = dict()
-simba = dict()
-"""
class ParseObject(dict):
- def __getattr__(self, name): return self[name]
+ def __getattr__(self, name):
+ return self[name]
+
class spadeXML:
- '''SPADE XML analyzer'''
- def __init__(self):
-
self.ch = spadeXMLHandler()
-
- def parseString(self, xmlstream, tag_attr, chars):
- self.ch.tag_attr = tag_attr
- parseString(xmlstream,
self.ch)
- return self.ch.tag_name, self.ch.message
+ '''SPADE XML analyzer'''
+ def __init__(self):
+
self.ch = spadeXMLHandler()
+ def parseString(self, xmlstream, tag_attr, chars):
+ self.ch.tag_attr = tag_attr
+ parseString(xmlstream,
self.ch)
+ return self.ch.tag_name, self.ch.message
+
class spadeXMLHandler(ContentHandler):
- def __init__(self):
- self.chars = ""
- self.message = ""
- self.current_tag = ""
- self.current_mtp = ""
+ def __init__(self):
+ self.chars = ""
+ self.message = ""
+ self.current_tag = ""
+ self.current_mtp = ""
- def startDocument(self):
+ def startDocument(self):
- self.content = ParseObject()
-
- def startElement(self, name, attrs):
- '''Called when a node starts'''
- self.chars = ""
- self.tag_name = name
- if name == "platform":
- self.current_tag = "platform"
- self.content['platform'] = ParseObject()
- #print "Current Tag: " + name
- elif name == "acc":
- self.current_tag = "acc"
- self.content['acc'] = ParseObject()
- self.content.acc['mtp'] = ParseObject()
- #print "Current Tag: " + name
- elif name == "ams":
- self.current_tag = "ams"
- self.content['ams'] = ParseObject()
- #print "Current Tag: " + name
- elif name == "df":
- self.current_tag = "df"
- self.content['df'] = ParseObject()
- #print "Current Tag: " + name
- elif name == "mtp":
- self.current_tag = attrs.getValue("name")
- self.current_mtp = self.current_tag
- self.content.acc.mtp[self.current_tag] = ParseObject()
-
- else:
- self.chars = ""
- self.tag_name = name
+ self.content = ParseObject()
+
+ def startElement(self, name, attrs):
+ '''Called when a node starts'''
+ self.chars = ""
+ self.tag_name = name
+ if name == "platform":
+ self.current_tag = "platform"
+ self.content['platform'] = ParseObject()
+ #print "Current Tag: " + name
+ elif name == "acc":
+ self.current_tag = "acc"
+ self.content['acc'] = ParseObject()
+ self.content.acc['mtp'] = ParseObject()
+ #print "Current Tag: " + name
+ elif name == "ams":
+ self.current_tag = "ams"
+ self.content['ams'] = ParseObject()
+ #print "Current Tag: " + name
+ elif name == "df":
+ self.current_tag = "df"
+ self.content['df'] = ParseObject()
+ #print "Current Tag: " + name
+ elif name == "mtp":
+ self.current_tag = attrs.getValue("name")
+ self.current_mtp = self.current_tag
+ self.content.acc.mtp[self.current_tag] = ParseObject()
+
+ else:
+ self.chars = ""
+ self.tag_name = name
+
+ def characters(self, ch):
+ '''Characters included in a node'''
+ self.chars = str(self.chars + ch)
+
+ def endElement(self, name):
+ '''Called when a node ends'''
+ if name == "hostname":
+ if self.current_tag == "platform":
+ self.content.platform['hostname'] = self.chars
+ elif self.current_tag == "ams":
+ self.content.ams['hostname'] = self.chars
+ elif self.current_tag == "df":
+ self.content.df['hostname'] = self.chars
+ elif self.current_tag == "acc":
+ self.content.acc['hostname'] = self.chars
+
+ elif name == "password":
+ if self.current_tag == "ams":
+ self.content.ams['password'] = self.chars
+ elif self.current_tag == "df":
+ self.content.df['password'] = self.chars
+ elif self.current_tag == "acc":
+ self.content.acc['password'] = self.chars
- def characters(self, ch):
- '''Characters included in a node'''
- self.chars = str(self.chars + ch)
-
- def endElement(self, name):
- '''Called when a node ends'''
- if name == "hostname":
- if self.current_tag == "platform":
- self.content.platform['hostname'] = self.chars
- elif self.current_tag == "ams":
- self.content.ams['hostname'] = self.chars
- elif self.current_tag == "df":
- self.content.df['hostname'] = self.chars
- elif self.current_tag == "acc":
- self.content.acc['hostname'] = self.chars
+ elif name == "port":
+ if self.current_tag == "platform":
+ self.content.platform['port'] = self.chars
+ elif self.current_tag == "ams":
+ self.content.ams['port'] = self.chars
+ elif self.current_tag == "df":
+ self.content.df['port'] = self.chars
+ elif self.current_tag == "acc":
+ self.content.acc['port'] = self.chars
+ else:
+ self.content.acc[self.current_tag]['port'] = self.chars
- elif name == "password":
- if self.current_tag == "ams":
- self.content.ams['password'] = self.chars
- elif self.current_tag == "df":
- self.content.df['password'] = self.chars
- elif self.current_tag == "acc":
- self.content.acc['password'] = self.chars
+ elif name == "mtp":
+ self.current_mtp = ""
- elif name == "port":
- if self.current_tag == "platform":
- self.content.platform['port'] = self.chars
- elif self.current_tag == "ams":
- self.content.ams['port'] = self.chars
- elif self.current_tag == "df":
- self.content.df['port'] = self.chars
- elif self.current_tag == "acc":
- self.content.acc['port'] = self.chars
- else:
- self.content.acc[self.current_tag]['port'] = self.chars
+ elif name == "protocol":
+ self.content.acc["mtp"][self.current_mtp]['protocol'] =
self.chars
- elif name == "mtp":
- self.current_mtp = ""
-
- elif name == "protocol":
- self.content.acc["mtp"][self.current_mtp]['protocol'] = self.chars
+ #elif name == "address":
+ #
self.content.acc[self.current_tag][self.current_mtp]['address'] = self.chars
- #elif name == "address":
- # self.content.acc[self.current_tag][self.current_mtp]['address'] =
self.chars
+ elif name == "instance":
+ self.content.acc["mtp"][self.current_mtp]['instance'] =
self.chars
- elif name == "instance":
- self.content.acc["mtp"][self.current_mtp]['instance'] = self.chars
+ elif name == "path":
+ self.content.platform["path"] = self.chars
- elif name == "path":
- self.content.platform["path"] = self.chars
+ elif name == "adminpasswd":
+ self.content["adminpasswd"] = self.chars
- elif name == "adminpasswd":
- self.content["adminpasswd"] = self.chars
class ConfigParser:
-
- """def get(self, section, keyword):
- answer = ""
- try:
- d = spade[section]
- answer = d[keyword]
- except:
- print "Section %s does not have keyword %s" % (str(section), keyword)
- return answer"""
-
- def __init__(self):
- # Create a parser
- self.parser = make_parser()
- # Tell the parser we are not interested in XML namespaces
- self.parser.setFeature(feature_namespaces, 0)
+ """def get(self, section, keyword):
+ answer = ""
+ try:
+ d = spade[section]
+ answer = d[keyword]
+ except:
+ print "Section %s does not have keyword %s" % (str(section),
keyword)
+ return answer"""
- # Create the handler
- self.dh = spadeXMLHandler()
+ def __init__(self):
+ # Create a parser
+ self.parser = make_parser()
- # Tell the parser to use our handler
- self.parser.setContentHandler(self.dh)
+ # Tell the parser we are not interested in XML namespaces
+ self.parser.setFeature(feature_namespaces, 0)
- def parse(self,fn):
+ # Create the handler
+ self.dh = spadeXMLHandler()
- # Parse the input
- self.parser.parse(fn)
+ # Tell the parser to use our handler
+ self.parser.setContentHandler(self.dh)
- return self.dh.content
+ def parse(self, fn):
- """
- # Manage the results
- spade['domain'] = domain
- spade['acc'] = acc
- spade['ams'] = ams
- spade['df'] = df
- spade['jabber'] = jabber
- spade['simba'] = simba
- #print spade
- """
+ # Parse the input
+ self.parser.parse(fn)
+ return self.dh.content
=======================================
--- /trunk/spade/Unit.py Wed Jun 6 10:16:25 2007
+++ /trunk/spade/Unit.py Fri Nov 23 05:19:16 2012
@@ -1,4 +1,4 @@
-# -*- coding: UTF8 -*-
+# -*- coding: utf-8 -*-
import random
import string
@@ -6,65 +6,102 @@
from Queue import *
import Behaviour
+
class CreationError(Exception):
- def __init__(self):
- Exception.__init__(self)
+ def __init__(self):
+ Exception.__init__(self)
+
+
class NotValidName(CreationError):
def __init__(self):
CreationError.__init__(self)
+
+
class NotValidGoalChange(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class NotValidType(CreationError):
def __init__(self):
CreationError.__init__(self)
+
+
class NotValidGoal(CreationError):
def __init__(self):
CreationError.__init__(self)
+
+
class NotAdmin(CreationError):
def __init__(self):
CreationError.__init__(self)
+
+
class NotSupervisor(CreationError):
def __init__(self):
CreationError.__init__(self)
+
+
class JoinError(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class PaswordNeeded(JoinError):
def __init__(self):
JoinError.__init__(self)
+
+
class MembersOnly(JoinError):
- def __init__(self):
- JoinError.__init__(self)
+ def __init__(self):
+ JoinError.__init__(self)
+
+
class BanedUser(JoinError):
def __init__(self):
JoinError.__init__(self)
+
+
class NickNameConflict(JoinError):
def __init__(self):
JoinError.__init__(self)
+
+
class MaximumUsers(JoinError):
def __init__(self):
JoinError.__init__(self)
+
+
class LockedUnit(JoinError):
def __init__(self):
JoinError.__init__(self)
+
+
class Unavailable(Exception):
def __init__(self):
- Exception.__init__(self)
+ Exception.__init__(self)
+
+
class DestroyError(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class NotValidUnit(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class LastOwner(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class Unit(Behaviour.OneShotBehaviour):
- def __init__(self,agent, nick, name, type="Team", goalList=[],
agentList=[], contentLanguage="sl",password=None,create=True):
+ def __init__(self, agent, nick, name, type="Team", goalList=[],
agentList=[], contentLanguage="sl", password=None, create=True):
Behaviour.OneShotBehaviour.__init__(self)
- self.myAgent=agent
+ self.myAgent = agent
self.name = name
self.type = type
self.goalList = goalList
@@ -73,660 +110,641 @@
self.platform = self.myAgent.getSpadePlatformJID()
self.muc_name = self.myAgent.getMUC()
self._roster = {}
- self.nick=nick
- self.password=password
- self.create=create
- self.parent_type=None
- self.parent=None
- id_base
= "".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)]) #@UnusedVariable
+ self.nick = nick
+ self.password = password
+ self.create = create
+ self.parent_type = None
+ self.parent = None
+ id_base = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)]) # @UnusedVariable
self.ID = str(name) + str(self.myAgent.getAID().getName()) +
id_base
- self.state="unavailable"
- self.UnavailableMsg="Unit"
- self.members=[]
- self.owner_admin=False
-
+ self.state = "unavailable"
+ self.UnavailableMsg = "Unit"
+ self.members = []
+ self.owner_admin = False
def setup(self):
- pass
-
-
-
-
+ pass
def myCreate(self):
- if not self.checkGoal(self.goalList):
- raise NotValidGoal
- elif not self.checkType():
- raise NotValidType
- elif self.type=="Hierarchy" and self.password==None:
- raise PaswordNeeded
- elif not self.testRoomName():
- raise NotValidName
- elif not self.createRoom():
- raise CreationError
- else:
- self.state="available"
- if self.agentList!=[]:
- #enviando invitaciones
+ if not self.checkGoal(self.goalList):
+ raise NotValidGoal
+ elif not self.checkType():
+ raise NotValidType
+ elif self.type == "Hierarchy" and self.password is None:
+ raise PaswordNeeded
+ elif not self.testRoomName():
+ raise NotValidName
+ elif not self.createRoom():
+ raise CreationError
+ else:
+ self.state = "available"
+ if self.agentList != []:
+ #enviando invitaciones
self.invite(self.agentList)
- #registrando en el DF
- #dad = DF.DfAgentDescription()
- #ds = DF.ServiceDescription()
- #ds.setType("Unit: "+self.parent)
- #ds.setName(
self.name)
- #dad.addService(ds)
- # res = self.myAgent.registerService(dad)
- #anyadimos el comportamiento que lee los presence
- self.owner_admin=True
- p = Presence()
- t = Behaviour.MessageTemplate(p)
-
self.presenceBehaviour=self.PresenceBehaviour(self.muc_name,
self.name,self.nick,self)
- self.myAgent.addBehaviour(self.presenceBehaviour, t)
+ #registrando en el DF
+ #dad = DF.DfAgentDescription()
+ #ds = DF.ServiceDescription()
+ #ds.setType("Unit: "+self.parent)
+ #ds.setName(
self.name)
+ #dad.addService(ds)
+ # res = self.myAgent.registerService(dad)
+ #anyadimos el comportamiento que lee los presence
+ self.owner_admin = True
+ p = Presence()
+ t = Behaviour.MessageTemplate(p)
+ self.presenceBehaviour = self.PresenceBehaviour(self.muc_name,
self.name, self.nick, self)
+ self.myAgent.addBehaviour(self.presenceBehaviour, t)
def myJoin(self):
- #The Organization exists
- if not self.testUnitName():
- raise NotValidName
- #The room no existe
- elif not self.myJoinRoom():
- raise JoinError
- #No es una organizacion
- else:
- info=self.getInfo()
- if info:
- self.type = info["type"]
- self.contentLanguage = info["contentLanguage"]
- self.parent=info["parent"]
- parent_info=self.myAgent.getOrganizationInfo(self.parent)
- self.parent_type=parent_info["type"]
- self.goal=info["goal"]
- self.state="available"
- p = Presence()
- t = Behaviour.MessageTemplate(p)
-
self.presenceBehaviour=self.PresenceBehaviour(self.muc_name,
self.name,self.nick,self)
- self.myAgent.addBehaviour(self.presenceBehaviour, t)
-
-
-
+ #The Organization exists
+ if not self.testUnitName():
+ raise NotValidName
+ #The room no existe
+ elif not self.myJoinRoom():
+ raise JoinError
+ #No es una organizacion
+ else:
+ info = self.getInfo()
+ if info:
+ self.type = info["type"]
+ self.contentLanguage = info["contentLanguage"]
+ self.parent = info["parent"]
+ parent_info = self.myAgent.getOrganizationInfo(self.parent)
+ self.parent_type = parent_info["type"]
+ self.goal = info["goal"]
+ self.state = "available"
+ p = Presence()
+ t = Behaviour.MessageTemplate(p)
+ self.presenceBehaviour = self.PresenceBehaviour(self.muc_name,
self.name, self.nick, self)
+ self.myAgent.addBehaviour(self.presenceBehaviour, t)
def testRoomName(self):
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- iq = Iq(frm=self.muc_name, attrs={"id":ID})
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ iq = Iq(frm=self.muc_name, attrs={"id": ID})
t = Behaviour.MessageTemplate(iq)
- b=self.TestRoomNameBehaviour(ID,self.muc_name,
self.name)
+ b = self.TestRoomNameBehaviour(ID, self.muc_name,
self.name)
self.myAgent.addBehaviour(b, t)
b.join()
return b.result
-
-
-
-
class TestRoomNameBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,ID,muc_name,roomname):
+ def __init__(self, ID, muc_name, roomname):
Behaviour.OneShotBehaviour.__init__(self)
- self.ID=ID
+ self.ID = ID
self.result = False
- self.muc_name=muc_name
- self.roomname=roomname
+ self.muc_name = muc_name
+ self.roomname = roomname
def _process(self):
- iq = Iq(to=self.muc_name,typ='get', attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/disco#items")
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
- if msg:
- if query:
- self.result = True
- items = msg.getQueryChildren()
- for item in items:
- if item.getAttr("jid") ==
str(self.roomname+"@"+self.muc_name):
- self.result = False
- else:
- self.result = False
-
+ iq = Iq(to=self.muc_name, typ='get', attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/disco#items")
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ msg = self._receive(True, 10)
+ if msg:
+ if query:
+ self.result = True
+ items = msg.getQueryChildren()
+ for item in items:
+ if item.getAttr("jid") == str(self.roomname + "@"
+ self.muc_name):
+ self.result = False
+ else:
+ self.result = False
def createRoom(self):
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Presence(frm=
self.name+"@"+self.muc_name+"/"+self.nick)
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Presence(frm=
self.name + "@" + self.muc_name + "/" + self.nick)
t1 = Behaviour.MessageTemplate(p)
-
b=self.CreateRoomBehaviour(ID,self.muc_name,
self.name,self.nick,self.parent,self.contentLanguage,self.type,self.goalList,self.password,self.agentList)
+ b = self.CreateRoomBehaviour(ID, self.muc_name,
self.name,
self.nick, self.parent, self.contentLanguage, self.type, self.goalList,
self.password, self.agentList)
self.myAgent.addBehaviour(b, t1)
b.join()
return b.result
class CreateRoomBehaviour(Behaviour.OneShotBehaviour):
- def
__init__(self,ID,muc_name,roomname,nick,parent,contentLanguage,type,goalList,password,agentList):
+ def __init__(self, ID, muc_name, roomname, nick, parent,
contentLanguage, type, goalList, password, agentList):
Behaviour.OneShotBehaviour.__init__(self)
self.result = False
- self.ID=ID
- self.nick=nick
- self.muc_name=muc_name
-
self.name=roomname
- self.parent=parent
- self.contentLanguage=contentLanguage
- self.type=type
- self.goalList=goalList
- self.password=password
- self.agentList=agentList
+ self.ID = ID
+ self.nick = nick
+ self.muc_name = muc_name
+
self.name = roomname
+ self.parent = parent
+ self.contentLanguage = contentLanguage
+ self.type = type
+ self.goalList = goalList
+ self.password = password
+ self.agentList = agentList
def _process(self):
- p = Presence(to=
self.name+"@"+self.muc_name+"/"+self.nick)
+ p = Presence(to=
self.name + "@" + self.muc_name + "/" +
self.nick)
x = Protocol("x", xmlns="
http://jabber.org/protocol/muc")
p.addChild(node=x)
self.myAgent.jabber.send(p)
- msg=self._receive(True,10)
+ msg = self._receive(True, 10)
if msg:
- if msg.getAttr("type")=="error":
+ if msg.getAttr("type") == "error":
print "Room creation is restricted"
- self.result= False
+ self.result = False
return
else:
- self.result= False
- return
- template= Iq(frm=
self.name+"@"+self.muc_name,
attrs={"id":self.ID})
+ self.result = False
+ return
+ template = Iq(frm=
self.name + "@" + self.muc_name,
attrs={"id": self.ID})
t = Behaviour.MessageTemplate(template)
self.setTemplate(t)
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='get',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#owner")
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='get',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#owner")
iq.addChild(node=query)
self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
+ msg = self._receive(True, 10)
#para descartar los presence anteriores
- while msg and msg.getName()!="iq":
- msg = self._receive(True,10)
+ while msg and msg.getName() != "iq":
+ msg = self._receive(True, 10)
- #setting room configuration
- if not msg or msg.getAttr("type")=="error":
- print "No configuration is possible: "+msg.getError()
+ #setting room configuration
+ if not msg or msg.getAttr("type") == "error":
+ print "No configuration is possible: " + msg.getError()
#cambiar
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='set',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#owner")
- x=Node(tag="x", attrs={"xmlns":"jabber:x:data","
type":"submit"})
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='set',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#owner")
+ x = Node(tag="x", attrs={"xmlns": "jabber:x:data", "
type": "submit"})
query.addChild(node=x)
iq.addChild(node=query)
self.myAgent.jabber.send(iq)
#return False
- self.result= False
+ self.result = False
return
- ispasswordprotected=False
- if self.type=="Hierarchy" or self.password!=None:
- ispasswordprotected=True
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='set',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#owner")
- x=Node(tag="x", attrs={"xmlns":"jabber:x:data","
type":"submit"})
- resquery=msg.getQueryChildren()[0] #nos quedamos con el hijo
de query
- if resquery: items = resquery.getTags("field")
- if resquery==None:
+ ispasswordprotected = False
+ if self.type == "Hierarchy" or self.password is not None:
+ ispasswordprotected = True
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='set',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#owner")
+ x = Node(tag="x", attrs={"xmlns": "jabber:x:data", "
type": "submit"})
+ resquery = msg.getQueryChildren()[0] # nos quedamos con el
hijo de query
+ if resquery:
+ items = resquery.getTags("field")
+ if resquery is None:
print "No configuration is possible"
return False
for item in items:
- if item.getAttr("var"):
- value=None
- if item.getAttr("var") == "muc#roomconfig_lang":
- value=self.contentLanguage
- if item.getAttr("var") == "muc#roomconfig_roomdesc":
- value=self.type
- if item.getAttr("var") == "muc#roomconfig_roomname":
- value=
self.name
- if item.getAttr("var") == "muc#roomconfig_roomtype":
- value="Unit:"+self.parent
- if item.getAttr("var")
== "muc#roomconfig_presencebroadcast":
- value="moderator"
- if item.getAttr("var") == "muc#roomconfig_persistentroom":
- value="1"
- if item.getAttr("var") == "muc#roomconfig_publicroom":
- value="1"
- if item.getAttr("var") == "muc#roomconfig_moderatedroom":
- value="1"
- if item.getAttr("var")
== "muc#roomconfig_passwordprotectedroom":
- if self.type=="Hierarchy" or self.password!=None:
- value="1"
- else:
- value="0"
- if item.getAttr("var")=="muc#roomconfig_roomsecret":
- value=self.password
- if item.getAttr("var") == "muc#roomconfig_whois":
- if self.type=="Hierarchy":
- value="moderators"
- else:
- value="anyone"
- if item.getAttr("var") == "muc#roomconfig_changeSubject":
- value="0"
- if item.getAttr("var") == "muc#roomconfig_membersonly":
- if self.type=="Flat":
- value="0"
- else:
- value="1"
- node=Node(tag="field", attrs={"var":item.getAttr("var")})
- valnode=Node(tag="value")
- valnode.addData(value)
- node.addChild(node=valnode)
- if(item.getAttr("var")!="muc#roomconfig_roomsecret" or
ispasswordprotected) and value!=None:
- x.addChild(node=node)
+ if item.getAttr("var"):
+ value = None
+ if item.getAttr("var") == "muc#roomconfig_lang":
+ value = self.contentLanguage
+ if item.getAttr("var") == "muc#roomconfig_roomdesc":
+ value = self.type
+ if item.getAttr("var") == "muc#roomconfig_roomname":
+ value =
self.name
+ if item.getAttr("var") == "muc#roomconfig_roomtype":
+ value = "Unit:" + self.parent
+ if item.getAttr("var")
== "muc#roomconfig_presencebroadcast":
+ value = "moderator"
+ if item.getAttr("var")
== "muc#roomconfig_persistentroom":
+ value = "1"
+ if item.getAttr("var") == "muc#roomconfig_publicroom":
+ value = "1"
+ if item.getAttr("var")
== "muc#roomconfig_moderatedroom":
+ value = "1"
+ if item.getAttr("var")
== "muc#roomconfig_passwordprotectedroom":
+ if self.type == "Hierarchy" or self.password is
not None:
+ value = "1"
+ else:
+ value = "0"
+ if item.getAttr("var") == "muc#roomconfig_roomsecret":
+ value = self.password
+ if item.getAttr("var") == "muc#roomconfig_whois":
+ if self.type == "Hierarchy":
+ value = "moderators"
+ else:
+ value = "anyone"
+ if item.getAttr("var")
== "muc#roomconfig_changeSubject":
+ value = "0"
+ if item.getAttr("var") == "muc#roomconfig_membersonly":
+ if self.type == "Flat":
+ value = "0"
+ else:
+ value = "1"
+ node = Node(tag="field", attrs={"var":
item.getAttr("var")})
+ valnode = Node(tag="value")
+ valnode.addData(value)
+ node.addChild(node=valnode)
+ if(item.getAttr("var") != "muc#roomconfig_roomsecret"
or ispasswordprotected) and value is not None:
+ x.addChild(node=node)
query.addChild(node=x)
iq.addChild(node=query)
self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
- if msg and msg.getAttr("type")=="result": #comprobar mejor el
mensaje que se devuelve
+ msg = self._receive(True, 10)
+ if msg and msg.getAttr("type") == "result": # comprobar mejor
el mensaje que se devuelve
- m = Message(to=
self.name+"@"+self.muc_name, typ="groupchat")
- sub = Node(tag="subject")
- sub.addData(str(self.goalList))
- m.addChild(node=sub)
- self.myAgent.jabber.send(m)
- #quitarlo luego
- for agent in self.agentList:
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='set',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#admin")
- item= Node(tag="item",
attrs={"affiliation":"member","jid":agent})
- query.addChild(node=item)
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- self.result= True
+ m = Message(to=
self.name + "@" + self.muc_name,
typ="groupchat")
+ sub = Node(tag="subject")
+ sub.addData(str(self.goalList))
+ m.addChild(node=sub)
+ self.myAgent.jabber.send(m)
+ #quitarlo luego
+ for agent in self.agentList:
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='set',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#admin")
+ item = Node(tag="item",
attrs={"affiliation": "member", "jid": agent})
+ query.addChild(node=item)
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ self.result = True
else:
- return False
+ return False
def myJoinRoom(self):
- p =
Presence(frm=
self.name+"@"+self.muc_name,attrs={"type":"error"})
+ p = Presence(frm=
self.name + "@" + self.muc_name,
attrs={"type": "error"})
t1 = Behaviour.MessageTemplate(p)
-
b=self.MyJoinRoomBehaviour(self.muc_name,
self.name,self.nick,self.password)
+ b = self.MyJoinRoomBehaviour(self.muc_name,
self.name, self.nick,
self.password)
self.myAgent.addBehaviour(b, t1)
b.join()
return b.result
class MyJoinRoomBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,roomname,nick,password):
+ def __init__(self, muc_name, roomname, nick, password):
Behaviour.OneShotBehaviour.__init__(self)
self.result = False
- self.nick=nick
- self.muc_name=muc_name
-
self.name=roomname
- self.password=password
+ self.nick = nick
+ self.muc_name = muc_name
+
self.name = roomname
+ self.password = password
def _process(self):
- p = Presence(to=
self.name+"@"+self.muc_name+"/"+self.nick)
- x = Node(tag="x",
attrs={"xmlns":"
http://jabber.org/protocol/muc"})
- if self.password!=None:
- pas=Node(tag="password")
+ p = Presence(to=
self.name + "@" + self.muc_name + "/" +
self.nick)
+ x = Node(tag="x",
attrs={"xmlns": "
http://jabber.org/protocol/muc"})
+ if self.password is not None:
+ pas = Node(tag="password")
pas.addData(self.password)
x.addChild(node=pas)
p.addChild(node=x)
self.myAgent.jabber.send(p)
- msg=self._receive(True,10)
+ msg = self._receive(True, 10)
if msg:
- error=msg.getTag("error")
- if error.getAttr("code")=="401":
- raise PaswordNeeded
- if error.getAttr("code")=="407":
- raise MembersOnly
- if error.getAttr("code")=="403":
- raise BanedUser
- if error.getAttr("code")=="409":
- raise NickNameConflict
- if error.getAttr("code")=="503":
- raise MaximumNumber
- if error.getAttr("code")=="404":
- raise LockedUnit
- self.result = False
- return
+ error = msg.getTag("error")
+ if error.getAttr("code") == "401":
+ raise PaswordNeeded
+ if error.getAttr("code") == "407":
+ raise MembersOnly
+ if error.getAttr("code") == "403":
+ raise BanedUser
+ if error.getAttr("code") == "409":
+ raise NickNameConflict
+ if error.getAttr("code") == "503":
+ raise MaximumNumber
+ if error.getAttr("code") == "404":
+ raise LockedUnit
+ self.result = False
+ return
self.result = True
-
- def checkGoal(self,goalList):
+ def checkGoal(self, goalList):
#falta por implementar
- if goalList!=None:
- return True
+ if goalList is not None:
+ return True
else:
- return False
-
+ return False
def checkType(self):
- types=("Flat","Team","Hierarchy")
+ types = ("Flat", "Team", "Hierarchy")
if self.type in types:
- return True
+ return True
return False
def testUnitName(self):
- info=self.getInfo()
+ info = self.getInfo()
if info:
- if info["parent"]!="Organization" and info["parent"]!="":
+ if info["parent"] != "Organization" and info["parent"] != "":
return True
return False
- def invite(self,agentList):
- if self.state=="unavailable":
- print "The "+self.UnavailableMsg+" "+
self.name+" is
unavailable"
+ def invite(self, agentList):
+ if self.state == "unavailable":
+ print "The " + self.UnavailableMsg + " " +
self.name + " is
unavailable"
return
for agent in agentList:
- message = Node(tag="message",
attrs={"to":
self.name+"@"+self.muc_name})
-
x=Node(tag="x",attrs={"xmlns":"
http://jabber.org/protocol/muc#user"})
- y=Node(tag="invite",attrs={"to":agent})
- r=Node(tag="reason")
- r.addData("Inivitation to the Unit "+
self.name)
- y.addChild(node=r)
- x.addChild(node=y)
- message.addChild(node=x)
- self.myAgent.jabber.send(message)
+ message = Node(tag="message", attrs={"to":
self.name + "@" +
self.muc_name})
+ x = Node(tag="x",
attrs={"xmlns": "
http://jabber.org/protocol/muc#user"})
+ y = Node(tag="invite", attrs={"to": agent})
+ r = Node(tag="reason")
+ r.addData("Inivitation to the Unit " +
self.name)
+ y.addChild(node=r)
+ x.addChild(node=y)
+ message.addChild(node=x)
+ self.myAgent.jabber.send(message)
- def setGoal(self,goalList):
+ def setGoal(self, goalList):
"""
Updates organization goals
"""
#comprobar que sea un objetivo valido
- if self.state=="unavailable":
- print "The "+self.UnavailableMsg+" "+
self.name+" is
unavailable"
+ if self.state == "unavailable":
+ print "The " + self.UnavailableMsg + " " +
self.name + " is
unavailable"
return
if not self.checkGoal(goalList):
raise NotValidGoal
return
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Message(frm=
self.name+"@"+self.muc_name, typ="error",
attrs={"id":ID})
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Message(frm=
self.name + "@" + self.muc_name, typ="error",
attrs={"id": ID})
t1 = Behaviour.MessageTemplate(p)
- b=self.SetGoalBehaviour(self.muc_name,
self.name,goalList,ID)
+ b = self.SetGoalBehaviour(self.muc_name,
self.name, goalList, ID)
self.myAgent.addBehaviour(b, t1)
-
-
class SetGoalBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,roomname,goalList,ID):
+ def __init__(self, muc_name, roomname, goalList, ID):
Behaviour.OneShotBehaviour.__init__(self)
- self.goalList=goalList
- self.muc_name=muc_name
-
self.name=roomname
- self.ID=ID
+ self.goalList = goalList
+ self.muc_name = muc_name
+
self.name = roomname
+ self.ID = ID
def _process(self):
- m = Message(to=
self.name+"@"+self.muc_name,
typ="groupchat",attrs={"id":self.ID})
+ m = Message(to=
self.name + "@" + self.muc_name,
typ="groupchat", attrs={"id": self.ID})
sub = Node(tag="subject")
sub.addData(str(self.goalList))
m.addChild(node=sub)
self.myAgent.jabber.send(m)
- msg=self._receive(True,10)
+ msg = self._receive(True, 10)
if msg:
raise NotValidGoalChange
def getGoal(self):
- """
- Retruns a list of goals
- """
- if self.state=="unavailable":
- print "The "+self.UnavailableMsg+" "+
self.name+" is unavailable"
- return
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Iq(frm=
self.name+"@"+self.muc_name,typ='result', attrs={"id":ID})
- t1 = Behaviour.MessageTemplate(p)
- b=self.GetGoalBehaviour(self.muc_name,
self.name,ID)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
-
+ """
+ Retruns a list of goals
+ """
+ if self.state == "unavailable":
+ print "The " + self.UnavailableMsg + " " +
self.name + " is
unavailable"
+ return
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Iq(frm=
self.name + "@" + self.muc_name, typ='result',
attrs={"id": ID})
+ t1 = Behaviour.MessageTemplate(p)
+ b = self.GetGoalBehaviour(self.muc_name,
self.name, ID)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
class GetGoalBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,roomname,ID):
+ def __init__(self, muc_name, roomname, ID):
Behaviour.OneShotBehaviour.__init__(self)
- self.ID=ID
- self.muc_name=muc_name
-
self.name=roomname
- self.result=None
+ self.ID = ID
+ self.muc_name = muc_name
+
self.name = roomname
+ self.result = None
def _process(self):
- goal=None
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='get',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/disco#info")
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- msg=self._receive(True,10)
- if msg:
- query = msg.getTag("query")
- if query:
- x = query.getTag("x")
- if x:
- items =x.getChildren()
- for item in items:
- if item.getAttr("var")=="muc#roominfo_subject":
- if item.getTags("value"):
- goal=item.getTags("value")[0].getData()
- if goal==None:
- print "Not goal"
- self.result=goal
-
+ goal = None
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='get',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/disco#info")
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ msg = self._receive(True, 10)
+ if msg:
+ query = msg.getTag("query")
+ if query:
+ x = query.getTag("x")
+ if x:
+ items = x.getChildren()
+ for item in items:
+ if item.getAttr("var")
== "muc#roominfo_subject":
+ if item.getTags("value"):
+ goal =
item.getTags("value")[0].getData()
+ if goal is None:
+ print "Not goal"
+ self.result = goal
def getInfo(self):
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Iq(frm=
self.name+"@"+self.muc_name,typ='result', attrs={"id":ID})
- t1 = Behaviour.MessageTemplate(p)
- b=self.GetInfoBehaviour(self.muc_name,
self.name,ID)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
-
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Iq(frm=
self.name + "@" + self.muc_name, typ='result',
attrs={"id": ID})
+ t1 = Behaviour.MessageTemplate(p)
+ b = self.GetInfoBehaviour(self.muc_name,
self.name, ID)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
class GetInfoBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,roomname,ID):
+ def __init__(self, muc_name, roomname, ID):
Behaviour.OneShotBehaviour.__init__(self)
- self.ID=ID
- self.muc_name=muc_name
-
self.name=roomname
- self.result=None
+ self.ID = ID
+ self.muc_name = muc_name
+
self.name = roomname
+ self.result = None
def _process(self):
- info={}
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='get',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/disco#info")
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- msg=self._receive(True,10)
- if msg:
- query = msg.getTag("query")
- if query:
- x = query.getTag("x")
- if x:
- items =x.getChildren()
- for item in items:
- if item.getAttr("var")=="muc#roominfo_description":
- if item.getTags("value"):
- info["type"]=item.getTags("value")[0].getData()
- if item.getAttr("var")=="muc#roominfo_subject":
- if item.getTags("value"):
- info["goal"]=item.getTags("value")[0].getData()
- if item.getAttr("var")=="muc#roominfo_type":
- if item.getTags("value")[0].getData():
- if ':' in
item.getTags("value")[0].getData():
- info["parent"]=
item.getTags("value")[0].getData().split(':')[1]
- else:
-
info["parent"]=item.getTags("value")[0].getData()
- if item.getAttr("var")=="muc#roominfo_type":
- if item.getTags("value"):
-
info["contentLanguage"]=item.getTags("value")[0].getData()
- self.result=info
-
+ info = {}
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='get',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/disco#info")
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ msg = self._receive(True, 10)
+ if msg:
+ query = msg.getTag("query")
+ if query:
+ x = query.getTag("x")
+ if x:
+ items = x.getChildren()
+ for item in items:
+ if item.getAttr("var")
== "muc#roominfo_description":
+ if item.getTags("value"):
+ info["type"] =
item.getTags("value")[0].getData()
+ if item.getAttr("var")
== "muc#roominfo_subject":
+ if item.getTags("value"):
+ info["goal"] =
item.getTags("value")[0].getData()
+ if item.getAttr("var") == "muc#roominfo_type":
+ if item.getTags("value")[0].getData():
+ if ':' in
item.getTags("value")[0].getData():
+ info["parent"] =
item.getTags("value")[0].getData().split(':')[1]
+ else:
+ info["parent"] =
item.getTags("value")[0].getData()
+ if item.getAttr("var") == "muc#roominfo_type":
+ if item.getTags("value"):
+ info["contentLanguage"] =
item.getTags("value")[0].getData()
+ self.result = info
def getMemberList(self):
- """
- Returns a List with Agents' names belonging to the organization
- """
- if self.state=="unavailable":
- print "The "+self.UnavailableMsg+" "+
self.name+" is unavailable"
- return
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Iq(frm=
self.name+"@"+self.muc_name, attrs={"id":ID})
- t1 = Behaviour.MessageTemplate(p)
- b=self.GetMemberListBehaviour(self.muc_name,
self.name,ID)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
+ """
+ Returns a List with Agents' names belonging to the organization
+ """
+ if self.state == "unavailable":
+ print "The " + self.UnavailableMsg + " " +
self.name + " is
unavailable"
+ return
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Iq(frm=
self.name + "@" + self.muc_name, attrs={"id": ID})
+ t1 = Behaviour.MessageTemplate(p)
+ b = self.GetMemberListBehaviour(self.muc_name,
self.name, ID)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
class GetMemberListBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,roomname,ID):
+ def __init__(self, muc_name, roomname, ID):
Behaviour.OneShotBehaviour.__init__(self)
- self.ID=ID
- self.muc_name=muc_name
-
self.name=roomname
- self.result=[]
+ self.ID = ID
+ self.muc_name = muc_name
+
self.name = roomname
+ self.result = []
def _process(self):
- # si es una unidad tambien hay que mirar si el presence
broadcast est√° restringido
- # if not checkOwner(self.myAgent):
- # print "This agent is not allowed to get the memberList"
- agents=[]
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='get',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#admin")
- item= Node(tag="item", attrs={"affiliation":"member"})
- query.addChild(node=item)
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- msg=self._receive(True,10)
- if msg:
- error=msg.getError()
- if error!=None:
+ # si es una unidad tambien hay que mirar si el
presence broadcast est√° restringido
+ # if not checkOwner(self.myAgent):
+ # print "This agent is not allowed to get the
memberList"
+ agents = []
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='get',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#admin")
+ item = Node(tag="item", attrs={"affiliation": "member"})
+ query.addChild(node=item)
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ msg = self._receive(True, 10)
+ if msg:
+ error = msg.getError()
+ if error is not None:
print error
return
- query = msg.getTag("query")
- if query:
- items =query.getChildren()
+ query = msg.getTag("query")
+ if query:
+ items = query.getChildren()
for item in items:
agents.append(str(item.getAttr("jid")))
- self.result=agents
+ self.result = agents
return
-
def getMaxAgents(self):
- """
***The diff for this file has been truncated for email.***
=======================================
--- /trunk/spade/Unit_new.py Thu Jun 7 02:55:43 2007
+++ /trunk/spade/Unit_new.py Fri Nov 23 05:19:16 2012
@@ -1,4 +1,4 @@
-# -*- coding: UTF8 -*-
+# -*- coding: utf-8 -*-
import random
import string
@@ -6,65 +6,102 @@
from Queue import *
import Behaviour
+
class CreationError(Exception):
- def __init__(self):
- Exception.__init__(self)
+ def __init__(self):
+ Exception.__init__(self)
+
+
class NotValidName(CreationError):
def __init__(self):
CreationError.__init__(self)
+
+
class NotValidGoalChange(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class NotValidType(CreationError):
def __init__(self):
CreationError.__init__(self)
+
+
class NotValidGoal(CreationError):
def __init__(self):
CreationError.__init__(self)
+
+
class NotCreatePermision(CreationError):
def __init__(self):
CreationError.__init__(self)
+
+
class NotSupervisor(CreationError):
def __init__(self):
CreationError.__init__(self)
+
+
class JoinError(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class PaswordNeeded(JoinError):
def __init__(self):
JoinError.__init__(self)
+
+
class MembersOnly(JoinError):
- def __init__(self):
- JoinError.__init__(self)
+ def __init__(self):
+ JoinError.__init__(self)
+
+
class BanedUser(JoinError):
def __init__(self):
JoinError.__init__(self)
+
+
class NickNameConflict(JoinError):
def __init__(self):
JoinError.__init__(self)
+
+
class MaximumUsers(JoinError):
def __init__(self):
JoinError.__init__(self)
+
+
class LockedUnit(JoinError):
def __init__(self):
JoinError.__init__(self)
+
+
class Unavailable(Exception):
def __init__(self):
- Exception.__init__(self)
+ Exception.__init__(self)
+
+
class DestroyError(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class NotValidUnit(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class LastOwner(Exception):
def __init__(self):
Exception.__init__(self)
+
+
class Unit_new(Behaviour.OneShotBehaviour):
- def __init__(self,agent, nick, name, type="Team", goalList=[],
agentList=[], contentLanguage="sl",password=None,create=True):
+ def __init__(self, agent, nick, name, type="Team", goalList=[],
agentList=[], contentLanguage="sl", password=None, create=True):
Behaviour.OneShotBehaviour.__init__(self)
- self.myAgent=agent
+ self.myAgent = agent
self.name = name
self.type = type
self.goalList = goalList
@@ -73,665 +110,646 @@
self.platform = self.myAgent.getSpadePlatformJID()
self.muc_name = self.myAgent.getMUC()
self._roster = {}
- self.nick=nick
- self.password=password
- self.create=create
- self.parent_type=None
- self.parent=None
- id_base
= "".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)]) #@UnusedVariable
+ self.nick = nick
+ self.password = password
+ self.create = create
+ self.parent_type = None
+ self.parent = None
+ id_base = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)]) # @UnusedVariable
self.ID = str(name) + str(self.myAgent.getAID().getName()) +
id_base
- self.state="unavailable"
- self.UnavailableMsg="Unit"
- self.members=[]
- self.owner=False
- self.orgOwner=None
-
+ self.state = "unavailable"
+ self.UnavailableMsg = "Unit"
+ self.members = []
+ self.owner = False
+ self.orgOwner = None
def setup(self):
- pass
-
-
-
-
+ pass
def myCreate(self):
- if not self.checkGoal(self.goalList):
- raise NotValidGoal
- elif not self.checkType():
- raise NotValidType
- elif self.type=="Hierarchy" and self.password==None:
- raise PaswordNeeded
- elif not self.testRoomName():
- raise NotValidName
- elif not self.createRoom():
- raise CreationError
- else:
- self.state="available"
- if self.agentList!=[]:
- #enviando invitaciones
+ if not self.checkGoal(self.goalList):
+ raise NotValidGoal
+ elif not self.checkType():
+ raise NotValidType
+ elif self.type == "Hierarchy" and self.password is None:
+ raise PaswordNeeded
+ elif not self.testRoomName():
+ raise NotValidName
+ elif not self.createRoom():
+ raise CreationError
+ else:
+ self.state = "available"
+ if self.agentList != []:
+ #enviando invitaciones
self.invite(self.agentList)
- #registrando en el DF
- #dad = DF.DfAgentDescription()
- #ds = DF.ServiceDescription()
- #ds.setType("Unit: "+self.parent)
- #ds.setName(
self.name)
- #dad.addService(ds)
- # res = self.myAgent.registerService(dad)
- #anyadimos el comportamiento que lee los presence
- self.owner=True
- p = Presence()
- t = Behaviour.MessageTemplate(p)
-
self.presenceBehaviour=self.PresenceBehaviour(self.muc_name,
self.name,self.nick,self)
- self.myAgent.addBehaviour(self.presenceBehaviour, t)
+ #registrando en el DF
+ #dad = DF.DfAgentDescription()
+ #ds = DF.ServiceDescription()
+ #ds.setType("Unit: "+self.parent)
+ #ds.setName(
self.name)
+ #dad.addService(ds)
+ # res = self.myAgent.registerService(dad)
+ #anyadimos el comportamiento que lee los presence
+ self.owner = True
+ p = Presence()
+ t = Behaviour.MessageTemplate(p)
+ self.presenceBehaviour = self.PresenceBehaviour(self.muc_name,
self.name, self.nick, self)
+ self.myAgent.addBehaviour(self.presenceBehaviour, t)
def myJoin(self):
- #The Organization exists
- if not self.testUnitName():
- raise NotValidName
- #The room no existe
- elif not self.myJoinRoom():
- raise JoinError
- #No es una organizacion
- else:
- info=self.getInfo()
- if info:
- self.type = info["type"]
- self.contentLanguage = info["contentLanguage"]
- self.parent=info["parent"]
- parent_info=self.myAgent.getOrganizationInfo(self.parent)
- self.parent_type=parent_info["type"]
- self.goal=info["goal"]
- self.state="available"
- p = Presence()
- t = Behaviour.MessageTemplate(p)
-
self.presenceBehaviour=self.PresenceBehaviour(self.muc_name,
self.name,self.nick,self)
- self.myAgent.addBehaviour(self.presenceBehaviour, t)
-
-
-
+ #The Organization exists
+ if not self.testUnitName():
+ raise NotValidName
+ #The room no existe
+ elif not self.myJoinRoom():
+ raise JoinError
+ #No es una organizacion
+ else:
+ info = self.getInfo()
+ if info:
+ self.type = info["type"]
+ self.contentLanguage = info["contentLanguage"]
+ self.parent = info["parent"]
+ parent_info = self.myAgent.getOrganizationInfo(self.parent)
+ self.parent_type = parent_info["type"]
+ self.goal = info["goal"]
+ self.state = "available"
+ p = Presence()
+ t = Behaviour.MessageTemplate(p)
+ self.presenceBehaviour = self.PresenceBehaviour(self.muc_name,
self.name, self.nick, self)
+ self.myAgent.addBehaviour(self.presenceBehaviour, t)
def testRoomName(self):
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- iq = Iq(frm=self.muc_name, attrs={"id":ID})
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ iq = Iq(frm=self.muc_name, attrs={"id": ID})
t = Behaviour.MessageTemplate(iq)
- b=self.TestRoomNameBehaviour(ID,self.muc_name,
self.name)
+ b = self.TestRoomNameBehaviour(ID, self.muc_name,
self.name)
self.myAgent.addBehaviour(b, t)
b.join()
return b.result
-
-
-
-
class TestRoomNameBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,ID,muc_name,roomname):
+ def __init__(self, ID, muc_name, roomname):
Behaviour.OneShotBehaviour.__init__(self)
- self.ID=ID
+ self.ID = ID
self.result = False
- self.muc_name=muc_name
- self.roomname=roomname
+ self.muc_name = muc_name
+ self.roomname = roomname
def _process(self):
- iq = Iq(to=self.muc_name,typ='get', attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/disco#items")
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
- if msg:
- if query:
- self.result = True
- items = msg.getQueryChildren()
- for item in items:
- if item.getAttr("jid") ==
str(self.roomname+"@"+self.muc_name):
- self.result = False
- else:
- self.result = False
-
+ iq = Iq(to=self.muc_name, typ='get', attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/disco#items")
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ msg = self._receive(True, 10)
+ if msg:
+ if query:
+ self.result = True
+ items = msg.getQueryChildren()
+ for item in items:
+ if item.getAttr("jid") == str(self.roomname + "@"
+ self.muc_name):
+ self.result = False
+ else:
+ self.result = False
def createRoom(self):
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Presence(frm=
self.name+"@"+self.muc_name+"/"+self.nick)
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Presence(frm=
self.name + "@" + self.muc_name + "/" + self.nick)
t1 = Behaviour.MessageTemplate(p)
-
b=self.CreateRoomBehaviour(ID,self.muc_name,
self.name,self.nick,self.parent,self.contentLanguage,self.type,self.goalList,self.password,self.orgOwner)
+ b = self.CreateRoomBehaviour(ID, self.muc_name,
self.name,
self.nick, self.parent, self.contentLanguage, self.type, self.goalList,
self.password, self.orgOwner)
self.myAgent.addBehaviour(b, t1)
b.join()
return b.result
class CreateRoomBehaviour(Behaviour.OneShotBehaviour):
- def
__init__(self,ID,muc_name,roomname,nick,parent,contentLanguage,type,goalList,password,orgOwner):
+ def __init__(self, ID, muc_name, roomname, nick, parent,
contentLanguage, type, goalList, password, orgOwner):
Behaviour.OneShotBehaviour.__init__(self)
self.result = False
- self.ID=ID
- self.nick=nick
- self.muc_name=muc_name
-
self.name=roomname
- self.parent=parent
- self.contentLanguage=contentLanguage
- self.type=type
- self.goalList=goalList
- self.password=password
- self.orgOwner=orgOwner
+ self.ID = ID
+ self.nick = nick
+ self.muc_name = muc_name
+
self.name = roomname
+ self.parent = parent
+ self.contentLanguage = contentLanguage
+ self.type = type
+ self.goalList = goalList
+ self.password = password
+ self.orgOwner = orgOwner
def _process(self):
- p = Presence(to=
self.name+"@"+self.muc_name+"/"+self.nick)
+ p = Presence(to=
self.name + "@" + self.muc_name + "/" +
self.nick)
x = Protocol("x", xmlns="
http://jabber.org/protocol/muc")
p.addChild(node=x)
self.myAgent.jabber.send(p)
- msg=self._receive(True,10)
+ msg = self._receive(True, 10)
if msg:
- if msg.getAttr("type")=="error":
+ if msg.getAttr("type") == "error":
print "Room creation is restricted"
- self.result= False
+ self.result = False
return
else:
- self.result= False
- return
- template= Iq(frm=
self.name+"@"+self.muc_name,
attrs={"id":self.ID})
+ self.result = False
+ return
+ template = Iq(frm=
self.name + "@" + self.muc_name,
attrs={"id": self.ID})
t = Behaviour.MessageTemplate(template)
self.setTemplate(t)
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='get',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#owner")
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='get',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#owner")
iq.addChild(node=query)
self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
+ msg = self._receive(True, 10)
#para descartar los presence anteriores
- while msg and msg.getName()!="iq":
- msg = self._receive(True,10)
+ while msg and msg.getName() != "iq":
+ msg = self._receive(True, 10)
- #setting room configuration
- if not msg or msg.getAttr("type")=="error":
- print "No configuration is possible: "+msg.getError()
+ #setting room configuration
+ if not msg or msg.getAttr("type") == "error":
+ print "No configuration is possible: " + msg.getError()
#cambiar
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='set',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#owner")
- x=Node(tag="x", attrs={"xmlns":"jabber:x:data","
type":"submit"})
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='set',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#owner")
+ x = Node(tag="x", attrs={"xmlns": "jabber:x:data", "
type": "submit"})
query.addChild(node=x)
iq.addChild(node=query)
self.myAgent.jabber.send(iq)
#return False
- self.result= False
+ self.result = False
return
- ispasswordprotected=False
- if self.type=="Hierarchy" or self.password!=None:
- ispasswordprotected=True
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='set',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#owner")
- x=Node(tag="x", attrs={"xmlns":"jabber:x:data","
type":"submit"})
- resquery=msg.getQueryChildren()[0] #nos quedamos con el hijo
de query
- if resquery: items = resquery.getTags("field")
- if resquery==None:
+ ispasswordprotected = False
+ if self.type == "Hierarchy" or self.password is not None:
+ ispasswordprotected = True
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='set',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#owner")
+ x = Node(tag="x", attrs={"xmlns": "jabber:x:data", "
type": "submit"})
+ resquery = msg.getQueryChildren()[0] # nos quedamos con el
hijo de query
+ if resquery:
+ items = resquery.getTags("field")
+ if resquery is None:
print "No configuration is possible"
return False
for item in items:
- if item.getAttr("var"):
- value=None
- if item.getAttr("var") == "muc#roomconfig_lang":
- value=self.contentLanguage
- if item.getAttr("var") == "muc#roomconfig_roomdesc":
- value=self.type
- if item.getAttr("var") == "muc#roomconfig_roomname":
- value=
self.name
- if item.getAttr("var") == "muc#roomconfig_roomtype":
- value="Unit:"+self.parent
- if item.getAttr("var")
== "muc#roomconfig_presencebroadcast":
- value="moderator"
- if item.getAttr("var") == "muc#roomconfig_persistentroom":
- value="1"
- if item.getAttr("var") == "muc#roomconfig_publicroom":
- value="1"
- if item.getAttr("var") == "muc#roomconfig_moderatedroom":
- value="1"
- if item.getAttr("var")
== "muc#roomconfig_passwordprotectedroom":
- if self.type=="Hierarchy" or self.password!=None:
- value="1"
- else:
- value="0"
- if item.getAttr("var")=="muc#roomconfig_roomsecret":
- value=self.password
- if item.getAttr("var") == "muc#roomconfig_whois":
- if self.type=="Hierarchy":
- value="moderators"
- else:
- value="anyone"
- #como configurar?????????????
- if item.getAttr("var") == "muc#roomconfig_changesubject":
- value="1"
- if item.getAttr("var") == "muc#roomconfig_allowinvites":
- value="1"
- ####################################333
- if item.getAttr("var") == "muc#roomconfig_membersonly":
- if self.type=="Flat":
- value="0"
- else:
- value="1"
- node=Node(tag="field", attrs={"var":item.getAttr("var")})
- valnode=Node(tag="value")
- valnode.addData(value)
- node.addChild(node=valnode)
- if(item.getAttr("var")!="muc#roomconfig_roomsecret" or
ispasswordprotected) and value!=None:
- x.addChild(node=node)
+ if item.getAttr("var"):
+ value = None
+ if item.getAttr("var") == "muc#roomconfig_lang":
+ value = self.contentLanguage
+ if item.getAttr("var") == "muc#roomconfig_roomdesc":
+ value = self.type
+ if item.getAttr("var") == "muc#roomconfig_roomname":
+ value =
self.name
+ if item.getAttr("var") == "muc#roomconfig_roomtype":
+ value = "Unit:" + self.parent
+ if item.getAttr("var")
== "muc#roomconfig_presencebroadcast":
+ value = "moderator"
+ if item.getAttr("var")
== "muc#roomconfig_persistentroom":
+ value = "1"
+ if item.getAttr("var") == "muc#roomconfig_publicroom":
+ value = "1"
+ if item.getAttr("var")
== "muc#roomconfig_moderatedroom":
+ value = "1"
+ if item.getAttr("var")
== "muc#roomconfig_passwordprotectedroom":
+ if self.type == "Hierarchy" or self.password is
not None:
+ value = "1"
+ else:
+ value = "0"
+ if item.getAttr("var") == "muc#roomconfig_roomsecret":
+ value = self.password
+ if item.getAttr("var") == "muc#roomconfig_whois":
+ if self.type == "Hierarchy":
+ value = "moderators"
+ else:
+ value = "anyone"
+ #como configurar?????????????
+ if item.getAttr("var")
== "muc#roomconfig_changesubject":
+ value = "1"
+ if item.getAttr("var")
== "muc#roomconfig_allowinvites":
+ value = "1"
+ ####################################333
+ if item.getAttr("var") == "muc#roomconfig_membersonly":
+ if self.type == "Flat":
+ value = "0"
+ else:
+ value = "1"
+ node = Node(tag="field", attrs={"var":
item.getAttr("var")})
+ valnode = Node(tag="value")
+ valnode.addData(value)
+ node.addChild(node=valnode)
+ if(item.getAttr("var") != "muc#roomconfig_roomsecret"
or ispasswordprotected) and value is not None:
+ x.addChild(node=node)
query.addChild(node=x)
iq.addChild(node=query)
self.myAgent.jabber.send(iq)
- msg = self._receive(True,10)
- if msg and msg.getAttr("type")=="result": #comprobar mejor el
mensaje que se devuelve
+ msg = self._receive(True, 10)
+ if msg and msg.getAttr("type") == "result": # comprobar mejor
el mensaje que se devuelve
- m = Message(to=
self.name+"@"+self.muc_name, typ="groupchat")
- sub = Node(tag="subject")
- sub.addData(str(self.goalList))
- m.addChild(node=sub)
- self.myAgent.jabber.send(m)
- #añadiendo al owner de la organizacion
- self.myAgent.jabber.send(iq)
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='set',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#admin")
- item= Node(tag="item",
attrs={"affiliation":"owner","jid":self.orgOwner})
- query.addChild(node=item)
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- self.result= True
+ m = Message(to=
self.name + "@" + self.muc_name,
typ="groupchat")
+ sub = Node(tag="subject")
+ sub.addData(str(self.goalList))
+ m.addChild(node=sub)
+ self.myAgent.jabber.send(m)
+ #añadiendo al owner de la organizacion
+ self.myAgent.jabber.send(iq)
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='set',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#admin")
+ item = Node(tag="item",
attrs={"affiliation": "owner", "jid": self.orgOwner})
+ query.addChild(node=item)
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ self.result = True
else:
- return False
+ return False
def myJoinRoom(self):
- p =
Presence(frm=
self.name+"@"+self.muc_name,attrs={"type":"error"})
+ p = Presence(frm=
self.name + "@" + self.muc_name,
attrs={"type": "error"})
t1 = Behaviour.MessageTemplate(p)
-
b=self.MyJoinRoomBehaviour(self.muc_name,
self.name,self.nick,self.password)
+ b = self.MyJoinRoomBehaviour(self.muc_name,
self.name, self.nick,
self.password)
self.myAgent.addBehaviour(b, t1)
b.join()
return b.result
class MyJoinRoomBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,roomname,nick,password):
+ def __init__(self, muc_name, roomname, nick, password):
Behaviour.OneShotBehaviour.__init__(self)
self.result = False
- self.nick=nick
- self.muc_name=muc_name
-
self.name=roomname
- self.password=password
+ self.nick = nick
+ self.muc_name = muc_name
+
self.name = roomname
+ self.password = password
def _process(self):
- p = Presence(to=
self.name+"@"+self.muc_name+"/"+self.nick)
- x = Node(tag="x",
attrs={"xmlns":"
http://jabber.org/protocol/muc"})
- if self.password!=None:
- pas=Node(tag="password")
+ p = Presence(to=
self.name + "@" + self.muc_name + "/" +
self.nick)
+ x = Node(tag="x",
attrs={"xmlns": "
http://jabber.org/protocol/muc"})
+ if self.password is not None:
+ pas = Node(tag="password")
pas.addData(self.password)
x.addChild(node=pas)
p.addChild(node=x)
self.myAgent.jabber.send(p)
- msg=self._receive(True,10)
+ msg = self._receive(True, 10)
if msg:
- error=msg.getTag("error")
- if error.getAttr("code")=="401":
- raise PaswordNeeded
- if error.getAttr("code")=="407":
- raise MembersOnly
- if error.getAttr("code")=="403":
- raise BanedUser
- if error.getAttr("code")=="409":
- raise NickNameConflict
- if error.getAttr("code")=="503":
- raise MaximumNumber
- if error.getAttr("code")=="404":
- raise LockedUnit
- self.result = False
- return
+ error = msg.getTag("error")
+ if error.getAttr("code") == "401":
+ raise PaswordNeeded
+ if error.getAttr("code") == "407":
+ raise MembersOnly
+ if error.getAttr("code") == "403":
+ raise BanedUser
+ if error.getAttr("code") == "409":
+ raise NickNameConflict
+ if error.getAttr("code") == "503":
+ raise MaximumNumber
+ if error.getAttr("code") == "404":
+ raise LockedUnit
+ self.result = False
+ return
self.result = True
-
- def checkGoal(self,goalList):
+ def checkGoal(self, goalList):
#falta por implementar
- if goalList!=None:
- return True
+ if goalList is not None:
+ return True
else:
- return False
-
+ return False
def checkType(self):
- types=("Flat","Team","Hierarchy")
+ types = ("Flat", "Team", "Hierarchy")
if self.type in types:
- return True
+ return True
return False
def testUnitName(self):
- info=self.getInfo()
+ info = self.getInfo()
if info:
- if info["parent"]!="Organization" and info["parent"]!="":
+ if info["parent"] != "Organization" and info["parent"] != "":
return True
return False
- def invite(self,agentList):
- if self.state=="unavailable":
- print "The "+self.UnavailableMsg+" "+
self.name+" is
unavailable"
+ def invite(self, agentList):
+ if self.state == "unavailable":
+ print "The " + self.UnavailableMsg + " " +
self.name + " is
unavailable"
return
for agent in agentList:
- message = Node(tag="message",
attrs={"to":
self.name+"@"+self.muc_name})
-
x=Node(tag="x",attrs={"xmlns":"
http://jabber.org/protocol/muc#user"})
- y=Node(tag="invite",attrs={"to":agent})
- r=Node(tag="reason")
- r.addData("Inivitation to the Unit "+
self.name)
- y.addChild(node=r)
- x.addChild(node=y)
- message.addChild(node=x)
- self.myAgent.jabber.send(message)
+ message = Node(tag="message", attrs={"to":
self.name + "@" +
self.muc_name})
+ x = Node(tag="x",
attrs={"xmlns": "
http://jabber.org/protocol/muc#user"})
+ y = Node(tag="invite", attrs={"to": agent})
+ r = Node(tag="reason")
+ r.addData("Inivitation to the Unit " +
self.name)
+ y.addChild(node=r)
+ x.addChild(node=y)
+ message.addChild(node=x)
+ self.myAgent.jabber.send(message)
- def setGoal(self,goalList):
+ def setGoal(self, goalList):
"""
Updates organization goals
"""
#comprobar que sea un objetivo valido
- if self.state=="unavailable":
- print "The "+self.UnavailableMsg+" "+
self.name+" is
unavailable"
+ if self.state == "unavailable":
+ print "The " + self.UnavailableMsg + " " +
self.name + " is
unavailable"
return
if not self.checkGoal(goalList):
raise NotValidGoal
return
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Message(frm=
self.name+"@"+self.muc_name, typ="error",
attrs={"id":ID})
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Message(frm=
self.name + "@" + self.muc_name, typ="error",
attrs={"id": ID})
t1 = Behaviour.MessageTemplate(p)
- b=self.SetGoalBehaviour(self.muc_name,
self.name,goalList,ID)
+ b = self.SetGoalBehaviour(self.muc_name,
self.name, goalList, ID)
self.myAgent.addBehaviour(b, t1)
-
-
class SetGoalBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,roomname,goalList,ID):
+ def __init__(self, muc_name, roomname, goalList, ID):
Behaviour.OneShotBehaviour.__init__(self)
- self.goalList=goalList
- self.muc_name=muc_name
-
self.name=roomname
- self.ID=ID
+ self.goalList = goalList
+ self.muc_name = muc_name
+
self.name = roomname
+ self.ID = ID
def _process(self):
- m = Message(to=
self.name+"@"+self.muc_name,
typ="groupchat",attrs={"id":self.ID})
+ m = Message(to=
self.name + "@" + self.muc_name,
typ="groupchat", attrs={"id": self.ID})
sub = Node(tag="subject")
sub.addData(str(self.goalList))
m.addChild(node=sub)
self.myAgent.jabber.send(m)
- msg=self._receive(True,10)
+ msg = self._receive(True, 10)
if msg:
raise NotValidGoalChange
def getGoal(self):
- """
- Retruns a list of goals
- """
- if self.state=="unavailable":
- print "The "+self.UnavailableMsg+" "+
self.name+" is unavailable"
- return
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Iq(frm=
self.name+"@"+self.muc_name,typ='result', attrs={"id":ID})
- t1 = Behaviour.MessageTemplate(p)
- b=self.GetGoalBehaviour(self.muc_name,
self.name,ID)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
-
+ """
+ Retruns a list of goals
+ """
+ if self.state == "unavailable":
+ print "The " + self.UnavailableMsg + " " +
self.name + " is
unavailable"
+ return
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Iq(frm=
self.name + "@" + self.muc_name, typ='result',
attrs={"id": ID})
+ t1 = Behaviour.MessageTemplate(p)
+ b = self.GetGoalBehaviour(self.muc_name,
self.name, ID)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
class GetGoalBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,roomname,ID):
+ def __init__(self, muc_name, roomname, ID):
Behaviour.OneShotBehaviour.__init__(self)
- self.ID=ID
- self.muc_name=muc_name
-
self.name=roomname
- self.result=None
+ self.ID = ID
+ self.muc_name = muc_name
+
self.name = roomname
+ self.result = None
def _process(self):
- goal=None
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='get',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/disco#info")
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- msg=self._receive(True,10)
- if msg:
- query = msg.getTag("query")
- if query:
- x = query.getTag("x")
- if x:
- items =x.getChildren()
- for item in items:
- if item.getAttr("var")=="muc#roominfo_subject":
- if item.getTags("value"):
- goal=item.getTags("value")[0].getData()
- if goal==None:
- print "Not goal"
- self.result=goal
-
+ goal = None
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='get',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/disco#info")
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ msg = self._receive(True, 10)
+ if msg:
+ query = msg.getTag("query")
+ if query:
+ x = query.getTag("x")
+ if x:
+ items = x.getChildren()
+ for item in items:
+ if item.getAttr("var")
== "muc#roominfo_subject":
+ if item.getTags("value"):
+ goal =
item.getTags("value")[0].getData()
+ if goal is None:
+ print "Not goal"
+ self.result = goal
def getInfo(self):
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Iq(frm=
self.name+"@"+self.muc_name,typ='result', attrs={"id":ID})
- t1 = Behaviour.MessageTemplate(p)
- b=self.GetInfoBehaviour(self.muc_name,
self.name,ID)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
-
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Iq(frm=
self.name + "@" + self.muc_name, typ='result',
attrs={"id": ID})
+ t1 = Behaviour.MessageTemplate(p)
+ b = self.GetInfoBehaviour(self.muc_name,
self.name, ID)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
class GetInfoBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,roomname,ID):
+ def __init__(self, muc_name, roomname, ID):
Behaviour.OneShotBehaviour.__init__(self)
- self.ID=ID
- self.muc_name=muc_name
-
self.name=roomname
- self.result=None
+ self.ID = ID
+ self.muc_name = muc_name
+
self.name = roomname
+ self.result = None
def _process(self):
- info={}
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='get',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/disco#info")
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- msg=self._receive(True,10)
- if msg:
- query = msg.getTag("query")
- if query:
- x = query.getTag("x")
- if x:
- items =x.getChildren()
- for item in items:
- if item.getAttr("var")=="muc#roominfo_description":
- if item.getTags("value"):
-
info["type"]=str(item.getTags("value")[0].getData())
- if item.getAttr("var")=="muc#roominfo_subject":
- if item.getTags("value"):
-
info["goal"]=str(item.getTags("value")[0].getData())
- if item.getAttr("var")=="muc#roominfo_type":
- if item.getTags("value")[0].getData():
- if ':' in
item.getTags("value")[0].getData():
- info["parent"]=
str(item.getTags("value")[0].getData().split(':')[1])
- else:
-
info["parent"]=str(item.getTags("value")[0].getData())
- if item.getAttr("var")=="muc#roominfo_lang":
- if item.getTags("value"):
-
info["contentLanguage"]=str(item.getTags("value")[0].getData())
- self.result=info
-
+ info = {}
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='get',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/disco#info")
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ msg = self._receive(True, 10)
+ if msg:
+ query = msg.getTag("query")
+ if query:
+ x = query.getTag("x")
+ if x:
+ items = x.getChildren()
+ for item in items:
+ if item.getAttr("var")
== "muc#roominfo_description":
+ if item.getTags("value"):
+ info["type"] =
str(item.getTags("value")[0].getData())
+ if item.getAttr("var")
== "muc#roominfo_subject":
+ if item.getTags("value"):
+ info["goal"] =
str(item.getTags("value")[0].getData())
+ if item.getAttr("var") == "muc#roominfo_type":
+ if item.getTags("value")[0].getData():
+ if ':' in
item.getTags("value")[0].getData():
+ info["parent"] =
str(item.getTags("value")[0].getData().split(':')[1])
+ else:
+ info["parent"] =
str(item.getTags("value")[0].getData())
+ if item.getAttr("var") == "muc#roominfo_lang":
+ if item.getTags("value"):
+ info["contentLanguage"] =
str(item.getTags("value")[0].getData())
+ self.result = info
def getMemberList(self):
- """
- Returns a List with Agents' names belonging to the organization
- """
- if self.state=="unavailable":
- print "The "+self.UnavailableMsg+" "+
self.name+" is unavailable"
- return
-
ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))]
for a in range(5)])
- p = Iq(frm=
self.name+"@"+self.muc_name, attrs={"id":ID})
- t1 = Behaviour.MessageTemplate(p)
- b=self.GetMemberListBehaviour(self.muc_name,
self.name,ID)
- self.myAgent.addBehaviour(b, t1)
- b.join()
- return b.result
+ """
+ Returns a List with Agents' names belonging to the organization
+ """
+ if self.state == "unavailable":
+ print "The " + self.UnavailableMsg + " " +
self.name + " is
unavailable"
+ return
+ ID = "".join([string.ascii_letters[int(random.randint(0,
len(string.ascii_letters) - 1))] for a in range(5)])
+ p = Iq(frm=
self.name + "@" + self.muc_name, attrs={"id": ID})
+ t1 = Behaviour.MessageTemplate(p)
+ b = self.GetMemberListBehaviour(self.muc_name,
self.name, ID)
+ self.myAgent.addBehaviour(b, t1)
+ b.join()
+ return b.result
class GetMemberListBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self,muc_name,roomname,ID):
+ def __init__(self, muc_name, roomname, ID):
Behaviour.OneShotBehaviour.__init__(self)
- self.ID=ID
- self.muc_name=muc_name
-
self.name=roomname
- self.result=[]
+ self.ID = ID
+ self.muc_name = muc_name
+
self.name = roomname
+ self.result = []
def _process(self):
- # si es una unidad tambien hay que mirar si el presence
broadcast est√° restringido
- # if not checkOwner(self.myAgent):
- # print "This agent is not allowed to get the memberList"
- agents=[]
- iq = Iq(to=
self.name+"@"+self.muc_name,typ='get',
attrs={"id":self.ID})
- query =
Protocol('query',xmlns="
http://jabber.org/protocol/muc#admin")
- item= Node(tag="item", attrs={"affiliation":"member"})
- query.addChild(node=item)
- iq.addChild(node=query)
- self.myAgent.jabber.send(iq)
- msg=self._receive(True,10)
- if msg:
- error=msg.getError()
- if error!=None:
+ # si es una unidad tambien hay que mirar si el
presence broadcast est√° restringido
+ # if not checkOwner(self.myAgent):
+ # print "This agent is not allowed to get the
memberList"
+ agents = []
+ iq = Iq(to=
self.name + "@" + self.muc_name, typ='get',
attrs={"id": self.ID})
+ query = Protocol('query',
xmlns="
http://jabber.org/protocol/muc#admin")
+ item = Node(tag="item", attrs={"affiliation": "member"})
+ query.addChild(node=item)
+ iq.addChild(node=query)
+ self.myAgent.jabber.send(iq)
+ msg = self._receive(True, 10)
+ if msg:
+ error = msg.getError()
+ if error is not None:
print error
return
- query = msg.getTag("query")
- if query:
- items =query.getChildren()
+ query = msg.getTag("query")
+ if query:
***The diff for this file has been truncated for email.***
=======================================
--- /trunk/spade/XMLCodec.py Thu May 17 07:58:09 2007
+++ /trunk/spade/XMLCodec.py Fri Nov 23 05:19:16 2012
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
import xml.sax
from xml.sax import handler
from BasicFipaDateTime import *
@@ -6,413 +7,327 @@
import Envelope
-
class XMLCodec(handler.ContentHandler):
- """
- XML Parser
- """
- def __init__(self):
- #self.parser = xmlreader.IncrementalParser()
- #self.parser.setContentHandler(self)
- #self.parser.setErrorHandler(self)
+ """
+ XML Parser
+ """
+ def __init__(self):
+ #self.parser = xmlreader.IncrementalParser()
+ #self.parser.setContentHandler(self)
+ #self.parser.setErrorHandler(self)
- self.ToTag = False
-
- #Constants
- self.ENVELOPE_TAG = "envelope"
- self.PARAMS_TAG = "params"
- self.INDEX = "index"
- self.INDEX_ATTR = ' index="'
- self.TO_TAG = "to"
- self.AID_TAG = "agent-identifier"
- self.AID_NAME = "name"
- self.AID_ADDRESSES = "addresses"
- self.AID_ADDRESS = "url"
- self.FROM_TAG = "from"
- self.COMMENTS_TAG = "comments"
- self.REPRESENTATION_TAG = "acl-representation"
- self.LENGTH_TAG = "payload-length"
- self.ENCODING_TAG = "payload-encoding"
- self.DATE_TAG = "date"
- #self.ENCRYPTED_TAG = "encrypted"
- self.INTENDED_TAG = "intended-receiver"
- self.RECEIVED_TAG = "received"
- self.RECEIVED_DATE = "received-date"
- self.RECEIVED_BY = "received-by"
- self.RECEIVED_FROM = "received-from"
- self.RECEIVED_ID = "received-id"
- self.RECEIVED_VIA = "received-via"
- self.RECEIVED_ATTR = "value"
- self.PROP_TAG = "user-defined"
- self.PROP_ATTR = "href"
- self.PROP_ATTR_TYPE = "type"
- self.PROP_STRING_TYPE ="string"
- self.PROP_BYTE_TYPE="byte-array"
- self.PROP_SER_TYPE="serialized"
- self.OT = "<"
- self.ET = "</"
- self.CT = ">"
- self.NULL = ""
-
- # ***************************************************
- # * Encoding methods *
- # ***************************************************
+ self.ToTag = False
- """ Encode the information of Agent, Tags To and From """
- def encodeAid(self, agentid):
-
- if not isinstance(agentid, aid):
- return ""
+ #Constants
+ self.ENVELOPE_TAG = "envelope"
+ self.PARAMS_TAG = "params"
+ self.INDEX = "index"
+ self.INDEX_ATTR = ' index="'
+ self.TO_TAG = "to"
+ self.AID_TAG = "agent-identifier"
+ self.AID_NAME = "name"
+ self.AID_ADDRESSES = "addresses"
+ self.AID_ADDRESS = "url"
+ self.FROM_TAG = "from"
+ self.COMMENTS_TAG = "comments"
+ self.REPRESENTATION_TAG = "acl-representation"
+ self.LENGTH_TAG = "payload-length"
+ self.ENCODING_TAG = "payload-encoding"
+ self.DATE_TAG = "date"
+ #self.ENCRYPTED_TAG = "encrypted"
+ self.INTENDED_TAG = "intended-receiver"
+ self.RECEIVED_TAG = "received"
+ self.RECEIVED_DATE = "received-date"
+ self.RECEIVED_BY = "received-by"
+ self.RECEIVED_FROM = "received-from"
+ self.RECEIVED_ID = "received-id"
+ self.RECEIVED_VIA = "received-via"
+ self.RECEIVED_ATTR = "value"
+ self.PROP_TAG = "user-defined"
+ self.PROP_ATTR = "href"
+ self.PROP_ATTR_TYPE = "type"
+ self.PROP_STRING_TYPE = "string"
+ self.PROP_BYTE_TYPE = "byte-array"
+ self.PROP_SER_TYPE = "serialized"
+ self.OT = "<"
+ self.ET = "</"
+ self.CT = ">"
+ self.NULL = ""
- sb = self.OT + self.AID_TAG + self.CT
- sb = sb + self.encodeTag( self.AID_NAME, agentid.getName() )
- sb = sb + self.OT + self.AID_ADDRESSES + self.CT
-
- addresses = agentid.getAddresses()
- for addr in addresses:
- sb = sb + self.encodeTag( self.AID_ADDRESS, addr )
+ # ***************************************************
+ # * Encoding methods *
+ # ***************************************************
- sb = sb + self.ET + self.AID_ADDRESSES + self.CT
- sb = sb + self.ET + self.AID_TAG + self.CT
+ """ Encode the information of Agent, Tags To and From """
+ def encodeAid(self, agentid):
- return sb
+ if not isinstance(agentid, aid):
+ return ""
- """
- This does the following:
- < tag >
- content
- </ tag >
- """
- def encodeTag( self, tag, content ):
- sb = self.OT + tag + self.CT
- sb = sb + content
- sb = sb + self.ET + tag + self.CT
+ sb = self.OT + self.AID_TAG + self.CT
+ sb = sb + self.encodeTag(self.AID_NAME, agentid.getName())
+ sb = sb + self.OT + self.AID_ADDRESSES + self.CT
- return sb
-
- """
- A user-defined property (String name, Object value) is encoded the
following way:
- <user-defined href="name" type="type">value</user-defined>
- """
- """
- def encodeProp( self, prop):
- v = None
- Object o = p.getValue();
- String type = PROP_STRING_TYPE;
- if (o instanceof String) {
- v = (String)o;
- }
- else if (o instanceof byte[]) {
- type = PROP_BYTE_TYPE;
- v = new String(Base64.encode((byte[])o));
- }
- else if (o instanceof Serializable) {
- type = PROP_SER_TYPE;
- try{
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(bos);
- oos.writeObject(o);
- oos.close();
- byte[] bytes = bos.toByteArray();
- if(bytes != null)
- v = new String(Base64.encode(bytes));
- }catch(IOException ioe){
- return;
- }
- }
- else {
- return;
- }
- sb.append(OT).append(PROP_TAG).append(" ");
- sb.append(PROP_ATTR).append("=\"").append(p.getName()).append("\" ");
- sb.append(PROP_ATTR_TYPE).append("=\"").append(type).append("\"");
- sb.append(CT);
- sb.append(v);
- sb.append(ET).append(PROP_TAG).append(CT);
- }
- private void decodeProp(StringBuffer acc, Property p) {
- if(propType.equals(PROP_SER_TYPE)){
- try{
- char[] serdata = acc.toString().toCharArray();
- ObjectInputStream ois = new ObjectInputStream(
- new ByteArrayInputStream(Base64.decode(serdata)));
- p.setValue((Serializable)ois.readObject());
- }catch(Exception e){
- // nothing, we leave value of this property as null;
- }
- }else if(propType.equals(PROP_BYTE_TYPE)){
- char[] bytes = acc.toString().toCharArray();
- p.setValue(Base64.decode(bytes));
- }else{
- p.setValue(acc.toString());
- }
- propType = null;
- }
-"""
-
- def encodeOneLineTag( self, tag1, tag2, value ):
- sb = self.OT + tag1 + " "
- sb = sb + tag2 + '="' + value + '"/>'
+ addresses = agentid.getAddresses()
+ for addr in addresses:
+ sb = sb + self.encodeTag(self.AID_ADDRESS, addr)
- return sb
-
- def encodeXML(self, env):
- """
- General Encoding of the envelope
- """
-
- #Create the message XML
- sb = self.OT + self.ENVELOPE_TAG + self.CT
- sb = sb + self.OT + self.PARAMS_TAG + self.INDEX_ATTR + "1" + '"' +
self.CT
-
- #Create tag TO
- tos = env.getTo()
- for agentid in tos:
- sb = sb + self.OT + self.TO_TAG + self.CT
- sb = sb + self.encodeAid(agentid)
- sb = sb + self.ET + self.TO_TAG + self.CT
-
- #Create tag from
- if env.getFrom() != None:
- sb = sb + self.OT + self.FROM_TAG + self.CT
- sb = sb + self.encodeAid( env.getFrom() )
- sb = sb + self.ET + self.FROM_TAG + self.CT
-
- #Create tag comments
- if env.getComments() != None and len(env.getComments()) > 0:
- sb = sb + self.encodeTag( self.COMMENTS_TAG, env.getComments() )
-
- #Create tag acl-representation
- if env.getAclRepresentation() != None:
- sb = sb + self.encodeTag( self.REPRESENTATION_TAG,
env.getAclRepresentation() )
-
- #Create tag payload-length
- if env.getPayloadLength() != None:
- sb = sb + self.encodeTag( self.LENGTH_TAG, str(env.getPayloadLength())
)
-
- #Create tag payload-encoding
- if env.getPayloadEncoding() != None and len(env.getPayloadEncoding()) >
0:
- sb = sb + self.encodeTag( self.ENCODING_TAG, env.getPayloadEncoding() )
-
- #Create tag date
- #Create object BasicFipaDateTime
- if env.getDate() != None:
- date = BasicFipaDateTime()
- date.fromString( str(env.getDate()) )
- sb = sb + self.encodeTag( self.DATE_TAG, str(date) )
+ sb = sb + self.ET + self.AID_ADDRESSES + self.CT
+ sb = sb + self.ET + self.AID_TAG + self.CT
+
+ return sb
+
+ """
+ This does the following:
+ < tag >
+ content
+ </ tag >
+ """
+ def encodeTag(self, tag, content):
+ sb = self.OT + tag + self.CT
+ sb = sb + content
+ sb = sb + self.ET + tag + self.CT
+
+ return sb
+
+ """
+ A user-defined property (String name, Object value) is encoded the
following way:
+ <user-defined href="name" type="type">value</user-defined>
+ """
+
+ def encodeOneLineTag(self, tag1, tag2, value):
+ sb = self.OT + tag1 + " "
+ sb = sb + tag2 + '="' + value + '"/>'
+
+ return sb
+
+ def encodeXML(self, env):
+ """
+ General Encoding of the envelope
+ """
+
+ #Create the message XML
+ sb = self.OT + self.ENVELOPE_TAG + self.CT
+ sb = sb + self.OT + self.PARAMS_TAG + self.INDEX_ATTR + "1" + '"'
+ self.CT
+
+ #Create tag TO
+ tos = env.getTo()
+ for agentid in tos:
+ sb = sb + self.OT + self.TO_TAG + self.CT
+ sb = sb + self.encodeAid(agentid)
+ sb = sb + self.ET + self.TO_TAG + self.CT
+
+ #Create tag from
+ if env.getFrom() is not None:
+ sb = sb + self.OT + self.FROM_TAG + self.CT
+ sb = sb + self.encodeAid(env.getFrom())
+ sb = sb + self.ET + self.FROM_TAG + self.CT
+
+ #Create tag comments
+ if env.getComments() is not None and len(env.getComments()) > 0:
+ sb = sb + self.encodeTag(self.COMMENTS_TAG, env.getComments())
+
+ #Create tag acl-representation
+ if env.getAclRepresentation() is not None:
+ sb = sb + self.encodeTag(self.REPRESENTATION_TAG,
env.getAclRepresentation())
+
+ #Create tag payload-length
+ if env.getPayloadLength() is not None:
+ sb = sb + self.encodeTag(self.LENGTH_TAG,
str(env.getPayloadLength()))
+
+ #Create tag payload-encoding
+ if env.getPayloadEncoding() is not None and
len(env.getPayloadEncoding()) > 0:
+ sb = sb + self.encodeTag(self.ENCODING_TAG,
env.getPayloadEncoding())
+
+ #Create tag date
+ #Create object BasicFipaDateTime
+ if env.getDate() is not None:
+ date = BasicFipaDateTime()
+ date.fromString(str(env.getDate()))
+ sb = sb + self.encodeTag(self.DATE_TAG, str(date))
+
+ #Create tag encrypted (NL: not sure it is still in FIPA)
+ """
+ for i in env.getEncrypted():
+ sb = sb + self.encodeTag( self.ENCRYPTED_TAG, str(i) )
+ """
+
+ #Create tag intended-receiver
+ for i in env.getIntendedReceiver():
+ sb = sb + self.OT + self.INTENDED_TAG + self.CT
+ sb = sb + self.encodeAid(i)
+ sb = sb + self.ET + self.INTENDED_TAG + self.CT
+
+ """
+ #Create tags for user properties
+ for (i=env.getAllProperties();i.hasNext();) {
+ encodeProp(sb,(Property)i.next());
+ """
+
+ #Create tag received
+ ro = env.getReceived()
+ if ro is not None:
+ #Create tag received
+ sb = sb + self.OT + self.RECEIVED_TAG + self.CT
+ #Date
+ value = BasicFipaDateTime(ro.getDate())
+ if value is not None:
+ sb = sb + self.encodeOneLineTag(self.RECEIVED_DATE,
self.RECEIVED_ATTR, str(value))
+ #By
+ value = ro.getBy()
+ if value is not None:
+ sb = sb + self.encodeOneLineTag(self.RECEIVED_BY,
self.RECEIVED_ATTR, value)
+ #From
+ value = ro.getFrom()
+ if value is not None:
+ sb = sb + self.encodeOneLineTag(self.RECEIVED_FROM,
self.RECEIVED_ATTR, value)
+ #Id
+ value = ro.getId()
+ if value is not None:
+ sb = sb + self.encodeOneLineTag(self.RECEIVED_ID,
self.RECEIVED_ATTR, value)
+ #Via
+ value = ro.getVia()
+ if value is not None:
+ sb = sb + self.encodeOneLineTag(self.RECEIVED_VIA,
self.RECEIVED_ATTR, value)
+
+ sb = sb + self.ET + self.RECEIVED_TAG + self.CT
+
+ sb = sb + self.ET + self.PARAMS_TAG + self.CT
+ sb = sb + self.ET + self.ENVELOPE_TAG + self.CT
-
- #Create tag encrypted (NL: not sure it is still in FIPA)
- """
- for i in env.getEncrypted():
- sb = sb + self.encodeTag( self.ENCRYPTED_TAG, str(i) )
- """
-
- #Create tag intended-receiver
- for i in env.getIntendedReceiver():
- sb = sb + self.OT + self.INTENDED_TAG + self.CT
- sb = sb + self.encodeAid(i)
- sb = sb + self.ET + self.INTENDED_TAG + self.CT
-
- """
- #Create tags for user properties
- for (i=env.getAllProperties();i.hasNext();) {
- encodeProp(sb,(Property)i.next());
- """
+ return sb
- #Create tag received
- ro = env.getReceived()
- if ro != None:
- #Create tag received
- sb = sb + self.OT + self.RECEIVED_TAG + self.CT
- #Date
- value = BasicFipaDateTime( ro.getDate() )
- if value != None:
- sb = sb + self.encodeOneLineTag( self.RECEIVED_DATE,
self.RECEIVED_ATTR, str( value ) )
- #By
- value = ro.getBy()
- if value != None:
- sb = sb + self.encodeOneLineTag( self.RECEIVED_BY, self.RECEIVED_ATTR,
value )
- #From
- value = ro.getFrom()
- if value != None:
- sb = sb + self.encodeOneLineTag( self.RECEIVED_FROM,
self.RECEIVED_ATTR, value )
- #Id
- value = ro.getId()
- if value != None:
- sb = sb + self.encodeOneLineTag( self.RECEIVED_ID, self.RECEIVED_ATTR,
value )
- #Via
- value = ro.getVia()
- if value != None:
- sb = sb + self.encodeOneLineTag( self.RECEIVED_VIA,
self.RECEIVED_ATTR, value )
+ """
+ ***************************************************
+ * Decoding methods *
+ ***************************************************
+ """
- sb = sb + self.ET + self.RECEIVED_TAG + self.CT
+ #This method is called when start the document XML
+ def startDocument(self):
+ self.env = Envelope.Envelope()
+ #This method is called at the end of parsing */
+ def endDocument(self):
+ pass
+ #Put the ro object in to envelope
+ #env.setReceived(ro)
+ #This method is called when jmp event of begin element.*/
+ #def startElement(self, uri, localName, rawName, attributes):
+ def startElement(self, localName, attributes):
- sb = sb + self.ET + self.PARAMS_TAG + self.CT
- sb = sb + self.ET + self.ENVELOPE_TAG + self.CT
-
- return sb
+ #Detection of the begin of to or from tags
+ self.accumulator = ""
- """
- ***************************************************
- * Decoding methods *
- ***************************************************
- """
-
- #This method is called when start the document XML
- def startDocument(self):
- self.env = Envelope.Envelope()
-
- #This method is called at the end of parsing */
- def endDocument(self):
- pass
- #Put the ro object in to envelope
- #env.setReceived(ro)
+ if self.TO_TAG.lower() == localName.lower():
+ self.aid = aid()
+ self.aidTag = self.TO_TAG
+ #self.env.addTo(aid)
- #This method is called when jmp event of begin element.*/
- #def startElement(self, uri, localName, rawName, attributes):
- def startElement(self, localName, attributes):
-
- #Detection of the begin of to or from tags
- self.accumulator = ""
-
- if self.TO_TAG.lower() == localName.lower():
- self.aid = aid()
- self.aidTag = self.TO_TAG
- #self.env.addTo(aid)
+ elif self.FROM_TAG.lower() == localName.lower():
+ self.aid = aid()
+ self.aidTag = self.FROM_TAG
+ #self.env.setFrom(aid)
- elif self.FROM_TAG.lower() == localName.lower():
- self.aid = aid()
- self.aidTag = self.FROM_TAG
- #self.env.setFrom(aid)
+ elif self.INTENDED_TAG.lower() == localName.lower():
+ self.aid = aid()
+ self.aidTag = self.INTENDED_TAG
+ #self.env.addIntendedReceiver(self.aid)
- elif self.INTENDED_TAG.lower() == localName.lower():
- self.aid = aid()
- self.aidTag = self.INTENDED_TAG
- #self.env.addIntendedReceiver(self.aid)
+ elif self.RECEIVED_TAG.lower() == localName.lower():
+ self.env.setReceived(ReceivedObject())
- elif self.RECEIVED_TAG.lower() == localName.lower():
- self.env.setReceived(ReceivedObject())
-
- elif self.RECEIVED_BY.lower() == localName.lower():
- self.env.received.setBy( attributes.getValue(self.RECEIVED_ATTR) )
+ elif self.RECEIVED_BY.lower() == localName.lower():
+
self.env.received.setBy(attributes.getValue(self.RECEIVED_ATTR))
- elif self.RECEIVED_FROM.lower() == localName.lower():
- self.env.received.setFrom( attributes.getValue(self.RECEIVED_ATTR) )
+ elif self.RECEIVED_FROM.lower() == localName.lower():
+
self.env.received.setFrom(attributes.getValue(self.RECEIVED_ATTR))
- elif self.RECEIVED_DATE.lower() == localName.lower():
- self.env.received.setDate( BasicFipaDateTime(
str(attributes.getValue(self.RECEIVED_ATTR) )) )
+ elif self.RECEIVED_DATE.lower() == localName.lower():
+
self.env.received.setDate(BasicFipaDateTime(str(attributes.getValue(self.RECEIVED_ATTR))))
- elif self.RECEIVED_ID.lower() == localName.lower():
- self.env.received.setId( attributes.getValue(self.RECEIVED_ATTR) )
+ elif self.RECEIVED_ID.lower() == localName.lower():
+
self.env.received.setId(attributes.getValue(self.RECEIVED_ATTR))
- elif self.RECEIVED_VIA.lower() == localName.lower():
- self.env.received.setVia( attributes.getValue(self.RECEIVED_ATTR) )
+ elif self.RECEIVED_VIA.lower() == localName.lower():
+
self.env.received.setVia(attributes.getValue(self.RECEIVED_ATTR))
- """
- elif self.PROP_TAG.lower() == localName.lower():
- prop = Property()
- env.addProperties(prop)
- prop.setName(attributes.getValue(self.PROP_ATTR))
- propType = attributes.getValue(self.PROP_ATTR_TYPE)
- """
-
- #This method is called the end of element
- #def endElement(self, namespaceURL, localName, qname):
- def endElement(self, localName):
-
- #Capture the value the attributes of class
- if self.AID_NAME.lower() == localName.lower():
- self.aid.setName(self.accumulator)
+ """
+ elif self.PROP_TAG.lower() == localName.lower():
+ prop = Property()
+ env.addProperties(prop)
+ prop.setName(attributes.getValue(self.PROP_ATTR))
+ propType = attributes.getValue(self.PROP_ATTR_TYPE)
+ """
- elif self.AID_ADDRESS.lower() == localName.lower():
- self.aid.addAddress(self.accumulator)
+ #This method is called the end of element
+ #def endElement(self, namespaceURL, localName, qname):
+ def endElement(self, localName):
- elif self.TO_TAG.lower() == localName.lower():
- self.aidTag = ""
+ #Capture the value the attributes of class
+ if self.AID_NAME.lower() == localName.lower():
+ self.aid.setName(self.accumulator)
- elif self.FROM_TAG.lower() == localName.lower():
- self.aidTag = ""
+ elif self.AID_ADDRESS.lower() == localName.lower():
+ self.aid.addAddress(self.accumulator)
- elif self.INTENDED_TAG.lower() == localName.lower():
- self.aidTag = ""
+ elif self.TO_TAG.lower() == localName.lower():
+ self.aidTag = ""
- elif self.AID_TAG.lower() == localName.lower():
- if self.aidTag == self.TO_TAG:
- self.env.addTo(self.aid)
- elif self.aidTag == self.FROM_TAG:
- self.env.setFrom(self.aid)
- elif self.aidTag == self.INTENDED_TAG:
- self.env.addIntendedReceiver(self.aid)
+ elif self.FROM_TAG.lower() == localName.lower():
+ self.aidTag = ""
- elif self.COMMENTS_TAG.lower() == localName.lower():
- self.env.setComments(self.accumulator)
+ elif self.INTENDED_TAG.lower() == localName.lower():
+ self.aidTag = ""
- elif self.REPRESENTATION_TAG.lower() == localName.lower():
- self.env.setAclRepresentation(self.accumulator)
+ elif self.AID_TAG.lower() == localName.lower():
+ if self.aidTag == self.TO_TAG:
+ self.env.addTo(self.aid)
+ elif self.aidTag == self.FROM_TAG:
+ self.env.setFrom(self.aid)
+ elif self.aidTag == self.INTENDED_TAG:
+ self.env.addIntendedReceiver(self.aid)
- elif self.LENGTH_TAG.lower() == localName.lower():
- self.env.setPayloadLength( long(self.accumulator) )
- """
- if(logger.isLoggable(Logger.WARNING))
- logger.log(Logger.FINE,"Length: "+env.getPayloadLength());
- """
+ elif self.COMMENTS_TAG.lower() == localName.lower():
+ self.env.setComments(self.accumulator)
- elif self.ENCODING_TAG.lower() ==localName.lower():
- self.env.setPayloadEncoding(self.accumulator)
+ elif self.REPRESENTATION_TAG.lower() == localName.lower():
+ self.env.setAclRepresentation(self.accumulator)
- elif self.DATE_TAG.lower() == localName.lower():
- bfdt= BasicFipaDateTime()
- bfdt.fromString(str(self.accumulator))
- self.env.setDate( bfdt )
+ elif self.LENGTH_TAG.lower() == localName.lower():
+ self.env.setPayloadLength(long(self.accumulator))
+ """
+ if(logger.isLoggable(Logger.WARNING))
+ logger.log(Logger.FINE,"Length: "+env.getPayloadLength());
+ """
- """
- elif self.PROP_TAG.lower() == localName.lower():
- decodeProp(accumulator, prop);
- """
- """
- #Not sure it is still in FIPA
- elif self.ENCRYPTED_TAG.lower() == localName.low():
- self.env.addEncrypted(accumulator)
- """
-
- #This method is called when exist characters in the elements
- def characters(self, buff):
- self.accumulator = self.accumulator + buff
-
- """
- /** This method is called when warning occur*/
- public void warning(SAXParseException exception) {
- if(logger.isLoggable(Logger.WARNING))
- logger.log(Logger.WARNING," line " + exception.getLineNumber() + ": "+
- exception.getMessage());
- }
-
- /** This method is called when errors occur*/
- public void error(SAXParseException exception) {
- if(logger.isLoggable(Logger.WARNING))
- logger.log(Logger.WARNING,"ERROR: line " + exception.getLineNumber()
+ ": " +
- exception.getMessage());
- }
-
- /** This method is called when non-recoverable errors occur.*/
- public void fatalError(SAXParseException exception) throws SAXException{
- if(logger.isLoggable(Logger.WARNING))
- logger.log(Logger.SEVERE,"FATAL: line " + exception.getLineNumber()
+ ": " +
- exception.getMessage());
- throw exception;
- }
- """
+ elif self.ENCODING_TAG.lower() == localName.lower():
+ self.env.setPayloadEncoding(self.accumulator)
- # Main method #
- def parse(self, _in):
- """
- parses the xml input
- """
- xml.sax.parseString(_in, self)
- return self.env
+ elif self.DATE_TAG.lower() == localName.lower():
+ bfdt = BasicFipaDateTime()
+ bfdt.fromString(str(self.accumulator))
+ self.env.setDate(bfdt)
+ """
+ elif self.PROP_TAG.lower() == localName.lower():
+ decodeProp(accumulator, prop);
+ """
+ """
+ #Not sure it is still in FIPA
+ elif self.ENCRYPTED_TAG.lower() == localName.low():
+ self.env.addEncrypted(accumulator)
+ """
+ #This method is called when exist characters in the elements
+ def characters(self, buff):
+ self.accumulator = self.accumulator + buff
+ # Main method #
+ def parse(self, _in):
+ """
+ parses the xml input
+ """
+ xml.sax.parseString(_in, self)
+ return self.env
=======================================
--- /trunk/spade/XSBKB.py Tue Jul 10 16:56:02 2012
+++ /trunk/spade/XSBKB.py Fri Nov 23 05:19:16 2012
@@ -1,48 +1,49 @@
+# -*- coding: utf-8 -*-
from logic import KB
from pyxf import xsb
-class XSBKB( KB ):
- '''XSB Prolog knowledge base'''
- def __init__( self, sentence=None, path='xsb' ):
- '''Constructor method
- Usage: XSBKB( sentence, path )
- sentence - Prolog sentence to be added to the KB (default: None)
- path - path to XSB executable (default: 'xsb')'''
- self.xsb = xsb( path )
- if sentence:
- self.tell( sentence )
- def tell( self, sentence ):
- '''Adds sentence to KB'''
- sentence = sentence.strip()
- if sentence[ -1 ] == '.':
- sentence = sentence[ :-1 ]
- return self.xsb.query( 'assert(' + sentence + ')' )
+class XSBKB(KB):
+ '''XSB Prolog knowledge base'''
+ def __init__(self, sentence=None, path='xsb'):
+ '''Constructor method
+ Usage: XSBKB( sentence, path )
+ sentence - Prolog sentence to be added to the KB (default: None)
+ path - path to XSB executable (default: 'xsb')'''
+ self.xsb = xsb(path)
+ if sentence:
+ self.tell(sentence)
- def ask( self, query ):
- '''Queries the KB'''
- return self.xsb.query( query )
+ def tell(self, sentence):
+ '''Adds sentence to KB'''
+ sentence = sentence.strip()
+ if sentence[-1] == '.':
+ sentence = sentence[:-1]
+ return self.xsb.query('assert(' + sentence + ')')
+
+ def ask(self, query):
+ '''Queries the KB'''
+ return self.xsb.query(query)
+
+ def retract(self, sentence):
+ '''Deletes sentence from KB'''
+ sentence = sentence.strip()
+ if sentence[-1] == '.':
+ sentence = sentence[:-1]
+ return self.xsb.query('retract(' + sentence + ')')
- def retract( self, sentence ):
- '''Deletes sentence from KB'''
- sentence = sentence.strip()
- if sentence[ -1 ] == '.':
- sentence = sentence[ :-1 ]
- return self.xsb.query( 'retract(' + sentence + ')' )
+ def loadModule(self, module):
+ '''Loads module to KB
+ Usage: instance.loadModule( path )
+ path - path to module'''
+ self.xsb.load(module)
- def loadModule( self, module ):
- '''Loads module to KB
- Usage: instance.loadModule( path )
- path - path to module'''
- self.xsb.load( module )
-
if __name__ == '__main__':
- kb = XSBKB()
- kb.tell( 'a(b,c)' )
- kb.tell( 'a(c,d)' )
- kb.tell( '( p(_X,_Y) :- a(_X,_Y) )' )
- kb.tell( '( p(_X,_Y) :- a(_X,_Z), p(_Z,_Y) )' )
- for result in kb.ask( 'p(X,Y)' ):
- print result
- kb.retract( 'a(b,c)' )
-
+ kb = XSBKB()
+ kb.tell('a(b,c)')
+ kb.tell('a(c,d)')
+ kb.tell('( p(_X,_Y) :- a(_X,_Y) )')
+ kb.tell('( p(_X,_Y) :- a(_X,_Z), p(_Z,_Y) )')
+ for result in kb.ask('p(X,Y)'):
+ print result
+ kb.retract('a(b,c)')
=======================================
--- /trunk/spade/__init__.py Thu Jun 24 16:31:43 2010
+++ /trunk/spade/__init__.py Fri Nov 23 05:19:16 2012
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
import ACLMessage
import Behaviour
import Envelope
=======================================
--- /trunk/spade/bdi.py Tue Jul 31 06:58:54 2012
+++ /trunk/spade/bdi.py Fri Nov 23 05:19:16 2012
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
from logic import *
from copy import copy
import types
@@ -9,14 +10,23 @@
from FlexQueue import FlexQueue
from Queue import Queue
-class PreConditionFailed (Exception): pass
-class PostConditionFailed(Exception): pass
-class ServiceFailed(Exception): pass
+
+class PreConditionFailed (Exception):
+ pass
+
+
+class PostConditionFailed(Exception):
+ pass
+
+
+class ServiceFailed(Exception):
+ pass
+
class Goal:
-
- types = ["achieve","mantain","cease","query","perform"]
-
+
+ types = ["achieve", "mantain", "cease", "query", "perform"]
+
def __init__(self, expression, typ="achieve"):
self.type = typ
self.expression = expression
@@ -29,26 +39,26 @@
def testConflict(self, goal):
# No conflict test at the moment
return False
-
+
def __str__(self):
if self.unreachable:
- return "UNREACHABLE("+str(self.expression)+")"
+ return "UNREACHABLE(" + str(self.expression) + ")"
elif self.done:
- return "DONE("+str(self.expression)+")"
+ return "DONE(" + str(self.expression) + ")"
else:
return str(self.expression)
def __repr__(self):
- return self.__str__()
+ return self.__str__()
class PlanList(dict):
#plans hash table. PID is the PlanID
def add(self, plan):
- pid = random.randint(1,100000000)
- while self.has_key(pid):
- pid = random.randint(1,100000000)
- self[pid]=plan
+ pid = random.randint(1, 100000000)
+ while pid in self:
+ pid = random.randint(1, 100000000)
+ self[pid] = plan
plan.pid = pid
return pid
@@ -60,26 +70,26 @@
# Agent.Agent.__init__(self,agentjid, password, port=port,
debug=debug, p2p=p2p)
def __init__(self, period):
Behaviour.PeriodicBehaviour.__init__(self, period)
- self.goals = [] # active goals
- self.plans = PlanList() # plan library
- self.intentions = [] # selected plans for execution
+ self.goals = [] # active goals
+ self.plans = PlanList() # plan library
+ self.intentions = [] # selected plans for execution
#self.services = [] # services offered by the agent
- self.TBCBP = tbcbp.TBCBP()
- self.active_goals = FlexQueue()
- self.prepared_goals = FlexQueue()
- self.scheduler = Queue()
+ self.TBCBP = tbcbp.TBCBP()
+ self.active_goals = FlexQueue()
+ self.prepared_goals = FlexQueue()
+ self.scheduler = Queue()
self._needDeliberate = True
-
+
def configureKB(self, typ, sentence=None, path=None):
- self.myAgent.kb.configure(typ,sentence,path)
+ self.myAgent.kb.configure(typ, sentence, path)
def addBelieve(self, sentence, type="insert"):
- self.myAgent.addBelieve(sentence,type)
+ self.myAgent.addBelieve(sentence, type)
self._needDeliberate = True
def removeBelieve(self, sentence, type="delete"):
- self.myAgent.removeBelieve(sentence,type)
+ self.myAgent.removeBelieve(sentence, type)
def askBelieve(self, sentence):
return self.myAgent.askBelieve(sentence)
@@ -91,25 +101,25 @@
def getFact(self, name):
return self.myAgent.kb.get(name)
- def addPlan(self, P,Q,inputs, outputs, services):
+ def addPlan(self, P, Q, inputs, outputs, services):
'''Adds a new plan to the Planner (TBCBP)
Usage: addPlan (P, Q, services)
P - precondition of the plan
Q - postcondition of the plan
services - list of services names (strings)
-
+
Return: None'''
- cases=[]
+ cases = []
for s in services:
c = self.TBCBP.getCaseOfService(str(s))
- if c==None:
- self.myAgent.DEBUG("Plan was not added. Service "+str(s)
+ " does not exist.","err",'bdi')
+ if c is None:
+ self.myAgent.DEBUG("Plan was not added. Service " + str(s)
+ " does not exist.", "err", 'bdi')
return False
cases.append(c)
plan = tbcbp.Plan(cases)
self.TBCBP.addPlan(plan)
- self.myAgent.DEBUG("Plan added: "+str(plan),"ok",'bdi')
+ self.myAgent.DEBUG("Plan added: " + str(plan), "ok", 'bdi')
self._needDeliberate = True
return True
@@ -121,24 +131,25 @@
if g.testConflict(goal):
conflict = True
break
- if not conflict and self.askBelieve(goal.expression)==False:
- self.myAgent.DEBUG("Goal added: "+str(goal),"ok", 'bdi')
+ if not conflict and self.askBelieve(goal.expression) is False:
+ self.myAgent.DEBUG("Goal added: " + str(goal), "ok", 'bdi')
self.goals.append(goal)
self._needDeliberate = True
-
+
def registerServiceInTBCBP(self, service, time=1):
'''Registers new service in the Planner (TBCBP)
Usage: registerService(service, time)
service - A DF.Service class
time - the estimated execution time of the service (optional)
-
+
Returns: None'''
-
- self.TBCBP.registerService(service=service,time=time)
+
+ self.TBCBP.registerService(service=service, time=time)
self._needDeliberate = True
def unregisterServiceInTBCBP(self, name=None, service=None):
- if not name: name= service.getName()
+ if not name:
+ name = service.getName()
self.TBCBP.delService(name)
self._needDeliberate = True
@@ -147,19 +158,19 @@
If there is not an existing plan, it composes a new one (when
possible)
Usage getPlan( goal )
goal - a Goal object to be achieved
-
+
Returns: TBCBP.Plan object or None is there is no available plan'''
-
- self.myAgent.DEBUG("Composing a plan for
goal "+str(goal),'info','bdi')
+
+ self.myAgent.DEBUG("Composing a plan for goal " +
str(goal), 'info', 'bdi')
plan = self.composePlan(goal)
- if plan == None:
+ if plan is None:
#goal is unreachable
- self.myAgent.DEBUG("No plan found for
Goal "+str(goal), 'warn','bdi')
+ self.myAgent.DEBUG("No plan found for Goal " +
str(goal), 'warn', 'bdi')
return None
plan['index'] = 0
- plan['goal'] = goal
+ plan['goal'] = goal
plan.agent_owner = self.myAgent
return plan
@@ -167,8 +178,8 @@
'''
calls the Temporal-Bounded Case Based Planner
'''
- return self.TBCBP.composePlan(goal,self.myAgent.kb,tout=20)
-
+ return self.TBCBP.composePlan(goal, self.myAgent.kb, tout=20)
+
def selectIntentions(self):
'''
Prepares new plan for active goals
@@ -179,41 +190,42 @@
#while not self.prepared_goals.empty(): #return
goal = self.prepared_goals.get()
- self.myAgent.DEBUG("Got goal "+ str(goal),'info','bdi')
+ self.myAgent.DEBUG("Got goal " + str(goal), 'info', 'bdi')
- if goal!=None:
- if self.askBelieve(goal.expression)==True:
- goal.done=True
- return None #continue
- if goal in self.active_goals: return None #continue
+ if goal is not None:
+ if self.askBelieve(goal.expression) is True:
+ goal.done = True
+ return None # continue
+ if goal in self.active_goals:
+ return None # continue
- self.myAgent.DEBUG("Activate Goal: " + str(goal), 'info','bdi')
+ self.myAgent.DEBUG("Activate Goal: " +
str(goal), 'info', 'bdi')
plan = self.getPlan(goal)
- if plan!=None:
+ if plan is not None:
#activate plan
- self.myAgent.DEBUG("Got a plan for goal " +
str(goal), 'info','bdi')
+ self.myAgent.DEBUG("Got a plan for goal " +
str(goal), 'info', 'bdi')
goal.selected = True
self.active_goals.put(goal)
plan.agent = self
- #init plan
+ #init plan
pid = self.plans.add(plan)
#activate first service
- self.insertNextService(plan,pid)
+ self.insertNextService(plan, pid)
self.planSelectedCB(plan)
else:
goal.unreachable = True
- self.myAgent.DEBUG("Goal is
Unreachable: "+str(goal), 'warn','bdi')
+ self.myAgent.DEBUG("Goal is Unreachable: " +
str(goal), 'warn', 'bdi')
return None
- def insertNextService(self,plan,pid):
+ def insertNextService(self, plan, pid):
'''Selects the next service of a plan to be executed
Usage: insertNextService( plan, pid)
plan - the running plan (TBCBP.Plan)
pid - the plan identifier'''
-
+
service_name = plan.getNextService()
- self.myAgent.DEBUG("next service is " +
str(service_name),'info','bdi')
- if service_name == None:
+ self.myAgent.DEBUG("next service is " +
str(service_name), 'info', 'bdi')
+ if service_name is None:
self.EndPlan(pid, plan)
return
service = self.TBCBP.getService(service_name)
@@ -223,10 +235,10 @@
self.scheduler.put(service)
- else: #plan has finished
+ else: # plan has finished
self.EndPlan(pid, plan)
- def EndPlan(self,pid,plan):
+ def EndPlan(self, pid, plan):
'''Finishes the execution of a plan.
If the plan run well, its case is rewarded. Otherwise, it is
punished.
Finally goal is setted as done and not active.
@@ -236,29 +248,29 @@
'''
del self.plans[pid]
#check its postcondition
- if len(plan.getQ()) > 0 and self.askBelieve(plan.getQ()[0])==False:
+ if len(plan.getQ()) > 0 and self.askBelieve(plan.getQ()[0]) is
False:
#logging.error(color_red+"PLAN FAILED "+str(plan)+color_none)
self.TBCBP.punish(plan.getCase())
- for goal in self.goals: #deselect the goal that raised the plan
+ for goal in self.goals: # deselect the goal that raised the
plan
if goal.expression == plan.getQ():
goal.selected = False
goal.done = False
self.active_goals.remove(goal)
else:
self.TBCBP.reward(plan.getCase())
- self.myAgent.DEBUG("Rewarding Plan",'ok','bdi')
- for goal in self.goals: #delete the goal that raised the
intention
+ self.myAgent.DEBUG("Rewarding Plan", 'ok', 'bdi')
+ for goal in self.goals: # delete the goal that raised the
intention
if goal.expression in plan.getQ():
- if goal.persistent: #if goal is persistent, deselect it
+ if goal.persistent: # if goal is persistent, deselect
it
self.prepared_goals.put(goal)
self.active_goals.remove(goal)
goal.done = True
goal.selected = False
- self.myAgent.DEBUG("Goal "+str(goal.expression)+" was
completed!",'ok','bdi')
- self.myAgent.DEBUG("Calling goal completed CB: "+
str(self.goalCompletedCB),'info','bdi')
+ self.myAgent.DEBUG("Goal " + str(goal.expression) + "
was completed!", 'ok', 'bdi')
+ self.myAgent.DEBUG("Calling goal completed CB: " +
str(self.goalCompletedCB), 'info', 'bdi')
self.goalCompletedCB(goal)
- def EndService(self,service,plan):
+ def EndService(self, service, plan):
'''Finishes the execution of a service.
If the service failed, it is punished and the plan is finished.
Otherwise, the next service of the plan is selected.
@@ -270,12 +282,12 @@
agent = self
pid = plan.pid
#service has been executed
- if len(service.getQ()) > 0 and
self.askBelieve(service.getQ()[0])==False:
+ if len(service.getQ()) > 0 and self.askBelieve(service.getQ()[0])
is False:
#service failed
- self.myAgent.DEBUG("Service execution
failed: "+str(service.getQ()))
+ self.myAgent.DEBUG("Service execution failed: " +
str(service.getQ()))
self.punishService(service)
#cancel plan and reactivate goal
- self.EndPlan(pid,plan)
+ self.EndPlan(pid, plan)
return
#5.2.1 select next service
@@ -284,26 +296,25 @@
self.serviceCompletedCB(service)
def deliberate(self):
- self.myAgent.DEBUG("deliberate about current
goals: "+str(self.goals),'info','bdi')
+ self.myAgent.DEBUG("deliberate about current goals: " +
str(self.goals), 'info', 'bdi')
for goal in self.goals:
- if (goal.unreachable == False) and (goal.done==False): # or
((goal.done==True) and (goal.persistent==True))):
- if self.askBelieve(goal.expression)==False:
- self.myAgent.DEBUG("Deliberate about " +
str(goal),'info','bdi')
+ if (goal.unreachable is False) and (goal.done is False): # or
((goal.done==True) and (goal.persistent==True))):
+ if self.askBelieve(goal.expression) is False:
+ self.myAgent.DEBUG("Deliberate about " +
str(goal), 'info', 'bdi')
if goal not in self.active_goals:
self.prepared_goals.put(goal)
else:
- self.myAgent.DEBUG("Goal " + str(goal) + "is already
in the KB: " + str(self.askBelieve(goal.expression)),'warn','bdi')
+ self.myAgent.DEBUG("Goal " + str(goal) + "is already
in the KB: " + str(self.askBelieve(goal.expression)), 'warn', 'bdi')
goal.done = True
-
def discover(self):
#TODO: use PubSub features
s = DF.Service()
results = self.myAgent.searchService(s)
- if results!=None:
- self.myAgent.DEBUG("Discovered "+str(len(results))+ "
services.", 'info','bdi')
+ if results is not None:
+ self.myAgent.DEBUG("Discovered " + str(len(results)) + "
services.", 'info', 'bdi')
for service in results:
- if self.TBCBP.getService(service.getName()) == None:
+ if self.TBCBP.getService(service.getName()) is None:
self.registerServiceInTBCBP(service)
def punishService(self, service):
@@ -311,9 +322,8 @@
Q = service.getQ()
I = service.getInputs()
O = service.getOutputs()
-
self.TBCBP.punish(Case(P=P,Q=Q,inputs=I,outputs=O,services=[service.getName()]))
+ self.TBCBP.punish(Case(P=P, Q=Q, inputs=I, outputs=O,
services=[service.getName()]))
return
-
####Init The agent
###self._setup()
@@ -321,7 +331,6 @@
###self._running = True
###self.behavioursGo.notifyAll()
###self.behavioursGo.release()
-
#############
# Main Loop #
#############
@@ -329,56 +338,55 @@
### try:
### #get and process all messages
### self.getMessages()
-
def _onTick(self):
"""
periodic behaviour execution
"""
#discover new services
- self.myAgent.DEBUG("Discover new services...", 'info','bdi')
+ self.myAgent.DEBUG("Discover new services...", 'info', 'bdi')
self.discover()
-
+
#deliberate about current goals
#if self._needDeliberate:
- self.myAgent.DEBUG("Deliberating...", 'info','bdi')
+ self.myAgent.DEBUG("Deliberating...", 'info', 'bdi')
self.deliberate()
#self._needDeliberate = False
-
+
#select intentions
- self.DEBUG("select intentions", 'info','bdi')
+ self.DEBUG("select intentions", 'info', 'bdi')
self.selectIntentions()
-
- self.myAgent.DEBUG("Init scheduler", 'info','bdi')
+
+ self.myAgent.DEBUG("Init scheduler", 'info', 'bdi')
#run a service each iteration
if not self.scheduler.empty():
service = self.scheduler.get()
- self.myAgent.DEBUG("Got service for execution: " +
str(service),'info','bdi')
-
+ self.myAgent.DEBUG("Got service for execution: " +
str(service), 'info', 'bdi')
+
#if service!=None:
pid = service.pid
plan = self.plans[pid]
- try:
+ try:
result = self.myAgent.invokeService(service)
except:
- self.myAgent.DEBUG("Service failed!", 'warn','bdi')
+ self.myAgent.DEBUG("Service failed!", 'warn', 'bdi')
self.EndService(service, plan)
else:
self.myAgent.DEBUG("NOP", 'info', 'bdi')
- self.myAgent.DEBUG("Restarting BDI cycle", 'info','bdi')
-
+ self.myAgent.DEBUG("Restarting BDI cycle", 'info', 'bdi')
def planSelectedCB(self, plan):
#callback executed when a new plan is selected for execution
#must be overloaded
pass
+
def goalCompletedCB(self, goal):
#callback executed when a goal is completed succesfully
#must be overloaded
pass
+
def serviceCompletedCB(self, service):
#callback executed when a service is completed succesfully
#must be overloaded
pass
-
=======================================
--- /trunk/spade/colors.py Wed Jun 21 11:10:23 2006
+++ /trunk/spade/colors.py Fri Nov 23 05:19:16 2012
@@ -1,19 +1,19 @@
+# -*- coding: utf-8 -*-
# Taken from xmpp debug
-color_none = chr(27) + "[0m"
-color_black = chr(27) + "[30m"
-color_red = chr(27) + "[31m"
-color_green = chr(27) + "[32m"
-color_brown = chr(27) + "[33m"
-color_blue = chr(27) + "[34m"
-color_magenta = chr(27) + "[35m"
-color_cyan = chr(27) + "[36m"
-color_light_gray = chr(27) + "[37m"
-color_dark_gray = chr(27) + "[30;1m"
-color_bright_red = chr(27) + "[31;1m"
+color_none = chr(27) + "[0m"
+color_black = chr(27) + "[30m"
+color_red = chr(27) + "[31m"
+color_green = chr(27) + "[32m"
+color_brown = chr(27) + "[33m"
+color_blue = chr(27) + "[34m"
+color_magenta = chr(27) + "[35m"
+color_cyan = chr(27) + "[36m"
+color_light_gray = chr(27) + "[37m"
+color_dark_gray = chr(27) + "[30;1m"
+color_bright_red = chr(27) + "[31;1m"
color_bright_green = chr(27) + "[32;1m"
-color_yellow = chr(27) + "[33;1m"
-color_bright_blue = chr(27) + "[34;1m"
-color_purple = chr(27) + "[35;1m"
-color_bright_cyan = chr(27) + "[36;1m"
-color_white = chr(27) + "[37;1m"
-
+color_yellow = chr(27) + "[33;1m"
+color_bright_blue = chr(27) + "[34;1m"
+color_purple = chr(27) + "[35;1m"
+color_bright_cyan = chr(27) + "[36;1m"
+color_white = chr(27) + "[37;1m"
=======================================
--- /trunk/spade/content.py Mon Jun 28 09:33:42 2010
+++ /trunk/spade/content.py Fri Nov 23 05:19:16 2012
@@ -1,9 +1,10 @@
-# encoding: UTF-8
+# -*- coding: utf-8 -*-
from xmpp import simplexml
from exceptions import KeyError
+
def co2xml(map):
- """ Convenience recursive function for transforming ContentObjects
into XML.
+ """ Convenience recursive function for transforming ContentObjects
into XML.
The transformation is {x:y} --> <x>y</x> """
xml = ""
for key, value in map.items():
@@ -14,10 +15,11 @@
for i in value:
xml += "<%s>%s</%s>" % (key, i, key)
xml += "</%s>" % (key)
- elif value != None and value != "None":
+ elif value is not None and value != "None":
xml += "<%s>%s</%s>" % (key, value, key)
return xml
+
class ContentObject(dict):
"""
WARNING: copy.copy() does NOT work for this class :-?
@@ -30,17 +32,16 @@
#print "KEY: ", key, "VALUE: ", value
try:
if ":" in key:
- prefix,tag = key.rsplit(":")
+ prefix, tag = key.rsplit(":")
if prefix not in self.namespaces:
# The usual FIPA namespace
if prefix == "fipa":
self.addNamespace("
http://www.fipa.org/schemas/fipa-rdf0#", "fipa")
else:
- self.addNamespace("",prefix)
+ self.addNamespace("", prefix)
except:
pass
return dict.__setitem__(self, key, value)
-
def DEACTIVATED__setattr__(self, key, value):
"""
@@ -48,92 +49,90 @@
without worry.
"""
#print "KEY: ", key, "VALUE: ", value
- if not self.__dict__.has_key('_ContentObject__initialised'):
+ if '_ContentObject__initialised' not in self.__dict__.keys():
return dict.__setattr__(self, key, value)
- elif self.__dict__.has_key(key):
+ elif key in self.__dict__.keys():
dict.__setattr__(self, key, value)
else:
#self.__setitem__(key, value)
try:
if ":" in key:
- prefix,tag = key.rsplit(":")
+ prefix, tag = key.rsplit(":")
if prefix not in self.namespaces:
# The usual FIPA namespace
if prefix == "fipa":
self.addNamespace("
http://www.fipa.org/schemas/fipa-rdf0#", "fipa")
else:
- self.addNamespace("",prefix)
+ self.addNamespace("", prefix)
except:
pass
self.__setitem__(key, value)
-
def __getattr__(self, name):
#print "GETATTR:", name
try:
- if self.has_key(name):
+ if name in self.keys():
return self[name]
except:
pass
for ns in self.namespaces.values():
try:
- if self.has_key(ns+name):
- return self[ns+name]
+ if ns + name in self.keys():
+ return self[ns + name]
except:
pass
# Ethical dilemma: Should ContentObject return a None when trying
to
# access a key that does not exist or should it raise an Exception?
#raise KeyError
return None
-
+
def addNamespace(self, uri, abv):
if abv[-1] != ":":
abv = abv + ":"
self.namespaces[uri] = abv
return
-
+
def pprint(self, ind=0):
s = ""
- for k,v in self.items():
+ for k, v in self.items():
try:
- s = s + ('\t'*ind)+str(k)+":\n"+v.pprint(ind+1)
+ '\n'
+ s = s + ('\t' * ind) + str(k) + ":\n" +
v.pprint(ind + 1) + '\n'
except:
- s = s + ('\t'*ind)+str(k)+": " + str(v) + '\n'
+ s = s + ('\t' * ind) + str(k) + ": " + str(v)
+ '\n'
return s
-
+
def asRDFXML(self):
# Build rdf:RDF node
- root = simplexml.Node("rdf:RDF",
{"xmlns:rdf":"
http://www.w3.org/1999/02/22-rdf-syntax-ns#"})
+ root = simplexml.Node("rdf:RDF",
{"xmlns:rdf": "
http://www.w3.org/1999/02/22-rdf-syntax-ns#"})
nss = {}
- for k,v in self.namespaces.items():
- if v in ["xml:","rdf:"]:
+ for k, v in self.namespaces.items():
+ if v in ["xml:", "rdf:"]:
pass
- elif v != None and v != "None":
- nss["xmlns:"+v[:-1]] = k
+ elif v is not None and v != "None":
+ nss["xmlns:" + v[:-1]] = k
root.attrs.update(nss)
root.addData("#WILDCARD#")
- return str(root).replace("#WILDCARD#",co2xml(self))
-
+ return str(root).replace("#WILDCARD#", co2xml(self))
"""CAWEN DIOS!!!
def asSL0(self):
return toSL0(self)
def toSL0(self, data = None):
-
+
self.co = []
self.l = []
self.other = []
-
+
sl = ""
for key,value in data.items():
if "ContentObject" in str(type(value)):
self.co.append((key,value))
elif "list" in str(type(value)): self.l.append((key,value))
- else self.other.append((key,value))
+ else self.other.append((key,value))
+
-
@@ -153,7 +152,7 @@
return sl
"""
-
+
def __str__(self):
return co2xml(self)
#return self.asRDFXML()
@@ -171,10 +170,10 @@
except:
return ""
else:
- # Blank node
+ # Blank node
is_list = False
#Â Is it a list?
- if node.attrs.has_key("list"):
+ if "list" in node.attrs.keys():
# It IS a marked list
is_list = True
else:
@@ -186,18 +185,18 @@
if is_list:
s = []
for c in node.kids:
- s.append(Node2CO(c,nsdict))
+ s.append(Node2CO(c, nsdict))
else:
s = ContentObject()
for c in node.kids:
#print "KID ",
c.name," NS ",c.namespace
if c.namespace in nsdict.keys():
- key = nsdict[c.namespace]+
c.name
+ key = nsdict[c.namespace] +
c.name
else:
- key =
c.name
- s[key] = Node2CO(c,nsdict)
+ key =
c.name
+ s[key] = Node2CO(c, nsdict)
return s
-
+
def RDFXML2CO(rdfdata):
#print "Gonna parse: "+rdfdata
@@ -208,21 +207,21 @@
return co
-if __name__=="__main__":
+if __name__ == "__main__":
import urllib2
#f = urllib2.urlopen("
http://infomesh.net/2003/rdfparser/meta.rdf")
#f =
urllib2.urlopen("
http://tourism.gti-ia.dsic.upv.es/rdf/ComidasTascaRapida.rdf")
ex = """<rdf:RDF
xmlns:rdf="
http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:foaf="
http://xmlns.com/foaf/0.1/"
+ xmlns:foaf="
http://xmlns.com/foaf/0.1/"
xmlns:dc="
http://purl.org/dc/elements/1.1/">
<rdf:Description
rdf:about="
http://en.wikipedia.org/wiki/Tony_Benn">
<dc:title>Tony Benn</dc:title>
<dc:publisher>Wikipedia</dc:publisher>
<foaf:primaryTopic>
<foaf:Person>
- <foaf:name>Tony Benn</foaf:name>
+ <foaf:name>Tony Benn</foaf:name>
</foaf:Person>
</foaf:primaryTopic>
</rdf:Description>
@@ -243,7 +242,7 @@
sco["spade:uno"] = ContentObject()
sco["spade:uno"]["spade:dos"] = "COSA"
sco.uno["spade:tres"] = "OTRA"
-
+
#print str(sco)
print "ORIGINAL:"
print sco.pprint()
@@ -254,5 +253,5 @@
print "SEGUNDO:"
print sco2.pprint()
print sco2.asRDFXML()
-
+
#print sco2.asSL0()
=======================================
--- /trunk/spade/dblite.py Tue Jul 31 06:58:54 2012
+++ /trunk/spade/dblite.py Fri Nov 23 05:19:16 2012
@@ -1,11 +1,12 @@
+# -*- coding: utf-8 -*-
## {{{
http://code.activestate.com/recipes/496770/ (r4)
"""PyDbLite.py
-In-memory database management, with selection by list comprehension
+In-memory database management, with selection by list comprehension
or generator expression
Fields are untyped : they can store anything that can be pickled.
-Selected records are returned as dictionaries. Each record is
+Selected records are returned as dictionaries. Each record is
identified by a unique id and has a version number incremented
at every record update, to detect concurrent access
@@ -54,14 +55,15 @@
set([])
except NameError:
from sets import Set as set
-
+
+
class Index:
"""Class used for indexing a base on a field
The instance of Index is an attribute the Base instance"""
- def __init__(self,db,field):
- self.db = db # database object (instance of Base)
- self.field = field # field name
+ def __init__(self, db, field):
+ self.db = db # database object (instance of Base)
+ self.field = field # field name
def __iter__(self):
return iter(self.db.indices[self.field])
@@ -69,30 +71,31 @@
def keys(self):
return self.db.indices[self.field].keys()
- def __getitem__(self,key):
+ def __getitem__(self, key):
"""Lookup by key : return the list of records where
field value is equal to this key, or an empty list"""
- ids = self.db.indices[self.field].get(key,[])
- return [ self.db.records[_id] for _id in ids ]
+ ids = self.db.indices[self.field].get(key, [])
+ return [self.db.records[_id] for _id in ids]
+
class Base:
- def __init__(self,basename):
+ def __init__(self, basename):
self.name = basename
- def create(self,*fields,**kw):
+ def create(self, *fields, **kw):
"""Create a new base with specified field names
A keyword argument mode can be specified ; it is used if a file
with the base name already exists
- if mode = 'open' : open the existing base, ignore the fields
- if mode = 'override' : erase the existing base and create a
new one with the specified fields"""
- self.mode = mode = kw.get("mode",None)
+ self.mode = mode = kw.get("mode", None)
if os.path.exists(
self.name):
if not os.path.isfile(
self.name):
- raise IOError,"%s exists and is not a file" %
self.name
+ raise IOError("%s exists and is not a file" %
self.name)
elif mode is None:
- raise IOError,"Base %s already exists" %
self.name
+ raise IOError("Base %s already exists" %
self.name)
elif mode == "open":
return self.open()
elif mode == "override":
@@ -104,59 +107,59 @@
self.commit()
return self
- def create_index(self,*fields):
+ def create_index(self, *fields):
"""Create an index on the specified field names
-
+
An index on a field is a mapping between the values taken by the
field
- and the sorted list of the ids of the records whose field is equal
to
+ and the sorted list of the ids of the records whose field is equal
to
this value
-
- For each indexed field, an attribute of self is created, an
instance
+
+ For each indexed field, an attribute of self is created, an
instance
of the class Index (see above). Its name it the field name, with
the
prefix _ to avoid name conflicts
"""
reset = False
for f in fields:
if not f in self.fields:
- raise NameError,"%s is not a field name" %f
+ raise NameError("%s is not a field name" % f)
# initialize the indices
if self.mode == "open" and f in self.indices:
continue
reset = True
self.indices[f] = {}
- for _id,record in self.records.iteritems():
+ for _id, record in self.records.iteritems():
# use bisect to quickly insert the id in the list
- bisect.insort(self.indices[f].setdefault(record[f],[]),
- _id)
+ bisect.insort(self.indices[f].setdefault(record[f], []),
+ _id)
# create a new attribute of self, used to find the records
# by this index
- setattr(self,'_'+f,Index(self,f))
+ setattr(self, '_' + f, Index(self, f))
if reset:
self.commit()
def open(self):
"""Open an existing database and load its content into memory"""
- _in = open(
self.name) # don't specify binary mode !
+ _in = open(
self.name) # don't specify binary mode !
self.fields = cPickle.load(_in)
self.next_id = cPickle.load(_in)
self.records = cPickle.load(_in)
self.indices = cPickle.load(_in)
for f in self.indices.keys():
- setattr(self,'_'+f,Index(self,f))
+ setattr(self, '_' + f, Index(self, f))
_in.close()
self.mode = "open"
return self
def commit(self):
"""Write the database to a file"""
- out = open(
self.name,'wb')
- cPickle.dump(self.fields,out)
- cPickle.dump(self.next_id,out)
- cPickle.dump(self.records,out)
- cPickle.dump(self.indices,out)
+ out = open(
self.name, 'wb')
+ cPickle.dump(self.fields, out)
+ cPickle.dump(self.next_id, out)
+ cPickle.dump(self.records, out)
+ cPickle.dump(self.indices, out)
out.close()
- def insert(self,*args,**kw):
+ def insert(self, *args, **kw):
"""Insert a record in the database
Parameters can be positional or keyword arguments. If positional
they must be in the same order as in the create() method
@@ -164,12 +167,12 @@
Returns the record identifier
"""
if args:
- kw = dict([(f,arg) for f,arg in zip(self.fields,args)])
+ kw = dict([(f, arg) for f, arg in zip(self.fields, args)])
# initialize all fields to None
- record = dict([(f,None) for f in self.fields])
+ record = dict([(f, None) for f in self.fields])
# set keys and values
- for (k,v) in kw.iteritems():
- record[k]=v
+ for (k, v) in kw.iteritems():
+ record[k] = v
# add the key __id__ : record identifier
record['__id__'] = self.next_id
# add the key __version__ : version number
@@ -178,45 +181,45 @@
self.records[self.next_id] = record
# update index
for ix in self.indices.keys():
- bisect.insort(self.indices[ix].setdefault(record[ix],[]),
- self.next_id)
+ bisect.insort(self.indices[ix].setdefault(record[ix], []),
+ self.next_id)
# increment the next __id__ to attribute
self.next_id += 1
return record['__id__']
- def delete(self,removed):
+ def delete(self, removed):
"""Remove a single record, or the records in an iterable
Before starting deletion, test if all records are in the base
and don't have twice the same __id__
Return the number of deleted items
"""
- if isinstance(removed,dict):
+ if isinstance(removed, dict):
# remove a single record
removed = [removed]
else:
# convert iterable into a list (to be able to sort it)
- removed = [ r for r in removed ]
+ removed = [r for r in removed]
if not removed:
return 0
- _ids = [ r['__id__'] for r in removed ]
+ _ids = [r['__id__'] for r in removed]
_ids.sort()
keys = set(self.records.keys())
# check if the records are in the base
if not set(_ids).issubset(keys):
missing = list(set(_ids).difference(keys))
- raise IndexError,'Delete aborted. Records with these ids' \
- ' not found in the base : %s' %str(missing)
+ raise IndexError('Delete aborted. Records with these ids'
+ ' not found in the base : %s' % str(missing))
# raise exception if duplicate ids
- for i in range(len(_ids)-1):
- if _ids[i] == _ids[i+1]:
- raise IndexError,"Delete aborted. Duplicate
id : %s" %_ids[i]
+ for i in range(len(_ids) - 1):
+ if _ids[i] == _ids[i + 1]:
+ raise IndexError("Delete aborted. Duplicate id : %s" %
_ids[i])
deleted = len(removed)
while removed:
r = removed.pop()
_id = r['__id__']
# remove id from indices
for indx in self.indices.keys():
- pos = bisect.bisect(self.indices[indx][r[indx]],_id)-1
+ pos = bisect.bisect(self.indices[indx][r[indx]], _id) - 1
del self.indices[indx][r[indx]][pos]
if not self.indices[indx][r[indx]]:
del self.indices[indx][r[indx]]
@@ -224,7 +227,7 @@
del self.records[_id]
return deleted
- def update(self,record,**kw):
+ def update(self, record, **kw):
"""Update the record with new keys and values and update indices"""
# update indices
_id = record["__id__"]
@@ -233,28 +236,28 @@
if record[indx] == kw[indx]:
continue
# remove id for the old value
- old_pos =
bisect.bisect(self.indices[indx][record[indx]],_id)-1
+ old_pos = bisect.bisect(self.indices[indx][record[indx]],
_id) - 1
del self.indices[indx][record[indx]][old_pos]
if not self.indices[indx][record[indx]]:
del self.indices[indx][record[indx]]
# insert new value
-
bisect.insort(self.indices[indx].setdefault(kw[indx],[]),_id)
+ bisect.insort(self.indices[indx].setdefault(kw[indx], []),
_id)
# update record values
record.update(kw)
# increment version number
record["__version__"] += 1
- def add_field(self,field,default=None):
- if field in self.fields + ["__id__","__version__"]:
- raise ValueError,"Field %s already defined" %field
+ def add_field(self, field, default=None):
+ if field in self.fields + ["__id__", "__version__"]:
+ raise ValueError("Field %s already defined" % field)
for r in self:
r[field] = default
self.fields.append(field)
self.commit()
-
- def drop_field(self,field):
- if field in ["__id__","__version__"]:
- raise ValueError,"Can't delete field %s" %field
+
+ def drop_field(self, field):
+ if field in ["__id__", "__version__"]:
+ raise ValueError("Can't delete field %s" % field)
self.fields.remove(field)
for r in self:
del r[field]
@@ -262,30 +265,31 @@
del self.indices[field]
self.commit()
- def __call__(self,**kw):
+ def __call__(self, **kw):
"""Selection by field values
db(key=value) returns the list of records where r[key] = value"""
for key in kw:
if not key in self.fields:
- raise ValueError,"Field %s not in the database" %key
+ raise ValueError("Field %s not in the database" % key)
+
def sel_func(r):
for key in kw:
if not r[key] == kw[key]:
return False
return True
- return [ r for r in self if sel_func(r) ]
-
- def __getitem__(self,record_id):
+ return [r for r in self if sel_func(r)]
+
+ def __getitem__(self, record_id):
"""Direct access by record id"""
return self.records[record_id]
-
+
def __len__(self):
return len(self.records)
- def __delitem__(self,record_id):
+ def __delitem__(self, record_id):
"""Delete by record id"""
self.delete(self[record_id])
-
+
def __iter__(self):
"""Iteration on the records"""
return self.records.itervalues()
@@ -294,54 +298,53 @@
# test on a 1000 record base
import random
import datetime
- names = ['pierre','claire','simon','camille','jean',
- 'florence','marie-anne']
+ names =
['pierre', 'claire', 'simon', 'camille', 'jean', 'florence', 'marie-anne']
db = Base('PyDbLite_test')
- db.create('name','age','size','birth',mode="override")
+ db.create('name', 'age', 'size', 'birth', mode="override")
for i in range(1000):
db.insert(name=unicode(random.choice(names)),
- age=random.randint(7,47),size=random.uniform(1.10,1.95),
- birth=datetime.date(1990,10,10))
+ age=random.randint(7, 47), size=random.uniform(1.10,
1.95),
+ birth=datetime.date(1990, 10, 10))
db.create_index('age')
db.commit()
- print 'Record #20 :',db[20]
+ print 'Record #20 :', db[20]
print '\nRecords with age=30 :'
for rec in db._age[30]:
- print '%-10s | %2s
| %s' %(rec['name'],rec['age'],round(rec['size'],2))
+ print '%-10s | %2s | %s' % (rec['name'], rec['age'],
round(rec['size'], 2))
print "\nSame with __call__"
for rec in db(age=30):
- print '%-10s | %2s
| %s' %(rec['name'],rec['age'],round(rec['size'],2))
+ print '%-10s | %2s | %s' % (rec['name'], rec['age'],
round(rec['size'], 2))
print db._age[30] == db(age=30)
- db.insert(name=unicode(random.choice(names))) # missing fields
+ db.insert(name=unicode(random.choice(names))) # missing fields
print '\nNumber of records with 30 <= age < 33 :',
print sum([1 for r in db if 33 > r['age'] >= 30])
-
+
print db.delete([])
- d = db.delete([r for r in db if 32> r['age'] >= 30 and
r['name']==u'pierre'])
- print "\nDeleting %s records with name == 'pierre' and 30 <= age <
32" %d
+ d = db.delete([r for r in db if 32 > r['age'] >= 30 and r['name'] ==
u'pierre'])
+ print "\nDeleting %s records with name == 'pierre' and 30 <= age <
32" % d
print '\nAfter deleting records '
for rec in db._age[30]:
- print '%-10s | %2s
| %s' %(rec['name'],rec['age'],round(rec['size'],2))
- print '\n',sum([1 for r in db]),'records in the database'
+ print '%-10s | %2s | %s' % (rec['name'], rec['age'],
round(rec['size'], 2))
+ print '\n', sum([1 for r in db]), 'records in the database'
print '\nMake pierre uppercase for age > 27'
- for record in ([r for r in db if r['name']=='pierre' and r['age']
>27]) :
- db.update(record,name=u"Pierre")
- print len([r for r in db if r['name']==u'Pierre']),'Pierre'
- print len([r for r in db if r['name']==u'pierre']),'pierre'
- print len([r for r in db if r['name'] in
[u'pierre',u'Pierre']]),'p/Pierre'
- print 'is unicode :',isinstance(db[20]['name'],unicode)
+ for record in ([r for r in db if r['name'] == 'pierre' and r['age'] >
27]):
+ db.update(record, name=u"Pierre")
+ print len([r for r in db if r['name'] == u'Pierre']), 'Pierre'
+ print len([r for r in db if r['name'] == u'pierre']), 'pierre'
+ print len([r for r in db if r['name'] in [u'pierre',
u'Pierre']]), 'p/Pierre'
+ print 'is unicode :', isinstance(db[20]['name'], unicode)
db.commit()
db.open()
print '\nSame operation after commit + open'
- print len([r for r in db if r['name']==u'Pierre']),'Pierre'
- print len([r for r in db if r['name']==u'pierre']),'pierre'
- print len([r for r in db if r['name'] in
[u'pierre',u'Pierre']]),'p/Pierre'
- print 'is unicode :',isinstance(db[20]['name'],unicode)
-
+ print len([r for r in db if r['name'] == u'Pierre']), 'Pierre'
+ print len([r for r in db if r['name'] == u'pierre']), 'pierre'
+ print len([r for r in db if r['name'] in [u'pierre',
u'Pierre']]), 'p/Pierre'
+ print 'is unicode :', isinstance(db[20]['name'], unicode)
+
print "\nDeleting record #20"
del db[20]
if not 20 in db:
@@ -350,11 +353,11 @@
print db[21]
db.drop_field('name')
print db[21]
- db.add_field('adate',datetime.date.today())
+ db.add_field('adate', datetime.date.today())
print db[21]
-
+
k = db._age.keys()[0]
- print "key",k
+ print "key", k
print k in db._age
db.delete(db._age[k])
print db._age[k]
=======================================
--- /trunk/spade/fipa.py Wed Jul 14 06:10:54 2010
+++ /trunk/spade/fipa.py Fri Nov 23 05:19:16 2012
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
import Behaviour
import SL0Parser
import DF
@@ -15,13 +16,13 @@
self.p = SL0Parser.SL0Parser()
def _process(self):
- self._msg.addReceiver( self.myAgent.getAMS() )
+ self._msg.addReceiver(self.myAgent.getAMS())
self._msg.setPerformative('request')
self._msg.setLanguage('rdf')
self._msg.setProtocol('fipa-request')
self._msg.setOntology('FIPA-Agent-Management')
- content =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ content =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
content["fipa:action"] = ContentObject()
content["fipa:action"]["fipa:actor"] =
self.myAgent.getAID().asContentObject()
content["fipa:action"]["fipa:act"] = "search"
@@ -29,22 +30,22 @@
self._msg.setContentObject(content)
self.myAgent.send(self._msg)
- msg = self._receive(True,10)
- if msg == None or str(msg.getPerformative()) != 'agree':
+ msg = self._receive(True, 10)
+ if msg is None or str(msg.getPerformative()) != 'agree':
try:
aadname = str(self.AAD.getAID().getName())
except:
aadname = "<unknown>"
- self.myAgent.DEBUG("There was an error searching the Agent " +
aadname + "(not agree)","warn")
+ self.myAgent.DEBUG("There was an error searching the Agent " +
aadname + "(not agree)", "warn")
self.finished = True
return None
- msg = self._receive(True,20)
- if msg == None or msg.getPerformative() != 'inform':
+ msg = self._receive(True, 20)
+ if msg is None or msg.getPerformative() != 'inform':
try:
aadname = str(self.AAD.getAID().getName())
except:
aadname = "<unknown>"
- self.myAgent.DEBUG("There was an error searching the Agent " +
aadname + "(not inform)","warn")
+ self.myAgent.DEBUG("There was an error searching the Agent " +
aadname + "(not inform)", "warn")
self.finished = True
return None
else:
@@ -55,13 +56,12 @@
for i in co["fipa:result"]:
self.result.append(AmsAgentDescription(co=i))
- except Exception,e:
- self.DEBUG("Parse Exception: "+str(e),"err")
+ except Exception, e:
+ self.DEBUG("Parse Exception: " + str(e), "err")
self.result = []
return None
self.finished = True
-
class ModifyAgentBehaviour(Behaviour.OneShotBehaviour):
@@ -74,13 +74,13 @@
def _process(self):
p = SL0Parser.SL0Parser()
- self._msg.addReceiver( self.myAgent.getAMS() )
+ self._msg.addReceiver(self.myAgent.getAMS())
self._msg.setPerformative('request')
self._msg.setLanguage('rdf')
self._msg.setProtocol('fipa-request')
self._msg.setOntology('FIPA-Agent-Management')
- content =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ content =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
content["fipa:action"] = ContentObject()
content["fipa:action"]["fipa:actor"] =
self.myAgent.getAID().asContentObject()
content["fipa:action"]["fipa:act"] = "modify"
@@ -89,14 +89,14 @@
self.myAgent.send(self._msg)
- msg = self._receive(True,20)
- if msg == None or msg.getPerformative() != 'agree':
- self.myAgent.DEBUG("There was an error modifying the requested
Agent (not agree)","warn")
+ msg = self._receive(True, 20)
+ if msg is None or msg.getPerformative() != 'agree':
+ self.myAgent.DEBUG("There was an error modifying the requested
Agent (not agree)", "warn")
self.result = False
return False
- msg = self._receive(True,20)
- if msg == None or msg.getPerformative() != 'inform':
- self.myAgent.DEBUG("There was an error modifying the requested
Agent (not inform)","warn")
+ msg = self._receive(True, 20)
+ if msg is None or msg.getPerformative() != 'inform':
+ self.myAgent.DEBUG("There was an error modifying the requested
Agent (not inform)", "warn")
self.myAgent.DEBUG(str(msg.getContent()))
self.result = False
return False
@@ -113,13 +113,13 @@
def _process(self):
msg = self._msg
- msg.addReceiver( self.myAgent.getAMS() )
+ msg.addReceiver(self.myAgent.getAMS())
msg.setPerformative('request')
msg.setLanguage('rdf')
msg.setProtocol('fipa-request')
msg.setOntology('FIPA-Agent-Management')
- content =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ content =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
content["fipa:action"] = ContentObject()
content["fipa:action"]["fipa:actor"] =
self.myAgent.getAID().asContentObject()
content["fipa:action"]["fipa:act"] = "get-description"
@@ -127,20 +127,20 @@
self.myAgent.send(msg)
- msg = self._receive(True,20)
- if msg == None or msg.getPerformative() != 'agree':
- self.myAgent.DEBUG("There was an error getting platform
info","warn")
+ msg = self._receive(True, 20)
+ if msg is None or msg.getPerformative() != 'agree':
+ self.myAgent.DEBUG("There was an error getting platform info
(not-agree)", "warn")
return False
- msg = self._receive(True,20)
- if msg == None or msg.getPerformative() != 'inform':
- self.myAgent.DEBUG("There was an error getting platform
info","warn")
+ msg = self._receive(True, 20)
+ if msg is None or msg.getPerformative() != 'inform':
+ self.myAgent.DEBUG("There was an error getting platform info
(not-inform)", "warn")
return False
self.result = msg.getContentObject()
class registerServiceBehaviour(Behaviour.OneShotBehaviour):
- def __init__(self, msg, DAD, otherdf = None):
+ def __init__(self, msg, DAD, otherdf=None):
Behaviour.OneShotBehaviour.__init__(self)
self._msg = msg
self.DAD = DAD
@@ -151,10 +151,10 @@
def _process(self):
force_sl0 = False
if self.otherdf and isinstance(self.otherdf, AID.aid):
- self._msg.addReceiver( self.otherdf )
+ self._msg.addReceiver(self.otherdf)
force_sl0 = True
else:
- self._msg.addReceiver( self.myAgent.getDF() )
+ self._msg.addReceiver(self.myAgent.getDF())
self._msg.setPerformative('request')
self._msg.setProtocol('fipa-request')
self._msg.setOntology('FIPA-Agent-Management')
@@ -164,12 +164,12 @@
content = "((action "
content += str(self.myAgent.getAID())
content += "(register " + str(self.DAD) + ")"
- content +=" ))"
+ content += " ))"
self._msg.setContent(content)
else:
self._msg.setLanguage('rdf')
- content =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ content =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
content["fipa:action"] = ContentObject()
content["fipa:action"]["fipa:actor"] =
self.myAgent.getAID().asContentObject()
content["fipa:action"]["fipa:act"] = "register"
@@ -178,25 +178,26 @@
self.myAgent.send(self._msg)
- msg = self._receive(True,20)
- if msg == None or msg.getPerformative() not in ['agree', 'inform']:
- self.myAgent.DEBUG("There was an error registering the
service " +str(self.DAD)+ "(not agree)","warn")
+ msg = self._receive(True, 20)
+ if msg is None or msg.getPerformative() not in ['agree', 'inform']:
+ self.myAgent.DEBUG("There was an error registering the
service " + str(self.DAD) + "(not agree)", "warn")
self.result = False
return False
- elif msg == None or msg.getPerformative() == 'agree':
- msg = self._receive(True,20)
- if msg == None or msg.getPerformative() != 'inform':
+ elif msg is None or msg.getPerformative() == 'agree':
+ msg = self._receive(True, 20)
+ if msg is None or msg.getPerformative() != 'inform':
if not msg:
- self.DEBUG("There was an error registering the
Service " +str(self.DAD)+ ". (timeout)","warn")
+ self.DEBUG("There was an error registering the
Service " + str(self.DAD) + ". (timeout)", "warn")
elif msg.getPerformative() == 'failure':
- self.DEBUG("There was an error registering the
Service " +str(self.DAD)+ ". Failure: " +
msg.getContentObject()['fipa:error'],"warn")
+ self.DEBUG("There was an error registering the
Service " + str(self.DAD) + ". Failure: " +
msg.getContentObject()['fipa:error'], "warn")
else:
- self.DEBUG("There was an error registering the
Service " +str(self.DAD)+ ". (not inform)","warn")
+ self.DEBUG("There was an error registering the
Service " + str(self.DAD) + ". (not inform)", "warn")
self.result = False
return False
self.result = True
+
class deregisterServiceBehaviour(Behaviour.OneShotBehaviour):
def __init__(self, msg, DAD, otherdf=None):
Behaviour.OneShotBehaviour.__init__(self)
@@ -209,25 +210,25 @@
def _process(self):
force_sl0 = False
if self.otherdf and isinstance(self.otherdf, AID.aid):
- self._msg.addReceiver( self.otherdf )
+ self._msg.addReceiver(self.otherdf)
force_sl0 = True
else:
- self._msg.addReceiver( self.myAgent.getDF() )
+ self._msg.addReceiver(self.myAgent.getDF())
self._msg.setPerformative('request')
self._msg.setProtocol('fipa-request')
self._msg.setOntology('FIPA-Agent-Management')
if force_sl0:
- self._msg.setLanguage('fipa-sl0')
- content = "((action "
- content += str(self.myAgent.getAID())
- content += "(deregister " + str(self.DAD) + ")"
- content +=" ))"
- self._msg.setContent(content)
+ self._msg.setLanguage('fipa-sl0')
+ content = "((action "
+ content += str(self.myAgent.getAID())
+ content += "(deregister " + str(self.DAD) + ")"
+ content += " ))"
+ self._msg.setContent(content)
else:
self._msg.setLanguage('rdf')
- content =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ content =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
content["fipa:action"] = ContentObject()
content["fipa:action"]["fipa:actor"] =
self.myAgent.getAID().asContentObject()
content["fipa:action"]["fipa:act"] = "deregister"
@@ -236,25 +237,26 @@
self.myAgent.send(self._msg)
- msg = self._receive(True,20)
- if msg == None or msg.getPerformative() not in ['agree', 'inform']:
- self.myAgent.DEBUG("There was an error deregistering the
Service "+str(self.DAD) +". (not-agree)","warn")
+ msg = self._receive(True, 20)
+ if msg is None or msg.getPerformative() not in ['agree', 'inform']:
+ self.myAgent.DEBUG("There was an error deregistering the
Service " + str(self.DAD) + ". (not-agree)", "warn")
self.result = False
return
- elif msg == None or msg.getPerformative() == 'agree':
- msg = self._receive(True,20)
- if msg == None or msg.getPerformative() != 'inform':
+ elif msg is None or msg.getPerformative() == 'agree':
+ msg = self._receive(True, 20)
+ if msg is None or msg.getPerformative() != 'inform':
if not msg:
- self.DEBUG("There was an error deregistering the
Service "+str(self.DAD)+". (timeout)","warn")
+ self.DEBUG("There was an error deregistering the
Service " + str(self.DAD) + ". (timeout)", "warn")
elif msg.getPerformative() == 'failure':
- self.DEBUG("There was an error deregistering the
Service "+str(self.DAD)+". failure:" +
msg.getContentObject()['fipa:error'],"warn")
+ self.DEBUG("There was an error deregistering the
Service " + str(self.DAD) + ". failure:" +
msg.getContentObject()['fipa:error'], "warn")
else:
- self.DEBUG("There was an error deregistering the
Service "+str(self.DAD)+". (not inform)","warn")
+ self.DEBUG("There was an error deregistering the
Service " + str(self.DAD) + ". (not inform)", "warn")
self.result = False
return
self.result = True
+
class searchServiceBehaviour(Behaviour.OneShotBehaviour):
def __init__(self, msg, DAD):
@@ -266,7 +268,7 @@
def _process(self):
try:
- self._msg.addReceiver( self.myAgent.getDF() )
+ self._msg.addReceiver(self.myAgent.getDF())
self._msg.setPerformative('request')
self._msg.setLanguage('rdf')
self._msg.setProtocol('fipa-request')
@@ -283,34 +285,35 @@
self.myAgent.send(self._msg)
- msg = self._receive(True,20)
- if msg == None:
- self.DEBUG("There was an error searching the Service
(timeout on agree)","warn")
+ msg = self._receive(True, 20)
+ if msg is None:
+ self.DEBUG("There was an error searching the Service
(timeout on agree)", "warn")
return
elif msg.getPerformative() not in ['agree', 'inform']:
- self.DEBUG("There was an error searching the Service (not
agree) Failure: "+str(msg.getContentObject()["fipa:error"]),"warn")
+ self.DEBUG("There was an error searching the Service (not
agree) Failure: " + str(msg.getContentObject()["fipa:error"]), "warn")
return
elif msg.getPerformative() == 'agree':
msg = self._receive(True, 10)
- if msg == None:
- self.DEBUG("There was an error searching the Service
(timeout on inform)","warn")
+ if msg is None:
+ self.DEBUG("There was an error searching the Service
(timeout on inform)", "warn")
return
elif msg.getPerformative() != 'inform':
- self.DEBUG("There was an error searching the Service
(not inform) " + str(msg.getContentObject()['fipa:error']),"warn")
+ self.DEBUG("There was an error searching the Service
(not inform) " + str(msg.getContentObject()['fipa:error']), "warn")
return
content = msg.getContentObject()
self.result = []
for dfd in content.result:
- d = DF.DfAgentDescription(co = dfd)
+ d = DF.DfAgentDescription(co=dfd)
self.result.append(d)
except Exception, e:
- self.DEBUG("Exception searching service: "+str(e),"err")
+ self.DEBUG("Exception searching service: " + str(e), "err")
return
return
+
class modifyServiceBehaviour(Behaviour.OneShotBehaviour):
def __init__(self, msg, DAD):
Behaviour.OneShotBehaviour.__init__(self)
@@ -319,13 +322,13 @@
self.result = None
def _process(self):
- self._msg.addReceiver( self.myAgent.getDF() )
+ self._msg.addReceiver(self.myAgent.getDF())
self._msg.setPerformative('request')
self._msg.setLanguage('rdf')
self._msg.setProtocol('fipa-request')
self._msg.setOntology('FIPA-Agent-Management')
- content =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#":"fipa:"})
+ content =
ContentObject(namespaces={"
http://www.fipa.org/schemas/fipa-rdf0#": "fipa:"})
content["fipa:action"] = ContentObject()
content["fipa:action"]["fipa:actor"] =
self.myAgent.getAID().asContentObject()
content["fipa:action"]["fipa:act"] = "modify"
@@ -334,15 +337,16 @@
self.myAgent.send(self._msg)
- msg = self._receive(True,20)
- if msg == None or msg.getPerformative() != 'agree':
- self.DEBUG("There was an error modifying the Service. (not
agree) ","warn")
- if msg: self.DEBUG(msg.getContentObject()['fipa:error'],"warn")
- self.result=False
+ msg = self._receive(True, 20)
+ if msg is None or msg.getPerformative() != 'agree':
+ self.DEBUG("There was an error modifying the Service. (not
agree) ", "warn")
+ if msg:
+ self.DEBUG(msg.getContentObject()['fipa:error'], "warn")
+ self.result = False
return
- msg = self._receive(True,20)
- if msg == None or msg.getPerformative() != 'inform':
- self.DEBUG( "There was an error modifying the Service. (not
inform) " + str(msg.getContentObject()['fipa:error']),"warn")
+ msg = self._receive(True, 20)
+ if msg is None or msg.getPerformative() != 'inform':
+ self.DEBUG("There was an error modifying the Service. (not
inform) " + str(msg.getContentObject()['fipa:error']), "warn")
self.result = False
return
self.result = True
=======================================
--- /trunk/spade/kb.py Tue Jul 31 06:58:54 2012
+++ /trunk/spade/kb.py Fri Nov 23 05:19:16 2012
@@ -1,21 +1,30 @@
+# -*- coding: utf-8 -*-
from logic import FolKB, fol_bc_ask, expr, is_definite_clause, variables
import random
import string
import types
-class KBNameNotString(Exception): pass
-class KBValueNotKnown(Exception): pass
+
+class KBNameNotString(Exception):
+ pass
+
+
+class KBValueNotKnown(Exception):
+ pass
+
class KBConfigurationFailed(Exception):
def __init__(self, msg=""):
self.msg = msg
+
def __str__(self):
return repr(self.msg)
+
class SpadeKB(FolKB):
def tell(self, sentence):
- if issubclass(sentence.__class__,str):
+ if issubclass(sentence.__class__, str):
sentence = expr(sentence)
if is_definite_clause(sentence):
self.clauses.append(sentence)
@@ -23,7 +32,7 @@
raise Exception("Not a definite clause: %s" % sentence)
def retract(self, sentence):
- if issubclass(sentence.__class__,str):
+ if issubclass(sentence.__class__, str):
sentence = expr(sentence)
self.clauses.remove(sentence)
@@ -35,87 +44,89 @@
for a in ans:
res.append(dict([(x, v) for (x, v) in a.items() if x in vars]))
res.sort(key=str)
-
- if res==[]: return False
+
+ if res == []:
+ return False
for r in res:
- if r!={}:
+ if r != {}:
return res
- return True #res is a list of empty dicts
+ return True # res is a list of empty dicts
- def _encode(self, key,value):
+ def _encode(self, key, value):
key = key.capitalize()
if issubclass(value.__class__, str):
- self.tell("Var("+key+","+value.capitalize()+",Str)")
+ self.tell("Var(" + key + "," + value.capitalize() + ",Str)")
- elif issubclass(value.__class__,int):
- self.tell("Var("+key+","+str(value)+",Int)")
+ elif issubclass(value.__class__, int):
+ self.tell("Var(" + key + "," + str(value) + ",Int)")
- elif issubclass(value.__class__,float):
- self.tell("Var("+key+","+str(value) + ",Float)")
+ elif issubclass(value.__class__, float):
+ self.tell("Var(" + key + "," + str(value) + ",Float)")
- elif issubclass(value.__class__,list):
- listID
= ''.join(random.choice(string.ascii_uppercase+string.ascii_lowercase) for
x in range(8))
- listID = listID.capitalize()
#listID.replace(listID[0],listID[0].lower(),1)
+ elif issubclass(value.__class__, list):
+ listID = ''.join(random.choice(string.ascii_uppercase +
string.ascii_lowercase) for x in range(8))
+ listID = listID.capitalize() #
listID.replace(listID[0],listID[0].lower(),1)
for elem in value:
self._encode(listID, elem)
- self.tell("Var("+ key + ","+ listID +",List)")
+ self.tell("Var(" + key + "," + listID + ",List)")
- elif issubclass(value.__class__,dict):
- dictID
= ''.join(random.choice(string.ascii_uppercase+string.ascii_lowercase) for
x in range(8))
- dictID = dictID.capitalize()
#listID.replace(listID[0],listID[0].lower(),1)
- for k,v in value.items():
- elemID
= ''.join(random.choice(string.ascii_uppercase+string.ascii_lowercase) for
x in range(8))
- elemID = elemID.capitalize()
#elemID.replace(elemID[0],elemID[0].lower(),1)
- self._encode(elemID+"Key",k)
- self._encode(elemID+"Value",v)
- self.tell("Pair("+dictID+","+elemID+")")
- self.tell("Var("+key+","+dictID+",Dict)")
+ elif issubclass(value.__class__, dict):
+ dictID = ''.join(random.choice(string.ascii_uppercase +
string.ascii_lowercase) for x in range(8))
+ dictID = dictID.capitalize() #
listID.replace(listID[0],listID[0].lower(),1)
+ for k, v in value.items():
+ elemID = ''.join(random.choice(string.ascii_uppercase +
string.ascii_lowercase) for x in range(8))
+ elemID = elemID.capitalize() #
elemID.replace(elemID[0],elemID[0].lower(),1)
+ self._encode(elemID + "Key", k)
+ self._encode(elemID + "Value", v)
+ self.tell("Pair(" + dictID + "," + elemID + ")")
+ self.tell("Var(" + key + "," + dictID + ",Dict)")
else:
raise KBValueNotKnown
def _decode(self, key):
gen = self._gen_decode(key)
- try:
+ try:
return gen.next()
- except StopIteration:
+ except StopIteration:
return None
def _gen_decode(self, key):
key = key.capitalize()
- results = self.ask("Var("+key+", value, type)")
- if type(results)==types.BooleanType:
+ results = self.ask("Var(" + key + ", value, type)")
+ if isinstance(results, types.BooleanType):
yield None
- for res in results:
+ for res in results:
value = str(res[expr("value")])
- typ = str(res[expr("type")])
+ typ = str(res[expr("type")])
- if typ == "Int": yield int(value)
- elif typ == "Str": yield str(value).lower()
- elif typ == "Float": yield float(value)
+ if typ == "Int":
+ yield int(value)
+ elif typ == "Str":
+ yield str(value).lower()
+ elif typ == "Float":
+ yield float(value)
elif typ == "List":
l = []
listID = str(value)
gen = self._gen_decode(listID)
- hasElements=True
+ hasElements = True
while hasElements:
try:
l.append(gen.next())
except:
- hasElements=False
+ hasElements = False
yield l
elif typ == "Dict":
dictID = str(value)
d = {}
- for i in self.ask("Pair("+dictID+", elemid)"):
+ for i in self.ask("Pair(" + dictID + ", elemid)"):
elemID = str(i[expr("elemid")])
- newkey = self._gen_decode(elemID+"Key").next()
- newvalue = self._gen_decode(elemID+"Value").next()
+ newkey = self._gen_decode(elemID + "Key").next()
+ newvalue = self._gen_decode(elemID + "Value").next()
d[newkey] = newvalue
- yield d
-
+ yield d
-
class KB:
@@ -130,29 +141,35 @@
try:
if typ not in
["ECLiPSe", "Flora2", "SPARQL", "SWI", "XSB", "Spade"]:
raise KBConfigurationFailed(typ + " is not a valid KB.")
- if typ=="Spade":
+ if typ == "Spade":
self.kb = SpadeKB()
return
- elif typ=="SPARQL": import SPARQLKB
- elif typ=="XSB": import XSBKB
- elif typ=="Flora2": import Flora2KB
- elif typ=="SWI": import SWIKB
- elif typ=="ECLiPSe":import ECLiPSeKB
- else: raise KBConfigurationFailed("Could not
import "+str(typ)+" KB.")
+ elif typ == "SPARQL":
+ import SPARQLKB
+ elif typ == "XSB":
+ import XSBKB
+ elif typ == "Flora2":
+ import Flora2KB
+ elif typ == "SWI":
+ import SWIKB
+ elif typ == "ECLiPSe":
+ import ECLiPSeKB
+ else:
+ raise KBConfigurationFailed("Could not import " + str(typ)
+ " KB.")
except KBConfigurationFailed as e:
#self.myAgent.DEBUG(str(e)+" Using Fol KB.", 'warn')
typ = "Spade"
self.type = typ
- typ+="KB"
+ typ += "KB"
- if typ=="SpadeKB":
+ if typ == "SpadeKB":
self.kb = SpadeKB()
- elif path!=None:
- self.kb = eval(typ+"."+typ+"("+str(sentence)+", '"+path+"')")
+ elif path is not None:
+ self.kb = eval(typ + "." + typ + "(" + str(sentence) + ", '" +
path + "')")
else:
- self.kb = eval(typ+"."+typ+"("+str(sentence)+")")
+ self.kb = eval(typ + "." + typ + "(" + str(sentence) + ")")
def tell(self, sentence):
return self.kb.tell(sentence)
@@ -167,7 +184,7 @@
if not issubclass(key.__class__, str):
raise KBNameNotString
- self.kb._encode(key,value)
+ self.kb._encode(key, value)
def get(self, key):
return self.kb._decode(key)
@@ -177,48 +194,46 @@
kb0 = KB()
- kb0.set("varname1",1234)
+ kb0.set("varname1", 1234)
a = kb0.get("varname1")
print a, a.__class__
- kb0.set("varname2","myString")
+ kb0.set("varname2", "myString")
a = kb0.get("varname2")
print a, a.__class__
- kb0.set("varname3",1.34)
+ kb0.set("varname3", 1.34)
a = kb0.get("varname3")
print a, a.__class__
-
- kb0.set("varname4",[5,6,7,8])
+ kb0.set("varname4", [5, 6, 7, 8])
a = kb0.get("varname4")
print a, a.__class__
- kb0.set("varname5",[5,6.23,"7",[8,9]])
+ kb0.set("varname5", [5, 6.23, "7", [8, 9]])
a = kb0.get("varname5")
print a, a.__class__
- kb0.set("varname6",{'a':123,'b':456,789:"c"})
+ kb0.set("varname6", {'a': 123, 'b': 456, 789: "c"})
a = kb0.get("varname6")
print a, a.__class__
- kb0.set("varname7",{'a':[123.25],'b':[4,5,6],789:{'a':1,'b':2}})
+ kb0.set("varname7", {'a': [123.25], 'b': [4, 5, 6], 789: {'a': 1, 'b':
2}})
a = kb0.get("varname7")
print a, a.__class__
try:
- kb0.set(123,"newvalue")
+ kb0.set(123, "newvalue")
except KBNameNotString:
print "Test KBNameNotString passed."
-
- class A: pass
+ class A:
+ pass
try:
kb0.set("i8", A())
except KBValueNotKnown:
print "Test KBValueNotKnown passed."
-
a = kb0.get("varname9")
print a, a.__class__
=======================================
--- /trunk/spade/logic.py Tue Jul 31 06:58:54 2012
+++ /trunk/spade/logic.py Fri Nov 23 05:19:16 2012
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""Representations and Inference for Logic (Chapters 7-10)
Covers both Propositional and First-Order Logic. First we have four
@@ -21,12 +22,13 @@
to_cnf Convert to conjunctive normal form
unify Do unification of two FOL sentences
- diff, simp Symbolic differentiation and simplification
+ diff, simp Symbolic differentiation and simplification
"""
from __future__ import generators
import re
+
def every(predicate, seq):
"""True if every element of seq satisfies predicate.
>>> every(callable, [min, max])
@@ -35,17 +37,21 @@
0
"""
for x in seq:
- if not predicate(x): return False
+ if not predicate(x):
+ return False
return True
+
def isnumber(x):
"Is x a number? We say it is if it has a __int__ method."
return hasattr(x, '__int__')
+
def issequence(x):
"Is x a sequence? We say it is if it has a __getitem__ method."
return hasattr(x, '__getitem__')
+
def num_or_str(x):
"""The argument is a string; convert to a number if possible, or strip
it.
>>> num_or_str('42')
@@ -53,46 +59,48 @@
>>> num_or_str(' 42x ')
'42x'
"""
- if isnumber(x): return x
+ if isnumber(x):
+ return x
try:
- return int(x)
+ return int(x)
except ValueError:
try:
- return float(x)
+ return float(x)
except ValueError:
return str(x).strip()
#______________________________________________________________________________
+
class KB:
"""A Knowledge base to which you can tell and ask sentences.
To create a KB, first subclass this class and implement
- tell, ask_generator, and retract. Why ask_generator instead of ask?
+ tell, ask_generator, and retract. Why ask_generator instead of ask?
The book is a bit vague on what ask means --
For a Propositional Logic KB, ask(P & Q) returns True or False, but
for an
FOL KB, something like ask(Brother(x, y)) might return many
substitutions
- such as {x: Cain, y: Abel}, {x: Abel, y: Cain}, {x: George, y: Jeb},
etc.
+ such as {x: Cain, y: Abel}, {x: Abel, y: Cain}, {x: George, y: Jeb},
etc.
So ask_generator generates these one at a time, and ask either returns
the
first one or returns False."""
def __init__(self, sentence=None):
abstract
- def tell(self, sentence):
+ def tell(self, sentence):
"Add the sentence to the KB"
abstract
def ask(self, query):
"""Ask returns a substitution that makes the query true, or
it returns False. It is implemented in terms of ask_generator."""
- if issubclass(query.__class__,str):
+ if issubclass(query.__class__, str):
query = expr(query)
- try:
+ try:
return self.ask_generator(query).next()
except StopIteration:
return False
- def ask_generator(self, query):
+ def ask_generator(self, query):
"Yield all the substitutions that make query true."
abstract
@@ -109,11 +117,11 @@
if sentence:
self.tell(sentence)
- def tell(self, sentence):
+ def tell(self, sentence):
"Add the sentence's clauses to the KB"
- self.clauses.extend(conjuncts(to_cnf(sentence)))
+ self.clauses.extend(conjuncts(to_cnf(sentence)))
- def ask_generator(self, query):
+ def ask_generator(self, query):
"Yield the empty substitution if KB implies query; else False"
if not tt_entails(Expr('&', *self.clauses), query):
return
@@ -126,7 +134,7 @@
self.clauses.remove(c)
#______________________________________________________________________________
-
+
#class KB_Agent(agents.Agent):
"""A generic logical knowledge-based agent. [Fig. 7.1]"""
"""def __init__(self, KB):
@@ -139,10 +147,10 @@
return action
self.program = program
- def make_percept_sentence(self, percept, t):
+ def make_percept_sentence(self, percept, t):
return(Expr("Percept")(percept, t))
- def make_action_query(self, t):
+ def make_action_query(self, t):
return(expr("ShouldDo(action, %d)" % t))
def make_action_sentence(self, action, t):
@@ -150,6 +158,7 @@
#______________________________________________________________________________
+
class Expr:
"""A symbolic mathematical expression. We use this class for logical
expressions, and for terms within logical expressions. In general, an
@@ -169,10 +178,10 @@
A symbol, representing a function term or FOL proposition
Exprs can be constructed with operator overloading: if x and y are
Exprs,
- then so are x + y and x & y, etc. Also, if F and x are Exprs, then so
is
- F(x); it works by overloading the __call__ method of the Expr F. Note
- that in the Expr that is created by F(x), the op is the str 'F', not
the
- Expr F. See
http://www.python.org/doc/current/ref/specialnames.html
+ then so are x + y and x & y, etc. Also, if F and x are Exprs, then so
is
+ F(x); it works by overloading the __call__ method of the Expr F. Note
+ that in the Expr that is created by F(x), the op is the str 'F', not
the
+ Expr F. See
http://www.python.org/doc/current/ref/specialnames.html
to learn more about operator overloading in Python.
WARNING: x == y and x != y are NOT Exprs. The reason is that we want
@@ -183,7 +192,7 @@
equivalence) and logical disequality (or XOR). You have 3 choices:
(1) Expr('<=>', x, y) and Expr('^', x, y)
Note that ^ is bitwose XOR in Python (and Java and C++)
- (2) expr('x <=> y') and expr('x =/= y').
+ (2) expr('x <=> y') and expr('x =/= y').
See the doc string for the function expr.
(3) (x % y) and (x ^ y).
It is very ugly to have (x % y) mean (x <=> y), but we need
@@ -200,7 +209,7 @@
"Op is a string or number; args are Exprs (or are coerced to
Exprs)."
assert isinstance(op, str) or (isnumber(op) and not args)
self.op = num_or_str(op)
- self.args = map(expr, args) ## Coerce args to Exprs
+ self.args = map(expr, args) # Coerce args to Exprs
def __call__(self, *args):
"""Self must be a symbol with no args, such as Expr('F'). Create
a new
@@ -210,19 +219,19 @@
def __repr__(self):
"Show something like 'P' or 'P(x, y)', or '~P' or '(P | Q | R)'"
- if len(self.args) == 0: # Constant or proposition with arity 0
+ if len(self.args) == 0: # Constant or proposition with arity 0
return str(self.op)
- elif is_symbol(self.op): # Functional or Propositional operator
+ elif is_symbol(self.op): # Functional or Propositional operator
return '%s(%s)' % (self.op, ', '.join(map(repr, self.args)))
- elif len(self.args) == 1: # Prefix operator
+ elif len(self.args) == 1: # Prefix operator
return self.op + repr(self.args[0])
- else: # Infix operator
- return '(%s)' % (' '+self.op+' ').join(map(repr, self.args))
+ else: # Infix operator
+ return '(%s)' % (' ' + self.op + ' ').join(map(repr,
self.args))
def __eq__(self, other):
"""x and y are equal iff their ops and args are equal."""
- return (other is self) or (isinstance(other, Expr)
- and self.op == other.op and self.args == other.args)
+ return (other is self) or (isinstance(other, Expr)
+ and self.op == other.op and self.args
== other.args)
def __hash__(self):
"Need a hash method so Exprs can live in dicts."
@@ -230,25 +239,59 @@
# See
http://www.python.org/doc/current/lib/module-operator.html
# Not implemented: not, abs, pos, concat, contains, *item, *slice
- def __lt__(self, other): return Expr('<', self, other)
- def __le__(self, other): return Expr('<=', self, other)
- def __ge__(self, other): return Expr('>=', self, other)
- def __gt__(self, other): return Expr('>', self, other)
- def __add__(self, other): return Expr('+', self, other)
- def __sub__(self, other): return Expr('-', self, other)
- def __and__(self, other): return Expr('&', self, other)
- def __div__(self, other): return Expr('/', self, other)
- def __truediv__(self, other):return Expr('/', self, other)
- def __invert__(self): return Expr('~', self)
- def __lshift__(self, other): return Expr('<<', self, other)
- def __rshift__(self, other): return Expr('>>', self, other)
- def __mul__(self, other): return Expr('*', self, other)
- def __neg__(self): return Expr('-', self)
- def __or__(self, other): return Expr('|', self, other)
- def __pow__(self, other): return Expr('**', self, other)
- def __xor__(self, other): return Expr('^', self, other)
- def __mod__(self, other): return Expr('<=>', self, other) ## (x %
y)
-
+ def __lt__(self, other):
+ return Expr('<', self, other)
+
+ def __le__(self, other):
+ return Expr('<=', self, other)
+
+ def __ge__(self, other):
+ return Expr('>=', self, other)
+
+ def __gt__(self, other):
+ return Expr('>', self, other)
+
+ def __add__(self, other):
+ return Expr('+', self, other)
+
+ def __sub__(self, other):
+ return Expr('-', self, other)
+
+ def __and__(self, other):
+ return Expr('&', self, other)
+
+ def __div__(self, other):
+ return Expr('/', self, other)
+
+ def __truediv__(self, other):
+ return Expr('/', self, other)
+
+ def __invert__(self):
+ return Expr('~', self)
+
+ def __lshift__(self, other):
+ return Expr('<<', self, other)
+
+ def __rshift__(self, other):
+ return Expr('>>', self, other)
+
+ def __mul__(self, other):
+ return Expr('*', self, other)
+
+ def __neg__(self):
+ return Expr('-', self)
+
+ def __or__(self, other):
+ return Expr('|', self, other)
+
+ def __pow__(self, other):
+ return Expr('**', self, other)
+
+ def __xor__(self, other):
+ return Expr('^', self, other)
+
+ def __mod__(self, other):
+ return Expr('<=>', self, other) # (x % y)
def expr(s):
@@ -266,29 +309,35 @@
>>> expr('P & Q | ~R(x, F(x))')
((P & Q) | ~R(x, F(x)))
"""
- if isinstance(s, Expr): return s
- if isnumber(s): return Expr(s)
+ if isinstance(s, Expr):
+ return s
+ if isnumber(s):
+ return Expr(s)
## Replace the alternative spellings of operators with canonical
spellings
s = s.replace('==>', '>>').replace('<==', '<<')
s = s.replace('<=>', '%').replace('=/=', '^')
## Replace a symbol or number, such as 'P' with 'Expr("P")'
s = re.sub(r'([a-zA-Z0-9_.]+)', r'Expr("\1")', s)
## Now eval the string. (A security hole; do not use with an
adversary.)
- return eval(s, {'Expr':Expr})
+ return eval(s, {'Expr': Expr})
+
def is_symbol(s):
"A string s is a symbol if it starts with an alphabetic char."
return isinstance(s, str) and s[0].isalpha()
+
def is_var_symbol(s):
"A logic variable symbol is an initial-lowercase string."
return is_symbol(s) and s[0].islower()
+
def is_prop_symbol(s):
"""A proposition logic symbol is an initial-uppercase string other than
TRUE or FALSE."""
return is_symbol(s) and s[0].isupper() and s != 'TRUE' and s != 'FALSE'
+
def is_positive(s):
"""s is an unnegated logical expression
>>> is_positive(expr('F(A, B)'))
@@ -298,6 +347,7 @@
"""
return s.op != '~'
+
def is_negative(s):
"""s is a negated logical expression
>>> is_negative(expr('F(A, B)'))
@@ -307,6 +357,7 @@
"""
return s.op == '~'
+
def is_literal(s):
"""s is a FOL literal
>>> is_literal(expr('~F(A, B)'))
@@ -318,6 +369,7 @@
"""
return is_symbol(s.op) or (s.op == '~' and is_literal(s.args[0]))
+
def literals(s):
"""returns the list of literals of logical expression s.
>>> literals(expr('F(A, B)'))
@@ -338,6 +390,7 @@
else:
return []
+
def variables(s):
"""returns the set of variables in logical expression s.
>>> ppset(variables(F(x, A, y)))
@@ -352,7 +405,8 @@
for lit in literals(s):
vars = vars.union(variables(lit))
return vars
-
+
+
def is_definite_clause(s):
"""returns True for exprs s of the form A & B & ... & C ==> D,
where all literals are positive. In clause form, this is
@@ -371,11 +425,12 @@
(op == '>>' and every(is_positive, literals(s))))
## Useful constant Exprs used in examples and code:
-TRUE, FALSE, ZERO, ONE, TWO = map(Expr, ['TRUE', 'FALSE', 0, 1, 2])
-A, B, C, F, G, P, Q, x, y, z = map(Expr, 'ABCFGPQxyz')
+TRUE, FALSE, ZERO, ONE, TWO = map(Expr, ['TRUE', 'FALSE', 0, 1, 2])
+A, B, C, F, G, P, Q, x, y, z = map(Expr, 'ABCFGPQxyz')
#______________________________________________________________________________
+
def tt_entails(kb, alpha):
"""Use truth tables to determine if KB entails sentence alpha. [Fig.
7.10]
>>> tt_entails(expr('P & Q'), expr('Q'))
@@ -383,17 +438,21 @@
"""
return tt_check_all(kb, alpha, prop_symbols(kb & alpha), {})
+
def tt_check_all(kb, alpha, symbols, model):
"Auxiliary routine to implement tt_entails."
if not symbols:
- if pl_true(kb, model): return pl_true(alpha, model)
- else: return True
- assert result != None
+ if pl_true(kb, model):
+ return pl_true(alpha, model)
+ else:
+ return True
+ assert result is not None
else:
P, rest = symbols[0], symbols[1:]
return (tt_check_all(kb, alpha, rest, extend(model, P, True)) and
tt_check_all(kb, alpha, rest, extend(model, P, False)))
+
def prop_symbols(x):
"Return a list of all propositional symbols in x."
if not isinstance(x, Expr):
@@ -407,6 +466,7 @@
s.add(symbol)
return list(s)
+
def tt_true(alpha):
"""Is the sentence alpha a tautology? (alpha will be coerced to an
expr.)
>>> tt_true(expr("(P >> Q) <=> (~P | Q)"))
@@ -414,6 +474,7 @@
"""
return tt_entails(TRUE, expr(alpha))
+
def pl_true(exp, model={}):
"""Return True if the propositional logic expression is true in the
model,
and False if it is false. If the model does not specify the value for
@@ -428,21 +489,27 @@
return model.get(exp)
elif op == '~':
p = pl_true(args[0], model)
- if p == None: return None
- else: return not p
+ if p is None:
+ return None
+ else:
+ return not p
elif op == '|':
result = False
for arg in args:
p = pl_true(arg, model)
- if p == True: return True
- if p == None: result = None
+ if p is True:
+ return True
+ if p is None:
+ result = None
return result
elif op == '&':
result = True
for arg in args:
p = pl_true(arg, model)
- if p == False: return False
- if p == None: result = None
+ if p is False:
+ return False
+ if p is None:
+ result = None
return result
p, q = args
if op == '>>':
@@ -450,20 +517,23 @@
elif op == '<<':
return pl_true(p | ~q, model)
pt = pl_true(p, model)
- if pt == None: return None
+ if pt is None:
+ return None
qt = pl_true(q, model)
- if qt == None: return None
+ if qt is None:
+ return None
if op == '<=>':
return pt == qt
elif op == '^':
return pt != qt
else:
- raise ValueError, "illegal operator in logic expression" + str(exp)
+ raise ValueError("illegal operator in logic expression" + str(exp))
#______________________________________________________________________________
## Convert to Conjunctive Normal Form (CNF)
-
+
+
def to_cnf(s):
"""Convert a propositional logical sentence s to conjunctive normal
form.
That is, of the form ((A | ~B | ...) & (B | C | ...) & ...) [p. 215]
@@ -476,18 +546,21 @@
>>> to_cnf("A & (B | (D & E))")
(A & (D | B) & (E | B))
"""
- if isinstance(s, str): s = expr(s)
- s = eliminate_implications(s) # Steps 1, 2 from p. 215
- s = move_not_inwards(s) # Step 3
- return distribute_and_over_or(s) # Step 4
-
+ if isinstance(s, str):
+ s = expr(s)
+ s = eliminate_implications(s) # Steps 1, 2 from p. 215
+ s = move_not_inwards(s) # Step 3
+ return distribute_and_over_or(s) # Step 4
+
+
def eliminate_implications(s):
"""Change >>, <<, and <=> into &, |, and ~. That is, return an Expr
that is equivalent to s, but has only &, |, and ~ as logical operators.
>>> eliminate_implications(A >> (~B << C))
((~B | ~C) | ~A)
"""
- if not s.args or is_symbol(s.op): return s ## (Atoms are
unchanged.)
+ if not s.args or is_symbol(s.op):
+ return s # (Atoms are unchanged.)
args = map(eliminate_implications, s.args)
a, b = args[0], args[-1]
if s.op == '>>':
@@ -499,6 +572,7 @@
else:
return Expr(s.op, *args)
+
def move_not_inwards(s):
"""Rewrite sentence s by moving negation sign inward.
>>> move_not_inwards(~(A | B))
@@ -511,15 +585,19 @@
if s.op == '~':
NOT = lambda b: move_not_inwards(~b)
a = s.args[0]
- if a.op == '~': return move_not_inwards(a.args[0]) # ~~A ==> A
- if a.op =='&': return NaryExpr('|', *map(NOT, a.args))
- if a.op =='|': return NaryExpr('&', *map(NOT, a.args))
+ if a.op == '~':
+ return move_not_inwards(a.args[0]) # ~~A ==> A
+ if a.op == '&':
+ return NaryExpr('|', *map(NOT, a.args))
+ if a.op == '|':
+ return NaryExpr('&', *map(NOT, a.args))
return s
elif is_symbol(s.op) or not s.args:
return s
else:
return Expr(s.op, *map(move_not_inwards, s.args))
+
def distribute_and_over_or(s):
"""Given a sentence s consisting of conjunctions and disjunctions
of literals, return an equivalent sentence in CNF.
@@ -528,9 +606,9 @@
"""
if s.op == '|':
s = NaryExpr('|', *s.args)
- if len(s.args) == 0:
+ if len(s.args) == 0:
return FALSE
- if len(s.args) == 1:
+ if len(s.args) == 1:
return distribute_and_over_or(s.args[0])
conj = find_if((lambda d: d.op == '&'), s.args)
if not conj:
@@ -541,13 +619,14 @@
else:
rest = NaryExpr('|', *others)
return NaryExpr('&', *map(distribute_and_over_or,
- [(c|rest) for c in conj.args]))
+ [(c | rest) for c in conj.args]))
elif s.op == '&':
return NaryExpr('&', *map(distribute_and_over_or, s.args))
else:
return s
-_NaryExprTable = {'&':TRUE, '|':FALSE, '+':ZERO, '*':ONE}
+_NaryExprTable = {'&': TRUE, '|': FALSE, '+': ZERO, '*': ONE}
+
def NaryExpr(op, *args):
"""Create an Expr, but with an nary, associative op, so we can promote
@@ -557,8 +636,10 @@
"""
arglist = []
for arg in args:
- if arg.op == op: arglist.extend(arg.args)
- else: arglist.append(arg)
+ if arg.op == op:
+ arglist.extend(arg.args)
+ else:
+ arglist.append(arg)
if len(args) == 1:
return args[0]
elif len(args) == 0:
@@ -566,6 +647,7 @@
else:
return Expr(op, *arglist)
+
def conjuncts(s):
"""Return a list of the conjuncts in the sentence s.
>>> conjuncts(A & B)
@@ -573,11 +655,12 @@
>>> conjuncts(A | B)
[(A | B)]
"""
- if isinstance(s, Expr) and s.op == '&':
+ if isinstance(s, Expr) and s.op == '&':
return s.args
else:
return [s]
+
def disjuncts(s):
"""Return a list of the disjuncts in the sentence s.
>>> disjuncts(A | B)
@@ -585,13 +668,14 @@
>>> disjuncts(A & B)
[(A & B)]
"""
- if isinstance(s, Expr) and s.op == '|':
+ if isinstance(s, Expr) and s.op == '|':
return s.args
else:
return [s]
#______________________________________________________________________________
+
def pl_resolution(KB, alpha):
"Propositional Logic Resolution: say if alpha follows from KB. [Fig.
7.12]"
clauses = KB.clauses + conjuncts(to_cnf(~alpha))
@@ -599,14 +683,18 @@
while True:
n = len(clauses)
pairs = [(clauses[i], clauses[j])
- for i in range(n) for j in range(i+1, n)]
+ for i in range(n) for j in range(i + 1, n)]
for (ci, cj) in pairs:
resolvents = pl_resolve(ci, cj)
- if FALSE in resolvents: return True
+ if FALSE in resolvents:
+ return True
new = new.union(set(resolvents))
- if new.issubset(set(clauses)): return False
+ if new.issubset(set(clauses)):
+ return False
for c in new:
- if c not in clauses: clauses.append(c)
+ if c not in clauses:
+ clauses.append(c)
+
def pl_resolve(ci, cj):
"""Return all clauses that can be obtained by resolving clauses ci and
cj.
@@ -619,13 +707,14 @@
for di in disjuncts(ci):
for dj in disjuncts(cj):
if di == ~dj or ~di == dj:
- dnew = unique(removeall(di, disjuncts(ci)) +
+ dnew = unique(removeall(di, disjuncts(ci)) +
removeall(dj, disjuncts(cj)))
clauses.append(NaryExpr('|', *dnew))
return clauses
#______________________________________________________________________________
+
class PropHornKB(PropKB):
"A KB of Propositional Horn clauses."
@@ -635,7 +724,7 @@
assert op == '>>' or is_prop_symbol(op), "Must be Horn Clause"
self.clauses.append(sentence)
- def ask_generator(self, query):
+ def ask_generator(self, query):
"Yield the empty substitution if KB implies query; else False"
if not pl_fc_entails(self.clauses, query):
return
@@ -650,19 +739,21 @@
def clauses_with_premise(self, p):
"""The list of clauses in KB that have p in the premise.
This could be cached away for O(1) speed, but we'll recompute
it."""
- return [c for c in self.clauses
+ return [c for c in self.clauses
if c.op == '>>' and p in conjuncts(c.args[0])]
+
def pl_fc_entails(KB, q):
"""Use forward chaining to see if a HornKB entails symbol q. [Fig.
7.14]
>>> pl_fc_entails(Fig[7,15], expr('Q'))
True
"""
count = dict([(c, len(conjuncts(c.args[0]))) for c in KB.clauses
- if c.op == '>>'])
+ if c.op == '>>'])
inferred = DefaultDict(False)
agenda = [s for s in KB.clauses if is_prop_symbol(s.op)]
- if q in agenda: return True
+ if q in agenda:
+ return True
while agenda:
p = agenda.pop()
if not inferred[p]:
@@ -670,7 +761,8 @@
for c in KB.clauses_with_premise(p):
count[c] -= 1
if count[c] == 0:
- if c.args[1] == q: return True
+ if c.args[1] == q:
+ return True
agenda.append(c.args[1])
return False
@@ -679,13 +771,14 @@
## Propositional Logic Forward Chaining example [Fig. 7.15]
#Fig[7,15] = PropHornKB()
-#for s in "P>>Q (L&M)>>P (B&L)>>M (A&P)>>L (A&B)>>L A
B".split():
+#for s in "P>>Q (L&M)>>P (B&L)>>M (A&P)>>L (A&B)>>L A
B".split():
# Fig[7,15].tell(expr(s))
#______________________________________________________________________________
# DPLL-Satisfiable [Fig. 7.16]
+
def dpll_satisfiable(s):
"""Check satisfiability of a propositional sentence.
This differs from the book code in two ways: (1) it returns a model
@@ -700,15 +793,16 @@
clauses = conjuncts(to_cnf(s))
symbols = prop_symbols(s)
return dpll(clauses, symbols, {})
-
+
+
def dpll(clauses, symbols, model):
"See if the clauses are true in a partial model."
- unknown_clauses = [] ## clauses with an unknown truth value
+ unknown_clauses = [] # clauses with an unknown truth value
for c in clauses:
- val = pl_true(c, model)
- if val == False:
+ val = pl_true(c, model)
+ if val is False:
return False
- if val != True:
+ if val is not True:
unknown_clauses.append(c)
if not unknown_clauses:
return model
@@ -721,7 +815,8 @@
P = symbols.pop()
return (dpll(clauses, symbols, extend(model, P, True)) or
dpll(clauses, symbols, extend(model, P, False)))
-
+
+
def find_pure_symbol(symbols, unknown_clauses):
"""Find a symbol and its value if it appears only as a positive literal
(or only as a negative) in clauses.
@@ -731,11 +826,15 @@
for s in symbols:
found_pos, found_neg = False, False
for c in unknown_clauses:
- if not found_pos and s in disjuncts(c): found_pos = True
- if not found_neg and ~s in disjuncts(c): found_neg = True
- if found_pos != found_neg: return s, found_pos
+ if not found_pos and s in disjuncts(c):
+ found_pos = True
+ if not found_neg and ~s in disjuncts(c):
+ found_neg = True
+ if found_pos != found_neg:
+ return s, found_pos
return None, None
+
def find_unit_clause(clauses, model):
"""A unit clause has only 1 variable that is not bound in the model.
>>> find_unit_clause([A|B|C, B|~C, A|~B], {A:True})
@@ -751,7 +850,7 @@
if num_not_in_model == 1:
return P, value
return None, None
-
+
def literal_symbol(literal):
"""The symbol in this literal (without the negation).
@@ -764,7 +863,7 @@
return literal.args[0]
else:
return literal
-
+
#______________________________________________________________________________
# Walk-SAT [Fig. 7.17]
@@ -772,13 +871,13 @@
def WalkSAT(clauses, p=0.5, max_flips=10000):
## model is a random assignment of true/false to the symbols in clauses
## See ~/aima1e/print1/manual/knowledge+logic-answers.tex ???
- model = dict([(s, random.choice([True, False]))
+ model = dict([(s, random.choice([True, False]))
for s in prop_symbols(clauses)])
for i in range(max_flips):
satisfied, unsatisfied = [], []
for clause in clauses:
if_(pl_true(clause, model), satisfied,
unsatisfied).append(clause)
- if not unsatisfied: ## if model satisfies all the clauses
+ if not unsatisfied: # if model satisfies all the clauses
return model
clause = random.choice(unsatisfied)
if probability(p):
@@ -788,7 +887,6 @@
raise NotImplementedError
model[sym] = not model[sym]
-
# PL-Wumpus-Agent [Fig. 7.19]
#class PLWumpusAgent(agents.Agent):
"""An agent for the wumpus world that does logical inference. [Fig.
7.19]"""
@@ -810,13 +908,14 @@
for [i, j] in fringe(visited):
if KB.ask('~P_%d,%d & ~W_%d,%d' % (i, j, i, j)) !=
False:
raise NotImplementedError
- KB.ask('~P_%d,%d | ~W_%d,%d' % (i, j, i, j)) != False
- if action == None:
+ KB.ask('~P_%d,%d | ~W_%d,%d' % (i, j, i, j)) != False
+ if action == None:
action = random.choice(['Forward', 'Right', 'Left'])
return action
self.program = program"""
+
def update_position(x, y, orientation, action):
if action == 'TurnRight':
orientation = turn_right(orientation)
@@ -825,9 +924,10 @@
elif action == 'Forward':
x, y = x + vector_add((x, y), orientation)
return x, y, orientation
-
+
#______________________________________________________________________________
+
def unify(x, y, s):
"""Unify expressions x,y with substitution s; return a substitution
that
would make x,y equal, or None if x,y can not unify. x and y can be
@@ -835,7 +935,7 @@
>>> ppsubst(unify(x + y, y + C, {}))
{x: y, y: C}
"""
- if s == None:
+ if s is None:
return None
elif x == y:
return s
@@ -854,10 +954,12 @@
else:
return None
+
def is_variable(x):
"A variable is an Expr with no args and a lowercase symbol as the op."
return isinstance(x, Expr) and not x.args and is_var_symbol(x.op)
+
def unify_var(var, x, s):
if var in s:
return unify(s[var], x, s)
@@ -866,14 +968,15 @@
else:
return extend(s, var, x)
+
def occur_check(var, x, s):
"""Return true if variable var occurs anywhere in x
(or in subst(s, x), if s has a binding for x)."""
if var == x:
return True
- elif is_variable(x) and s.has_key(x):
- return occur_check(var, s[x], s) # fixed
+ elif is_variable(x) and x in s:
+ return occur_check(var, s[x], s) # fixed
# What else might x be? an Expr, a list, a string?
elif isinstance(x, Expr):
# Compare operator and arguments
@@ -886,7 +989,7 @@
else:
# A variable cannot occur in a string
return False
-
+
#elif isinstance(x, Expr):
# return var.op == x.op or occur_check(var, x.args)
#elif not isinstance(x, str) and issequence(x):
@@ -894,33 +997,36 @@
# if occur_check(var, xi): return True
#return False
+
def extend(s, var, val):
"""Copy the substitution s and extend it by setting var to val;
return copy.
-
+
>>> ppsubst(extend({x: 1}, y, 2))
{x: 1, y: 2}
"""
s2 = s.copy()
s2[var] = val
return s2
-
+
+
def subst(s, x):
"""Substitute the substitution s into the expression x.
>>> subst({x: 42, y:0}, F(x) + y)
(F(42) + 0)
"""
- if isinstance(x, list):
+ if isinstance(x, list):
return [subst(s, xi) for xi in x]
- elif isinstance(x, tuple):
+ elif isinstance(x, tuple):
return tuple([subst(s, xi) for xi in x])
- elif not isinstance(x, Expr):
+ elif not isinstance(x, Expr):
return x
- elif is_var_symbol(x.op):
+ elif is_var_symbol(x.op):
return s.get(x, x)
- else:
+ else:
return Expr(x.op, *[subst(s, arg) for arg in x.args])
-
+
+
def fol_fc_ask(KB, alpha):
"""Inefficient forward chaining for first-order logic. [Fig. 9.3]
KB is an FOLHornKB and alpha must be an atomic sentence."""
@@ -931,6 +1037,7 @@
ps, q = conjuncts(r.args[0]), r.args[1]
raise NotImplementedError
+
def standardize_apart(sentence, dic={}):
"""Replace all the variables in sentence with new variables.
>>> e = expr('F(a, b, c) & G(c, A, 23)')
@@ -943,7 +1050,7 @@
"""
if not isinstance(sentence, Expr):
return sentence
- elif is_var_symbol(sentence.op):
+ elif is_var_symbol(sentence.op):
if sentence in dic:
return dic[sentence]
else:
@@ -951,7 +1058,7 @@
v = Expr('v_%d' % standardize_apart.counter)
dic[sentence] = v
return v
- else:
+ else:
return Expr(sentence.op,
*[standardize_apart(a, dic) for a in sentence.args])
@@ -972,8 +1079,8 @@
False
"""
- def __init__ (self, initial_clauses=[]):
- self.clauses = [] # inefficient: no indexing
+ def __init__(self, initial_clauses=[]):
+ self.clauses = [] # inefficient: no indexing
for clause in initial_clauses:
self.tell(clause)
@@ -989,6 +1096,7 @@
def retract(self, sentence):
self.clauses.remove(sentence)
+
def test_ask(q):
e = expr(q)
vars = variables(e)
@@ -1008,14 +1116,14 @@
'(Mother(m, c)) ==> Loves(m, c)',
'(Mother(m, r) & Rabbit(r)) ==> Rabbit(m)',
'(Farmer(f)) ==> Human(f)',
- # Note that this order of conjuncts
+ # Note that this order of conjuncts
# would result in infinite recursion:
#'(Human(h) & Mother(m, h)) ==> Human(m)'
'(Mother(m, h) & Human(h)) ==> Human(m)'
])
)
-
-
+
+
def fol_bc_ask(KB, goals, theta={}):
***The diff for this file has been truncated for email.***
=======================================
--- /trunk/spade/msgtypes.py Fri Apr 27 09:56:18 2007
+++ /trunk/spade/msgtypes.py Fri Nov 23 05:19:16 2012
@@ -1,6 +1,6 @@
+# -*- coding: utf-8 -*-
# Message types (that an agent can receive)
-MSG_ACL = "ACL"
-MSG_IQ = "IQ"
-MSG_PRESENCE = "PRESENCE"
-MSG_JABBER = "JABBER"
-
+MSG_ACL = "ACL"
+MSG_IQ = "IQ"
+MSG_PRESENCE = "PRESENCE"
+MSG_JABBER = "JABBER"
=======================================
--- /trunk/spade/mtp/http.py Fri Nov 9 09:51:22 2012
+++ /trunk/spade/mtp/http.py Fri Nov 23 05:19:16 2012
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
HTTP MTP for SPADE
@@ -17,39 +18,36 @@
import httplib
-
#Specific constants
PORT = 2099
PROTOCOL_VERSION = "HTTP/1.1"
BOUNDARY = "SpadeMtpHttpMimeMultipartMixedBoundary"
-BI="--"
+BI = "--"
FIPA_CT_HYPHEN = "multipart-mixed"
FIPA_CT = "multipart/mixed"
-FIPA_HP =
{'Cache-Control':'no-cache', 'Host':'localhost:80', 'Mime-Version':'1.0',
- 'Content-Type':FIPA_CT+' ; boundary="'+BOUNDARY+'"',
- 'Content-Length':'0' , 'Connection':'close'}
+FIPA_HP =
{'Cache-Control': 'no-cache', 'Host': 'localhost:80', 'Mime-Version': '1.0',
+ 'Content-Type': FIPA_CT + ' ; boundary="' + BOUNDARY + '"',
+ 'Content-Length': '0', 'Connection': 'close'}
-FIPA_HP_LOWER =
{'cache-control':'no-cache', 'host':'localhost:80', 'mime-version':'1.0',
- 'content-type':FIPA_CT+' ; boundary="'+BOUNDARY+'"',
- 'content-length':'0' , 'connection':'close'}
+FIPA_HP_LOWER =
{'cache-control': 'no-cache', 'host': 'localhost:80', 'mime-version': '1.0',
+ 'content-type': FIPA_CT + ' ; boundary="' + BOUNDARY
+ '"',
+ 'content-length': '0', 'connection': 'close'}
-FIPA_HR =
{'Content-type':'text/plain','Cache-Control':'no-cache','Connection':'close'}
+FIPA_HR =
{'Content-type': 'text/plain', 'Cache-Control': 'no-cache', 'Connection': 'close'}
-FIPA_HR_LOWER =
{'content-type':'text/plain','cache-control':'no-cache','connection':'close'}
+FIPA_HR_LOWER =
{'content-type': 'text/plain', 'cache-control': 'no-cache', 'connection': 'close'}
FIPA_CT_ENV = "application/fipa.mts.env.rep.xml.std"
FIPA_CT_PAY = "application/fipa.acl.rep.string.std"
-CONTENT_TYPE="Content-Type: "
+CONTENT_TYPE = "Content-Type: "
-CT_XML = "application/xml"
+CT_XML = "application/xml"
CT_TEXT = "application/text"
CT_JSON = "application/json"
-
class http(MTP.MTP):
-
def setup(self):
self.httpserver = HttpServer()
self.httpserver.setName("SpadeHttpServer")
@@ -57,28 +55,27 @@
self.httpserver.start()
#print "SPADE HTTP MTP Starting . . ."
-
- def make_body(self,envelope,message):
+ def make_body(self, envelope, message):
"""
Create the body of the message
"""
language = message.getAclRepresentation()
payload = str(message)
-
+
body = BI + BOUNDARY + "\r\n"
if language == ACLMessage.FIPA_ACL_REP_JSON:
# the new JSON way
body = body + CONTENT_TYPE + CT_JSON + "\n\n"
body = body + envelope + "\r\n" + BI + BOUNDARY + "\r\n"
body = body + CONTENT_TYPE + CT_JSON + "\n\n"
-
+
elif language == ACLMessage.FIPA_ACL_REP_STRING:
# Standard way
body = body + CONTENT_TYPE + FIPA_CT_ENV + "\n\n"
body = body + envelope + "\r\n" + BI + BOUNDARY + "\r\n"
body = body + CONTENT_TYPE + FIPA_CT_PAY + "\n\n"
-
- else: #language == ACLMessage.FIPA_ACL_REP_XML
+
+ else: # language == ACLMessage.FIPA_ACL_REP_XML
if "/JADE" not in envelope:
# Standard way
body = body + CONTENT_TYPE + FIPA_CT_ENV + "\n\n"
@@ -91,23 +88,20 @@
body = body + CONTENT_TYPE + CT_TEXT + "\r\n"
body = body + payload + "\r\n"
- body = body + BI + BOUNDARY + BI +"\r\n"
+ body = body + BI + BOUNDARY + BI + "\r\n"
return body
-
def stop(self):
try:
- del self.httpserver
+ self.httpserver.shutdown()
except Exception, e:
- pass
- #print "EXCEPTION STOPPING HTTP", str(e)
+ print "EXCEPTION STOPPING HTTP", str(e)
- def send(self,envelope,payload):
+ def send(self, envelope, payload):
"""
Send a message to a http agent
"""
-
envelope.setPayloadLength(str(len(str(payload))))
try:
@@ -120,7 +114,7 @@
pass
# Making the body to send
- body = self.make_body(strenv,payload)
+ body = self.make_body(strenv, payload)
# NO CAPS
#self.fipaHeadersPost = FIPA_HP_LOWER
#self.fipaHeadersPost['content-length'] = str(len(body))
@@ -129,21 +123,17 @@
self.fipaHeadersPost = FIPA_HP
self.fipaHeadersPost['Content-Length'] = str(len(str(body)))
-
# Geting message receivers
to = envelope.getTo()
#print ">>>HTTP TRANSPORT: TO = " + str(to)
for receiver in to:
- #print ">>>HTTP TRANSPORT: RECEIVER = " + str(receiver)
for ad in receiver.getAddresses():
ad = str(ad)
- #print ">>>HTTP TRANSPORT: ADDRESS = " + ad
# HTTP URI = http://address:port
if ad[0:7] == "http://":
ad = ad[7:]
- #print ">>>HTTP TRANSPORT: FINAL ADDRESS = " + ad
# HTTP connection
#host = ad.split("/acc")[0]
@@ -152,11 +142,7 @@
self.fipaHeadersPost['Host'] = host
- #print str(self.fipaHeadersPost)
- #print str(body)
-
-
-
conn.request("POST",remote_path,body,self.fipaHeadersPost)
+ conn.request("POST", remote_path, body,
self.fipaHeadersPost)
response = conn.getresponse()
@@ -166,28 +152,29 @@
if response.reason != "OK":
print "Conection Error: Bad reason",
str(response.reason)
- #print response.status, response.reason
-
conn.close()
# End connection
- #print "HTTP Connection closed"
-
+ # HTTP Connection closed
class HttpServer(threading.Thread):
def run(self):
BaseHTTPServer.HTTPServer.allow_reuse_address = True
- httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
- #print "HTTP Transport serving at port", PORT
- httpd.mtp = self.mtp
- httpd.serve_forever()
+ BaseHTTPServer.HTTPServer.timeout = 1
+ self.httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
+ self.httpd.mtp = self.mtp
+ self.httpd.serve_forever(poll_interval=0.5)
+
+ def shutdown(self):
+ self.httpd.shutdown()
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
protocol_version = PROTOCOL_VERSION
- def log_message(format,*args): pass
+ def log_message(format, *args):
+ pass
def send_response(self, code, message=None):
"""
@@ -199,8 +186,7 @@
message = self.responses[code][0]
else:
message = ''
- self.wfile.write("%s %d %s\r\n" %(self.protocol_version, code,
message))
-
+ self.wfile.write("%s %d %s\r\n" % (self.protocol_version, code,
message))
def do_POST(self):
"""
@@ -210,16 +196,13 @@
# fipa specification only allows HTTP/1.1
self.send_error(505)
- #print "HEADERS!!!", self.headers
-
new_headers = {}
for k in self.headers.keys():
new_headers[k.lower()] = self.headers[k]
for i in FIPA_HP.keys():
if i.lower() not in new_headers.keys():
- #print "HEADERS MISMATCH", str(self.headers.keys()),
str(FIPA_HP.keys())
- self.send_error(400,"FIPA headers required (
www.fipa.org)")
+ self.send_error(400, "FIPA headers required
(
www.fipa.org)")
break
#if self.headers.keys() in FIPA_HP.keys():
@@ -227,14 +210,13 @@
# self.send_error(400,"FIPA headers required (
www.fipa.org)")
if self.headers.getheader('Mime-Version') !=
FIPA_HP['Mime-Version']:
- self.send_error(400,"mime-version must be 1.0")
+ self.send_error(400, "mime-version must be 1.0")
if FIPA_CT not in self.headers.getheader('Content-Type'):
- #print "FIPA_CT NOT IN CT"
+ #FIPA_CT NOT IN CT
self.send_error(415)
if 'boundary' not in self.headers.getparamnames():
- #print "GETPARAMNAMES", str(self.headers.getparamnames())
self.send_error(415)
boundary = self.headers.getparam('boundary')
@@ -243,8 +225,8 @@
if clen <= 0:
send_error(411)
- envelope , payload = self.getContent(self.rfile,boundary,clen)
-
+ envelope, payload = self.getContent(self.rfile, boundary, clen)
+
# Dispatching message
if envelope and payload:
self.server.mtp.dispatch(envelope, payload)
@@ -253,11 +235,10 @@
self.send_response(200)
for header in FIPA_HR.keys():
- self.send_header(header,FIPA_HR[header])
+ self.send_header(header, FIPA_HR[header])
self.end_headers()
-
- def getContent(self,rfile,boundary,clen):
+ def getContent(self, rfile, boundary, clen):
"""
Parses entity body catching the envelope and payload of the
incoming message
"""
@@ -265,14 +246,13 @@
env = None
pay = None
-
part = 0
- buf1 = rfile.read(int(clen)).split(BI+boundary+BI)
+ buf1 = rfile.read(int(clen)).split(BI + boundary + BI)
if len(buf1) != 2:
- self.send_error(400,"Malformed Multipart-Mixed MIME")
+ self.send_error(400, "Malformed Multipart-Mixed MIME")
- buf2 = buf1[0].split(BI+boundary)
+ buf2 = buf1[0].split(BI + boundary)
parts = len(buf2)
@@ -287,25 +267,24 @@
pay = buf2[2]
else:
- self.send_error(400,"Malformed Multipart-Mixed MIME")
+ self.send_error(400, "Malformed Multipart-Mixed MIME")
except:
- self.send_error(400,"Malformed Multipart-Mixed MIME")
+ self.send_error(400, "Malformed Multipart-Mixed MIME")
# searching CLRF CLRF where envelope really starts, before this
sequence is the envelope content type
index = env.find('\r\n\r\n')
if index < 0:
index = env.find('\n\n')
type_env = env[0:index]
- env = env[index+2:]
+ env = env[index + 2:]
# the same for payload
index = pay.find('\r\n\r\n')
if index < 0:
index = pay.find('\n\n')
type_pay = pay[0:index]
- pay = pay[index+2:]
+ pay = pay[index + 2:]
-
# Content types check
try:
type_env = type_env.split(':')[1].split(';')[0].strip()
@@ -327,39 +306,34 @@
try:
envelope = xc.parse(env)
except Exception, e:
- self.send_error(400,"Malformed FIPA Envelope")
+ self.send_error(400, "Malformed FIPA Envelope")
elif type_env == CT_JSON:
envelope = Envelope.Envelope(jsonstring=env)
else:
self.send_error(415)
return None, None
-
if FIPA_CT_PAY in type_pay or CT_TEXT in type_pay:
p = ACLParser.ACLParser()
try:
payload = p.parse(pay)
except Exception, e:
- self.send_error(400,"Malformed FIPA ACL Payload")
- return envelope,None
- elif type_pay == CT_XML or type_pay
== "application/"+ACLMessage.FIPA_ACL_REP_XML:
+ self.send_error(400, "Malformed FIPA ACL Payload")
+ return envelope, None
+ elif type_pay == CT_XML or type_pay == "application/" +
ACLMessage.FIPA_ACL_REP_XML:
p = ACLParser.ACLxmlParser()
try:
payload = p.parse(pay)
except Exception, e:
- self.send_error(400,"Malformed FIPA XML Payload")
- return envelope,None
+ self.send_error(400, "Malformed FIPA XML Payload")
+ return envelope, None
elif type_pay == CT_JSON:
payload = ACLMessage.ACLMessage(jsonstring=pay)
else:
self.send_error(415)
- return envelope,None
-
-
- return (envelope,payload)
-
-
+ return envelope, None
+ return (envelope, payload)
#Required constants
@@ -369,25 +343,23 @@
if __name__ == "__main__":
- http_mtp = http("SpadeHttpSever",None,None)
+ http_mtp = http("SpadeHttpSever", None, None)
import time
time.sleep(5)
msg = ACLMessage.ACLMessage()
msg.setPerformative("inform")
-
msg.addReceiver(AID.aid("b@localhost",["xmpp://b@localhost", "
http://localhost:2099/b"]))
+ msg.addReceiver(AID.aid("b@localhost",
["xmpp://b@localhost", "
http://localhost:2099/b"]))
msg.setContent("testACLMessage")
msg.setLanguage(ACLMessage.FIPA_ACL_REP_XML)
env = Envelope.Envelope()
-
env.addTo(AID.aid("b@localhost",["xmpp://b@localhost", "
http://localhost:2099/b"]))
-
env.setFrom(AID.aid("a@localhost",["xmpp://a@localhost", "
http://localhost:2099/a"]))
+ env.addTo(AID.aid("b@localhost",
["xmpp://b@localhost", "
http://localhost:2099/b"]))
+ env.setFrom(AID.aid("a@localhost",
["xmpp://a@localhost", "
http://localhost:2099/a"]))
env.setAclRepresentation(ACLMessage.FIPA_ACL_REP_XML)
env.setPayloadEncoding("US-ASCII")
env.setDate("20121105T134259368626")
-
- http_mtp.send(env,msg)
-
+ http_mtp.send(env, msg)
"""
=======================================
--- /trunk/spade/mtp/simba.py Wed Jul 25 09:02:05 2007
+++ /trunk/spade/mtp/simba.py Fri Nov 23 05:19:16 2012
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
from spade import MTP
from spade import AID
@@ -8,104 +9,87 @@
import SocketServer
import xmpp
-#try:
-# import stack_thread as thread
-#except:
-# import thread
-
import thread
+
class SimbaRequestHandler(SocketServer.DatagramRequestHandler):
- '''
- Request handler for SIMBA messages
- '''
- def handle(self):
- msg = str(self.request[0])
- #print "SIMBA SS: New incoming message: " + msg
- acl = self.server.parser.parse(msg)
- envelope = Envelope.Envelope(_from=acl.getSender(),
to=acl.getReceivers(), aclRepresentation="fipa.acl.rep.string.std")
- self.server.dispatch(envelope, msg)
- #print "SIMBA SS: Message dispatched"
+ '''
+ Request handler for SIMBA messages
+ '''
+ def handle(self):
+ msg = str(self.request[0])
+ #print "SIMBA SS: New incoming message: " + msg
+ acl = self.server.parser.parse(msg)
+ envelope = Envelope.Envelope(_from=acl.getSender(),
to=acl.getReceivers(), aclRepresentation="fipa.acl.rep.string.std")
+ self.server.dispatch(envelope, msg)
+ #print "SIMBA SS: Message dispatched"
class simba(MTP.MTP):
- def receiveThread(self):
- SocketServer.ThreadingUDPServer.allow_reuse_address = True
- self.SS = SocketServer.ThreadingUDPServer(("", self.port),
SimbaRequestHandler)
- self.SS.dispatch = self.dispatch
- self.SS.parser = ACLParser.ACLParser()
- #print "SIMBA SS listening on port " + str(self.port)
- self.SS.serve_forever()
+ def receiveThread(self):
+ SocketServer.ThreadingUDPServer.allow_reuse_address = True
+ self.SS = SocketServer.ThreadingUDPServer(("", self.port),
SimbaRequestHandler)
+ self.SS.dispatch = self.dispatch
+ self.SS.parser = ACLParser.ACLParser()
+ #print "SIMBA SS listening on port " + str(self.port)
+ self.SS.serve_forever()
- def stop(self):
- try:
- del self.SS
- except Exception,e:
- pass
- print "EXCEPTION IN SIMBA",str(e)
+ def stop(self):
+ try:
+ del self.SS
+ except Exception, e:
+ pass
+ print "EXCEPTION IN SIMBA", str(e)
- def setup(self):
- '''
- Secondary constructor
- '''
- #print ">>>SIMBA Transport ready for action"
- #self.address = self.config.acc[
self.name].address
- #self.port = self.config.acc[
self.name].port
- self.port = 2001
-
- # Launch receive thread
- #print ">>>SIMBA: Going to start new thread"
- tid = thread.start_new_thread(self.receiveThread, ())
- #print ">>>SIMBA: Started new thread " + str(tid)
-
-
- def send(self, envelope, payload, to=None):
- '''
- Send a message to a SIMBA agent
- '''
- #print ">>>SIMBA TRANSPORT: A MESSAGE TO SEND FOR ME"
+ def setup(self):
+ '''
+ Secondary constructor
+ '''
+ #self.address = self.config.acc[
self.name].address
+ #self.port = self.config.acc[
self.name].port
+ self.port = 2001
- payload = str(payload.getPayload()[0])
- #print ">>>SIMBA: PAYLOAD = " + payload
- try:
- p = ACLParser.ACLxmlParser()
- aclmsg = p.parse(payload)
- except:
- print ">>>SIMBA: COULD NOT BUILD ACL"
- pass
+ # Launch receive thread
+ tid = thread.start_new_thread(self.receiveThread, ())
- if to == None:
- to = envelope.getTo()
- #print ">>>SIMBA TRANSPORT: TO = " + str(to)
+ def send(self, envelope, payload, to=None):
+ '''
+ Send a message to a SIMBA agent
+ '''
+ payload = str(payload.getPayload()[0])
+ try:
+ p = ACLParser.ACLxmlParser()
+ aclmsg = p.parse(payload)
+ except:
+ print ">>>SIMBA: COULD NOT BUILD ACL"
+ pass
- for receiver in to:
- #print ">>>SIMBA TRANSPORT: RECEIVER = " + str(receiver)
- for ad in receiver.getAddresses():
- ad = str(ad) # Type change
- #print ">>>SIMBA TRANSPORT: ADDRESS = " + ad
- # SIMBA URI = simba://address:port
- if ad[0:8] == "simba://":
- ad = ad[8:]
- #print ">>>SIMBA TRANSPORT: ADDRESS FINAL = " + ad
- # Check for the presence of a port
- if ':' in ad:
- ip, port = ad.split(':')
- else:
- ip = ad
- port = 2001
+ if to is None:
+ to = envelope.getTo()
- # Set up a SIMBA socket to send the message
- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- try:
- s.connect((ip, port))
- # FORCE ACL WITH PARENTHESIS
- s.send(str(aclmsg)) # ACL with parenthesis, oh no!
- s.close()
- #print ">>>SIMBA message succesfully sent"
- except:
- print "Could not send SIMBA message"
+ for receiver in to:
+ for ad in receiver.getAddresses():
+ ad = str(ad) # Type change
+ # SIMBA URI = simba://address:port
+ if ad[0:8] == "simba://":
+ ad = ad[8:]
+ # Check for the presence of a port
+ if ':' in ad:
+ ip, port = ad.split(':')
+ else:
+ ip = ad
+ port = 2001
+ # Set up a SIMBA socket to send the message
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ try:
+ s.connect((ip, port))
+ # FORCE ACL WITH PARENTHESIS
+ s.send(str(aclmsg)) # ACL with parenthesis, oh no!
+ s.close()
+ except:
+ print "Could not send SIMBA message"
# Required
PROTOCOL = "simba"
=======================================
--- /trunk/spade/odict.py Tue Jul 31 06:58:54 2012
+++ /trunk/spade/odict.py Fri Nov 23 05:19:16 2012
@@ -130,7 +130,7 @@
>>> d.update({'foo': 'bar'})
>>> d
odict.odict([('a', 'b'), ('c', 'd'), ('foo', 'bar')])
-
+
Keep in mind that when updating from dict-literals the order is not
preserved as these dicts are unsorted!
@@ -179,7 +179,7 @@
>>> d.reverse()
>>> d
odict.odict([('spam', []), ('foo', 'bar'), ('c', 'd'), ('a', 'b')])
-
+
And sort it like a list:
>>> d.sort(key=lambda x: x[0].lower())
=======================================
--- /trunk/spade/peer2peer.py Tue Jun 29 12:24:20 2010
+++ /trunk/spade/peer2peer.py Fri Nov 23 05:19:16 2012
@@ -1,23 +1,32 @@
+# -*- coding: utf-8 -*-
import Behaviour
import xmpp
import SocketServer
import pickle
import random
+import thread
+import time
+import threading
+import socket
-class P2PBehaviour(Behaviour.Behaviour):
+
+class P2PBehaviour(Behaviour.OneShotBehaviour):
class P2PRequestHandler(SocketServer.StreamRequestHandler):
+ timeout = 5
+
def handle(self):
self.server.requests.append(self.request)
- try:
- data = ""
- while True:
+ data = ""
+ close = False
+ while not close and not self.server.closing: # True:
+ try:
#Read message length
length = self.rfile.read(8)
if not length:
#EOF
break
data = self.rfile.read(int(length))
- self.server.owner.DEBUG("P2P message received.","ok")
+ self.server.owner.DEBUG("P2P message received.", "ok")
if data:
try:
#Try with a serialized message
@@ -28,22 +37,42 @@
#Try with a jabber message
n = xmpp.simplexml.XML2Node(str(data))
m = xmpp.Message(node=n)
-
self.server._jabber_messageCB(None,m,raiseFlag=False)
- self.server.owner.DEBUG("The p2p message is
XML:"+str(m))
+ self.server._jabber_messageCB(None, m,
raiseFlag=False)
+ self.server.owner.DEBUG("The p2p message is
XML:" + str(m))
data = ""
- except Exception, e:
- self.server.owner.DEBUG("P2P Socket Closed to "+
str(self.client_address),"err") #,":",str(e),":",str(length),str(data)
+ except socket.timeout:
+ close = True
+ # handle timeout
+ except Exception, e:
+ self.server.owner.DEBUG("P2P Socket Closed to " +
str(self.client_address), "err")
+ close = True
+ def kill(self):
+ """
+ stops the behavior
+ """
+ try:
+ self._forceKill.set()
+ self.myAgent.DEBUG("Stoping Behavior " + str(self), "info")
+ except:
+ #Behavior is already dead
+ self.myAgent.DEBUG("Behavior " + str(self) + " is already
dead", "warn")
+
+ self.server.closing = True
+ if self.server is not None:
+ thread.start_new_thread(self.server.shutdown, ())
def _process(self):
try:
- self.server.handle_request()
- except Exception,e:
- self.myAgent.DEBUG("P2P server failed: "+str(e),"err")
+ self.server.serve_forever(poll_interval=0.5) #
handle_request()
+ except Exception, e:
+ self.myAgent.DEBUG("P2P server failed: " + str(e), "err")
+ self.kill()
def onEnd(self):
self.myAgent.p2p_ready = False
- self.server.stop()
+ if self.server is not None:
+ self.server.server_close() # shutdown()
if not self.finished:
try:
for sock in self.server.requests:
@@ -53,39 +82,48 @@
except:
pass
self.server.socket.close()
- del self.server
+ #del self.server
except:
pass
- iq = xmpp.Iq("result",queryNS=xmpp.NS_DISCO_INFO)
+ iq = xmpp.Iq("result", queryNS=xmpp.NS_DISCO_INFO)
for to in self.myAgent.p2p_routes.keys():
iq.setTo(to)
self.myAgent.send(iq)
self.finished = True
def onStart(self):
- open = False
+ self.server = None
SocketServer.ThreadingTCPServer.allow_reuse_address = True
- while open == False:
+ #SocketServer.TCPServer.timeout = 1
+ count = 5
+ while self.server is None and count > 0:
try:
self.server = SocketServer.ThreadingTCPServer(('',
self.myAgent.P2PPORT), self.P2PRequestHandler)
self.server.owner = self.myAgent
- open = True
+ self.server.timeout = 0.5
except:
- self.myAgent.P2PPORT = random.randint(1025,65535)
+ self.myAgent.P2PPORT = random.randint(1025, 65535)
self.myAgent.DEBUG("Changing P2P port to " +
str(self.myAgent.P2PPORT))
+ count -= 1
- self.server._jabber_messageCB = self.myAgent._jabber_messageCB
- self.server.postMessage = self.myAgent.postMessage
- self.server.requests = []
- self.myAgent.DEBUG(self.getName()+": P2P Behaviour Started at
port "+ str(self.myAgent.P2PPORT))
- self.finished = False #Flag to mark (later) if we have passed
through onEnd
- self.myAgent.p2p_ready = True
-
+ if self.server is not None:
+ self.server.closing = False
+ self.server._jabber_messageCB = self.myAgent._jabber_messageCB
+ self.server.postMessage = self.myAgent.postMessage
+ self.server.requests = []
+ self.myAgent.DEBUG(self.myAgent.getName() + ": P2P Behaviour
Started at port " + str(self.myAgent.P2PPORT))
+ self.finished = False # Flag to mark (later) if we have
passed through onEnd
+ self.myAgent.p2p_ready = True
+ else:
+ self.myAgent.DEBUG("Could not start P2P Behaviour", "err")
+ self.kill()
+
+
class StreamInitiationBehaviour(Behaviour.EventBehaviour):
def _process(self):
self.msg = self._receive(False)
- if self.msg != None:
+ if self.msg is not None:
if self.msg.getType() == "set":
if self.msg.getTag("si").getAttr("profile")
== "
http://jabber.org/protocol/si/profile/spade-p2p-messaging":
#P2P Messaging Offer
@@ -94,11 +132,11 @@
#Take note of sender's p2p address if any
if self.msg.getTag("si").getTag("p2p"):
remote_address =
str(self.msg.getTag("si").getTag("p2p").getData())
- d = {"url":remote_address, "p2p":True}
+ d = {"url": remote_address, "p2p": True}
self.myAgent.p2p_lock.acquire()
- if
self.myAgent.p2p_routes.has_key(str(self.msg.getFrom().getStripped())):
+ if str(self.msg.getFrom().getStripped()) in
self.myAgent.p2p_routes:
self.myAgent.p2p_routes[str(self.msg.getFrom().getStripped())].update(d)
- if
self.myAgent.p2p_routes[str(self.msg.getFrom().getStripped())].has_key("socket"):
+ if "socket" in
self.myAgent.p2p_routes[str(self.msg.getFrom().getStripped())]:
self.myAgent.p2p_routes[str(self.msg.getFrom().getStripped())]["socket"].close()
else:
self.myAgent.p2p_routes[str(self.msg.getFrom().getStripped())] = d
@@ -112,14 +150,14 @@
p2p.setNamespace('
http://jabber.org/protocol/si/profile/spade-p2p-messaging')
value = p2p.addChild("value")
value.setData(self.myAgent.getP2PUrl())
- self.myAgent.DEBUG("P2P: Accept offer
from "+str(self.msg.getFrom())+"."+str(reply) )
+ self.myAgent.DEBUG("P2P: Accept offer from " +
str(self.msg.getFrom()) + "." + str(reply))
else:
#Refuse offer
reply = self.msg.buildReply("error")
- err = reply.addChild("error",
attrs={"code":"403","type":"cancel"})
+ err = reply.addChild("error",
attrs={"code": "403", "type": "cancel"})
err.addChild("forbidden")
err.setNamespace("urn:ietf:params:xml:ns:xmpp-stanzas")
- self.myAgent.DEBUG("P2P: Refuse offer
from "+str(self.msg.getFrom())+"."+str(reply))
+ self.myAgent.DEBUG("P2P: Refuse offer from " +
str(self.msg.getFrom()) + "." + str(reply))
self.myAgent.send(reply)
@@ -128,15 +166,15 @@
def _process(self):
self.msg = self._receive(False)
- if self.msg != None:
+ if self.msg is not None:
if self.msg.getType() == "get":
#Inform of services
reply = self.msg.buildReply("result")
if self.myAgent.p2p_ready:
- reply.getTag("query").addChild("feature",
{"var":"
http://jabber.org/protocol/si"})
- reply.getTag("query").addChild("feature",
{"var":"
http://jabber.org/protocol/si/profile/spade-p2p-messaging"})
+ reply.getTag("query").addChild("feature",
{"var": "
http://jabber.org/protocol/si"})
+ reply.getTag("query").addChild("feature",
{"var": "
http://jabber.org/protocol/si/profile/spade-p2p-messaging"})
self.myAgent.send(reply)
- self.myAgent.DEBUG(self.myAgent.getName()+": Sent Disco
reply to "+ str(reply.getTo()))
+ self.myAgent.DEBUG(self.myAgent.getName() + ": Sent Disco
reply to " + str(reply.getTo()))
elif self.msg.getType() == "result":
services = []
for child in self.msg.getQueryChildren():
@@ -147,32 +185,32 @@
#This agent does no longer support p2p
self.myAgent.p2p_lock.acquire()
try:
- self.myAgent.DEBUG("Deleting "+str(frm)+" from
P2P routes: "+ str(self.myAgent.p2p_routes),"warn")
+ self.myAgent.DEBUG("Deleting " + str(frm) + "
from P2P routes: " + str(self.myAgent.p2p_routes), "warn")
del self.myAgent.p2p_routes[frm]
except:
pass
self.myAgent.p2p_lock.release()
else:
self.myAgent.DEBUG("DiscoBehaviour returned with no
message", "warn")
-
+
+
class SendStreamInitiationBehav(Behaviour.OneShotBehaviour):
-
- def __init__(self,to):
+
+ def __init__(self, to):
Behaviour.OneShotBehaviour.__init__(self)
self.to = to
-
self.id = 'offer'+str(random.randint(1,10000))
- self.temp_iq = xmpp.Iq(attrs={'id':
self.id})
-
-
+
self.id = 'offer' + str(random.randint(1, 10000))
+ self.temp_iq = xmpp.Iq(attrs={'id':
self.id})
+
def _process(self):
self.result = False
#Offer Stream Initiation
- self.myAgent.DEBUG( "Offer StreamInitiation to" + str(
self.to))
- iq = xmpp.Iq(attrs={'id':
self.id})
+ self.myAgent.DEBUG("Offer StreamInitiation to" + str(
self.to))
+ iq = xmpp.Iq(attrs={'id':
self.id})
iq.setTo(
self.to)
iq.setType("set")
- si = xmpp.Node("si",
{"profile":"
http://jabber.org/protocol/si/profile/spade-p2p-messaging"})
+ si = xmpp.Node("si",
{"profile": "
http://jabber.org/protocol/si/profile/spade-p2p-messaging"})
si.setNamespace("
http://jabber.org/protocol/si")
if self.myAgent.p2p_ready:
p2pnode = xmpp.Node("p2p")
@@ -185,46 +223,45 @@
msg = self._receive(True, 4)
if msg:
self.result = False
- if msg.getType() =="result":
- self.myAgent.DEBUG("StreamRequest Agreed","ok")
+ if msg.getType() == "result":
+ self.myAgent.DEBUG("StreamRequest Agreed", "ok")
try:
remote_address =
str(msg.getTag("si").getTag("p2p").getTag("value").getData())
- d = {"url":remote_address, "p2p":True}
- if
self.myAgent.p2p_routes.has_key(str(msg.getFrom().getStripped())):
+ d = {"url": remote_address, "p2p": True}
+ if str(msg.getFrom().getStripped()) in
self.myAgent.p2p_routes:
self.myAgent.p2p_routes[str(msg.getFrom().getStripped())].update(d)
self.result = True
else:
self.myAgent.p2p_routes[str(msg.getFrom().getStripped())] = d
except Exception, e:
- self.myAgent.DEBUG("Malformed StreamRequest Answer: "+
str(e),"err")
+ self.myAgent.DEBUG("Malformed StreamRequest Answer: "
+ str(e), "err")
self.myAgent.p2p_routes[str(msg.getFrom().getStripped())] = {}
elif msg.getType() == "error":
- self.myAgent.DEBUG("StreamRequest REFUSED","warn")
- self.myAgent.p2p_routes[str(msg.getFrom().getStripped())]
= {'p2p':False}
+ self.myAgent.DEBUG("StreamRequest REFUSED", "warn")
+ self.myAgent.p2p_routes[str(msg.getFrom().getStripped())]
= {'p2p': False}
else:
#Not message, treat like a refuse
- self.myAgent.DEBUG("StreamRequest REFUSED","warn")
- self.myAgent.p2p_routes[str(iq.getTo().getStripped())] =
{'p2p':False}
-
+ self.myAgent.DEBUG("StreamRequest REFUSED", "warn")
+ self.myAgent.p2p_routes[str(iq.getTo().getStripped())] =
{'p2p': False}
+
class RequestDiscoInfoBehav(Behaviour.OneShotBehaviour):
- def __init__(self,to):
+ def __init__(self, to):
Behaviour.OneShotBehaviour.__init__(self)
-
+
self.to = to
-
self.id = 'nsdi'+str(random.randint(1,10000))
- self.temp_iq = xmpp.Iq(queryNS=xmpp.NS_DISCO_INFO,
attrs={'id':
self.id})
+
self.id = 'nsdi' + str(random.randint(1, 10000))
+ self.temp_iq = xmpp.Iq(queryNS=xmpp.NS_DISCO_INFO, attrs={'id':
self.id})
self.temp_iq.setType("result")
-
def _process(self):
self.result = []
- iq = xmpp.Iq(queryNS=xmpp.NS_DISCO_INFO, attrs={'id':
self.id})
+ iq = xmpp.Iq(queryNS=xmpp.NS_DISCO_INFO, attrs={'id':
self.id})
iq.setTo(
self.to)
iq.setType("get")
- self.myAgent.DEBUG("Send IQ message: "+str(iq))
-
+ self.myAgent.DEBUG("Send IQ message: " + str(iq))
+
self.myAgent.send(iq)
#msg = self._receive(True, 10)
msg = self._receive(True)
@@ -237,4 +274,3 @@
self.myAgent.DEBUG("Disco Info returned no results from "
+ str(
self.to), "warn")
else:
self.myAgent.DEBUG("No Disco Info retrieved from " +
str(
self.to), "warn")
-
=======================================
--- /trunk/spade/pubsub.py Fri Jul 30 06:42:53 2010
+++ /trunk/spade/pubsub.py Fri Nov 23 05:19:16 2012
@@ -1,9 +1,11 @@
+# -*- coding: utf-8 -*-
from Behaviour import MessageTemplate, OneShotBehaviour
from xmpp.protocol import *
from xmpp.simplexml import Node
import uuid
+
def gen_id():
return str(uuid.uuid4())
@@ -27,7 +29,7 @@
class PubSub(object):
- def __init__(self, agent): #, msgrecv):
+ def __init__(self, agent): # , msgrecv):
self._client = agent.getAID().getName()
#self.msgrecv = msgrecv
self.myAgent = agent
@@ -35,58 +37,56 @@
def _sendAndReceive(self, iq, getContents):
id = gen_id()
- t = MessageTemplate(Iq(attrs={'id':id}))
+ t = MessageTemplate(Iq(attrs={'id': id}))
iq.setID(id)
- b = self._sendAndReceiveBehav(iq,getContents)
-
+ b = self._sendAndReceiveBehav(iq, getContents)
+
if self.myAgent._running:
- self.myAgent.addBehaviour(b,t)
+ self.myAgent.addBehaviour(b, t)
b.join()
else:
- self.myAgent.runBehaviourOnce(b,t)
-
+ self.myAgent.runBehaviourOnce(b, t)
+
return b.result
-
+
class _sendAndReceiveBehav(OneShotBehaviour):
- def __init__(self,iq,getContents):
+ def __init__(self, iq, getContents):
OneShotBehaviour.__init__(self)
self.iq = iq
self.getContents = getContents
self.timeout = 15
- self.result = (None,None)
-
+ self.result = (None, None)
+
def _process(self):
#print 'Sending ', str(
self.iq)
self.myAgent.send(
self.iq)
#Wait for the answer
- msg = self._receive(block=True,timeout=self.timeout)
+ msg = self._receive(block=True, timeout=self.timeout)
#print 'Received ', str(msg)
if msg is None:
#Timeout
- self.result = ('error',['timeout'])
+ self.result = ('error', ['timeout'])
return
if msg['type'] == 'error':
errors = []
for error in msg.getTag('error').getChildren():
- if error.getName() == 'text': continue
+ if error.getName() == 'text':
+ continue
errors.append(error.getName())
- self.result = ('error',errors)
+ self.result = ('error', errors)
return
if msg['type'] == 'result':
- self.result = ('ok',self.getContents(msg))
+ self.result = ('ok', self.getContents(msg))
return
- self.result = ('error',['unknown'])
+ self.result = ('error', ['unknown'])
return
-
-
-
def publish(self, node, event=None):
"""
- Publishes an item to a given node.
-
+ Publishes an item to a given node.
+
XXX: 'node' here is not an XML node, but the attribute for
<publish>
@type node: string
@@ -99,14 +99,14 @@
'ok' the name of the created node.
"""
iq = Iq(
- typ='set',
+ typ='set',
queryNS=None,
attrs={},
frm=self._client
- )
+ )
- pubsub_node = Node(tag='pubsub', attrs={'xmlns':NS_PUBSUB})
- publish_node = Node(tag='publish', attrs={'node':node})
+ pubsub_node = Node(tag='pubsub', attrs={'xmlns': NS_PUBSUB})
+ publish_node = Node(tag='publish', attrs={'node': node})
item_node = Node(tag='item')
if event is not None:
item_node.addChild(node=event)
@@ -118,12 +118,9 @@
node_publish = msg.getTag('pubsub').getTag('publish')
#XXX: Server implementation always returns the item id, but
XEP-60 does
# vim snot require it
- return [node_publish['node'],node_publish.getTag('item')['id']]
+ return [node_publish['node'],
node_publish.getTag('item')['id']]
return self._sendAndReceive(iq, getContents)
-
-
-
def subscribe(self, node, server=None, jid=None):
"""
@@ -139,10 +136,10 @@
'ok', an empty list.
"""
-
+
if server is None:
server = self._server
-
+
if jid is None:
jid = self._client
@@ -152,10 +149,10 @@
attrs={},
frm=self._client,
to=server
- )
+ )
- pubsub_node = Node(tag='pubsub', attrs={'xmlns':NS_PUBSUB})
- subscribe_node = Node(tag='subscribe',
attrs={'node':node, 'jid':jid})
+ pubsub_node = Node(tag='pubsub', attrs={'xmlns': NS_PUBSUB})
+ subscribe_node = Node(tag='subscribe', attrs={'node': node, 'jid':
jid})
pubsub_node.addChild(node=subscribe_node)
iq.addChild(node=pubsub_node)
@@ -188,10 +185,10 @@
attrs={},
frm=self._client,
to=server
- )
+ )
- pubsub_node = Node(tag='pubsub', attrs={'xmlns':NS_PUBSUB_OWNER})
- unsubscribe_node = Node(tag='unsubscribe',
attrs={'node':node, 'jid':jid})
+ pubsub_node = Node(tag='pubsub', attrs={'xmlns': NS_PUBSUB_OWNER})
+ unsubscribe_node = Node(tag='unsubscribe', attrs={'node':
node, 'jid': jid})
pubsub_node.addChild(node=unsubscribe_node)
iq.addChild(node=pubsub_node)
return self._sendAndReceive(iq, lambda msg: [])
@@ -225,47 +222,43 @@
attrs={},
frm=self._client,
to=server
- )
-
+ )
- pubsub_node = Node(tag='pubsub', attrs={'xmlns':NS_PUBSUB})
- create_node = Node(tag='create', attrs={} if node is None else
{'node':node})
+ pubsub_node = Node(tag='pubsub', attrs={'xmlns': NS_PUBSUB})
+ create_node = Node(tag='create', attrs={} if node is None else
{'node': node})
pubsub_node.addChild(node=create_node)
iq.addChild(node=pubsub_node)
- if parent is not None or type=='collection' or access is not None:
- field_nodes=[]
+ if parent is not None or type == 'collection' or access is not
None:
+ field_nodes = []
configure_node = Node(tag='configure')
- field_nodes.append(DataField('FORM_TYPE',
NS_PUBSUB+'#node_config','hidden'))
+ field_nodes.append(DataField('FORM_TYPE', NS_PUBSUB
+ '#node_config', 'hidden'))
if parent is not None:
- field_nodes.append(DataField('pubsub#collection',parent))
+ field_nodes.append(DataField('pubsub#collection', parent))
# <field
var='pubsub#collection'><value>announcements</value></field>
if type == 'collection':
-
field_nodes.append(DataField('pubsub#node_type','collection'))
+
field_nodes.append(DataField('pubsub#node_type', 'collection'))
if access is not None:
- field_nodes.append(DataField('pubsub#access_model',access))
- x_node = DataForm(typ='submit',data=field_nodes)
+ field_nodes.append(DataField('pubsub#access_model',
access))
+ x_node = DataForm(typ='submit', data=field_nodes)
configure_node.addChild(x_node)
pubsub_node.addChild(configure_node)
- return self._sendAndReceive(iq, lambda
msg:[msg.getTag('pubsub').getTag('create')['node']])
-
-
+ return self._sendAndReceive(iq, lambda msg:
[msg.getTag('pubsub').getTag('create')['node']])
def createInstantNode(self, server=None, type='leaf', parent=None,
access=None):
"""
Creates an instant node without a name. The server will generate
id.
"""
-
+
if server is None:
server = self._server
-
+
return createNode(self, None, server, type, parent, access)
-
def deleteNode(self, node, server=None):
"""
- Deletes the selected node.
+ Deletes the selected node.
@type node: string
@param node: id of the node to delete
@@ -278,26 +271,22 @@
"""
-
+
#TODO: A method to redirect the subscriptions to the node to
another one COULD be implemented
if server is None:
server = self._server
-
+
iq = Iq(
typ='set',
queryNS=None,
attrs={},
frm=self._client,
to=server,
- )
+ )
- pubsub_node = Node(tag='pubsub', attrs={'xmlns':NS_PUBSUB_OWNER})
- pubsub_node.addChild(name='delete', attrs={'node':node})
+ pubsub_node = Node(tag='pubsub', attrs={'xmlns': NS_PUBSUB_OWNER})
+ pubsub_node.addChild(name='delete', attrs={'node': node})
iq.addChild(node=pubsub_node)
return self._sendAndReceive(iq, lambda msg: [])
-
-
-
-
=======================================
--- /trunk/spade/pygooglechart.py Sat Jun 26 06:49:59 2010
+++ /trunk/spade/pygooglechart.py Fri Nov 23 05:19:16 2012
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
pygooglechart - A complete Python wrapper for the Google Chart API
@@ -37,11 +38,12 @@
reo_colour = re.compile('^([A-Fa-f0-9]{2,2}){3,4}$')
+
def _check_colour(colour):
if not reo_colour.match(colour):
- raise InvalidParametersException('Colours need to be in ' \
- 'RRGGBB or RRGGBBAA format. One of your colours has %s' % \
- colour)
+ raise InvalidParametersException('Colours need to be in '
+ 'RRGGBB or RRGGBBAA format. One
of your colours has %s' %
+ colour)
def _reset_warnings():
@@ -122,7 +124,7 @@
def check_clip(scaled, clipped):
if clipped != scaled:
warnings.warn('One or more of of your data points has been '
- 'clipped because it is out of range.')
+ 'clipped because it is out of range.')
class SimpleData(Data):
@@ -194,8 +196,8 @@
ExtendedData.enc_map[first],
ExtendedData.enc_map[second]))
else:
- raise DataOutOfRangeException( \
- 'Item #%i "%s" is out of range' %
(data.index(value), \
+ raise DataOutOfRangeException(
+ 'Item #%i "%s" is out of range' %
(data.index(value),
value))
encoded_data.append(''.join(sub_data))
return 'chd=e:' + ','.join(encoded_data)
@@ -291,8 +293,8 @@
LINEAR_STRIPES = 'ls'
def __init__(self, width, height, title=None, legend=None,
colours=None,
- auto_scale=True, x_range=None, y_range=None,
- colours_within_series=None):
+ auto_scale=True, x_range=None, y_range=None,
+ colours_within_series=None):
if type(self) == Chart:
raise AbstractClassException('This is an abstract class')
assert(isinstance(width, int))
@@ -350,7 +352,7 @@
if self.legend_position:
url_bits.append('chdlp=%s' % (self.legend_position))
if self.colours:
- url_bits.append('chco=%s' % ','.join(self.colours))
+ url_bits.append('chco=%s' % ','.join(self.colours))
if self.colours_within_series:
url_bits.append('chco=%s' % '|'.join(self.colours_within_series))
ret = self.fill_to_url()
@@ -358,9 +360,9 @@
url_bits.append(ret)
ret = self.axis_to_url()
if ret:
- url_bits.append(ret)
+ url_bits.append(ret)
if self.markers:
- url_bits.append(self.markers_to_url())
+ url_bits.append(self.markers_to_url())
if self.line_styles:
style = []
for index in xrange(max(self.line_styles) + 1):
@@ -381,8 +383,8 @@
opener = urllib2.urlopen(self.get_url())
if opener.headers['content-type'] != 'image/png':
- raise BadContentTypeException('Server responded with a ' \
- 'content-type of %s' % opener.headers['content-type'])
+ raise BadContentTypeException('Server responded with a '
+ 'content-type of %s' %
opener.headers['content-type'])
open(file_name, 'wb').write(opener.read())
@@ -398,7 +400,7 @@
def set_legend(self, legend):
"""legend needs to be a list, tuple or None"""
assert(isinstance(legend, list) or isinstance(legend, tuple) or
- legend is None)
+ legend is None)
if legend:
self.legend = [urllib.quote(a) for a in legend]
else:
@@ -407,7 +409,7 @@
def set_legend_position(self, legend_position):
if legend_position:
self.legend_position = urllib.quote(legend_position)
- else:
+ else:
self.legend_position = None
# Chart colours
@@ -416,7 +418,7 @@
def set_colours(self, colours):
# colours needs to be a list, tuple or None
assert(isinstance(colours, list) or isinstance(colours, tuple) or
- colours is None)
+ colours is None)
# make sure the colours are in the right format
if colours:
for col in colours:
@@ -426,12 +428,12 @@
def set_colours_within_series(self, colours):
# colours needs to be a list, tuple or None
assert(isinstance(colours, list) or isinstance(colours, tuple) or
- colours is None)
+ colours is None)
# make sure the colours are in the right format
if colours:
for col in colours:
_check_colour(col)
- self.colours_within_series = colours
+ self.colours_within_series = colours
# Background/Chart colours
#
-------------------------------------------------------------------------
@@ -471,8 +473,8 @@
areas = []
for area in (Chart.BACKGROUND, Chart.CHART, Chart.ALPHA):
if self.fill_types[area]:
- areas.append('%s,%s,%s' % (area, self.fill_types[area], \
- self.fill_area[area]))
+ areas.append('%s,%s,%s' % (area, self.fill_types[area],
+ self.fill_area[area]))
if areas:
return 'chf=' + '|'.join(areas)
@@ -620,16 +622,16 @@
try:
self.axis[axis_index].set_positions(positions)
except IndexError:
- raise InvalidParametersException('Axis index %i has not been '
\
- 'created' % axis)
+ raise InvalidParametersException('Axis index %i has not been '
+ 'created' % axis)
- def set_axis_style(self, axis_index, colour, font_size=None, \
- alignment=None):
+ def set_axis_style(self, axis_index, colour, font_size=None,
+ alignment=None):
try:
self.axis[axis_index].set_style(colour, font_size, alignment)
except IndexError:
- raise InvalidParametersException('Axis index %i has not been '
\
- 'created' % axis)
+ raise InvalidParametersException('Axis index %i has not been '
+ 'created' % axis)
def axis_to_url(self):
available_axis = []
@@ -665,12 +667,12 @@
# Markers, Ranges and Fill area (chm)
#
-------------------------------------------------------------------------
- def markers_to_url(self):
+ def markers_to_url(self):
return 'chm=%s' % '|'.join([','.join(a) for a in self.markers])
def add_marker(self, index, point, marker_type, colour, size,
priority=0):
- self.markers.append((marker_type, colour, str(index), str(point), \
- str(size), str(priority)))
+ self.markers.append((marker_type, colour, str(index), str(point),
+ str(size), str(priority)))
def add_horizontal_range(self, colour, start, stop):
self.markers.append(('r', colour, '0', str(start), str(stop)))
@@ -679,14 +681,14 @@
self.markers.append(('D', colour, str(data_set), '0', str(size),
str(priority)))
def add_marker_text(self, string, colour, data_set, data_point, size,
priority=0):
- self.markers.append((str(string), colour, str(data_set),
str(data_point), str(size), str(priority)))
+ self.markers.append((str(string), colour, str(data_set),
str(data_point), str(size), str(priority)))
def add_vertical_range(self, colour, start, stop):
self.markers.append(('R', colour, '0', str(start), str(stop)))
def add_fill_range(self, colour, index_start, index_end):
- self.markers.append(('b', colour, str(index_start),
str(index_end), \
- '1'))
+ self.markers.append(('b', colour, str(index_start), str(index_end),
+ '1'))
def add_fill_simple(self, colour):
self.markers.append(('B', colour, '1', '1', '1'))
@@ -694,8 +696,8 @@
# Line styles
#
-------------------------------------------------------------------------
- def set_line_style(self, index, thickness=1, line_segment=None, \
- blank_segment=None):
+ def set_line_style(self, index, thickness=1, line_segment=None,
+ blank_segment=None):
value = []
value.append(str(thickness))
if line_segment:
@@ -706,10 +708,10 @@
# Grid
#
-------------------------------------------------------------------------
- def set_grid(self, x_step, y_step, line_segment=1, \
- blank_segment=0):
- self.grid = '%s,%s,%s,%s' % (x_step, y_step, line_segment, \
- blank_segment)
+ def set_grid(self, x_step, y_step, line_segment=1,
+ blank_segment=0):
+ self.grid = '%s,%s,%s,%s' % (x_step, y_step, line_segment,
+ blank_segment)
class ScatterChart(Chart):
@@ -832,20 +834,20 @@
# Skip 'BarChart.get_url_bits' and call Chart directly so the
parent
# doesn't add "chbh" before we do.
url_bits = BarChart.get_url_bits(self, data_class=data_class,
- skip_chbh=True)
+ skip_chbh=True)
if self.group_spacing is not None:
if self.bar_spacing is None:
- raise InvalidParametersException('Bar spacing is
required ' \
- 'to be set when setting group spacing')
+ raise InvalidParametersException('Bar spacing is required '
+ 'to be set when setting
group spacing')
if self.bar_width is None:
- raise InvalidParametersException('Bar width is required
to ' \
- 'be set when setting bar spacing')
+ raise InvalidParametersException('Bar width is required
to '
+ 'be set when setting bar
spacing')
url_bits.append('chbh=%i,%i,%i'
- % (self.bar_width, self.bar_spacing, self.group_spacing))
+ % (self.bar_width, self.bar_spacing,
self.group_spacing))
elif self.bar_spacing is not None:
if self.bar_width is None:
- raise InvalidParametersException('Bar width is required
to ' \
- 'be set when setting bar spacing')
+ raise InvalidParametersException('Bar width is required
to '
+ 'be set when setting bar
spacing')
url_bits.append('chbh=%i,%i' % (self.bar_width,
self.bar_spacing))
elif self.bar_width:
url_bits.append('chbh=%i' % self.bar_width)
@@ -876,8 +878,8 @@
Chart.__init__(self, *args, **kwargs)
self.pie_labels = []
if self.y_range:
- warnings.warn('y_range is not used with %s.' % \
- (self.__class__.__name__))
+ warnings.warn('y_range is not used with %s.' %
+ (self.__class__.__name__))
def set_pie_labels(self, labels):
self.pie_labels = [urllib.quote(a) for a in labels]
@@ -962,7 +964,7 @@
PieChart.__init__(self, *args, **kwargs)
if self.auto_scale and not self.x_range:
warnings.warn('Please specify an x_range with
GoogleOMeterChart, '
- 'otherwise one arrow will always be at the max.')
+ 'otherwise one arrow will always be at the max.')
def type_to_url(self):
return 'cht=gom'
@@ -1057,10 +1059,9 @@
types = ChartGrammar.get_possible_chart_types()
if chart_type not in types:
raise UnknownChartType('%s is an unknown chart type. Possible '
- 'chart types are %s' % (chart_type, ','.join(types)))
+ 'chart types are %s' %
(chart_type, ','.join(types)))
return globals()[chart_type + 'Chart'](w, h, auto_scale=auto_scale,
- x_range=x_range, y_range=y_range)
+ x_range=x_range,
y_range=y_range)
def download(self):
pass
-
=======================================
***Additional files exist in this changeset.***