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

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

Added a function to help find parents of a given oid

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