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

Last change on this file since 30359 was 30359, checked in by Georgiy Litvinov, 8 years ago

Added URI Encoding method for xslt utils

  • Property svn:keywords set to Author Date Id Revision
File size: 20.8 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 public static Node getCollectionText(String collection, String site_name, String lang, String key)
348 {
349 return getCollectionTextWithArgs(collection, site_name, lang, key, null);
350 }
351
352 public static Node getCollectionText(String collection, String site_name, String lang, String key, String args_str)
353 {
354
355 String[] args = null;
356 if (args_str != null && !args_str.equals(""))
357 {
358 args = StringUtils.split(args_str, ";");
359 }
360
361 return getCollectionTextWithArgs(collection, site_name, lang, key, args);
362 }
363
364 // xslt didn't like calling the function with Node varargs, so have this hack for now
365 public static Node getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1)
366 {
367 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1);
368 }
369
370 public static Node getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2)
371 {
372 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2);
373 }
374
375 public static Node getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2, Node n3)
376 {
377 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2, n3);
378 }
379
380 public static Node getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2, Node n3, Node n4)
381 {
382 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2, n3, n4);
383 }
384
385 public static Node getCollectionTextWithDOMMulti(String collection, String site_name, String lang, String key, Node... nodes)
386 {
387 int num_nodes = nodes.length;
388 String[] args = null;
389 if (num_nodes != 0)
390 {
391 args = new String[num_nodes];
392
393 for (int i = 0; i < num_nodes; i++)
394 {
395 String node_str = XMLConverter.getString(nodes[i]);
396 args[i] = node_str;
397 }
398 }
399 return getCollectionTextWithArgs(collection, site_name, lang, key, args);
400 }
401
402 public static Node getCollectionTextWithArgs(String collection, String site_name, String lang, String key, String[] args)
403 {
404 try
405 {
406 DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
407
408 CollectionClassLoader class_loader = new CollectionClassLoader(XSLTUtil.class.getClassLoader(), GSFile.siteHome(GlobalProperties.getGSDL3Home(), site_name), collection);
409 Dictionary dict = new Dictionary(collection, lang, class_loader);
410 String result = dict.get(key, args);
411 if (result != null)
412 {
413 return docBuilder.parse(new ByteArrayInputStream(("<fragment>" + result + "</fragment>").getBytes("UTF-8"))).getDocumentElement();
414 }
415 return docBuilder.parse(new ByteArrayInputStream(("<fragment>" + "text:" + collection + ":" + key + "</fragment>").getBytes())).getDocumentElement();
416 }
417 catch (Exception ex)
418 {
419 return null;
420 }
421 }
422
423 public static boolean isImage(String mimetype)
424 {
425 if (mimetype.startsWith("image/"))
426 {
427 return true;
428 }
429 return false;
430 }
431
432 // formatting /preprocessing functions
433 // some require a language, so we'll have a language param for all
434 public static String toLower(String orig, String lang)
435 {
436 return orig.toLowerCase();
437 }
438
439 public static String toUpper(String orig, String lang)
440 {
441 return orig.toUpperCase();
442 }
443
444 public static String tidyWhitespace(String original, String lang)
445 {
446
447 if (original == null || original.equals(""))
448 {
449 return original;
450 }
451 String new_s = original.replaceAll("\\s+", " ");
452 return new_s;
453 }
454
455 public static String stripWhitespace(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 byte[] toUTF8(String orig, String lang)
467 {
468 try
469 {
470 byte[] utf8 = orig.getBytes("UTF-8");
471 return utf8;
472 }
473 catch (Exception e)
474 {
475 logger.error("unsupported encoding");
476 return orig.getBytes();
477 }
478 }
479
480 public static String formatDate(String date, String lang)
481 {
482 String in_pattern = "yyyyMMdd";
483 String out_pattern = "dd MMMM yyyy";
484 if (date.length() == 6)
485 {
486 in_pattern = "yyyyMM";
487 }
488
489 SimpleDateFormat formatter = new SimpleDateFormat(in_pattern, new Locale(lang));
490 try
491 {
492 Date d = formatter.parse(date);
493 formatter.applyPattern(out_pattern);
494 String new_date = formatter.format(d);
495 return new_date;
496 }
497 catch (Exception e)
498 {
499 return date;
500 }
501
502 }
503
504 public static String getDetailFromDate(String date, String detail, String lang)
505 {
506 String in_pattern = "yyyyMMdd";
507 if (date.length() == 6)
508 {
509 in_pattern = "yyyyMM";
510 }
511
512 SimpleDateFormat formatter = new SimpleDateFormat(in_pattern, new Locale(lang));
513 try
514 {
515 Date d = formatter.parse(date);
516 if (detail.toLowerCase().equals("day"))
517 {
518 formatter.applyPattern("dd");
519 }
520 else if (detail.toLowerCase().equals("month"))
521 {
522 formatter.applyPattern("MMMM");
523 }
524 else if (detail.toLowerCase().equals("year"))
525 {
526 formatter.applyPattern("yyyy");
527 }
528 else
529 {
530 return "";
531 }
532 return formatter.format(d);
533 }
534 catch (Exception ex)
535 {
536 return "";
537 }
538 }
539
540 public static String formatLanguage(String display_lang, String lang)
541 {
542
543 return new Locale(display_lang).getDisplayLanguage(new Locale(lang));
544 }
545 public static String uriEncode(String input)
546 {
547 String result = "";
548 if (input != null && input != "") {
549 try {
550 result = URLEncoder.encode(input, "UTF-8");
551 } catch (UnsupportedEncodingException e) {
552 e.printStackTrace();
553 }
554
555 }
556 return result;
557
558 }
559
560 public static String cgiSafe(String original, String lang)
561 {
562
563 original = original.replace('&', ' ');
564 original = original.replaceAll(" ", "%20");
565 return original;
566 }
567
568 public static String formatBigNumber(String num, String lang)
569 {
570
571 String num_str = num;
572 char[] num_chars = num_str.toCharArray();
573 String zero_str = "";
574 String formatted_str = "";
575
576 for (int i = num_chars.length - 4; i >= 0; i--)
577 {
578 zero_str += '0';
579 }
580
581 String sig_str = "";
582 for (int i = 0; i < 3 && i < num_chars.length; i++)
583 {
584 sig_str = sig_str + num_chars[i];
585 if (i == 1 && i + 1 < num_chars.length)
586 {
587 sig_str = sig_str + ".";
588 }
589 }
590
591 int sig_int = Math.round(Float.parseFloat(sig_str));
592 String new_sig_str = sig_int + "";
593 if (sig_str.length() > 2)
594 {
595 new_sig_str = sig_int + "0";
596 }
597
598 char[] final_chars = (new_sig_str + zero_str).toCharArray();
599 int count = 1;
600 for (int i = final_chars.length - 1; i >= 0; i--)
601 {
602 formatted_str = final_chars[i] + formatted_str;
603 if (count == 3 && i != 0)
604 {
605 formatted_str = "," + formatted_str;
606 count = 1;
607 }
608 else
609 {
610 count++;
611 }
612 }
613 return formatted_str;
614 }
615
616 public static String hashToSectionId(String hashString)
617 {
618 if (hashString == null || hashString.length() == 0)
619 {
620 return "";
621 }
622
623 int firstDotIndex = hashString.indexOf(".");
624 if (firstDotIndex == -1)
625 {
626 return "";
627 }
628
629 String sectionString = hashString.substring(firstDotIndex + 1);
630
631 return sectionString;
632 }
633
634 public static String hashToDepthClass(String hashString)
635 {
636 if (hashString == null || hashString.length() == 0)
637 {
638 return "";
639 }
640
641 String sectionString = hashToSectionId(hashString);
642
643 int count = sectionString.split("\\.").length;
644
645 if (sectionString.equals(""))
646 {
647 return "sectionHeaderDepthTitle";
648 }
649 else
650 {
651 return "sectionHeaderDepth" + count;
652 }
653 }
654
655 public static String escapeNewLines(String str)
656 {
657 if (str == null || str.length() < 1)
658 {
659 return null;
660 }
661 return str.replace("\n", "\\\n");
662 }
663
664 public static String escapeQuotes(String str)
665 {
666 if (str == null || str.length() < 1)
667 {
668 return null;
669 }
670 return str.replace("\"", "\\\"");
671 }
672
673 public static String escapeNewLinesAndQuotes(String str)
674 {
675 if (str == null || str.length() < 1)
676 {
677 return null;
678 }
679 return escapeNewLines(escapeQuotes(str));
680 }
681
682 public static String getGlobalProperty(String name)
683 {
684 return GlobalProperties.getProperty(name);
685 }
686
687 public static void clearMetadataStorage()
688 {
689 _foundTableValues.clear();
690 }
691
692 public static boolean checkMetadataNotDuplicate(String name, String value)
693 {
694 if (_foundTableValues.containsKey(name))
695 {
696 for (String mapValue : _foundTableValues.get(name))
697 {
698 if (mapValue.equals(value))
699 {
700 return false;
701 }
702 }
703 _foundTableValues.get(name).add(value);
704 return true;
705 }
706
707 ArrayList<String> newList = new ArrayList<String>();
708 newList.add(value);
709
710 _foundTableValues.put(name, newList);
711
712 return true;
713 }
714
715 public static String reCAPTCHAimage(String publicKey, String privateKey)
716 {
717 ReCaptcha c = ReCaptchaFactory.newReCaptcha(publicKey, privateKey, false);
718 return c.createRecaptchaHtml(null, null);
719 }
720
721 public static String getInterfaceStringsAsJavascript(String interface_name, String lang, String prefix)
722 {
723 String prependToPrefix = "gs.text";
724 return XSLTUtil.getInterfaceStringsAsJavascript(interface_name, lang, prefix, prependToPrefix);
725 }
726
727 // generates javascript: 2 arrays are declared and populated with strings that declare variables and assign their values
728 // to be strings loaded from the interface_name.properties file for the language.
729 public static String getInterfaceStringsAsJavascript(String interface_name, String lang, String prefix, String prependToPrefix)
730 {
731 // 1. Generating Javascript of the form:
732 // if(!gs.text) { gs.text = new Array(); }
733 // if(!gs.text.dse) { gs.text.dse = new Array(); }
734 StringBuffer outputStr = new StringBuffer();
735 outputStr.append("if(!gs.text) { ");
736 outputStr.append(prependToPrefix + " = new Array(); ");
737 outputStr.append("}\n");
738 outputStr.append("if(!gs.text." + prefix + ") { ");
739 outputStr.append(prependToPrefix + "." + prefix + " = new Array(); ");
740 outputStr.append("}\n");
741
742 int foundCount = 0;
743
744 for (String dictName : new String[] { "interface_" + interface_name, "interface_default", "interface_default2" })
745 {
746 Dictionary dict = new Dictionary(dictName, lang);
747 Enumeration keys = dict.getKeys();
748 if (keys == null)
749 {
750 continue;
751 }
752
753 // Get all properties in the language-specific dictionary with the given key prefix
754 // Create Javascript strings of the form:
755 // prependToPrefix.key= "value";\n
756 while (keys.hasMoreElements())
757 {
758 String key = (String) keys.nextElement();
759 if (key.startsWith(prefix))
760 {
761 String value = getInterfaceText(interface_name, dictName, lang, key, null);
762
763 outputStr.append(prependToPrefix);
764 outputStr.append(".");
765 outputStr.append(key);
766 outputStr.append("=\"");
767 outputStr.append(value);
768 outputStr.append("\";\n");
769 }
770 }
771
772 if (foundCount > 0)
773 {
774 break;
775 }
776 }
777
778 return outputStr.toString();
779 }
780
781 public static String xmlNodeToString(Node node)
782 {
783 return GSXML.xmlNodeToString(node);
784 }
785
786 // Test from cmdline with:
787 // 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
788 public static void main(String args[])
789 {
790 System.out.println("\n@@@@@\n" + XSLTUtil.getInterfaceStringsAsJavascript("default", "en", "dse", "gs.text") + "@@@@@\n");
791 }
792}
Note: See TracBrowser for help on using the repository browser.