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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. * @return if adding succeeded or not.
  161. */
  162. public boolean addCallbackType(final CallbackObject callback) {
  163. if (!callbackHash.containsKey(callback.getType())) {
  164. callbackHash.put(callback.getType(), callback);
  165. return true;
  166. }
  167. return false;
  168. }
  169. /**
  170. * Remove a callback type.
  171. *
  172. * @param callback CallbackObject subclass to remove.
  173. * @return if removal succeeded or not.
  174. */
  175. public boolean delCallbackType(final CallbackObject callback) {
  176. if (callbackHash.containsKey(callback.getType())) {
  177. callbackHash.remove(callback.getType());
  178. return true;
  179. }
  180. return false;
  181. }
  182. /**
  183. * Get reference to callback object.
  184. *
  185. * @param callback Name of type of callback object.
  186. * @return CallbackObject returns the callback object for this type
  187. */
  188. private CallbackObject getCallbackType(final Class<? extends CallbackInterface> callback) {
  189. if (!callbackHash.containsKey(callback)) {
  190. throw new CallbackNotFoundException("Callback not found: " + callback.getName());
  191. }
  192. return callbackHash.get(callback);
  193. }
  194. /**
  195. * Remove all callbacks associated with a specific object.
  196. *
  197. * @param o instance of ICallbackInterface to remove.
  198. */
  199. public void delAllCallback(final CallbackInterface o) {
  200. callbackHash.values().stream()
  201. .filter(cb -> cb != null && cb.getType().isInstance(o))
  202. .forEach(cb -> cb.del(o));
  203. }
  204. /**
  205. * Add all callbacks that this object implements.
  206. *
  207. * @param o instance of ICallbackInterface to add.
  208. */
  209. public void addAllCallback(final CallbackInterface o) {
  210. callbackHash.values().stream()
  211. .filter(cb -> cb != null && cb.getType().isInstance(o))
  212. .forEach(cb -> cb.add(o));
  213. }
  214. /**
  215. * Add a callback.
  216. * This method will throw a CallbackNotFoundException if the callback does not exist.
  217. *
  218. * @param <S> The type of callback
  219. * @param callback Type of callback object
  220. * @param o instance of ICallbackInterface to add.
  221. * @throws CallbackNotFoundException If callback is not found.
  222. * @throws NullPointerException If 'o' is null
  223. */
  224. public <S extends CallbackInterface> void addCallback(
  225. final Class<S> callback, final S o) throws CallbackNotFoundException {
  226. if (o == null) {
  227. throw new NullPointerException("CallbackInterface is null");
  228. }
  229. final CallbackObject cb = getCallbackType(callback);
  230. if (cb != null) {
  231. cb.add(o);
  232. }
  233. }
  234. /**
  235. * Add a callback with a specific target.
  236. * This method will throw a CallbackNotFoundException if the callback does not exist.
  237. *
  238. * @param <S> The type of callback
  239. * @param callback Type of callback object.
  240. * @param o instance of ICallbackInterface to add.
  241. * @param target Parameter to specify that a callback should only fire for specific things
  242. * @throws CallbackNotFoundException If callback is not found.
  243. * @throws NullPointerException If 'o' is null
  244. */
  245. public <S extends CallbackInterface> void addCallback(
  246. final Class<S> callback,
  247. final S o, final String target) throws CallbackNotFoundException {
  248. if (o == null) {
  249. throw new NullPointerException("CallbackInterface is null");
  250. }
  251. ((CallbackObjectSpecific) getCallbackType(callback)).add(o, target);
  252. }
  253. /**
  254. * Add a callback without an exception.
  255. * This should be used if a callback is not essential for execution (ie the DebugOut callback)
  256. *
  257. * @param <S> The type of callback object
  258. * @param callback Type of callback object.
  259. * @param o instance of ICallbackInterface to add.
  260. * @return true/false if the callback was added or not.
  261. */
  262. public <S extends CallbackInterface> boolean addNonCriticalCallback(
  263. final Class<S> callback, final S o) {
  264. try {
  265. addCallback(callback, o);
  266. return true;
  267. } catch (CallbackNotFoundException e) {
  268. return false;
  269. }
  270. }
  271. /**
  272. * Add a callback with a specific target.
  273. * This should be used if a callback is not essential for execution
  274. *
  275. * @param <S> The type of callback
  276. * @param callback Type of callback object.
  277. * @param o instance of ICallbackInterface to add.
  278. * @param target Parameter to specify that a callback should only fire for specific things
  279. * @return true/false if the callback was added or not.
  280. */
  281. public <S extends CallbackInterface> boolean addNonCriticalCallback(
  282. final Class<S> callback, final S o, final String target) {
  283. try {
  284. addCallback(callback, o, target);
  285. return true;
  286. } catch (CallbackNotFoundException e) {
  287. return false;
  288. }
  289. }
  290. /**
  291. * Remove a callback.
  292. *
  293. * @param callback Type of callback object.
  294. * @param o instance of ICallbackInterface to remove.
  295. */
  296. public void delCallback(final Class<? extends CallbackInterface> callback,
  297. final CallbackInterface o) {
  298. getCallbackType(callback).del(o);
  299. }
  300. /**
  301. * Gets a proxy object which can be used to despatch callbacks of the
  302. * specified type. Callers may pass <code>null</code> for the first two
  303. * arguments of any callback, and these will automatically be replaced
  304. * by the relevant Parser instance and the current date.
  305. *
  306. * @param <T> The type of the callback to retrieve
  307. * @param callback The callback to retrieve
  308. * @return A proxy object which can be used to call the specified callback
  309. */
  310. @SuppressWarnings({"unchecked", "rawtypes"})
  311. public <T extends CallbackInterface> T getCallback(final Class<T> callback) {
  312. return (T) Proxy.newProxyInstance(getClass().getClassLoader(),
  313. new Class[]{ callback }, new CallbackHandler(callback));
  314. }
  315. /**
  316. * A Proxy invocation handler for a specified parser callback.
  317. */
  318. private class CallbackHandler implements InvocationHandler {
  319. /** The callback that should be called. */
  320. private final Class<? extends CallbackInterface> callback;
  321. /**
  322. * Creates a new callback handler for the specified callback.
  323. *
  324. * @param callback The callback to handle
  325. */
  326. public CallbackHandler(final Class<? extends CallbackInterface> callback) {
  327. this.callback = callback;
  328. }
  329. @Override
  330. public Object invoke(final Object proxy, final Method method, final Object[] args) {
  331. final Object[] modifiedArgs = new Object[args.length - 2];
  332. System.arraycopy(args, 2, modifiedArgs, 0, args.length - 2);
  333. if (args[1] == null) {
  334. getCallbackType(callback).call(modifiedArgs);
  335. } else {
  336. getCallbackType(callback).call((Date) args[1], modifiedArgs);
  337. }
  338. return null;
  339. }
  340. }
  341. }