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.

DynamicRequestHandler.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /*
  2. * Copyright (c) 2006-2011 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.addons.ui_web;
  23. import com.dmdirc.Channel;
  24. import com.dmdirc.Server;
  25. import com.dmdirc.addons.ui_web.uicomponents.WebInputHandler;
  26. import com.dmdirc.addons.ui_web.uicomponents.WebInputWindow;
  27. import com.dmdirc.addons.ui_web.uicomponents.WebWindow;
  28. import com.dmdirc.config.Identity;
  29. import com.dmdirc.config.IdentityManager;
  30. import com.dmdirc.parser.common.ChannelJoinRequest;
  31. import com.dmdirc.parser.interfaces.ChannelClientInfo;
  32. import java.io.IOException;
  33. import java.net.URI;
  34. import java.net.URISyntaxException;
  35. import java.util.ArrayList;
  36. import java.util.HashMap;
  37. import java.util.List;
  38. import java.util.Map;
  39. import java.util.Timer;
  40. import java.util.TimerTask;
  41. import javax.servlet.http.HttpServletRequest;
  42. import javax.servlet.http.HttpServletResponse;
  43. import org.mortbay.jetty.HttpConnection;
  44. import org.mortbay.jetty.Request;
  45. import org.mortbay.jetty.handler.AbstractHandler;
  46. import org.mortbay.util.ajax.Continuation;
  47. import org.mortbay.util.ajax.ContinuationSupport;
  48. import org.mortbay.util.ajax.JSON;
  49. import org.mortbay.util.ajax.JSONObjectConvertor;
  50. /**
  51. * Handles requests for dynamic resources (prefixed with /dynamic/).
  52. *
  53. * @author chris
  54. */
  55. public class DynamicRequestHandler extends AbstractHandler {
  56. /** Number of milliseconds before a client is timed out. */
  57. private static final long TIMEOUT = 1000 * 60 * 2; // Two minutes
  58. /** The last time each client was seen. */
  59. private static final Map<String, Client> CLIENTS
  60. = new HashMap<String, Client>();
  61. /** The controller which owns this request handler. */
  62. private final WebInterfaceUI controller;
  63. /**
  64. * Creates a new instance of DynamicRequestHandler. Registers object
  65. * convertors with the JSON serialiser.
  66. */
  67. public DynamicRequestHandler(final WebInterfaceUI controller) {
  68. super();
  69. this.controller = controller;
  70. JSON.registerConvertor(Event.class, new JSONObjectConvertor());
  71. JSON.registerConvertor(WebWindow.class, new JSONObjectConvertor());
  72. JSON.registerConvertor(Message.class, new JSONObjectConvertor());
  73. JSON.registerConvertor(Client.class, new JSONObjectConvertor());
  74. new Timer().schedule(new TimerTask() {
  75. @Override
  76. public void run() {
  77. synchronized (CLIENTS) {
  78. for (Map.Entry<String, Client> entry
  79. : new HashMap<String, Client>(CLIENTS).entrySet()) {
  80. if (entry.getValue().getTime() > TIMEOUT) {
  81. CLIENTS.remove(entry.getKey());
  82. }
  83. }
  84. }
  85. }
  86. }, ERROR, ERROR);
  87. }
  88. /**
  89. * {@inheritDoc}
  90. *
  91. * @throws IOException If unable to write response
  92. */
  93. @Override
  94. public void handle(final String target, final HttpServletRequest request,
  95. final HttpServletResponse response, final int dispatch)
  96. throws IOException {
  97. if (request.getParameter("clientID") != null) {
  98. final String clientID = request.getParameter("clientID");
  99. if (!CLIENTS.containsKey(clientID)) {
  100. CLIENTS.put(clientID, new Client(controller,
  101. request.getRemoteHost()));
  102. }
  103. synchronized (CLIENTS) {
  104. CLIENTS.get(clientID).touch();
  105. }
  106. }
  107. if (((request instanceof Request) ? (Request) request : HttpConnection
  108. .getCurrentConnection().getRequest()).isHandled()) {
  109. return;
  110. }
  111. if (target.equals("/dynamic/feed")) {
  112. doFeed(request, response);
  113. handled(request);
  114. } else if (target.equals("/dynamic/getprofiles")) {
  115. doProfiles(response);
  116. handled(request);
  117. } else if (target.equals("/dynamic/newserver")) {
  118. doNewServer(request, response);
  119. handled(request);
  120. } else if (target.equals("/dynamic/windowrefresh")) {
  121. doWindowRefresh(request, response);
  122. handled(request);
  123. } else if (target.equals("/dynamic/input")) {
  124. doInput(request, response);
  125. handled(request);
  126. } else if (target.equals("/dynamic/nicklistrefresh")) {
  127. doNicklist(request, response);
  128. handled(request);
  129. } else if (target.equals("/dynamic/tab")) {
  130. doTab(request, response);
  131. handled(request);
  132. } else if (target.equals("/dynamic/keyup")
  133. || target.equals("/dynamic/keydown")) {
  134. doKeyUpDown(target.equals("/dynamic/keyup"), request, response);
  135. handled(request);
  136. } else if (target.equals("/dynamic/key")) {
  137. doKey(request, response);
  138. handled(request);
  139. } else if (target.equals("/dynamic/clients")) {
  140. doClients(request, response);
  141. handled(request);
  142. } else if (target.equals("/dynamic/joinchannel")) {
  143. doJoinChannel(request, response);
  144. handled(request);
  145. } else if (target.equals("/dynamic/openquery")) {
  146. doOpenQuery(request, response);
  147. handled(request);
  148. }
  149. }
  150. /**
  151. * Handles a request for the event feed.
  152. *
  153. * @param request The servlet request that is being handled
  154. * @param response The servlet response object to write to
  155. * @throws IOException If unable to write the response
  156. */
  157. private void doFeed(final HttpServletRequest request,
  158. final HttpServletResponse response) throws IOException {
  159. response.setStatus(HttpServletResponse.SC_OK);
  160. response.setContentType("application/json");
  161. final Client client = CLIENTS.get(request.getParameter("clientID"));
  162. synchronized (client.getMutex()) {
  163. List<Event> myEvents = client.retrieveEvents();
  164. if (myEvents.isEmpty()) {
  165. Continuation continuation = ContinuationSupport
  166. .getContinuation(request, client.getMutex());
  167. client.setContinuation(continuation);
  168. continuation.suspend(30000L);
  169. myEvents = client.retrieveEvents();
  170. }
  171. client.setContinuation(null);
  172. final String json = JSON.toString(myEvents.toArray());
  173. response.getWriter().write(json);
  174. }
  175. }
  176. private void doInput(final HttpServletRequest request,
  177. final HttpServletResponse response) throws IOException {
  178. final WebWindow window = WebWindow.getWindow(
  179. request.getParameter("window"));
  180. if (window instanceof WebInputWindow) {
  181. final WebInputWindow wiw = (WebInputWindow) window;
  182. wiw.getInputHandler(request.getParameter("clientID")).enterPressed(
  183. request.getParameter("input"));
  184. }
  185. }
  186. private void doKey(final HttpServletRequest request,
  187. final HttpServletResponse response) throws IOException {
  188. final WebWindow window = WebWindow.getWindow(
  189. request.getParameter("window"));
  190. if (window instanceof WebInputWindow) {
  191. final WebInputWindow wiw = (WebInputWindow) window;
  192. try {
  193. ((WebInputHandler) wiw.getInputHandler(
  194. request.getParameter("clientID"),
  195. request.getParameter("input"),
  196. request.getParameter("selstart"),
  197. request.getParameter("selend"))).handleKeyPressed(
  198. request.getParameter("input"),
  199. Integer.parseInt(request.getParameter("key")),
  200. Boolean.parseBoolean(request.getParameter("shift")),
  201. Boolean.parseBoolean(request.getParameter("ctrl")));
  202. } catch (NumberFormatException ex) {
  203. // Do nothing
  204. }
  205. }
  206. }
  207. private void doTab(final HttpServletRequest request,
  208. final HttpServletResponse response) throws IOException {
  209. final WebWindow window = WebWindow.getWindow(request.getParameter(
  210. "window"));
  211. if (window instanceof WebInputWindow) {
  212. final WebInputWindow wiw = (WebInputWindow) window;
  213. ((WebInputHandler) wiw.getInputHandler(request.getParameter(
  214. "clientID"),
  215. request.getParameter("input"), request.getParameter(
  216. "selstart"),
  217. request.getParameter("selend"))).doTabCompletion(false);
  218. }
  219. }
  220. private void doKeyUpDown(final boolean up, final HttpServletRequest request,
  221. final HttpServletResponse response) throws IOException {
  222. final WebWindow window = WebWindow.getWindow(request.getParameter(
  223. "window"));
  224. if (window instanceof WebInputWindow) {
  225. final WebInputWindow wiw = (WebInputWindow) window;
  226. final WebInputHandler wih = ((WebInputHandler) wiw.getInputHandler(
  227. request.getParameter("clientID"),
  228. request.getParameter("input"),
  229. request.getParameter("selstart"),
  230. request.getParameter("selend")));
  231. if (up) {
  232. wih.doBufferUp();
  233. } else {
  234. wih.doBufferDown();
  235. }
  236. }
  237. }
  238. private void doNewServer(final HttpServletRequest request,
  239. final HttpServletResponse response) throws
  240. IOException {
  241. try {
  242. new Server(new URI("irc://" + request.getParameter("password") + "@"
  243. + request.getParameter("server") + ":"
  244. + request.getParameter("port")),
  245. findProfile(request.getParameter("profile"))).connect();
  246. } catch (URISyntaxException ex) {
  247. // Ugh.
  248. }
  249. }
  250. private void doNicklist(final HttpServletRequest request,
  251. final HttpServletResponse response) throws IOException {
  252. response.setStatus(HttpServletResponse.SC_OK);
  253. response.setContentType("application/json");
  254. final List<Event> nickEvents = new ArrayList<Event>();
  255. nickEvents.add(new Event("clearnicklist", false));
  256. for (ChannelClientInfo cci : ((Channel) (WebWindow.getWindow(
  257. request.getParameter("window"))).getContainer())
  258. .getChannelInfo().getChannelClients()) {
  259. nickEvents.add(new Event("addnicklist",
  260. cci.getClient().getNickname()));
  261. }
  262. response.getWriter().write(JSON.toString(nickEvents.toArray()));
  263. }
  264. private void doProfiles(final HttpServletResponse response) throws
  265. IOException {
  266. response.setStatus(HttpServletResponse.SC_OK);
  267. response.setContentType("application/json");
  268. final List<Event> profileEvents = new ArrayList<Event>();
  269. profileEvents.add(new Event("clearprofiles", null));
  270. for (Identity identity : IdentityManager.getCustomIdentities(
  271. "profile")) {
  272. profileEvents.add(new Event("addprofile", identity.getName()));
  273. }
  274. response.getWriter().write(JSON.toString(profileEvents.toArray()));
  275. }
  276. private void doWindowRefresh(final HttpServletRequest request,
  277. final HttpServletResponse response) throws IOException {
  278. response.setStatus(HttpServletResponse.SC_OK);
  279. response.setContentType("application/json");
  280. final List<Event> windowEvents = new ArrayList<Event>();
  281. final WebWindow window = WebWindow.getWindow(request.getParameter(
  282. "window"));
  283. windowEvents.add(new Event("clearwindow", window.getId()));
  284. for (String line : window.getMessages()) {
  285. windowEvents.add(new Event("lineadded", new Message(line, window)));
  286. }
  287. response.getWriter().write(JSON.toString(windowEvents.toArray()));
  288. }
  289. private void doClients(final HttpServletRequest request,
  290. final HttpServletResponse response) throws IOException {
  291. response.setStatus(HttpServletResponse.SC_OK);
  292. response.setContentType("application/json");
  293. response.getWriter().write(JSON.toString(CLIENTS.values().toArray()));
  294. }
  295. private void doJoinChannel(final HttpServletRequest request,
  296. final HttpServletResponse response) throws IOException {
  297. final String windowID = request.getParameter("source");
  298. final WebWindow window = WebWindow.getWindow(windowID);
  299. window.getContainer().getServer().join(new ChannelJoinRequest(request.
  300. getParameter("channel")));
  301. }
  302. private void doOpenQuery(final HttpServletRequest request,
  303. final HttpServletResponse response) throws IOException {
  304. final String windowID = request.getParameter("source");
  305. final WebWindow window = WebWindow.getWindow(windowID);
  306. window.getContainer().getServer().getQuery(request.getParameter(
  307. "target"));
  308. }
  309. private Identity findProfile(final String parameter) {
  310. for (Identity identity : IdentityManager.getCustomIdentities(
  311. "profile")) {
  312. if (identity.getName().equals(parameter)) {
  313. return identity;
  314. }
  315. }
  316. return null;
  317. }
  318. private void handled(final HttpServletRequest request) {
  319. ((request instanceof Request) ? (Request) request
  320. : HttpConnection.getCurrentConnection().getRequest())
  321. .setHandled(true);
  322. }
  323. public static void addEvent(final Event event) {
  324. synchronized (CLIENTS) {
  325. for (Client client : CLIENTS.values()) {
  326. client.addEvent(event);
  327. }
  328. }
  329. }
  330. public static void addEvent(final String clientID, final Event event) {
  331. CLIENTS.get(clientID).addEvent(event);
  332. }
  333. }