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

Last change on this file since 33215 was 33215, checked in by kjdon, 5 years ago

in asking for something from eg heritage2 interface file, need to look in default2 not default interface properties file

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