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

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

This will now copy the uploaded file rather than moving it

  • Property svn:keywords set to Author Date Id Revision
File size: 28.2 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
547 // set the lang in the session
548 session.setAttribute(GSParams.LANGUAGE, lang);
549
550 String output = request.getParameter(GSParams.OUTPUT);
551 if (output == null || output.equals(""))
552 {
553 output = "html"; // uses html by default
554 }
555
556 // If server output, force a switch to traditional interface
557 //output = (output.equals("server")) ? "html" : output;
558
559 // Force change the output mode if client-side XSLT is supported - server vs. client
560 // BUT only if the library allows client-side transforms
561 if (supports_client_xslt)
562 {
563 // MUST be done before the xml_message is built
564 Cookie[] cookies = request.getCookies();
565 Cookie xsltCookie = null;
566
567 // The client has cookies enabled and a value set - use it!
568 if (cookies != null)
569 {
570 for (Cookie c : cookies)
571 {
572 if (c.getName().equals("supportsXSLT"))
573 {
574 xsltCookie = c;
575 break;
576 }
577 }
578 output = (xsltCookie != null && xsltCookie.getValue().equals("true") && output.equals("html")) ? "xsltclient" : output;
579 }
580 }
581
582 // the request to the receptionist
583 Element xml_message = this.doc.createElement(GSXML.MESSAGE_ELEM);
584 Element xml_request = GSXML.createBasicRequest(this.doc, GSXML.REQUEST_TYPE_PAGE, "", lang, uid);
585 xml_request.setAttribute(GSXML.OUTPUT_ATT, output);
586
587 xml_message.appendChild(xml_request);
588
589 String action = request.getParameter(GSParams.ACTION);
590 String subaction = request.getParameter(GSParams.SUBACTION);
591 String collection = request.getParameter(GSParams.COLLECTION);
592 String service = request.getParameter(GSParams.SERVICE);
593
594 // We clean up the cache session_ids_table if system
595 // commands are issued (and also don't need to do caching for this request)
596 boolean should_cache = true;
597 if (action != null && action.equals(GSParams.SYSTEM))
598 {
599 should_cache = false;
600
601 // we may want to remove all collection cache info, or just a specific collection
602 boolean clean_all = true;
603 String clean_collection = null;
604 // system commands are to activate/deactivate stuff
605 // collection param is in the sc parameter.
606 // don't like the fact that it is hard coded here
607 String coll = request.getParameter(GSParams.SYSTEM_CLUSTER);
608 if (coll != null && !coll.equals(""))
609 {
610 clean_all = false;
611 clean_collection = coll;
612 }
613 else
614 {
615 // check other system types
616 if (subaction.equals("a") || subaction.equals("d"))
617 {
618 String module_name = request.getParameter("sn");
619 if (module_name != null && !module_name.equals(""))
620 {
621 clean_all = false;
622 clean_collection = module_name;
623 }
624 }
625 }
626 if (clean_all)
627 {
628 session_ids_table = new Hashtable();
629 session.removeAttribute(GSXML.USER_SESSION_CACHE_ATT);
630 }
631 else
632 {
633 // just clean up info for clean_collection
634 ArrayList cache_list = new ArrayList(session_ids_table.values());
635 for (int i = 0; i < cache_list.size(); i++)
636 {
637 UserSessionCache cache = (UserSessionCache) cache_list.get(i);
638 cache.cleanupCache(clean_collection);
639 }
640
641 }
642
643 }
644
645 // cache_key is the collection name, or service name
646 String cache_key = collection;
647 if (cache_key == null || cache_key.equals(""))
648 {
649 cache_key = service;
650 }
651
652 // logger.info("should_cache= " + should_cache);
653
654 //clear the collection-specific cache in the session, since we have no way to know whether this session is
655 //about the same collection as the last session or not.
656 Enumeration attributeNames = session.getAttributeNames();
657 while (attributeNames.hasMoreElements())
658 {
659 String name = (String) attributeNames.nextElement();
660 if (!name.equals(GSXML.USER_SESSION_CACHE_ATT) && !name.equals(GSParams.LANGUAGE) && !name.equals(GSXML.USER_ID_ATT))
661 {
662
663 session.removeAttribute(name);
664 }
665 }
666
667 UserSessionCache session_cache = null;
668 Hashtable param_table = null;
669 Hashtable table = null;
670 String sid = session.getId();
671 if (should_cache == true && cache_key != null && !cache_key.equals(""))
672 {
673 if (session_ids_table.containsKey(sid))
674 {
675 session_cache = (UserSessionCache) session_ids_table.get(sid);
676 param_table = session_cache.getParamsTable();
677 logger.info("collections in table: " + tableToString(param_table));
678 if (param_table.containsKey(cache_key))
679 {
680 //logger.info("existing table: " + collection);
681 table = (Hashtable) param_table.get(cache_key);
682 }
683 else
684 {
685 table = new Hashtable();
686 param_table.put(cache_key, table);
687 //logger.info("new table: " + collection);
688 }
689 }
690 else
691 {
692 param_table = new Hashtable();
693 table = new Hashtable();
694 param_table.put(cache_key, table);
695 session_cache = new UserSessionCache(sid, param_table);
696 session_ids_table.put(sid, session_cache);
697 session.setAttribute(GSXML.USER_SESSION_CACHE_ATT, session_cache);
698 //logger.info("new session id");
699 }
700 }
701
702 if (action == null || action.equals(""))
703 {
704 // should we do all the following stuff if using default page?
705 // display the home page - the default page
706 xml_request.setAttribute(GSXML.ACTION_ATT, "p");
707 xml_request.setAttribute(GSXML.SUBACTION_ATT, PageAction.HOME_PAGE);
708 }
709 else
710 {
711 xml_request.setAttribute(GSXML.ACTION_ATT, action);
712 if (subaction != null)
713 {
714 xml_request.setAttribute(GSXML.SUBACTION_ATT, subaction);
715 }
716
717 // create the param list for the greenstone request - includes
718 // the params from the current request and any others from the saved session
719 Element xml_param_list = this.doc.createElement(GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
720 xml_request.appendChild(xml_param_list);
721
722 Enumeration params = request.getParameterNames();
723 while (params.hasMoreElements())
724 {
725 String name = (String) params.nextElement();
726 if (!name.equals(GSParams.ACTION) && !name.equals(GSParams.SUBACTION) && !name.equals(GSParams.LANGUAGE) && !name.equals(GSParams.OUTPUT))
727 {// we have already dealt with these
728
729 String value = "";
730 String[] values = request.getParameterValues(name);
731 value = values[0];
732 if (values.length > 1)
733 {
734 for (int i = 1; i < values.length; i++)
735 {
736 value += "," + values[i];
737 }
738 }
739 // either add it to the param list straight away, or save it to the session and add it later
740 if (this.params.shouldSave(name) && table != null)
741 {
742 table.put(name, value);
743 }
744 else
745 {
746 Element param = this.doc.createElement(GSXML.PARAM_ELEM);
747 param.setAttribute(GSXML.NAME_ATT, name);
748 param.setAttribute(GSXML.VALUE_ATT, GSXML.xmlSafe(value));
749 xml_param_list.appendChild(param);
750 }
751 }
752 }
753 //put everything in the table into the session
754 // do we need to do this? why not just put from table into param list
755 if (table != null)
756 {
757 Enumeration keys = table.keys();
758 while (keys.hasMoreElements())
759 {
760 String name = (String) keys.nextElement();
761 session.setAttribute(name, (String) table.get(name));
762 }
763 }
764
765 // put in all the params from the session cache
766 params = session.getAttributeNames();
767 while (params.hasMoreElements())
768 {
769 String name = (String) params.nextElement();
770
771 if (!name.equals(GSXML.USER_SESSION_CACHE_ATT) && !name.equals(GSParams.LANGUAGE) && !name.equals(GSXML.USER_ID_ATT))
772 {
773
774 // lang and uid are stored but we dont want it in the param list cos its already in the request
775 Element param = this.doc.createElement(GSXML.PARAM_ELEM);
776 param.setAttribute(GSXML.NAME_ATT, name);
777 String value = GSXML.xmlSafe((String) session.getAttribute(name));
778
779 // ugly hack to undo : escaping
780 value = StringUtils.replace(value, "%3A", "\\:");
781 param.setAttribute(GSXML.VALUE_ATT, value);
782 xml_param_list.appendChild(param);
783 }
784 }
785 }
786
787 if (!output.equals("html") && !output.equals("server") && !output.equals("xsltclient"))
788 {
789 response.setContentType("text/xml"); // for now use text
790 }
791
792 //Add custom HTTP headers if requested
793 String httpHeadersParam = request.getParameter(GSParams.HTTPHEADERFIELDS);
794 if (httpHeadersParam != null && httpHeadersParam.length() > 0)
795 {
796 Gson gson = new Gson();
797 Type type = new TypeToken<List<Map<String, String>>>()
798 {
799 }.getType();
800 List<Map<String, String>> httpHeaders = gson.fromJson(httpHeadersParam, type);
801 if (httpHeaders != null && httpHeaders.size() > 0)
802 {
803
804 for (int j = 0; j < httpHeaders.size(); j++)
805 {
806 Map nameValueMap = (Map) httpHeaders.get(j);
807 String name = (String) nameValueMap.get("name");
808 String value = (String) nameValueMap.get("value");
809
810 if (name != null && value != null)
811 {
812 response.setHeader(name, value);
813 }
814 }
815 }
816 }
817
818 Node xml_result = this.recept.process(xml_message);
819 encodeURLs(xml_result, response);
820 out.println(this.converter.getPrettyString(xml_result));
821
822 displaySize(session_ids_table);
823
824 } //end of doGet(HttpServletRequest, HttpServletResponse)
825
826 //a debugging method
827 private void displaySize(Hashtable table)
828 {
829 if (table == null)
830 {
831 logger.info("cached table is null");
832 return;
833 }
834 if (table.size() == 0)
835 {
836 logger.info("cached table size is zero");
837 return;
838 }
839 int num_cached_coll = 0;
840 ArrayList cache_list = new ArrayList(table.values());
841 for (int i = 0; i < cache_list.size(); i++)
842 {
843 num_cached_coll += ((UserSessionCache) cache_list.get(i)).tableSize();
844 }
845 logger.info("Number of sessions : total number of cached collection info = " + table.size() + " : " + num_cached_coll);
846 }
847
848 /** merely a debugging method! */
849 private String tableToString(Hashtable table)
850 {
851 String str = "";
852 Enumeration keys = table.keys();
853 while (keys.hasMoreElements())
854 {
855 String name = (String) keys.nextElement();
856 str += name + ", ";
857 }
858 return str;
859 }
860
861 /**
862 * this goes through each URL and adds in a session id if needed-- its
863 * needed if the browser doesn't accept cookies also escapes things if
864 * needed
865 */
866 protected void encodeURLs(Node dataNode, HttpServletResponse response)
867 {
868
869 if (dataNode == null)
870 {
871 return;
872 }
873
874 Element data = null;
875
876 short nodeType = dataNode.getNodeType();
877 if (nodeType == Node.DOCUMENT_NODE)
878 {
879 Document docNode = (Document) dataNode;
880 data = docNode.getDocumentElement();
881 }
882 else
883 {
884 data = (Element) dataNode;
885 }
886
887 if (data != null)
888 {
889
890 // get all the <a> elements
891 NodeList hrefs = data.getElementsByTagName("a");
892 // Instead of calculating each iteration...
893 int hrefscount = hrefs.getLength();
894
895 for (int i = 0; hrefs != null && i < hrefscount; i++)
896 {
897 Element a = (Element) hrefs.item(i);
898 // ugly hack to get rid of : in the args - interferes with session handling
899 String href = a.getAttribute("href");
900 if (!href.equals(""))
901 {
902 if (href.indexOf("?") != -1)
903 {
904 String[] parts = StringUtils.split(href, "\\?", -1);
905 if (parts.length == 1)
906 {
907 parts[0] = StringUtils.replace(parts[0], ":", "%3A");
908 href = "?" + parts[0];
909 }
910 else
911 {
912 parts[1] = StringUtils.replace(parts[1], ":", "%3A");
913 href = parts[0] + "?" + parts[1];
914 }
915
916 }
917 a.setAttribute("href", response.encodeURL(href));
918 }
919 }
920
921 // now find any submit bits - get all the <form> elements
922 NodeList forms = data.getElementsByTagName("form");
923 int formscount = forms.getLength();
924 for (int i = 0; forms != null && i < formscount; i++)
925 {
926 Element form = (Element) forms.item(i);
927 form.setAttribute("action", response.encodeURL(form.getAttribute("action")));
928 }
929 // are these the only cases where URLs occur??
930 // we should only do this for greenstone urls?
931 }
932
933 }
934
935 synchronized protected int getNextUserId()
936 {
937 next_user_id++;
938 return next_user_id;
939 }
940
941 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
942 {
943 doGet(request, response);
944 }
945}
Note: See TracBrowser for help on using the repository browser.