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

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

renamed groupsContains to csvContains as that better reflects what its doing. Added getFormattedCCSSelection - returns a comma separated list of all collecitons and groups that are specified in the two args.

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