You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CallbackObject.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /*
  2. * Copyright (c) 2006-2014 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.parser.common;
  23. import com.dmdirc.parser.interfaces.FakableArgument;
  24. import com.dmdirc.parser.interfaces.FakableSource;
  25. import com.dmdirc.parser.interfaces.Parser;
  26. import com.dmdirc.parser.interfaces.callbacks.CallbackInterface;
  27. import com.dmdirc.parser.interfaces.callbacks.ErrorInfoListener;
  28. import java.lang.annotation.Annotation;
  29. import java.lang.reflect.Constructor;
  30. import java.lang.reflect.InvocationTargetException;
  31. import java.lang.reflect.Method;
  32. import java.util.Date;
  33. import java.util.HashMap;
  34. import java.util.List;
  35. import java.util.Map;
  36. import java.util.concurrent.CopyOnWriteArrayList;
  37. /**
  38. * Superclass for all callback types.
  39. */
  40. public class CallbackObject {
  41. /** The type of callback that this object is operating with. */
  42. protected final Class<? extends CallbackInterface> type;
  43. /** Arraylist for storing callback information related to the callback. */
  44. protected final List<CallbackInterface> callbackInfo
  45. = new CopyOnWriteArrayList<>();
  46. /** Reference to the Parser that owns this callback. */
  47. protected Parser myParser;
  48. /** Reference to the CallbackManager in charge of this callback. */
  49. protected CallbackManager myManager;
  50. /** A map of interfaces to their concrete implementations. */
  51. private final Map<Class<?>, Class<?>> implementationMap;
  52. /**
  53. * Create a new instance of the Callback Object.
  54. *
  55. * @param parser Parser That owns this callback
  56. * @param manager CallbackManager that is in charge of this callback
  57. * @param type The type of callback to use
  58. * @param implementationMap A map of interfaces to their parser-specific
  59. * implementations
  60. * @since 0.6.6
  61. */
  62. public CallbackObject(final Parser parser, final CallbackManager manager,
  63. final Class<? extends CallbackInterface> type,
  64. final Map<Class<?>, Class<?>> implementationMap) {
  65. this.myParser = parser;
  66. this.myManager = manager;
  67. this.type = type;
  68. this.implementationMap = implementationMap;
  69. }
  70. /**
  71. * Add a callback pointer to the appropriate ArrayList.
  72. *
  73. * @param eMethod OBject to callback to.
  74. */
  75. protected final void addCallback(final CallbackInterface eMethod) {
  76. if (!callbackInfo.contains(eMethod)) {
  77. callbackInfo.add(eMethod);
  78. }
  79. }
  80. /**
  81. * Delete a callback pointer from the appropriate ArrayList.
  82. *
  83. * @param eMethod Object that was being called back to.
  84. */
  85. protected final void delCallback(final CallbackInterface eMethod) {
  86. callbackInfo.remove(eMethod);
  87. }
  88. /**
  89. * Call the OnErrorInfo callback.
  90. *
  91. * @param errorInfo ParserError object to pass as error.
  92. */
  93. protected final void callErrorInfo(final ParserError errorInfo) {
  94. myManager.getCallback(ErrorInfoListener.class).onErrorInfo(myParser, new Date(), errorInfo);
  95. }
  96. /**
  97. * Add a new callback.
  98. *
  99. * @param eMethod Object to callback to.
  100. */
  101. public void add(final CallbackInterface eMethod) {
  102. addCallback(eMethod);
  103. }
  104. /**
  105. * Remove a callback.
  106. *
  107. * @param eMethod Object to remove callback to.
  108. */
  109. public void del(final CallbackInterface eMethod) {
  110. delCallback(eMethod);
  111. }
  112. /**
  113. * Retrieves the type of callback that this callback object is for.
  114. *
  115. * @return This object's type
  116. * @since 0.6.3m2
  117. */
  118. public Class<? extends CallbackInterface> getType() {
  119. return type;
  120. }
  121. /**
  122. * Actually calls this callback. The specified arguments must match those
  123. * specified in the callback's interface, or an error will be raised.
  124. *
  125. * @param args The arguments to pass to the callback implementation
  126. */
  127. public void call(final Object... args) {
  128. createFakeArgs(args);
  129. for (CallbackInterface iface : callbackInfo) {
  130. try {
  131. type.getMethods()[0].invoke(iface, args);
  132. } catch (SecurityException | IllegalAccessException |
  133. IllegalArgumentException | InvocationTargetException e) {
  134. if (getType().equals(ErrorInfoListener.class)) {
  135. System.out.printf("Exception in onError Callback. [%s]\n", e.getMessage());
  136. e.printStackTrace();
  137. } else {
  138. final ParserError ei = new ParserError(ParserError.ERROR_ERROR,
  139. "Exception in callback (" + e.getMessage() + ")",
  140. myParser.getLastLine());
  141. ei.setException(e);
  142. callErrorInfo(ei);
  143. }
  144. }
  145. }
  146. }
  147. /**
  148. * Replaces all null entries in the specified array with fake values, if the
  149. * corresponding parameter of this callback's type is marked with the
  150. * {@link FakableArgument} annotation. The fake classes are constructed by
  151. * using parameters designated {@link FakableSource}.
  152. *
  153. * @param args The arguments to be faked
  154. */
  155. protected void createFakeArgs(final Object[] args) {
  156. int i = 0;
  157. for (Annotation[] anns : type.getMethods()[0].getParameterAnnotations()) {
  158. for (Annotation ann : anns) {
  159. if (ann.annotationType().equals(FakableArgument.class) && args[i] == null) {
  160. args[i] = getFakeArg(args, type.getMethods()[0].getParameterTypes()[i]);
  161. }
  162. }
  163. i++;
  164. }
  165. }
  166. /**
  167. * Tries to create fake argument of the specified target class, by using
  168. * {@link FakableSource} denoted parameters from the specified arg array.
  169. *
  170. * If an argument is missing, the method attempts to create a fake instance
  171. * by recursing into this method again. Note that this could cause an
  172. * infinite recursion in cases of cyclic dependencies. If recursion fails,
  173. * the constructor is skipped.
  174. *
  175. * If the created object has a <code>setFake(boolean)</code> method, it is
  176. * automatically invoked with an argument of <code>true</code>.
  177. *
  178. * @param args The arguments array to use for sources
  179. * @param target The class that should be constructed
  180. * @return An instance of the target class, or null on failure
  181. */
  182. protected Object getFakeArg(final Object[] args, final Class<?> target) {
  183. final Map<Class<?>, Object> sources = new HashMap<>();
  184. int i = 0;
  185. for (Annotation[] anns : type.getMethods()[0].getParameterAnnotations()) {
  186. for (Annotation ann : anns) {
  187. if (ann.annotationType().equals(FakableSource.class)) {
  188. final Class<?> argType = type.getMethods()[0].getParameterTypes()[i];
  189. sources.put(argType, args[i]);
  190. }
  191. }
  192. i++;
  193. }
  194. final Class<?> actualTarget = getImplementation(target);
  195. for (Constructor<?> ctor : actualTarget.getConstructors()) {
  196. final Object[] params = new Object[ctor.getParameterTypes().length];
  197. i = 0;
  198. Object param;
  199. boolean failed = false;
  200. for (Class<?> needed : ctor.getParameterTypes()) {
  201. boolean found = false;
  202. for (Map.Entry<Class<?>, Object> entry : sources.entrySet()) {
  203. if (entry.getKey().isAssignableFrom(needed)) {
  204. params[i] = entry.getValue();
  205. found = true;
  206. }
  207. }
  208. if (!found) {
  209. param = getFakeArg(args, needed);
  210. if (param == null) {
  211. failed = true;
  212. } else {
  213. params[i] = param;
  214. }
  215. }
  216. i++;
  217. }
  218. if (!failed) {
  219. try {
  220. final Object instance = ctor.newInstance(params);
  221. for (Method method : actualTarget.getMethods()) {
  222. if (method.getName().equals("setFake")
  223. && method.getParameterTypes().length == 1
  224. && method.getParameterTypes()[0].equals(Boolean.TYPE)) {
  225. method.invoke(instance, true);
  226. }
  227. }
  228. return instance;
  229. } catch (InstantiationException | IllegalAccessException |
  230. IllegalArgumentException | InvocationTargetException ex) {
  231. // Do nothing
  232. }
  233. }
  234. }
  235. return null;
  236. }
  237. /**
  238. * Returns the concrete class which should be instantiated if this callback
  239. * object desires an instance of the specified type. Generally, this will
  240. * translate the common interfaces to specific parser-dependent
  241. * implementations.
  242. *
  243. * @param type The type to be instantiated
  244. * @return A concrete implementation of that type
  245. */
  246. protected Class<?> getImplementation(final Class<?> type) {
  247. return implementationMap.containsKey(type) ? implementationMap.get(type) : type;
  248. }
  249. }