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

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

substring match for host/collection works

  • Property svn:keywords set to Author Date Id Revision
File size: 17.6 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.util.*;
15
16import javax.servlet.http.*;
17
18import org.apache.velocity.Template;
19import org.apache.velocity.context.Context;
20import org.apache.velocity.servlet.VelocityServlet;
21import org.greenstone.gsdlas.database.DatabaseException;
22import org.greenstone.gsdlas.profiles.Predicate;
23import org.greenstone.gsdlas.users.UserManagementException;
24import org.greenstone.gsdlas.users.UserManager;
25import org.greenstone.gsdlas.util.ArrayHelper;
26
27/**
28 * @author schweer
29 *
30 * TODO To change the template for this generated type comment go to
31 * Window - Preferences - Java - Code Style - Code Templates
32 */
33public class AlertingService extends VelocityServlet {
34
35 public static final String[] actions = new String[] {
36 "createSubscription",
37 "deleteSubscription",
38 "editSubscription",
39 "showFeed",
40 "listSubscriptions",
41 "login",
42 "register",
43 "logout",
44 "showLoginForm",
45 "showRegistrationForm"
46 };
47
48
49 protected Template handleRequest(HttpServletRequest req,
50 HttpServletResponse res, Context context) {
51
52 String action = req.getParameter("action");
53
54 Map args = req.getParameterMap();
55
56 if (action != null && action.equals("receiveEvent")) {
57 receiveEvent(args);
58 return null;
59 }
60
61 // TODO stop this, we need multi-valued stuff
62 args = normalise(args);
63
64 if (action == null || !ArrayHelper.contains(actions, action)) {
65 String title = "Unknown action";
66 String message = "I don't know how to " + action;
67 String details = "The only actions I know are " + Arrays.toString(actions);
68 return showError(context, message, details);
69 }
70
71 String templateString = "";
72
73 try {
74 Method method = AlertingService.class.getDeclaredMethod(action, new Class[] {Map.class, Context.class});
75 templateString = (String) method.invoke(this, new Object[] {args, context});
76 } catch (Exception e) {
77 String message = "An error has occured, I couldn't do what you told me to do.";
78 String details = e.getMessage() + " (" + e.getClass().getName() + "); "
79 + e.getCause()
80 + " ; action is " + action;
81 return showError(context, message, details);
82 }
83
84 Template template = null;
85 try {
86 template = getTemplate(templateString);
87 } catch (Exception e) {
88 // TODO Auto-generated catch block
89 e.printStackTrace();
90 try {
91 error((HttpServletRequest)context.get(REQUEST),
92 (HttpServletResponse)context.get(RESPONSE),
93 e);
94 } catch (Exception e2) {
95 // TODO Auto-generated catch block
96 e2.printStackTrace();
97 }
98 }
99 return template;
100 }
101
102 /**
103 * @param arguments
104 * @param context
105 * @return the Velocity template to use
106 * @throws Exception
107 */
108 public String createSubscription(Map arguments, Context context) throws Exception {
109 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
110 if (!UserManager.getInstance().isLoggedIn(session)) {
111 session.setAttribute("next_action", "createSubscription");
112 return showLoginForm(arguments, context);
113 }
114 if (arguments.containsKey("next_page") && arguments.get("next_page").equals("finish")) {
115 arguments.putAll(getPageArgsFromSession(session));
116 arguments.put("username", session.getAttribute("username"));
117 ProfileStore.getInstance().createSubscription(arguments);
118 return listSubscriptions(arguments, context);
119 } else {
120 return showSubscriptionWizardPage(arguments, context, true);
121 }
122 }
123
124 public String deleteSubscription(Map arguments, Context context) {
125 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
126 if (!UserManager.getInstance().isLoggedIn(session)) {
127 session.setAttribute("next_action", "deleteSubscription");
128 return showLoginForm(arguments, context);
129 }
130 String subscriptionID = (String) arguments.get("subscriptionID");
131 ProfileStore.getInstance().deleteSubscription(subscriptionID);
132 return listSubscriptions(arguments, context);
133 }
134
135 public String editSubscription(Map arguments, Context context) throws Exception {
136 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
137 if (!UserManager.getInstance().isLoggedIn(session)) {
138 session.setAttribute("next_action", "editSubscription");
139 return showLoginForm(arguments, context);
140 }
141 if (arguments.containsKey("next_page") && arguments.get("next_page").equals("finish")) {
142 ProfileStore.getInstance().changeSubscription(arguments, session);
143 return listSubscriptions(arguments, context);
144 } else {
145 return showSubscriptionWizardPage(arguments, context, false);
146 }
147 }
148
149 public String showFeed(Map arguments, Context context) {
150 context.put("list", ""/* TODO pass subscription list */);
151 return "feed.vm";
152 }
153
154 public String showLoginForm(Map arguments, Context context) {
155 return "login.vm";
156 }
157
158 public String showRegistrationForm(Map arguments, Context context) {
159 return "register.vm";
160 }
161
162 public String listSubscriptions(Map arguments, Context context) {
163 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
164 if (!UserManager.getInstance().isLoggedIn(session)) {
165 session.setAttribute("next_action", "listSubscriptions");
166 return showLoginForm(arguments, context);
167 }
168 String username = (String) session.getAttribute("username");
169 context.put("title", "List of Subscriptions for " + username);
170 try {
171 Collection subscriptions = ProfileStore.getInstance().getAllSubscriptionsFor(username);
172 context.put("list", subscriptions);
173 return "list.vm";
174 } catch (DatabaseException de) {
175 context.put("message", "couldn't get list of subscriptions for " + username);
176 context.put("details", de.getMessage());
177 return "error.vm";
178 }
179 }
180
181 public String login(Map arguments, Context context) throws Exception {
182 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
183 try {
184 UserManager.getInstance().loginUser(arguments, session);
185 } catch (UserManagementException e) {
186 context.put("error", Boolean.TRUE);
187 context.put("errormessage", e.getMessage());
188 return showLoginForm(arguments, context);
189 }
190 if (session.getAttribute("next_action") != null) {
191 String nextAction = (String) session.getAttribute("next_action");
192 Method method = AlertingService.class.getDeclaredMethod(nextAction, new Class[] {Map.class, Context.class});
193 return (String) method.invoke(this, new Object[] {arguments, context});
194 }
195 return listSubscriptions(arguments, context);
196 }
197
198 public String register(Map arguments, Context context) throws Exception {
199 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
200 try {
201 UserManager.getInstance().createUser(arguments, session);
202 } catch (UserManagementException e) {
203 context.put("error", Boolean.TRUE);
204 context.put("errormessage", e.getMessage());
205 return showRegistrationForm(arguments, context);
206 }
207 return login(arguments, context);
208 }
209
210 public String logout(Map arguments, Context context) {
211 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
212 Enumeration atts = session.getAttributeNames();
213 while (atts.hasMoreElements()) {
214 session.removeAttribute((String) atts.nextElement());
215 }
216 session.invalidate();
217 return "general.vm";
218 }
219
220 public void receiveEvent(Map rawEvent) {
221 Map event = new TreeMap();
222 for (Iterator iter = rawEvent.keySet().iterator(); iter.hasNext();) {
223 String key = (String) iter.next();
224 String[] value = (String[]) rawEvent.get(key);
225 event.put(key, value[0]);
226 }
227
228 GreenstoneCommunicator gsComm = null;
229 try {
230 gsComm = new GreenstoneCommunicator(new URL((String) event.get("hostID")));
231 } catch (MalformedURLException e) {
232 // TODO Auto-generated catch block
233 e.printStackTrace();
234 } catch (Exception e) {
235 // TODO Auto-generated catch block
236 e.printStackTrace();
237 }
238 Set matchedSubscriptions = ProfileStore.getInstance().filter(event, gsComm);
239 System.out.println(matchedSubscriptions.size() + " matching subscriptions: " + matchedSubscriptions);
240 // TODO do something with the matched subscriptions
241 }
242
243 /**
244 * @param args
245 */
246 private Map normalise(Map args) {
247 Map result = new TreeMap();
248 for (Iterator iter = args.keySet().iterator(); iter.hasNext();) {
249 String key = (String) iter.next();
250 if (Predicate.isMultiValued(key) || key.equals("way")) {
251 // multi-valued attributes
252 String[] values = ((String[]) args.get(key));
253 result.put(key, Arrays.asList(values));
254 } else {
255 String firstValue = ((String[])args.get(key))[0];
256 result.put(key, firstValue);
257 }
258 }
259 return result;
260 }
261
262 /**
263 * @param context
264 * @param message
265 * @param details
266 * @return
267 */
268 private Template showError(Context context, String message, String details) {
269 context.put("title", "Error");
270 context.put("message", message);
271 context.put("details", details);
272 try {
273 return getTemplate("error.vm");
274 } catch (Exception e) {
275 try {
276 super.error((HttpServletRequest)context.get("req"),
277 (HttpServletResponse)context.get("res"),
278 e);
279 } catch (Exception e2) {
280 e2.printStackTrace();
281 }
282 }
283 return null;
284 }
285
286 /**
287 * @param arguments
288 * @param context
289 * @param create
290 * @return
291 * @throws Exception
292 */
293 private String showSubscriptionWizardPage(Map arguments, Context context, boolean create) throws Exception {
294 if (create) {
295 context.put("action", "createSubscription");
296 } else {
297 context.put("action", "editSubscription");
298 }
299 if (!arguments.containsKey("current_page")) {
300 return "sub_type-details.vm";
301 }
302
303 HttpSession session = ((HttpServletRequest)context.get(REQUEST)).getSession(true);
304 String currentPage = (String) arguments.get("current_page");
305 String direction = (String) arguments.get("next_page");
306
307 if (arguments.containsKey("host_query")) {
308 String hostQuery = (String) arguments.get("host_query");
309 if (hostQuery != null && hostQuery.length() != 0)
310 arguments.remove("hostID");
311 }
312 if (arguments.containsKey("collection_query")) {
313 String collQuery = (String) arguments.get("collection_query");
314 if (collQuery != null && collQuery.length() != 0)
315 arguments.remove("collectionID");
316 }
317
318 // save page arguments
319 savePageArgsToSession(currentPage, arguments, session);
320
321 String nextPage = getNextPage(currentPage, direction);
322
323 // fill prefill
324 context.put("prefill", getPageArgsFromSession(nextPage, session));
325
326 // fill preview
327 context.put("preview", getPagePreview(nextPage, session));
328
329 // get page-specific stuff
330 if (nextPage.equals("host")) {
331 String[] hostNames;
332 try {
333 GreenstoneCommunicator gsComm = new GreenstoneCommunicator();
334 hostNames = gsComm.getHostNames();
335 } catch (Exception e) {
336 hostNames = new String[] { "localhost" };
337 }
338 context.put("hostnames", hostNames);
339 session.setAttribute("hostnames", hostNames);
340 } else if (nextPage.equals("collection")) {
341 // TODO might be query instead of just name
342 List hostNames = (List) arguments.get("hostID");
343 if (hostNames == null || hostNames.isEmpty()) {
344 hostNames = new Vector();
345 // no host names -> use host query
346 String[] hostsFromSession = (String[]) session.getAttribute("hostnames");
347 if (hostsFromSession == null || hostsFromSession.length == 0) {
348 try {
349 GreenstoneCommunicator gsComm = new GreenstoneCommunicator();
350 hostsFromSession = gsComm.getHostNames();
351 } catch (Exception e) {
352 hostsFromSession = new String[] { "localhost" };
353 }
354 }
355 String hostQuery = (String) arguments.get("host_query");
356 for (int i = 0; i < hostsFromSession.length; i++) {
357 if (hostsFromSession[i] != null && hostsFromSession[i].indexOf(hostQuery) >= 0) {
358 hostNames.add(hostsFromSession[i]);
359 }
360 }
361 }
362
363 Map collNames = new TreeMap();
364 for (Iterator iter = hostNames.iterator(); iter.hasNext();) {
365 String host = (String) iter.next();
366 Set collNamesForHost = new TreeSet();
367 try {
368 URL url = new URL("http://" + host + ":8080/soap/servlet/rpcrouter");
369 GreenstoneCommunicator gsComm = new GreenstoneCommunicator(url);
370 collNamesForHost.addAll(Arrays.asList(gsComm.getCollectionNames()));
371 } catch (Exception e) {
372 // TODO Auto-generated catch block
373 e.printStackTrace();
374 }
375 collNames.put(host, collNamesForHost);
376 }
377 context.put("collectionnames", collNames);
378 context.put("hostnames", hostNames);
379 }
380
381 return "sub_" + nextPage + ".vm";
382 }
383
384 /**
385 * @param nextPage
386 * @param session
387 * @return
388 */
389 private Map getPagePreview(String nextPage, HttpSession session) {
390 Map preview = new TreeMap();
391 if (nextPage.equals("type-details")) {
392 return preview;
393 }
394 preview.putAll(getPageArgsFromSession("type-details", session));
395 if (nextPage.equals("host")) {
396 return preview;
397 }
398 preview.putAll(getPageArgsFromSession("host", session));
399 if (nextPage.equals("collection")) {
400 return preview;
401 }
402 preview.putAll(getPageArgsFromSession("collection", session));
403 return preview;
404 }
405
406 /**
407 * @param currentPage
408 * @param direction
409 * @return
410 * @throws Exception
411 */
412 private String getNextPage(String currentPage, String direction) throws Exception {
413 String nextPage;
414 if (currentPage.equals("host") && direction.equals("back")) {
415 nextPage = "type-details";
416 } else if (currentPage.equals("type-details") || (currentPage.equals("collection") && direction.equals("back"))) {
417 nextPage = "host";
418 } else if (currentPage.equals("host") || (currentPage.equals("notification") && direction.equals("back"))) {
419 nextPage = "collection";
420 } else if (currentPage.equals("collection")) {
421 nextPage = "notification";
422 } else {
423 throw new Exception("unknown combination of currentPage=" + currentPage + " and nextPage=" + direction);
424 }
425 return nextPage;
426 }
427
428 /**
429 * @param page
430 * @param session
431 * @return
432 */
433 private Map getPageArgsFromSession(String page, HttpSession session) {
434 Map pageArgs = (Map) session.getAttribute("page_args");
435 if (pageArgs == null || !pageArgs.containsKey(page))
436 return new TreeMap();
437 return (Map) pageArgs.get(page);
438 }
439
440 private Map getPageArgsFromSession(HttpSession session) {
441 Map result = new TreeMap();
442 Map pageArgs = (Map) session.getAttribute("page_args");
443 if (pageArgs != null) {
444 for (Iterator iter = pageArgs.values().iterator(); iter.hasNext();) {
445 Map args = (Map) iter.next();
446 result.putAll(args);
447 }
448 }
449 return result;
450 }
451
452 /**
453 * @param page
454 * @param arguments
455 * @param session
456 */
457 private void savePageArgsToSession(String page, Map arguments, HttpSession session) {
458 Map pageArgs = (Map) session.getAttribute("page_args");
459 if (pageArgs == null) {
460 pageArgs = new TreeMap();
461 }
462 pageArgs.put(page, arguments);
463 session.setAttribute("page_args", pageArgs);
464 }
465}
Note: See TracBrowser for help on using the repository browser.