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

Last change on this file since 26334 was 26334, checked in by sjm84, 12 years ago

Fixing the language setting not working correctly when getting collection text. Also correcting missing macrons in Maori

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