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.

CallbackManager.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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.Parser;
  24. import com.dmdirc.parser.interfaces.SpecificCallback;
  25. import com.dmdirc.parser.interfaces.callbacks.*; //NOPMD
  26. import java.lang.reflect.InvocationHandler;
  27. import java.lang.reflect.Method;
  28. import java.lang.reflect.Proxy;
  29. import java.util.Collections;
  30. import java.util.Date;
  31. import java.util.HashMap;
  32. import java.util.Map;
  33. /**
  34. * Parser Callback Manager.
  35. * Manages adding/removing/calling callbacks.
  36. */
  37. public class CallbackManager {
  38. private static final Class<?>[] CLASSES = {
  39. AwayStateListener.class,
  40. OtherAwayStateListener.class,
  41. ChannelOtherAwayStateListener.class,
  42. ChannelActionListener.class,
  43. ChannelCtcpListener.class,
  44. ChannelCtcpReplyListener.class,
  45. ChannelListModeListener.class,
  46. ChannelNamesListener.class,
  47. ChannelJoinListener.class,
  48. ChannelKickListener.class,
  49. ChannelMessageListener.class,
  50. ChannelModeChangeListener.class,
  51. ChannelNickChangeListener.class,
  52. ChannelNonUserModeChangeListener.class,
  53. ChannelModeMessageListener.class,
  54. ChannelModeNoticeListener.class,
  55. ChannelNoticeListener.class,
  56. ChannelPartListener.class,
  57. ChannelQuitListener.class,
  58. ChannelSelfJoinListener.class,
  59. ChannelSingleModeChangeListener.class,
  60. ChannelTopicListener.class,
  61. ChannelUserModeChangeListener.class,
  62. CompositionStateChangeListener.class,
  63. ConnectErrorListener.class,
  64. DataInListener.class,
  65. DataOutListener.class,
  66. DebugInfoListener.class,
  67. ErrorInfoListener.class,
  68. GroupListStartListener.class,
  69. GroupListEntryListener.class,
  70. GroupListEndListener.class,
  71. NetworkDetectedListener.class,
  72. InviteListener.class,
  73. MotdEndListener.class,
  74. MotdLineListener.class,
  75. MotdStartListener.class,
  76. NickChangeListener.class,
  77. NickInUseListener.class,
  78. AuthNoticeListener.class,
  79. NumericListener.class,
  80. PasswordRequiredListener.class,
  81. PingFailureListener.class,
  82. PingSuccessListener.class,
  83. PingSentListener.class,
  84. PrivateActionListener.class,
  85. PrivateCtcpListener.class,
  86. PrivateCtcpReplyListener.class,
  87. PrivateMessageListener.class,
  88. PrivateNoticeListener.class,
  89. QuitListener.class,
  90. ServerErrorListener.class,
  91. ServerReadyListener.class,
  92. SocketCloseListener.class,
  93. UnknownActionListener.class,
  94. UnknownCtcpListener.class,
  95. UnknownCtcpReplyListener.class,
  96. UnknownMessageListener.class,
  97. UnknownNoticeListener.class,
  98. UserModeChangeListener.class,
  99. UserModeDiscoveryListener.class,
  100. WallDesyncListener.class,
  101. WallopListener.class,
  102. WalluserListener.class,
  103. ServerNoticeListener.class,
  104. UnknownServerNoticeListener.class,
  105. };
  106. /** Hashtable used to store the different types of callback known. */
  107. private final Map<Class<? extends CallbackInterface>, CallbackObject> callbackHash
  108. = new HashMap<>();
  109. /** A map of implementations to use for parser interfaces. */
  110. private final Map<Class<?>, Class<?>> implementationMap;
  111. /**
  112. * Constructor to create a CallbackManager.
  113. *
  114. * @param implementationMap A map of implementations to use
  115. */
  116. public CallbackManager(final Map<Class<?>, Class<?>> implementationMap) {
  117. this.implementationMap = Collections.unmodifiableMap(implementationMap);
  118. }
  119. /**
  120. * Initialises this callback manager.
  121. *
  122. * @param parser The parser associated with this CallbackManager
  123. */
  124. public void initialise(final Parser parser) {
  125. for (Class<?> type : CLASSES) {
  126. if (type.isAnnotationPresent(SpecificCallback.class)) {
  127. addCallbackType(getSpecificCallbackObject(parser, type));
  128. } else {
  129. addCallbackType(getCallbackObject(parser, type));
  130. }
  131. }
  132. }
  133. /**
  134. * Retrieves a relevant {@link CallbackObject} for the specified type.
  135. *
  136. * @param parser The parser that this manager belongs to
  137. * @param type The type of callback to create an object for
  138. * @return The relevant CallbackObject
  139. */
  140. protected CallbackObject getCallbackObject(final Parser parser, final Class<?> type) {
  141. return new CallbackObject(parser, this, type.asSubclass(CallbackInterface.class),
  142. implementationMap);
  143. }
  144. /**
  145. * Retrieves a relevant {@link CallbackObjectSpecific} for the specified type.
  146. *
  147. * @param parser The parser that this manager belongs to
  148. * @param type The type of callback to create an object for
  149. * @return The relevant CallbackObject
  150. */
  151. protected CallbackObjectSpecific getSpecificCallbackObject(
  152. final Parser parser, final Class<?> type) {
  153. return new CallbackObjectSpecific(parser, this, type.asSubclass(CallbackInterface.class),
  154. implementationMap);
  155. }
  156. /**
  157. * Add new callback type.
  158. *
  159. * @param callback CallbackObject subclass for the callback.
  160. */
  161. private void addCallbackType(final CallbackObject callback) {
  162. if (!callbackHash.containsKey(callback.getType())) {
  163. callbackHash.put(callback.getType(), callback);
  164. }
  165. }
  166. /**
  167. * Get reference to callback object.
  168. *
  169. * @param callback Name of type of callback object.
  170. * @return CallbackObject returns the callback object for this type
  171. */
  172. private CallbackObject getCallbackType(final Class<? extends CallbackInterface> callback) {
  173. if (!callbackHash.containsKey(callback)) {
  174. throw new CallbackNotFoundException("Callback not found: " + callback.getName());
  175. }
  176. return callbackHash.get(callback);
  177. }
  178. /**
  179. * Remove all callbacks associated with a specific object.
  180. *
  181. * @param o instance of ICallbackInterface to remove.
  182. */
  183. public void delAllCallback(final CallbackInterface o) {
  184. callbackHash.values().stream()
  185. .filter(cb -> cb != null && cb.getType().isInstance(o))
  186. .forEach(cb -> cb.del(o));
  187. }
  188. /**
  189. * Add all callbacks that this object implements.
  190. *
  191. * @param o instance of ICallbackInterface to add.
  192. */
  193. public void addAllCallback(final CallbackInterface o) {
  194. callbackHash.values().stream()
  195. .filter(cb -> cb != null && cb.getType().isInstance(o))
  196. .forEach(cb -> cb.add(o));
  197. }
  198. /**
  199. * Add a callback.
  200. * This method will throw a CallbackNotFoundException if the callback does not exist.
  201. *
  202. * @param <S> The type of callback
  203. * @param callback Type of callback object
  204. * @param o instance of ICallbackInterface to add.
  205. * @throws CallbackNotFoundException If callback is not found.
  206. * @throws NullPointerException If 'o' is null
  207. */
  208. public <S extends CallbackInterface> void addCallback(
  209. final Class<S> callback, final S o) throws CallbackNotFoundException {
  210. if (o == null) {
  211. throw new NullPointerException("CallbackInterface is null");
  212. }
  213. final CallbackObject cb = getCallbackType(callback);
  214. if (cb != null) {
  215. cb.add(o);
  216. }
  217. }
  218. /**
  219. * Add a callback with a specific target.
  220. * This method will throw a CallbackNotFoundException if the callback does not exist.
  221. *
  222. * @param <S> The type of callback
  223. * @param callback Type of callback object.
  224. * @param o instance of ICallbackInterface to add.
  225. * @param target Parameter to specify that a callback should only fire for specific things
  226. * @throws CallbackNotFoundException If callback is not found.
  227. * @throws NullPointerException If 'o' is null
  228. */
  229. public <S extends CallbackInterface> void addCallback(
  230. final Class<S> callback,
  231. final S o, final String target) throws CallbackNotFoundException {
  232. if (o == null) {
  233. throw new NullPointerException("CallbackInterface is null");
  234. }
  235. ((CallbackObjectSpecific) getCallbackType(callback)).add(o, target);
  236. }
  237. /**
  238. * Remove a callback.
  239. *
  240. * @param callback Type of callback object.
  241. * @param o instance of ICallbackInterface to remove.
  242. */
  243. public void delCallback(final Class<? extends CallbackInterface> callback,
  244. final CallbackInterface o) {
  245. getCallbackType(callback).del(o);
  246. }
  247. /**
  248. * Gets a proxy object which can be used to despatch callbacks of the
  249. * specified type. Callers may pass <code>null</code> for the first two
  250. * arguments of any callback, and these will automatically be replaced
  251. * by the relevant Parser instance and the current date.
  252. *
  253. * @param <T> The type of the callback to retrieve
  254. * @param callback The callback to retrieve
  255. * @return A proxy object which can be used to call the specified callback
  256. */
  257. @SuppressWarnings({"unchecked", "rawtypes"})
  258. public <T extends CallbackInterface> T getCallback(final Class<T> callback) {
  259. return (T) Proxy.newProxyInstance(getClass().getClassLoader(),
  260. new Class[]{ callback }, new CallbackHandler(callback));
  261. }
  262. /**
  263. * A Proxy invocation handler for a specified parser callback.
  264. */
  265. private class CallbackHandler implements InvocationHandler {
  266. /** The callback that should be called. */
  267. private final Class<? extends CallbackInterface> callback;
  268. /**
  269. * Creates a new callback handler for the specified callback.
  270. *
  271. * @param callback The callback to handle
  272. */
  273. public CallbackHandler(final Class<? extends CallbackInterface> callback) {
  274. this.callback = callback;
  275. }
  276. @Override
  277. public Object invoke(final Object proxy, final Method method, final Object[] args) {
  278. final Object[] modifiedArgs = new Object[args.length - 2];
  279. System.arraycopy(args, 2, modifiedArgs, 0, args.length - 2);
  280. if (args[1] == null) {
  281. getCallbackType(callback).call(modifiedArgs);
  282. } else {
  283. getCallbackType(callback).call((Date) args[1], modifiedArgs);
  284. }
  285. return null;
  286. }
  287. }
  288. }