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

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

Don't call this if name is null

  • Property svn:keywords set to Author Date Id Revision
File size: 39.4 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((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 if (currentDoc == null)
202 {
203 // Can happen if an editor creates an auto-save temporary file
204 // (such as #header.xsl#) that is not well formed XML
205 continue;
206 }
207
208 NodeList metadataElems = currentDoc.getElementsByTagNameNS(GSXML.GSF_NAMESPACE, "metadata"); //gsf:metadata
209 NodeList foreachMetadataElems = currentDoc.getElementsByTagNameNS(GSXML.GSF_NAMESPACE, "foreach-metadata"); //gsf:foreach-metadata
210 NodeList imageElems = currentDoc.getElementsByTagNameNS(GSXML.GSF_NAMESPACE, "image"); //gsf:image
211 NodeList includeElems = currentDoc.getElementsByTagNameNS(GSXML.XSL_NAMESPACE, "include");
212 NodeList importElems = currentDoc.getElementsByTagNameNS(GSXML.XSL_NAMESPACE, "import");
213
214 ArrayList<String> names = new ArrayList<String>();
215 for (int i = 0; i < metadataElems.getLength(); i++)
216 {
217 Element current = (Element) metadataElems.item(i);
218 String name = current.getAttribute(GSXML.NAME_ATT);
219 if (name != null && name.length() > 0 && !names.contains(name))
220 {
221 names.add(name);
222 }
223 }
224
225 for (int i = 0; i < foreachMetadataElems.getLength(); i++)
226 {
227 Element current = (Element) foreachMetadataElems.item(i);
228 String name = current.getAttribute(GSXML.NAME_ATT);
229 if (name != null && name.length() > 0 && !names.contains(name))
230 {
231 names.add(name);
232 }
233 }
234
235 for (int i = 0; i < imageElems.getLength(); i++)
236 {
237 Element current = (Element) imageElems.item(i);
238 String type = current.getAttribute(GSXML.TYPE_ATT);
239 if (type == null || type.length() == 0)
240 {
241 continue;
242 }
243
244 if (type.equals("source"))
245 {
246 String[] standardSourceMeta = new String[] { "SourceFile", "ImageHeight", "ImageWidth", "ImageType", "srcicon" };
247 for (String meta : standardSourceMeta)
248 {
249 if (!names.contains(meta))
250 {
251 names.add(meta);
252 }
253 }
254 }
255 else if (type.equals("screen"))
256 {
257 String[] standardScreenMeta = new String[] { "Screen", "ScreenHeight", "ScreenWidth", "ScreenType", "screenicon" };
258 for (String meta : standardScreenMeta)
259 {
260 if (!names.contains(meta))
261 {
262 names.add(meta);
263 }
264 }
265 }
266 else if (type.equals("thumb"))
267 {
268 String[] standardThumbMeta = new String[] { "Thumb", "ThumbHeight", "ThumbWidth", "ThumbType", "thumbicon" };
269 for (String meta : standardThumbMeta)
270 {
271 if (!names.contains(meta))
272 {
273 names.add(meta);
274 }
275 }
276 }
277 }
278
279 metaNames.put(currentFile.getAbsolutePath(), names);
280
281 ArrayList<String> includeAndImportList = new ArrayList<String>();
282 for (int i = 0; i < includeElems.getLength(); i++)
283 {
284 includeAndImportList.add(((Element) includeElems.item(i)).getAttribute(GSXML.HREF_ATT));
285 }
286 for (int i = 0; i < importElems.getLength(); i++)
287 {
288 includeAndImportList.add(((Element) importElems.item(i)).getAttribute(GSXML.HREF_ATT));
289 }
290 includes.put(currentFile.getAbsolutePath(), includeAndImportList);
291
292 String filename = currentFile.getName();
293 if (files.get(filename) == null)
294 {
295 ArrayList<File> fileList = new ArrayList<File>();
296 fileList.add(currentFile);
297 files.put(currentFile.getName(), fileList);
298 }
299 else
300 {
301 ArrayList<File> fileList = files.get(filename);
302 fileList.add(currentFile);
303 }
304 }
305
306 //Second pass
307 for (File currentFile : xslFiles)
308 {
309 ArrayList<File> filesToGet = new ArrayList<File>();
310 filesToGet.add(currentFile);
311
312 ArrayList<String> fullNameList = new ArrayList<String>();
313
314 while (filesToGet.size() > 0)
315 {
316 File currentFileTemp = filesToGet.remove(0);
317
318 //Add the names from this file
319 ArrayList<String> currentNames = metaNames.get(currentFileTemp.getAbsolutePath());
320 if (currentNames == null)
321 {
322 continue;
323 }
324
325 fullNameList.addAll(currentNames);
326
327 ArrayList<String> includedHrefs = includes.get(currentFileTemp.getAbsolutePath());
328
329 for (String href : includedHrefs)
330 {
331 int lastSepIndex = href.lastIndexOf("/");
332 if (lastSepIndex != -1)
333 {
334 href = href.substring(lastSepIndex + 1);
335 }
336
337 ArrayList<File> filesToAdd = files.get(href);
338 if (filesToAdd != null)
339 {
340 filesToGet.addAll(filesToAdd);
341 }
342 }
343 }
344
345 _metadataRequiredMap.put(currentFile.getAbsolutePath(), fullNameList);
346 }
347 }
348
349 protected void preProcessRequest(Element request)
350 {
351 String action = request.getAttribute(GSXML.ACTION_ATT);
352 String subaction = request.getAttribute(GSXML.SUBACTION_ATT);
353
354 String name = null;
355 if (!subaction.equals(""))
356 {
357 String key = action + ":" + subaction;
358 name = this.xslt_map.get(key);
359 }
360 // try the action by itself
361 if (name == null)
362 {
363 name = this.xslt_map.get(action);
364 }
365
366 Element cgi_param_list = (Element) GSXML.getChildByTagName(request, GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
367 String collection = "";
368
369 if (cgi_param_list != null)
370 {
371 // Don't waste time getting all the parameters
372 HashMap<String, Serializable> params = GSXML.extractParams(cgi_param_list, false);
373 collection = (String) params.get(GSParams.COLLECTION);
374 if (collection == null)
375 {
376 collection = "";
377 }
378 }
379
380 ArrayList<File> stylesheets = GSFile.getStylesheetFiles(GlobalProperties.getGSDL3Home(), (String) this.config_params.get(GSConstants.SITE_NAME), collection, (String) this.config_params.get(GSConstants.INTERFACE_NAME), base_interfaces, name);
381
382 Element extraMetadataList = this.doc.createElement(GSXML.EXTRA_METADATA + GSXML.LIST_MODIFIER);
383 for (File stylesheet : stylesheets)
384 {
385 ArrayList<String> requiredMetadata = _metadataRequiredMap.get(stylesheet.getAbsolutePath());
386
387 if (requiredMetadata != null)
388 {
389 for (String metadataString : requiredMetadata)
390 {
391 Element metadataElem = this.doc.createElement(GSXML.EXTRA_METADATA);
392 metadataElem.setAttribute(GSXML.NAME_ATT, metadataString);
393 extraMetadataList.appendChild(metadataElem);
394 }
395 }
396 }
397 request.appendChild(request.getOwnerDocument().importNode(extraMetadataList, true));
398 }
399
400 protected Node postProcessPage(Element page)
401 {
402 // might need to add some data to the page
403 addExtraInfo(page);
404 // transform the page using xslt
405 Node transformed_page = transformPage(page);
406
407 // if the user has specified they want only a part of the full page then subdivide it
408 boolean subdivide = false;
409 String excerptID = null;
410 String excerptTag = null;
411 Element request = (Element) GSXML.getChildByTagName(page, GSXML.PAGE_REQUEST_ELEM);
412 Element cgi_param_list = (Element) GSXML.getChildByTagName(request, GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
413 if (cgi_param_list != null)
414 {
415 HashMap<String, Serializable> params = GSXML.extractParams(cgi_param_list, false);
416 if ((excerptID = (String) params.get(GSParams.EXCERPT_ID)) != null)
417 {
418 subdivide = true;
419 }
420 if ((excerptTag = (String) params.get(GSParams.EXCERPT_TAG)) != null)
421 {
422 subdivide = true;
423 }
424 }
425
426 if (subdivide)
427 {
428 Node subdivided_page = subdivide(transformed_page, excerptID, excerptTag);
429 if (subdivided_page != null)
430 {
431 return subdivided_page;
432 }
433 }
434
435 return transformed_page;
436 }
437
438 protected Node subdivide(Node transformed_page, String excerptID, String excerptTag)
439 {
440 if (excerptID != null)
441 {
442 Node selectedElement = getNodeByIdRecursive(transformed_page, excerptID);
443 modifyNodesByTagRecursive(selectedElement, "a");
444 return selectedElement;
445 }
446 else if (excerptTag != null)
447 {
448 Node selectedElement = getNodeByTagRecursive(transformed_page, excerptTag);
449 return selectedElement;
450 }
451 return transformed_page;
452 }
453
454 protected Node getNodeByIdRecursive(Node parent, String id)
455 {
456 if (parent.hasAttributes() && ((Element) parent).getAttribute("id").equals(id))
457 {
458 return parent;
459 }
460
461 NodeList children = parent.getChildNodes();
462 for (int i = 0; i < children.getLength(); i++)
463 {
464 Node result = null;
465 if ((result = getNodeByIdRecursive(children.item(i), id)) != null)
466 {
467 return result;
468 }
469 }
470 return null;
471 }
472
473 protected Node getNodeByTagRecursive(Node parent, String tag)
474 {
475 if (parent.getNodeType() == Node.ELEMENT_NODE && ((Element) parent).getTagName().equals(tag))
476 {
477 return parent;
478 }
479
480 NodeList children = parent.getChildNodes();
481 for (int i = 0; i < children.getLength(); i++)
482 {
483 Node result = null;
484 if ((result = getNodeByTagRecursive(children.item(i), tag)) != null)
485 {
486 return result;
487 }
488 }
489 return null;
490 }
491
492 protected Node modifyNodesByTagRecursive(Node parent, String tag)
493 {
494 if (parent == null || (parent.getNodeType() == Node.ELEMENT_NODE && ((Element) parent).getTagName().equals(tag)))
495 {
496 return parent;
497 }
498
499 NodeList children = parent.getChildNodes();
500 for (int i = 0; i < children.getLength(); i++)
501 {
502 Node result = null;
503 if ((result = modifyNodesByTagRecursive(children.item(i), tag)) != null)
504 {
505 //TODO: DO SOMETHING HERE?
506 }
507 }
508 return null;
509 }
510
511 /**
512 * overwrite this to add any extra info that might be needed in the page
513 * before transformation
514 */
515 protected void addExtraInfo(Element page)
516 {
517 }
518
519 /**
520 * transform the page using xslt we need to get any format element out of
521 * the page and add it to the xslt before transforming
522 */
523 protected Node transformPage(Element page)
524 {
525 _debug = false;
526
527 boolean allowsClientXSLT = (Boolean) config_params.get(GSConstants.ALLOW_CLIENT_SIDE_XSLT);
528 //System.out.println("Client side transforms allowed? " + allowsClientXSLT);
529
530 String currentInterface = (String) config_params.get(GSConstants.INTERFACE_NAME);
531
532 Element request = (Element) GSXML.getChildByTagName(page, GSXML.PAGE_REQUEST_ELEM);
533 String output = request.getAttribute(GSXML.OUTPUT_ATT);
534
535 //System.out.println("Current output mode is: " + output + ", current interface name is: " + currentInterface);
536
537 if (allowsClientXSLT)
538 {
539 if (!currentInterface.endsWith(GSConstants.CLIENT_SIDE_XSLT_INTERFACE_SUFFIX) && output.equals("html"))
540 {
541 System.out.println("output is html and we are not currently using a client side version, switching");
542 // Switch the interface
543 config_params.put(GSConstants.INTERFACE_NAME, currentInterface.concat(GSConstants.CLIENT_SIDE_XSLT_INTERFACE_SUFFIX));
544 }
545 else if ((currentInterface.endsWith(GSConstants.CLIENT_SIDE_XSLT_INTERFACE_SUFFIX) && !output.equals("html")) || output.equals("server"))
546 {
547 // The reverse needs to happen too
548 config_params.put(GSConstants.INTERFACE_NAME, currentInterface.substring(0, currentInterface.length() - GSConstants.CLIENT_SIDE_XSLT_INTERFACE_SUFFIX.length()));
549 }
550 }
551 else if (currentInterface.endsWith(GSConstants.CLIENT_SIDE_XSLT_INTERFACE_SUFFIX))
552 {
553 config_params.put(GSConstants.INTERFACE_NAME, currentInterface.substring(0, currentInterface.length() - GSConstants.CLIENT_SIDE_XSLT_INTERFACE_SUFFIX.length()));
554 }
555
556 // DocType defaults in case the skin doesn't have an "xsl:output" element
557 String qualifiedName = "html";
558 String publicID = "-//W3C//DTD HTML 4.01 Transitional//EN";
559 String systemID = "http://www.w3.org/TR/html4/loose.dtd";
560
561 // We need to create an empty document with a predefined DocType,
562 // that will then be used for the transformation by the DOMResult
563 Document docWithDoctype = converter.newDOM(qualifiedName, publicID, systemID);
564
565 if (output.equals("xsltclient"))
566 {
567 // If you're just getting the client-side transform page, why bother with the rest of this?
568 Element html = docWithDoctype.createElement("html");
569 Element img = docWithDoctype.createElement("img");
570 img.setAttribute("src", "interfaces/default/images/loading.gif"); // Make it dynamic
571 img.setAttribute("alt", "Please wait...");
572 Text title_text = docWithDoctype.createTextNode("Please wait..."); // Make this language dependent
573 Element head = docWithDoctype.createElement("head");
574 Element title = docWithDoctype.createElement("title");
575 title.appendChild(title_text);
576 Element body = docWithDoctype.createElement("body");
577 Element script = docWithDoctype.createElement("script");
578 Element jquery = docWithDoctype.createElement("script");
579 jquery.setAttribute("src", "jquery.js");
580 jquery.setAttribute("type", "text/javascript");
581 Comment jquery_comment = docWithDoctype.createComment("jQuery");
582 Comment script_comment = docWithDoctype.createComment("Filler for browser");
583 script.setAttribute("src", "test.js");
584 script.setAttribute("type", "text/javascript");
585 Element pagevar = docWithDoctype.createElement("script");
586 Element style = docWithDoctype.createElement("style");
587 style.setAttribute("type", "text/css");
588 Text style_text = docWithDoctype.createTextNode("body { text-align: center; padding: 50px; font: 14pt Arial, sans-serif; font-weight: bold; }");
589 pagevar.setAttribute("type", "text/javascript");
590 Text page_var_text = docWithDoctype.createTextNode("var placeholder = true;");
591
592 html.appendChild(head);
593 head.appendChild(title);
594 head.appendChild(style);
595 style.appendChild(style_text);
596 html.appendChild(body);
597 head.appendChild(pagevar);
598 head.appendChild(jquery);
599 head.appendChild(script);
600 pagevar.appendChild(page_var_text);
601 jquery.appendChild(jquery_comment);
602 script.appendChild(script_comment);
603 body.appendChild(img);
604 docWithDoctype.appendChild(html);
605
606 return (Node) docWithDoctype;
607 }
608
609 // 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
610 logger.debug("page before transforming:");
611 logger.debug(this.converter.getPrettyStringLogger(page, logger));
612
613 String action = request.getAttribute(GSXML.ACTION_ATT);
614 String subaction = request.getAttribute(GSXML.SUBACTION_ATT);
615
616 // we should choose how to transform the data based on output, eg diff
617 // choice for html, and wml??
618 // for now, if output=xml, we don't transform the page, we just return
619 // the page xml
620 Document theXML = null;
621
622 if (output.equals("xml") || (output.equals("json")) || output.equals("clientside"))
623 {
624 // Append some bits and pieces first...
625 theXML = converter.newDOM();
626 // Import into new document first!
627 Node newPage = theXML.importNode(page, true);
628 theXML.appendChild(newPage);
629 Element root = theXML.createElement("xsltparams");
630 newPage.appendChild(root);
631
632 Element libname = theXML.createElement("param");
633 libname.setAttribute("name", "library_name");
634 Text libnametext = theXML.createTextNode((String) config_params.get(GSConstants.LIBRARY_NAME));
635 libname.appendChild(libnametext);
636
637 Element intname = theXML.createElement("param");
638 intname.setAttribute("name", "interface_name");
639 Text intnametext = theXML.createTextNode((String) config_params.get(GSConstants.INTERFACE_NAME));
640 intname.appendChild(intnametext);
641
642 Element siteName = theXML.createElement("param");
643 siteName.setAttribute("name", "site_name");
644 Text siteNameText = theXML.createTextNode((String) config_params.get(GSConstants.SITE_NAME));
645 siteName.appendChild(siteNameText);
646
647 Element filepath = theXML.createElement("param");
648 filepath.setAttribute("name", "filepath");
649 Text filepathtext = theXML.createTextNode(GlobalProperties.getGSDL3Home());
650 filepath.appendChild(filepathtext);
651
652 root.appendChild(libname);
653 root.appendChild(intname);
654 root.appendChild(siteName);
655 root.appendChild(filepath);
656
657 if ((output.equals("xml")) || output.equals("json"))
658 {
659 // in the case of "json", calling method responsible for converting to JSON-string
660 return theXML.getDocumentElement();
661 }
662 }
663
664 Element cgi_param_list = (Element) GSXML.getChildByTagName(request, GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
665 String collection = "";
666 String inlineTemplate = "";
667 if (cgi_param_list != null)
668 {
669 // Don't waste time getting all the parameters
670 HashMap<String, Serializable> params = GSXML.extractParams(cgi_param_list, false);
671 collection = (String) params.get(GSParams.COLLECTION);
672 if (collection == null)
673 {
674 collection = "";
675 }
676
677 inlineTemplate = (String) params.get(GSParams.INLINE_TEMPLATE);
678
679 if (params.get(GSParams.DEBUG) != null && (((String) params.get(GSParams.DEBUG)).equals("on") || ((String) params.get(GSParams.DEBUG)).equals("1") || ((String) params.get(GSParams.DEBUG)).equals("true")))
680 {
681 String[] groups = new UserContext(request).getGroups();
682
683 boolean found = false;
684 for (String g : groups)
685 {
686 if (g.equals("administrator"))
687 {
688 found = true;
689 }
690 }
691 if (found)
692 {
693 _debug = true;
694 }
695 }
696 }
697
698 config_params.put("collName", collection);
699
700 Document style_doc = getXSLTDocument(action, subaction, collection);
701 if (style_doc == null)
702 {
703 String errorPage = this.converter.getParseErrorMessage();
704 if (errorPage != null)
705 {
706 return XMLTransformer.constructErrorXHTMLPage("Cannot parse the xslt file\n" + errorPage);
707 }
708 return page;
709 }
710
711 // put the page into a document - this is necessary for xslt to get
712 // the paths right if you have paths relative to the document root
713 // eg /page.
714 Document doc = this.converter.newDOM();
715 doc.appendChild(doc.importNode(page, true));
716 Element page_response = (Element) GSXML.getChildByTagName(page, GSXML.PAGE_RESPONSE_ELEM);
717 Element format_elem = (Element) GSXML.getChildByTagName(page_response, GSXML.FORMAT_ELEM);
718
719 NodeList pageElems = doc.getElementsByTagName("page");
720 if (pageElems.getLength() > 0)
721 {
722 Element pageElem = (Element) pageElems.item(0);
723 String langAtt = pageElem.getAttribute(GSXML.LANG_ATT);
724
725 if (langAtt != null && langAtt.length() > 0)
726 {
727 config_params.put("lang", langAtt);
728 }
729 }
730
731 if (output.equals("formatelem"))
732 {
733 return format_elem;
734 }
735 if (format_elem != null)
736 {
737 //page_response.removeChild(format_elem);
738 logger.debug("format elem=" + this.converter.getPrettyStringLogger(format_elem, logger));
739 // need to transform the format info
740 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");
741 Document configStylesheet_doc = this.converter.getDOM(new File(configStylesheet_file));
742
743 if (configStylesheet_doc != null)
744 {
745 Document format_doc = this.converter.newDOM();
746 format_doc.appendChild(format_doc.importNode(format_elem, true));
747
748 if (_debug)
749 {
750 String siteHome = GSFile.siteHome(GlobalProperties.getGSDL3Home(), (String) this.config_params.get(GSConstants.SITE_NAME));
751 GSXSLT.insertDebugElements(format_doc, GSFile.collectionConfigFile(siteHome, collection));
752 }
753
754 Node result = this.transformer.transform(configStylesheet_doc, format_doc, config_params); // Needs addressing <-
755
756 // Since we started creating documents with DocTypes, we can end up with
757 // Document objects here. But we will be working with an Element instead,
758 // so we grab the DocumentElement() of the Document object in such a case.
759 Element new_format;
760 if (result.getNodeType() == Node.DOCUMENT_NODE)
761 {
762 new_format = ((Document) result).getDocumentElement();
763 }
764 else
765 {
766 new_format = (Element) result;
767 }
768 logger.debug("new format elem=" + this.converter.getPrettyStringLogger(new_format, logger));
769 if (output.equals("newformat"))
770 {
771 return new_format;
772 }
773
774 // add extracted GSF statements in to the main stylesheet
775 if (_debug)
776 {
777 String siteHome = GSFile.siteHome(GlobalProperties.getGSDL3Home(), (String) this.config_params.get(GSConstants.SITE_NAME));
778 GSXSLT.mergeStylesheetsDebug(style_doc, new_format, true, true, "OTHER1", GSFile.collectionConfigFile(siteHome, collection));
779 }
780 else
781 {
782 GSXSLT.mergeStylesheets(style_doc, new_format, true);
783 }
784 //System.out.println("added extracted GSF statements into the main stylesheet") ;
785
786 // add extracted GSF statements in to the debug test stylesheet
787 //GSXSLT.mergeStylesheets(oldStyle_doc, new_format);
788 }
789 else
790 {
791 logger.error(" couldn't parse the config_format stylesheet, adding the format info as is");
792 GSXSLT.mergeStylesheets(style_doc, format_elem, true);
793 //GSXSLT.mergeStylesheets(oldStyle_doc, format_elem);
794 }
795 logger.debug("the converted stylesheet is:");
796 logger.debug(this.converter.getPrettyStringLogger(style_doc.getDocumentElement(), logger));
797 }
798
799 //for debug purposes only
800 Document oldStyle_doc = style_doc;
801 Document preprocessingXsl;
802 try
803 {
804 preprocessingXsl = getDoc(preprocess_xsl_filename);
805 String errMsg = ((XMLConverter.ParseErrorHandler) parser.getErrorHandler()).getErrorMessage();
806 if (errMsg != null)
807 {
808 return XMLTransformer.constructErrorXHTMLPage("error loading preprocess xslt file: " + preprocess_xsl_filename + "\n" + errMsg);
809 }
810 }
811 catch (java.io.FileNotFoundException e)
812 {
813 return fileNotFoundErrorPage(e.getMessage());
814 }
815 catch (Exception e)
816 {
817 e.printStackTrace();
818 System.out.println("error loading preprocess xslt");
819 return XMLTransformer.constructErrorXHTMLPage("error loading preprocess xslt\n" + e.getMessage());
820 }
821
822 Document libraryXsl = null;
823 try
824 {
825 libraryXsl = GSXSLT.mergedXSLTDocumentCascade("gslib.xsl", (String) this.config_params.get(GSConstants.SITE_NAME), collection, (String) this.config_params.get(GSConstants.INTERFACE_NAME), base_interfaces, _debug);
826 }
827 catch (Exception e)
828 {
829 e.printStackTrace();
830 System.out.println("error loading gslib xslt");
831 return XMLTransformer.constructErrorXHTMLPage("error loading gslib xslt\n" + e.getMessage());
832 }
833
834 // Combine the skin file and library variables/templates into one document.
835 // Please note: We dont just use xsl:import because the preprocessing stage
836 // needs to know what's available in the library.
837
838 Document skinAndLibraryXsl = null;
839 Document skinAndLibraryDoc = converter.newDOM();
840
841 // Applying the preprocessing XSLT - in its own block {} to allow use of non-unique variable names
842 {
843
844 skinAndLibraryXsl = converter.newDOM();
845 Element root = skinAndLibraryXsl.createElement("skinAndLibraryXsl");
846 skinAndLibraryXsl.appendChild(root);
847
848 Element s = skinAndLibraryXsl.createElement("skinXsl");
849 s.appendChild(skinAndLibraryXsl.importNode(style_doc.getDocumentElement(), true));
850 root.appendChild(s);
851
852 Element l = skinAndLibraryXsl.createElement("libraryXsl");
853 if (libraryXsl != null)
854 {
855 Element libraryXsl_el = libraryXsl.getDocumentElement();
856 l.appendChild(skinAndLibraryXsl.importNode(libraryXsl_el, true));
857 }
858 root.appendChild(l);
859
860 //System.out.println("Skin and Library XSL are now together") ;
861
862 //System.out.println("Pre-processing the skin file...") ;
863
864 //pre-process the skin style sheet
865 //In other words, apply the preProcess.xsl to 'skinAndLibraryXsl' in order to
866 //expand all GS-Lib statements into complete XSL statements and also to create
867 //a valid xsl style sheet document.
868
869 XMLTransformer preProcessor = new XMLTransformer();
870 // Perform the transformation, by passing in:
871 // preprocess-stylesheet, source-xsl (skinAndLibraryXsl), and the node that should
872 // be in the result (skinAndLibraryDoc)
873 preProcessor.transform_withResultNode(preprocessingXsl, skinAndLibraryXsl, skinAndLibraryDoc);
874 //System.out.println("GS-Lib statements are now expanded") ;
875 }
876
877 // there is a thing called a URIResolver which you can set for a
878 // transformer or transformer factory. may be able to use this
879 // instead of this absoluteIncludepaths hack
880
881 //GSXSLT.absoluteIncludePaths(skinAndLibraryDoc, GlobalProperties.getGSDL3Home(), (String) this.config_params.get(GSConstants.SITE_NAME), collection, (String) this.config_params.get(GSConstants.INTERFACE_NAME), base_interfaces);
882
883 //Same but for the debug version when we want the do the transformation like we use to do
884 //without any gslib elements.
885 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);
886
887 //Send different stages of the skin xslt to the browser for debug purposes only
888 //using &o=skindoc or &o=skinandlib etc...
889 if (output.equals("skindoc"))
890 {
891 return converter.getDOM(getStringFromDocument(style_doc));
892 }
893 if (output.equals("skinandlib"))
894 {
895 return converter.getDOM(getStringFromDocument(skinAndLibraryXsl));
896 }
897 if (output.equals("skinandlibdoc") || output.equals("clientside"))
898 {
899
900 Node skinAndLib = converter.getDOM(getStringFromDocument(skinAndLibraryDoc));
901
902 if (output.equals("skinandlibdoc"))
903 {
904 return skinAndLib;
905 }
906 else
907 {
908 // Send XML and skinandlibdoc down the line together
909 Document finalDoc = converter.newDOM();
910 Node finalDocSkin = finalDoc.importNode(skinAndLibraryDoc.getDocumentElement(), true);
911 Node finalDocXML = finalDoc.importNode(theXML.getDocumentElement(), true);
912 Element root = finalDoc.createElement("skinlibPlusXML");
913 root.appendChild(finalDocSkin);
914 root.appendChild(finalDocXML);
915 finalDoc.appendChild(root);
916 return (Node) finalDoc.getDocumentElement();
917 }
918 }
919 if (output.equals("oldskindoc"))
920 {
921 return converter.getDOM(getStringFromDocument(oldStyle_doc));
922 }
923
924 // We now no longer create a document with doctype before the transformation
925 // We let the XMLTransformer do the work of first working out the doctype from any
926 // that may be set in the (merged) stylesheets and then setting the doctype when transforming
927
928 /*
929 // Try to get the system and public ID from the current skin xsl document
930 // otherwise keep the default values.
931 Element root = skinAndLibraryDoc.getDocumentElement();
932 NodeList nodes = root.getElementsByTagName("xsl:output");
933 // If there is at least one "xsl:output" command in the final xsl then...
934 if (nodes.getLength() != 0)
935 {
936 // There should be only one element called xsl:output,
937 // but if this is not the case get the last one
938 Element xsl_output = (Element) nodes.item(nodes.getLength() - 1);
939 if (xsl_output != null)
940 {
941 // Qualified name will always be html even for xhtml pages
942 //String attrValue = xsl_output.getAttribute("method");
943 //qualifiedName = attrValue.equals("") ? qualifiedName : attrValue;
944
945 String attrValue = xsl_output.getAttribute("doctype-system");
946 systemID = attrValue.equals("") ? systemID : attrValue;
947
948 attrValue = xsl_output.getAttribute("doctype-public");
949 publicID = attrValue.equals("") ? publicID : attrValue;
950 }
951 }
952
953 //System.out.println(converter.getPrettyString(docWithDoctype));
954 //System.out.println("Doctype vals: " + qualifiedName + " " + publicID + " " + systemID) ;
955
956 docWithDoctype = converter.newDOM(qualifiedName, publicID, systemID);
957 */
958
959 //System.out.println("Generate final HTML from current skin") ;
960 //Transformation of the XML message from the receptionist to HTML with doctype
961
962 if (inlineTemplate != null)
963 {
964 try
965 {
966 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");
967
968 if (_debug)
969 {
970 GSXSLT.mergeStylesheetsDebug(skinAndLibraryDoc, inlineTemplateDoc.getDocumentElement(), true, true, "OTHER2", "INLINE");
971 }
972 else
973 {
974 GSXSLT.mergeStylesheets(skinAndLibraryDoc, inlineTemplateDoc.getDocumentElement(), true);
975 }
976 }
977 catch (Exception ex)
978 {
979 ex.printStackTrace();
980 }
981 }
982
983 if (_debug)
984 {
985 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);
986 }
987 else
988 {
989 GSXSLT.inlineImportAndIncludeFiles(skinAndLibraryDoc, null, (String) this.config_params.get(GSConstants.SITE_NAME), collection, (String) this.config_params.get(GSConstants.INTERFACE_NAME), base_interfaces);
990 }
991 skinAndLibraryDoc = (Document) performFormatPass(collection, skinAndLibraryDoc, doc, new UserContext(request), TEXT_PASS);
992 skinAndLibraryDoc = (Document) performFormatPass(collection, skinAndLibraryDoc, doc, new UserContext(request), CONFIG_PASS);
993
994 if (output.equals("xmlfinal"))
995 {
996 return doc;
997 }
998
999 if (output.equals("skinandlibdocfinal"))
1000 {
1001 return converter.getDOM(getStringFromDocument(skinAndLibraryDoc));
1002 }
1003
1004 // The transformer will now work out the resulting doctype from any set in the (merged) stylesheets and
1005 // will set this in the output document it creates. So don't pass in any docWithDocType to the transformer
1006 //Node finalResult = this.transformer.transform(skinAndLibraryDoc, doc, config_params, docWithDoctype);
1007 Node finalResult = this.transformer.transform(skinAndLibraryDoc, doc, config_params);
1008
1009 if (_debug)
1010 {
1011 GSXSLT.fixTables((Document) finalResult);
1012 }
1013
1014 return finalResult;
1015
1016 // The line below will do the transformation like we use to do before having Skin++ implemented,
1017 // it will not contain any GS-Lib statements expanded, and the result will not contain any doctype.
1018
1019 //return (Element)this.transformer.transform(style_doc, doc, config_params);
1020 //return null; // For now - change later
1021 }
1022
1023 protected Node performFormatPass(String collection, Document skinAndLibraryDoc, Document doc, UserContext userContext, int pass)
1024 {
1025 String formatFile;
1026 if (pass == CONFIG_PASS)
1027 {
1028 formatFile = "config_format.xsl";
1029 }
1030 else
1031 {
1032 formatFile = "text_fragment_format.xsl";
1033 }
1034 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);
1035 Document configStylesheet_doc = this.converter.getDOM(new File(configStylesheet_file));
1036
1037 if (configStylesheet_doc != null)
1038 {
1039 return this.transformer.transform(configStylesheet_doc, skinAndLibraryDoc, config_params);
1040 }
1041 return skinAndLibraryDoc;
1042 }
1043
1044 // method to convert Document to a proper XML string for debug purposes only
1045 protected String getStringFromDocument(Document doc)
1046 {
1047 String content = "";
1048 try
1049 {
1050 DOMSource domSource = new DOMSource(doc);
1051 StringWriter writer = new StringWriter();
1052 StreamResult result = new StreamResult(writer);
1053 TransformerFactory tf = TransformerFactory.newInstance();
1054 Transformer transformer = tf.newTransformer();
1055 transformer.transform(domSource, result);
1056 content = writer.toString();
1057 System.out.println("Change the & to &Amp; for proper debug display");
1058 content = StringUtils.replace(content, "&", "&amp;");
1059 writer.flush();
1060 }
1061 catch (TransformerException ex)
1062 {
1063 ex.printStackTrace();
1064 return null;
1065 }
1066 return content;
1067 }
1068
1069 protected synchronized Document getDoc(String docName) throws Exception
1070 {
1071 File xslt_file = new File(docName);
1072
1073 FileReader reader = new FileReader(xslt_file);
1074 InputSource xml_source = new InputSource(reader);
1075 this.parser.parse(xml_source);
1076 Document doc = this.parser.getDocument();
1077
1078 return doc;
1079 }
1080
1081 protected Document getXSLTDocument(String action, String subaction, String collection)
1082 {
1083 String name = null;
1084 if (!subaction.equals(""))
1085 {
1086 String key = action + ":" + subaction;
1087 name = this.xslt_map.get(key);
1088 }
1089 // try the action by itself
1090 if (name == null)
1091 {
1092 name = this.xslt_map.get(action);
1093 }
1094 if (name == null)
1095 {
1096 // so we can reandomly create any named page
1097 if (action.equals("p") && !subaction.equals(""))
1098 {
1099 // TODO: pages/ won't work for interface other than default!!
1100 name = "pages/" + subaction + ".xsl";
1101 }
1102
1103 }
1104
1105 if(name != null)
1106 {
1107 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);
1108 }
1109 return finalDoc;
1110 }
1111
1112 // returns the path to the gslib.xsl file that is applicable for the current interface
1113 protected String getGSLibXSLFilename()
1114 {
1115 return GSFile.xmlTransformDir(GSFile.interfaceHome(GlobalProperties.getGSDL3Home(), (String) this.config_params.get(GSConstants.INTERFACE_NAME))) + File.separatorChar + "gslib.xsl";
1116 }
1117
1118 // Call this when a FileNotFoundException could be thrown when loading an xsl (xml) file.
1119 // Returns an error xhtml page indicating which xsl (or other xml) file is missing.
1120 protected Document fileNotFoundErrorPage(String filenameMessage)
1121 {
1122 String errorMessage = "ERROR missing file: " + filenameMessage;
1123 Element errPage = XMLTransformer.constructErrorXHTMLPage(errorMessage);
1124 logger.error(errorMessage);
1125 return errPage.getOwnerDocument();
1126 }
1127}
Note: See TracBrowser for help on using the repository browser.