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

Last change on this file since 26243 was 26243, checked in by kjdon, 12 years ago

added getCollectionTextWithDOM methods - looks for collname.properties in the collection's resources folder

  • Property svn:keywords set to Author Date Id Revision
File size: 16.8 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.File;
22import java.text.SimpleDateFormat;
23import java.util.ArrayList;
24import java.util.Date;
25import java.util.Enumeration;
26import java.util.HashMap;
27import java.util.Locale;
28
29import net.tanesha.recaptcha.ReCaptcha;
30import net.tanesha.recaptcha.ReCaptchaFactory;
31
32import org.apache.commons.lang3.StringUtils;
33import org.apache.log4j.Logger;
34import org.greenstone.util.GlobalProperties;
35import org.w3c.dom.Node;
36import org.w3c.dom.NodeList;
37
38/**
39 * a class to contain various static methods that are used by the xslt
40 * stylesheets
41 */
42public class XSLTUtil
43{
44 protected static HashMap<String, ArrayList<String>> _foundTableValues = new HashMap<String, ArrayList<String>>();
45 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.util.XSLTUtil.class.getName());
46
47 /* some tests */
48 public static boolean equals(String s1, String s2)
49 {
50 return s1.equals(s2);
51 }
52
53 public static boolean notEquals(String s1, String s2)
54 {
55 return !s1.equals(s2);
56 }
57
58 public static boolean exists(String s1, String s2)
59 {
60 return !s1.equals("");
61 }
62
63 public static boolean contains(String s1, String s2)
64 {
65 return (s1.indexOf(s2) != -1);
66 }
67
68 public static boolean startsWith(String s1, String s2)
69 {
70 return s1.startsWith(s2);
71 }
72
73 public static boolean endsWith(String s1, String s2)
74 {
75 return s1.endsWith(s2);
76 }
77
78 public static boolean lessThan(String s1, String s2)
79 {
80 return (s1.compareTo(s2) < 0);
81 }
82
83 public static boolean lessThanOrEquals(String s1, String s2)
84 {
85 return (s1.compareTo(s2) <= 0);
86 }
87
88 public static boolean greaterThan(String s1, String s2)
89 {
90 return (s1.compareTo(s2) > 0);
91 }
92
93 public static boolean greaterThanOrEquals(String s1, String s2)
94 {
95 return (s1.compareTo(s2) >= 0);
96 }
97
98 public static boolean oidIsMatchOrParent(String first, String second)
99 {
100 if (first.equals(second))
101 {
102 return true;
103 }
104
105 String[] firstParts = first.split(".");
106 String[] secondParts = second.split(".");
107
108 if (firstParts.length >= secondParts.length)
109 {
110 return false;
111 }
112
113 for (int i = 0; i < firstParts.length; i++)
114 {
115 if (!firstParts[i].equals(secondParts[i]))
116 {
117 return false;
118 }
119 }
120
121 return true;
122 }
123
124
125 public static String replace(String orig, String match, String replacement)
126 {
127 return orig.replace(match, replacement);
128 }
129
130 public static String getNumberedItem(String list, int number)
131 {
132 String[] items = StringUtils.split(list, ",", -1);
133 if (items.length > number)
134 {
135 return items[number];
136 }
137 return ""; // index out of bounds
138 }
139
140 /**
141 * Generates links to equivalent documents for a document with a default
142 * document icon/type. Links are generated from the parameters: a list of
143 * document icons which are each in turn embedded in the matching starting
144 * link tag in the list of docStartLinks (these starting links link to the
145 * equivalent documents in another format). Each link's start tag is closed
146 * with the corresponding closing tag in the docEndLinks list. Parameter
147 * token is the list separator. Parameter divider is the string that should
148 * separate each final link generated from the next. Returns a string that
149 * represents a sequence of links to equivalent documents, where the anchor
150 * is a document icon.
151 */
152 public static String getEquivDocLinks(String token, String docIconsString, String docStartLinksString, String docEndLinksString, String divider)
153 {
154 String[] docIcons = StringUtils.split(docIconsString, token, -1);
155 String[] startLinks = StringUtils.split(docStartLinksString, token, -1);
156 String[] endLinks = StringUtils.split(docEndLinksString, token, -1);
157
158 StringBuffer buffer = new StringBuffer();
159 for (int i = 0; i < docIcons.length; i++)
160 {
161 if (i > 0)
162 {
163 buffer.append(divider);
164 }
165 buffer.append(startLinks[i] + docIcons[i] + endLinks[i]);
166 }
167
168 return buffer.toString();
169 }
170
171
172 public static String getInterfaceText(String interface_name, String lang, String key)
173 {
174 return getInterfaceText(interface_name, lang, key, null);
175 }
176
177 public static String getInterfaceText(String interface_name, String lang, String key, String args_str)
178 {
179 key = key.replaceAll("__INTERFACE_NAME__", interface_name);
180
181 String[] args = null;
182 if (args_str != null && !args_str.equals(""))
183 {
184 args = StringUtils.split(args_str, ";");
185 }
186 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
187 String result = dict.get(key, args);
188 if (result == null)
189 { // not found
190 //if not found, search a separate subdirectory named by the interface name
191 String sep_interface_dir = interface_name + File.separatorChar + lang + File.separatorChar + "interface";
192 dict = new Dictionary(sep_interface_dir, lang);
193 result = dict.get(key, args);
194 if (result != null)
195 {
196 result = result.replaceAll("__INTERFACE_NAME__", interface_name);
197 return result;
198 }
199 }
200
201 if (result == null && !interface_name.equals("default"))
202 { // not found, try the default interface
203 dict = new Dictionary("interface_default", lang);
204 result = dict.get(key, args);
205 }
206
207 if (result == null)
208 { // not found
209 return "_" + key + "_";
210 }
211 result = result.replaceAll("__INTERFACE_NAME__", interface_name);
212 return result;
213 }
214
215 public static String getInterfaceTextWithDOM(String interface_name, String lang, String key, Node arg_node)
216 {
217 String[] args = new String[1];
218
219 String node_str = XMLConverter.getString(arg_node);
220 args[0] = node_str;
221 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
222 String result = dict.get(key, args);
223 if (result == null)
224 { // not found
225 //if not found, search a separate subdirectory named by the interface name
226 String sep_interface_dir = interface_name + File.separatorChar + lang + File.separatorChar + "interface";
227 dict = new Dictionary(sep_interface_dir, lang);
228 result = dict.get(key, args);
229 if (result != null)
230 {
231 return result;
232 }
233 }
234
235 if (result == null && !interface_name.equals("default"))
236 { // not found, try the default interface
237 dict = new Dictionary("interface_default", lang);
238 result = dict.get(key, args);
239 }
240
241 if (result == null)
242 { // not found
243 return "_" + key + "_";
244 }
245
246 return result;
247 }
248
249 public static String getInterfaceTextWithDOM(String interface_name, String lang, String key, Node arg1_node, Node arg2_node)
250 {
251 String[] args = new String[2];
252
253 String node_str = XMLConverter.getString(arg1_node);
254 args[0] = node_str;
255 node_str = XMLConverter.getString(arg2_node);
256 args[1] = node_str;
257 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
258 String result = dict.get(key, args);
259 if (result == null)
260 { // not found
261 //if not found, search a separate subdirectory named by the interface name
262 String sep_interface_dir = interface_name + File.separatorChar + lang + File.separatorChar + "interface";
263 dict = new Dictionary(sep_interface_dir, lang);
264 result = dict.get(key, args);
265 if (result != null)
266 {
267 return result;
268 }
269 }
270
271 if (result == null && !interface_name.equals("default"))
272 { // not found, try the default interface
273 dict = new Dictionary("interface_default", lang);
274 result = dict.get(key, args);
275 }
276
277 if (result == null)
278 { // not found
279 return "_" + key + "_";
280 }
281
282 return result;
283 }
284
285 // xslt didn't like calling the function with Node varargs, so have this hack for now
286 public static String getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1) {
287 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1);
288 }
289 public static String getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2) {
290 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2);
291 }
292 public static String getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2, Node n3) {
293 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2, n3);
294 }
295 public static String getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2, Node n3, Node n4) {
296 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2, n3, n4);
297 }
298 public static String getCollectionTextWithDOMMulti(String collection, String site_name, String lang, String key, Node ... nodes) {
299
300 int num_nodes = nodes.length;
301 String[] args = new String[num_nodes];
302
303 for (int i=0; i<num_nodes; i++) {
304
305 String node_str = XMLConverter.getString(nodes[i]);
306 args[i] = node_str;
307 }
308 CollectionClassLoader class_loader = new CollectionClassLoader(XSLTUtil.class.getClassLoader(), GSFile.siteHome(GlobalProperties.getGSDL3Home(), site_name), collection);
309 Dictionary dict = new Dictionary(collection, lang, class_loader);
310 String result = dict.get(key, args);
311 if (result != null) {
312 return result;
313 }
314 return "text:"+collection+":"+key;
315
316 }
317
318
319 public static boolean isImage(String mimetype)
320 {
321 if (mimetype.startsWith("image/"))
322 {
323 return true;
324 }
325 return false;
326 }
327
328 // formatting /preprocessing functions
329 // some require a language, so we'll have a language param for all
330 public static String toLower(String orig, String lang)
331 {
332 return orig.toLowerCase();
333 }
334
335 public static String toUpper(String orig, String lang)
336 {
337 return orig.toUpperCase();
338 }
339
340 public static String tidyWhitespace(String original, String lang)
341 {
342
343 if (original == null || original.equals(""))
344 {
345 return original;
346 }
347 String new_s = original.replaceAll("\\s+", " ");
348 return new_s;
349 }
350
351 public static String stripWhitespace(String original, String lang)
352 {
353
354 if (original == null || original.equals(""))
355 {
356 return original;
357 }
358 String new_s = original.replaceAll("\\s+", "");
359 return new_s;
360 }
361
362 public static byte[] toUTF8(String orig, String lang)
363 {
364 try
365 {
366 byte[] utf8 = orig.getBytes("UTF-8");
367 return utf8;
368 }
369 catch (Exception e)
370 {
371 logger.error("unsupported encoding");
372 return orig.getBytes();
373 }
374 }
375
376 public static String formatDate(String date, String lang)
377 {
378
379 String in_pattern = "yyyyMMdd";
380 String out_pattern = "dd MMMM yyyy";
381 if (date.length() == 6)
382 {
383 in_pattern = "yyyyMM";
384 }
385
386 SimpleDateFormat formatter = new SimpleDateFormat(in_pattern, new Locale(lang));
387 try
388 {
389 Date d = formatter.parse(date);
390 formatter.applyPattern(out_pattern);
391 String new_date = formatter.format(d);
392 return new_date;
393 }
394 catch (Exception e)
395 {
396 return date;
397 }
398
399 }
400
401 public static String formatLanguage(String display_lang, String lang)
402 {
403
404 return new Locale(display_lang).getDisplayLanguage(new Locale(lang));
405 }
406
407 public static String cgiSafe(String original, String lang)
408 {
409
410 original = original.replace('&', ' ');
411 original = original.replaceAll(" ", "%20");
412 return original;
413 }
414
415 public static String formatBigNumber(String num, String lang)
416 {
417
418 String num_str = num;
419 char[] num_chars = num_str.toCharArray();
420 String zero_str = "";
421 String formatted_str = "";
422
423 for (int i = num_chars.length - 4; i >= 0; i--)
424 {
425 zero_str += '0';
426 }
427
428 String sig_str = "";
429 for (int i = 0; i < 3 && i < num_chars.length; i++)
430 {
431 sig_str = sig_str + num_chars[i];
432 if (i == 1 && i + 1 < num_chars.length)
433 {
434 sig_str = sig_str + ".";
435 }
436 }
437
438 int sig_int = Math.round(Float.parseFloat(sig_str));
439 String new_sig_str = sig_int + "";
440 if (sig_str.length() > 2)
441 {
442 new_sig_str = sig_int + "0";
443 }
444
445 char[] final_chars = (new_sig_str + zero_str).toCharArray();
446 int count = 1;
447 for (int i = final_chars.length - 1; i >= 0; i--)
448 {
449 formatted_str = final_chars[i] + formatted_str;
450 if (count == 3 && i != 0)
451 {
452 formatted_str = "," + formatted_str;
453 count = 1;
454 }
455 else
456 {
457 count++;
458 }
459 }
460 return formatted_str;
461 }
462
463 public static String hashToSectionId(String hashString)
464 {
465 if (hashString == null || hashString.length() == 0)
466 {
467 return "";
468 }
469
470 int firstDotIndex = hashString.indexOf(".");
471 if (firstDotIndex == -1)
472 {
473 return "";
474 }
475
476 String sectionString = hashString.substring(firstDotIndex + 1);
477
478 return sectionString;
479 }
480
481 public static String hashToDepthClass(String hashString)
482 {
483 if (hashString == null || hashString.length() == 0)
484 {
485 return "";
486 }
487
488 String sectionString = hashToSectionId(hashString);
489
490 int count = sectionString.split("\\.").length;
491
492 if (sectionString.equals(""))
493 {
494 return "sectionHeaderDepthTitle";
495 }
496 else
497 {
498 return "sectionHeaderDepth" + count;
499 }
500 }
501
502 public static String escapeNewLines(String str)
503 {
504 if (str == null || str.length() < 1)
505 {
506 return null;
507 }
508 return str.replace("\n", "\\\n");
509 }
510
511 public static String escapeQuotes(String str)
512 {
513 if (str == null || str.length() < 1)
514 {
515 return null;
516 }
517 return str.replace("\"", "\\\"");
518 }
519
520 public static String escapeNewLinesAndQuotes(String str)
521 {
522 if (str == null || str.length() < 1)
523 {
524 return null;
525 }
526 return escapeNewLines(escapeQuotes(str));
527 }
528
529 public static String getGlobalProperty(String name)
530 {
531 return GlobalProperties.getProperty(name);
532 }
533
534 public static void clearMetadataStorage()
535 {
536 _foundTableValues.clear();
537 }
538
539 public static boolean checkMetadataNotDuplicate(String name, String value)
540 {
541 if (_foundTableValues.containsKey(name))
542 {
543 for (String mapValue : _foundTableValues.get(name))
544 {
545 if (mapValue.equals(value))
546 {
547 return false;
548 }
549 }
550 _foundTableValues.get(name).add(value);
551 return true;
552 }
553
554 ArrayList<String> newList = new ArrayList<String>();
555 newList.add(value);
556
557 _foundTableValues.put(name, newList);
558
559 return true;
560 }
561
562 public static String reCAPTCHAimage(String publicKey, String privateKey)
563 {
564 ReCaptcha c = ReCaptchaFactory.newReCaptcha(publicKey, privateKey, false);
565 return c.createRecaptchaHtml(null, null);
566 }
567
568 public static String getInterfaceStringsAsJavascript(String interface_name, String lang, String prefix)
569 {
570 String prependToPrefix = "gs.text";
571 return XSLTUtil.getInterfaceStringsAsJavascript(interface_name, lang, prefix, prependToPrefix);
572 }
573
574 // generates javascript: 2 arrays are declared and populated with strings that declare variables and assign their values
575 // to be strings loaded from the interface_name.properties file for the language.
576 public static String getInterfaceStringsAsJavascript(String interface_name, String lang, String prefix, String prependToPrefix)
577 {
578 // 1. Generating Javascript of the form:
579 // if(!gs.text) { gs.text = new Array(); }
580 // if(!gs.text.dse) { gs.text.dse = new Array(); }
581 StringBuffer outputStr = new StringBuffer();
582 outputStr.append("if(!gs.text) { ");
583 outputStr.append(prependToPrefix + " = new Array(); ");
584 outputStr.append("}\n");
585 outputStr.append("if(!gs.text." + prefix + ") { ");
586 outputStr.append(prependToPrefix + "." + prefix + " = new Array(); ");
587 outputStr.append("}\n");
588
589 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
590 Enumeration keys = dict.getKeys();
591 if (keys == null)
592 { // try default interface
593 //logger.debug("****** Interface name: " + interface_name + " does not have any keys. Trying interface_default.");
594 dict = new Dictionary("interface_default", lang);
595 keys = dict.getKeys();
596 }
597
598 // Get all properties in the language-specific dictionary with the given key prefix
599 // Create Javascript strings of the form:
600 // prependToPrefix.key= "value";\n
601 while (keys.hasMoreElements())
602 {
603 String key = (String) keys.nextElement();
604 if (key.startsWith(prefix))
605 {
606 String value = getInterfaceText(interface_name, lang, key);
607
608 outputStr.append(prependToPrefix);
609 outputStr.append(".");
610 outputStr.append(key);
611 outputStr.append("=\"");
612 outputStr.append(value);
613 outputStr.append("\";\n");
614 }
615 }
616
617 return outputStr.toString();
618 }
619
620 public static String xmlNodeToString(Node node)
621 {
622 return GSXML.xmlNodeToString(node);
623 }
624
625 // Test from cmdline with:
626 // 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
627 public static void main(String args[])
628 {
629 System.out.println("\n@@@@@\n" + XSLTUtil.getInterfaceStringsAsJavascript("default", "en", "dse", "gs.text") + "@@@@@\n");
630 }
631}
Note: See TracBrowser for help on using the repository browser.