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

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

todo tags etc

  • Property svn:keywords set to Author Date Id Revision
File size: 18.9 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(Constants.ACTION_PARAM);
74
75 Map args = req.getParameterMap();
76
77 if (action != null && action.equals("receiveEvent")) {
78 receiveEvent(args);
79 return null;
80 }
81
82 args = normalise(args);
83
84 if (action == null || !ArrayHelper.contains(actions, action)) {
85 String title = "Unknown action";
86 String message = "I don't know how to " + action;
87 String details = "The only actions I know are " + Arrays.toString(actions);
88 return showError(context, message, details);
89 }
90
91 String templateString = "";
92
93 try {
94 Method method = AlertingService.class.getDeclaredMethod(action, new Class[] {Map.class, Context.class});
95 templateString = (String) method.invoke(this, new Object[] {args, context});
96 } catch (Exception e) {
97 String message = "An error has occured, I couldn't do what you told me to do.";
98 String details = e.getMessage() + " (" + e.getClass().getName() + "); "
99 + e.getCause()
100 + " ; action is " + action;
101 return showError(context, message, details);
102 }
103
104 Template template = null;
105 try {
106 template = getTemplate(templateString);
107 } catch (Exception e) {
108 // TODO Auto-generated catch block
109 e.printStackTrace();
110 try {
111 error((HttpServletRequest)context.get(REQUEST),
112 (HttpServletResponse)context.get(RESPONSE),
113 e);
114 } catch (Exception e2) {
115 // TODO Auto-generated catch block
116 e2.printStackTrace();
117 }
118 }
119 return template;
120 }
121
122 /**
123 * @param arguments
124 * @param context
125 * @return the Velocity template to use
126 * @throws Exception
127 */
128 public String createSubscription(Map arguments, Context context) throws Exception {
129 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
130 if (!UserManager.getInstance().isLoggedIn(session)) {
131 session.setAttribute("next_action", "createSubscription");
132 return showLoginForm(arguments, context);
133 }
134 if (arguments.containsKey("next_page") && arguments.get("next_page").equals("finish")) {
135 arguments.putAll(getPageArgsFromSession(session));
136 arguments.put("username", session.getAttribute("username"));
137 ProfileStore.getInstance().createSubscription(arguments);
138 return listSubscriptions(arguments, context);
139 } else {
140 return showSubscriptionWizardPage(arguments, context, true);
141 }
142 }
143
144 public String deleteSubscription(Map arguments, Context context) {
145 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
146 if (!UserManager.getInstance().isLoggedIn(session)) {
147 session.setAttribute("next_action", "deleteSubscription");
148 return showLoginForm(arguments, context);
149 }
150 String subscriptionID = (String) arguments.get("subscriptionID");
151 try {
152 ProfileStore.getInstance().deleteSubscription(subscriptionID);
153 } catch (DatabaseException e) {
154 // TODO Auto-generated catch block
155 e.printStackTrace();
156 } catch (SQLException e) {
157 // TODO Auto-generated catch block
158 e.printStackTrace();
159 }
160 return listSubscriptions(arguments, context);
161 }
162
163 public String editSubscription(Map arguments, Context context) throws Exception {
164 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
165 if (!UserManager.getInstance().isLoggedIn(session)) {
166 session.setAttribute("next_action", "editSubscription");
167 return showLoginForm(arguments, context);
168 }
169 if (arguments.containsKey("next_page") && arguments.get("next_page").equals("finish")) {
170 ProfileStore.getInstance().changeSubscription(arguments, session);
171 return listSubscriptions(arguments, context);
172 } else {
173 return showSubscriptionWizardPage(arguments, context, false);
174 }
175 }
176
177 public String showFeed(Map arguments, Context context) {
178 context.put("list", ""/* TODO pass subscription list */);
179 return "feed.vm";
180 }
181
182 public String showLoginForm(Map arguments, Context context) {
183 return "login.vm";
184 }
185
186 public String showRegistrationForm(Map arguments, Context context) {
187 return "register.vm";
188 }
189
190 public String listSubscriptions(Map arguments, Context context) {
191 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
192 if (!UserManager.getInstance().isLoggedIn(session)) {
193 session.setAttribute("next_action", "listSubscriptions");
194 return showLoginForm(arguments, context);
195 }
196 String username = (String) session.getAttribute("username");
197 context.put("title", "List of Subscriptions for " + username);
198 try {
199 Collection subscriptions = ProfileStore.getInstance().getAllSubscriptionsFor(username);
200 context.put("list", subscriptions);
201 return "list.vm";
202 } catch (DatabaseException de) {
203 context.put("message", "couldn't get list of subscriptions for " + username);
204 context.put("details", de.getMessage());
205 return "error.vm";
206 }
207 }
208
209 public String login(Map arguments, Context context) throws Exception {
210 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
211 try {
212 UserManager.getInstance().loginUser(arguments, session);
213 } catch (UserManagementException e) {
214 context.put("error", Boolean.TRUE);
215 context.put("errormessage", e.getMessage());
216 return showLoginForm(arguments, context);
217 }
218 if (session.getAttribute("next_action") != null) {
219 String nextAction = (String) session.getAttribute("next_action");
220 Method method = AlertingService.class.getDeclaredMethod(nextAction, new Class[] {Map.class, Context.class});
221 return (String) method.invoke(this, new Object[] {arguments, context});
222 }
223 return listSubscriptions(arguments, context);
224 }
225
226 public String register(Map arguments, Context context) throws Exception {
227 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
228 try {
229 UserManager.getInstance().createUser(arguments, session);
230 } catch (UserManagementException e) {
231 context.put("error", Boolean.TRUE);
232 context.put("errormessage", e.getMessage());
233 return showRegistrationForm(arguments, context);
234 }
235 return login(arguments, context);
236 }
237
238 public String logout(Map arguments, Context context) {
239 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
240 Enumeration atts = session.getAttributeNames();
241 while (atts.hasMoreElements()) {
242 session.removeAttribute((String) atts.nextElement());
243 }
244 session.invalidate();
245 return "general.vm";
246 }
247
248 public void receiveEvent(Map rawEvent) {
249 Map event = new TreeMap();
250 for (Iterator iter = rawEvent.keySet().iterator(); iter.hasNext();) {
251 String key = (String) iter.next();
252 String[] value = (String[]) rawEvent.get(key);
253 event.put(key, value[0]);
254 }
255 System.out.println("receiving event " + event);
256
257 GreenstoneCommunicator gsComm = null;
258 try {
259 String hostID = (String) event.get(Constants.HOST_ID_FIELD);
260 gsComm = new GreenstoneCommunicator(new URL(hostID));
261 } catch (MalformedURLException e) {
262 // TODO Auto-generated catch block
263 e.printStackTrace();
264 } catch (Exception e) {
265 // TODO Auto-generated catch block
266 e.printStackTrace();
267 }
268 Set matchedSubscriptions = ProfileStore.getInstance().filter(event, gsComm);
269 System.out.println(matchedSubscriptions.size() + " matching subscriptions: " + matchedSubscriptions);
270 // TODO do something with the matched subscriptions
271 }
272
273 /**
274 * @param args
275 */
276 private Map normalise(Map args) {
277 Map result = new TreeMap();
278 for (Iterator iter = args.keySet().iterator(); iter.hasNext();) {
279 String key = (String) iter.next();
280 if (Predicate.isMultiValued(key) || key.equals("way")) {
281 // multi-valued attributes
282 String[] values = ((String[]) args.get(key));
283 result.put(key, Arrays.asList(values));
284 } else {
285 String firstValue = ((String[])args.get(key))[0];
286 result.put(key, firstValue);
287 }
288 }
289 return result;
290 }
291
292 /**
293 * @param context
294 * @param message
295 * @param details
296 * @return
297 */
298 private Template showError(Context context, String message, String details) {
299 context.put("title", "Error");
300 context.put("message", message);
301 context.put("details", details);
302 try {
303 return getTemplate("error.vm");
304 } catch (Exception e) {
305 try {
306 super.error((HttpServletRequest)context.get("req"),
307 (HttpServletResponse)context.get("res"),
308 e);
309 } catch (Exception e2) {
310 e2.printStackTrace();
311 }
312 }
313 return null;
314 }
315
316 /**
317 * @param arguments
318 * @param context
319 * @param create
320 * @return
321 * @throws Exception
322 */
323 private String showSubscriptionWizardPage(Map arguments, Context context, boolean create) throws Exception {
324 if (create) {
325 context.put(Constants.ACTION_PARAM, "createSubscription");
326 } else {
327 context.put(Constants.ACTION_PARAM, "editSubscription");
328 }
329 if (!arguments.containsKey("current_page")) {
330 return "sub_type-details.vm";
331 }
332
333 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
334 String currentPage = (String) arguments.get("current_page");
335 String direction = (String) arguments.get("next_page");
336
337 if (arguments.containsKey(Constants.HOST_QUERY_FIELD)) {
338 String hostQuery = (String) arguments.get(Constants.HOST_QUERY_FIELD);
339 if (hostQuery != null && hostQuery.length() != 0)
340 arguments.remove(Constants.HOST_ID_FIELD);
341 }
342 if (arguments.containsKey(Constants.COLLECTION_QUERY_FIELD)) {
343 String collQuery = (String) arguments.get(Constants.COLLECTION_QUERY_FIELD);
344 if (collQuery != null && collQuery.length() != 0)
345 arguments.remove(Constants.COLLECTION_ID_FIELD);
346 }
347
348 // save page arguments
349 savePageArgsToSession(currentPage, arguments, session);
350
351 String nextPage = getNextPage(currentPage, direction);
352
353 // fill prefill
354 context.put("prefill", getPageArgsFromSession(nextPage, session));
355
356 // fill preview
357 context.put("preview", getPagePreview(nextPage, session));
358
359 // get page-specific stuff
360 if (nextPage.equals("host")) {
361 String[] hostNames;
362 try {
363 GreenstoneCommunicator gsComm = new GreenstoneCommunicator();
364 hostNames = gsComm.getHostNames();
365 } catch (Exception e) {
366 hostNames = new String[] { "localhost" };
367 }
368 context.put("hostnames", hostNames);
369 session.setAttribute("hostnames", hostNames);
370 } else if (nextPage.equals("collection")) {
371 List hostNames = (List) arguments.get(Constants.HOST_ID_FIELD);
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(Constants.HOST_QUERY_FIELD);
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.