source: main/trunk/greenstone3/src/java/org/greenstone/gsdl3/core/TransformingReceptionist.java@ 26555

Last change on this file since 26555 was 26555, checked in by sjm84, 11 years ago

Fixing the location of the collectionConfig file

  • Property svn:keywords set to Author Date Id Revision
File size: 38.1 KB
Line 
1package org.greenstone.gsdl3.core;
2
3import java.io.File;
4import java.io.FileReader;
5import java.io.Serializable;
6import java.io.StringWriter;
7import java.util.ArrayList;
8import java.util.HashMap;
9
10import javax.xml.transform.Transformer;
11import javax.xml.transform.TransformerException;
12import javax.xml.transform.TransformerFactory;
13import javax.xml.transform.dom.DOMSource;
14import javax.xml.transform.stream.StreamResult;
15
16import org.apache.commons.lang3.StringUtils;
17import org.apache.log4j.Logger;
18import org.apache.xerces.parsers.DOMParser;
19import org.greenstone.gsdl3.action.Action;
20import org.greenstone.gsdl3.util.GSConstants;
21import org.greenstone.gsdl3.util.GSFile;
22import org.greenstone.gsdl3.util.GSParams;
23import org.greenstone.gsdl3.util.GSXML;
24import org.greenstone.gsdl3.util.GSXSLT;
25import org.greenstone.gsdl3.util.UserContext;
26import org.greenstone.gsdl3.util.XMLConverter;
27import org.greenstone.gsdl3.util.XMLTransformer;
28import org.greenstone.util.GlobalProperties;
29import org.w3c.dom.Comment;
30import org.w3c.dom.Document;
31import org.w3c.dom.Element;
32import org.w3c.dom.Node;
33import org.w3c.dom.NodeList;
34import org.w3c.dom.Text;
35import org.xml.sax.InputSource;
36
37/**
38 * A receptionist that uses xslt to transform the page_data before returning it.
39 * . Receives requests consisting of an xml representation of cgi args, and
40 * returns the page of data - in html by default. The requests are processed by
41 * the appropriate action class
42 *
43 * @see Action
44 */
45public class TransformingReceptionist extends Receptionist
46{
47 protected static final int CONFIG_PASS = 1;
48 protected static final int TEXT_PASS = 2;
49
50 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.core.TransformingReceptionist.class.getName());
51
52 /** The preprocess.xsl file is in a fixed location */
53 static final String preprocess_xsl_filename = GlobalProperties.getGSDL3Home() + File.separatorChar + "interfaces" + File.separatorChar + "core" + File.separatorChar + "transform" + File.separatorChar + "preProcess.xsl";
54
55 /** the list of xslt to use for actions */
56 protected HashMap<String, String> xslt_map = null;
57
58 /** a transformer class to transform xml using xslt */
59 protected XMLTransformer transformer = null;
60
61 protected TransformerFactory transformerFactory = null;
62 protected DOMParser parser = null;
63
64 protected HashMap<String, ArrayList<String>> _metadataRequiredMap = new HashMap<String, ArrayList<String>>();
65
66 boolean _debug = true;
67
68 public TransformingReceptionist()
69 {
70 super();
71 this.xslt_map = new HashMap<String, String>();
72 this.transformer = new XMLTransformer();
73 try
74 {
75 transformerFactory = org.apache.xalan.processor.TransformerFactoryImpl.newInstance();
76 this.converter = new XMLConverter();
77 //transformerFactory.setURIResolver(new MyUriResolver()) ;
78
79 parser = new DOMParser();
80 parser.setFeature("http://xml.org/sax/features/validation", false);
81 // don't try and load external DTD - no need if we are not validating, and may cause connection errors if a proxy is not set up.
82 parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
83 // a performance test showed that having this on lead to increased
84 // memory use for small-medium docs, and not much gain for large
85 // docs.
86 // http://www.sosnoski.com/opensrc/xmlbench/conclusions.html
87 parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
88 parser.setFeature("http://apache.org/xml/features/continue-after-fatal-error", true);
89 // setting a handler for when fatal errors, errors or warnings happen during xml parsing
90 // call XMLConverter's getParseErrorMessage() to get the errorstring that can be rendered as web page
91 this.parser.setErrorHandler(new XMLConverter.ParseErrorHandler());
92 }
93 catch (Exception e)
94 {
95 e.printStackTrace();
96 }
97 }
98
99 /** configures the receptionist - overwrite this to set up the xslt map */
100 public boolean configure()
101 {
102 if (this.config_params == null)
103 {
104 logger.error(" config variables must be set before calling configure");
105 return false;
106 }
107 if (this.mr == null)
108 {
109 logger.error(" message router must be set before calling configure");
110 return false;
111 }
112
113 // find the config file containing a list of actions
114 File interface_config_file = new File(GSFile.interfaceConfigFile(GSFile.interfaceHome(GlobalProperties.getGSDL3Home(), (String) this.config_params.get(GSConstants.INTERFACE_NAME))));
115 if (!interface_config_file.exists())
116 {
117 logger.error(" interface config file: " + interface_config_file.getPath() + " not found!");
118 return false;
119 }
120 Document config_doc = this.converter.getDOM(interface_config_file, "utf-8");
121 if (config_doc == null)
122 {
123 logger.error(" could not parse interface config file: " + interface_config_file.getPath());
124 return false;
125 }
126 Element config_elem = config_doc.getDocumentElement();
127 String base_interface = config_elem.getAttribute("baseInterface");
128 setUpBaseInterface(base_interface);
129 setUpInterfaceOptions(config_elem);
130
131 Element action_list = (Element) GSXML.getChildByTagName(config_elem, GSXML.ACTION_ELEM + GSXML.LIST_MODIFIER);
132 NodeList actions = action_list.getElementsByTagName(GSXML.ACTION_ELEM);
133
134 for (int i = 0; i < actions.getLength(); i++)
135 {
136 Element action = (Element) actions.item(i);
137 String class_name = action.getAttribute("class");
138 String action_name = action.getAttribute("name");
139 Action ac = null;
140 try
141 {
142 ac = (Action) Class.forName("org.greenstone.gsdl3.action." + class_name).newInstance();
143 }
144 catch (Exception e)
145 {
146 logger.error(" couldn't load in action " + class_name);
147 e.printStackTrace();
148 continue;
149 }
150 ac.setConfigParams(this.config_params);
151 ac.setMessageRouter(this.mr);
152 ac.configure();
153 ac.addActionParameters(this.params);
154 this.action_map.put(action_name, ac);
155
156 // now do the xslt map
157 String xslt = action.getAttribute("xslt");
158 if (!xslt.equals(""))
159 {
160 this.xslt_map.put(action_name, xslt);
161 }
162 NodeList subactions = action.getElementsByTagName(GSXML.SUBACTION_ELEM);
163 for (int j = 0; j < subactions.getLength(); j++)
164 {
165 Element subaction = (Element) subactions.item(j);
166 String subname = subaction.getAttribute(GSXML.NAME_ATT);
167 String subxslt = subaction.getAttribute("xslt");
168
169 String map_key = action_name + ":" + subname;
170 logger.debug("adding in to xslt map, " + map_key + "->" + subxslt);
171 this.xslt_map.put(map_key, subxslt);
172 }
173 }
174 Element lang_list = (Element) GSXML.getChildByTagName(config_elem, "languageList");
175 if (lang_list == null)
176 {
177 logger.error(" didn't find a language list in the config file!!");
178 }
179 else
180 {
181 this.language_list = (Element) this.doc.importNode(lang_list, true);
182 }
183
184 getRequiredMetadataNamesFromXSLFiles();
185
186 return true;
187 }
188
189 protected void getRequiredMetadataNamesFromXSLFiles()
190 {
191 ArrayList<File> xslFiles = GSFile.getAllXSLFiles((String) this.config_params.get(GSConstants.INTERFACE_NAME), (String) this.config_params.get(GSConstants.SITE_NAME));
192
193 HashMap<String, ArrayList<String>> includes = new HashMap<String, ArrayList<String>>();
194 HashMap<String, ArrayList<File>> files = new HashMap<String, ArrayList<File>>();
195 HashMap<String, ArrayList<String>> metaNames = new HashMap<String, ArrayList<String>>();
196
197 //First exploratory pass
198 for (File currentFile : xslFiles)
199 {
200 Document currentDoc = this.converter.getDOM(currentFile);
201 NodeList metadataElems = currentDoc.getElementsByTagNameNS(GSXML.GSF_NAMESPACE, "metadata"); //gsf:metadata
202 NodeList foreachMetadataElems = currentDoc.getElementsByTagNameNS(GSXML.GSF_NAMESPACE, "foreach-metadata"); //gsf:foreach-metadata
203 NodeList imageElems = currentDoc.getElementsByTagNameNS(GSXML.GSF_NAMESPACE, "image"); //gsf:image
204 NodeList includeElems = currentDoc.getElementsByTagNameNS(GSXML.XSL_NAMESPACE, "include");
205 NodeList importElems = currentDoc.getElementsByTagNameNS(GSXML.XSL_NAMESPACE, "import");
206
207 ArrayList<String> names = new ArrayList<String>();
208 for (int i = 0; i < metadataElems.getLength(); i++)
209 {
210 Element current = (Element) metadataElems.item(i);
211 String name = current.getAttribute(GSXML.NAME_ATT);
212 if (name != null && name.length() > 0 && !names.contains(name))
213 {
214 names.add(name);
215 }
216 }
217
218 for (int i = 0; i < foreachMetadataElems.getLength(); i++)
219 {
220 Element current = (Element) foreachMetadataElems.item(i);
221 String name = current.getAttribute(GSXML.NAME_ATT);
222 if (name != null && name.length() > 0 && !names.contains(name))
223 {
224 names.add(name);
225 }
226 }
227
228 for (int i = 0; i < imageElems.getLength(); i++)
229 {
230 Element current = (Element) imageElems.item(i);
231 String type = current.getAttribute(GSXML.TYPE_ATT);
232 if (type == null || type.length() == 0)
233 {
234 continue;
235 }
236
237 if (type.equals("source"))
238 {
239 String[] standardSourceMeta = new String[] { "SourceFile", "ImageHeight", "ImageWidth", "ImageType", "srcicon" };
240 for (String meta : standardSourceMeta)
241 {
242 if (!names.contains(meta))
243 {
244 names.add(meta);
245 }
246 }
247 }
248 else if (type.equals("screen"))
249 {
250 String[] standardScreenMeta = new String[] { "Screen", "ScreenHeight", "ScreenWidth", "ScreenType", "screenicon" };
251 for (String meta : standardScreenMeta)
252 {
253 if (!names.contains(meta))
254 {
255 names.add(meta);
256 }
257 }
258 }
259 else if (type.equals("thumb"))
260 {
261 String[] standardThumbMeta = new String[] { "Thumb", "ThumbHeight", "ThumbWidth", "ThumbType", "thumbicon" };
262 for (String meta : standardThumbMeta)
263 {
264 if (!names.contains(meta))
265 {
266 names.add(meta);
267 }
268 }
269 }
270 }
271
272 metaNames.put(currentFile.getAbsolutePath(), names);
273
274 ArrayList<String> includeAndImportList = new ArrayList<String>();
275 for (int i = 0; i < includeElems.getLength(); i++)
276 {
277 includeAndImportList.add(((Element) includeElems.item(i)).getAttribute(GSXML.HREF_ATT));
278 }
279 for (int i = 0; i < importElems.getLength(); i++)
280 {
281 includeAndImportList.add(((Element) importElems.item(i)).getAttribute(GSXML.HREF_ATT));
282 }
283 includes.put(currentFile.getAbsolutePath(), includeAndImportList);
284
285 String filename = currentFile.getName();
286 if (files.get(filename) == null)
287 {
288 ArrayList<File> fileList = new ArrayList<File>();
289 fileList.add(currentFile);
290 files.put(currentFile.getName(), fileList);
291 }
292 else
293 {
294 ArrayList<File> fileList = files.get(filename);
295 fileList.add(currentFile);
296 }
297 }
298
299 //Second pass
300 for (File currentFile : xslFiles)
301 {
302 ArrayList<File> filesToGet = new ArrayList<File>();
303 filesToGet.add(currentFile);
304
305 ArrayList<String> fullNameList = new ArrayList<String>();
306
307 while (filesToGet.size() > 0)
308 {
309 File currentFileTemp = filesToGet.remove(0);
310
311 //Add the names from this file
312 ArrayList<String> currentNames = metaNames.get(currentFileTemp.getAbsolutePath());
313 fullNameList.addAll(currentNames);
314
315 ArrayList<String> includedHrefs = includes.get(currentFileTemp.getAbsolutePath());
316
317 for (String href : includedHrefs)
318 {
319 int lastSepIndex = href.lastIndexOf("/");
320 if (lastSepIndex != -1)
321 {
322 href = href.substring(lastSepIndex + 1);
323 }
324
325 ArrayList<File> filesToAdd = files.get(href);
326 if (filesToAdd != null)
327 {
328 filesToGet.addAll(filesToAdd);
329 }
330 }
331 }
332
333 _metadataRequiredMap.put(currentFile.getAbsolutePath(), fullNameList);
334 }
335 }
336
337 protected void preProcessRequest(Element request)
338 {
339 String action = request.getAttribute(GSXML.ACTION_ATT);
340 String subaction = request.getAttribute(GSXML.SUBACTION_ATT);
341
342 String name = null;
343 if (!subaction.equals(""))
344 {
345 String key = action + ":" + subaction;
346 name = this.xslt_map.get(key);
347 }
348 // try the action by itself
349 if (name == null)
350 {
351 name = this.xslt_map.get(action);
352 }
353
354 String stylesheetFile = GSFile.interfaceStylesheetFile(GlobalProperties.getGSDL3Home(), (String) this.config_params.get(GSConstants.INTERFACE_NAME), name);
355 stylesheetFile = stylesheetFile.replace("/", File.separator);
356
357 ArrayList<String> requiredMetadata = _metadataRequiredMap.get(stylesheetFile);
358
359 if (requiredMetadata != null)
360 {
361 Element extraMetadataList = this.doc.createElement(GSXML.EXTRA_METADATA + GSXML.LIST_MODIFIER);
362
363 for (String metadataString : requiredMetadata)
364 {
365 Element metadataElem = this.doc.createElement(GSXML.EXTRA_METADATA);
366 metadataElem.setAttribute(GSXML.NAME_ATT, metadataString);
367 extraMetadataList.appendChild(metadataElem);
368 }
369 request.appendChild(request.getOwnerDocument().importNode(extraMetadataList, true));
370 }
371 }
372
373 protected Node postProcessPage(Element page)
374 {
375 // might need to add some data to the page
376 addExtraInfo(page);
377 // transform the page using xslt
378 Node transformed_page = transformPage(page);
379
380 // if the user has specified they want only a part of the full page then subdivide it
381 boolean subdivide = false;
382 String excerptID = null;
383 String excerptTag = null;
384 Element request = (Element) GSXML.getChildByTagName(page, GSXML.PAGE_REQUEST_ELEM);
385 Element cgi_param_list = (Element) GSXML.getChildByTagName(request, GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
386 if (cgi_param_list != null)
387 {
388 HashMap<String, Serializable> params = GSXML.extractParams(cgi_param_list, false);
389 if ((excerptID = (String) params.get(GSParams.EXCERPT_ID)) != null)
390 {
391 subdivide = true;
392 }
393 if ((excerptTag = (String) params.get(GSParams.EXCERPT_TAG)) != null)
394 {
395 subdivide = true;
396 }
397 }
398
399 if (subdivide)
400 {
401 Node subdivided_page = subdivide(transformed_page, excerptID, excerptTag);
402 if (subdivided_page != null)
403 {
404 return subdivided_page;
405 }
406 }
407
408 return transformed_page;
409 }
410
411 protected Node subdivide(Node transformed_page, String excerptID, String excerptTag)
412 {
413 if (excerptID != null)
414 {
415 Node selectedElement = getNodeByIdRecursive(transformed_page, excerptID);
416 modifyNodesByTagRecursive(selectedElement, "a");
417 return selectedElement;
418 }
419 else if (excerptTag != null)
420 {
421 Node selectedElement = getNodeByTagRecursive(transformed_page, excerptTag);
422 return selectedElement;
423 }
424 return transformed_page;
425 }
426
427 protected Node getNodeByIdRecursive(Node parent, String id)
428 {
429 if (parent.hasAttributes() && ((Element) parent).getAttribute("id").equals(id))
430 {
431 return parent;
432 }
433
434 NodeList children = parent.getChildNodes();
435 for (int i = 0; i < children.getLength(); i++)
436 {
437 Node result = null;
438 if ((result = getNodeByIdRecursive(children.item(i), id)) != null)
439 {
440 return result;
441 }
442 }
443 return null;
444 }
445
446 protected Node getNodeByTagRecursive(Node parent, String tag)
447 {
448 if (parent.getNodeType() == Node.ELEMENT_NODE && ((Element) parent).getTagName().equals(tag))
449 {
450 return parent;
451 }
452
453 NodeList children = parent.getChildNodes();
454 for (int i = 0; i < children.getLength(); i++)
455 {
456 Node result = null;
457 if ((result = getNodeByTagRecursive(children.item(i), tag)) != null)
458 {
459 return result;
460 }
461 }
462 return null;
463 }
464
465 protected Node modifyNodesByTagRecursive(Node parent, String tag)
466 {
467 if (parent == null || (parent.getNodeType() == Node.ELEMENT_NODE && ((Element) parent).getTagName().equals(tag)))
468 {
469 return parent;
470 }
471
472 NodeList children = parent.getChildNodes();
473 for (int i = 0; i < children.getLength(); i++)
474 {
475 Node result = null;
476 if ((result = modifyNodesByTagRecursive(children.item(i), tag)) != null)
477 {
478 //TODO: DO SOMETHING HERE?
479 }
480 }
481 return null;
482 }
483
484 /**
485 * overwrite this to add any extra info that might be needed in the page
486 * before transformation
487 */
488 protected void addExtraInfo(Element page)
489 {
490 }
491
492 /**
493 * transform the page using xslt we need to get any format element out of
494 * the page and add it to the xslt before transforming
495 */
496 protected Node transformPage(Element page)
497 {
498 _debug = false;
499
500 boolean allowsClientXSLT = (Boolean) config_params.get(GSConstants.ALLOW_CLIENT_SIDE_XSLT);
501 //System.out.println("Client side transforms allowed? " + allowsClientXSLT);
502
503 String currentInterface = (String) config_params.get(GSConstants.INTERFACE_NAME);
504
505 Element request = (Element) GSXML.getChildByTagName(page, GSXML.PAGE_REQUEST_ELEM);
506 String output = request.getAttribute(GSXML.OUTPUT_ATT);
507
508 //System.out.println("Current output mode is: " + output + ", current interface name is: " + currentInterface);
509
510 if (allowsClientXSLT)
511 {
512 if (!currentInterface.endsWith(GSConstants.CLIENT_SIDE_XSLT_INTERFACE_SUFFIX) && output.equals("html"))
513 {
514 System.out.println("output is html and we are not currently using a client side version, switching");
515 // Switch the interface
516 config_params.put(GSConstants.INTERFACE_NAME, currentInterface.concat(GSConstants.CLIENT_SIDE_XSLT_INTERFACE_SUFFIX));
517 }
518 else if ((currentInterface.endsWith(GSConstants.CLIENT_SIDE_XSLT_INTERFACE_SUFFIX) && !output.equals("html")) || output.equals("server"))
519 {
520 // The reverse needs to happen too
521 config_params.put(GSConstants.INTERFACE_NAME, currentInterface.substring(0, currentInterface.length() - GSConstants.CLIENT_SIDE_XSLT_INTERFACE_SUFFIX.length()));
522 }
523 }
524 else if (currentInterface.endsWith(GSConstants.CLIENT_SIDE_XSLT_INTERFACE_SUFFIX))
525 {
526 config_params.put(GSConstants.INTERFACE_NAME, currentInterface.substring(0, currentInterface.length() - GSConstants.CLIENT_SIDE_XSLT_INTERFACE_SUFFIX.length()));
527 }
528
529 // DocType defaults in case the skin doesn't have an "xsl:output" element
530 String qualifiedName = "html";
531 String publicID = "-//W3C//DTD HTML 4.01 Transitional//EN";
532 String systemID = "http://www.w3.org/TR/html4/loose.dtd";
533
534 // We need to create an empty document with a predefined DocType,
535 // that will then be used for the transformation by the DOMResult
536 Document docWithDoctype = converter.newDOM(qualifiedName, publicID, systemID);
537
538 if (output.equals("xsltclient"))
539 {
540 // If you're just getting the client-side transform page, why bother with the rest of this?
541 Element html = docWithDoctype.createElement("html");
542 Element img = docWithDoctype.createElement("img");
543 img.setAttribute("src", "interfaces/default/images/loading.gif"); // Make it dynamic
544 img.setAttribute("alt", "Please wait...");
545 Text title_text = docWithDoctype.createTextNode("Please wait..."); // Make this language dependent
546 Element head = docWithDoctype.createElement("head");
547 Element title = docWithDoctype.createElement("title");
548 title.appendChild(title_text);
549 Element body = docWithDoctype.createElement("body");
550 Element script = docWithDoctype.createElement("script");
551 Element jquery = docWithDoctype.createElement("script");
552 jquery.setAttribute("src", "jquery.js");
553 jquery.setAttribute("type", "text/javascript");
554 Comment jquery_comment = docWithDoctype.createComment("jQuery");
555 Comment script_comment = docWithDoctype.createComment("Filler for browser");
556 script.setAttribute("src", "test.js");
557 script.setAttribute("type", "text/javascript");
558 Element pagevar = docWithDoctype.createElement("script");
559 Element style = docWithDoctype.createElement("style");
560 style.setAttribute("type", "text/css");
561 Text style_text = docWithDoctype.createTextNode("body { text-align: center; padding: 50px; font: 14pt Arial, sans-serif; font-weight: bold; }");
562 pagevar.setAttribute("type", "text/javascript");
563 Text page_var_text = docWithDoctype.createTextNode("var placeholder = true;");
564
565 html.appendChild(head);
566 head.appendChild(title);
567 head.appendChild(style);
568 style.appendChild(style_text);
569 html.appendChild(body);
570 head.appendChild(pagevar);
571 head.appendChild(jquery);
572 head.appendChild(script);
573 pagevar.appendChild(page_var_text);
574 jquery.appendChild(jquery_comment);
575 script.appendChild(script_comment);
576 body.appendChild(img);
577 docWithDoctype.appendChild(html);
578
579 return (Node) docWithDoctype;
580 }
581
582 // Passing in the pretty string here means it needs to be generated even when not debugging; so use custom function to return blank when debug is off
583 logger.debug("page before transforming:");
584 logger.debug(this.converter.getPrettyStringLogger(page, logger));
585
586 String action = request.getAttribute(GSXML.ACTION_ATT);
587 String subaction = request.getAttribute(GSXML.SUBACTION_ATT);
588
589 // we should choose how to transform the data based on output, eg diff
590 // choice for html, and wml??
591 // for now, if output=xml, we don't transform the page, we just return
592 // the page xml
593 Document theXML = null;
594
595 if (output.equals("xml") || (output.equals("json")) || output.equals("clientside"))
596 {
597 // Append some bits and pieces first...
598 theXML = converter.newDOM();
599 // Import into new document first!
600 Node newPage = theXML.importNode(page, true);
601 theXML.appendChild(newPage);
602 Element root = theXML.createElement("xsltparams");
603 newPage.appendChild(root);
604
605 Element libname = theXML.createElement("param");
606 libname.setAttribute("name", "library_name");
607 Text libnametext = theXML.createTextNode((String) config_params.get(GSConstants.LIBRARY_NAME));
608 libname.appendChild(libnametext);
609
610 Element intname = theXML.createElement("param");
611 intname.setAttribute("name", "interface_name");
612 Text intnametext = theXML.createTextNode((String) config_params.get(GSConstants.INTERFACE_NAME));
613 intname.appendChild(intnametext);
614
615 Element siteName = theXML.createElement("param");
616 siteName.setAttribute("name", "site_name");
617 Text siteNameText = theXML.createTextNode((String) config_params.get(GSConstants.SITE_NAME));
618 siteName.appendChild(siteNameText);
619
620 Element filepath = theXML.createElement("param");
621 filepath.setAttribute("name", "filepath");
622 Text filepathtext = theXML.createTextNode(GlobalProperties.getGSDL3Home());
623 filepath.appendChild(filepathtext);
624
625 root.appendChild(libname);
626 root.appendChild(intname);
627 root.appendChild(siteName);
628 root.appendChild(filepath);
629
630 if ((output.equals("xml")) || output.equals("json")) {
631 // in the case of "json", calling method responsible for converting to JSON-string
632 return theXML.getDocumentElement();
633 }
634 }
635
636
637 Element cgi_param_list = (Element) GSXML.getChildByTagName(request, GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
638 String collection = "";
639 String inlineTemplate = "";
640 if (cgi_param_list != null)
641 {
642 // Don't waste time getting all the parameters
643 HashMap<String, Serializable> params = GSXML.extractParams(cgi_param_list, false);
644 collection = (String) params.get(GSParams.COLLECTION);
645 if (collection == null)
646 {
647 collection = "";
648 }
649
650 inlineTemplate = (String) params.get(GSParams.INLINE_TEMPLATE);
651
652 if (params.get(GSParams.DEBUG) != null && (((String) params.get(GSParams.DEBUG)).equals("on") || ((String) params.get(GSParams.DEBUG)).equals("1")))
653 {
654 _debug = true;
655 }
656 }
657
658 config_params.put("collName", collection);
659
660 Document style_doc = getXSLTDocument(action, subaction, collection);
661 if (style_doc == null)
662 {
663 String errorPage = this.converter.getParseErrorMessage();
664 if (errorPage != null)
665 {
666 return XMLTransformer.constructErrorXHTMLPage("Cannot parse the xslt file\n" + errorPage);
667 }
668 return page;
669 }
670
671 // put the page into a document - this is necessary for xslt to get
672 // the paths right if you have paths relative to the document root
673 // eg /page.
674 Document doc = this.converter.newDOM();
675 doc.appendChild(doc.importNode(page, true));
676 Element page_response = (Element) GSXML.getChildByTagName(page, GSXML.PAGE_RESPONSE_ELEM);
677 Element format_elem = (Element) GSXML.getChildByTagName(page_response, GSXML.FORMAT_ELEM);
678
679 NodeList pageElems = doc.getElementsByTagName("page");
680 if (pageElems.getLength() > 0)
681 {
682 Element pageElem = (Element) pageElems.item(0);
683 String langAtt = pageElem.getAttribute(GSXML.LANG_ATT);
684
685 if (langAtt != null && langAtt.length() > 0)
686 {
687 config_params.put("lang", langAtt);
688 }
689 }
690
691 if (output.equals("formatelem"))
692 {
693 return format_elem;
694 }
695 if (format_elem != null)
696 {
697 //page_response.removeChild(format_elem);
698 logger.debug("format elem=" + this.converter.getPrettyStringLogger(format_elem, logger));
699 // need to transform the format info
700 String configStylesheet_file = GSFile.stylesheetFile(GlobalProperties.getGSDL3Home(), (String) this.config_params.get(GSConstants.SITE_NAME), collection, (String) this.config_params.get(GSConstants.INTERFACE_NAME), base_interfaces, "config_format.xsl");
701 Document configStylesheet_doc = this.converter.getDOM(new File(configStylesheet_file));
702
703 if (configStylesheet_doc != null)
704 {
705 Document format_doc = this.converter.newDOM();
706 format_doc.appendChild(format_doc.importNode(format_elem, true));
707
708 if (_debug)
709 {
710 String siteHome = GSFile.siteHome(GlobalProperties.getGSDL3Home(), (String) this.config_params.get(GSConstants.SITE_NAME));
711 GSXSLT.insertDebugElements(format_doc, GSFile.collectionConfigFile(siteHome, collection));
712 }
713
714 Node result = this.transformer.transform(configStylesheet_doc, format_doc, config_params); // Needs addressing <-
715
716 // Since we started creating documents with DocTypes, we can end up with
717 // Document objects here. But we will be working with an Element instead,
718 // so we grab the DocumentElement() of the Document object in such a case.
719 Element new_format;
720 if (result.getNodeType() == Node.DOCUMENT_NODE)
721 {
722 new_format = ((Document) result).getDocumentElement();
723 }
724 else
725 {
726 new_format = (Element) result;
727 }
728 logger.debug("new format elem=" + this.converter.getPrettyStringLogger(new_format, logger));
729 if (output.equals("newformat"))
730 {
731 return new_format;
732 }
733
734 // add extracted GSF statements in to the main stylesheet
735 if (_debug)
736 {
737 String siteHome = GSFile.siteHome(GlobalProperties.getGSDL3Home(), (String) this.config_params.get(GSConstants.SITE_NAME));
738 GSXSLT.mergeStylesheetsDebug(style_doc, new_format, true, true, "OTHER1", GSFile.collectionConfigFile(siteHome, collection));
739 }
740 else
741 {
742 GSXSLT.mergeStylesheets(style_doc, new_format, true);
743 }
744 //System.out.println("added extracted GSF statements into the main stylesheet") ;
745
746 // add extracted GSF statements in to the debug test stylesheet
747 //GSXSLT.mergeStylesheets(oldStyle_doc, new_format);
748 }
749 else
750 {
751 logger.error(" couldn't parse the config_format stylesheet, adding the format info as is");
752 GSXSLT.mergeStylesheets(style_doc, format_elem, true);
753 //GSXSLT.mergeStylesheets(oldStyle_doc, format_elem);
754 }
755 logger.debug("the converted stylesheet is:");
756 logger.debug(this.converter.getPrettyStringLogger(style_doc.getDocumentElement(), logger));
757 }
758
759 //for debug purposes only
760 Document oldStyle_doc = style_doc;
761 Document preprocessingXsl;
762 try
763 {
764 preprocessingXsl = getDoc(preprocess_xsl_filename);
765 String errMsg = ((XMLConverter.ParseErrorHandler) parser.getErrorHandler()).getErrorMessage();
766 if (errMsg != null)
767 {
768 return XMLTransformer.constructErrorXHTMLPage("error loading preprocess xslt file: " + preprocess_xsl_filename + "\n" + errMsg);
769 }
770 }
771 catch (java.io.FileNotFoundException e)
772 {
773 return fileNotFoundErrorPage(e.getMessage());
774 }
775 catch (Exception e)
776 {
777 e.printStackTrace();
778 System.out.println("error loading preprocess xslt");
779 return XMLTransformer.constructErrorXHTMLPage("error loading preprocess xslt\n" + e.getMessage());
780 }
781
782 Document libraryXsl = null;
783 try
784 {
785 String gsLibFile = this.getGSLibXSLFilename();
786 if (new File(gsLibFile).exists())
787 {
788 libraryXsl = getDoc(gsLibFile);
789 String errMsg = ((XMLConverter.ParseErrorHandler) parser.getErrorHandler()).getErrorMessage();
790 if (errMsg != null)
791 {
792 return XMLTransformer.constructErrorXHTMLPage("Error loading xslt file: " + this.getGSLibXSLFilename() + "\n" + errMsg);
793 }
794 }
795 }
796 catch (java.io.FileNotFoundException e)
797 {
798 return fileNotFoundErrorPage(e.getMessage());
799 }
800 catch (Exception e)
801 {
802 e.printStackTrace();
803 System.out.println("error loading gslib xslt");
804 return XMLTransformer.constructErrorXHTMLPage("error loading gslib xslt\n" + e.getMessage());
805 }
806
807 // Combine the skin file and library variables/templates into one document.
808 // Please note: We dont just use xsl:import because the preprocessing stage
809 // needs to know what's available in the library.
810
811 Document skinAndLibraryXsl = null;
812 Document skinAndLibraryDoc = converter.newDOM();
813
814 // Applying the preprocessing XSLT - in its own block {} to allow use of non-unique variable names
815 {
816
817 skinAndLibraryXsl = converter.newDOM();
818 Element root = skinAndLibraryXsl.createElement("skinAndLibraryXsl");
819 skinAndLibraryXsl.appendChild(root);
820
821 Element s = skinAndLibraryXsl.createElement("skinXsl");
822 s.appendChild(skinAndLibraryXsl.importNode(style_doc.getDocumentElement(), true));
823 root.appendChild(s);
824
825 Element l = skinAndLibraryXsl.createElement("libraryXsl");
826 if (libraryXsl != null)
827 {
828 Element libraryXsl_el = libraryXsl.getDocumentElement();
829 l.appendChild(skinAndLibraryXsl.importNode(libraryXsl_el, true));
830 }
831 root.appendChild(l);
832
833 //System.out.println("Skin and Library XSL are now together") ;
834
835 //System.out.println("Pre-processing the skin file...") ;
836
837 //pre-process the skin style sheet
838 //In other words, apply the preProcess.xsl to 'skinAndLibraryXsl' in order to
839 //expand all GS-Lib statements into complete XSL statements and also to create
840 //a valid xsl style sheet document.
841
842 XMLTransformer preProcessor = new XMLTransformer();
843 // Perform the transformation, by passing in:
844 // preprocess-stylesheet, source-xsl (skinAndLibraryXsl), and the node that should
845 // be in the result (skinAndLibraryDoc)
846 preProcessor.transform_withResultNode(preprocessingXsl, skinAndLibraryXsl, skinAndLibraryDoc);
847 //System.out.println("GS-Lib statements are now expanded") ;
848 }
849
850 // there is a thing called a URIResolver which you can set for a
851 // transformer or transformer factory. may be able to use this
852 // instead of this absoluteIncludepaths hack
853
854 //GSXSLT.absoluteIncludePaths(skinAndLibraryDoc, GlobalProperties.getGSDL3Home(), (String) this.config_params.get(GSConstants.SITE_NAME), collection, (String) this.config_params.get(GSConstants.INTERFACE_NAME), base_interfaces);
855
856 //Same but for the debug version when we want the do the transformation like we use to do
857 //without any gslib elements.
858 GSXSLT.absoluteIncludePaths(oldStyle_doc, GlobalProperties.getGSDL3Home(), (String) this.config_params.get(GSConstants.SITE_NAME), collection, (String) this.config_params.get(GSConstants.INTERFACE_NAME), base_interfaces);
859
860 //Send different stages of the skin xslt to the browser for debug purposes only
861 //using &o=skindoc or &o=skinandlib etc...
862 if (output.equals("skindoc"))
863 {
864 return converter.getDOM(getStringFromDocument(style_doc));
865 }
866 if (output.equals("skinandlib"))
867 {
868 return converter.getDOM(getStringFromDocument(skinAndLibraryXsl));
869 }
870 if (output.equals("skinandlibdoc") || output.equals("clientside"))
871 {
872
873 Node skinAndLib = converter.getDOM(getStringFromDocument(skinAndLibraryDoc));
874
875 if (output.equals("skinandlibdoc"))
876 {
877 return skinAndLib;
878 }
879 else
880 {
881 // Send XML and skinandlibdoc down the line together
882 Document finalDoc = converter.newDOM();
883 Node finalDocSkin = finalDoc.importNode(skinAndLibraryDoc.getDocumentElement(), true);
884 Node finalDocXML = finalDoc.importNode(theXML.getDocumentElement(), true);
885 Element root = finalDoc.createElement("skinlibPlusXML");
886 root.appendChild(finalDocSkin);
887 root.appendChild(finalDocXML);
888 finalDoc.appendChild(root);
889 return (Node) finalDoc.getDocumentElement();
890 }
891 }
892 if (output.equals("oldskindoc"))
893 {
894 return converter.getDOM(getStringFromDocument(oldStyle_doc));
895 }
896
897 // Try to get the system and public ID from the current skin xsl document
898 // otherwise keep the default values.
899 Element root = skinAndLibraryDoc.getDocumentElement();
900 NodeList nodes = root.getElementsByTagName("xsl:output");
901 // If there is at least one "xsl:output" command in the final xsl then...
902 if (nodes.getLength() != 0)
903 {
904 // There should be only one element called xsl:output,
905 // but if this is not the case get the last one
906 Element xsl_output = (Element) nodes.item(nodes.getLength() - 1);
907 if (xsl_output != null)
908 {
909 // Qualified name will always be html even for xhtml pages
910 //String attrValue = xsl_output.getAttribute("method");
911 //qualifiedName = attrValue.equals("") ? qualifiedName : attrValue;
912
913 String attrValue = xsl_output.getAttribute("doctype-system");
914 systemID = attrValue.equals("") ? systemID : attrValue;
915
916 attrValue = xsl_output.getAttribute("doctype-public");
917 publicID = attrValue.equals("") ? publicID : attrValue;
918 }
919 }
920
921 //System.out.println(converter.getPrettyString(docWithDoctype));
922 //System.out.println("Doctype vals: " + qualifiedName + " " + publicID + " " + systemID) ;
923
924 docWithDoctype = converter.newDOM(qualifiedName, publicID, systemID);
925
926 //System.out.println("Generate final HTML from current skin") ;
927 //Transformation of the XML message from the receptionist to HTML with doctype
928
929 if (inlineTemplate != null)
930 {
931 try
932 {
933 Document inlineTemplateDoc = this.converter.getDOM("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"" + GSXML.XSL_NAMESPACE + "\" xmlns:java=\"" + GSXML.JAVA_NAMESPACE + "\" xmlns:util=\"" + GSXML.UTIL_NAMESPACE + "\" xmlns:gsf=\"" + GSXML.GSF_NAMESPACE + "\">" + inlineTemplate + "</xsl:stylesheet>", "UTF-8");
934
935 if (_debug)
936 {
937 GSXSLT.mergeStylesheetsDebug(skinAndLibraryDoc, inlineTemplateDoc.getDocumentElement(), true, true, "OTHER2", "INLINE");
938 }
939 else
940 {
941 GSXSLT.mergeStylesheets(skinAndLibraryDoc, inlineTemplateDoc.getDocumentElement(), true);
942 }
943 }
944 catch (Exception ex)
945 {
946 ex.printStackTrace();
947 }
948 }
949
950 if (_debug)
951 {
952 GSXSLT.inlineImportAndIncludeFilesDebug(skinAndLibraryDoc, null, _debug, this.getGSLibXSLFilename(), (String) this.config_params.get(GSConstants.SITE_NAME), collection, (String) this.config_params.get(GSConstants.INTERFACE_NAME), base_interfaces);
953 }
954 else
955 {
956 GSXSLT.inlineImportAndIncludeFiles(skinAndLibraryDoc, null, (String) this.config_params.get(GSConstants.SITE_NAME), collection, (String) this.config_params.get(GSConstants.INTERFACE_NAME), base_interfaces);
957 }
958 skinAndLibraryDoc = (Document) performFormatPass(collection, skinAndLibraryDoc, doc, new UserContext(request), TEXT_PASS);
959 skinAndLibraryDoc = (Document) performFormatPass(collection, skinAndLibraryDoc, doc, new UserContext(request), CONFIG_PASS);
960
961 if (output.equals("xmlfinal"))
962 {
963 return doc;
964 }
965
966 if (output.equals("skinandlibdocfinal"))
967 {
968 return converter.getDOM(getStringFromDocument(skinAndLibraryDoc));
969 }
970
971 Node finalResult = this.transformer.transform(skinAndLibraryDoc, doc, config_params, docWithDoctype);
972
973 if (_debug)
974 {
975 GSXSLT.fixTables((Document) finalResult);
976 }
977
978 return finalResult;
979
980 // The line below will do the transformation like we use to do before having Skin++ implemented,
981 // it will not contain any GS-Lib statements expanded, and the result will not contain any doctype.
982
983 //return (Element)this.transformer.transform(style_doc, doc, config_params);
984 //return null; // For now - change later
985 }
986
987 protected Node performFormatPass(String collection, Document skinAndLibraryDoc, Document doc, UserContext userContext, int pass)
988 {
989 String formatFile;
990 if (pass == CONFIG_PASS)
991 {
992 formatFile = "config_format.xsl";
993 }
994 else
995 {
996 formatFile = "text_fragment_format.xsl";
997 }
998 String configStylesheet_file = GSFile.stylesheetFile(GlobalProperties.getGSDL3Home(), (String) this.config_params.get(GSConstants.SITE_NAME), collection, (String) this.config_params.get(GSConstants.INTERFACE_NAME), base_interfaces, formatFile);
999 Document configStylesheet_doc = this.converter.getDOM(new File(configStylesheet_file));
1000
1001 if (configStylesheet_doc != null)
1002 {
1003 return this.transformer.transform(configStylesheet_doc, skinAndLibraryDoc, config_params);
1004 }
1005 return skinAndLibraryDoc;
1006 }
1007
1008 // method to convert Document to a proper XML string for debug purposes only
1009 protected String getStringFromDocument(Document doc)
1010 {
1011 String content = "";
1012 try
1013 {
1014 DOMSource domSource = new DOMSource(doc);
1015 StringWriter writer = new StringWriter();
1016 StreamResult result = new StreamResult(writer);
1017 TransformerFactory tf = TransformerFactory.newInstance();
1018 Transformer transformer = tf.newTransformer();
1019 transformer.transform(domSource, result);
1020 content = writer.toString();
1021 System.out.println("Change the & to &Amp; for proper debug display");
1022 content = StringUtils.replace(content, "&", "&amp;");
1023 writer.flush();
1024 }
1025 catch (TransformerException ex)
1026 {
1027 ex.printStackTrace();
1028 return null;
1029 }
1030 return content;
1031 }
1032
1033 protected synchronized Document getDoc(String docName) throws Exception
1034 {
1035 File xslt_file = new File(docName);
1036
1037 FileReader reader = new FileReader(xslt_file);
1038 InputSource xml_source = new InputSource(reader);
1039 this.parser.parse(xml_source);
1040 Document doc = this.parser.getDocument();
1041
1042 return doc;
1043 }
1044
1045 protected Document getXSLTDocument(String action, String subaction, String collection)
1046 {
1047 String name = null;
1048 if (!subaction.equals(""))
1049 {
1050 String key = action + ":" + subaction;
1051 name = this.xslt_map.get(key);
1052 }
1053 // try the action by itself
1054 if (name == null)
1055 {
1056 name = this.xslt_map.get(action);
1057 }
1058 if (name == null)
1059 {
1060 // so we can reandomly create any named page
1061 if (action.equals("p") && !subaction.equals(""))
1062 {
1063 // TODO: pages/ won't work for interface other than default!!
1064 name = "pages/" + subaction + ".xsl";
1065 }
1066
1067 }
1068 Document finalDoc = GSXSLT.mergedXSLTDocumentCascade(name, (String) this.config_params.get(GSConstants.SITE_NAME), collection, (String) this.config_params.get(GSConstants.INTERFACE_NAME), base_interfaces, _debug);
1069 return finalDoc;
1070 }
1071
1072 // returns the path to the gslib.xsl file that is applicable for the current interface
1073 protected String getGSLibXSLFilename()
1074 {
1075 return GSFile.xmlTransformDir(GSFile.interfaceHome(GlobalProperties.getGSDL3Home(), (String) this.config_params.get(GSConstants.INTERFACE_NAME))) + File.separatorChar + "gslib.xsl";
1076 }
1077
1078 // Call this when a FileNotFoundException could be thrown when loading an xsl (xml) file.
1079 // Returns an error xhtml page indicating which xsl (or other xml) file is missing.
1080 protected Document fileNotFoundErrorPage(String filenameMessage)
1081 {
1082 String errorMessage = "ERROR missing file: " + filenameMessage;
1083 Element errPage = XMLTransformer.constructErrorXHTMLPage(errorMessage);
1084 logger.error(errorMessage);
1085 return errPage.getOwnerDocument();
1086 }
1087}
Note: See TracBrowser for help on using the repository browser.