2 * Reactor - Engine.java - Copyright © 2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.reactor.engine;
22 import java.util.SortedMap;
23 import java.util.concurrent.TimeUnit;
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;
30 import org.apache.log4j.Logger;
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;
38 * Reactor main engine.
40 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
42 public class Engine extends AbstractExecutionThreadService {
45 private static final Logger logger = Logger.getLogger(Engine.class);
47 /** All defined reactions. */
48 private final Set<Reaction> reactions = Sets.newHashSet();
50 /** Reaction states. */
51 private final Map<Reaction, ReactionExecution> reactionExecutions = Maps.newHashMap();
58 * Adds the given reaction to this engine.
61 * The reaction to add to this engine
63 @SuppressWarnings("synthetic-access")
64 public void addReaction(Reaction reaction) {
65 reactions.add(reaction);
66 reactionExecutions.put(reaction, new ReactionExecution());
70 // ABSTRACTSERVICE METHODS
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);
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);
93 Reaction nextReaction = nextReactions.get(nextReactions.firstKey());
94 ReactionExecution reactionExecution = reactionExecutions.get(nextReaction);
95 logger.debug(String.format("Next Reaction: %s.", nextReaction));
97 /* wait until the next reaction has to run. */
99 long waitTime = (reactionExecution.lastExecutionTime() + nextReaction.updateInterval()) - System.currentTimeMillis();
100 logger.debug(String.format("Time to wait for next Reaction: %d millseconds.", waitTime));
105 logger.debug(String.format("Waiting for %d milliseconds.", waitTime));
106 TimeUnit.MILLISECONDS.sleep(waitTime);
107 } catch (InterruptedException ie1) {
112 /* are we still running? */
118 reactionExecution.setLastExecutionTime(System.currentTimeMillis());
119 Query query = nextReaction.query();
120 net.pterodactylus.reactor.State state;
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. */
131 logger.debug(String.format("State is %s.", state));
132 reactionExecution.addState(state);
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());
142 /* run action if trigger was hit. */
143 logger.debug(String.format("Trigger was hit: %s.", triggerHit));
145 logger.info("Executing Action...");
146 nextReaction.action().execute(reactionExecution.currentState(), reactionExecution.previousState());
152 * Stores execution states of a {@link Reaction}.
154 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
156 private static class ReactionExecution {
158 /** The time the reaction was last executed. */
159 private long lastExecutionTime;
161 /** The previous state of the reaction. */
162 private net.pterodactylus.reactor.State previousState;
164 /** The current state of the reaction. */
165 private net.pterodactylus.reactor.State currentState;
172 * Returns the time the reaction was last executed. If the reaction was
173 * not yet executed, this method returns {@code 0}.
175 * @return The last execution time of the reaction (in milliseconds
176 * since Jan 1, 1970 UTC)
178 public long lastExecutionTime() {
179 return lastExecutionTime;
183 * Returns the current state of the reaction. If the reaction was not
184 * yet executed, this method returns {@code null}.
186 * @return The current state of the reaction
188 public net.pterodactylus.reactor.State currentState() {
193 * Returns the previous state of the reaction. If the reaction was not
194 * yet executed at least twice, this method returns {@code null}.
196 * @return The previous state of the reaction
198 public net.pterodactylus.reactor.State previousState() {
199 return previousState;
203 * Sets the last execution time of the reaction.
205 * @param lastExecutionTime
206 * The last execution time of the reaction (in milliseconds
207 * since Jan 1, 1970 UTC)
208 * @return This execution
210 public ReactionExecution setLastExecutionTime(long lastExecutionTime) {
211 this.lastExecutionTime = lastExecutionTime;
220 * Adds the given state as current state and moves the current state
221 * into the previous state.
224 * The new current state
225 * @return This execution
227 public ReactionExecution addState(net.pterodactylus.reactor.State state) {
228 previousState = currentState;
229 currentState = state;