View Javadoc

1   /*
2    * The contents of this file are subject to the BT "ZEUS" Open Source
3    * Licence (L77741), Version 1.0 (the "Licence"); you may not use this file
4    * except in compliance with the Licence. You may obtain a copy of the Licence
5    * from $ZEUS_INSTALL/licence.html or alternatively from
6    * http://www.labs.bt.com/projects/agents/zeus/licence.htm
7    *
8    * Except as stated in Clause 7 of the Licence, software distributed under the
9    * Licence is distributed WITHOUT WARRANTY OF ANY KIND, either express or
10   * implied. See the Licence for the specific language governing rights and
11   * limitations under the Licence.
12   *
13   * The Original Code is within the package zeus.*.
14   * The Initial Developer of the Original Code is British Telecommunications
15   * public limited company, whose registered office is at 81 Newgate Street,
16   * London, EC1A 7AJ, England. Portions created by British Telecommunications
17   * public limited company are Copyright 1996-2001. All Rights Reserved.
18   *
19   * THIS NOTICE MUST BE INCLUDED ON ANY COPY OF THIS FILE
20   */
21  package zeus.agents;
22  import zeus.actors.*;
23  import zeus.concepts.*;
24  import java.net.*;
25  import java.util.*;
26  import java.io.*;
27  import java.net.*;
28  import JADE_SL.*;
29  import JADE_SL.lang.sl.*;
30  import JADE_SL.abs.*;
31  import zeus.util.SystemProps;
32  import zeus.actors.intrays.*;
33  
34  
35  /***
36   * FIPA_AMS_Services is used by the ACC agent to wrap the Nameserver
37   * so that it can be accessed exernally.
38   *
39   * Change Log
40   * ----------
41   * 01/03/02 - using JADE_SL parser.
42   */
43  public class FIPA_AMS_Services extends FIPA_Services implements AddressListener{
44      
45      private Hashtable ams_info = new Hashtable();
46      private SLCodec codec = new SLCodec();
47      
48      public void exec(AgentContext context) {
49          this.type = new String("ams");
50          
51          this.context = context;
52       //  System.out.println("trying registration");
53          
54          registerAlias(this.type);
55          AddressBook book = context.getAddressBook(); 
56          book.addAddressListener(this); 
57          setName();
58          setRegister();
59          setDeregister();
60          setModify();
61          setSearch();
62          setGet_description();
63       
64      }
65      
66      
67      
68      
69      public void setGet_description() {
70          MsgHandler handler = context.getMsgHandler();
71          String msg_pattern[] = {"receiver",type,"content","//A(.*)get-description(.*)//Z"};
72          handler.addRule(new MessageRuleImpl(context.newId("Rule"),msg_pattern, this, "handleGet_description"));
73      }
74      
75      
76      
77      /***
78       * not the best thing to do...
79       */
80      private String stripLeadingTrailing(String str) {
81          String retVal = str.substring(1,str.length()-1);
82          System.err.println("retVal is : " +retVal);
83          return retVal;
84      }
85      
86      
87      /***
88       * this ap-description is hard coded to use the ports in Zeus_ACC_Server
89       */
90      public void handleGet_description(Performative perf) {
91        //  System.out.println("handleGet_description in ams called");
92          try {
93              String content = perf.getContent();
94              Performative agree = new Performative("agree");
95              agree.setSender(perf.getReceiver());
96              agree.setReceiver(perf.getSender());
97              FIPA_AMS_Management_Content agreeCont = ZeusParser.FIPA_AMS_Management_Content(content);
98              AbsContentElement slcontent = codec.decode(SLOntology.getInstance(),content);
99              //System.out.println("AMS:parsed content fine");
100             slcontent.dump();
101             
102             //    sendAgree(perf);
103             
104             InetAddress ip = InetAddress.getLocalHost();
105             Performative reply = new Performative("inform");
106             reply.setSender("ams");
107             reply.setReceiver(perf.getSender());
108             FIPA_AP_Description desc = new FIPA_AP_Description();
109             desc.setDynamic(false);
110             desc.setMobility(false);
111             desc.setName(SystemProps.getProperty("HAP.address"));
112             FIPA_Transport_Profile trans = new FIPA_Transport_Profile();
113             FIPA_MTP_Description mtp = new FIPA_MTP_Description();
114             mtp.setMTPName("fipa.mts.mtp.iiop.std");
115             TransportConfig iiop = SystemProps.getTransport ("FIPA_IIOP_2000"); 
116             mtp.addAddress("iiop://" + ip.getHostAddress() +":" + iiop.getPort() +"/acc");
117             trans.addMTPDescription(mtp);
118             FIPA_MTP_Description mtphttp = new FIPA_MTP_Description();
119             mtphttp.setMTPName("fipa.mts.mtp.http.std");
120             TransportConfig http = SystemProps.getTransport ("FIPA_HTTP_2000"); 
121                   mtphttp.addAddress("http://" + ip.getHostAddress() +":" + http.getPort() +"/acc");
122             trans.addMTPDescription(mtphttp);
123             desc.setTransportProfile(trans);
124             reply.setContent("(result " +stripLeadingTrailing(perf.getContent()) + "(set " + desc.toString() +"))");
125             reply.setLanguage("FIPA-SL0");
126             reply.setProtocol("FIPA-Request");
127             reply.setOntology("FIPA-Agent-Management");
128             reply.setConversationId(perf.getConversationId());
129             reply.setInReplyTo(perf.getReplyWith());
130             //System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
131             //System.out.println(reply.toString());
132             //System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
133             
134             reply.send(context); }
135             catch (Exception e) {
136               //  e.printStackTrace();
137                 notUnderstood(perf,"failed");
138             }
139             
140     }
141     
142     public void informDone(Performative perf) {
143         String content = perf.getContent();
144         Performative inform = new Performative("inform");
145         inform.setSender("ams");
146         inform.setReceiver(perf.getSender());
147         inform.setLanguage("FIPA-SL0");
148         inform.setProtocol("FIPA-Request");
149         inform.setOntology("FIPA-Agent-Management");
150         inform.setConversationId(perf.getConversationId());
151         inform.setInReplyTo(perf.getReplyWith());
152         inform.setContent("(done" + content + ")");
153         send(inform);
154     }
155     
156     
157     /***
158      *make an "agree" response in SL
159      **/
160     public void sendAgree(Performative perf) {
161         Performative agree = new Performative("agree");
162         agree.setContent( perf.getContent().substring(0,perf.getContent().length() -1)+"true)");
163         agree.setLanguage("FIPA-SL0");
164         agree.setProtocol("FIPA-Request");
165         agree.setOntology("FIPA-Agent-Management");
166         agree.setConversationId(perf.getConversationId());
167         agree.setInReplyTo(perf.getReplyWith());
168         agree.setReceiver(perf.getSender());
169         agree.setSender("ams");
170         agree.send(context);
171     }
172     
173     /***
174      * method for handleing a registration message to the ams
175      */
176     public void handleRegister(Performative perf) {
177         try {
178             //System.out.println("new handleRegister in ams called");
179             String content = perf.getContent();
180             AbsContentElement slcontent = codec.decode(SLOntology.getInstance(),content);
181             //System.out.println("AMS:parsed content fine");
182             slcontent.dump();
183             AbsAgentAction act = (AbsAgentAction) slcontent.getAbsObject("ACTION");
184             sendAgree(perf);
185             AbsConcept absActor = (AbsConcept) slcontent.getAbsObject("ACTOR");
186             AbsAggregate agentAddresses = (AbsAggregate) absActor.getAbsObject("addresses");
187             AbsPrimitive agentName = (AbsPrimitive) absActor.getAbsObject("name");
188             String addr = SL_Util.makeAddressString(agentName,agentAddresses);
189             ams_info.put(addr, makeDescription(act));
190             informDone(perf);
191         }
192         catch (Exception e) {
193             e.printStackTrace();
194         }
195     }
196     
197     
198     public AMS_Description makeDescription(AbsConcept act) {
199         try {
200             AbsConcept target_descr = (AbsConcept) act.getAbsObject("_SL.UNNAMED0"); // dangerous?
201             AbsConcept desName = (AbsConcept) target_descr.getAbsObject("name");
202             AbsPrimitive targName = (AbsPrimitive) desName.getAbsObject("name");
203             AbsAggregate targAddresses =  (AbsAggregate) desName.getAbsObject("addresses");
204             FIPA_AID_Address agent = new FIPA_AID_Address(SL_Util.makeAddressString(targName, targAddresses));
205             AbsPrimitive targOwnership = (AbsPrimitive) target_descr.getAbsObject("ownership");
206             AbsPrimitive targState = (AbsPrimitive) target_descr.getAbsObject("state");
207             AMS_Description desc = new AMS_Description();
208             desc.setName(agent);
209             if (targOwnership != null) {
210             desc.setOwnership(targOwnership.getString());}
211             if (targState != null) { 
212             desc.setState(targState.getString()); }
213             return (desc);      
214         }
215         catch (Exception e) {
216             // probably an empty param
217           //  e.printStackTrace(); // surpress error!
218             return (null);
219         }
220         
221     }
222     
223     
224     public void  handleDeregister(Performative perf) {
225         //System.out.println("handleDeregister in ams called");
226         try {
227             // parse the content
228             String content = perf.getContent();
229             String agreeCont = new String(content);
230             AbsContentElement slcontent = codec.decode(SLOntology.getInstance(),content);
231             AbsAgentAction act = (AbsAgentAction) slcontent.getAbsObject("ACTION");
232             // check and see if it is a deregistration message, if it is then agree to register,
233             // otherwise send a not understood
234             if (act != null) {
235                 if (act.getTypeName().equalsIgnoreCase("deregister")) {
236                     sendAgree(perf);
237                 }
238                 else {
239                     ;//       simpleReply(perf,UNEXPECTED,"not_understood");
240                 }
241             }
242             OntologyDb ont = context.getOntologyDb();
243             ResourceDb res = context.getResourceDb();
244             Fact agentDesc = ont.getFact(true,"agent");
245             String name = new String();
246             AbsConcept absActor = (AbsConcept) slcontent.getAbsObject("ACTOR");
247             AbsAggregate agentAddresses = (AbsAggregate) absActor.getAbsObject("addresses");
248             AbsPrimitive agentName = (AbsPrimitive) absActor.getAbsObject("name");
249             String searchAddr = SL_Util.makeAddressString(agentName,agentAddresses);
250             Enumeration allAddresses = ams_info.keys();
251             while (allAddresses.hasMoreElements()) {
252                 String current = (String) allAddresses.nextElement();
253                 if (current.equals(searchAddr)) {
254                     ams_info.remove(current);
255                     informDone(perf);
256                     return;
257                 }
258             }
259         } catch (Exception e) {
260             e.printStackTrace();
261         }}
262         
263         
264         
265         
266         
267         public void handleModify(Performative perf) {
268             //System.out.println("handleModify in ams called");
269             try {
270                 Enumeration members = ams_info.elements();
271                 String content = perf.getContent();
272                 FIPA_AMS_Management_Content cont = ZeusParser.FIPA_AMS_Management_Content(content);
273                 AbsContentElement slcontent = codec.decode(SLOntology.getInstance(),content);
274                 //System.out.println("AMS:parsed content fine");
275                 slcontent.dump();
276                 AMS_Description desc = cont.getDescription();
277                 Performative agree = new Performative("agree");
278                 FIPA_AMS_Management_Content agreeCont = ZeusParser.FIPA_AMS_Management_Content(content);
279                 agreeCont.setResult(true);
280                 agree.setSender(perf.getReceiver());
281                 agree.setReceiver(perf.getSender());
282                 agree.setLanguage("FIPA-SL0");
283                 agree.setProtocol("FIPA-Request");
284                 agree.setOntology("FIPA-Agent-Management");
285                 agree.setContent(agreeCont.toString());
286                 agree.setConversationId(perf.getConversationId());
287                 agree.setInReplyTo(perf.getReplyWith());
288                 agree.send(context);
289                 Vector matches = new Vector();
290                 while (members.hasMoreElements()) {
291                     debug("attempting a match");
292                     AMS_Description member = (AMS_Description) members.nextElement();
293                     debug("calling match");
294                     boolean matched = desc.match(member);
295                     debug("matched = " + String.valueOf(matched));
296                     if (matched)
297                         matches.addElement(member);
298                 }
299                 String retVal = new String("(set ");
300                 Enumeration allMatch = matches.elements();
301                 boolean notEmpty = false;
302                 while (allMatch.hasMoreElements()) {
303                     notEmpty = true;
304                     retVal += ((AMS_Description) allMatch.nextElement()).toString() +" ";
305                 }
306                 retVal += " )";
307                 Performative inform = new Performative("inform");
308                 cont.setAction("search");
309                 if (notEmpty) cont.setResult(retVal);
310                 inform.setSender(perf.getReceiver());
311                 inform.setReceiver(perf.getSender());
312                 inform.setLanguage("FIPA-SL0");
313                 inform.setProtocol("FIPA-Request");
314                 inform.setOntology("FIPA-Agent-Management");
315                 inform.setContent(cont.toString());
316                 inform.setConversationId(perf.getConversationId());
317                 inform.setInReplyTo(perf.getReplyWith());
318                 inform.send(context);
319             } catch (Exception e) {
320                 notUnderstood(perf,"failed");
321                 e.printStackTrace(); }
322                 notUnderstood(perf,"(unsupported-act " + perf.getType() +")");
323                 
324         }
325         
326         
327         
328         public void handleSearch(Performative perf) {
329             try {
330                 Enumeration members = ams_info.elements();
331                 String in = perf.getContent();
332                 AbsContentElement slcontent = codec.decode(SLOntology.getInstance(),in);
333                 //System.out.println("AMS:parsed content fine");
334                 slcontent.dump();
335                 AbsAgentAction act = (AbsAgentAction) slcontent.getAbsObject("ACTION");
336                 AMS_Description desc = makeDescription(act);
337                 Performative agree = new Performative("agree");
338                 sendAgree(perf);
339                 Vector matches = new Vector();
340                
341                 while (members.hasMoreElements()) {
342                     debug("attempting a match");
343                     AMS_Description member = (AMS_Description) members.nextElement();
344                     debug("calling match");
345                     if (desc!=null) { 
346                     boolean matched = desc.match(member);
347                     debug("matched = " + String.valueOf(matched));
348                     if (matched)
349                         matches.addElement(member);
350                     }
351                     else matches.addElement(member); 
352                 }
353                 Enumeration allMatch = matches.elements();
354                 boolean notEmpty = false;
355                 String retVal = new String();
356                 while (allMatch.hasMoreElements()) {
357                     notEmpty = true;
358                     retVal += ((AMS_Description) allMatch.nextElement()).toString() +" ";
359                 }
360                 Performative inform = new Performative("inform");
361                 inform.setSender(perf.getReceiver());
362                 inform.setReceiver(perf.getSender());
363                 inform.setLanguage("FIPA-SL0");
364                 inform.setProtocol("FIPA-Request");
365                 inform.setOntology("FIPA-Agent-Management");
366                 String rcontent = new String("((result "+ in.substring(1,in.length()-1) + " (set " );
367                 rcontent += retVal;
368                 rcontent+= ")))";
369                 inform.setContent(rcontent);
370                 inform.setConversationId(perf.getConversationId());
371                 inform.setInReplyTo(perf.getReplyWith());
372                 inform.send(context);
373             } catch (Exception e) {
374                 notUnderstood(perf,"failed");
375                 e.printStackTrace(); }
376                 
377         }
378         
379         
380         
381         public void notUnderstood(Performative inPerf, String reason) {
382             Performative outPerf = new Performative("not-understood");
383             outPerf.setReceiver(inPerf.getSender());
384             outPerf.setSender(inPerf.getReceiver());
385             outPerf.setLanguage("FIPA-SL0");
386             outPerf.setProtocol("FIPA-Request");
387             outPerf.setOntology("FIPA-Agent-Management");
388             String content = inPerf.getContent();
389             FIPA_AMS_Management_Content cont = ZeusParser.FIPA_AMS_Management_Content(content);
390             cont.setResult(reason);
391             outPerf.setContent(cont.toString());
392             
393             
394         }
395         
396         
397         void debug(String str) {
398             //System.out.println("FIPA_AMS_Services : "+ str);
399             ;
400         }
401         
402         public static void main(String argv[]) {
403             
404             FIPA_AMS_Services serv = new FIPA_AMS_Services();
405             serv.debug(serv.stripLeadingTrailing(argv[0]));
406         }
407         
408         public void newAddress(AddressEvent addr) {
409             Address currentAddr = addr.getAddress();
410             String nameStr = new String();
411             InTray serv = context.getMailBox().getInTray(); 
412             try { 
413                 Zeus_ACC_Server server = (Zeus_ACC_Server) serv; 
414             if (currentAddr instanceof zeus.concepts.ZeusAddress) {
415                 String name = currentAddr.getName() +"@"+ zeus.util.SystemProps.getProperty("HAP.address");
416                 nameStr = new String("(agent-identifier :name ");
417                 nameStr += name.toString() +" :addresses (sequence ";
418                 nameStr += server.getResponseAddress(); 
419                 nameStr +="))";
420                 // handle nothing else!
421                 FIPA_AID_Address fAddr = new FIPA_AID_Address(nameStr);
422                 AMS_Description desc = new AMS_Description();
423                 desc.setName(fAddr);
424                 desc.setOwnership("ams@" + SystemProps.getProperty("HAP.address"));
425                 desc.setState("active");
426                // System.out.println("nameStr = " + nameStr); 
427                 //System.out.println("desc = " + desc.toString()); 
428                 ams_info.put(nameStr, desc);
429             }
430             else
431                 return;
432             }catch (Exception e) {
433                 //e.printStackTrace(); 
434                 ;
435             }
436             
437         }
438         
439         public void deleteAddress(AddressEvent addr) {
440             
441             ;
442         }
443         
444         public void replaceAddress(AddressEvent addr) {
445             ;
446         }
447         
448 }