KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > pentaho > core > util > XmlHelper


1 /*
2  * Copyright 2006 Pentaho Corporation. All rights reserved.
3  * This software was developed by Pentaho Corporation and is provided under the terms
4  * of the Mozilla Public License, Version 1.1, or any later version. You may not use
5  * this file except in compliance with the license. If you need a copy of the license,
6  * please go to http://www.mozilla.org/MPL/MPL-1.1.txt. The Original Code is the Pentaho
7  * BI Platform. The Initial Developer is Pentaho Corporation.
8  *
9  * Software distributed under the Mozilla Public License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
11  * the license for the specific language governing your rights and limitations.
12  *
13  * @created Jun 17, 2005
14  * @author James Dixon
15  * @author Marc Batchelor
16  */

17
18 package org.pentaho.core.util;
19
20 import java.io.File JavaDoc;
21 import java.io.FileInputStream JavaDoc;
22 import java.io.FileWriter JavaDoc;
23 import java.io.InputStream JavaDoc;
24 import java.io.InputStreamReader JavaDoc;
25 import java.io.StringReader JavaDoc;
26 import java.io.StringWriter JavaDoc;
27 import java.math.BigDecimal JavaDoc;
28 import java.net.URL JavaDoc;
29 import java.net.URLClassLoader JavaDoc;
30 import java.text.ParseException JavaDoc;
31 import java.text.SimpleDateFormat JavaDoc;
32 import java.util.ArrayList JavaDoc;
33 import java.util.Date JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.Iterator JavaDoc;
36 import java.util.List JavaDoc;
37 import java.util.Locale JavaDoc;
38 import java.util.Map JavaDoc;
39 import java.util.ResourceBundle JavaDoc;
40 import java.util.Set JavaDoc;
41 import java.util.TimeZone JavaDoc;
42 import javax.xml.transform.Transformer JavaDoc;
43 import javax.xml.transform.TransformerFactory JavaDoc;
44 import javax.xml.transform.URIResolver JavaDoc;
45 import javax.xml.transform.stream.StreamResult JavaDoc;
46 import javax.xml.transform.stream.StreamSource JavaDoc;
47 import org.dom4j.Document;
48 import org.dom4j.DocumentException;
49 import org.dom4j.DocumentHelper;
50 import org.dom4j.Element;
51 import org.dom4j.Node;
52 import org.pentaho.core.session.IPentahoSession;
53 import org.pentaho.core.system.PentahoSystem;
54 import org.pentaho.messages.Messages;
55 import org.pentaho.messages.util.LocaleHelper;
56 import org.pentaho.util.PentahoChainedException;
57 import org.pentaho.util.logging.Logger;
58
59 /**
60  * @author mbatchel/jdixon
61  *
62  * TODO To change the template for this generated type comment go to Window -
63  * Preferences - Java - Code Style - Code Templates
64  */

65 public class XmlHelper {
66
67     public static Document getDocFromString(String JavaDoc str) {
68         Document document = null;
69         try {
70             document = DocumentHelper.parseText(str);
71         } catch (Exception JavaDoc e) {
72             Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0001_GET_DOC_FROM_STRING_ERROR", e.getMessage()), e); //$NON-NLS-1$
73
}
74         return document;
75     }
76
77     public static Document getDocFromFile(File JavaDoc f) {
78         Document document = null;
79         try {
80           FileInputStream JavaDoc fis = new FileInputStream JavaDoc(f);
81           try {
82             document = getDocFromStream( fis );
83           } finally {
84             fis.close();
85           }
86         } catch (Exception JavaDoc e) {
87             String JavaDoc fName = null;
88             try {
89                 fName = f.getCanonicalPath();
90             } catch (Exception JavaDoc ignored) {
91             }
92             Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0002_GET_DOC_FROM_FILE_ERROR", fName), e); //$NON-NLS-1$
93
}
94         return document;
95     }
96
97     public static Document getDocFromStream(InputStream JavaDoc inStream) throws Exception JavaDoc {
98         Document document = null;
99         InputStreamReader JavaDoc reader = new InputStreamReader JavaDoc(inStream, LocaleHelper.getSystemEncoding());
100         try {
101           StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
102           if (reader != null) {
103               char buffer[] = new char[1000];
104               int bytesRead;
105               while ((bytesRead = reader.read(buffer)) > 0) {
106                   sb.append(buffer, 0, bytesRead);
107               }
108           }
109           document = DocumentHelper.parseText(sb.toString());
110           return document;
111         } finally {
112           try {
113             inStream.close();
114           } catch (Exception JavaDoc ex) {
115             // TODO: Make better message
116
Logger.error(XmlHelper.class.getName(), ex.toString());
117           }
118         }
119     }
120
121     protected static final StringBuffer JavaDoc transform(StreamSource JavaDoc xslSrc, StreamSource JavaDoc docSrc, Map JavaDoc params, IPentahoSession session) throws Exception JavaDoc {
122
123         // Get the two paramters "class" and "source".
124
StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
125         StringWriter JavaDoc writer = new StringWriter JavaDoc();
126         if ((xslSrc == null) || (docSrc == null)) {
127             if (xslSrc == null)
128                 Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0003_NULL_XSL_SOURCE")); //$NON-NLS-1$
129
if (docSrc == null)
130                 Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0004_NULL_DOCUMENT")); //$NON-NLS-1$
131
} else {
132             URIResolver JavaDoc resolver = new SolutionURIResolver(session);
133             TransformerFactory JavaDoc tf = TransformerFactory.newInstance();
134             tf.setURIResolver(resolver);
135             // TODO need to look into compiling the XSLs...
136
Transformer JavaDoc t = tf.newTransformer(xslSrc);
137             // Start the transformation
138
if (params != null) {
139                 Set JavaDoc keys = params.keySet();
140                 Iterator JavaDoc it = keys.iterator();
141                 String JavaDoc key, val;
142                 while (it.hasNext()) {
143                     key = (String JavaDoc) it.next();
144                     val = (String JavaDoc) params.get(key);
145                     t.setParameter(key, val);
146                 }
147             }
148             t.transform(docSrc, new StreamResult JavaDoc(writer));
149             sb = writer.getBuffer();
150         }
151         return sb;
152     }
153
154     public static final StringBuffer JavaDoc transformXml(String JavaDoc xslName, String JavaDoc path, Document document, Map JavaDoc params, IPentahoSession session) {
155
156         try {
157             // Add encoding for any xsl that may set/use it
158
if (params == null) {
159                 params = new HashMap JavaDoc();
160             }
161             params.put("output-encoding", LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
162
// params.put("output-encoding", getEncodingFromLocale(
163
// PentahoSystem.getLocale())); //$NON-NLS-1$
164
File JavaDoc localeXsl = getlocalizedXsl(path, xslName);
165             if (localeXsl == null || !localeXsl.exists()) {
166                 return null;
167             }
168             FileInputStream JavaDoc xslIS = new FileInputStream JavaDoc(localeXsl);
169             StreamSource JavaDoc xslSrc = new StreamSource JavaDoc(xslIS);
170             StringReader JavaDoc xmlReader = new StringReader JavaDoc(document.asXML());
171             StreamSource JavaDoc docSrc = new StreamSource JavaDoc(xmlReader);
172             return transform(xslSrc, docSrc, params, session);
173         } catch (Exception JavaDoc e) {
174             Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0006_TRASFORM_XML_ERROR", e.getMessage(), xslName), e); //$NON-NLS-1$
175
}
176         return null;
177     }
178
179     public static final StringBuffer JavaDoc transformXml(String JavaDoc xslName, Document document, Map JavaDoc params, IPentahoSession session) {
180
181         try {
182             // Add encoding for any xsl that may set/use it
183
if (params == null) {
184                 params = new HashMap JavaDoc();
185             }
186             params.put("output-encoding", LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
187
File JavaDoc localeXsl = getlocalizedXsl(xslName);
188             if (localeXsl == null || !localeXsl.exists()) {
189                 return null;
190             }
191             FileInputStream JavaDoc xslIS = new FileInputStream JavaDoc(localeXsl);
192             StreamSource JavaDoc xslSrc = new StreamSource JavaDoc(xslIS);
193             StringReader JavaDoc xmlReader = new StringReader JavaDoc(document.asXML());
194             StreamSource JavaDoc docSrc = new StreamSource JavaDoc(xmlReader);
195             return transform(xslSrc, docSrc, params, session);
196         } catch (Exception JavaDoc e) {
197             Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0006_TRASFORM_XML_ERROR", e.getMessage(), xslName), e); //$NON-NLS-1$
198
}
199         return null;
200     }
201
202     public static final StringBuffer JavaDoc transformXmlUrl(String JavaDoc xslName, String JavaDoc path, String JavaDoc uri, Map JavaDoc params, IPentahoSession session) {
203         try {
204             // Add encoding for any xsl that may set/use it
205
if (params == null) {
206                 params = new HashMap JavaDoc();
207             }
208             params.put("output-encoding", LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
209
File JavaDoc localeXsl = getlocalizedXsl(path, xslName);
210             FileInputStream JavaDoc xslIS = new FileInputStream JavaDoc(localeXsl);
211             StreamSource JavaDoc xslSrc = new StreamSource JavaDoc(xslIS);
212             URL JavaDoc url = new URL JavaDoc(uri);
213             InputStream JavaDoc is = url.openStream();
214             StreamSource JavaDoc docSrc = new StreamSource JavaDoc(is);
215             return transform(xslSrc, docSrc, params, session);
216         } catch (Exception JavaDoc e) {
217             Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0007_TRANSFORM_XML_URL", e.getMessage(), xslName), e); //$NON-NLS-1$
218
}
219         return null;
220     }
221
222     public static final StringBuffer JavaDoc transformXml(String JavaDoc xslName, String JavaDoc path, String JavaDoc document, Map JavaDoc params, IPentahoSession session) {
223
224         try {
225             // Add encoding for any xsl that may set/use it
226
if (params == null) {
227                 params = new HashMap JavaDoc();
228             }
229             params.put("output-encoding", LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
230
File JavaDoc localeXsl = getlocalizedXsl(path, xslName);
231             FileInputStream JavaDoc xslIS = new FileInputStream JavaDoc(localeXsl);
232             StreamSource JavaDoc xslSrc = new StreamSource JavaDoc(xslIS);
233             StringReader JavaDoc xmlReader = new StringReader JavaDoc(document);
234             StreamSource JavaDoc docSrc = new StreamSource JavaDoc(xmlReader);
235             return transform(xslSrc, docSrc, params, session);
236         } catch (Exception JavaDoc e) {
237             Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0006_TRASFORM_XML_ERROR", e.getMessage(), xslName), e); //$NON-NLS-1$
238
}
239         return null;
240     }
241
242     public static ResourceBundle JavaDoc getBundle(String JavaDoc baseName, File JavaDoc localeDir, Locale JavaDoc locale) {
243         try {
244
245             URL JavaDoc localeDirUrl = localeDir.getParentFile().toURL();
246             URLClassLoader JavaDoc loader = new URLClassLoader JavaDoc(new URL JavaDoc[] { localeDirUrl });
247
248             ResourceBundle JavaDoc bundle = ResourceBundle.getBundle(baseName, locale, loader);
249             return bundle;
250
251         } catch (Exception JavaDoc e) {
252             Logger.error("XmlHelper", Messages.getErrorString("XmlHelper.ERROR_0012_COULD_NOT_READ_PROPERTIES", localeDir.getAbsolutePath() + File.separator + baseName), e); //$NON-NLS-1$ //$NON-NLS-2$
253
}
254         return null;
255     }
256
257     public static void localizeDoc(Node document, File JavaDoc file, Locale JavaDoc locale, boolean xmlEncode) {
258
259         String JavaDoc fileName = file.getName();
260         int dotIndex = fileName.indexOf('.');
261         String JavaDoc baseName = fileName.substring(0, dotIndex);
262         ResourceBundle JavaDoc bundle = null;
263         bundle = getBundle(baseName, file, locale);
264         if (bundle == null) {
265             return;
266         }
267         localizeDoc(document, bundle, locale, file.getAbsolutePath(), xmlEncode);
268
269     }
270
271     public static String JavaDoc getXmlEncodedString(String JavaDoc rawValue) {
272         StringBuffer JavaDoc value = new StringBuffer JavaDoc();
273         for (int n = 0; n < rawValue.length(); n++) {
274             int charValue = rawValue.charAt(n);
275             if (charValue >= 0x80) {
276                 value.append("&#x"); //$NON-NLS-1$
277
value.append(Integer.toString(charValue, 0x10));
278                 value.append(";"); //$NON-NLS-1$
279
} else {
280                 value.append((char) charValue);
281             }
282         }
283         return value.toString();
284
285     }
286
287     public static void localizeDoc(Node document, ResourceBundle JavaDoc bundle, Locale JavaDoc locale, String JavaDoc bundlePath, boolean xmlEncode) {
288
289         if (bundle == null) {
290             return;
291         }
292         try {
293
294             List JavaDoc nodes = document.selectNodes("descendant::*"); //$NON-NLS-1$
295
Iterator JavaDoc nodeIterator = nodes.iterator();
296             while (nodeIterator.hasNext()) {
297                 Node node = (Node) nodeIterator.next();
298                 String JavaDoc name = node.getText();
299                 if (name.startsWith("%") && !node.getPath().endsWith("/text()")) { //$NON-NLS-1$ //$NON-NLS-2$
300
try {
301                         if (bundle != null) {
302                             String JavaDoc localeText = bundle.getString(name.substring(1));
303                             if (localeText != null) {
304                                 if (xmlEncode) {
305                                     node.setText(getXmlEncodedString(localeText));
306                                 } else {
307                                     node.setText(localeText);
308                                 }
309                             }
310                         }
311                     } catch (Exception JavaDoc e) {
312                         Logger.warn("XmlHelper", Messages.getString("XmlHelper.WARN_MISSING_RESOURCE_PROPERTY", name.substring(1), bundlePath, locale.toString())); //$NON-NLS-1$ //$NON-NLS-2$
313
}
314                 }
315             }
316
317         } catch (Exception JavaDoc e) {
318             Logger.error("XmlHelper", Messages.getErrorString("XmlHelper.ERROR_0012_COULD_NOT_READ_PROPERTIES", bundlePath), e); //$NON-NLS-1$ //$NON-NLS-2$
319
}
320
321     }
322
323     public static final File JavaDoc getlocalizedFile(String JavaDoc solutionPath, String JavaDoc fileName, String JavaDoc extension) {
324
325         Locale JavaDoc locale = LocaleHelper.getLocale();
326
327         String JavaDoc language = locale.getLanguage();
328         String JavaDoc country = locale.getCountry();
329         String JavaDoc variant = locale.getVariant();
330
331         String JavaDoc fullPath = PentahoSystem.getApplicationContext().getSolutionPath(solutionPath + File.separator + fileName + extension);
332         File JavaDoc file = new File JavaDoc(fullPath);
333
334         fileName = file.getName();
335         int dotIndex = fileName.indexOf('.');
336         String JavaDoc baseName = fileName.substring(0, dotIndex);
337
338         File JavaDoc directory = file.getParentFile();
339         File JavaDoc localeFile = null;
340         if (!variant.equals("")) { //$NON-NLS-1$
341
localeFile = new File JavaDoc(directory, baseName + "_" + language + "_" + country + "_" + variant + extension); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
342
}
343         if (localeFile == null || !localeFile.exists()) {
344             localeFile = new File JavaDoc(directory, baseName + "_" + language + "_" + country + extension); //$NON-NLS-1$//$NON-NLS-2$
345
}
346         if (!localeFile.exists()) {
347             localeFile = new File JavaDoc(directory, baseName + "_" + language + extension); //$NON-NLS-1$
348
}
349         if (!localeFile.exists()) {
350             localeFile = new File JavaDoc(directory, baseName + extension);
351         }
352         if (localeFile.exists()) {
353             return localeFile;
354         }
355         // we should not get this far...
356
Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0011_TRASFORM_XSL_DOES_NOT_EXIST", fullPath)); //$NON-NLS-1$
357
return null;
358
359     }
360
361     public static final File JavaDoc getlocalizedFile(File JavaDoc file) {
362
363         Locale JavaDoc locale = LocaleHelper.getLocale();
364
365         String JavaDoc language = locale.getLanguage();
366         String JavaDoc country = locale.getCountry();
367         String JavaDoc variant = locale.getVariant();
368
369         String JavaDoc fileName = file.getName();
370         int dotIndex = fileName.indexOf('.');
371         String JavaDoc baseName = fileName.substring(0, dotIndex);
372         String JavaDoc extension = fileName.substring(fileName.lastIndexOf('.'));
373
374         File JavaDoc directory = file.getParentFile();
375         File JavaDoc localeFile = null;
376         if (!variant.equals("")) { //$NON-NLS-1$
377
localeFile = new File JavaDoc(directory, baseName + "_" + language + "_" + country + "_" + variant + extension); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
378
}
379         if (localeFile == null || !localeFile.exists()) {
380             localeFile = new File JavaDoc(directory, baseName + "_" + language + "_" + country + extension); //$NON-NLS-1$//$NON-NLS-2$
381
}
382         if (!localeFile.exists()) {
383             localeFile = new File JavaDoc(directory, baseName + "_" + language + extension); //$NON-NLS-1$
384
}
385         if (!localeFile.exists()) {
386             localeFile = new File JavaDoc(directory, baseName + extension);
387         }
388         if (localeFile.exists()) {
389             return localeFile;
390         }
391         // we should not get this far...
392
Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0011_TRASFORM_XSL_DOES_NOT_EXIST", file.getAbsolutePath())); //$NON-NLS-1$
393
return null;
394
395     }
396
397     public static final File JavaDoc getlocalizedXsl(String JavaDoc path, String JavaDoc xslName) {
398
399         Locale JavaDoc locale = LocaleHelper.getLocale();
400
401         String JavaDoc language = locale.getLanguage();
402         String JavaDoc country = locale.getCountry();
403         String JavaDoc variant = locale.getVariant();
404
405         if (path == null) {
406             path = "system/custom/xsl"; //$NON-NLS-1$
407
}
408
409         String JavaDoc fullPath = PentahoSystem.getApplicationContext().getSolutionPath(path + File.separator + xslName).replace('\\', '/');
410         File JavaDoc file = new File JavaDoc(fullPath);
411         if (!file.exists()) {
412             fullPath = PentahoSystem.getApplicationContext().getSolutionPath("system/custom/xsl/" + xslName).replace('\\', '/'); //$NON-NLS-1$
413
file = new File JavaDoc(fullPath);
414             if (!file.exists()) {
415                 Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0011_TRASFORM_XSL_DOES_NOT_EXIST", fullPath)); //$NON-NLS-1$
416
return null;
417             }
418         }
419
420         String JavaDoc fileName = file.getName();
421         int dotIndex = fileName.indexOf('.');
422         String JavaDoc baseName = fileName.substring(0, dotIndex);
423         String JavaDoc extension = ".xsl"; //$NON-NLS-1$
424

425         File JavaDoc directory = file.getParentFile();
426         File JavaDoc localeFile = null;
427         if (!variant.equals("")) { //$NON-NLS-1$
428
localeFile = new File JavaDoc(directory, baseName + "_" + language + "_" + country + "_" + variant + extension); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
429
}
430         if (localeFile == null || !localeFile.exists()) {
431             localeFile = new File JavaDoc(directory, baseName + "_" + language + "_" + country + extension); //$NON-NLS-1$//$NON-NLS-2$
432
}
433         if (!localeFile.exists()) {
434             localeFile = new File JavaDoc(directory, baseName + "_" + language + extension); //$NON-NLS-1$
435
}
436         if (!localeFile.exists()) {
437             localeFile = new File JavaDoc(directory, baseName + extension);
438         }
439         if (localeFile.exists()) {
440             return localeFile;
441         }
442         // we should not get this far...
443
Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0011_TRASFORM_XSL_DOES_NOT_EXIST", fullPath)); //$NON-NLS-1$
444
return null;
445
446     }
447
448     public static final File JavaDoc getlocalizedXsl(String JavaDoc xslName) {
449
450         Locale JavaDoc locale = LocaleHelper.getLocale();
451
452         String JavaDoc language = locale.getLanguage();
453         String JavaDoc country = locale.getCountry();
454         String JavaDoc variant = locale.getVariant();
455
456         String JavaDoc fullPath = PentahoSystem.getApplicationContext().getSolutionPath("system/custom/xsl/" + xslName); //$NON-NLS-1$
457
File JavaDoc file = new File JavaDoc(fullPath);
458
459         String JavaDoc fileName = file.getName();
460         int dotIndex = fileName.indexOf('.');
461         String JavaDoc baseName = fileName.substring(0, dotIndex);
462         String JavaDoc extension = ".xsl"; //$NON-NLS-1$
463

464         File JavaDoc directory = file.getParentFile();
465         File JavaDoc localeFile = null;
466         if (!variant.equals("")) { //$NON-NLS-1$
467
localeFile = new File JavaDoc(directory, baseName + "_" + language + "_" + country + "_" + variant + extension); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
468
}
469         if (localeFile == null || !localeFile.exists()) {
470             localeFile = new File JavaDoc(directory, baseName + "_" + language + "_" + country + extension); //$NON-NLS-1$//$NON-NLS-2$
471
}
472         if (!localeFile.exists()) {
473             localeFile = new File JavaDoc(directory, baseName + "_" + language + extension); //$NON-NLS-1$
474
}
475         if (!localeFile.exists()) {
476             localeFile = new File JavaDoc(directory, baseName + extension);
477         }
478         if (localeFile.exists()) {
479             return localeFile;
480         }
481         // we should not get this far...
482
Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0011_TRASFORM_XSL_DOES_NOT_EXIST", fullPath)); //$NON-NLS-1$
483
return null;
484
485     }
486
487     public static Document getDomFromString(String JavaDoc str) {
488         Document document = null;
489         try {
490             document = DocumentHelper.parseText(str);
491         } catch (Exception JavaDoc e) {
492             Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0008_GET_DOM_FROM_STRING_ERROR", e.getMessage()), e); //$NON-NLS-1$
493
}
494         return document;
495     }
496
497     public static void saveDomToFile(Document doc, File JavaDoc file) {
498         String JavaDoc xml = doc.asXML();
499         try {
500             FileWriter JavaDoc fos = new FileWriter JavaDoc(file);
501             try {
502               fos.write(xml);
503             } finally {
504               try {
505                 fos.close();
506               } catch (Exception JavaDoc ex) {
507                 Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0009_SAVE_DOMoTO_FILE_ERROR", ex.getMessage()), ex); //$NON-NLS-1$
508
}
509             }
510         } catch (Exception JavaDoc e) {
511             Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0009_SAVE_DOMoTO_FILE_ERROR", e.getMessage()), e); //$NON-NLS-1$
512
}
513     }
514
515     public static void saveDomToFile(Document doc, String JavaDoc fullPath) {
516         String JavaDoc xml = doc.asXML();
517         File JavaDoc file = new File JavaDoc(fullPath);
518         try {
519             FileWriter JavaDoc fos = new FileWriter JavaDoc(file);
520             try {
521               fos.write(xml);
522             } finally {
523               try {
524                 fos.close();
525               } catch (Exception JavaDoc ex) {
526                 Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0009_SAVE_DOMoTO_FILE_ERROR", ex.getMessage()), ex); //$NON-NLS-1$
527
}
528             }
529         } catch (Exception JavaDoc e) {
530             Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0009_SAVE_DOMoTO_FILE_ERROR", e.getMessage()), e); //$NON-NLS-1$
531
}
532     }
533
534     public static Document getDomFromResource(String JavaDoc path) {
535         String JavaDoc str = getContentFromSolutionResource(path);
536         return getDomFromString(str);
537     }
538
539     public static String JavaDoc getContentFromResource(String JavaDoc fullPath) {
540
541         StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc();
542         try {
543             FileInputStream JavaDoc fin = new FileInputStream JavaDoc(fullPath);
544             InputStreamReader JavaDoc reader = new InputStreamReader JavaDoc(fin, LocaleHelper.getSystemEncoding());
545             try {
546               // InputStream in = context.getResourceAsStream( path );
547
if (reader != null) {
548                   boolean reading = true;
549                   int bytesRead;
550                   char buffer[] = new char[1000];
551                   while (reading) {
552                       bytesRead = reader.read(buffer);
553                       reading = bytesRead == buffer.length;
554                       strBuf.append(buffer, 0, bytesRead);
555                   }
556               }
557             } finally {
558               try {
559                 reader.close();
560               } catch (Exception JavaDoc ex) {
561                 Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0010_GET_CONTENT_FROM_RESOURCE_ERROR", ex.getMessage()), ex); //$NON-NLS-1$
562
}
563             }
564         } catch (Exception JavaDoc e) {
565             Logger.error(XmlHelper.class.getName(), Messages.getErrorString("XmlHelper.ERROR_0010_GET_CONTENT_FROM_RESOURCE_ERROR", e.getMessage()), e); //$NON-NLS-1$
566

567         }
568         return strBuf.toString();
569     }
570
571     public static String JavaDoc getContentFromSolutionResource(String JavaDoc path) {
572         String JavaDoc fullPath = PentahoSystem.getApplicationContext().getSolutionPath(path);
573         return getContentFromResource(fullPath);
574     }
575
576     /*
577      * The following methods converts lists/maps to/from XML. author: mbatchelor
578      */

579
580     public static String JavaDoc listToXML(List JavaDoc l) throws UnsupportedOperationException JavaDoc {
581         return listToXML(l, ""); //$NON-NLS-1$
582
}
583
584     public static String JavaDoc listToXML(List JavaDoc l, String JavaDoc indent) throws UnsupportedOperationException JavaDoc {
585         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
586         sb.append(indent).append("<list>\r"); //$NON-NLS-1$
587
String JavaDoc newIndent = indent + " "; //$NON-NLS-1$
588
Object JavaDoc obj;
589         for (int i = 0; i < l.size(); i++) {
590             obj = l.get(i);
591             sb.append(newIndent).append("<list-element>\r"); //$NON-NLS-1$
592
objToXML(obj, sb, newIndent);
593             sb.append(newIndent).append("</list-element>\r"); //$NON-NLS-1$
594
}
595         sb.append(indent).append("</list>\r"); //$NON-NLS-1$
596
return sb.toString();
597     }
598
599     public static String JavaDoc mapToXML(Map JavaDoc m) throws UnsupportedOperationException JavaDoc {
600         return mapToXML(m, ""); //$NON-NLS-1$
601
}
602
603     public static String JavaDoc mapToXML(Map JavaDoc mp, String JavaDoc indent) throws UnsupportedOperationException JavaDoc {
604         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
605         sb.append(indent).append("<map>\r"); //$NON-NLS-1$
606
String JavaDoc newIndent = indent + " "; //$NON-NLS-1$
607
Iterator JavaDoc it = mp.entrySet().iterator();
608         Map.Entry JavaDoc ent;
609         Object JavaDoc obj;
610         while (it.hasNext()) {
611             ent = (Map.Entry JavaDoc) it.next();
612             if (!(ent.getKey() instanceof String JavaDoc)) {
613                 throw new UnsupportedOperationException JavaDoc(Messages.getErrorString("XMLUTL.ERROR_0011_MAP_KEYS")); //$NON-NLS-1$
614
}
615             sb.append(newIndent).append("<map-entry>\r"); //$NON-NLS-1$
616
sb.append(newIndent).append("<key>\r"); //$NON-NLS-1$
617
sb.append(newIndent).append("<![CDATA[").append(ent.getKey().toString()).append("]]>\r"); //$NON-NLS-1$ //$NON-NLS-2$
618
sb.append(newIndent).append("</key>\r"); //$NON-NLS-1$
619
obj = ent.getValue();
620             objToXML(obj, sb, newIndent);
621             sb.append(newIndent).append("</map-entry>\r"); //$NON-NLS-1$
622
}
623         sb.append(indent).append("</map>\r"); //$NON-NLS-1$
624
return sb.toString();
625     }
626
627     private static void objToXML(Object JavaDoc obj, StringBuffer JavaDoc sb, String JavaDoc newIndent) {
628         if (obj instanceof String JavaDoc) {
629             sb.append(newIndent).append("<string-value>\r"); //$NON-NLS-1$
630
sb.append(newIndent).append("<![CDATA[").append((String JavaDoc) obj).append("]]>\r"); //$NON-NLS-1$ //$NON-NLS-2$
631
sb.append(newIndent).append("</string-value>\r"); //$NON-NLS-1$
632
} else if (obj instanceof StringBuffer JavaDoc) {
633             sb.append(newIndent).append("<stringbuffer-value>\r"); //$NON-NLS-1$
634
sb.append(newIndent).append("<![CDATA[").append(obj.toString()).append("]]>\r"); //$NON-NLS-1$ //$NON-NLS-2$
635
sb.append(newIndent).append("</stringbuffer-value>\r"); //$NON-NLS-1$
636
} else if (obj instanceof BigDecimal JavaDoc) {
637             sb.append(newIndent).append("<bigdecimal-value>").append(obj.toString()).append("</bigdecimal-value>\r"); //$NON-NLS-1$ //$NON-NLS-2$
638
} else if (obj instanceof Date JavaDoc) {
639             SimpleDateFormat JavaDoc fmt = new SimpleDateFormat JavaDoc();
640             fmt.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$
641
sb.append(newIndent).append("<date-value>"); //$NON-NLS-1$
642
sb.append(fmt.format((Date JavaDoc) obj)).append("</date-value>\r"); //$NON-NLS-1$
643
} else if (obj instanceof Long JavaDoc) {
644             sb.append(newIndent).append("<long-value>"); //$NON-NLS-1$
645
sb.append(obj.toString()).append("</long-value>\r"); //$NON-NLS-1$
646
} else if (obj instanceof Map JavaDoc) {
647             sb.append(newIndent).append("<map-value>\r"); //$NON-NLS-1$
648
sb.append(mapToXML((Map JavaDoc) obj, newIndent));
649             sb.append(newIndent).append("</map-value>\r"); //$NON-NLS-1$
650
} else if (obj instanceof List JavaDoc) {
651             sb.append(newIndent).append("<list-value>\r"); //$NON-NLS-1$
652
sb.append(listToXML((List JavaDoc) obj, newIndent));
653             sb.append(newIndent).append("</list-value>\r"); //$NON-NLS-1$
654
} else {
655             throw new UnsupportedOperationException JavaDoc(Messages.getErrorString("XMLUTL.ERROR_0012_DATA_TYPE", obj.getClass().getName())); //$NON-NLS-1$
656
}
657
658     }
659
660     public static List JavaDoc xmlToList(String JavaDoc s) throws PentahoChainedException {
661         try {
662             Document doc = DocumentHelper.parseText(s);
663             Element root = doc.getRootElement();
664             return processList(root);
665         } catch (DocumentException ex) {
666             throw new PentahoChainedException(Messages.getErrorString("XMLUTL.ERROR_0013_PARSING"), ex); //$NON-NLS-1$
667
} catch (ParseException JavaDoc pex) {
668             throw new PentahoChainedException(Messages.getErrorString("XMLUTL.ERROR_0013_PARSING"), pex); //$NON-NLS-1$
669
}
670     }
671
672     public static Map JavaDoc xmlToMap(String JavaDoc s) throws PentahoChainedException {
673         try {
674             Document doc = DocumentHelper.parseText(s);
675             Element root = doc.getRootElement();
676             return processMap(root);
677         } catch (DocumentException ex) {
678             throw new PentahoChainedException(Messages.getErrorString("XMLUTL.ERROR_0013_PARSING"), ex); //$NON-NLS-1$
679
} catch (ParseException JavaDoc pex) {
680             throw new PentahoChainedException(Messages.getErrorString("XMLUTL.ERROR_0013_PARSING"), pex); //$NON-NLS-1$
681
}
682     }
683
684     public static List JavaDoc processList(Element ele) throws ParseException JavaDoc {
685         List JavaDoc rtn = new ArrayList JavaDoc();
686         Iterator JavaDoc it = ele.elementIterator();
687         Element anElement;
688         while (it.hasNext()) {
689             anElement = (Element) it.next();
690             processListElement(anElement, rtn);
691         }
692         return rtn;
693     }
694
695     public static Map JavaDoc processMap(Element ele) throws ParseException JavaDoc {
696         Map JavaDoc rtn = new HashMap JavaDoc();
697         Iterator JavaDoc it = ele.elementIterator();
698         Element anElement;
699         while (it.hasNext()) {
700             anElement = (Element) it.next();
701             processMapElement(anElement, rtn);
702         }
703         return rtn;
704     }
705
706     public static Object JavaDoc elementToObject(Element anElement) throws ParseException JavaDoc {
707         if (anElement.getName().equals("string-value")) { //$NON-NLS-1$
708
return anElement.getTextTrim();
709         } else if (anElement.getName().equals("stringbuffer-value")) { //$NON-NLS-1$
710
return new StringBuffer JavaDoc(anElement.getTextTrim());
711         } else if (anElement.getName().equals("bigdecimal-value")) { //$NON-NLS-1$
712
return new BigDecimal JavaDoc(anElement.getTextTrim());
713         } else if (anElement.getName().equals("long-value")) { //$NON-NLS-1$
714
return new Long JavaDoc(anElement.getTextTrim());
715         } else if (anElement.getName().equals("date-value")) { //$NON-NLS-1$
716
SimpleDateFormat JavaDoc fmt = new SimpleDateFormat JavaDoc();
717             fmt.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$
718
return fmt.parse(anElement.getTextTrim());
719         } else if (anElement.getName().equals("list-value")) { //$NON-NLS-1$
720
return processList(anElement.element("list")); //$NON-NLS-1$
721
} else if (anElement.getName().equals("map-value")) { //$NON-NLS-1$
722
return processMap(anElement.element("map")); //$NON-NLS-1$
723
} else {
724             throw new ParseException JavaDoc(Messages.getErrorString("XMLUTL.ERROR_0014_UNKNOWN_TYPE", anElement.getName()), 0); //$NON-NLS-1$
725
}
726     }
727
728     public static void processListElement(Element ele, List JavaDoc rtn) throws ParseException JavaDoc {
729         Iterator JavaDoc it = ele.elementIterator();
730         Element anElement;
731         while (it.hasNext()) {
732             anElement = (Element) it.next();
733             Object JavaDoc anObj = elementToObject(anElement);
734             rtn.add(anObj);
735         }
736     }
737
738     public static void processMapElement(Element ele, Map JavaDoc rtn) throws ParseException JavaDoc {
739         Iterator JavaDoc it = ele.elementIterator();
740         Element keyElement = null;
741         Element valueElement = null;
742         Element anElement = null;
743         while (it.hasNext()) {
744             anElement = (Element) it.next();
745             if (anElement.getName().equals("key")) { //$NON-NLS-1$
746
keyElement = anElement;
747             } else {
748                 valueElement = anElement;
749             }
750         }
751         // Now, we have our key and our value. Let's figure out what kind of
752
// processing is required.
753
Object JavaDoc anObj = elementToObject(valueElement);
754         rtn.put(keyElement.getTextTrim(), anObj);
755     }
756
757     public static String JavaDoc getNodeText(String JavaDoc path, Node rootNode) {
758         return (getNodeText(path, rootNode, null));
759     }
760
761     public static long getNodeText(String JavaDoc path, Node rootNode, long defaultValue) {
762         String JavaDoc valueStr = getNodeText(path, rootNode, Long.toString(defaultValue));
763         try {
764             return Long.parseLong(valueStr);
765         } catch (Exception JavaDoc e) {
766         }
767         return defaultValue;
768     }
769
770     public static double getNodeText(String JavaDoc path, Node rootNode, double defaultValue) {
771         String JavaDoc valueStr = getNodeText(path, rootNode, null);
772         if ( valueStr == null ) {
773             return defaultValue;
774         }
775         try {
776             return Double.parseDouble(valueStr);
777         } catch (Exception JavaDoc e) {
778         }
779         return defaultValue;
780     }
781
782     public static String JavaDoc getNodeText(String JavaDoc path, Node rootNode, String JavaDoc defaultValue) {
783         if ( rootNode == null ) {
784             return( defaultValue );
785         }
786         Node node = rootNode.selectSingleNode(path);
787         if (node == null) {
788             return defaultValue;
789         }
790         return node.getText();
791     }
792
793     public static void decode(String JavaDoc[] strings ) {
794         if ( strings != null ) {
795             for ( int i = 0; i < strings.length; ++i ) {
796                 strings[i] = decode( strings[i] );
797             }
798         }
799     }
800         
801     public static String JavaDoc decode(String JavaDoc string) {
802         // TODO replace this is a more robust encoder
803
if (string == null) {
804             return null;
805         }
806         string = string.replaceAll("&lt;", "<"); //$NON-NLS-1$ //$NON-NLS-2$
807
string = string.replaceAll("&gt;", ">"); //$NON-NLS-1$ //$NON-NLS-2$
808
string = string.replaceAll("&amp;", "&"); //$NON-NLS-1$ //$NON-NLS-2$
809
return string;
810     }
811
812     public static void encode(String JavaDoc[] strings ) {
813         if ( strings != null ) {
814             for ( int i = 0; i < strings.length; ++i ) {
815                 strings[i] = encode( strings[i] );
816             }
817         }
818     }
819
820     public static String JavaDoc encode(String JavaDoc string) {
821         // TODO replace this is a more robust encoder
822
if (string == null) {
823             return null;
824         }
825         string = string.replaceAll("<", "&lt;"); //$NON-NLS-1$//$NON-NLS-2$
826
string = string.replaceAll(">", "&gt;"); //$NON-NLS-1$//$NON-NLS-2$
827
string = string.replaceAll("&", "&amp;"); //$NON-NLS-1$//$NON-NLS-2$
828
return string;
829     }
830
831 }
832
Popular Tags