Add method to remove reactions.
[rhynodge.git] / src / main / java / net / pterodactylus / reactor / engine / Engine.java
1 /*
2  * Reactor - Engine.java - Copyright © 2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.reactor.engine;
19
20 import java.util.HashMap;
21 import java.util.Map;
22 import java.util.SortedMap;
23
24 import net.pterodactylus.reactor.Filter;
25 import net.pterodactylus.reactor.Query;
26 import net.pterodactylus.reactor.Reaction;
27 import net.pterodactylus.reactor.Trigger;
28 import net.pterodactylus.reactor.states.AbstractState;
29 import net.pterodactylus.reactor.states.FailedState;
30
31 import org.apache.log4j.Logger;
32
33 import com.google.common.collect.Maps;
34 import com.google.common.util.concurrent.AbstractExecutionThreadService;
35
36 /**
37  * Reactor main engine.
38  *
39  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
40  */
41 public class Engine extends AbstractExecutionThreadService {
42
43         /** The logger. */
44         private static final Logger logger = Logger.getLogger(Engine.class);
45
46         /** All defined reactions. */
47         /* synchronize on itself. */
48         private final Map<String, Reaction> reactions = new HashMap<String, Reaction>();
49
50         /** Reaction states. */
51         /* synchronize on reactions. */
52         private final Map<Reaction, ReactionExecution> reactionExecutions = Maps.newHashMap();
53
54         //
55         // ACCESSORS
56         //
57
58         /**
59          * Adds the given reaction to this engine.
60          *
61          * @param name
62          *            The name of the reaction
63          * @param reaction
64          *            The reaction to add to this engine
65          * @throws IllegalStateException
66          *             if the engine already contains a {@link Reaction} with the
67          *             given name
68          */
69         @SuppressWarnings("synthetic-access")
70         public void addReaction(String name, Reaction reaction) {
71                 synchronized (reactions) {
72                         if (reactions.containsKey(name)) {
73                                 throw new IllegalStateException(String.format("Engine already contains a Reaction named “%s!”", name));
74                         }
75                         reactions.put(name, reaction);
76                         reactionExecutions.put(reaction, new ReactionExecution());
77                         reactions.notifyAll();
78                 }
79         }
80
81         /**
82          * Removes the reaction with the given name.
83          *
84          * @param name
85          *            The name of the reaction to remove
86          */
87         public void removeReaction(String name) {
88                 synchronized (reactions) {
89                         if (!reactions.containsKey(name)) {
90                                 return;
91                         }
92                         Reaction reaction = reactions.remove(name);
93                         reactionExecutions.remove(reaction);
94                         reactions.notifyAll();
95                 }
96         }
97
98         //
99         // ABSTRACTSERVICE METHODS
100         //
101
102         /**
103          * {@inheritDoc}
104          */
105         @Override
106         public void run() {
107                 while (isRunning()) {
108
109                         /* delay if we have no reactions. */
110                         synchronized (reactions) {
111                                 if (reactions.isEmpty()) {
112                                         logger.debug("Sleeping while no Reactions available.");
113                                         try {
114                                                 reactions.wait();
115                                         } catch (InterruptedException ie1) {
116                                                 /* ignore, we’re looping anyway. */
117                                         }
118                                         continue;
119                                 }
120                         }
121
122                         /* find next reaction. */
123                         SortedMap<Long, Reaction> nextReactions = Maps.newTreeMap();
124                         Reaction nextReaction;
125                         ReactionExecution reactionExecution;
126                         synchronized (reactions) {
127                                 for (Reaction reaction : reactions.values()) {
128                                         nextReactions.put(reactionExecutions.get(reaction).lastExecutionTime() + reaction.updateInterval(), reaction);
129                                 }
130                                 nextReaction = nextReactions.get(nextReactions.firstKey());
131                                 reactionExecution = reactionExecutions.get(nextReaction);
132                         }
133                         logger.debug(String.format("Next Reaction: %s.", nextReaction));
134
135                         /* wait until the next reaction has to run. */
136                         long waitTime = (reactionExecution.lastExecutionTime() + nextReaction.updateInterval()) - System.currentTimeMillis();
137                         logger.debug(String.format("Time to wait for next Reaction: %d millseconds.", waitTime));
138                         if (waitTime > 0) {
139                                 synchronized (reactions) {
140                                         try {
141                                                 logger.debug(String.format("Waiting for %d milliseconds.", waitTime));
142                                                 reactions.wait(waitTime);
143                                         } catch (InterruptedException ie1) {
144                                                 /* we’re looping! */
145                                         }
146                                 }
147
148                                 /* re-start loop to check for new reactions. */
149                                 continue;
150                         }
151
152                         /* run reaction. */
153                         reactionExecution.setLastExecutionTime(System.currentTimeMillis());
154                         Query query = nextReaction.query();
155                         net.pterodactylus.reactor.State state;
156                         try {
157                                 logger.debug("Querying system...");
158                                 state = query.state();
159                                 if (state == null) {
160                                         state = FailedState.INSTANCE;
161                                 }
162                                 logger.debug("System queried.");
163                         } catch (Throwable t1) {
164                                 logger.warn("Querying system failed!", t1);
165                                 state = new AbstractState(t1) {
166                                         /* no further state. */
167                                 };
168                         }
169                         logger.debug(String.format("State is %s.", state));
170
171                         /* convert states. */
172                         for (Filter filter : nextReaction.filters()) {
173                                 if (state.success()) {
174                                         net.pterodactylus.reactor.State newState = filter.filter(state);
175                                         logger.debug(String.format("Old state is %s, new state is %s.", state, newState));
176                                         state = newState;
177                                 }
178                         }
179                         if (state.success()) {
180                                 reactionExecution.addState(state);
181                         }
182
183                         /* only run trigger if we have collected two states. */
184                         Trigger trigger = nextReaction.trigger();
185                         boolean triggerHit = false;
186                         if ((reactionExecution.previousState() != null) && state.success()) {
187                                 logger.debug("Checking Trigger for changes...");
188                                 triggerHit = trigger.triggers(reactionExecution.currentState(), reactionExecution.previousState());
189                         }
190
191                         /* run action if trigger was hit. */
192                         logger.debug(String.format("Trigger was hit: %s.", triggerHit));
193                         if (triggerHit) {
194                                 logger.info("Executing Action...");
195                                 nextReaction.action().execute(trigger.output());
196                         }
197
198                 }
199         }
200
201         /**
202          * Stores execution states of a {@link Reaction}.
203          *
204          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
205          */
206         private static class ReactionExecution {
207
208                 /** The time the reaction was last executed. */
209                 private long lastExecutionTime;
210
211                 /** The previous state of the reaction. */
212                 private net.pterodactylus.reactor.State previousState;
213
214                 /** The current state of the reaction. */
215                 private net.pterodactylus.reactor.State currentState;
216
217                 //
218                 // ACCESSORS
219                 //
220
221                 /**
222                  * Returns the time the reaction was last executed. If the reaction was
223                  * not yet executed, this method returns {@code 0}.
224                  *
225                  * @return The last execution time of the reaction (in milliseconds
226                  *         since Jan 1, 1970 UTC)
227                  */
228                 public long lastExecutionTime() {
229                         return lastExecutionTime;
230                 }
231
232                 /**
233                  * Returns the current state of the reaction. If the reaction was not
234                  * yet executed, this method returns {@code null}.
235                  *
236                  * @return The current state of the reaction
237                  */
238                 public net.pterodactylus.reactor.State currentState() {
239                         return currentState;
240                 }
241
242                 /**
243                  * Returns the previous state of the reaction. If the reaction was not
244                  * yet executed at least twice, this method returns {@code null}.
245                  *
246                  * @return The previous state of the reaction
247                  */
248                 public net.pterodactylus.reactor.State previousState() {
249                         return previousState;
250                 }
251
252                 /**
253                  * Sets the last execution time of the reaction.
254                  *
255                  * @param lastExecutionTime
256                  *            The last execution time of the reaction (in milliseconds
257                  *            since Jan 1, 1970 UTC)
258                  * @return This execution
259                  */
260                 public ReactionExecution setLastExecutionTime(long lastExecutionTime) {
261                         this.lastExecutionTime = lastExecutionTime;
262                         return this;
263                 }
264
265                 //
266                 // ACTIONS
267                 //
268
269                 /**
270                  * Adds the given state as current state and moves the current state
271                  * into the previous state.
272                  *
273                  * @param state
274                  *            The new current state
275                  * @return This execution
276                  */
277                 public ReactionExecution addState(net.pterodactylus.reactor.State state) {
278                         previousState = currentState;
279                         currentState = state;
280                         return this;
281                 }
282
283         }
284
285 }