Move XML parsing into its own method.
[rhynodge.git] / src / main / java / net / pterodactylus / reactor / loader / ChainWatcher.java
1 /*
2  * Reactor - ChainWatcher.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.reactor.loader;
19
20 import java.io.File;
21 import java.io.FilenameFilter;
22 import java.util.HashMap;
23 import java.util.Map;
24 import java.util.Map.Entry;
25 import java.util.concurrent.TimeUnit;
26
27 import net.pterodactylus.reactor.Reaction;
28 import net.pterodactylus.reactor.engine.Engine;
29 import net.pterodactylus.reactor.loader.Chain.Parameter;
30 import net.pterodactylus.reactor.loader.Chain.Part;
31
32 import org.apache.log4j.Logger;
33 import org.simpleframework.xml.Serializer;
34 import org.simpleframework.xml.core.Persister;
35
36 import com.google.common.base.Predicate;
37 import com.google.common.collect.Maps;
38 import com.google.common.util.concurrent.AbstractExecutionThreadService;
39 import com.google.common.util.concurrent.Uninterruptibles;
40
41 /**
42  * Watches a directory for chain XML files and loads and unloads
43  * {@link Reaction}s from the {@link Engine}.
44  *
45  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
46  */
47 public class ChainWatcher extends AbstractExecutionThreadService {
48
49         /** The logger. */
50         private static final Logger logger = Logger.getLogger(ChainWatcher.class);
51
52         /** The reaction loader. */
53         private final ReactionLoader reactionLoader = new ReactionLoader();
54
55         /** The engine to load reactions with. */
56         private final Engine engine;
57
58         /** The directory to watch for chain XML files. */
59         private final String directory;
60
61         /**
62          * Creates a new chain watcher.
63          *
64          * @param engine
65          *            The engine to load reactions with
66          * @param directory
67          *            The directory to watch
68          */
69         public ChainWatcher(Engine engine, String directory) {
70                 this.engine = engine;
71                 this.directory = directory;
72         }
73
74         //
75         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
76         //
77
78         /**
79          * {@inheritDoc}
80          */
81         @Override
82         protected void run() throws Exception {
83
84                 /* loaded chains. */
85                 final Map<String, Chain> loadedChains = new HashMap<String, Chain>();
86
87                 while (isRunning()) {
88
89                         /* check if directory is there. */
90                         File directoryFile = new File(directory);
91                         if (!directoryFile.exists() || !directoryFile.isDirectory() || !directoryFile.canRead()) {
92                                 Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
93                                 continue;
94                         }
95
96                         /* list all files, scan for XMLs. */
97                         logger.debug(String.format("Scanning %s...", directory));
98                         File[] xmlFiles = directoryFile.listFiles(new FilenameFilter() {
99
100                                 @Override
101                                 public boolean accept(File dir, String name) {
102                                         return name.endsWith(".xml");
103                                 }
104                         });
105                         logger.debug(String.format("Found %d XML file(s), parsing...", xmlFiles.length));
106
107                         /* now parse all XML files. */
108                         Map<String, Chain> chains = new HashMap<String, Chain>();
109                         for (File xmlFile : xmlFiles) {
110
111                                 /* parse XML file. */
112                                 Chain chain = parseXmlFile(xmlFile);
113
114                                 /* dump chain */
115                                 logger.debug(String.format(" Enabled: %s", chain.enabled()));
116
117                                 logger.debug(String.format(" Query: %s", chain.query().name()));
118                                 for (Parameter parameter : chain.query().parameters()) {
119                                         logger.debug(String.format("  Parameter: %s=%s", parameter.name(), parameter.value()));
120                                 }
121                                 for (Part filter : chain.filters()) {
122                                         logger.debug(String.format(" Filter: %s", filter.name()));
123                                         for (Parameter parameter : filter.parameters()) {
124                                                 logger.debug(String.format("  Parameter: %s=%s", parameter.name(), parameter.value()));
125                                         }
126                                 }
127                                 logger.debug(String.format(" Trigger: %s", chain.trigger().name()));
128                                 for (Parameter parameter : chain.trigger().parameters()) {
129                                         logger.debug(String.format("  Parameter: %s=%s", parameter.name(), parameter.value()));
130                                 }
131                                 logger.debug(String.format(" Action: %s", chain.action().name()));
132                                 for (Parameter parameter : chain.action().parameters()) {
133                                         logger.debug(String.format("  Parameter: %s=%s", parameter.name(), parameter.value()));
134                                 }
135
136                                 chains.put(xmlFile.getName(), chain);
137                         }
138
139                         /* filter enabled chains. */
140                         Map<String, Chain> enabledChains = Maps.filterEntries(chains, new Predicate<Entry<String, Chain>>() {
141
142                                 @Override
143                                 public boolean apply(Entry<String, Chain> chainEntry) {
144                                         return chainEntry.getValue().enabled();
145                                 }
146                         });
147                         logger.debug(String.format("Found %d enabled Chain(s).", enabledChains.size()));
148
149                         /* check for removed chains. */
150                         for (Entry<String, Chain> loadedChain : loadedChains.entrySet()) {
151
152                                 /* skip chains that still exist. */
153                                 if (enabledChains.containsKey(loadedChain.getKey())) {
154                                         continue;
155                                 }
156
157                                 logger.info(String.format("Removing Chain: %s", loadedChain.getKey()));
158                                 engine.removeReaction(loadedChain.getKey());
159                                 loadedChains.remove(loadedChain.getKey());
160                         }
161
162                         /* check for new chains. */
163                         for (Entry<String, Chain> enabledChain : enabledChains.entrySet()) {
164
165                                 /* skip already loaded chains. */
166                                 if (loadedChains.containsValue(enabledChain.getValue())) {
167                                         continue;
168                                 }
169
170                                 logger.info(String.format("Loading new Chain: %s", enabledChain.getKey()));
171
172                                 Reaction reaction = reactionLoader.loadReaction(enabledChain.getValue());
173                                 engine.addReaction(enabledChain.getKey(), reaction);
174                                 loadedChains.put(enabledChain.getKey(), enabledChain.getValue());
175                         }
176
177                         /* wait before checking again. */
178                         Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);
179                 }
180         }
181
182         //
183         // STATIC METHODS
184         //
185
186         /**
187          * Parses the given XML file into a {@link Chain}.
188          *
189          * @param xmlFile
190          *            The XML file to parse
191          * @return The parsed chain
192          */
193         private static Chain parseXmlFile(File xmlFile) {
194                 Serializer serializer = new Persister();
195                 logger.debug(String.format("Reading %s...", xmlFile.getPath()));
196                 return serializer.read(Chain.class, xmlFile);
197         }
198
199 }