1
2
3
4
5
6 package functional.agent;
7
8 import java.util.Collection;
9 import java.util.HashSet;
10 import java.util.Iterator;
11 import java.util.Set;
12
13 import org.neo.swarm.ApplicationContext;
14 import org.neo.swarm.SwarmContainer;
15
16 /***
17 * Represents an Agent that travels to all ApplicationContexts and displays the set of visited URIs upon exiting.
18 * Note: Mobile agents rely on the AppContextBinding interface to gain a reference to the local application
19 * context, which in turn provides the ability to access all container components and services.
20 * @author navery
21 */
22 public class MobileAgentImpl implements MobileAgent {
23
24 public String name = "MobileAgent";
25 ApplicationContext ac;
26 String currentURI;
27 Set visited = new HashSet();
28
29 /***
30 * Determines where to next..
31 */
32 public void execute() {
33 try {
34 System.out.println("Executing: Agent:" + this.name + " context:" + this.currentURI);
35
36 SwarmContainer container = (SwarmContainer) this.ac.retrieveComponent("container");
37
38
39 Collection appContexts = container.getComponentsOfType(ApplicationContext.class);
40
41
42 Iterator iter = appContexts.iterator();
43 while (iter.hasNext()){
44 ApplicationContext newAC = (ApplicationContext) iter.next();
45 String acID = newAC.getURI();
46 if (!visited.contains(acID)){
47 this.visit(acID, newAC);
48 break;
49 }
50 }
51 System.out.println("Agent exiting = this instance visited:" + this.visited);
52 } catch (Exception e) {
53 e.printStackTrace();
54 }
55 }
56
57 /***
58 * Relocates Agent to the chosen node.
59 * @param newURI
60 */
61 public void visit(String newURI, ApplicationContext newAC) {
62 System.out.println("Agent about to shift to:"+newURI);
63
64 visited.add(newURI);
65
66
67 newAC.addPreConstructedComponent(this.name, this);
68
69
70 MobileAgent remoteAgent = (MobileAgent) newAC.retrieveComponent(this.name);
71
72
73 remoteAgent.execute();
74
75
76 this.ac.removeComponent(this.name);
77 }
78
79
80
81
82 public void bind(ApplicationContext context) {
83 System.out.println("Agent being injected into appContext:"+this.currentURI);
84 this.ac = context;
85 this.currentURI = context.getURI();
86 }
87 }