1 package cz.cuni.amis.pogamut.defcon.agentmanager;
2
3 import cz.cuni.amis.pogamut.base.agent.IAgentId;
4 import cz.cuni.amis.pogamut.base.agent.impl.AgentId;
5 import cz.cuni.amis.pogamut.base.agent.params.impl.AgentParameters;
6 import cz.cuni.amis.pogamut.base.factory.guice.GuiceAgentFactory;
7 import cz.cuni.amis.pogamut.defcon.agent.DefConAgent;
8 import cz.cuni.amis.pogamut.defcon.agentmanager.exception.CantInstantiateAgentException;
9 import cz.cuni.amis.pogamut.defcon.agentmanager.exception.ModuleForAgentClassNotFoundException;
10 import cz.cuni.amis.pogamut.defcon.factory.DefConAgentModule;
11
12
13
14
15
16
17
18 public class DefConAgentManager {
19
20 private static final DefConAgentManager instance = new DefConAgentManager();
21
22 public static DefConAgentManager getInstance() {
23 return instance;
24 }
25
26 private DefConAgentManager() {
27 }
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42 public <T extends DefConAgent<?>> T getAgentInstance(
43 Class<? extends DefConAgentModule> cls)
44 throws CantInstantiateAgentException,
45 ModuleForAgentClassNotFoundException {
46
47 DefConAgentModule module;
48 try {
49 module = cls.newInstance();
50 } catch (InstantiationException e1) {
51 throw new CantInstantiateAgentException(e1.getMessage(), this);
52 } catch (IllegalAccessException e1) {
53 throw new ModuleForAgentClassNotFoundException(e1.getMessage(),
54 this);
55 }
56
57 try {
58 AgentParameters params = new AgentParameters();
59 IAgentId id = params.setAgentId(new AgentId("DefConBot"))
60 .getAgentId();
61 module.newBindings(id);
62 GuiceAgentFactory<DefConAgent, AgentParameters> factory =
63 new GuiceAgentFactory<DefConAgent, AgentParameters>(module);
64 return (T) factory.newAgent(params);
65 } catch (Exception e) {
66 throw new CantInstantiateAgentException("Instantiation of "
67 + cls.getName() + " agent failed.", e, this);
68 }
69 }
70
71
72
73
74
75
76
77
78
79
80
81
82
83 public DefConAgent getAgentInstance(String className)
84 throws CantInstantiateAgentException,
85 ModuleForAgentClassNotFoundException {
86 Class cls;
87 try {
88 cls = Class.forName(className);
89 } catch (ClassNotFoundException e) {
90 throw new IllegalArgumentException("Class " + className
91 + " not found.");
92 }
93 if (!DefConAgent.class.isAssignableFrom(cls)) {
94 throw new IllegalArgumentException(className
95 + " is not subclass od AbstractDefConAgent");
96 }
97 return getAgentInstance(cls);
98 }
99
100 }