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

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

stripWhitespace and tidyWhitespace are now part of the formatting commands

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