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

Last change on this file since 33720 was 33720, checked in by ak19, 4 years ago

Implemented Dr Bainbridge's suggestions based on Kathy's solution to preventing script elements in queries (like a close script tag, open script tag, alert(1), close script tag) from ending up live when a search is performed.

  • 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 getInterfaceTextWithArgs(interface_name, lang, key, null);
225 }
226
227 public static String getInterfaceText(String interface_name, String lang, String key, String args_str)
228 {
229 String[] args = null;
230 if (args_str != null && !args_str.equals(""))
231 {
232 args = StringUtils.split(args_str, ";");
233 }
234 return getInterfaceTextWithArgs(interface_name, lang, key, args);
235 }
236
237 public static String getInterfaceText(String interface_name, String dictionary_name, String lang, String key, String args_str)
238 {
239 String[] args = null;
240 if (args_str != null && !args_str.equals(""))
241 {
242 args = StringUtils.split(args_str, ";");
243 }
244
245 // try the specified dictionary first
246 Dictionary dict = new Dictionary(dictionary_name, lang);
247 String result = dict.get(key, args);
248 if (result == null) {
249 // fall back to a general interface text search
250 return getInterfaceTextWithArgs(interface_name, lang, key, args);
251 }
252 result = result.replaceAll("__INTERFACE_NAME__", interface_name); // do we need to so this here?
253 return result;
254 }
255
256 public static String getInterfaceTextWithDOM(String interface_name, String lang, String key, Node arg_node)
257 {
258 return getInterfaceTextWithDOMMulti(interface_name, lang, key, arg_node);
259 }
260
261 public static String getInterfaceTextWithDOM(String interface_name, String lang, String key, Node arg1_node, Node arg2_node)
262 {
263 return getInterfaceTextWithDOMMulti(interface_name, lang, key, arg1_node, arg2_node);
264 }
265
266 public static String getInterfaceTextWithDOMMulti(String interface_name, String lang, String key, Node... nodes)
267 {
268 int num_nodes = nodes.length;
269 String[] args = null;
270 if (num_nodes != 0)
271 {
272 args = new String[num_nodes];
273
274 for (int i = 0; i < num_nodes; i++)
275 {
276 String node_str = XMLConverter.getString(nodes[i]);
277 args[i] = node_str;
278 }
279 }
280 return getInterfaceTextWithArgs(interface_name, lang, key, args);
281
282 }
283
284 /* This is the base method that actually does the work of looking up the various chain of dictionaries */
285 public static String getInterfaceTextWithArgs(String interface_name, String lang, String key, String[] args)
286 {
287 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
288
289 // do we need this?? values can have __INTERFACE_NAME__ but would keys ever have it???
290 key = key.replaceAll("__INTERFACE_NAME__", interface_name);
291 String result = dict.get(key, args);
292 if (result == null)
293 { // not found - TODO delete this???
294 //if not found, search a separate subdirectory named by the interface name
295 String sep_interface_dir = interface_name + File.separatorChar + lang + File.separatorChar + "interface";
296 dict = new Dictionary(sep_interface_dir, lang);
297 result = dict.get(key, args);
298 if (result != null)
299 {
300 return result;
301 }
302 }
303
304 if (result == null && !interface_name.startsWith("default")) {
305 // not found, try the default interface
306 if (interface_name.endsWith("2")) { // hack for interface_xxx2.properties
307 dict = new Dictionary("interface_default2", lang);
308 } else {
309 dict = new Dictionary("interface_default", lang);
310
311 }
312 result = dict.get(key, args);
313 }
314
315 if (result == null)
316 { // not found
317 return "?" + key + "?";
318 }
319 result = result.replaceAll("__INTERFACE_NAME__", interface_name);
320
321 return result;
322
323
324
325 }
326 public static String getInterfaceTextSubstituteArgs(String value, String args_str)
327 {
328 String[] args = null;
329 if (args_str != null && !args_str.equals("")) {
330 args = StringUtils.split(args_str, ";");
331 }
332
333 return Dictionary.processArgs(value,args);
334 }
335
336 public static Node getCollectionText(String collection, String site_name, String lang, String key)
337 {
338 return getCollectionTextWithArgs(collection, site_name, lang, key, null);
339 }
340
341 public static Node getCollectionText(String collection, String site_name, String lang, String key, String args_str)
342 {
343
344 String[] args = null;
345 if (args_str != null && !args_str.equals(""))
346 {
347 args = StringUtils.split(args_str, ";");
348 }
349
350 return getCollectionTextWithArgs(collection, site_name, lang, key, args);
351 }
352
353 // xslt didn't like calling the function with Node varargs, so have this hack for now
354 public static Node getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1)
355 {
356 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1);
357 }
358
359 public static Node getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2)
360 {
361 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2);
362 }
363
364 public static Node getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2, Node n3)
365 {
366 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2, n3);
367 }
368
369 public static Node getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2, Node n3, Node n4)
370 {
371 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2, n3, n4);
372 }
373
374 public static Node getCollectionTextWithDOMMulti(String collection, String site_name, String lang, String key, Node... nodes)
375 {
376 int num_nodes = nodes.length;
377 String[] args = null;
378 if (num_nodes != 0)
379 {
380 args = new String[num_nodes];
381
382 for (int i = 0; i < num_nodes; i++)
383 {
384 String node_str = XMLConverter.getString(nodes[i]);
385 args[i] = node_str;
386 }
387 }
388 return getCollectionTextWithArgs(collection, site_name, lang, key, args);
389 }
390
391 public static Node getCollectionTextWithArgs(String collection, String site_name, String lang, String key, String[] args)
392 {
393 try
394 {
395 DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
396
397 CustomClassLoader class_loader = new CustomClassLoader(XSLTUtil.class.getClassLoader(), GSFile.collectionResourceDir(GSFile.siteHome(GlobalProperties.getGSDL3Home(), site_name), collection));
398 Dictionary dict = new Dictionary("interface_custom", lang, class_loader);
399 String result = dict.get(key, args);
400 if (result != null)
401 {
402 return docBuilder.parse(new ByteArrayInputStream(("<fragment>" + result + "</fragment>").getBytes("UTF-8"))).getDocumentElement();
403 }
404 return docBuilder.parse(new ByteArrayInputStream(("<fragment>" + "text:" + collection + ":" + key + "</fragment>").getBytes())).getDocumentElement();
405 }
406 catch (Exception ex)
407 {
408 return null;
409 }
410 }
411
412 public static String getGenericText(String dictionary_name, String lang, String key) {
413 return getGenericTextWithArgs(dictionary_name, lang, key, null);
414 }
415
416 public String getGenericText(String dictionary_name, String lang, String key, String args_str) {
417 String[] args = null;
418 if (args_str != null && !args_str.equals("")) {
419 args = StringUtils.split(args_str, ";");
420 }
421 return getGenericTextWithArgs(dictionary_name, lang, key, args);
422 }
423
424 public static String getGenericTextWithArgs(String dictionary_name, String lang, String key, String[] args)
425 {
426 Dictionary dict = new Dictionary(dictionary_name, lang);
427 String result = dict.get(key, args);
428 if (result == null) {
429 return "_"+dictionary_name+"_"+key+"_";
430 }
431 return result;
432 }
433
434
435
436 public static boolean isImage(String mimetype)
437 {
438 if (mimetype.startsWith("image/"))
439 {
440 return true;
441 }
442 return false;
443 }
444
445 // formatting /preprocessing functions
446 // some require a language, so we'll have a language param for all
447 public static String toLower(String orig, String lang)
448 {
449 return orig.toLowerCase();
450 }
451
452 public static String toUpper(String orig, String lang)
453 {
454 return orig.toUpperCase();
455 }
456
457 public static String tidyWhitespace(String original, String lang)
458 {
459
460 if (original == null || original.equals(""))
461 {
462 return original;
463 }
464 String new_s = original.replaceAll("\\s+", " ");
465 return new_s;
466 }
467
468 public static String stripWhitespace(String original, String lang)
469 {
470
471 if (original == null || original.equals(""))
472 {
473 return original;
474 }
475 String new_s = original.replaceAll("\\s+", "");
476 return new_s;
477 }
478
479 public static byte[] toUTF8(String orig, String lang)
480 {
481 try
482 {
483 byte[] utf8 = orig.getBytes("UTF-8");
484 return utf8;
485 }
486 catch (Exception e)
487 {
488 logger.error("unsupported encoding");
489 return orig.getBytes();
490 }
491 }
492
493 public static String formatDate(String date, String lang)
494 {
495 String in_pattern = "yyyyMMdd";
496 String out_pattern = "dd MMMM yyyy";
497 if (date.length() == 6)
498 {
499 in_pattern = "yyyyMM";
500 out_pattern = "MMMM yyyy";
501 }
502 // remove the 00
503 else if (date.length() == 8 && date.endsWith("00")) {
504 date = date.substring(0,6);
505 in_pattern = "yyyyMM";
506 out_pattern = "MMMM yyyy";
507 }
508
509 SimpleDateFormat formatter = new SimpleDateFormat(in_pattern, new Locale(lang));
510 try
511 {
512 Date d = formatter.parse(date);
513 formatter.applyPattern(out_pattern);
514 String new_date = formatter.format(d);
515 return new_date;
516 }
517 catch (Exception e)
518 {
519 return date;
520 }
521
522 }
523
524 public static final int TS_SECS = 0;
525 public static final int TS_MILLISECS = 1;
526 public static final int F_DATE = 0;
527 public static final int F_TIME = 1;
528 public static final int F_DATETIME = 2;
529 public static final int F_DAYSAGO = 3;
530
531 public static String formatTimeStamp(String timestamp, int ts_type, int format_type, String lang) {
532 try {
533 long ts = Long.parseLong(timestamp);
534 if (ts_type == TS_SECS) {
535 ts = ts * 1000;
536 }
537 if (format_type == F_DAYSAGO) {
538 long current_time = new Date().getTime();
539 long days = (current_time - ts)/86400000;
540 return String.valueOf(days);
541 }
542 Date d = new Date(ts);
543 DateFormat df;
544 switch (format_type) {
545 case F_DATE:
546 df = DateFormat.getDateInstance(DateFormat.DEFAULT, new Locale(lang));
547 break;
548 case F_TIME:
549 df = DateFormat.getTimeInstance(DateFormat.DEFAULT, new Locale(lang));
550 break;
551 case F_DATETIME:
552 df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, new Locale(lang));
553 break;
554 default:
555 df = DateFormat.getDateInstance(DateFormat.DEFAULT, new Locale(lang));
556 break;
557 }
558
559 return df.format(d);
560 } catch (Exception e) {
561
562 return timestamp + e.getMessage();
563 }
564
565 }
566 public static String getDetailFromDate(String date, String detail, String lang)
567 {
568 String in_pattern = "yyyyMMdd";
569 if (date.length() == 6)
570 {
571 in_pattern = "yyyyMM";
572 }
573 // remove the 00
574 else if (date.length() == 8 && date.endsWith("00")) {
575 date = date.substring(0,6);
576 in_pattern = "yyyyMM";
577 }
578
579 SimpleDateFormat formatter = new SimpleDateFormat(in_pattern, new Locale(lang));
580 try
581 {
582 Date d = formatter.parse(date);
583 if (detail.toLowerCase().equals("day"))
584 {
585 formatter.applyPattern("dd");
586 }
587 else if (detail.toLowerCase().equals("month"))
588 {
589 formatter.applyPattern("MMMM");
590 }
591 else if (detail.toLowerCase().equals("year"))
592 {
593 formatter.applyPattern("yyyy");
594 }
595 else
596 {
597 return "";
598 }
599 return formatter.format(d);
600 }
601 catch (Exception ex)
602 {
603 return "";
604 }
605 }
606
607 public static String formatLanguage(String display_lang, String lang)
608 {
609
610 return new Locale(display_lang).getDisplayLanguage(new Locale(lang));
611 }
612
613 public static boolean checkFileExistence(String site_name, String filePath){
614
615 String gsdl3_home = GlobalProperties.getGSDL3Home();
616 //Remove leading file separator
617 filePath = filePath.replaceAll("^/+", "");
618 //Remove duplicates and replace by separator for current platform
619 filePath = filePath.replaceAll("/+", File.separator);
620 //Create full path to check
621 String fullPath = GSFile.siteHome(gsdl3_home, site_name) + File.separator + filePath;
622 File file = new File(fullPath);
623 if (file.exists() && file.isFile()) {
624 return true;
625 }
626 return false;
627 }
628
629 public static String uriEncode(String input)
630 {
631 String result = "";
632 try {
633 result = URLEncoder.encode(input, "UTF-8");
634 } catch (UnsupportedEncodingException e) {
635 e.printStackTrace();
636 }
637
638 return result;
639
640 }
641
642 public static String cgiSafe(String original, String lang)
643 {
644
645 original = original.replace('&', ' ');
646 original = original.replaceAll(" ", "%20");
647 return original;
648 }
649
650 public static String formatBigNumber(String num, String lang)
651 {
652
653 String num_str = num;
654 char[] num_chars = num_str.toCharArray();
655 String zero_str = "";
656 String formatted_str = "";
657
658 for (int i = num_chars.length - 4; i >= 0; i--)
659 {
660 zero_str += '0';
661 }
662
663 String sig_str = "";
664 for (int i = 0; i < 3 && i < num_chars.length; i++)
665 {
666 sig_str = sig_str + num_chars[i];
667 if (i == 1 && i + 1 < num_chars.length)
668 {
669 sig_str = sig_str + ".";
670 }
671 }
672
673 int sig_int = Math.round(Float.parseFloat(sig_str));
674 String new_sig_str = sig_int + "";
675 if (sig_str.length() > 2)
676 {
677 new_sig_str = sig_int + "0";
678 }
679
680 char[] final_chars = (new_sig_str + zero_str).toCharArray();
681 int count = 1;
682 for (int i = final_chars.length - 1; i >= 0; i--)
683 {
684 formatted_str = final_chars[i] + formatted_str;
685 if (count == 3 && i != 0)
686 {
687 formatted_str = "," + formatted_str;
688 count = 1;
689 }
690 else
691 {
692 count++;
693 }
694 }
695 return formatted_str;
696 }
697
698 public static String hashToSectionId(String hashString)
699 {
700 if (hashString == null || hashString.length() == 0)
701 {
702 return "";
703 }
704
705 int firstDotIndex = hashString.indexOf(".");
706 if (firstDotIndex == -1)
707 {
708 return "";
709 }
710
711 String sectionString = hashString.substring(firstDotIndex + 1);
712
713 return sectionString;
714 }
715
716 public static String hashToDepthClass(String hashString)
717 {
718 if (hashString == null || hashString.length() == 0)
719 {
720 return "";
721 }
722
723 String sectionString = hashToSectionId(hashString);
724
725 int count = sectionString.split("\\.").length;
726
727 if (sectionString.equals(""))
728 {
729 return "sectionHeaderDepthTitle";
730 }
731 else
732 {
733 return "sectionHeaderDepth" + count;
734 }
735 }
736
737 public static String escapeNewLines(String str)
738 {
739 if (str == null || str.length() < 1)
740 {
741 return null;
742 }
743 return str.replace("\n", "\\\n");
744 }
745
746 public static String escapeQuotes(String str)
747 {
748 if (str == null || str.length() < 1)
749 {
750 return null;
751 }
752 return str.replace("\"", "\\\"");
753 }
754 public static String escapeAngleBrackets(String str)
755 {
756 if (str == null || str.length() < 1)
757 {
758 return null;
759 }
760 return str.replace("<", "&lt;").replace(">", "&gt;");
761 }
762
763 public static String escapeNewLinesAndQuotes(String str)
764 {
765 if (str == null || str.length() < 1)
766 {
767 return null;
768 }
769 return escapeNewLines(escapeQuotes(str));
770 }
771
772 public static String escapeNewLinesQuotesAngleBracketsForJSString(String str)
773 {
774 // The \n and " becomes \\\n and \\\"
775 // but the <> are escaped/encoded for html, i.e. &gt; and &lt;
776 if (str == null || str.length() < 1)
777 {
778 return null;
779 }
780 return escapeAngleBrackets(escapeNewLines(escapeQuotes(str)));
781 }
782 public static String getGlobalProperty(String name)
783 {
784 return GlobalProperties.getProperty(name);
785 }
786
787 public static void clearMetadataStorage()
788 {
789 _foundTableValues.clear();
790 }
791
792 public static boolean checkMetadataNotDuplicate(String name, String value)
793 {
794 if (_foundTableValues.containsKey(name))
795 {
796 for (String mapValue : _foundTableValues.get(name))
797 {
798 if (mapValue.equals(value))
799 {
800 return false;
801 }
802 }
803 _foundTableValues.get(name).add(value);
804 return true;
805 }
806
807 ArrayList<String> newList = new ArrayList<String>();
808 newList.add(value);
809
810 _foundTableValues.put(name, newList);
811
812 return true;
813 }
814
815 public static String reCAPTCHAimage(String publicKey, String privateKey)
816 {
817 ReCaptcha c = ReCaptchaFactory.newReCaptcha(publicKey, privateKey, false);
818 return c.createRecaptchaHtml(null, null);
819 }
820
821 public static String getInterfaceStringsAsJavascript(String interface_name, String lang, String prefix)
822 {
823 String prependToPrefix = "gs.text";
824 return XSLTUtil.getInterfaceStringsAsJavascript(interface_name, lang, prefix, prependToPrefix);
825 }
826
827 // generates javascript: 2 arrays are declared and populated with strings that declare variables and assign their values
828 // to be strings loaded from the interface_name.properties file for the language.
829 public static String getInterfaceStringsAsJavascript(String interface_name, String lang, String prefix, String prependToPrefix)
830 {
831 String prefixwithdot = prefix+".";
832 // 1. Generating Javascript of the form:
833 // if(!gs.text) { gs.text = new Array(); }
834 // if(!gs.text.dse) { gs.text.dse = new Array(); }
835 StringBuffer outputStr = new StringBuffer();
836 outputStr.append("if(!gs.text) { ");
837 outputStr.append(prependToPrefix + " = new Array(); ");
838 outputStr.append("}\n");
839 outputStr.append("if(!gs.text." + prefix + ") { ");
840 outputStr.append(prependToPrefix + "." + prefix + " = new Array(); ");
841 outputStr.append("}\n");
842
843 int foundCount = 0;
844
845 for (String dictName : new String[] { "interface_" + interface_name, "interface_default", "interface_default2" })
846 {
847 // get all the keys from the english dictionary as this is a complete set
848 Dictionary dict = new Dictionary(dictName, "en");
849 Enumeration keys = dict.getKeys();
850 if (keys == null)
851 {
852 continue;
853 }
854
855 // Get all properties in the language-specific dictionary with the given key prefix
856 // Create Javascript strings of the form:
857 // prependToPrefix.key= "value";\n
858 while (keys.hasMoreElements())
859 {
860 String key = (String) keys.nextElement();
861 if (key.startsWith(prefixwithdot))
862 {
863 // get the language dependent value for the key. This will return the english if no value found for the given lang
864 String value = getInterfaceText(interface_name, dictName, lang, key, null);
865
866 outputStr.append(prependToPrefix);
867 outputStr.append(".");
868 outputStr.append(key);
869 outputStr.append("=\"");
870 outputStr.append(value);
871 outputStr.append("\";\n");
872 }
873 }
874
875 if (foundCount > 0)
876 {
877 break;
878 }
879 }
880
881 return outputStr.toString();
882 }
883
884 public static String xmlNodeToString(Node node)
885 {
886 return GSXML.xmlNodeToString(node);
887 }
888
889 // Test from cmdline with:
890 // 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
891 public static void main(String args[])
892 {
893 System.out.println("\n@@@@@\n" + XSLTUtil.getInterfaceStringsAsJavascript("default", "en", "dse", "gs.text") + "@@@@@\n");
894 }
895}
Note: See TracBrowser for help on using the repository browser.