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

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

Tidying the imports of this file

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