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

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

Make sure the document editor functionality is off when we don't have collection building

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