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

Last change on this file since 29921 was 29921, checked in by Georgiy Litvinov, 9 years ago

Hierarchy classifier bugfix

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