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

Last change on this file since 24993 was 24993, checked in by sjm84, 12 years ago

Adding UserContext to replace the use of lang and uid

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