Java IRC bot
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.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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.irc.callbacks;
  23. import com.dmdirc.parser.irc.IRCParser;
  24. import com.dmdirc.parser.irc.ParserError;
  25. import com.dmdirc.parser.irc.callbacks.interfaces.ICallbackInterface;
  26. import java.lang.annotation.Annotation;
  27. import java.lang.reflect.Constructor;
  28. import java.lang.reflect.InvocationTargetException;
  29. import java.lang.reflect.Method;
  30. import java.util.ArrayList;
  31. import java.util.HashMap;
  32. import java.util.List;
  33. import java.util.Map;
  34. /**
  35. * CallbackObject.
  36. * Superclass for all callback types.
  37. *
  38. * @author Shane Mc Cormack
  39. */
  40. public class CallbackObject {
  41. /** The type of callback that this object is operating with. */
  42. protected final Class<? extends ICallbackInterface> type;
  43. /** Arraylist for storing callback information related to the callback. */
  44. protected final List<ICallbackInterface> callbackInfo = new ArrayList<ICallbackInterface>();
  45. /** Reference to the IRCParser that owns this callback. */
  46. protected IRCParser myParser;
  47. /** Reference to the CallbackManager in charge of this callback. */
  48. protected CallbackManager myManager;
  49. /**
  50. * Create a new instance of the Callback Object.
  51. *
  52. * @param parser IRCParser That owns this callback
  53. * @param manager CallbackManager that is in charge of this callback
  54. * @param type The type of callback to use
  55. * @since 0.6.3
  56. */
  57. protected CallbackObject(final IRCParser parser, final CallbackManager manager,
  58. final Class<? extends ICallbackInterface> type) {
  59. this.myParser = parser;
  60. this.myManager = manager;
  61. this.type = type;
  62. }
  63. /**
  64. * Add a callback pointer to the appropriate ArrayList.
  65. *
  66. * @param eMethod OBject to callback to.
  67. */
  68. protected final void addCallback(final ICallbackInterface eMethod) {
  69. for (int i = 0; i < callbackInfo.size(); i++) {
  70. if (eMethod.equals(callbackInfo.get(i))) { return; }
  71. }
  72. callbackInfo.add(eMethod);
  73. }
  74. /**
  75. * Delete a callback pointer from the appropriate ArrayList.
  76. *
  77. * @param eMethod Object that was being called back to.
  78. */
  79. protected final void delCallback(final ICallbackInterface eMethod) {
  80. for (int i = 0; i < callbackInfo.size(); i++) {
  81. if (eMethod.equals(callbackInfo.get(i))) { callbackInfo.remove(i); break; }
  82. }
  83. }
  84. /**
  85. * Call the OnErrorInfo callback.
  86. *
  87. * @param errorInfo ParserError object to pass as error.
  88. * @return true if error call succeeded, false otherwise
  89. */
  90. protected final boolean callErrorInfo(final ParserError errorInfo) {
  91. return myManager.getCallbackType("OnErrorInfo").call(errorInfo);
  92. }
  93. /**
  94. * Add a new callback.
  95. *
  96. * @param eMethod Object to callback to.
  97. */
  98. public void add(final ICallbackInterface eMethod) { addCallback(eMethod); }
  99. /**
  100. * Remove a callback.
  101. *
  102. * @param eMethod Object to remove callback to.
  103. */
  104. public void del(final ICallbackInterface eMethod) { delCallback(eMethod); }
  105. /**
  106. * Get the name for this callback.
  107. *
  108. * @return Name of callback
  109. */
  110. public String getName() {
  111. return "On" + type.getSimpleName().substring(1); // Trim the 'I'
  112. }
  113. /**
  114. * Get the name for this callback in lowercase.
  115. *
  116. * @return Name of callback, in lowercase
  117. */
  118. public final String getLowerName() { return this.getName().toLowerCase(); }
  119. /**
  120. * Actually calls this callback. The specified arguments must match those
  121. * specified in the callback's interface, or an error will be raised.
  122. *
  123. * @param args The arguments to pass to the callback implementation
  124. * @return True if a method was called, false otherwise
  125. */
  126. public boolean call(final Object ... args) {
  127. boolean bResult = false;
  128. final Object[] newArgs = new Object[args.length + 1];
  129. System.arraycopy(args, 0, newArgs, 1, args.length);
  130. newArgs[0] = myParser;
  131. if (myParser.getCreateFake()) {
  132. createFakeArgs(newArgs);
  133. }
  134. for (ICallbackInterface iface : new ArrayList<ICallbackInterface>(callbackInfo)) {
  135. try {
  136. type.getMethods()[0].invoke(iface, newArgs);
  137. } catch (Exception e) {
  138. final ParserError ei = new ParserError(ParserError.ERROR_ERROR,
  139. "Exception in callback ("+e.getMessage()+")", myParser.getLastLine());
  140. ei.setException(e);
  141. callErrorInfo(ei);
  142. }
  143. bResult = true;
  144. }
  145. return bResult;
  146. }
  147. /**
  148. * Replaces all null entries in the specified array with fake values,
  149. * if the corresponding parameter of this callback's type is marked with
  150. * the {@link FakableArgument} annotation. The fake classes are constructed
  151. * by 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)
  160. && 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
  177. * is 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<Class, Object>();
  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. sources.put(type.getMethods()[0].getParameterTypes()[i], args[i]);
  190. }
  191. }
  192. i++;
  193. }
  194. for (Constructor<?> ctor : target.getConstructors()) {
  195. Object[] params = new Object[ctor.getParameterTypes().length];
  196. i = 0;
  197. Object param;
  198. boolean failed = false;
  199. for (Class<?> needed : ctor.getParameterTypes()) {
  200. if (sources.containsKey(needed)) {
  201. params[i] = sources.get(needed);
  202. } else if ((param = getFakeArg(args, needed)) != null) {
  203. params[i] = param;
  204. } else {
  205. failed = true;
  206. }
  207. i++;
  208. }
  209. if (!failed) {
  210. try {
  211. final Object instance = ctor.newInstance(params);
  212. for (Method method : target.getMethods()) {
  213. if (method.getName().equals("setFake")
  214. && method.getParameterTypes().length == 1
  215. && method.getParameterTypes()[0].equals(Boolean.TYPE)) {
  216. method.invoke(instance, true);
  217. }
  218. }
  219. return instance;
  220. } catch (InstantiationException ex) {
  221. // Do nothing
  222. } catch (IllegalAccessException ex) {
  223. // Do nothing
  224. } catch (IllegalArgumentException ex) {
  225. // Do nothing
  226. } catch (InvocationTargetException ex) {
  227. // Do nothing
  228. }
  229. }
  230. }
  231. return null;
  232. }
  233. }