Add reactor engine.
[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.Map;
21 import java.util.Set;
22 import java.util.SortedMap;
23 import java.util.concurrent.TimeUnit;
24
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
30 import org.apache.log4j.Logger;
31
32 import com.google.common.collect.Maps;
33 import com.google.common.collect.Sets;
34 import com.google.common.util.concurrent.AbstractExecutionThreadService;
35 import com.google.common.util.concurrent.Uninterruptibles;
36
37 /**
38  * Reactor main engine.
39  *
40  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
41  */
42 public class Engine extends AbstractExecutionThreadService {
43
44         /** The logger. */
45         private static final Logger logger = Logger.getLogger(Engine.class);
46
47         /** All defined reactions. */
48         private final Set<Reaction> reactions = Sets.newHashSet();
49
50         /** Reaction states. */
51         private final Map<Reaction, ReactionExecution> reactionExecutions = Maps.newHashMap();
52
53         //
54         // ACCESSORS
55         //
56
57         /**
58          * Adds the given reaction to this engine.
59          *
60          * @param reaction
61          *            The reaction to add to this engine
62          */
63         @SuppressWarnings("synthetic-access")
64         public void addReaction(Reaction reaction) {
65                 reactions.add(reaction);
66                 reactionExecutions.put(reaction, new ReactionExecution());
67         }
68
69         //
70         // ABSTRACTSERVICE METHODS
71         //
72
73         /**
74          * {@inheritDoc}
75          */
76         @Override
77         public void run() {
78                 while (isRunning()) {
79
80                         /* delay if we have no reactions. */
81                         if (reactions.isEmpty()) {
82                                 logger.trace("Sleeping for 1 second while no Reactions available.");
83                                 Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
84                                 continue;
85                         }
86
87                         /* find next reaction. */
88                         SortedMap<Long, Reaction> nextReactions = Maps.newTreeMap();
89                         for (Reaction reaction : reactions) {
90                                 ReactionExecution reactionExecution = reactionExecutions.get(reaction);
91                                 nextReactions.put(reactionExecution.lastExecutionTime() + reaction.updateInterval(), reaction);
92                         }
93                         Reaction nextReaction = nextReactions.get(nextReactions.firstKey());
94                         ReactionExecution reactionExecution = reactionExecutions.get(nextReaction);
95                         logger.debug(String.format("Next Reaction: %s.", nextReaction));
96
97                         /* wait until the next reaction has to run. */
98                         while (isRunning()) {
99                                 long waitTime = (reactionExecution.lastExecutionTime() + nextReaction.updateInterval()) - System.currentTimeMillis();
100                                 logger.debug(String.format("Time to wait for next Reaction: %d millseconds.", waitTime));
101                                 if (waitTime <= 0) {
102                                         break;
103                                 }
104                                 try {
105                                         logger.debug(String.format("Waiting for %d milliseconds.", waitTime));
106                                         TimeUnit.MILLISECONDS.sleep(waitTime);
107                                 } catch (InterruptedException ie1) {
108                                         /* we’re looping! */
109                                 }
110                         }
111
112                         /* are we still running? */
113                         if (!isRunning()) {
114                                 break;
115                         }
116
117                         /* run reaction. */
118                         reactionExecution.setLastExecutionTime(System.currentTimeMillis());
119                         Query query = nextReaction.query();
120                         net.pterodactylus.reactor.State state;
121                         try {
122                                 logger.debug("Querying system...");
123                                 state = query.state();
124                                 logger.debug("System queried.");
125                         } catch (Throwable t1) {
126                                 logger.warn("Querying system failed!", t1);
127                                 state = new AbstractState(t1) {
128                                         /* no further state. */
129                                 };
130                         }
131                         logger.debug(String.format("State is %s.", state));
132                         reactionExecution.addState(state);
133
134                         /* only run trigger if we have collected two states. */
135                         boolean triggerHit = false;
136                         if (reactionExecution.previousState() != null) {
137                                 Trigger trigger = nextReaction.trigger();
138                                 logger.debug("Checking Trigger for changes...");
139                                 triggerHit = trigger.triggers(reactionExecution.currentState(), reactionExecution.previousState());
140                         }
141
142                         /* run action if trigger was hit. */
143                         logger.debug(String.format("Trigger was hit: %s.", triggerHit));
144                         if (triggerHit) {
145                                 logger.info("Executing Action...");
146                                 nextReaction.action().execute(reactionExecution.currentState(), reactionExecution.previousState());
147                         }
148                 }
149         }
150
151         /**
152          * Stores execution states of a {@link Reaction}.
153          *
154          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
155          */
156         private static class ReactionExecution {
157
158                 /** The time the reaction was last executed. */
159                 private long lastExecutionTime;
160
161                 /** The previous state of the reaction. */
162                 private net.pterodactylus.reactor.State previousState;
163
164                 /** The current state of the reaction. */
165                 private net.pterodactylus.reactor.State currentState;
166
167                 //
168                 // ACCESSORS
169                 //
170
171                 /**
172                  * Returns the time the reaction was last executed. If the reaction was
173                  * not yet executed, this method returns {@code 0}.
174                  *
175                  * @return The last execution time of the reaction (in milliseconds
176                  *         since Jan 1, 1970 UTC)
177                  */
178                 public long lastExecutionTime() {
179                         return lastExecutionTime;
180                 }
181
182                 /**
183                  * Returns the current state of the reaction. If the reaction was not
184                  * yet executed, this method returns {@code null}.
185                  *
186                  * @return The current state of the reaction
187                  */
188                 public net.pterodactylus.reactor.State currentState() {
189                         return currentState;
190                 }
191
192                 /**
193                  * Returns the previous state of the reaction. If the reaction was not
194                  * yet executed at least twice, this method returns {@code null}.
195                  *
196                  * @return The previous state of the reaction
197                  */
198                 public net.pterodactylus.reactor.State previousState() {
199                         return previousState;
200                 }
201
202                 /**
203                  * Sets the last execution time of the reaction.
204                  *
205                  * @param lastExecutionTime
206                  *            The last execution time of the reaction (in milliseconds
207                  *            since Jan 1, 1970 UTC)
208                  * @return This execution
209                  */
210                 public ReactionExecution setLastExecutionTime(long lastExecutionTime) {
211                         this.lastExecutionTime = lastExecutionTime;
212                         return this;
213                 }
214
215                 //
216                 // ACTIONS
217                 //
218
219                 /**
220                  * Adds the given state as current state and moves the current state
221                  * into the previous state.
222                  *
223                  * @param state
224                  *            The new current state
225                  * @return This execution
226                  */
227                 public ReactionExecution addState(net.pterodactylus.reactor.State state) {
228                         previousState = currentState;
229                         currentState = state;
230                         return this;
231                 }
232
233         }
234
235 }