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

Last change on this file since 35394 was 35394, checked in by kjdon, 3 years ago

need to do the class loader trick for the javascript version of getting insterface strings

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