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

Last change on this file since 8867 was 8867, checked in by schweer, 19 years ago

fixed BTS 12: restore subscriptions/predicates from database

  • Property svn:keywords set to Author Date Id Revision
File size: 18.7 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.MalformedURLException;
13import java.net.URL;
14import java.sql.SQLException;
15import java.util.*;
16
17import javax.servlet.ServletConfig;
18import javax.servlet.ServletException;
19import javax.servlet.http.*;
20
21import org.apache.velocity.Template;
22import org.apache.velocity.context.Context;
23import org.apache.velocity.servlet.VelocityServlet;
24import org.greenstone.gsdlas.database.DatabaseException;
25import org.greenstone.gsdlas.profiles.Predicate;
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 "showFeed",
61 "listSubscriptions",
62 "login",
63 "register",
64 "logout",
65 "showLoginForm",
66 "showRegistrationForm"
67 };
68
69
70 protected Template handleRequest(HttpServletRequest req,
71 HttpServletResponse res, Context context) {
72
73 String action = req.getParameter("action");
74
75 Map args = req.getParameterMap();
76
77 if (action != null && action.equals("receiveEvent")) {
78 receiveEvent(args);
79 return null;
80 }
81
82 // TODO stop this, we need multi-valued stuff
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 " + Arrays.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) {
179 context.put("list", ""/* TODO pass subscription list */);
180 return "feed.vm";
181 }
182
183 public String showLoginForm(Map arguments, Context context) {
184 return "login.vm";
185 }
186
187 public String showRegistrationForm(Map arguments, Context context) {
188 return "register.vm";
189 }
190
191 public String listSubscriptions(Map arguments, Context context) {
192 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
193 if (!UserManager.getInstance().isLoggedIn(session)) {
194 session.setAttribute("next_action", "listSubscriptions");
195 return showLoginForm(arguments, context);
196 }
197 String username = (String) session.getAttribute("username");
198 context.put("title", "List of Subscriptions for " + username);
199 try {
200 Collection subscriptions = ProfileStore.getInstance().getAllSubscriptionsFor(username);
201 context.put("list", subscriptions);
202 return "list.vm";
203 } catch (DatabaseException de) {
204 context.put("message", "couldn't get list of subscriptions for " + username);
205 context.put("details", de.getMessage());
206 return "error.vm";
207 }
208 }
209
210 public String login(Map arguments, Context context) throws Exception {
211 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
212 try {
213 UserManager.getInstance().loginUser(arguments, session);
214 } catch (UserManagementException e) {
215 context.put("error", Boolean.TRUE);
216 context.put("errormessage", e.getMessage());
217 return showLoginForm(arguments, context);
218 }
219 if (session.getAttribute("next_action") != null) {
220 String nextAction = (String) session.getAttribute("next_action");
221 Method method = AlertingService.class.getDeclaredMethod(nextAction, new Class[] {Map.class, Context.class});
222 return (String) method.invoke(this, new Object[] {arguments, context});
223 }
224 return listSubscriptions(arguments, context);
225 }
226
227 public String register(Map arguments, Context context) throws Exception {
228 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
229 try {
230 UserManager.getInstance().createUser(arguments, session);
231 } catch (UserManagementException e) {
232 context.put("error", Boolean.TRUE);
233 context.put("errormessage", e.getMessage());
234 return showRegistrationForm(arguments, context);
235 }
236 return login(arguments, context);
237 }
238
239 public String logout(Map arguments, Context context) {
240 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
241 Enumeration atts = session.getAttributeNames();
242 while (atts.hasMoreElements()) {
243 session.removeAttribute((String) atts.nextElement());
244 }
245 session.invalidate();
246 return "general.vm";
247 }
248
249 public void receiveEvent(Map rawEvent) {
250 Map event = new TreeMap();
251 for (Iterator iter = rawEvent.keySet().iterator(); iter.hasNext();) {
252 String key = (String) iter.next();
253 String[] value = (String[]) rawEvent.get(key);
254 event.put(key, value[0]);
255 }
256
257 GreenstoneCommunicator gsComm = null;
258 try {
259 gsComm = new GreenstoneCommunicator(new URL((String) event.get("hostID")));
260 } catch (MalformedURLException e) {
261 // TODO Auto-generated catch block
262 e.printStackTrace();
263 } catch (Exception e) {
264 // TODO Auto-generated catch block
265 e.printStackTrace();
266 }
267 Set matchedSubscriptions = ProfileStore.getInstance().filter(event, gsComm);
268 System.out.println(matchedSubscriptions.size() + " matching subscriptions: " + matchedSubscriptions);
269 // TODO do something with the matched subscriptions
270 }
271
272 /**
273 * @param args
274 */
275 private Map normalise(Map args) {
276 Map result = new TreeMap();
277 for (Iterator iter = args.keySet().iterator(); iter.hasNext();) {
278 String key = (String) iter.next();
279 if (Predicate.isMultiValued(key) || key.equals("way")) {
280 // multi-valued attributes
281 String[] values = ((String[]) args.get(key));
282 result.put(key, Arrays.asList(values));
283 } else {
284 String firstValue = ((String[])args.get(key))[0];
285 result.put(key, firstValue);
286 }
287 }
288 return result;
289 }
290
291 /**
292 * @param context
293 * @param message
294 * @param details
295 * @return
296 */
297 private Template showError(Context context, String message, String details) {
298 context.put("title", "Error");
299 context.put("message", message);
300 context.put("details", details);
301 try {
302 return getTemplate("error.vm");
303 } catch (Exception e) {
304 try {
305 super.error((HttpServletRequest)context.get("req"),
306 (HttpServletResponse)context.get("res"),
307 e);
308 } catch (Exception e2) {
309 e2.printStackTrace();
310 }
311 }
312 return null;
313 }
314
315 /**
316 * @param arguments
317 * @param context
318 * @param create
319 * @return
320 * @throws Exception
321 */
322 private String showSubscriptionWizardPage(Map arguments, Context context, boolean create) throws Exception {
323 if (create) {
324 context.put("action", "createSubscription");
325 } else {
326 context.put("action", "editSubscription");
327 }
328 if (!arguments.containsKey("current_page")) {
329 return "sub_type-details.vm";
330 }
331
332 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
333 String currentPage = (String) arguments.get("current_page");
334 String direction = (String) arguments.get("next_page");
335
336 if (arguments.containsKey("host_query")) {
337 String hostQuery = (String) arguments.get("host_query");
338 if (hostQuery != null && hostQuery.length() != 0)
339 arguments.remove("hostID");
340 }
341 if (arguments.containsKey("collection_query")) {
342 String collQuery = (String) arguments.get("collection_query");
343 if (collQuery != null && collQuery.length() != 0)
344 arguments.remove("collectionID");
345 }
346
347 // save page arguments
348 savePageArgsToSession(currentPage, arguments, session);
349
350 String nextPage = getNextPage(currentPage, direction);
351
352 // fill prefill
353 context.put("prefill", getPageArgsFromSession(nextPage, session));
354
355 // fill preview
356 context.put("preview", getPagePreview(nextPage, session));
357
358 // get page-specific stuff
359 if (nextPage.equals("host")) {
360 String[] hostNames;
361 try {
362 GreenstoneCommunicator gsComm = new GreenstoneCommunicator();
363 hostNames = gsComm.getHostNames();
364 } catch (Exception e) {
365 hostNames = new String[] { "localhost" };
366 }
367 context.put("hostnames", hostNames);
368 session.setAttribute("hostnames", hostNames);
369 } else if (nextPage.equals("collection")) {
370 // TODO might be query instead of just name
371 List hostNames = (List) arguments.get("hostID");
372 if (hostNames == null || hostNames.isEmpty()) {
373 hostNames = new Vector();
374 // no host names -> use host query
375 String[] hostsFromSession = (String[]) session.getAttribute("hostnames");
376 if (hostsFromSession == null || hostsFromSession.length == 0) {
377 try {
378 GreenstoneCommunicator gsComm = new GreenstoneCommunicator();
379 hostsFromSession = gsComm.getHostNames();
380 } catch (Exception e) {
381 hostsFromSession = new String[] { "localhost" };
382 }
383 }
384 String hostQuery = (String) arguments.get("host_query");
385 for (int i = 0; i < hostsFromSession.length; i++) {
386 if (hostsFromSession[i] != null && hostsFromSession[i].indexOf(hostQuery) >= 0) {
387 hostNames.add(hostsFromSession[i]);
388 }
389 }
390 }
391
392 Map collNames = new TreeMap();
393 for (Iterator iter = hostNames.iterator(); iter.hasNext();) {
394 String host = (String) iter.next();
395 Set collNamesForHost = new TreeSet();
396 try {
397 URL url = new URL("http://" + host + ":8080/soap/servlet/rpcrouter");
398 GreenstoneCommunicator gsComm = new GreenstoneCommunicator(url);
399 collNamesForHost.addAll(Arrays.asList(gsComm.getCollectionNames()));
400 } catch (Exception e) {
401 // TODO Auto-generated catch block
402 e.printStackTrace();
403 }
404 collNames.put(host, collNamesForHost);
405 }
406 context.put("collectionnames", collNames);
407 context.put("hostnames", hostNames);
408 }
409
410 return "sub_" + nextPage + ".vm";
411 }
412
413 /**
414 * @param nextPage
415 * @param session
416 * @return
417 */
418 private Map getPagePreview(String nextPage, HttpSession session) {
419 Map preview = new TreeMap();
420 if (nextPage.equals("type-details")) {
421 return preview;
422 }
423 preview.putAll(getPageArgsFromSession("type-details", session));
424 if (nextPage.equals("host")) {
425 return preview;
426 }
427 preview.putAll(getPageArgsFromSession("host", session));
428 if (nextPage.equals("collection")) {
429 return preview;
430 }
431 preview.putAll(getPageArgsFromSession("collection", session));
432 return preview;
433 }
434
435 /**
436 * @param currentPage
437 * @param direction
438 * @return
439 * @throws Exception
440 */
441 private String getNextPage(String currentPage, String direction) throws Exception {
442 String nextPage;
443 if (currentPage.equals("host") && direction.equals("back")) {
444 nextPage = "type-details";
445 } else if (currentPage.equals("type-details") || (currentPage.equals("collection") && direction.equals("back"))) {
446 nextPage = "host";
447 } else if (currentPage.equals("host") || (currentPage.equals("notification") && direction.equals("back"))) {
448 nextPage = "collection";
449 } else if (currentPage.equals("collection")) {
450 nextPage = "notification";
451 } else {
452 throw new Exception("unknown combination of currentPage=" + currentPage + " and nextPage=" + direction);
453 }
454 return nextPage;
455 }
456
457 /**
458 * @param page
459 * @param session
460 * @return
461 */
462 private Map getPageArgsFromSession(String page, HttpSession session) {
463 Map pageArgs = (Map) session.getAttribute("page_args");
464 if (pageArgs == null || !pageArgs.containsKey(page))
465 return new TreeMap();
466 return (Map) pageArgs.get(page);
467 }
468
469 private Map getPageArgsFromSession(HttpSession session) {
470 Map result = new TreeMap();
471 Map pageArgs = (Map) session.getAttribute("page_args");
472 if (pageArgs != null) {
473 for (Iterator iter = pageArgs.values().iterator(); iter.hasNext();) {
474 Map args = (Map) iter.next();
475 result.putAll(args);
476 }
477 }
478 return result;
479 }
480
481 /**
482 * @param page
483 * @param arguments
484 * @param session
485 */
486 private void savePageArgsToSession(String page, Map arguments, HttpSession session) {
487 Map pageArgs = (Map) session.getAttribute("page_args");
488 if (pageArgs == null) {
489 pageArgs = new TreeMap();
490 }
491 pageArgs.put(page, arguments);
492 session.setAttribute("page_args", pageArgs);
493 }
494}
Note: See TracBrowser for help on using the repository browser.