2 * Rhynodge - ChainWatcher.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.rhynodge.loader;
21 import java.io.FilenameFilter;
22 import java.io.IOException;
23 import java.util.HashMap;
24 import java.util.HashSet;
26 import java.util.Map.Entry;
28 import java.util.concurrent.TimeUnit;
30 import net.pterodactylus.rhynodge.Reaction;
31 import net.pterodactylus.rhynodge.engine.Engine;
32 import net.pterodactylus.rhynodge.loader.Chain.Parameter;
33 import net.pterodactylus.rhynodge.loader.Chain.Part;
35 import org.apache.log4j.Logger;
37 import com.fasterxml.jackson.core.JsonParseException;
38 import com.fasterxml.jackson.databind.JsonMappingException;
39 import com.fasterxml.jackson.databind.ObjectMapper;
40 import com.google.common.base.Predicate;
41 import com.google.common.collect.Maps;
42 import com.google.common.util.concurrent.AbstractExecutionThreadService;
43 import com.google.common.util.concurrent.Uninterruptibles;
46 * Watches a directory for chain configuration files and loads and unloads
47 * {@link Reaction}s from the {@link Engine}.
49 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
51 public class ChainWatcher extends AbstractExecutionThreadService {
54 private static final Logger logger = Logger.getLogger(ChainWatcher.class);
56 /** The JSON object mapper. */
57 private static final ObjectMapper objectMapper = new ObjectMapper();
59 /** The reaction loader. */
60 private final ReactionLoader reactionLoader = new ReactionLoader();
62 /** The engine to load reactions with. */
63 private final Engine engine;
65 /** The directory to watch for chain configuration files. */
66 private final String directory;
69 * Creates a new chain watcher.
72 * The engine to load reactions with
74 * The directory to watch
76 public ChainWatcher(Engine engine, String directory) {
78 this.directory = directory;
82 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
89 protected void run() throws Exception {
92 final Map<String, Chain> loadedChains = new HashMap<String, Chain>();
96 /* check if directory is there. */
97 File directoryFile = new File(directory);
98 if (!directoryFile.exists() || !directoryFile.isDirectory() || !directoryFile.canRead()) {
99 Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
103 /* list all files, scan for configuration files. */
104 logger.debug(String.format("Scanning %s...", directory));
105 File[] configurationFiles = directoryFile.listFiles(new FilenameFilter() {
108 public boolean accept(File dir, String name) {
109 return name.endsWith(".json");
112 logger.debug(String.format("Found %d configuration file(s), parsing...", configurationFiles.length));
114 /* now parse all XML files. */
115 Map<String, Chain> chains = new HashMap<String, Chain>();
116 for (File configurationFile : configurationFiles) {
118 /* parse XML file. */
119 Chain chain = parseConfigurationFile(configurationFile);
121 logger.warn(String.format("Could not parse %s.", configurationFile));
126 logger.debug(String.format(" Enabled: %s", chain.enabled()));
128 if (chain.watcher() != null) {
129 logger.debug(String.format("Reaction: %s", chain.watcher().name()));
131 logger.debug(String.format(" Query: %s", chain.query().name()));
132 for (Parameter parameter : chain.query().parameters()) {
133 logger.debug(String.format(" Parameter: %s=%s", parameter.name(), parameter.value()));
135 for (Part filter : chain.filters()) {
136 logger.debug(String.format(" Filter: %s", filter.name()));
137 for (Parameter parameter : filter.parameters()) {
138 logger.debug(String.format(" Parameter: %s=%s", parameter.name(), parameter.value()));
141 logger.debug(String.format(" Trigger: %s", chain.trigger().name()));
142 for (Parameter parameter : chain.trigger().parameters()) {
143 logger.debug(String.format(" Parameter: %s=%s", parameter.name(), parameter.value()));
146 logger.debug(String.format(" Action: %s", chain.action().name()));
147 for (Parameter parameter : chain.action().parameters()) {
148 logger.debug(String.format(" Parameter: %s=%s", parameter.name(), parameter.value()));
151 chains.put(getReactionName(configurationFile.getName()), chain);
154 /* filter enabled chains. */
155 Map<String, Chain> enabledChains = Maps.filterEntries(chains, new Predicate<Entry<String, Chain>>() {
158 public boolean apply(Entry<String, Chain> chainEntry) {
159 return chainEntry.getValue().enabled();
162 logger.debug(String.format("Found %d enabled Chain(s).", enabledChains.size()));
164 /* check for removed chains. */
165 Set<String> chainsToRemove = new HashSet<String>();
166 for (Entry<String, Chain> loadedChain : loadedChains.entrySet()) {
168 /* skip chains that still exist. */
169 if (enabledChains.containsKey(loadedChain.getKey())) {
173 logger.info(String.format("Removing Chain: %s", loadedChain.getKey()));
174 engine.removeReaction(loadedChain.getKey());
175 chainsToRemove.add(loadedChain.getKey());
178 /* remove removed chains from loaded chains. */
179 for (String reactionName : chainsToRemove) {
180 loadedChains.remove(reactionName);
183 /* check for new chains. */
184 for (Entry<String, Chain> enabledChain : enabledChains.entrySet()) {
186 /* skip already loaded chains. */
187 if (loadedChains.containsValue(enabledChain.getValue())) {
191 logger.info(String.format("Loading new Chain: %s", enabledChain.getKey()));
193 Reaction reaction = reactionLoader.loadReaction(enabledChain.getValue());
194 engine.addReaction(enabledChain.getKey(), reaction);
195 loadedChains.put(enabledChain.getKey(), enabledChain.getValue());
198 /* wait before checking again. */
199 Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);
208 * Parses the given configuration file into a {@link Chain}.
210 * @param configurationFile
211 * The configuration file to parse
212 * @return The parsed chain
214 private static Chain parseConfigurationFile(File configurationFile) {
216 return objectMapper.readValue(configurationFile, Chain.class);
217 } catch (JsonParseException jpe1) {
218 logger.warn(String.format("Could not parse %s.", configurationFile), jpe1);
219 } catch (JsonMappingException jme1) {
220 logger.warn(String.format("Could not parse %s.", configurationFile), jme1);
221 } catch (IOException ioe1) {
222 logger.info(String.format("Could not read %s.", configurationFile));
228 * Extracts the name of the reaction from the given filename.
231 * The filename to extract the reaction name from
232 * @return The name of the reaction
234 private static String getReactionName(String filename) {
235 return (filename.lastIndexOf(".") > -1) ? filename.substring(0, filename.lastIndexOf(".")) : filename;