- }
-
- private net.pterodactylus.rhynodge.State runReaction(Optional<NextReaction> nextReaction, String reactionName) {
- logger.info(format("Running Query for %s...", reactionName));
- Query query = nextReaction.get().getReaction().query();
- net.pterodactylus.rhynodge.State state;
- try {
- logger.debug("Querying system...");
- state = query.state();
- if (state == null) {
- state = FailedState.INSTANCE;
- }
- logger.debug("System queried.");
- } catch (Throwable t1) {
- logger.warn("Querying system failed!", t1);
- state = new AbstractState(t1) {
- };
- }
- return state;
- }
-
- private void waitForNextReactionToStart(Optional<NextReaction> nextReaction, long waitTime) {
- synchronized (reactions) {
- try {
- logger.info(format("Waiting until %tc.", nextReaction.get().getNextTime()));
- reactions.wait(waitTime);
- } catch (InterruptedException ie1) {
- /* we’re looping! */
- }
- }
- }
-
- private Optional<NextReaction> getNextReaction() {
- while (isRunning()) {
- synchronized (reactions) {
- if (reactions.isEmpty()) {
- logger.debug("Sleeping while no Reactions available.");
- try {
- reactions.wait();
- } catch (InterruptedException ie1) {
- /* ignore, we’re looping anyway. */
- }
- continue;
- }
- }
-
- /* find next reaction. */
- SortedMap<Long, Pair<String, Reaction>> nextReactions = newTreeMap();
- synchronized (reactions) {
- for (Entry<String, Reaction> reactionEntry : reactions.entrySet()) {
- Optional<net.pterodactylus.rhynodge.State> state = stateManager.loadLastState(reactionEntry.getKey());
- long stateTime = state.isPresent() ? state.get().time() : 0;
- nextReactions.put(stateTime + reactionEntry.getValue().updateInterval(), Pair.of(reactionEntry.getKey(), reactionEntry.getValue()));
- }
- Pair<String, Reaction> keyReaction = nextReactions.get(nextReactions.firstKey());
- return of(new NextReaction(keyReaction.getKey(), keyReaction.getValue(), nextReactions.firstKey()));
- }
- }
- return empty();
- }
-
- private static class NextReaction {
-
- private final String key;
- private final Reaction reaction;
- private final long nextTime;
-
- private NextReaction(String key, Reaction reaction, long nextTime) {
- this.key = key;
- this.reaction = reaction;
- this.nextTime = nextTime;
- }
-
- public String getKey() {
- return key;
- }
-
- public Reaction getReaction() {
- return reaction;
- }
-
- public long getNextTime() {
- return nextTime;
- }
-