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

Last change on this file since 26253 was 26253, checked in by sjm84, 12 years ago

Reformatting this file

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