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

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