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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /*
  2. * Copyright (c) 2006-2015 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.events.ErrorInfoEvent;
  24. import com.dmdirc.parser.interfaces.FakableArgument;
  25. import com.dmdirc.parser.interfaces.FakableSource;
  26. import com.dmdirc.parser.interfaces.Parser;
  27. import com.dmdirc.parser.interfaces.callbacks.CallbackInterface;
  28. import com.dmdirc.parser.interfaces.callbacks.ErrorInfoListener;
  29. import java.lang.annotation.Annotation;
  30. import java.lang.reflect.Constructor;
  31. import java.lang.reflect.InvocationTargetException;
  32. import java.lang.reflect.Method;
  33. import java.util.Date;
  34. import java.util.HashMap;
  35. import java.util.List;
  36. import java.util.Map;
  37. import java.util.concurrent.CopyOnWriteArrayList;
  38. /**
  39. * Superclass for all callback types.
  40. */
  41. public class CallbackObject {
  42. /** The type of callback that this object is operating with. */
  43. protected final Class<? extends CallbackInterface> type;
  44. /** Arraylist for storing callback information related to the callback. */
  45. protected final List<CallbackInterface> callbackInfo
  46. = new CopyOnWriteArrayList<>();
  47. /** Reference to the Parser that owns this callback. */
  48. protected Parser myParser;
  49. /** Reference to the CallbackManager in charge of this callback. */
  50. protected CallbackManager myManager;
  51. /** A map of interfaces to their concrete implementations. */
  52. private final Map<Class<?>, Class<?>> implementationMap;
  53. /**
  54. * Create a new instance of the Callback Object.
  55. *
  56. * @param parser Parser That owns this callback
  57. * @param manager CallbackManager that is in charge of this callback
  58. * @param type The type of callback to use
  59. * @param implementationMap A map of interfaces to their parser-specific
  60. * implementations
  61. * @since 0.6.6
  62. */
  63. public CallbackObject(final Parser parser, final CallbackManager manager,
  64. final Class<? extends CallbackInterface> type,
  65. final Map<Class<?>, Class<?>> implementationMap) {
  66. this.myParser = parser;
  67. this.myManager = manager;
  68. this.type = type;
  69. this.implementationMap = implementationMap;
  70. }
  71. /**
  72. * Add a callback pointer to the appropriate ArrayList.
  73. *
  74. * @param eMethod OBject to callback to.
  75. */
  76. protected final void addCallback(final CallbackInterface eMethod) {
  77. if (!callbackInfo.contains(eMethod)) {
  78. callbackInfo.add(eMethod);
  79. }
  80. }
  81. /**
  82. * Delete a callback pointer from the appropriate ArrayList.
  83. *
  84. * @param eMethod Object that was being called back to.
  85. */
  86. protected final void delCallback(final CallbackInterface eMethod) {
  87. callbackInfo.remove(eMethod);
  88. }
  89. /**
  90. * Call the OnErrorInfo callback.
  91. *
  92. * @param errorInfo ParserError object to pass as error.
  93. */
  94. protected final void callErrorInfo(final ParserError errorInfo) {
  95. myManager.publish(new ErrorInfoEvent(myParser, new Date(), errorInfo));
  96. }
  97. /**
  98. * Add a new callback.
  99. *
  100. * @param eMethod Object to callback to.
  101. */
  102. public void add(final CallbackInterface eMethod) {
  103. addCallback(eMethod);
  104. }
  105. /**
  106. * Remove a callback.
  107. *
  108. * @param eMethod Object to remove callback to.
  109. */
  110. public void del(final CallbackInterface eMethod) {
  111. delCallback(eMethod);
  112. }
  113. /**
  114. * Retrieves the type of callback that this callback object is for.
  115. *
  116. * @return This object's type
  117. * @since 0.6.3m2
  118. */
  119. public Class<? extends CallbackInterface> getType() {
  120. return type;
  121. }
  122. /**
  123. * Actually calls this callback. The specified arguments must match those
  124. * specified in the callback's interface, or an error will be raised.
  125. *
  126. * @param args The arguments to pass to the callback implementation
  127. */
  128. public void call(final Object... args) {
  129. createFakeArgs(args);
  130. for (CallbackInterface iface : callbackInfo) {
  131. try {
  132. type.getMethods()[0].invoke(iface, args);
  133. } catch (SecurityException | IllegalAccessException |
  134. IllegalArgumentException | InvocationTargetException e) {
  135. if (getType().equals(ErrorInfoListener.class)) {
  136. System.out.printf("Exception in onError Callback. [%s]\n", e.getMessage());
  137. e.printStackTrace();
  138. } else {
  139. final ParserError ei = new ParserError(ParserError.ERROR_ERROR,
  140. "Exception in callback (" + e.getMessage() + ")",
  141. myParser.getLastLine());
  142. ei.setException(e);
  143. callErrorInfo(ei);
  144. }
  145. }
  146. }
  147. }
  148. /**
  149. * Replaces all null entries in the specified array with fake values, if the
  150. * corresponding parameter of this callback's type is marked with the
  151. * {@link FakableArgument} annotation. The fake classes are constructed by
  152. * using parameters designated {@link FakableSource}.
  153. *
  154. * @param args The arguments to be faked
  155. */
  156. protected void createFakeArgs(final Object[] args) {
  157. int i = 0;
  158. for (Annotation[] anns : type.getMethods()[0].getParameterAnnotations()) {
  159. for (Annotation ann : anns) {
  160. if (ann.annotationType().equals(FakableArgument.class) && args[i] == null) {
  161. args[i] = getFakeArg(args, type.getMethods()[0].getParameterTypes()[i]);
  162. }
  163. }
  164. i++;
  165. }
  166. }
  167. /**
  168. * Tries to create fake argument of the specified target class, by using
  169. * {@link FakableSource} denoted parameters from the specified arg array.
  170. *
  171. * If an argument is missing, the method attempts to create a fake instance
  172. * by recursing into this method again. Note that this could cause an
  173. * infinite recursion in cases of cyclic dependencies. If recursion fails,
  174. * the constructor is skipped.
  175. *
  176. * If the created object has a <code>setFake(boolean)</code> method, it is
  177. * automatically invoked with an argument of <code>true</code>.
  178. *
  179. * @param args The arguments array to use for sources
  180. * @param target The class that should be constructed
  181. * @return An instance of the target class, or null on failure
  182. */
  183. protected Object getFakeArg(final Object[] args, final Class<?> target) {
  184. final Map<Class<?>, Object> sources = new HashMap<>();
  185. int i = 0;
  186. for (Annotation[] anns : type.getMethods()[0].getParameterAnnotations()) {
  187. for (Annotation ann : anns) {
  188. if (ann.annotationType().equals(FakableSource.class)) {
  189. final Class<?> argType = type.getMethods()[0].getParameterTypes()[i];
  190. sources.put(argType, args[i]);
  191. }
  192. }
  193. i++;
  194. }
  195. final Class<?> actualTarget = getImplementation(target);
  196. for (Constructor<?> ctor : actualTarget.getConstructors()) {
  197. final Object[] params = new Object[ctor.getParameterTypes().length];
  198. i = 0;
  199. Object param;
  200. boolean failed = false;
  201. for (Class<?> needed : ctor.getParameterTypes()) {
  202. boolean found = false;
  203. for (Map.Entry<Class<?>, Object> entry : sources.entrySet()) {
  204. if (entry.getKey().isAssignableFrom(needed)) {
  205. params[i] = entry.getValue();
  206. found = true;
  207. }
  208. }
  209. if (!found) {
  210. param = getFakeArg(args, needed);
  211. if (param == null) {
  212. failed = true;
  213. } else {
  214. params[i] = param;
  215. }
  216. }
  217. i++;
  218. }
  219. if (!failed) {
  220. try {
  221. final Object instance = ctor.newInstance(params);
  222. for (Method method : actualTarget.getMethods()) {
  223. if (method.getName().equals("setFake")
  224. && method.getParameterTypes().length == 1
  225. && method.getParameterTypes()[0].equals(Boolean.TYPE)) {
  226. method.invoke(instance, true);
  227. }
  228. }
  229. return instance;
  230. } catch (InstantiationException | IllegalAccessException |
  231. IllegalArgumentException | InvocationTargetException ex) {
  232. // Do nothing
  233. }
  234. }
  235. }
  236. return null;
  237. }
  238. /**
  239. * Returns the concrete class which should be instantiated if this callback
  240. * object desires an instance of the specified type. Generally, this will
  241. * translate the common interfaces to specific parser-dependent
  242. * implementations.
  243. *
  244. * @param type The type to be instantiated
  245. * @return A concrete implementation of that type
  246. */
  247. protected Class<?> getImplementation(final Class<?> type) {
  248. return implementationMap.containsKey(type) ? implementationMap.get(type) : type;
  249. }
  250. }