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 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. /*
  2. * Copyright (c) 2006-2013 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<CallbackInterface>();
  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. * @return true if error call succeeded, false otherwise
  93. */
  94. protected final boolean callErrorInfo(final ParserError errorInfo) {
  95. return myManager.getCallbackType(ErrorInfoListener.class).call(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. * @return True if a method was called, false otherwise
  128. */
  129. public boolean call(final Object... args) {
  130. return call(new Date(), args);
  131. }
  132. /**
  133. * Actually calls this callback. The specified arguments must match those
  134. * specified in the callback's interface, or an error will be raised.
  135. *
  136. * @param date The date/time at which the event occured
  137. * @param args The arguments to pass to the callback implementation
  138. * @return True if a method was called, false otherwise
  139. */
  140. public boolean call(final Date date, final Object... args) {
  141. boolean bResult = false;
  142. final Object[] newArgs = new Object[args.length + 2];
  143. System.arraycopy(args, 0, newArgs, 2, args.length);
  144. newArgs[0] = myParser;
  145. newArgs[1] = date;
  146. createFakeArgs(newArgs);
  147. for (CallbackInterface iface : callbackInfo) {
  148. try {
  149. type.getMethods()[0].invoke(iface, newArgs);
  150. } catch (Exception e) {
  151. if (getType().equals(ErrorInfoListener.class)) {
  152. System.out.printf("Exception in onError Callback. [%s]\n", e.getMessage());
  153. e.printStackTrace();
  154. } else {
  155. final ParserError ei = new ParserError(ParserError.ERROR_ERROR,
  156. "Exception in callback (" + e.getMessage() + ")",
  157. myParser.getLastLine());
  158. ei.setException(e);
  159. callErrorInfo(ei);
  160. }
  161. }
  162. bResult = true;
  163. }
  164. return bResult;
  165. }
  166. /**
  167. * Replaces all null entries in the specified array with fake values,
  168. * if the corresponding parameter of this callback's type is marked with
  169. * the {@link FakableArgument} annotation. The fake classes are constructed
  170. * by using parameters designated {@link FakableSource}.
  171. *
  172. * @param args The arguments to be faked
  173. */
  174. protected void createFakeArgs(final Object[] args) {
  175. int i = 0;
  176. for (Annotation[] anns : type.getMethods()[0].getParameterAnnotations()) {
  177. for (Annotation ann : anns) {
  178. if (ann.annotationType().equals(FakableArgument.class) && args[i] == null) {
  179. args[i] = getFakeArg(args, type.getMethods()[0].getParameterTypes()[i]);
  180. }
  181. }
  182. i++;
  183. }
  184. }
  185. /**
  186. * Tries to create fake argument of the specified target class, by using
  187. * {@link FakableSource} denoted parameters from the specified arg array.
  188. *
  189. * If an argument is missing, the method attempts to create a fake instance
  190. * by recursing into this method again. Note that this could cause an
  191. * infinite recursion in cases of cyclic dependencies. If recursion fails,
  192. * the constructor is skipped.
  193. *
  194. * If the created object has a <code>setFake(boolean)</code> method, it
  195. * is automatically invoked with an argument of <code>true</code>.
  196. *
  197. * @param args The arguments array to use for sources
  198. * @param target The class that should be constructed
  199. * @return An instance of the target class, or null on failure
  200. */
  201. protected Object getFakeArg(final Object[] args, final Class<?> target) {
  202. final Map<Class<?>, Object> sources = new HashMap<Class<?>, Object>();
  203. int i = 0;
  204. for (Annotation[] anns : type.getMethods()[0].getParameterAnnotations()) {
  205. for (Annotation ann : anns) {
  206. if (ann.annotationType().equals(FakableSource.class)) {
  207. final Class<?> argType = type.getMethods()[0].getParameterTypes()[i];
  208. sources.put(argType, args[i]);
  209. }
  210. }
  211. i++;
  212. }
  213. final Class<?> actualTarget = getImplementation(target);
  214. for (Constructor<?> ctor : actualTarget.getConstructors()) {
  215. Object[] params = new Object[ctor.getParameterTypes().length];
  216. i = 0;
  217. Object param;
  218. boolean failed = false;
  219. for (Class<?> needed : ctor.getParameterTypes()) {
  220. boolean found = false;
  221. for (Map.Entry<Class<?>, Object> entry : sources.entrySet()) {
  222. if (entry.getKey().isAssignableFrom(needed)) {
  223. params[i] = entry.getValue();
  224. found = true;
  225. }
  226. }
  227. if (!found) {
  228. param = getFakeArg(args, needed);
  229. if (param == null) {
  230. failed = true;
  231. } else {
  232. params[i] = param;
  233. }
  234. }
  235. i++;
  236. }
  237. if (!failed) {
  238. try {
  239. final Object instance = ctor.newInstance(params);
  240. for (Method method : actualTarget.getMethods()) {
  241. if (method.getName().equals("setFake")
  242. && method.getParameterTypes().length == 1
  243. && method.getParameterTypes()[0].equals(Boolean.TYPE)) {
  244. method.invoke(instance, true);
  245. }
  246. }
  247. return instance;
  248. } catch (InstantiationException ex) {
  249. // Do nothing
  250. } catch (IllegalAccessException ex) {
  251. // Do nothing
  252. } catch (IllegalArgumentException ex) {
  253. // Do nothing
  254. } catch (InvocationTargetException ex) {
  255. // Do nothing
  256. }
  257. }
  258. }
  259. return null;
  260. }
  261. /**
  262. * Returns the concrete class which should be instansiated if this
  263. * callback object desires an instance of the specified type. Generally,
  264. * this will translate the common interfaces to specific parser-dependent
  265. * implementations.
  266. *
  267. * @param type The type to be instansiated
  268. * @return A concrete implementation of that type
  269. */
  270. protected Class<?> getImplementation(final Class<?> type) {
  271. return implementationMap.containsKey(type) ? implementationMap.get(type) : type;
  272. }
  273. }