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.Filter;
26 import net.pterodactylus.reactor.Query;
27 import net.pterodactylus.reactor.Reaction;
28 import net.pterodactylus.reactor.Trigger;
29 import net.pterodactylus.reactor.states.AbstractState;
31 import org.apache.log4j.Logger;
33 import com.google.common.collect.Maps;
34 import com.google.common.collect.Sets;
35 import com.google.common.util.concurrent.AbstractExecutionThreadService;
36 import com.google.common.util.concurrent.Uninterruptibles;
39 * Reactor main engine.
41 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
43 public class Engine extends AbstractExecutionThreadService {
46 private static final Logger logger = Logger.getLogger(Engine.class);
48 /** All defined reactions. */
49 private final Set<Reaction> reactions = Sets.newHashSet();
51 /** Reaction states. */
52 private final Map<Reaction, ReactionExecution> reactionExecutions = Maps.newHashMap();
59 * Adds the given reaction to this engine.
62 * The reaction to add to this engine
64 @SuppressWarnings("synthetic-access")
65 public void addReaction(Reaction reaction) {
66 reactions.add(reaction);
67 reactionExecutions.put(reaction, new ReactionExecution());
71 // ABSTRACTSERVICE METHODS
81 /* delay if we have no reactions. */
82 if (reactions.isEmpty()) {
83 logger.trace("Sleeping for 1 second while no Reactions available.");
84 Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
88 /* find next reaction. */
89 SortedMap<Long, Reaction> nextReactions = Maps.newTreeMap();
90 for (Reaction reaction : reactions) {
91 ReactionExecution reactionExecution = reactionExecutions.get(reaction);
92 nextReactions.put(reactionExecution.lastExecutionTime() + reaction.updateInterval(), reaction);
94 Reaction nextReaction = nextReactions.get(nextReactions.firstKey());
95 ReactionExecution reactionExecution = reactionExecutions.get(nextReaction);
96 logger.debug(String.format("Next Reaction: %s.", nextReaction));
98 /* wait until the next reaction has to run. */
100 long waitTime = (reactionExecution.lastExecutionTime() + nextReaction.updateInterval()) - System.currentTimeMillis();
101 logger.debug(String.format("Time to wait for next Reaction: %d millseconds.", waitTime));
106 logger.debug(String.format("Waiting for %d milliseconds.", waitTime));
107 TimeUnit.MILLISECONDS.sleep(waitTime);
108 } catch (InterruptedException ie1) {
113 /* are we still running? */
119 reactionExecution.setLastExecutionTime(System.currentTimeMillis());
120 Query query = nextReaction.query();
121 net.pterodactylus.reactor.State state;
123 logger.debug("Querying system...");
124 state = query.state();
125 logger.debug("System queried.");
126 } catch (Throwable t1) {
127 logger.warn("Querying system failed!", t1);
128 state = new AbstractState(t1) {
129 /* no further state. */
132 logger.debug(String.format("State is %s.", state));
134 /* convert states. */
135 for (Filter filter : nextReaction.filters()) {
136 net.pterodactylus.reactor.State newState = filter.filter(state);
137 logger.debug(String.format("Old state is %s, new state is %s.", state, newState));
140 reactionExecution.addState(state);
142 /* only run trigger if we have collected two states. */
143 Trigger trigger = nextReaction.trigger();
144 boolean triggerHit = false;
145 if (reactionExecution.previousState() != null) {
146 logger.debug("Checking Trigger for changes...");
147 triggerHit = trigger.triggers(reactionExecution.currentState(), reactionExecution.previousState());
150 /* run action if trigger was hit. */
151 logger.debug(String.format("Trigger was hit: %s.", triggerHit));
153 logger.info("Executing Action...");
154 nextReaction.action().execute(trigger.trigger());
161 * Stores execution states of a {@link Reaction}.
163 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
165 private static class ReactionExecution {
167 /** The time the reaction was last executed. */
168 private long lastExecutionTime;
170 /** The previous state of the reaction. */
171 private net.pterodactylus.reactor.State previousState;
173 /** The current state of the reaction. */
174 private net.pterodactylus.reactor.State currentState;
181 * Returns the time the reaction was last executed. If the reaction was
182 * not yet executed, this method returns {@code 0}.
184 * @return The last execution time of the reaction (in milliseconds
185 * since Jan 1, 1970 UTC)
187 public long lastExecutionTime() {
188 return lastExecutionTime;
192 * Returns the current state of the reaction. If the reaction was not
193 * yet executed, this method returns {@code null}.
195 * @return The current state of the reaction
197 public net.pterodactylus.reactor.State currentState() {
202 * Returns the previous state of the reaction. If the reaction was not
203 * yet executed at least twice, this method returns {@code null}.
205 * @return The previous state of the reaction
207 public net.pterodactylus.reactor.State previousState() {
208 return previousState;
212 * Sets the last execution time of the reaction.
214 * @param lastExecutionTime
215 * The last execution time of the reaction (in milliseconds
216 * since Jan 1, 1970 UTC)
217 * @return This execution
219 public ReactionExecution setLastExecutionTime(long lastExecutionTime) {
220 this.lastExecutionTime = lastExecutionTime;
229 * Adds the given state as current state and moves the current state
230 * into the previous state.
233 * The new current state
234 * @return This execution
236 public ReactionExecution addState(net.pterodactylus.reactor.State state) {
237 previousState = currentState;
238 currentState = state;