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

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

Removing two print statements

  • Property svn:keywords set to Author Date Id Revision
File size: 14.7 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.util.ArrayList;
22import java.util.Date;
23import java.util.Enumeration;
24import java.util.HashMap;
25import java.util.Locale;
26import java.util.MissingResourceException;
27import java.io.File;
28import java.text.SimpleDateFormat;
29
30import net.tanesha.recaptcha.ReCaptcha;
31import net.tanesha.recaptcha.ReCaptchaFactory;
32
33import org.apache.log4j.*;
34import org.w3c.dom.Node;
35
36import org.apache.commons.lang3.StringUtils;
37import org.greenstone.util.GlobalProperties;
38
39/**
40 * a class to contain various static methods that are used by the xslt
41 * stylesheets
42 */
43public class XSLTUtil
44{
45 protected static HashMap<String, ArrayList<String>> _foundTableValues = new HashMap<String, ArrayList<String>>();
46 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.util.XSLTUtil.class.getName());
47
48 /* some tests */
49 public static boolean equals(String s1, String s2)
50 {
51 return s1.equals(s2);
52 }
53
54 public static boolean notEquals(String s1, String s2)
55 {
56 return !s1.equals(s2);
57 }
58
59 public static boolean exists(String s1, String s2)
60 {
61 return !s1.equals("");
62 }
63
64 public static boolean contains(String s1, String s2)
65 {
66 return (s1.indexOf(s2) != -1);
67 }
68
69 public static boolean startsWith(String s1, String s2)
70 {
71 return s1.startsWith(s2);
72 }
73
74 public static boolean endsWith(String s1, String s2)
75 {
76 return s1.endsWith(s2);
77 }
78
79 public static boolean lessThan(String s1, String s2)
80 {
81 return (s1.compareTo(s2) < 0);
82 }
83
84 public static boolean lessThanOrEquals(String s1, String s2)
85 {
86 return (s1.compareTo(s2) <= 0);
87 }
88
89 public static boolean greaterThan(String s1, String s2)
90 {
91 return (s1.compareTo(s2) > 0);
92 }
93
94 public static boolean greaterThanOrEquals(String s1, String s2)
95 {
96 return (s1.compareTo(s2) >= 0);
97 }
98
99 public static boolean oidIsMatchOrParent(String first, String second)
100 {
101 if (first.equals(second))
102 {
103 return true;
104 }
105
106 String[] firstParts = first.split(".");
107 String[] secondParts = second.split(".");
108
109 if (firstParts.length >= secondParts.length)
110 {
111 return false;
112 }
113
114 for (int i = 0; i < firstParts.length; i++)
115 {
116 if (!firstParts[i].equals(secondParts[i]))
117 {
118 return false;
119 }
120 }
121
122 return true;
123 }
124
125 /* some preprocessing functions */
126 public static String toLower(String orig)
127 {
128 return orig.toLowerCase();
129 }
130
131 public static String toUpper(String orig)
132 {
133 return orig.toUpperCase();
134 }
135
136 public static byte[] toUTF8(String orig)
137 {
138 try
139 {
140 byte[] utf8 = orig.getBytes("UTF-8");
141 return utf8;
142 }
143 catch (Exception e)
144 {
145 logger.error("unsupported encoding");
146 return orig.getBytes();
147 }
148 }
149
150 public static String replace(String orig, String match, String replacement)
151 {
152 return orig.replace(match, replacement);
153 }
154
155 public static String getNumberedItem(String list, int number)
156 {
157 String[] items = StringUtils.split(list, ",", -1);
158 if (items.length > number)
159 {
160 return items[number];
161 }
162 return ""; // index out of bounds
163 }
164
165 /**
166 * Generates links to equivalent documents for a document with a default
167 * document icon/type. Links are generated from the parameters: a list of
168 * document icons which are each in turn embedded in the matching starting
169 * link tag in the list of docStartLinks (these starting links link to the
170 * equivalent documents in another format). Each link's start tag is closed
171 * with the corresponding closing tag in the docEndLinks list. Parameter
172 * token is the list separator. Parameter divider is the string that should
173 * separate each final link generated from the next. Returns a string that
174 * represents a sequence of links to equivalent documents, where the anchor
175 * is a document icon.
176 */
177 public static String getEquivDocLinks(String token, String docIconsString, String docStartLinksString, String docEndLinksString, String divider)
178 {
179 String[] docIcons = StringUtils.split(docIconsString, token, -1);
180 String[] startLinks = StringUtils.split(docStartLinksString, token, -1);
181 String[] endLinks = StringUtils.split(docEndLinksString, token, -1);
182
183 StringBuffer buffer = new StringBuffer();
184 for (int i = 0; i < docIcons.length; i++)
185 {
186 if (i > 0)
187 {
188 buffer.append(divider);
189 }
190 buffer.append(startLinks[i] + docIcons[i] + endLinks[i]);
191 }
192
193 return buffer.toString();
194 }
195
196 public static String tidyWhitespace(String original)
197 {
198
199 if (original == null || original.equals(""))
200 {
201 return original;
202 }
203 String new_s = original.replaceAll("\\s+", " ");
204 return new_s;
205 }
206
207 public static String getInterfaceText(String interface_name, String lang, String key)
208 {
209 return getInterfaceText(interface_name, lang, key, null);
210 }
211
212 public static String getInterfaceText(String interface_name, String lang, String key, String args_str)
213 {
214 key = key.replaceAll("__INTERFACE_NAME__", interface_name);
215
216 String[] args = null;
217 if (args_str != null && !args_str.equals(""))
218 {
219 args = StringUtils.split(args_str, ";");
220 }
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 result = result.replaceAll("__INTERFACE_NAME__", interface_name);
232 return result;
233 }
234 }
235
236 if (result == null && !interface_name.equals("default"))
237 { // not found, try the default interface
238 dict = new Dictionary("interface_default", lang);
239 result = dict.get(key, args);
240 }
241
242 if (result == null)
243 { // not found
244 return "_" + key + "_";
245 }
246 result = result.replaceAll("__INTERFACE_NAME__", interface_name);
247 return result;
248 }
249
250 public static String getInterfaceTextWithDOM(String interface_name, String lang, String key, Node arg_node)
251 {
252 String[] args = new String[1];
253
254 String node_str = XMLConverter.getString(arg_node);
255 args[0] = node_str;
256 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
257 String result = dict.get(key, args);
258 if (result == null)
259 { // not found
260 //if not found, search a separate subdirectory named by the interface name
261 String sep_interface_dir = interface_name + File.separatorChar + lang + File.separatorChar + "interface";
262 dict = new Dictionary(sep_interface_dir, lang);
263 result = dict.get(key, args);
264 if (result != null)
265 {
266 return result;
267 }
268 }
269
270 if (result == null && !interface_name.equals("default"))
271 { // not found, try the default interface
272 dict = new Dictionary("interface_default", lang);
273 result = dict.get(key, args);
274 }
275
276 if (result == null)
277 { // not found
278 return "_" + key + "_";
279 }
280
281 return result;
282 }
283
284 public static String getInterfaceTextWithDOM(String interface_name, String lang, String key, Node arg1_node, Node arg2_node)
285 {
286 String[] args = new String[2];
287
288 String node_str = XMLConverter.getString(arg1_node);
289 args[0] = node_str;
290 node_str = XMLConverter.getString(arg2_node);
291 args[1] = node_str;
292 Dictionary dict = new Dictionary("interface_" + interface_name, lang);
293 String result = dict.get(key, args);
294 if (result == null)
295 { // not found
296 //if not found, search a separate subdirectory named by the interface name
297 String sep_interface_dir = interface_name + File.separatorChar + lang + File.separatorChar + "interface";
298 dict = new Dictionary(sep_interface_dir, lang);
299 result = dict.get(key, args);
300 if (result != null)
301 {
302 return result;
303 }
304 }
305
306 if (result == null && !interface_name.equals("default"))
307 { // not found, try the default interface
308 dict = new Dictionary("interface_default", lang);
309 result = dict.get(key, args);
310 }
311
312 if (result == null)
313 { // not found
314 return "_" + key + "_";
315 }
316
317 return result;
318 }
319
320 public static boolean isImage(String mimetype)
321 {
322 if (mimetype.startsWith("image/"))
323 {
324 return true;
325 }
326 return false;
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)
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
574 // Test from cmdline with:
575 // 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
576 public static void main(String args[])
577 {
578 System.out.println("\n@@@@@\n" + XSLTUtil.getInterfaceStringsAsJavascript("default", "en", "dse", "gs.text") + "@@@@@\n");
579 }
580}
Note: See TracBrowser for help on using the repository browser.