source: main/trunk/greenstone3/src/java/org/greenstone/gsdl3/LibraryServlet.java@ 25304

Last change on this file since 25304 was 25304, checked in by kjdon, 12 years ago

removed a few hard coded strings, working on handling external links

  • Property svn:keywords set to Author Date Id Revision
File size: 32.0 KB
Line 
1package org.greenstone.gsdl3;
2
3import org.greenstone.gsdl3.comms.*;
4import org.greenstone.gsdl3.core.*;
5import org.greenstone.gsdl3.service.Authentication;
6import org.greenstone.gsdl3.util.*;
7import org.greenstone.gsdl3.action.PageAction; // used to get the default action
8import org.w3c.dom.Document;
9import org.w3c.dom.Element;
10import org.w3c.dom.Node;
11import org.w3c.dom.NodeList;
12import java.io.*;
13import javax.servlet.*;
14import javax.servlet.http.*;
15
16import java.util.Enumeration;
17import java.util.ArrayList;
18import java.util.HashMap;
19import java.util.Iterator;
20import java.util.List;
21import java.util.Map;
22import java.lang.reflect.Type;
23import java.util.Hashtable;
24import org.apache.log4j.*;
25
26import com.google.gson.Gson;
27import com.google.gson.reflect.TypeToken;
28
29// Apache Commons
30import org.apache.commons.lang3.*;
31
32/**
33 * a servlet to serve the greenstone library - we are using servlets instead of
34 * cgi the init method is called only once - the first time the servlet classes
35 * are loaded. Each time a request comes in to the servlet, the session() method
36 * is called in a new thread (calls doGet/doPut etc) takes the a=p&p=home type
37 * args and builds a simple request to send to its receptionist, which returns a
38 * result in html, cos output=html is set in the request
39 *
40 * 18/Jul/07 xiao modify to make the cached parameters collection-specific. Most
41 * of the work is done in doGet(), except adding an inner class
42 * UserSessionCache.
43 *
44 * @see Receptionist
45 */
46public class LibraryServlet extends HttpServlet
47{
48
49 /** the receptionist to send messages to */
50 protected Receptionist recept = null;
51
52 /**
53 * the default language - is specified by setting a servlet param, otherwise
54 * DEFAULT_LANG is used
55 */
56 protected String default_lang = null;
57
58 /** Whether or not client-side XSLT support should be exposed */
59 protected boolean supports_client_xslt = false;
60
61 /**
62 * The default default - used if a default lang is not specified in the
63 * servlet params
64 */
65 protected final String DEFAULT_LANG = "en";
66
67 /** container Document to create XML Nodes */
68 protected Document doc = null;
69
70 /** a converter class to parse XML and create Docs */
71 protected XMLConverter converter = null;
72
73 /**
74 * the cgi stuff - the Receptionist can add new args to this
75 *
76 * its used by the servlet to determine what args to save
77 */
78 protected GSParams params = null;
79
80 /**
81 * user id - new one per session. This doesn't work if session state is
82 * saved between restarts - this requires this value to be saved too.
83 */
84 protected int next_user_id = 0;
85
86 /**
87 * a hash that contains all the active session IDs mapped to the cached
88 * items It is updated whenever the whole site or a particular collection is
89 * reconfigured using the command a=s&sa=c or a=s&sa=c&c=xxx It is in the
90 * form: sid -> (UserSessionCache object)
91 */
92 protected Hashtable session_ids_table = new Hashtable();
93
94 /**
95 * the maximum interval that the cached info remains in session_ids_table
96 * (in seconds) This is set in web.xml
97 */
98 protected int session_expiration = 1800;
99
100 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.LibraryServlet.class.getName());
101
102 /** initialise the servlet */
103 public void init(ServletConfig config) throws ServletException
104 {
105 // always call super.init;
106 super.init(config);
107 // disable preferences - does this work anyway??
108 //System.setProperty("java.util.prefs.PreferencesFactory", "org.greenstone.gsdl3.util.DisabledPreferencesFactory");
109
110 String library_name = config.getInitParameter(GSConstants.LIBRARY_NAME);
111 String gsdl3_home = config.getInitParameter(GSConstants.GSDL3_HOME);
112 String interface_name = config.getInitParameter(GSConstants.INTERFACE_NAME);
113
114 String allowXslt = (String) config.getInitParameter(GSConstants.ALLOW_CLIENT_SIDE_XSLT);
115 supports_client_xslt = allowXslt != null && allowXslt.equals("true");
116
117 this.default_lang = config.getInitParameter(GSConstants.DEFAULT_LANG);
118 String sess_expire = config.getInitParameter(GSXML.SESSION_EXPIRATION);
119
120 if (sess_expire != null && !sess_expire.equals(""))
121 {
122 this.session_expiration = Integer.parseInt(sess_expire);
123 }
124
125 if (library_name == null || interface_name == null)
126 {
127 // must have this
128 System.err.println("initialisation parameters not all set!");
129 System.err.println(" you must have libraryname and interfacename");
130 System.exit(1);
131 }
132
133 String site_name = config.getInitParameter(GSConstants.SITE_NAME);
134 String remote_site_name = null;
135 String remote_site_type = null;
136 String remote_site_address = null;
137
138 if (site_name == null)
139 {
140 // no site, try for communicator
141 remote_site_name = config.getInitParameter("remote_site_name");
142 remote_site_type = config.getInitParameter("remote_site_type");
143 remote_site_address = config.getInitParameter("remote_site_address");
144 if (remote_site_name == null || remote_site_type == null || remote_site_address == null)
145 {
146 System.err.println("initialisation paramters not all set!");
147 System.err.println("if site_name is not set, then you must have remote_site_name, remote_site_type and remote_site_address set");
148 System.exit(1);
149 }
150 }
151
152 if (this.default_lang == null)
153 {
154 // choose english
155 this.default_lang = DEFAULT_LANG;
156 }
157
158 HashMap config_params = new HashMap();
159
160 config_params.put(GSConstants.LIBRARY_NAME, library_name);
161 config_params.put(GSConstants.INTERFACE_NAME, interface_name);
162 config_params.put(GSConstants.ALLOW_CLIENT_SIDE_XSLT, supports_client_xslt);
163
164 if (site_name != null)
165 {
166 config_params.put(GSConstants.SITE_NAME, site_name);
167 }
168 this.converter = new XMLConverter();
169 this.doc = this.converter.newDOM();
170
171 // the receptionist -the servlet will talk to this
172 String recept_name = (String) config.getInitParameter("receptionist_class");
173 if (recept_name == null)
174 {
175 this.recept = new DefaultReceptionist();
176 }
177 else
178 {
179 try
180 {
181 this.recept = (Receptionist) Class.forName("org.greenstone.gsdl3.core." + recept_name).newInstance();
182 }
183 catch (Exception e)
184 { // cant use this new one, so use normal one
185 System.err.println("LibraryServlet configure exception when trying to use a new Receptionist " + recept_name + ": " + e.getMessage());
186 e.printStackTrace();
187 this.recept = new DefaultReceptionist();
188 }
189 }
190 this.recept.setConfigParams(config_params);
191
192 // the receptionist uses a MessageRouter or Communicator to send its requests to. We either create a MessageRouter here for the designated site (if site_name set), or we create a Communicator for a remote site. The is given to teh Receptionist, and the servlet never talks to it again.directly.
193 if (site_name != null)
194 {
195 String mr_name = (String) config.getInitParameter("messagerouter_class");
196 MessageRouter message_router = null;
197 if (mr_name == null)
198 { // just use the normal MR
199 message_router = new MessageRouter();
200 }
201 else
202 { // try the specified one
203 try
204 {
205 message_router = (MessageRouter) Class.forName("org.greenstone.gsdl3.core." + mr_name).newInstance();
206 }
207 catch (Exception e)
208 { // cant use this new one, so use normal one
209 System.err.println("LibraryServlet configure exception when trying to use a new MessageRouter " + mr_name + ": " + e.getMessage());
210 e.printStackTrace();
211 message_router = new MessageRouter();
212 }
213 }
214
215 message_router.setSiteName(site_name);
216 message_router.setLibraryName(library_name);
217 message_router.configure();
218 this.recept.setMessageRouter(message_router);
219 }
220 else
221 {
222 // talking to a remote site, create a communicator
223 Communicator communicator = null;
224 // we need to create the XML to configure the communicator
225 Element site_elem = this.doc.createElement(GSXML.SITE_ELEM);
226 site_elem.setAttribute(GSXML.TYPE_ATT, remote_site_type);
227 site_elem.setAttribute(GSXML.NAME_ATT, remote_site_name);
228 site_elem.setAttribute(GSXML.ADDRESS_ATT, remote_site_address);
229
230 if (remote_site_type.equals(GSXML.COMM_TYPE_SOAP_JAVA))
231 {
232 communicator = new SOAPCommunicator();
233 }
234 else
235 {
236 System.err.println("LibraryServlet.init Error: invalid Communicator type: " + remote_site_type);
237 System.exit(1);
238 }
239
240 if (!communicator.configure(site_elem))
241 {
242 System.err.println("LibraryServlet.init Error: Couldn't configure communicator");
243 System.exit(1);
244 }
245 this.recept.setMessageRouter(communicator);
246 }
247
248 // the params arg thingy
249
250 String params_name = (String) config.getInitParameter("params_class");
251 if (params_name == null)
252 {
253 this.params = new GSParams();
254 }
255 else
256 {
257 try
258 {
259 this.params = (GSParams) Class.forName("org.greenstone.gsdl3.util." + params_name).newInstance();
260 }
261 catch (Exception e)
262 {
263 System.err.println("LibraryServlet configure exception when trying to use a new params thing " + params_name + ": " + e.getMessage());
264 e.printStackTrace();
265 this.params = new GSParams();
266 }
267 }
268 // pass it to the receptionist
269 this.recept.setParams(this.params);
270 this.recept.configure();
271
272 //Allow the message router and the document to be accessed from anywhere in this servlet context
273 this.getServletContext().setAttribute("GSRouter", this.recept.getMessageRouter());
274 this.getServletContext().setAttribute("GSDocument", this.doc);
275 }
276
277 private void logUsageInfo(HttpServletRequest request)
278 {
279 String usageInfo = "";
280
281 //session-info: get params stored in the session
282 HttpSession session = request.getSession(true);
283 Enumeration attributeNames = session.getAttributeNames();
284 while (attributeNames.hasMoreElements())
285 {
286 String name = (String) attributeNames.nextElement();
287 usageInfo += name + "=" + session.getAttribute(name) + " ";
288 }
289
290 //logged info = general-info + session-info
291 usageInfo = request.getServletPath() + " " + //serlvet
292 "[" + request.getQueryString() + "]" + " " + //the query string
293 "[" + usageInfo.trim() + "]" + " " + // params stored in a session
294 request.getRemoteAddr() + " " + //remote address
295 request.getRequestedSessionId() + " " + //session id
296 request.getHeader("user-agent") + " "; //the remote brower info
297
298 logger.info(usageInfo);
299
300 }
301
302 public class UserSessionCache implements HttpSessionBindingListener
303 {
304
305 String session_id = "";
306
307 /**
308 * a hash that maps the session ID to a hashtable that maps the
309 * coll_name to its parameters coll_name -> Hashtable (param_name ->
310 * param_value)
311 */
312 protected Hashtable coll_name_params_table = null;
313
314 public UserSessionCache(String id, Hashtable table)
315 {
316 session_id = id;
317 coll_name_params_table = (table == null) ? new Hashtable() : table;
318 }
319
320 protected void cleanupCache(String coll_name)
321 {
322 if (coll_name_params_table.containsKey(coll_name))
323 {
324 coll_name_params_table.remove(coll_name);
325 }
326 }
327
328 protected Hashtable getParamsTable()
329 {
330 return coll_name_params_table;
331 }
332
333 public void valueBound(HttpSessionBindingEvent event)
334 {
335 // Do nothing
336 }
337
338 public void valueUnbound(HttpSessionBindingEvent event)
339 {
340 if (session_ids_table.containsKey(session_id))
341 {
342 session_ids_table.remove(session_id);
343 }
344 }
345
346 public int tableSize()
347 {
348 return (coll_name_params_table == null) ? 0 : coll_name_params_table.size();
349 }
350
351 }
352
353 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
354 {
355 logUsageInfo(request);
356
357 Map<String, String[]> queryMap = request.getParameterMap();
358 if (queryMap != null)
359 {
360 Iterator<String> queryIter = queryMap.keySet().iterator();
361 boolean redirect = false;
362 String href = null;
363 String rl = null;
364 String el = null;
365 while (queryIter.hasNext())
366 {
367 String q = queryIter.next();
368 if (q.equals(GSParams.EXTERNAL_LINK_TYPE))
369 {
370 el = queryMap.get(q)[0];
371 }
372 else if (q.equals(GSParams.HREF))
373 {
374 href = queryMap.get(q)[0];
375 href = StringUtils.replace(href, "%2f", "/");
376 href = StringUtils.replace(href, "%7e", "~");
377 href = StringUtils.replace(href, "%3f", "?");
378 href = StringUtils.replace(href, "%3A", "\\:");
379 }
380 else if (q.equals(GSParams.RELATIVE_LINK))
381 {
382 rl = queryMap.get(q)[0];
383 }
384 }
385
386 //if query_string contains "el=direct", an href is specified, and its not a relative link, then the web page will be redirected to the external URl, otherwise a greenstone page with an external URL will be displayed
387 //"rl=0" this is an external link
388 //"rl=1" this is an internal link
389 if ((href != null) && (rl.equals("0")))
390 {// This is an external link,
391
392 if (el.equals("framed")) {
393 //TODO **** how best to change to a=p&sa=html&c=collection&url=href
394 // response.setContentType("text/xml");
395 //response.sendRedirect("http://localhost:8383/greenstone3/gs3library?a=p&sa=html&c=external&url="+href);
396 } else {
397 // el = '' or direct
398 //the web page is re-directed to the external URL (&el=&rl=0&href="http://...")
399 response.setContentType("text/xml");
400 response.sendRedirect(href);
401 }
402 }
403 }
404
405 // Nested Diagnostic Configurator to identify the client for
406 HttpSession session = request.getSession(true);
407 session.setMaxInactiveInterval(session_expiration);
408 String uid = (String) session.getAttribute(GSXML.USER_ID_ATT);
409 if (uid == null)
410 {
411 uid = "" + getNextUserId();
412 session.setAttribute(GSXML.USER_ID_ATT, uid);
413 }
414
415 request.setCharacterEncoding("UTF-8");
416 response.setContentType("text/html;charset=UTF-8");
417 PrintWriter out = response.getWriter();
418
419 String lang = request.getParameter(GSParams.LANGUAGE);
420 if (lang == null || lang.equals(""))
421 {
422 // try the session cached lang
423 lang = (String) session.getAttribute(GSParams.LANGUAGE);
424 if (lang == null || lang.equals(""))
425 {
426 // still not set, use the default
427 lang = this.default_lang;
428 }
429 }
430 UserContext userContext = new UserContext();
431 userContext.setLanguage(lang);
432 userContext.setUserID(uid);
433
434 // set the lang in the session
435 session.setAttribute(GSParams.LANGUAGE, lang);
436
437 String output = request.getParameter(GSParams.OUTPUT);
438 if (output == null || output.equals(""))
439 {
440 output = "html"; // uses html by default
441 }
442
443 // If server output, force a switch to traditional interface
444 //output = (output.equals("server")) ? "html" : output;
445
446 // Force change the output mode if client-side XSLT is supported - server vs. client
447 // BUT only if the library allows client-side transforms
448 if (supports_client_xslt)
449 {
450 // MUST be done before the xml_message is built
451 Cookie[] cookies = request.getCookies();
452 Cookie xsltCookie = null;
453
454 // The client has cookies enabled and a value set - use it!
455 if (cookies != null)
456 {
457 for (Cookie c : cookies)
458 {
459 if (c.getName().equals("supportsXSLT"))
460 {
461 xsltCookie = c;
462 break;
463 }
464 }
465 output = (xsltCookie != null && xsltCookie.getValue().equals("true") && output.equals("html")) ? "xsltclient" : output;
466 }
467 }
468
469 // the request to the receptionist
470 Element xml_message = this.doc.createElement(GSXML.MESSAGE_ELEM);
471 Element xml_request = GSXML.createBasicRequest(this.doc, GSXML.REQUEST_TYPE_PAGE, "", userContext);
472 xml_request.setAttribute(GSXML.OUTPUT_ATT, output);
473
474 xml_message.appendChild(xml_request);
475
476 String action = request.getParameter(GSParams.ACTION);
477 String subaction = request.getParameter(GSParams.SUBACTION);
478 String collection = request.getParameter(GSParams.COLLECTION);
479 String document = request.getParameter(GSParams.DOCUMENT);
480 String service = request.getParameter(GSParams.SERVICE);
481
482 // We clean up the cache session_ids_table if system
483 // commands are issued (and also don't need to do caching for this request)
484 boolean should_cache = true;
485 if (action != null && action.equals(GSParams.SYSTEM_ACTION))
486 {
487 should_cache = false;
488
489 // we may want to remove all collection cache info, or just a specific collection
490 boolean clean_all = true;
491 String clean_collection = null;
492 // system commands are to activate/deactivate stuff
493 // collection param is in the sc parameter.
494 // don't like the fact that it is hard coded here
495 String coll = request.getParameter(GSParams.SYSTEM_CLUSTER);
496 if (coll != null && !coll.equals(""))
497 {
498 clean_all = false;
499 clean_collection = coll;
500 }
501 else
502 {
503 // check other system types
504 if (subaction.equals("a") || subaction.equals("d"))
505 {
506 String module_name = request.getParameter("sn");
507 if (module_name != null && !module_name.equals(""))
508 {
509 clean_all = false;
510 clean_collection = module_name;
511 }
512 }
513 }
514 if (clean_all)
515 {
516 session_ids_table = new Hashtable();
517 session.removeAttribute(GSXML.USER_SESSION_CACHE_ATT);
518 }
519 else
520 {
521 // just clean up info for clean_collection
522 ArrayList cache_list = new ArrayList(session_ids_table.values());
523 for (int i = 0; i < cache_list.size(); i++)
524 {
525 UserSessionCache cache = (UserSessionCache) cache_list.get(i);
526 cache.cleanupCache(clean_collection);
527 }
528
529 }
530 }
531
532 // cache_key is the collection name, or service name
533 String cache_key = collection;
534 if (cache_key == null || cache_key.equals(""))
535 {
536 cache_key = service;
537 }
538
539 // logger.info("should_cache= " + should_cache);
540
541 //clear the collection-specific cache in the session, since we have no way to know whether this session is
542 //about the same collection as the last session or not.
543 Enumeration attributeNames = session.getAttributeNames();
544 while (attributeNames.hasMoreElements())
545 {
546 String name = (String) attributeNames.nextElement();
547 if (!name.equals(GSXML.USER_SESSION_CACHE_ATT) && !name.equals(GSParams.LANGUAGE) && !name.equals(GSXML.USER_ID_ATT))
548 {
549 session.removeAttribute(name);
550 }
551 }
552
553 UserSessionCache session_cache = null;
554 Hashtable param_table = null;
555 Hashtable table = null;
556 String sid = session.getId();
557 if (should_cache == true && cache_key != null && !cache_key.equals(""))
558 {
559 if (session_ids_table.containsKey(sid))
560 {
561 session_cache = (UserSessionCache) session_ids_table.get(sid);
562 param_table = session_cache.getParamsTable();
563 logger.info("collections in table: " + tableToString(param_table));
564 if (param_table.containsKey(cache_key))
565 {
566 //logger.info("existing table: " + collection);
567 table = (Hashtable) param_table.get(cache_key);
568 }
569 else
570 {
571 table = new Hashtable();
572 param_table.put(cache_key, table);
573 //logger.info("new table: " + collection);
574 }
575 }
576 else
577 {
578 param_table = new Hashtable();
579 table = new Hashtable();
580 param_table.put(cache_key, table);
581 session_cache = new UserSessionCache(sid, param_table);
582 session_ids_table.put(sid, session_cache);
583 session.setAttribute(GSXML.USER_SESSION_CACHE_ATT, session_cache);
584 //logger.info("new session id");
585 }
586 }
587
588 if (action == null || action.equals(""))
589 {
590 // should we do all the following stuff if using default page?
591 // display the home page - the default page
592 xml_request.setAttribute(GSXML.ACTION_ATT, "p");
593 xml_request.setAttribute(GSXML.SUBACTION_ATT, PageAction.HOME_PAGE);
594 }
595 else
596 {
597 xml_request.setAttribute(GSXML.ACTION_ATT, action);
598 if (subaction != null)
599 {
600 xml_request.setAttribute(GSXML.SUBACTION_ATT, subaction);
601 }
602
603 // create the param list for the greenstone request - includes
604 // the params from the current request and any others from the saved session
605 Element xml_param_list = this.doc.createElement(GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
606 xml_request.appendChild(xml_param_list);
607
608 for (String name : queryMap.keySet())
609 {
610 if (!name.equals(GSParams.ACTION) && !name.equals(GSParams.SUBACTION) && !name.equals(GSParams.LANGUAGE) && !name.equals(GSParams.OUTPUT))
611 {// we have already dealt with these
612
613 String value = "";
614 String[] values = request.getParameterValues(name);
615 value = values[0];
616 if (values.length > 1)
617 {
618 for (int i = 1; i < values.length; i++)
619 {
620 value += "," + values[i];
621 }
622 }
623 // either add it to the param list straight away, or save it to the session and add it later
624 if (this.params.shouldSave(name) && table != null)
625 {
626 table.put(name, value);
627 }
628 else
629 {
630 Element param = this.doc.createElement(GSXML.PARAM_ELEM);
631 param.setAttribute(GSXML.NAME_ATT, name);
632 param.setAttribute(GSXML.VALUE_ATT, GSXML.xmlSafe(value));
633 xml_param_list.appendChild(param);
634 }
635 }
636 }
637 //put everything in the table into the session
638 // do we need to do this? why not just put from table into param list
639 if (table != null)
640 {
641 Enumeration keys = table.keys();
642 while (keys.hasMoreElements())
643 {
644 String name = (String) keys.nextElement();
645 session.setAttribute(name, (String) table.get(name));
646 }
647 }
648
649 // put in all the params from the session cache
650 Enumeration params = session.getAttributeNames();
651 while (params.hasMoreElements())
652 {
653 String name = (String) params.nextElement();
654
655 if (!name.equals(GSXML.USER_SESSION_CACHE_ATT) && !name.equals(GSParams.LANGUAGE) && !name.equals(GSXML.USER_ID_ATT))
656 {
657
658 // lang and uid are stored but we dont want it in the param list cos its already in the request
659 Element param = this.doc.createElement(GSXML.PARAM_ELEM);
660 param.setAttribute(GSXML.NAME_ATT, name);
661 String value = GSXML.xmlSafe((String) session.getAttribute(name));
662
663 // ugly hack to undo : escaping
664 value = StringUtils.replace(value, "%3A", "\\:");
665 param.setAttribute(GSXML.VALUE_ATT, value);
666 xml_param_list.appendChild(param);
667 }
668 }
669 }
670
671 if (!output.equals("html") && !output.equals("server") && !output.equals("xsltclient"))
672 {
673 response.setContentType("text/xml"); // for now use text
674 }
675
676 //Add custom HTTP headers if requested
677 String httpHeadersParam = request.getParameter(GSParams.HTTPHEADERFIELDS);
678 if (httpHeadersParam != null && httpHeadersParam.length() > 0)
679 {
680 Gson gson = new Gson();
681 Type type = new TypeToken<List<Map<String, String>>>()
682 {
683 }.getType();
684 List<Map<String, String>> httpHeaders = gson.fromJson(httpHeadersParam, type);
685 if (httpHeaders != null && httpHeaders.size() > 0)
686 {
687
688 for (int j = 0; j < httpHeaders.size(); j++)
689 {
690 Map nameValueMap = (Map) httpHeaders.get(j);
691 String name = (String) nameValueMap.get("name");
692 String value = (String) nameValueMap.get("value");
693
694 if (name != null && value != null)
695 {
696 response.setHeader(name, value);
697 }
698 }
699 }
700 }
701
702 String requestedURL = request.getRequestURL().toString();
703 String baseURL = requestedURL.substring(0, requestedURL.indexOf(this.getServletName()));
704 xml_request.setAttribute("baseURL", baseURL);
705 xml_request.setAttribute("remoteAddress", request.getRemoteAddr());
706
707 if(!runSecurityChecks(request, xml_request, userContext, out, baseURL, collection, document))
708 {
709 return;
710 }
711
712 Node xml_result = this.recept.process(xml_message);
713 encodeURLs(xml_result, response);
714 out.println(this.converter.getPrettyString(xml_result));
715
716 displaySize(session_ids_table);
717
718 } //end of doGet(HttpServletRequest, HttpServletResponse)
719
720 private boolean runSecurityChecks(HttpServletRequest request, Element xml_request, UserContext userContext, PrintWriter out, String baseURL, String collection, String document) throws ServletException
721 {
722 //Check if we need to login or logout
723 Map<String, String[]> params = request.getParameterMap();
724 String[] username = params.get("username");
725 String[] password = params.get("password");
726 String[] logout = params.get("logout");
727
728 if (logout != null)
729 {
730 request.logout();
731 }
732
733 if (username != null && password != null)
734 {
735 if (request.getAuthType() != null)
736 {
737 request.logout();
738 }
739
740 try
741 {
742 password[0] = Authentication.hashPassword(password[0]);
743 request.login(username[0], password[0]);
744 }
745 catch (Exception ex)
746 {
747 //The user entered in either the wrong username or the wrong password
748 Element loginPageMessage = this.doc.createElement(GSXML.MESSAGE_ELEM);
749 Element loginPageRequest = GSXML.createBasicRequest(this.doc, GSXML.REQUEST_TYPE_PAGE, "", userContext);
750 loginPageRequest.setAttribute(GSXML.ACTION_ATT, "p");
751 loginPageRequest.setAttribute(GSXML.SUBACTION_ATT, "login");
752 loginPageRequest.setAttribute(GSXML.OUTPUT_ATT, "html");
753 loginPageRequest.setAttribute(GSXML.BASE_URL, baseURL);
754 loginPageMessage.appendChild(loginPageRequest);
755
756 Element paramList = this.doc.createElement(GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
757 loginPageRequest.appendChild(paramList);
758
759 Element messageParam = this.doc.createElement(GSXML.PARAM_ELEM);
760 messageParam.setAttribute(GSXML.NAME_ATT, "loginMessage");
761 messageParam.setAttribute(GSXML.VALUE_ATT, "Either your username or password was incorrect, please try again.");
762 paramList.appendChild(messageParam);
763
764 Element urlParam = this.doc.createElement(GSXML.PARAM_ELEM);
765 urlParam.setAttribute(GSXML.NAME_ATT, "redirectURL");
766 String queryString = "";
767 if(request.getQueryString() != null)
768 {
769 queryString = "?" + request.getQueryString().replace("&", "&amp;");
770 }
771 urlParam.setAttribute(GSXML.VALUE_ATT, this.getServletName() + queryString);
772 paramList.appendChild(urlParam);
773
774 Node loginPageResponse = this.recept.process(loginPageMessage);
775 out.println(this.converter.getPrettyString(loginPageResponse));
776
777 return false;
778 }
779 }
780
781 //If a user is logged in
782 if (request.getAuthType() != null)
783 {
784 Element userInformation = this.doc.createElement(GSXML.USER_INFORMATION_ELEM);
785 userInformation.setAttribute("username", request.getUserPrincipal().getName());
786
787 Element userInfoMessage = this.doc.createElement(GSXML.MESSAGE_ELEM);
788 Element userInfoRequest = GSXML.createBasicRequest(this.doc, GSXML.REQUEST_TYPE_SECURITY, "GetUserInformation", userContext);
789 userInfoMessage.appendChild(userInfoRequest);
790
791 Element paramList = this.doc.createElement(GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
792 userInfoRequest.appendChild(paramList);
793
794 Element param = this.doc.createElement(GSXML.PARAM_ELEM);
795 param.setAttribute(GSXML.NAME_ATT, GSXML.USERNAME_ATT);
796 param.setAttribute(GSXML.VALUE_ATT, request.getUserPrincipal().getName());
797 paramList.appendChild(param);
798
799 Element userInformationResponse = (Element) GSXML.getChildByTagName(this.recept.process(userInfoMessage), GSXML.RESPONSE_ELEM);
800 Element responseParamList = (Element) GSXML.getChildByTagName(userInformationResponse, GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
801 if (responseParamList == null)
802 {
803 logger.error("Can't get the groups for user " + request.getUserPrincipal().getName());
804 }
805 else
806 {
807 HashMap responseParams = GSXML.extractParams(responseParamList, true);
808 String groups = (String) responseParams.get(GSXML.GROUPS_ATT);
809
810 userInformation.setAttribute(GSXML.GROUPS_ATT, groups);
811 xml_request.appendChild(userInformation);
812 }
813 }
814
815 //If we are in a collection-related page then make sure this user is allowed to access it
816 if (collection != null && !collection.equals(""))
817 {
818 //Get the security info for this collection
819 Element securityMessage = this.doc.createElement(GSXML.MESSAGE_ELEM);
820 Element securityRequest = GSXML.createBasicRequest(this.doc, GSXML.REQUEST_TYPE_SECURITY, collection, userContext);
821 securityMessage.appendChild(securityRequest);
822 if (document != null && !document.equals(""))
823 {
824 securityRequest.setAttribute(GSXML.NODE_OID, document);
825 }
826
827 Element securityResponse = (Element) GSXML.getChildByTagName(this.recept.process(securityMessage), GSXML.RESPONSE_ELEM);
828 ArrayList<String> groups = GSXML.getGroupsFromSecurityResponse(securityResponse);
829
830 //If guests are not allowed to access this page then check to see if the user is in a group that is allowed to access the page
831 if (!groups.contains(""))
832 {
833 boolean found = false;
834 for (String group : groups)
835 {
836 if (request.isUserInRole(group))
837 {
838 found = true;
839 break;
840 }
841 }
842
843 //The current user is not allowed to access the page so produce a login page
844 if (!found)
845 {
846 Element loginPageMessage = this.doc.createElement(GSXML.MESSAGE_ELEM);
847 Element loginPageRequest = GSXML.createBasicRequest(this.doc, GSXML.REQUEST_TYPE_PAGE, "", userContext);
848 loginPageRequest.setAttribute(GSXML.ACTION_ATT, "p");
849 loginPageRequest.setAttribute(GSXML.SUBACTION_ATT, "login");
850 loginPageRequest.setAttribute(GSXML.OUTPUT_ATT, "html");
851 loginPageRequest.setAttribute(GSXML.BASE_URL, baseURL);
852 loginPageMessage.appendChild(loginPageRequest);
853
854 Element paramList = this.doc.createElement(GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
855 loginPageRequest.appendChild(paramList);
856
857 Element messageParam = this.doc.createElement(GSXML.PARAM_ELEM);
858 messageParam.setAttribute(GSXML.NAME_ATT, "loginMessage");
859 if (request.getAuthType() == null)
860 {
861 messageParam.setAttribute(GSXML.VALUE_ATT, "Please log in to view this page");
862 }
863 else
864 {
865 messageParam.setAttribute(GSXML.VALUE_ATT, "You are not in the correct group to view this page, would you like to log in as a different user?");
866 }
867 paramList.appendChild(messageParam);
868
869 Element urlParam = this.doc.createElement(GSXML.PARAM_ELEM);
870 urlParam.setAttribute(GSXML.NAME_ATT, "redirectURL");
871 urlParam.setAttribute(GSXML.VALUE_ATT, this.getServletName() + "?" + request.getQueryString().replace("&", "&amp;"));
872 paramList.appendChild(urlParam);
873
874 Node loginPageResponse = this.recept.process(loginPageMessage);
875 out.println(this.converter.getPrettyString(loginPageResponse));
876
877 return false;
878 }
879 }
880 }
881 return true;
882 }
883
884 //a debugging method
885 private void displaySize(Hashtable table)
886 {
887 if (table == null)
888 {
889 logger.info("cached table is null");
890 return;
891 }
892 if (table.size() == 0)
893 {
894 logger.info("cached table size is zero");
895 return;
896 }
897 int num_cached_coll = 0;
898 ArrayList cache_list = new ArrayList(table.values());
899 for (int i = 0; i < cache_list.size(); i++)
900 {
901 num_cached_coll += ((UserSessionCache) cache_list.get(i)).tableSize();
902 }
903 logger.info("Number of sessions : total number of cached collection info = " + table.size() + " : " + num_cached_coll);
904 }
905
906 /** merely a debugging method! */
907 private String tableToString(Hashtable table)
908 {
909 String str = "";
910 Enumeration keys = table.keys();
911 while (keys.hasMoreElements())
912 {
913 String name = (String) keys.nextElement();
914 str += name + ", ";
915 }
916 return str;
917 }
918
919 /**
920 * this goes through each URL and adds in a session id if needed-- its
921 * needed if the browser doesn't accept cookies also escapes things if
922 * needed
923 */
924 protected void encodeURLs(Node dataNode, HttpServletResponse response)
925 {
926
927 if (dataNode == null)
928 {
929 return;
930 }
931
932 Element data = null;
933
934 short nodeType = dataNode.getNodeType();
935 if (nodeType == Node.DOCUMENT_NODE)
936 {
937 Document docNode = (Document) dataNode;
938 data = docNode.getDocumentElement();
939 }
940 else
941 {
942 data = (Element) dataNode;
943 }
944
945 if (data != null)
946 {
947
948 // get all the <a> elements
949 NodeList hrefs = data.getElementsByTagName("a");
950 // Instead of calculating each iteration...
951 int hrefscount = hrefs.getLength();
952
953 for (int i = 0; hrefs != null && i < hrefscount; i++)
954 {
955 Element a = (Element) hrefs.item(i);
956 // ugly hack to get rid of : in the args - interferes with session handling
957 String href = a.getAttribute("href");
958 if (!href.equals(""))
959 {
960 if (href.indexOf("?") != -1)
961 {
962 String[] parts = StringUtils.split(href, "\\?", -1);
963 if (parts.length == 1)
964 {
965 parts[0] = StringUtils.replace(parts[0], ":", "%3A");
966 href = "?" + parts[0];
967 }
968 else
969 {
970 parts[1] = StringUtils.replace(parts[1], ":", "%3A");
971 href = parts[0] + "?" + parts[1];
972 }
973
974 }
975 a.setAttribute("href", response.encodeURL(href));
976 }
977 }
978
979 // now find any submit bits - get all the <form> elements
980 NodeList forms = data.getElementsByTagName("form");
981 int formscount = forms.getLength();
982 for (int i = 0; forms != null && i < formscount; i++)
983 {
984 Element form = (Element) forms.item(i);
985 form.setAttribute("action", response.encodeURL(form.getAttribute("action")));
986 }
987 // are these the only cases where URLs occur??
988 // we should only do this for greenstone urls?
989 }
990
991 }
992
993 synchronized protected int getNextUserId()
994 {
995 next_user_id++;
996 return next_user_id;
997 }
998
999 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
1000 {
1001 doGet(request, response);
1002 }
1003}
Note: See TracBrowser for help on using the repository browser.