Use Java 1.8, and its Optional.
[rhynodge.git] / src / main / java / net / pterodactylus / rhynodge / engine / Engine.java
1 /*
2  * Rhynodge - 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.rhynodge.engine;
19
20 import static com.google.common.collect.Maps.newTreeMap;
21 import static java.lang.String.format;
22 import static java.util.Optional.empty;
23 import static java.util.Optional.of;
24
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.Optional;
29 import java.util.SortedMap;
30
31 import net.pterodactylus.rhynodge.Filter;
32 import net.pterodactylus.rhynodge.Query;
33 import net.pterodactylus.rhynodge.Reaction;
34 import net.pterodactylus.rhynodge.Trigger;
35 import net.pterodactylus.rhynodge.states.AbstractState;
36 import net.pterodactylus.rhynodge.states.FailedState;
37 import net.pterodactylus.rhynodge.states.StateManager;
38
39 import com.google.common.util.concurrent.AbstractExecutionThreadService;
40 import org.apache.commons.lang3.tuple.Pair;
41 import org.apache.log4j.Logger;
42
43 /**
44  * Rhynodge main engine.
45  *
46  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
47  */
48 public class Engine extends AbstractExecutionThreadService {
49
50         /** The logger. */
51         private static final Logger logger = Logger.getLogger(Engine.class);
52
53         /** The state manager. */
54         private final StateManager stateManager;
55
56         /** All defined reactions. */
57         /* synchronize on itself. */
58         private final Map<String, Reaction> reactions = new HashMap<String, Reaction>();
59
60         /**
61          * Creates a new engine.
62          *
63          * @param stateManager
64          *            The state manager
65          */
66         public Engine(StateManager stateManager) {
67                 this.stateManager = stateManager;
68         }
69
70         //
71         // ACCESSORS
72         //
73
74         /**
75          * Adds the given reaction to this engine.
76          *
77          * @param name
78          *            The name of the reaction
79          * @param reaction
80          *            The reaction to add to this engine
81          */
82         public void addReaction(String name, Reaction reaction) {
83                 synchronized (reactions) {
84                         reactions.put(name, reaction);
85                         reactions.notifyAll();
86                 }
87         }
88
89         /**
90          * Removes the reaction with the given name.
91          *
92          * @param name
93          *            The name of the reaction to remove
94          */
95         public void removeReaction(String name) {
96                 synchronized (reactions) {
97                         if (!reactions.containsKey(name)) {
98                                 return;
99                         }
100                         reactions.remove(name);
101                         reactions.notifyAll();
102                 }
103         }
104
105         //
106         // ABSTRACTSERVICE METHODS
107         //
108
109         /**
110          * {@inheritDoc}
111          */
112         @Override
113         public void run() {
114                 while (isRunning()) {
115                         Optional<NextReaction> nextReaction = getNextReaction();
116                         if (!nextReaction.isPresent()) {
117                                 continue;
118                         }
119
120                         String reactionName = nextReaction.get().getKey();
121                         logger.debug(format("Next Reaction: %s.", reactionName));
122
123                         /* wait until the next reaction has to run. */
124                         Optional<net.pterodactylus.rhynodge.State> lastState = stateManager.loadLastState(reactionName);
125                         int lastStateFailCount = lastState.isPresent() ? lastState.get().failCount() : 0;
126                         long waitTime = nextReaction.get().getNextTime() - System.currentTimeMillis();
127                         logger.debug(format("Time to wait for next Reaction: %d millseconds.", waitTime));
128                         if (waitTime > 0) {
129                                 waitForNextReactionToStart(nextReaction, waitTime);
130
131                                 /* re-start loop to check for new reactions. */
132                                 continue;
133                         }
134
135                         net.pterodactylus.rhynodge.State state = runReaction(nextReaction, reactionName);
136                         logger.debug(format("State is %s.", state));
137
138                         /* convert states. */
139                         for (Filter filter : nextReaction.get().getReaction().filters()) {
140                                 if (state.success()) {
141                                         state = filter.filter(state);
142                                 }
143                         }
144                         if (!state.success()) {
145                                 state.setFailCount(lastStateFailCount + 1);
146                         }
147                         Optional<net.pterodactylus.rhynodge.State> lastSuccessfulState = stateManager.loadLastSuccessfulState(reactionName);
148
149                         /* merge states. */
150                         boolean triggerHit = false;
151                         Trigger trigger = nextReaction.get().getReaction().trigger();
152                         if (lastSuccessfulState.isPresent() && lastSuccessfulState.get().success() && state.success()) {
153                                 net.pterodactylus.rhynodge.State newState = trigger.mergeStates(lastSuccessfulState.get(), state);
154
155                                 /* save new state. */
156                                 stateManager.saveState(reactionName, newState);
157
158                                 triggerHit = trigger.triggers();
159                         } else {
160                                 /* save first or error state. */
161                                 stateManager.saveState(reactionName, state);
162                         }
163
164                         /* run action if trigger was hit. */
165                         logger.debug(format("Trigger was hit: %s.", triggerHit));
166                         if (triggerHit) {
167                                 logger.info("Executing Action...");
168                                 nextReaction.get().getReaction().action().execute(trigger.output(nextReaction.get().getReaction()));
169                         }
170
171                 }
172         }
173
174         private net.pterodactylus.rhynodge.State runReaction(Optional<NextReaction> nextReaction, String reactionName) {
175                 logger.info(format("Running Query for %s...", reactionName));
176                 Query query = nextReaction.get().getReaction().query();
177                 net.pterodactylus.rhynodge.State state;
178                 try {
179                         logger.debug("Querying system...");
180                         state = query.state();
181                         if (state == null) {
182                                 state = FailedState.INSTANCE;
183                         }
184                         logger.debug("System queried.");
185                 } catch (Throwable t1) {
186                         logger.warn("Querying system failed!", t1);
187                         state = new AbstractState(t1) {
188                         };
189                 }
190                 return state;
191         }
192
193         private void waitForNextReactionToStart(Optional<NextReaction> nextReaction, long waitTime) {
194                 synchronized (reactions) {
195                         try {
196                                 logger.info(format("Waiting until %tc.", nextReaction.get().getNextTime()));
197                                 reactions.wait(waitTime);
198                         } catch (InterruptedException ie1) {
199                                 /* we’re looping! */
200                         }
201                 }
202         }
203
204         private Optional<NextReaction> getNextReaction() {
205                 while (isRunning()) {
206                         synchronized (reactions) {
207                                 if (reactions.isEmpty()) {
208                                         logger.debug("Sleeping while no Reactions available.");
209                                         try {
210                                                 reactions.wait();
211                                         } catch (InterruptedException ie1) {
212                                                 /* ignore, we’re looping anyway. */
213                                         }
214                                         continue;
215                                 }
216                         }
217
218                         /* find next reaction. */
219                         SortedMap<Long, Pair<String, Reaction>> nextReactions = newTreeMap();
220                         synchronized (reactions) {
221                                 for (Entry<String, Reaction> reactionEntry : reactions.entrySet()) {
222                                         Optional<net.pterodactylus.rhynodge.State> state = stateManager.loadLastState(reactionEntry.getKey());
223                                         long stateTime = state.isPresent() ? state.get().time() : 0;
224                                         nextReactions.put(stateTime + reactionEntry.getValue().updateInterval(), Pair.of(reactionEntry.getKey(), reactionEntry.getValue()));
225                                 }
226                                 Pair<String, Reaction> keyReaction = nextReactions.get(nextReactions.firstKey());
227                                 return of(new NextReaction(keyReaction.getKey(), keyReaction.getValue(), nextReactions.firstKey()));
228                         }
229                 }
230                 return empty();
231         }
232
233         private static class NextReaction {
234
235                 private final String key;
236                 private final Reaction reaction;
237                 private final long nextTime;
238
239                 private NextReaction(String key, Reaction reaction, long nextTime) {
240                         this.key = key;
241                         this.reaction = reaction;
242                         this.nextTime = nextTime;
243                 }
244
245                 public String getKey() {
246                         return key;
247                 }
248
249                 public Reaction getReaction() {
250                         return reaction;
251                 }
252
253                 public long getNextTime() {
254                         return nextTime;
255                 }
256
257         }
258
259 }