source: main/trunk/greenstone3/src/java/org/greenstone/gsdl3/util/XSLTUtil.java@ 30477

Last change on this file since 30477 was 30477, checked in by davidb, 8 years ago

Changes in the Java code to support the new approach taken to client-side XSLT (using Saxon-CE JS library in the browser -- see next commit). Also some better error reporting when processing XSLT files

  • Property svn:keywords set to Author Date Id Revision
File size: 21.0 KB
Line 
1/*
2 * XSLTUtil.java
3 * Copyright (C) 2008 New Zealand Digital Library, http://www.nzdl.org
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19package org.greenstone.gsdl3.util;
20
21import java.io.ByteArrayInputStream;
22import java.io.File;
23import java.io.UnsupportedEncodingException;
24import java.net.URLEncoder;
25import java.text.SimpleDateFormat;
26import java.util.ArrayList;
27import java.util.Date;
28import java.util.Enumeration;
29import java.util.HashMap;
30import java.util.Locale;
31
32import javax.xml.parsers.DocumentBuilder;
33import javax.xml.parsers.DocumentBuilderFactory;
34
35import net.tanesha.recaptcha.ReCaptcha;
36import net.tanesha.recaptcha.ReCaptchaFactory;
37
38import org.apache.commons.lang3.StringUtils;
39import org.apache.log4j.Logger;
40import org.greenstone.util.GlobalProperties;
41import org.w3c.dom.Node;
42
43/**
44 * a class to contain various static methods that are used by the xslt
45 * stylesheets
46 */
47public class XSLTUtil
48{
49 protected static HashMap<String, ArrayList<String>> _foundTableValues = new HashMap<String, ArrayList<String>>();
50 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.util.XSLTUtil.class.getName());
51 protected static HashMap<String, String> _stringVariables = new HashMap<String, String>();
52
53 public static void storeString(String name, String value)
54 {
55 _stringVariables.put(name, value);
56 }
57
58 public static String getString(String name)
59 {
60 return _stringVariables.get(name);
61 }
62
63 /* some tests */
64 public static boolean equals(String s1, String s2)
65 {
66 return s1.equals(s2);
67 }
68
69 public static boolean notEquals(String s1, String s2)
70 {
71 return !s1.equals(s2);
72 }
73
74 public static boolean exists(String s1, String s2)
75 {
76 return !s1.equals("");
77 }
78
79 public static boolean contains(String s1, String s2)
80 {
81 return (s1.indexOf(s2) != -1);
82 }
83
84 public static boolean startsWith(String s1, String s2)
85 {
86 return s1.startsWith(s2);
87 }
88
89 public static boolean endsWith(String s1, String s2)
90 {
91 return s1.endsWith(s2);
92 }
93
94 public static boolean lessThan(String s1, String s2)
95 {
96 return (s1.compareTo(s2) < 0);
97 }
98
99 public static boolean lessThanOrEquals(String s1, String s2)
100 {
101 return (s1.compareTo(s2) <= 0);
102 }
103
104 public static boolean greaterThan(String s1, String s2)
105 {
106 return (s1.compareTo(s2) > 0);
107 }
108
109 public static boolean greaterThanOrEquals(String s1, String s2)
110 {
111 return (s1.compareTo(s2) >= 0);
112 }
113
114 public static boolean oidIsMatchOrParent(String first, String second)
115 {
116 if (first.equals(second))
117 {
118 return true;
119 }
120
121 String[] firstParts = first.split(".");
122 String[] secondParts = second.split(".");
123
124 if (firstParts.length >= secondParts.length)
125 {
126 return false;
127 }
128
129 for (int i = 0; i < firstParts.length; i++)
130 {
131 if (!firstParts[i].equals(secondParts[i]))
132 {
133 return false;
134 }
135 }
136
137 return true;
138 }
139
140 public static String oidDocumentRoot(String oid)
141 {
142 String[] oidParts = oid.split("\\.");
143
144 return oidParts[0];
145 }
146
147 public static String replace(String orig, String match, String replacement)
148 {
149 return orig.replace(match, replacement);
150 }
151
152 public static String getNumberedItem(String list, int number)
153 {
154 String[] items = list.split(",", -1); //String[] items = StringUtils.split(list, ",", -1);
155 // Using StringUtils.split() causes an off-by-one error for the boolean operators (fqk)
156 // where boolean operators combining rows in multiforms are shifted up by 1 row.
157
158 if (items.length > number)
159 {
160 return items[number];
161 }
162 return ""; // index out of bounds
163 }
164
165 /**
166 * Generates links to equivalent documents for a document with a default
167 * document icon/type. Links are generated from the parameters: a list of
168 * document icons which are each in turn embedded in the matching starting
169 * link tag in the list of docStartLinks (these starting links link to the
170 * equivalent documents in another format). Each link's start tag is closed
171 * with the corresponding closing tag in the docEndLinks list. Parameter
172 * token is the list separator. Parameter divider is the string that should
173 * separate each final link generated from the next. Returns a string that
174 * represents a sequence of links to equivalent documents, where the anchor
175 * is a document icon.
176 */
177 public static String getEquivDocLinks(String token, String docIconsString, String docStartLinksString, String docEndLinksString, String divider)
178 {
179 String[] docIcons = StringUtils.split(docIconsString, token, -1);
180 String[] startLinks = StringUtils.split(docStartLinksString, token, -1);
181 String[] endLinks = StringUtils.split(docEndLinksString, token, -1);
182
183 StringBuffer buffer = new StringBuffer();
184 for (int i = 0; i < docIcons.length; i++)
185 {
186 if (i > 0)
187 {
188 buffer.append(divider);
189 }
190 buffer.append(startLinks[i] + docIcons[i] + endLinks[i]);
191 }
192
193 return buffer.toString();
194 }
195
196 public static String getInterfaceText(String interface_name, String lang, String key)
197 {
198 return getInterfaceText(interface_name, lang, key, null);
199 }
200
201 public static String getInterfaceText(String interface_name, String lang, String key, String args_str)
202 {
203 key = key.replaceAll("__INTERFACE_NAME__", interface_name);
204
205 String[] args = null;
206 if (args_str != null && !args_str.equals(""))
207 {
208 args = StringUtils.split(args_str, ";");
209 }
210 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
211 String result = dict.get(key, args);
212 if (result == null)
213 { // not found
214 //if not found, search a separate subdirectory named by the interface name
215 String sep_interface_dir = interface_name + File.separatorChar + lang + File.separatorChar + "interface";
216 dict = new Dictionary(sep_interface_dir, lang);
217 result = dict.get(key, args);
218 if (result != null)
219 {
220 result = result.replaceAll("__INTERFACE_NAME__", interface_name);
221 return result;
222 }
223 }
224
225 if (result == null && !interface_name.equals("default"))
226 { // not found, try the default interface
227 dict = new Dictionary("interface_default", lang);
228 result = dict.get(key, args);
229 }
230
231 if (result == null)
232 { // not found
233 return "_" + key + "_";
234 }
235 result = result.replaceAll("__INTERFACE_NAME__", interface_name);
236 return result;
237 }
238
239 public static String getInterfaceText(String interfaceName, String dictionaryName, String lang, String key, String args_str)
240 {
241 key = key.replaceAll("__INTERFACE_NAME__", interfaceName);
242
243 String[] args = null;
244 if (args_str != null && !args_str.equals(""))
245 {
246 args = StringUtils.split(args_str, ";");
247 }
248 Dictionary dict = new Dictionary(dictionaryName, lang);
249 String result = dict.get(key, args);
250 if (result == null)
251 { // not found
252 //if not found, search a separate subdirectory named by the interface name
253 String sep_interface_dir = interfaceName + File.separatorChar + lang + File.separatorChar + "interface";
254 dict = new Dictionary(sep_interface_dir, lang);
255 result = dict.get(key, args);
256 if (result != null)
257 {
258 result = result.replaceAll("__INTERFACE_NAME__", interfaceName);
259 return result;
260 }
261 }
262
263 if (result == null && !interfaceName.equals("default"))
264 { // not found, try the default interface
265 dict = new Dictionary("interface_default", lang);
266 result = dict.get(key, args);
267 }
268
269 if (result == null)
270 { // not found
271 return "_" + key + "_";
272 }
273 result = result.replaceAll("__INTERFACE_NAME__", interfaceName);
274 return result;
275 }
276
277 public static String getInterfaceTextWithDOM(String interface_name, String lang, String key, Node arg_node)
278 {
279 String[] args = new String[1];
280
281 String node_str = XMLConverter.getString(arg_node);
282 args[0] = node_str;
283 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
284 String result = dict.get(key, args);
285 if (result == null)
286 { // not found
287 //if not found, search a separate subdirectory named by the interface name
288 String sep_interface_dir = interface_name + File.separatorChar + lang + File.separatorChar + "interface";
289 dict = new Dictionary(sep_interface_dir, lang);
290 result = dict.get(key, args);
291 if (result != null)
292 {
293 return result;
294 }
295 }
296
297 if (result == null && !interface_name.equals("default"))
298 { // not found, try the default interface
299 dict = new Dictionary("interface_default", lang);
300 result = dict.get(key, args);
301 }
302
303 if (result == null)
304 { // not found
305 return "_" + key + "_";
306 }
307
308 return result;
309 }
310
311 public static String getInterfaceTextWithDOM(String interface_name, String lang, String key, Node arg1_node, Node arg2_node)
312 {
313 String[] args = new String[2];
314
315 String node_str = XMLConverter.getString(arg1_node);
316 args[0] = node_str;
317 node_str = XMLConverter.getString(arg2_node);
318 args[1] = node_str;
319 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
320 String result = dict.get(key, args);
321 if (result == null)
322 { // not found
323 //if not found, search a separate subdirectory named by the interface name
324 String sep_interface_dir = interface_name + File.separatorChar + lang + File.separatorChar + "interface";
325 dict = new Dictionary(sep_interface_dir, lang);
326 result = dict.get(key, args);
327 if (result != null)
328 {
329 return result;
330 }
331 }
332
333 if (result == null && !interface_name.equals("default"))
334 { // not found, try the default interface
335 dict = new Dictionary("interface_default", lang);
336 result = dict.get(key, args);
337 }
338
339 if (result == null)
340 { // not found
341 return "_" + key + "_";
342 }
343
344 return result;
345 }
346
347
348 public static String getInterfaceTextSubstituteArgs(String value, String args_str)
349 {
350 String[] args = null;
351 if (args_str != null && !args_str.equals("")) {
352 args = StringUtils.split(args_str, ";");
353 }
354
355 return Dictionary.processArgs(value,args);
356 }
357
358 public static Node getCollectionText(String collection, String site_name, String lang, String key)
359 {
360 return getCollectionTextWithArgs(collection, site_name, lang, key, null);
361 }
362
363 public static Node getCollectionText(String collection, String site_name, String lang, String key, String args_str)
364 {
365
366 String[] args = null;
367 if (args_str != null && !args_str.equals(""))
368 {
369 args = StringUtils.split(args_str, ";");
370 }
371
372 return getCollectionTextWithArgs(collection, site_name, lang, key, args);
373 }
374
375 // xslt didn't like calling the function with Node varargs, so have this hack for now
376 public static Node getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1)
377 {
378 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1);
379 }
380
381 public static Node getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2)
382 {
383 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2);
384 }
385
386 public static Node getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2, Node n3)
387 {
388 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2, n3);
389 }
390
391 public static Node getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2, Node n3, Node n4)
392 {
393 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2, n3, n4);
394 }
395
396 public static Node getCollectionTextWithDOMMulti(String collection, String site_name, String lang, String key, Node... nodes)
397 {
398 int num_nodes = nodes.length;
399 String[] args = null;
400 if (num_nodes != 0)
401 {
402 args = new String[num_nodes];
403
404 for (int i = 0; i < num_nodes; i++)
405 {
406 String node_str = XMLConverter.getString(nodes[i]);
407 args[i] = node_str;
408 }
409 }
410 return getCollectionTextWithArgs(collection, site_name, lang, key, args);
411 }
412
413 public static Node getCollectionTextWithArgs(String collection, String site_name, String lang, String key, String[] args)
414 {
415 try
416 {
417 DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
418
419 CollectionClassLoader class_loader = new CollectionClassLoader(XSLTUtil.class.getClassLoader(), GSFile.siteHome(GlobalProperties.getGSDL3Home(), site_name), collection);
420 Dictionary dict = new Dictionary(collection, lang, class_loader);
421 String result = dict.get(key, args);
422 if (result != null)
423 {
424 return docBuilder.parse(new ByteArrayInputStream(("<fragment>" + result + "</fragment>").getBytes("UTF-8"))).getDocumentElement();
425 }
426 return docBuilder.parse(new ByteArrayInputStream(("<fragment>" + "text:" + collection + ":" + key + "</fragment>").getBytes())).getDocumentElement();
427 }
428 catch (Exception ex)
429 {
430 return null;
431 }
432 }
433
434 public static boolean isImage(String mimetype)
435 {
436 if (mimetype.startsWith("image/"))
437 {
438 return true;
439 }
440 return false;
441 }
442
443 // formatting /preprocessing functions
444 // some require a language, so we'll have a language param for all
445 public static String toLower(String orig, String lang)
446 {
447 return orig.toLowerCase();
448 }
449
450 public static String toUpper(String orig, String lang)
451 {
452 return orig.toUpperCase();
453 }
454
455 public static String tidyWhitespace(String original, String lang)
456 {
457
458 if (original == null || original.equals(""))
459 {
460 return original;
461 }
462 String new_s = original.replaceAll("\\s+", " ");
463 return new_s;
464 }
465
466 public static String stripWhitespace(String original, String lang)
467 {
468
469 if (original == null || original.equals(""))
470 {
471 return original;
472 }
473 String new_s = original.replaceAll("\\s+", "");
474 return new_s;
475 }
476
477 public static byte[] toUTF8(String orig, String lang)
478 {
479 try
480 {
481 byte[] utf8 = orig.getBytes("UTF-8");
482 return utf8;
483 }
484 catch (Exception e)
485 {
486 logger.error("unsupported encoding");
487 return orig.getBytes();
488 }
489 }
490
491 public static String formatDate(String date, String lang)
492 {
493 String in_pattern = "yyyyMMdd";
494 String out_pattern = "dd MMMM yyyy";
495 if (date.length() == 6)
496 {
497 in_pattern = "yyyyMM";
498 }
499
500 SimpleDateFormat formatter = new SimpleDateFormat(in_pattern, new Locale(lang));
501 try
502 {
503 Date d = formatter.parse(date);
504 formatter.applyPattern(out_pattern);
505 String new_date = formatter.format(d);
506 return new_date;
507 }
508 catch (Exception e)
509 {
510 return date;
511 }
512
513 }
514
515 public static String getDetailFromDate(String date, String detail, String lang)
516 {
517 String in_pattern = "yyyyMMdd";
518 if (date.length() == 6)
519 {
520 in_pattern = "yyyyMM";
521 }
522
523 SimpleDateFormat formatter = new SimpleDateFormat(in_pattern, new Locale(lang));
524 try
525 {
526 Date d = formatter.parse(date);
527 if (detail.toLowerCase().equals("day"))
528 {
529 formatter.applyPattern("dd");
530 }
531 else if (detail.toLowerCase().equals("month"))
532 {
533 formatter.applyPattern("MMMM");
534 }
535 else if (detail.toLowerCase().equals("year"))
536 {
537 formatter.applyPattern("yyyy");
538 }
539 else
540 {
541 return "";
542 }
543 return formatter.format(d);
544 }
545 catch (Exception ex)
546 {
547 return "";
548 }
549 }
550
551 public static String formatLanguage(String display_lang, String lang)
552 {
553
554 return new Locale(display_lang).getDisplayLanguage(new Locale(lang));
555 }
556 public static String uriEncode(String input)
557 {
558 String result = "";
559 try {
560 result = URLEncoder.encode(input, "UTF-8");
561 } catch (UnsupportedEncodingException e) {
562 e.printStackTrace();
563 }
564
565 return result;
566
567 }
568
569 public static String cgiSafe(String original, String lang)
570 {
571
572 original = original.replace('&', ' ');
573 original = original.replaceAll(" ", "%20");
574 return original;
575 }
576
577 public static String formatBigNumber(String num, String lang)
578 {
579
580 String num_str = num;
581 char[] num_chars = num_str.toCharArray();
582 String zero_str = "";
583 String formatted_str = "";
584
585 for (int i = num_chars.length - 4; i >= 0; i--)
586 {
587 zero_str += '0';
588 }
589
590 String sig_str = "";
591 for (int i = 0; i < 3 && i < num_chars.length; i++)
592 {
593 sig_str = sig_str + num_chars[i];
594 if (i == 1 && i + 1 < num_chars.length)
595 {
596 sig_str = sig_str + ".";
597 }
598 }
599
600 int sig_int = Math.round(Float.parseFloat(sig_str));
601 String new_sig_str = sig_int + "";
602 if (sig_str.length() > 2)
603 {
604 new_sig_str = sig_int + "0";
605 }
606
607 char[] final_chars = (new_sig_str + zero_str).toCharArray();
608 int count = 1;
609 for (int i = final_chars.length - 1; i >= 0; i--)
610 {
611 formatted_str = final_chars[i] + formatted_str;
612 if (count == 3 && i != 0)
613 {
614 formatted_str = "," + formatted_str;
615 count = 1;
616 }
617 else
618 {
619 count++;
620 }
621 }
622 return formatted_str;
623 }
624
625 public static String hashToSectionId(String hashString)
626 {
627 if (hashString == null || hashString.length() == 0)
628 {
629 return "";
630 }
631
632 int firstDotIndex = hashString.indexOf(".");
633 if (firstDotIndex == -1)
634 {
635 return "";
636 }
637
638 String sectionString = hashString.substring(firstDotIndex + 1);
639
640 return sectionString;
641 }
642
643 public static String hashToDepthClass(String hashString)
644 {
645 if (hashString == null || hashString.length() == 0)
646 {
647 return "";
648 }
649
650 String sectionString = hashToSectionId(hashString);
651
652 int count = sectionString.split("\\.").length;
653
654 if (sectionString.equals(""))
655 {
656 return "sectionHeaderDepthTitle";
657 }
658 else
659 {
660 return "sectionHeaderDepth" + count;
661 }
662 }
663
664 public static String escapeNewLines(String str)
665 {
666 if (str == null || str.length() < 1)
667 {
668 return null;
669 }
670 return str.replace("\n", "\\\n");
671 }
672
673 public static String escapeQuotes(String str)
674 {
675 if (str == null || str.length() < 1)
676 {
677 return null;
678 }
679 return str.replace("\"", "\\\"");
680 }
681
682 public static String escapeNewLinesAndQuotes(String str)
683 {
684 if (str == null || str.length() < 1)
685 {
686 return null;
687 }
688 return escapeNewLines(escapeQuotes(str));
689 }
690
691 public static String getGlobalProperty(String name)
692 {
693 return GlobalProperties.getProperty(name);
694 }
695
696 public static void clearMetadataStorage()
697 {
698 _foundTableValues.clear();
699 }
700
701 public static boolean checkMetadataNotDuplicate(String name, String value)
702 {
703 if (_foundTableValues.containsKey(name))
704 {
705 for (String mapValue : _foundTableValues.get(name))
706 {
707 if (mapValue.equals(value))
708 {
709 return false;
710 }
711 }
712 _foundTableValues.get(name).add(value);
713 return true;
714 }
715
716 ArrayList<String> newList = new ArrayList<String>();
717 newList.add(value);
718
719 _foundTableValues.put(name, newList);
720
721 return true;
722 }
723
724 public static String reCAPTCHAimage(String publicKey, String privateKey)
725 {
726 ReCaptcha c = ReCaptchaFactory.newReCaptcha(publicKey, privateKey, false);
727 return c.createRecaptchaHtml(null, null);
728 }
729
730 public static String getInterfaceStringsAsJavascript(String interface_name, String lang, String prefix)
731 {
732 String prependToPrefix = "gs.text";
733 return XSLTUtil.getInterfaceStringsAsJavascript(interface_name, lang, prefix, prependToPrefix);
734 }
735
736 // generates javascript: 2 arrays are declared and populated with strings that declare variables and assign their values
737 // to be strings loaded from the interface_name.properties file for the language.
738 public static String getInterfaceStringsAsJavascript(String interface_name, String lang, String prefix, String prependToPrefix)
739 {
740 // 1. Generating Javascript of the form:
741 // if(!gs.text) { gs.text = new Array(); }
742 // if(!gs.text.dse) { gs.text.dse = new Array(); }
743 StringBuffer outputStr = new StringBuffer();
744 outputStr.append("if(!gs.text) { ");
745 outputStr.append(prependToPrefix + " = new Array(); ");
746 outputStr.append("}\n");
747 outputStr.append("if(!gs.text." + prefix + ") { ");
748 outputStr.append(prependToPrefix + "." + prefix + " = new Array(); ");
749 outputStr.append("}\n");
750
751 int foundCount = 0;
752
753 for (String dictName : new String[] { "interface_" + interface_name, "interface_default", "interface_default2" })
754 {
755 Dictionary dict = new Dictionary(dictName, lang);
756 Enumeration keys = dict.getKeys();
757 if (keys == null)
758 {
759 continue;
760 }
761
762 // Get all properties in the language-specific dictionary with the given key prefix
763 // Create Javascript strings of the form:
764 // prependToPrefix.key= "value";\n
765 while (keys.hasMoreElements())
766 {
767 String key = (String) keys.nextElement();
768 if (key.startsWith(prefix))
769 {
770 String value = getInterfaceText(interface_name, dictName, lang, key, null);
771
772 outputStr.append(prependToPrefix);
773 outputStr.append(".");
774 outputStr.append(key);
775 outputStr.append("=\"");
776 outputStr.append(value);
777 outputStr.append("\";\n");
778 }
779 }
780
781 if (foundCount > 0)
782 {
783 break;
784 }
785 }
786
787 return outputStr.toString();
788 }
789
790 public static String xmlNodeToString(Node node)
791 {
792 return GSXML.xmlNodeToString(node);
793 }
794
795 // Test from cmdline with:
796 // java -classpath /research/ak19/gs3-svn/web/WEB-INF/lib/gsdl3.jar:/research/ak19/gs3-svn/web/WEB-INF/lib/log4j-1.2.8.jar:/research/ak19/gs3-svn/web/WEB-INF/classes/ org.greenstone.gsdl3.util.XSLTUtil
797 public static void main(String args[])
798 {
799 System.out.println("\n@@@@@\n" + XSLTUtil.getInterfaceStringsAsJavascript("default", "en", "dse", "gs.text") + "@@@@@\n");
800 }
801}
Note: See TracBrowser for help on using the repository browser.