[77] | 1 | package com.framsticks.observers; |
---|
| 2 | |
---|
| 3 | import com.framsticks.core.Entity; |
---|
| 4 | import com.framsticks.core.Instance; |
---|
| 5 | import com.framsticks.core.Parameters; |
---|
| 6 | import com.framsticks.core.Program; |
---|
| 7 | import com.framsticks.params.FramsClass; |
---|
| 8 | import com.framsticks.util.Casting; |
---|
| 9 | import org.apache.commons.configuration.Configuration; |
---|
| 10 | import org.apache.log4j.Logger; |
---|
| 11 | |
---|
| 12 | import java.util.*; |
---|
| 13 | |
---|
| 14 | /** |
---|
| 15 | * @author Piotr Sniegowski |
---|
| 16 | */ |
---|
| 17 | public abstract class Observer extends Entity { |
---|
| 18 | |
---|
| 19 | private final static Logger LOGGER = Logger.getLogger(Observer.class.getName()); |
---|
| 20 | |
---|
| 21 | public Observer(Parameters parameters) { |
---|
| 22 | super(parameters); |
---|
| 23 | } |
---|
| 24 | |
---|
| 25 | protected final Map<String, Endpoint> endpoints = new HashMap<String, Endpoint>(); |
---|
| 26 | |
---|
| 27 | protected Endpoint createEndpoint() { |
---|
| 28 | return new Endpoint(); |
---|
| 29 | } |
---|
| 30 | |
---|
| 31 | @Override |
---|
| 32 | protected void configure() { |
---|
| 33 | super.configure(); |
---|
| 34 | for (String name : config.getStringArray("endpoints")) { |
---|
| 35 | if (getEndpoints().containsKey(name)) { |
---|
| 36 | LOGGER.fatal("observer already contains endpoint named: " + name); |
---|
| 37 | continue; |
---|
| 38 | } |
---|
| 39 | Configuration c = config.subset("endpoints." + name); |
---|
| 40 | Parameters p = new Parameters(c.subset("entity"), name, null); |
---|
| 41 | Entity e = Program.configureEntity(p); |
---|
| 42 | Instance i = Casting.tryCast(Instance.class, e); |
---|
| 43 | if (i == null) { |
---|
| 44 | LOGGER.error("failed to create instance: " + p); |
---|
| 45 | continue; |
---|
| 46 | } |
---|
| 47 | i.configurePublic(); |
---|
| 48 | Endpoint endpoint = createEndpoint(); |
---|
| 49 | endpoint.configurePublic(this, i, name); |
---|
| 50 | getEndpoints().put(name, endpoint); |
---|
| 51 | LOGGER.info("instance " + i + " was added to " + Observer.this); |
---|
| 52 | } |
---|
| 53 | } |
---|
| 54 | |
---|
| 55 | @Override |
---|
| 56 | protected void run() { |
---|
| 57 | super.run(); |
---|
| 58 | for (Endpoint e : getEndpoints().values()) { |
---|
| 59 | e.getInstance().start(); |
---|
| 60 | } |
---|
| 61 | } |
---|
| 62 | |
---|
| 63 | |
---|
| 64 | public Map<String, Endpoint> getEndpoints() { |
---|
| 65 | return endpoints; |
---|
| 66 | } |
---|
| 67 | |
---|
| 68 | public static void constructFramsClass(FramsClass.Constructor constructor) { |
---|
| 69 | constructor.method("getEndpoints"); |
---|
| 70 | } |
---|
| 71 | |
---|
| 72 | |
---|
| 73 | } |
---|