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

Last change on this file since 32459 was 32459, checked in by kjdon, 6 years ago

added groupsContain method - can't just use a string contains as e.g. if the current coll is mgppdemo, and user is in gs2mgppdemo-collection-editor group, then the groups line would match with mgppdemo-collection-editor. so need to split teh string, and test each value

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