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

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

due to the way we call formatting functions from xslt, I have made them all have the same arguments, string and lang.

  • Property svn:keywords set to Author Date Id Revision
File size: 14.9 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;
36
37/**
38 * a class to contain various static methods that are used by the xslt
39 * stylesheets
40 */
41public class XSLTUtil
42{
43 protected static HashMap<String, ArrayList<String>> _foundTableValues = new HashMap<String, ArrayList<String>>();
44 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.util.XSLTUtil.class.getName());
45
46 /* some tests */
47 public static boolean equals(String s1, String s2)
48 {
49 return s1.equals(s2);
50 }
51
52 public static boolean notEquals(String s1, String s2)
53 {
54 return !s1.equals(s2);
55 }
56
57 public static boolean exists(String s1, String s2)
58 {
59 return !s1.equals("");
60 }
61
62 public static boolean contains(String s1, String s2)
63 {
64 return (s1.indexOf(s2) != -1);
65 }
66
67 public static boolean startsWith(String s1, String s2)
68 {
69 return s1.startsWith(s2);
70 }
71
72 public static boolean endsWith(String s1, String s2)
73 {
74 return s1.endsWith(s2);
75 }
76
77 public static boolean lessThan(String s1, String s2)
78 {
79 return (s1.compareTo(s2) < 0);
80 }
81
82 public static boolean lessThanOrEquals(String s1, String s2)
83 {
84 return (s1.compareTo(s2) <= 0);
85 }
86
87 public static boolean greaterThan(String s1, String s2)
88 {
89 return (s1.compareTo(s2) > 0);
90 }
91
92 public static boolean greaterThanOrEquals(String s1, String s2)
93 {
94 return (s1.compareTo(s2) >= 0);
95 }
96
97 public static boolean oidIsMatchOrParent(String first, String second)
98 {
99 if (first.equals(second))
100 {
101 return true;
102 }
103
104 String[] firstParts = first.split(".");
105 String[] secondParts = second.split(".");
106
107 if (firstParts.length >= secondParts.length)
108 {
109 return false;
110 }
111
112 for (int i = 0; i < firstParts.length; i++)
113 {
114 if (!firstParts[i].equals(secondParts[i]))
115 {
116 return false;
117 }
118 }
119
120 return true;
121 }
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 tidyWhitespace(String original)
171 {
172
173 if (original == null || original.equals(""))
174 {
175 return original;
176 }
177 String new_s = original.replaceAll("\\s+", " ");
178 return new_s;
179 }
180
181 public static String getInterfaceText(String interface_name, String lang, String key)
182 {
183 return getInterfaceText(interface_name, lang, key, null);
184 }
185
186 public static String getInterfaceText(String interface_name, String lang, String key, String args_str)
187 {
188 key = key.replaceAll("__INTERFACE_NAME__", interface_name);
189
190 String[] args = null;
191 if (args_str != null && !args_str.equals(""))
192 {
193 args = StringUtils.split(args_str, ";");
194 }
195 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
196 String result = dict.get(key, args);
197 if (result == null)
198 { // not found
199 //if not found, search a separate subdirectory named by the interface name
200 String sep_interface_dir = interface_name + File.separatorChar + lang + File.separatorChar + "interface";
201 dict = new Dictionary(sep_interface_dir, lang);
202 result = dict.get(key, args);
203 if (result != null)
204 {
205 result = result.replaceAll("__INTERFACE_NAME__", interface_name);
206 return result;
207 }
208 }
209
210 if (result == null && !interface_name.equals("default"))
211 { // not found, try the default interface
212 dict = new Dictionary("interface_default", lang);
213 result = dict.get(key, args);
214 }
215
216 if (result == null)
217 { // not found
218 return "_" + key + "_";
219 }
220 result = result.replaceAll("__INTERFACE_NAME__", interface_name);
221 return result;
222 }
223
224 public static String getInterfaceTextWithDOM(String interface_name, String lang, String key, Node arg_node)
225 {
226 String[] args = new String[1];
227
228 String node_str = XMLConverter.getString(arg_node);
229 args[0] = node_str;
230 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
231 String result = dict.get(key, args);
232 if (result == null)
233 { // not found
234 //if not found, search a separate subdirectory named by the interface name
235 String sep_interface_dir = interface_name + File.separatorChar + lang + File.separatorChar + "interface";
236 dict = new Dictionary(sep_interface_dir, lang);
237 result = dict.get(key, args);
238 if (result != null)
239 {
240 return result;
241 }
242 }
243
244 if (result == null && !interface_name.equals("default"))
245 { // not found, try the default interface
246 dict = new Dictionary("interface_default", lang);
247 result = dict.get(key, args);
248 }
249
250 if (result == null)
251 { // not found
252 return "_" + key + "_";
253 }
254
255 return result;
256 }
257
258 public static String getInterfaceTextWithDOM(String interface_name, String lang, String key, Node arg1_node, Node arg2_node)
259 {
260 String[] args = new String[2];
261
262 String node_str = XMLConverter.getString(arg1_node);
263 args[0] = node_str;
264 node_str = XMLConverter.getString(arg2_node);
265 args[1] = node_str;
266 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
267 String result = dict.get(key, args);
268 if (result == null)
269 { // not found
270 //if not found, search a separate subdirectory named by the interface name
271 String sep_interface_dir = interface_name + File.separatorChar + lang + File.separatorChar + "interface";
272 dict = new Dictionary(sep_interface_dir, lang);
273 result = dict.get(key, args);
274 if (result != null)
275 {
276 return result;
277 }
278 }
279
280 if (result == null && !interface_name.equals("default"))
281 { // not found, try the default interface
282 dict = new Dictionary("interface_default", lang);
283 result = dict.get(key, args);
284 }
285
286 if (result == null)
287 { // not found
288 return "_" + key + "_";
289 }
290
291 return result;
292 }
293
294 public static boolean isImage(String mimetype)
295 {
296 if (mimetype.startsWith("image/"))
297 {
298 return true;
299 }
300 return false;
301 }
302
303 // formatting /preprocessing functions
304 // some require a language, so we'll have a language param for all
305 public static String toLower(String orig, String lang)
306 {
307 return orig.toLowerCase();
308 }
309
310 public static String toUpper(String orig, String lang)
311 {
312 return orig.toUpperCase();
313 }
314
315 public static byte[] toUTF8(String orig, String lang)
316 {
317 try
318 {
319 byte[] utf8 = orig.getBytes("UTF-8");
320 return utf8;
321 }
322 catch (Exception e)
323 {
324 logger.error("unsupported encoding");
325 return orig.getBytes();
326 }
327 }
328
329 public static String formatDate(String date, String lang)
330 {
331
332 String in_pattern = "yyyyMMdd";
333 String out_pattern = "dd MMMM yyyy";
334 if (date.length() == 6)
335 {
336 in_pattern = "yyyyMM";
337 }
338
339 SimpleDateFormat formatter = new SimpleDateFormat(in_pattern, new Locale(lang));
340 try
341 {
342 Date d = formatter.parse(date);
343 formatter.applyPattern(out_pattern);
344 String new_date = formatter.format(d);
345 return new_date;
346 }
347 catch (Exception e)
348 {
349 return date;
350 }
351
352 }
353
354 public static String formatLanguage(String display_lang, String lang)
355 {
356
357 return new Locale(display_lang).getDisplayLanguage(new Locale(lang));
358 }
359
360 public static String cgiSafe(String original, String lang)
361 {
362
363 original = original.replace('&', ' ');
364 original = original.replaceAll(" ", "%20");
365 return original;
366 }
367
368 public static String formatBigNumber(String num, String lang)
369 {
370
371 String num_str = num;
372 char[] num_chars = num_str.toCharArray();
373 String zero_str = "";
374 String formatted_str = "";
375
376 for (int i = num_chars.length - 4; i >= 0; i--)
377 {
378 zero_str += '0';
379 }
380
381 String sig_str = "";
382 for (int i = 0; i < 3 && i < num_chars.length; i++)
383 {
384 sig_str = sig_str + num_chars[i];
385 if (i == 1 && i + 1 < num_chars.length)
386 {
387 sig_str = sig_str + ".";
388 }
389 }
390
391 int sig_int = Math.round(Float.parseFloat(sig_str));
392 String new_sig_str = sig_int + "";
393 if (sig_str.length() > 2)
394 {
395 new_sig_str = sig_int + "0";
396 }
397
398 char[] final_chars = (new_sig_str + zero_str).toCharArray();
399 int count = 1;
400 for (int i = final_chars.length - 1; i >= 0; i--)
401 {
402 formatted_str = final_chars[i] + formatted_str;
403 if (count == 3 && i != 0)
404 {
405 formatted_str = "," + formatted_str;
406 count = 1;
407 }
408 else
409 {
410 count++;
411 }
412 }
413 return formatted_str;
414 }
415
416 public static String hashToSectionId(String hashString)
417 {
418 if (hashString == null || hashString.length() == 0)
419 {
420 return "";
421 }
422
423 int firstDotIndex = hashString.indexOf(".");
424 if (firstDotIndex == -1)
425 {
426 return "";
427 }
428
429 String sectionString = hashString.substring(firstDotIndex + 1);
430
431 return sectionString;
432 }
433
434 public static String hashToDepthClass(String hashString)
435 {
436 if (hashString == null || hashString.length() == 0)
437 {
438 return "";
439 }
440
441 String sectionString = hashToSectionId(hashString);
442
443 int count = sectionString.split("\\.").length;
444
445 if (sectionString.equals(""))
446 {
447 return "sectionHeaderDepthTitle";
448 }
449 else
450 {
451 return "sectionHeaderDepth" + count;
452 }
453 }
454
455 public static String escapeNewLines(String str)
456 {
457 if (str == null || str.length() < 1)
458 {
459 return null;
460 }
461 return str.replace("\n", "\\\n");
462 }
463
464 public static String escapeQuotes(String str)
465 {
466 if (str == null || str.length() < 1)
467 {
468 return null;
469 }
470 return str.replace("\"", "\\\"");
471 }
472
473 public static String escapeNewLinesAndQuotes(String str)
474 {
475 if (str == null || str.length() < 1)
476 {
477 return null;
478 }
479 return escapeNewLines(escapeQuotes(str));
480 }
481
482 public static String getGlobalProperty(String name)
483 {
484 return GlobalProperties.getProperty(name);
485 }
486
487 public static void clearMetadataStorage()
488 {
489 _foundTableValues.clear();
490 }
491
492 public static boolean checkMetadataNotDuplicate(String name, String value)
493 {
494 if (_foundTableValues.containsKey(name))
495 {
496 for (String mapValue : _foundTableValues.get(name))
497 {
498 if (mapValue.equals(value))
499 {
500 return false;
501 }
502 }
503 _foundTableValues.get(name).add(value);
504 return true;
505 }
506
507 ArrayList<String> newList = new ArrayList<String>();
508 newList.add(value);
509
510 _foundTableValues.put(name, newList);
511
512 return true;
513 }
514
515 public static String reCAPTCHAimage(String publicKey, String privateKey)
516 {
517 ReCaptcha c = ReCaptchaFactory.newReCaptcha(publicKey, privateKey, false);
518 return c.createRecaptchaHtml(null, null);
519 }
520
521 public static String getInterfaceStringsAsJavascript(String interface_name, String lang, String prefix)
522 {
523 String prependToPrefix = "gs.text";
524 return XSLTUtil.getInterfaceStringsAsJavascript(interface_name, lang, prefix, prependToPrefix);
525 }
526
527 // generates javascript: 2 arrays are declared and populated with strings that declare variables and assign their values
528 // to be strings loaded from the interface_name.properties file for the language.
529 public static String getInterfaceStringsAsJavascript(String interface_name, String lang, String prefix, String prependToPrefix)
530 {
531 // 1. Generating Javascript of the form:
532 // if(!gs.text) { gs.text = new Array(); }
533 // if(!gs.text.dse) { gs.text.dse = new Array(); }
534 StringBuffer outputStr = new StringBuffer();
535 outputStr.append("if(!gs.text) { ");
536 outputStr.append(prependToPrefix + " = new Array(); ");
537 outputStr.append("}\n");
538 outputStr.append("if(!gs.text." + prefix + ") { ");
539 outputStr.append(prependToPrefix + "." + prefix + " = new Array(); ");
540 outputStr.append("}\n");
541
542 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
543 Enumeration keys = dict.getKeys();
544 if (keys == null)
545 { // try default interface
546 //logger.debug("****** Interface name: " + interface_name + " does not have any keys. Trying interface_default.");
547 dict = new Dictionary("interface_default", lang);
548 keys = dict.getKeys();
549 }
550
551 // Get all properties in the language-specific dictionary with the given key prefix
552 // Create Javascript strings of the form:
553 // prependToPrefix.key= "value";\n
554 while (keys.hasMoreElements())
555 {
556 String key = (String) keys.nextElement();
557 if (key.startsWith(prefix))
558 {
559 String value = getInterfaceText(interface_name, lang, key);
560
561 outputStr.append(prependToPrefix);
562 outputStr.append(".");
563 outputStr.append(key);
564 outputStr.append("=\"");
565 outputStr.append(value);
566 outputStr.append("\";\n");
567 }
568 }
569
570 return outputStr.toString();
571 }
572
573 public static String xmlNodeToString(Node node)
574 {
575 return GSXML.xmlNodeToString(node);
576 }
577
578 // Test from cmdline with:
579 // 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
580 public static void main(String args[])
581 {
582 System.out.println("\n@@@@@\n" + XSLTUtil.getInterfaceStringsAsJavascript("default", "en", "dse", "gs.text") + "@@@@@\n");
583 }
584}
Note: See TracBrowser for help on using the repository browser.