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

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