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;
20 import java.util.HashMap;
22 import java.util.Map.Entry;
23 import java.util.SortedMap;
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;
30 import net.pterodactylus.reactor.states.FailedState;
31 import net.pterodactylus.reactor.states.StateManager;
33 import org.apache.commons.lang3.tuple.Pair;
34 import org.apache.log4j.Logger;
36 import com.google.common.collect.Maps;
37 import com.google.common.util.concurrent.AbstractExecutionThreadService;
40 * Reactor main engine.
42 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
44 public class Engine extends AbstractExecutionThreadService {
47 private static final Logger logger = Logger.getLogger(Engine.class);
49 /** The state manager. */
50 private final StateManager stateManager = new StateManager("states");
52 /** All defined reactions. */
53 /* synchronize on itself. */
54 private final Map<String, Reaction> reactions = new HashMap<String, Reaction>();
61 * Adds the given reaction to this engine.
64 * The name of the reaction
66 * The reaction to add to this engine
67 * @throws IllegalStateException
68 * if the engine already contains a {@link Reaction} with the
71 public void addReaction(String name, Reaction reaction) {
72 synchronized (reactions) {
73 if (reactions.containsKey(name)) {
74 throw new IllegalStateException(String.format("Engine already contains a Reaction named “%s!”", name));
76 reactions.put(name, reaction);
77 reactions.notifyAll();
82 * Removes the reaction with the given name.
85 * The name of the reaction to remove
87 public void removeReaction(String name) {
88 synchronized (reactions) {
89 if (!reactions.containsKey(name)) {
92 reactions.remove(name);
93 reactions.notifyAll();
98 // ABSTRACTSERVICE METHODS
106 while (isRunning()) {
108 /* delay if we have no reactions. */
109 synchronized (reactions) {
110 if (reactions.isEmpty()) {
111 logger.debug("Sleeping while no Reactions available.");
114 } catch (InterruptedException ie1) {
115 /* ignore, we’re looping anyway. */
121 /* find next reaction. */
122 SortedMap<Long, Pair<String, Reaction>> nextReactions = Maps.newTreeMap();
124 Reaction nextReaction;
125 synchronized (reactions) {
126 for (Entry<String, Reaction> reactionEntry : reactions.entrySet()) {
127 net.pterodactylus.reactor.State state = stateManager.loadState(reactionEntry.getKey());
128 long stateTime = (state != null) ? state.time() : 0;
129 nextReactions.put(stateTime + reactionEntry.getValue().updateInterval(), Pair.of(reactionEntry.getKey(), reactionEntry.getValue()));
131 reactionName = nextReactions.get(nextReactions.firstKey()).getLeft();
132 nextReaction = nextReactions.get(nextReactions.firstKey()).getRight();
134 logger.debug(String.format("Next Reaction: %s.", nextReaction));
136 /* wait until the next reaction has to run. */
137 net.pterodactylus.reactor.State lastState = stateManager.loadState(reactionName);
138 long lastStateTime = (lastState != null) ? lastState.time() : 0;
139 long waitTime = (lastStateTime + nextReaction.updateInterval()) - System.currentTimeMillis();
140 logger.debug(String.format("Time to wait for next Reaction: %d millseconds.", waitTime));
142 synchronized (reactions) {
144 logger.debug(String.format("Waiting for %d milliseconds.", waitTime));
145 reactions.wait(waitTime);
146 } catch (InterruptedException ie1) {
151 /* re-start loop to check for new reactions. */
156 logger.info(String.format("Running Query for %s...", reactionName));
157 Query query = nextReaction.query();
158 net.pterodactylus.reactor.State state;
160 logger.debug("Querying system...");
161 state = query.state();
163 state = FailedState.INSTANCE;
165 logger.debug("System queried.");
166 } catch (Throwable t1) {
167 logger.warn("Querying system failed!", t1);
168 state = new AbstractState(t1) {
169 /* no further state. */
172 logger.debug(String.format("State is %s.", state));
174 /* convert states. */
175 for (Filter filter : nextReaction.filters()) {
176 if (state.success()) {
177 net.pterodactylus.reactor.State newState = filter.filter(state);
178 logger.debug(String.format("Old state is %s, new state is %s.", state, newState));
182 if (state.success()) {
183 stateManager.saveState(reactionName, state);
186 /* only run trigger if we have collected two states. */
187 Trigger trigger = nextReaction.trigger();
188 boolean triggerHit = false;
189 if ((lastState != null) && state.success()) {
190 logger.debug("Checking Trigger for changes...");
191 triggerHit = trigger.triggers(state, lastState);
194 /* run action if trigger was hit. */
195 logger.debug(String.format("Trigger was hit: %s.", triggerHit));
197 logger.info("Executing Action...");
198 nextReaction.action().execute(trigger.output());