100e42f763e5958fab3f82483ce301dd25974d34
[rhynodge.git] / src / main / java / net / pterodactylus / rhynodge / loader / ReactionLoader.java
1 /*
2  * Rhynodge - Loader.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.loader;
19
20 import java.lang.reflect.Constructor;
21 import java.lang.reflect.InvocationTargetException;
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.concurrent.TimeUnit;
25
26 import net.pterodactylus.rhynodge.Action;
27 import net.pterodactylus.rhynodge.Filter;
28 import net.pterodactylus.rhynodge.Query;
29 import net.pterodactylus.rhynodge.Reaction;
30 import net.pterodactylus.rhynodge.Trigger;
31 import net.pterodactylus.rhynodge.Watcher;
32 import net.pterodactylus.rhynodge.loader.Chain.Parameter;
33 import net.pterodactylus.rhynodge.loader.Chain.Part;
34
35 /**
36  * Creates {@link Reaction}s from {@link Chain}s.
37  *
38  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
39  */
40 public class ReactionLoader {
41
42         /**
43          * Creates a {@link Reaction} from the given {@link Chain}.
44          *
45          * @param chain
46          *            The chain to create a reaction from
47          * @return The created reaction
48          * @throws LoaderException
49          *             if a class can not be loaded
50          */
51         @SuppressWarnings("static-method")
52         public Reaction loadReaction(Chain chain) throws LoaderException {
53
54                 /* check if chain is enabled. */
55                 if (!chain.enabled()) {
56                         throw new IllegalArgumentException("Chain is not enabled.");
57                 }
58
59                 /* create action. */
60                 Action action = createObject(chain.action().name(), "net.pterodactylus.rhynodge.actions", extractParameters(chain.action().parameters()));
61
62                 /* do we have a reaction defined? */
63                 if (chain.watcher() != null) {
64                         Watcher watcher = createObject(chain.watcher().name(), "net.pterodactylus.rhynodge.watchers", extractParameters(chain.watcher().parameters()));
65                         return new Reaction(chain.name(), watcher.query(), watcher.filters(), watcher.trigger(), action);
66                 }
67
68                 /* create query. */
69                 Query query = createObject(chain.query().name(), "net.pterodactylus.rhynodge.queries", extractParameters(chain.query().parameters()));
70
71                 /* create filters. */
72                 List<Filter> filters = new ArrayList<Filter>();
73                 for (Part filterPart : chain.filters()) {
74                         filters.add(ReactionLoader.<Filter> createObject(filterPart.name(), "net.pterodactylus.rhynodge.filters", extractParameters(filterPart.parameters())));
75                 }
76
77                 /* create trigger. */
78                 Trigger trigger = createObject(chain.trigger().name(), "net.pterodactylus.rhynodge.triggers", extractParameters(chain.trigger().parameters()));
79
80                 return new Reaction(chain.name(), query, filters, trigger, action).setUpdateInterval(TimeUnit.SECONDS.toMillis(chain.updateInterval()));
81         }
82
83         //
84         // STATIC METHODS
85         //
86
87         /**
88          * Extracts all parameter values from the given parameters.
89          *
90          * @param parameters
91          *            The parameters to extract the values from
92          * @return The extracted values
93          */
94         private static List<String> extractParameters(List<Parameter> parameters) {
95                 List<String> parameterValues = new ArrayList<String>();
96
97                 for (Parameter parameter : parameters) {
98                         parameterValues.add(parameter.value());
99                 }
100
101                 return parameterValues;
102         }
103
104         /**
105          * Creates a new object.
106          * <p>
107          * First, {@code className} is used to try to load a {@link Class} with that
108          * name. If that fails, {@code packageName} is prepended to the class name.
109          * If no class can be found, a {@link LoaderException} will be thrown.
110          * <p>
111          * If a class could be located using the described method, a constructor
112          * will be searched that has the same number of {@link String} parameters as
113          * the given parameters. The parameters from the given parameters are then
114          * used in a constructor call to create the new object.
115          *
116          * @param className
117          *            The name of the class
118          * @param packageName
119          *            The optional name of the package to prepend
120          * @param parameters
121          *            The parameters for the constructor call
122          * @return The created object
123          * @throws LoaderException
124          *             if the object can not be created
125          */
126         @SuppressWarnings("unchecked")
127         private static <T> T createObject(String className, String packageName, List<String> parameters) throws LoaderException {
128
129                 /* try to load class without package name. */
130                 Class<?> objectClass = null;
131                 try {
132                         objectClass = Class.forName(className);
133                 } catch (ClassNotFoundException cnfe1) {
134                         /* ignore, we’ll try again. */
135                 }
136
137                 if (objectClass == null) {
138                         try {
139                                 objectClass = Class.forName(packageName + "." + className);
140                         } catch (ClassNotFoundException cnfe1) {
141                                 /* okay, now we need to throw. */
142                                 throw new LoaderException(String.format("Could find neither class “%s” nor class “%s.”", className, packageName + "." + className), cnfe1);
143                         }
144                 }
145
146                 /* locate an eligible constructor. */
147                 Constructor<?> wantedConstructor = null;
148                 for (Constructor<?> constructor : objectClass.getConstructors()) {
149                         Class<?>[] parameterTypes = constructor.getParameterTypes();
150                         if (parameterTypes.length != parameters.size()) {
151                                 continue;
152                         }
153                         boolean compatibleTypes = true;
154                         for (Class<?> parameterType : parameterTypes) {
155                                 if (parameterType != String.class) {
156                                         compatibleTypes = false;
157                                         break;
158                                 }
159                         }
160                         if (!compatibleTypes) {
161                                 continue;
162                         }
163                         wantedConstructor = constructor;
164                 }
165
166                 if (wantedConstructor == null) {
167                         throw new LoaderException("Could not find eligible constructor.");
168                 }
169
170                 try {
171                         return (T) wantedConstructor.newInstance(parameters.toArray());
172                 } catch (IllegalArgumentException iae1) {
173                         throw new LoaderException("Could not invoke constructor.", iae1);
174                 } catch (InstantiationException ie1) {
175                         throw new LoaderException("Could not invoke constructor.", ie1);
176                 } catch (IllegalAccessException iae1) {
177                         throw new LoaderException("Could not invoke constructor.", iae1);
178                 } catch (InvocationTargetException ite1) {
179                         throw new LoaderException("Could not invoke constructor.", ite1);
180                 }
181
182         }
183
184 }