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

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

trying to implement getCollectionText with no arguments for the dictionary string

  • Property svn:keywords set to Author Date Id Revision
File size: 17.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.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 public static String getCollectionText(String collection, String site_name, String lang, String key) {
286 return getCollectionTextWithDOMMulti(collection, site_name, lang, key);
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 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1);
291 }
292 public static String getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2) {
293 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2);
294 }
295 public static String getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2, Node n3) {
296 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2, n3);
297 }
298 public static String getCollectionTextWithDOM(String collection, String site_name, String lang, String key, Node n1, Node n2, Node n3, Node n4) {
299 return getCollectionTextWithDOMMulti(collection, site_name, lang, key, n1, n2, n3, n4);
300 }
301 public static String getCollectionTextWithDOMMulti(String collection, String site_name, String lang, String key, Node ... nodes) {
302
303 int num_nodes = nodes.length;
304 String [] args = null;
305 if (num_nodes != 0) {
306 args = new String[num_nodes];
307
308 for (int i=0; i<num_nodes; i++) {
309
310 String node_str = XMLConverter.getString(nodes[i]);
311 args[i] = node_str;
312 }
313 }
314 CollectionClassLoader class_loader = new CollectionClassLoader(XSLTUtil.class.getClassLoader(), GSFile.siteHome(GlobalProperties.getGSDL3Home(), site_name), collection);
315 Dictionary dict = new Dictionary(collection, lang, class_loader);
316 String result = dict.get(key, args);
317 if (result != null) {
318 return result;
319 }
320 return "text:"+collection+":"+key;
321
322 }
323
324
325 public static boolean isImage(String mimetype)
326 {
327 if (mimetype.startsWith("image/"))
328 {
329 return true;
330 }
331 return false;
332 }
333
334 // formatting /preprocessing functions
335 // some require a language, so we'll have a language param for all
336 public static String toLower(String orig, String lang)
337 {
338 return orig.toLowerCase();
339 }
340
341 public static String toUpper(String orig, String lang)
342 {
343 return orig.toUpperCase();
344 }
345
346 public static String tidyWhitespace(String original, String lang)
347 {
348
349 if (original == null || original.equals(""))
350 {
351 return original;
352 }
353 String new_s = original.replaceAll("\\s+", " ");
354 return new_s;
355 }
356
357 public static String stripWhitespace(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 byte[] toUTF8(String orig, String lang)
369 {
370 try
371 {
372 byte[] utf8 = orig.getBytes("UTF-8");
373 return utf8;
374 }
375 catch (Exception e)
376 {
377 logger.error("unsupported encoding");
378 return orig.getBytes();
379 }
380 }
381
382 public static String formatDate(String date, String lang)
383 {
384
385 String in_pattern = "yyyyMMdd";
386 String out_pattern = "dd MMMM yyyy";
387 if (date.length() == 6)
388 {
389 in_pattern = "yyyyMM";
390 }
391
392 SimpleDateFormat formatter = new SimpleDateFormat(in_pattern, new Locale(lang));
393 try
394 {
395 Date d = formatter.parse(date);
396 formatter.applyPattern(out_pattern);
397 String new_date = formatter.format(d);
398 return new_date;
399 }
400 catch (Exception e)
401 {
402 return date;
403 }
404
405 }
406
407 public static String formatLanguage(String display_lang, String lang)
408 {
409
410 return new Locale(display_lang).getDisplayLanguage(new Locale(lang));
411 }
412
413 public static String cgiSafe(String original, String lang)
414 {
415
416 original = original.replace('&', ' ');
417 original = original.replaceAll(" ", "%20");
418 return original;
419 }
420
421 public static String formatBigNumber(String num, String lang)
422 {
423
424 String num_str = num;
425 char[] num_chars = num_str.toCharArray();
426 String zero_str = "";
427 String formatted_str = "";
428
429 for (int i = num_chars.length - 4; i >= 0; i--)
430 {
431 zero_str += '0';
432 }
433
434 String sig_str = "";
435 for (int i = 0; i < 3 && i < num_chars.length; i++)
436 {
437 sig_str = sig_str + num_chars[i];
438 if (i == 1 && i + 1 < num_chars.length)
439 {
440 sig_str = sig_str + ".";
441 }
442 }
443
444 int sig_int = Math.round(Float.parseFloat(sig_str));
445 String new_sig_str = sig_int + "";
446 if (sig_str.length() > 2)
447 {
448 new_sig_str = sig_int + "0";
449 }
450
451 char[] final_chars = (new_sig_str + zero_str).toCharArray();
452 int count = 1;
453 for (int i = final_chars.length - 1; i >= 0; i--)
454 {
455 formatted_str = final_chars[i] + formatted_str;
456 if (count == 3 && i != 0)
457 {
458 formatted_str = "," + formatted_str;
459 count = 1;
460 }
461 else
462 {
463 count++;
464 }
465 }
466 return formatted_str;
467 }
468
469 public static String hashToSectionId(String hashString)
470 {
471 if (hashString == null || hashString.length() == 0)
472 {
473 return "";
474 }
475
476 int firstDotIndex = hashString.indexOf(".");
477 if (firstDotIndex == -1)
478 {
479 return "";
480 }
481
482 String sectionString = hashString.substring(firstDotIndex + 1);
483
484 return sectionString;
485 }
486
487 public static String hashToDepthClass(String hashString)
488 {
489 if (hashString == null || hashString.length() == 0)
490 {
491 return "";
492 }
493
494 String sectionString = hashToSectionId(hashString);
495
496 int count = sectionString.split("\\.").length;
497
498 if (sectionString.equals(""))
499 {
500 return "sectionHeaderDepthTitle";
501 }
502 else
503 {
504 return "sectionHeaderDepth" + count;
505 }
506 }
507
508 public static String escapeNewLines(String str)
509 {
510 if (str == null || str.length() < 1)
511 {
512 return null;
513 }
514 return str.replace("\n", "\\\n");
515 }
516
517 public static String escapeQuotes(String str)
518 {
519 if (str == null || str.length() < 1)
520 {
521 return null;
522 }
523 return str.replace("\"", "\\\"");
524 }
525
526 public static String escapeNewLinesAndQuotes(String str)
527 {
528 if (str == null || str.length() < 1)
529 {
530 return null;
531 }
532 return escapeNewLines(escapeQuotes(str));
533 }
534
535 public static String getGlobalProperty(String name)
536 {
537 return GlobalProperties.getProperty(name);
538 }
539
540 public static void clearMetadataStorage()
541 {
542 _foundTableValues.clear();
543 }
544
545 public static boolean checkMetadataNotDuplicate(String name, String value)
546 {
547 if (_foundTableValues.containsKey(name))
548 {
549 for (String mapValue : _foundTableValues.get(name))
550 {
551 if (mapValue.equals(value))
552 {
553 return false;
554 }
555 }
556 _foundTableValues.get(name).add(value);
557 return true;
558 }
559
560 ArrayList<String> newList = new ArrayList<String>();
561 newList.add(value);
562
563 _foundTableValues.put(name, newList);
564
565 return true;
566 }
567
568 public static String reCAPTCHAimage(String publicKey, String privateKey)
569 {
570 ReCaptcha c = ReCaptchaFactory.newReCaptcha(publicKey, privateKey, false);
571 return c.createRecaptchaHtml(null, null);
572 }
573
574 public static String getInterfaceStringsAsJavascript(String interface_name, String lang, String prefix)
575 {
576 String prependToPrefix = "gs.text";
577 return XSLTUtil.getInterfaceStringsAsJavascript(interface_name, lang, prefix, prependToPrefix);
578 }
579
580 // generates javascript: 2 arrays are declared and populated with strings that declare variables and assign their values
581 // to be strings loaded from the interface_name.properties file for the language.
582 public static String getInterfaceStringsAsJavascript(String interface_name, String lang, String prefix, String prependToPrefix)
583 {
584 // 1. Generating Javascript of the form:
585 // if(!gs.text) { gs.text = new Array(); }
586 // if(!gs.text.dse) { gs.text.dse = new Array(); }
587 StringBuffer outputStr = new StringBuffer();
588 outputStr.append("if(!gs.text) { ");
589 outputStr.append(prependToPrefix + " = new Array(); ");
590 outputStr.append("}\n");
591 outputStr.append("if(!gs.text." + prefix + ") { ");
592 outputStr.append(prependToPrefix + "." + prefix + " = new Array(); ");
593 outputStr.append("}\n");
594
595 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
596 Enumeration keys = dict.getKeys();
597 if (keys == null)
598 { // try default interface
599 //logger.debug("****** Interface name: " + interface_name + " does not have any keys. Trying interface_default.");
600 dict = new Dictionary("interface_default", lang);
601 keys = dict.getKeys();
602 }
603
604 // Get all properties in the language-specific dictionary with the given key prefix
605 // Create Javascript strings of the form:
606 // prependToPrefix.key= "value";\n
607 while (keys.hasMoreElements())
608 {
609 String key = (String) keys.nextElement();
610 if (key.startsWith(prefix))
611 {
612 String value = getInterfaceText(interface_name, lang, key);
613
614 outputStr.append(prependToPrefix);
615 outputStr.append(".");
616 outputStr.append(key);
617 outputStr.append("=\"");
618 outputStr.append(value);
619 outputStr.append("\";\n");
620 }
621 }
622
623 return outputStr.toString();
624 }
625
626 public static String xmlNodeToString(Node node)
627 {
628 return GSXML.xmlNodeToString(node);
629 }
630
631 // Test from cmdline with:
632 // 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
633 public static void main(String args[])
634 {
635 System.out.println("\n@@@@@\n" + XSLTUtil.getInterfaceStringsAsJavascript("default", "en", "dse", "gs.text") + "@@@@@\n");
636 }
637}
Note: See TracBrowser for help on using the repository browser.