source: trunk/gsdl3/extensions/gsdl-as/src/org/greenstone/gsdlas/AlertingService.java@ 9874

Last change on this file since 9874 was 9874, checked in by kjdon, 19 years ago

merged from branch ant-install-branch: merge 1

  • Property svn:keywords set to Author Date Id Revision
File size: 21.5 KB
Line 
1/*
2 * Created on Nov 22, 2004
3 * Copyright (C) Andrea Schweer, 2004
4 *
5 * This file is part of the Greenstone Alerting Service.
6 * Refer to the COPYING file in the base directory of this package
7 * for licensing information.
8 */
9package org.greenstone.gsdlas;
10
11import java.lang.reflect.Method;
12import java.net.URL;
13import java.sql.SQLException;
14import java.util.*;
15
16import javax.servlet.ServletConfig;
17import javax.servlet.ServletException;
18import javax.servlet.http.*;
19
20import org.apache.velocity.Template;
21import org.apache.velocity.context.Context;
22import org.apache.velocity.servlet.VelocityServlet;
23import org.greenstone.gsdlas.database.DatabaseException;
24import org.greenstone.gsdlas.profiles.Predicate;
25import org.greenstone.gsdlas.profiles.Subscription;
26import org.greenstone.gsdlas.users.UserManagementException;
27import org.greenstone.gsdlas.users.UserManager;
28import org.greenstone.gsdlas.util.ArrayHelper;
29
30/**
31 * @author schweer
32 *
33 * TODO To change the template for this generated type comment go to
34 * Window - Preferences - Java - Code Style - Code Templates
35 */
36public class AlertingService extends VelocityServlet {
37
38 /* (non-Javadoc)
39 * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
40 */
41 public void init(ServletConfig config) throws ServletException {
42 super.init(config);
43 System.out.println("reloading subs");
44 ProfileStore.getInstance().restoreFromDatabase();
45 try {
46 Set subs = ProfileStore.getInstance().getAllSubscriptionsFor("andrea");
47 System.out.println("reloaded " + subs.size() + " subs for andrea: ");
48 for (Iterator iter = subs.iterator(); iter.hasNext();) {
49 System.out.println(iter.next());
50 }
51 } catch (DatabaseException e) {
52 // TODO Auto-generated catch block
53 e.printStackTrace();
54 }
55 }
56 public static final String[] actions = new String[] {
57 "createSubscription",
58 "deleteSubscription",
59 "editSubscription",
60 "showEvents",
61 "showFeed",
62 "listSubscriptions",
63 "login",
64 "register",
65 "logout",
66 "showLoginForm",
67 "showRegistrationForm"
68 };
69
70
71 protected Template handleRequest(HttpServletRequest req,
72 HttpServletResponse res, Context context) {
73
74 String action = req.getParameter(Constants.ACTION_PARAM);
75
76 Map args = req.getParameterMap();
77
78 if (action != null && action.equals("receiveEvent")) {
79 receiveEvent(args);
80 return null;
81 }
82
83 args = normalise(args);
84
85 if (action == null || !ArrayHelper.contains(actions, action)) {
86 String title = "Unknown action";
87 String message = "I don't know how to " + action;
88 String details = "The only actions I know are " + ArrayHelper.toString(actions);
89 return showError(context, message, details);
90 }
91
92 String templateString = "";
93
94 try {
95 Method method = AlertingService.class.getDeclaredMethod(action, new Class[] {Map.class, Context.class});
96 templateString = (String) method.invoke(this, new Object[] {args, context});
97 } catch (Exception e) {
98 String message = "An error has occured, I couldn't do what you told me to do.";
99 String details = e.getMessage() + " (" + e.getClass().getName() + "); "
100 + e.getCause()
101 + " ; action is " + action;
102 return showError(context, message, details);
103 }
104
105 Template template = null;
106 try {
107 template = getTemplate(templateString);
108 } catch (Exception e) {
109 // TODO Auto-generated catch block
110 e.printStackTrace();
111 try {
112 error((HttpServletRequest)context.get(REQUEST),
113 (HttpServletResponse)context.get(RESPONSE),
114 e);
115 } catch (Exception e2) {
116 // TODO Auto-generated catch block
117 e2.printStackTrace();
118 }
119 }
120 return template;
121 }
122
123 /**
124 * @param arguments
125 * @param context
126 * @return the Velocity template to use
127 * @throws Exception
128 */
129 public String createSubscription(Map arguments, Context context) throws Exception {
130 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
131 if (!UserManager.getInstance().isLoggedIn(session)) {
132 session.setAttribute("next_action", "createSubscription");
133 return showLoginForm(arguments, context);
134 }
135 if (arguments.containsKey("next_page") && arguments.get("next_page").equals("finish")) {
136 arguments.putAll(getPageArgsFromSession(session));
137 arguments.put("username", session.getAttribute("username"));
138 ProfileStore.getInstance().createSubscription(arguments);
139 return listSubscriptions(arguments, context);
140 } else {
141 return showSubscriptionWizardPage(arguments, context, true);
142 }
143 }
144
145 public String deleteSubscription(Map arguments, Context context) {
146 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
147 if (!UserManager.getInstance().isLoggedIn(session)) {
148 session.setAttribute("next_action", "deleteSubscription");
149 return showLoginForm(arguments, context);
150 }
151 String subscriptionID = (String) arguments.get("subscriptionID");
152 try {
153 ProfileStore.getInstance().deleteSubscription(subscriptionID);
154 } catch (DatabaseException e) {
155 // TODO Auto-generated catch block
156 e.printStackTrace();
157 } catch (SQLException e) {
158 // TODO Auto-generated catch block
159 e.printStackTrace();
160 }
161 return listSubscriptions(arguments, context);
162 }
163
164 public String editSubscription(Map arguments, Context context) throws Exception {
165 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
166 if (!UserManager.getInstance().isLoggedIn(session)) {
167 session.setAttribute("next_action", "editSubscription");
168 return showLoginForm(arguments, context);
169 }
170 if (arguments.containsKey("next_page") && arguments.get("next_page").equals("finish")) {
171 ProfileStore.getInstance().changeSubscription(arguments, session);
172 return listSubscriptions(arguments, context);
173 } else {
174 return showSubscriptionWizardPage(arguments, context, false);
175 }
176 }
177
178 public String showFeed(Map arguments, Context context) throws NumberFormatException, DatabaseException, SQLException {
179 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
180 if (!UserManager.getInstance().isLoggedIn(session)) {
181 session.setAttribute("next_action", "showFeed");
182 return showLoginForm(arguments, context);
183 }
184 String subscriptionID = (String) arguments.get("subscriptionID");
185 Integer subID = new Integer(subscriptionID);
186 Set events = EventStore.getInstance().getEvents(subID);
187 context.put("list", events);
188 context.put("subscription", ProfileStore.getInstance().getSubscription(subID.intValue()));
189 HttpServletResponse res = (HttpServletResponse) context.get(RESPONSE);
190 res.setContentType("text/xml");
191 return "feed.vm";
192 }
193
194 public String showEvents(Map arguments, Context context) throws NumberFormatException, DatabaseException, SQLException {
195 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
196 if (!UserManager.getInstance().isLoggedIn(session)) {
197 session.setAttribute("next_action", "showEvents");
198 return showLoginForm(arguments, context);
199 }
200 String subscriptionID = (String) arguments.get("subscriptionID");
201 Integer subID = new Integer(subscriptionID);
202 Set events = EventStore.getInstance().getEvents(subID);
203 context.put("list", events);
204 context.put("subscription", ProfileStore.getInstance().getSubscription(subID.intValue()));
205 return "events.vm";
206 }
207
208 public String showLoginForm(Map arguments, Context context) {
209 return "login.vm";
210 }
211
212 public String showRegistrationForm(Map arguments, Context context) {
213 return "register.vm";
214 }
215
216 public String listSubscriptions(Map arguments, Context context) {
217 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
218 if (!UserManager.getInstance().isLoggedIn(session)) {
219 session.setAttribute("next_action", "listSubscriptions");
220 return showLoginForm(arguments, context);
221 }
222 String username = (String) session.getAttribute("username");
223 context.put("title", "List of Subscriptions for " + username);
224 try {
225 Collection subscriptions = ProfileStore.getInstance().getAllSubscriptionsFor(username);
226 context.put("list", subscriptions);
227 return "list.vm";
228 } catch (DatabaseException de) {
229 context.put("message", "couldn't get list of subscriptions for " + username);
230 context.put("details", de.getMessage());
231 return "error.vm";
232 }
233 }
234
235 public String login(Map arguments, Context context) throws Exception {
236 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
237 try {
238 UserManager.getInstance().loginUser(arguments, session);
239 } catch (UserManagementException e) {
240 context.put("error", Boolean.TRUE);
241 context.put("errormessage", e.getMessage());
242 return showLoginForm(arguments, context);
243 }
244 if (session.getAttribute("next_action") != null) {
245 String nextAction = (String) session.getAttribute("next_action");
246 Method method = AlertingService.class.getDeclaredMethod(nextAction, new Class[] {Map.class, Context.class});
247 return (String) method.invoke(this, new Object[] {arguments, context});
248 }
249 return listSubscriptions(arguments, context);
250 }
251
252 public String register(Map arguments, Context context) throws Exception {
253 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
254 try {
255 UserManager.getInstance().createUser(arguments, session);
256 } catch (UserManagementException e) {
257 context.put("error", Boolean.TRUE);
258 context.put("errormessage", e.getMessage());
259 return showRegistrationForm(arguments, context);
260 }
261 return login(arguments, context);
262 }
263
264 public String logout(Map arguments, Context context) {
265 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
266 Enumeration atts = session.getAttributeNames();
267 while (atts.hasMoreElements()) {
268 session.removeAttribute((String) atts.nextElement());
269 }
270 session.invalidate();
271 return "general.vm";
272 }
273
274 public void receiveEvent(Map rawEvent) {
275 Map event = new TreeMap();
276 for (Iterator iter = rawEvent.keySet().iterator(); iter.hasNext();) {
277 String key = (String) iter.next();
278 if (key.equals("action")) continue; // we don't want this
279 String[] value = (String[]) rawEvent.get(key);
280 event.put(key, value[0]);
281 }
282 System.out.println("receiving event " + event);
283
284 GreenstoneCommunicator gsComm = null;
285 try {
286 String hostID = (String) event.get(Constants.HOST_ID_FIELD);
287 gsComm = new GreenstoneCommunicator(new URL(hostID));
288 } catch (Exception e) {
289 System.err.println("Can't communicate to Greenstone: " + e.getMessage());
290 e.printStackTrace();
291 }
292
293 Set matchedSubscriptions = ProfileStore.getInstance().filter(event, gsComm);
294
295 try {
296 EventStore.getInstance().add(event, matchedSubscriptions);
297 Notifier.getInstance().sendNotifications(event, matchedSubscriptions);
298 } catch (Exception e) {
299 System.err.println("Couldn't save events: " + e.getMessage());
300 e.printStackTrace();
301 }
302 System.out.println(matchedSubscriptions.size() + " matching subscriptions: " + matchedSubscriptions);
303 }
304
305 /**
306 * @param args
307 */
308 private Map normalise(Map args) {
309 Map result = new TreeMap();
310 for (Iterator iter = args.keySet().iterator(); iter.hasNext();) {
311 String key = (String) iter.next();
312 if (Predicate.isMultiValued(key) || key.equals("way")) {
313 // multi-valued attributes
314 String[] values = ((String[]) args.get(key));
315 result.put(key, Arrays.asList(values));
316 } else {
317 String firstValue = ((String[])args.get(key))[0];
318 result.put(key, firstValue);
319 }
320 }
321 return result;
322 }
323
324 /**
325 * @param context
326 * @param message
327 * @param details
328 * @return
329 */
330 private Template showError(Context context, String message, String details) {
331 context.put("title", "Error");
332 context.put("message", message);
333 context.put("details", details);
334 try {
335 return getTemplate("error.vm");
336 } catch (Exception e) {
337 try {
338 super.error((HttpServletRequest)context.get("req"),
339 (HttpServletResponse)context.get("res"),
340 e);
341 } catch (Exception e2) {
342 e2.printStackTrace();
343 }
344 }
345 return null;
346 }
347
348 /**
349 * @param arguments
350 * @param context
351 * @param create
352 * @return
353 * @throws Exception
354 */
355 private String showSubscriptionWizardPage(Map arguments, Context context, boolean create) throws Exception {
356 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
357 if (create) {
358 context.put(Constants.ACTION_PARAM, "createSubscription");
359 } else {
360 // prefill from existing subscription
361 context.put(Constants.ACTION_PARAM, "editSubscription");
362 String subscriptionID = (String) arguments.get("subscriptionID");
363 int subID = Integer.parseInt(subscriptionID);
364 prefillFromSubscription(session, subID);
365 }
366 if (!arguments.containsKey("current_page")) {
367 return "sub_type-details.vm";
368 }
369
370 String currentPage = (String) arguments.get("current_page");
371 String direction = (String) arguments.get("next_page");
372
373 if (arguments.containsKey(Constants.HOST_QUERY_FIELD)) {
374 String hostQuery = (String) arguments.get(Constants.HOST_QUERY_FIELD);
375 if (hostQuery != null && hostQuery.length() != 0)
376 arguments.remove(Constants.HOST_ID_FIELD);
377 }
378 if (arguments.containsKey(Constants.COLLECTION_QUERY_FIELD)) {
379 String collQuery = (String) arguments.get(Constants.COLLECTION_QUERY_FIELD);
380 if (collQuery != null && collQuery.length() != 0)
381 arguments.remove(Constants.COLLECTION_ID_FIELD);
382 }
383
384 // save page arguments
385 savePageArgsToSession(currentPage, arguments, session);
386
387 String nextPage = getNextPage(currentPage, direction);
388
389 // fill prefill
390 context.put("prefill", getPageArgsFromSession(nextPage, session));
391
392 // fill preview
393 context.put("preview", getPagePreview(nextPage, session));
394
395 // get page-specific stuff
396 if (nextPage.equals("host")) {
397 String[] hostNames;
398 try {
399 GreenstoneCommunicator gsComm = new GreenstoneCommunicator();
400 hostNames = gsComm.getHostNames();
401 } catch (Exception e) {
402 hostNames = new String[] { "localhost" };
403 }
404 context.put("hostnames", hostNames);
405 session.setAttribute("hostnames", hostNames);
406 } else if (nextPage.equals("collection")) {
407 List hostNames = (List) arguments.get(Constants.HOST_ID_FIELD);
408 if (hostNames == null || hostNames.isEmpty()) {
409 hostNames = new Vector();
410 // no host names -> use host query
411 String[] hostsFromSession = (String[]) session.getAttribute("hostnames");
412 if (hostsFromSession == null || hostsFromSession.length == 0) {
413 try {
414 GreenstoneCommunicator gsComm = new GreenstoneCommunicator();
415 hostsFromSession = gsComm.getHostNames();
416 } catch (Exception e) {
417 hostsFromSession = new String[] { "localhost" };
418 }
419 }
420 String hostQuery = (String) arguments.get(Constants.HOST_QUERY_FIELD);
421 for (int i = 0; i < hostsFromSession.length; i++) {
422 if (hostsFromSession[i] != null && hostsFromSession[i].indexOf(hostQuery) >= 0) {
423 hostNames.add(hostsFromSession[i]);
424 }
425 }
426 }
427
428 Map collNames = new TreeMap();
429 for (Iterator iter = hostNames.iterator(); iter.hasNext();) {
430 String host = (String) iter.next();
431 Set collNamesForHost = new TreeSet();
432 try {
433 URL url = new URL("http://" + host + ":8080/soap/servlet/rpcrouter");
434 GreenstoneCommunicator gsComm = new GreenstoneCommunicator(url);
435 collNamesForHost.addAll(Arrays.asList(gsComm.getCollectionNames()));
436 } catch (Exception e) {
437 // TODO Auto-generated catch block
438 e.printStackTrace();
439 }
440 collNames.put(host, collNamesForHost);
441 }
442 context.put("collectionnames", collNames);
443 context.put("hostnames", hostNames);
444 }
445
446 return "sub_" + nextPage + ".vm";
447 }
448
449 /**
450 * @param session
451 * @param subID
452 */
453 private void prefillFromSubscription(HttpSession session, int subID) {
454 Subscription sub = ProfileStore.getInstance().getSubscription(subID);
455 Map typeArgs = new HashMap();
456 // TODO really fill stuff
457 savePageArgsToSession("type-details", typeArgs, session);
458 Map hostArgs = new HashMap();
459 savePageArgsToSession("host", hostArgs, session);
460 Map collArgs = new HashMap();
461 savePageArgsToSession("collection", collArgs, session);
462 Map notificationArgs = new HashMap();
463 savePageArgsToSession("notification", notificationArgs, session);
464 }
465
466 /**
467 * @param nextPage
468 * @param session
469 * @return
470 */
471 private Map getPagePreview(String nextPage, HttpSession session) {
472 Map preview = new TreeMap();
473 if (nextPage.equals("type-details")) {
474 return preview;
475 }
476 preview.putAll(getPageArgsFromSession("type-details", session));
477 if (nextPage.equals("host")) {
478 return preview;
479 }
480 preview.putAll(getPageArgsFromSession("host", session));
481 if (nextPage.equals("collection")) {
482 return preview;
483 }
484 preview.putAll(getPageArgsFromSession("collection", session));
485 return preview;
486 }
487
488 /**
489 * @param currentPage
490 * @param direction
491 * @return
492 * @throws Exception
493 */
494 private String getNextPage(String currentPage, String direction) throws Exception {
495 String nextPage;
496 if (currentPage.equals("host") && direction.equals("back")) {
497 nextPage = "type-details";
498 } else if (currentPage.equals("type-details") || (currentPage.equals("collection") && direction.equals("back"))) {
499 nextPage = "host";
500 } else if (currentPage.equals("host") || (currentPage.equals("notification") && direction.equals("back"))) {
501 nextPage = "collection";
502 } else if (currentPage.equals("collection")) {
503 nextPage = "notification";
504 } else {
505 throw new Exception("unknown combination of currentPage=" + currentPage + " and nextPage=" + direction);
506 }
507 return nextPage;
508 }
509
510 /**
511 * @param page
512 * @param session
513 * @return
514 */
515 private Map getPageArgsFromSession(String page, HttpSession session) {
516 Map pageArgs = (Map) session.getAttribute("page_args");
517 if (pageArgs == null || !pageArgs.containsKey(page))
518 return new TreeMap();
519 return (Map) pageArgs.get(page);
520 }
521
522 private Map getPageArgsFromSession(HttpSession session) {
523 Map result = new TreeMap();
524 Map pageArgs = (Map) session.getAttribute("page_args");
525 if (pageArgs != null) {
526 for (Iterator iter = pageArgs.values().iterator(); iter.hasNext();) {
527 Map args = (Map) iter.next();
528 result.putAll(args);
529 }
530 }
531 return result;
532 }
533
534 /**
535 * @param page
536 * @param arguments
537 * @param session
538 */
539 private void savePageArgsToSession(String page, Map arguments, HttpSession session) {
540 Map pageArgs = (Map) session.getAttribute("page_args");
541 if (pageArgs == null) {
542 pageArgs = new TreeMap();
543 }
544 pageArgs.put(page, arguments);
545 session.setAttribute("page_args", pageArgs);
546 }
547}
Note: See TracBrowser for help on using the repository browser.