KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > applications > editwizard > Utils


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10 package org.mmbase.applications.editwizard;
11
12 import org.w3c.dom.*;
13 import java.io.*;
14 import java.net.*;
15 import java.util.*;
16 import javax.xml.transform.*;
17 import javax.xml.transform.stream.*;
18 import javax.xml.transform.dom.*;
19 import javax.xml.parsers.DocumentBuilder JavaDoc;
20 import org.xml.sax.*;
21 import org.apache.xpath.XPathAPI;
22 import org.apache.xpath.objects.XObject;
23
24 import org.mmbase.bridge.Cloud;
25 import org.mmbase.util.logging.*;
26 import org.mmbase.util.ResourceLoader;
27
28 import org.mmbase.cache.xslt.*;
29 import org.mmbase.util.xml.URIResolver;
30 import org.mmbase.util.XMLErrorHandler;
31 import org.mmbase.util.XMLEntityResolver;
32
33 /**
34  * This class contains static utility methods used by the editwizard.
35  * Most methods handle xml functions for you and are just to support ease and lazyness.
36  *
37  *
38  * @javadoc
39  * @author Kars Veling
40  * @author Pierre van Rooden
41  * @author Michiel Meeuwissen
42  * @since MMBase-1.6
43  * @version $Id: Utils.java,v 1.41 2005/08/24 12:42:42 michiel Exp $
44  */

45
46 public class Utils {
47
48     private static final Logger log = Logging.getLoggerInstance(Utils.class);
49     /**
50      * This method returns a new instance of a DocumentBuilder.
51      *
52      * @return a DocumentBuilder.
53      */

54     public static DocumentBuilder JavaDoc getDocumentBuilder(boolean validate) {
55         return org.mmbase.util.XMLBasicReader.getDocumentBuilder(validate,
56             new XMLErrorHandler(validate, XMLErrorHandler.ERROR),
57             new XMLEntityResolver(validate, Utils.class));
58     }
59
60     /**
61      * This method returns an empty XMLDocument.
62      *
63      * @return a new empty Document. Returns null if something went wrong.
64      */

65     public static Document emptyDocument() {
66         try {
67             DocumentBuilder JavaDoc dBuilder = getDocumentBuilder(false);
68             return dBuilder.newDocument();
69         } catch (Throwable JavaDoc t) {
70             log.error(Logging.stackTrace(t));
71         }
72         return null;
73     }
74
75
76     /**
77      * This method can load a xml file and returns the resulting document. If something went wrong, null is returned.
78      *
79      * @param file the file to be loaded.
80      * @return The loaded xml Document
81      * @throws WizardException if the document is invalid
82      */

83     public static Document loadXMLFile(URL file) throws WizardException {
84         try {
85             try {
86                 DocumentBuilder JavaDoc b = getDocumentBuilder(true);
87                 return b.parse(file.openStream(), file.toExternalForm());
88             } catch (SAXParseException ex) {
89                 // try without validating, perhaps no doc-type was specified
90
DocumentBuilder JavaDoc b = getDocumentBuilder(false);
91                 Document d = b.parse(file.openStream(), file.toExternalForm());
92                 if (d.getDoctype() == null) {
93                     log.warn("No DocumentType specified in " + file);
94                     return d;
95                 } else {
96                     throw new WizardException("Error on line " + ex.getLineNumber() + " (column " + ex.getColumnNumber() + ") of schema xml file " + ex.getSystemId() + ": " + ex.getMessage());
97                 }
98             }
99         } catch (SAXException e) {
100             throw new WizardException("Could not load schema xml file '"+file + "' (SAX)\n" + Logging.stackTrace(e));
101         } catch (IOException ioe) {
102             throw new WizardException("Could not load schema xml file '"+file + "' (IO)\n" + Logging.stackTrace(ioe));
103         }
104     }
105
106     /**
107      * With this method you can parse a xml string and get the resulting Document.
108      *
109      * @param xml The xml string to be parsed. Note that you should supply xml for a valid document (one root node, etc)
110      * @return The newly created xml Document
111      * @throws WizardException if something went wrong
112      */

113     public static Document parseXML(String JavaDoc xml) throws WizardException {
114         try {
115             DocumentBuilder JavaDoc b = getDocumentBuilder(false);
116             StringReader reader = new StringReader(xml);
117             return b.parse(new InputSource(reader));
118         } catch (Exception JavaDoc e) {
119             throw new WizardException("Could not parse schema xml file. xml:"+xml + "\n" + Logging.stackTrace(e));
120         }
121     }
122
123     /**
124      * Serialize a node to the given writer.
125      *
126      * @param node The node to serialize
127      * @param writer The writer where the stream should be written to.
128      */

129     public static void printXML(Node node, Writer writer) {
130
131         try {
132             if (node == null) {
133                 writer.write("NULL");
134                 return;
135             }
136             Transformer serializer = FactoryCache.getCache().getDefaultFactory().newTransformer();
137             // shouldn't this tranformer be cached?
138
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
139             serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
140             serializer.transform(new DOMSource(node), new StreamResult(writer));
141         } catch (Exception JavaDoc e) {
142             log.error(Logging.stackTrace(e));
143             throw new RuntimeException JavaDoc(Logging.stackTrace(e));
144         }
145     }
146
147     /**
148      * Serialize a node to a string, and return the result.
149      *
150      * @param node The node to serialize
151      */

152     public static String JavaDoc getSerializedXML(Node node) {
153         StringWriter str = new StringWriter();
154         printXML(node, str);
155         return str.toString();
156     }
157
158     /**
159      * Serialize a node and returns the resulting String.
160      *
161      * @param node The node to serialize
162      * @return The resulting string.
163      */

164     public static String JavaDoc getXML(Node node) {
165         StringWriter writer = new StringWriter();
166         printXML(node, writer);
167         return writer.toString();
168     }
169
170     /***
171      * Serialize a nodelist and returns the resulting String (for debugging).
172      * @since MMBase-1.7.1
173      */

174     public static String JavaDoc getXML(NodeList nodeList) {
175         StringWriter writer = new StringWriter();
176         for (int i = 0; i < nodeList.getLength(); i++) {
177             writer.write("" + i + ":");
178             printXML(nodeList.item(i), writer);
179         }
180         return writer.toString();
181     }
182
183     /**
184      * Sets an attribute of a specific node. If the attribute does not exist, a new attribute is created.
185      * If the attribute already exists, the value is overwritten with the new one.
186      *
187      * @param node The node of which the
188      */

189     public static void setAttribute(Node node, String JavaDoc name, String JavaDoc value) {
190         Attr a = node.getOwnerDocument().createAttribute(name);
191         a.setNodeValue(value);
192         node.getAttributes().setNamedItem(a);
193     }
194
195     /**
196      * Gets an attribute of an node.
197      *
198      * @param node the node to get the attribute from
199      * @param name the attributename requested
200      * @return The value of the attribute. Returns "" if none exists.
201      */

202     public static String JavaDoc getAttribute(Node node, String JavaDoc name) {
203         return getAttribute(node, name, "");
204     }
205
206     /**
207      * Gets an attribute of an node.
208      *
209      * @param node the node to get the attribute from
210      * @param name the attributename requested
211      * @param defaultvalue the defaultvalue what should be returned if attribute was not found.
212      * @return The value of the attribute. Returns the defaultvalue if none exists.
213      */

214     public static String JavaDoc getAttribute(Node node, String JavaDoc name, String JavaDoc defaultvalue) {
215         try {
216             Node n = node.getAttributes().getNamedItem(name);
217             if (n == null) return defaultvalue;
218             return n.getNodeValue();
219         } catch (Exception JavaDoc e) {
220             log.debug(Logging.stackTrace(e));
221             return defaultvalue;
222         }
223     }
224
225     /**
226      * Returns the text value of the given node
227      *
228      * @param node the node where you want the text from.
229      * @return The value of the containing textnode. If no textnode present, "" is returned.
230      */

231     public static String JavaDoc getText(Node node) {
232         return getText(node, "");
233     }
234
235     /**
236      * Returns the text value of the given node. But can do more.
237      *
238      * @param node the node where you want the text from.
239      * @param defaultvalue of no text is found, this defaultvalue will be returned
240      * @param params params to be used. eg.: $username will be replaced by the values in the hashtable, if a 'username' key is in the hashtable.
241      * @return The value of the containing textnode. If no textnode present, defaultvalue is returned.
242      */

243     public static String JavaDoc getText(Node node, String JavaDoc defaultvalue, Map params) {
244         return fillInParams(getText(node, defaultvalue), params);
245     }
246
247     /**
248      * Returns the text value of the given node.
249      *
250      * @param node the node where you want the text from.
251      * @param defaultvalue if no text is found, this defaultvalue will be returned
252      * @return The value of the containing textnode. If no textnode present, defaultvalue is returned.
253      */

254     public static String JavaDoc getText(Node node, String JavaDoc defaultvalue) {
255         try {
256             // return the value of the node if that node is itself a text-holding node
257
if ((node.getNodeType()==Node.TEXT_NODE) ||
258                 (node.getNodeType()==Node.CDATA_SECTION_NODE) ||
259                 (node.getNodeType()==Node.ATTRIBUTE_NODE)) {
260                 return node.getNodeValue();
261             }
262             // otherwise return the text contained by the node's children
263
Node childnode=node.getFirstChild();
264             StringBuffer JavaDoc value = new StringBuffer JavaDoc();
265             while (childnode != null) {
266                 if ((childnode.getNodeType()==Node.TEXT_NODE) || (childnode.getNodeType()==Node.CDATA_SECTION_NODE)) {
267                     value.append(childnode.getNodeValue());
268                 }
269                 childnode = childnode.getNextSibling();
270             }
271             if (value.length() > 0) return value.toString();
272         } catch (Exception JavaDoc e) {
273             log.warn(e.getMessage());
274         }
275         return defaultvalue;
276     }
277
278     /**
279      * Selects a single node using the given xpath and uses the given node a a starting context and returns the textnode found. If no text is found, the default value is given.
280      *
281      * @param node the contextnode to start the xpath from.
282      * @param xpath the xpath which should be fired.
283      * @param defaultvalue this value will be returned when no node is found using the xpath.
284      * @return The text string.
285      */

286     public static String JavaDoc selectSingleNodeText(Node node, String JavaDoc xpath, String JavaDoc defaultvalue) {
287         return selectSingleNodeText(node, xpath, defaultvalue, null);
288     }
289
290     /**
291      * Selects a single node using the given xpath and uses the given node a a starting context and returns the textnode found.
292      * If no text is found, the default value is given.
293      * If a cloud argument is passed, it is used to select the most approprite text (using xml:lang attributes) depending on
294      * the cloud's properties.
295      *
296      * @param node the contextnode to start the xpath from.
297      * @param xpath the xpath which should be fired.
298      * @param defaultvalue this value will be returned when no node is found using the xpath.
299      * @param cloud the cloud whose locale is to be used for selecting language-specific texts
300      * @return The text string.
301      */

302     public static String JavaDoc selectSingleNodeText(Node node, String JavaDoc xpath, String JavaDoc defaultvalue, Cloud cloud) {
303         try {
304             XObject x = null;
305             // select based on cloud locale setting
306
if (cloud != null) {
307                 x = XPathAPI.eval(node, xpath + "[lang('"+cloud.getLocale().getLanguage()+"')]");
308             }
309             String JavaDoc xs = (x == null ? "" : x.str());
310             // mm: according to javadoc of xalan 2.5.2, x cannot be null, so I don't know if it was possible in older xalans, so just to be on the safe side
311

312             // if not found or n.a., just grab the first you can find
313
if (xs.equals("")) {
314                 x = XPathAPI.eval(node, xpath);
315             }
316             xs = (x == null ? "" : x.str());
317             if (xs.equals("")) {
318                 xs = defaultvalue;
319             }
320             return xs;
321
322         } catch (Exception JavaDoc e) {
323             log.error(Logging.stackTrace(e) + ", evaluating xpath:" + xpath);
324         }
325         return defaultvalue;
326     }
327
328     /**
329      * This method stores text in a node. If needed, a new text node is created.
330      *
331      * @param node the parentnode on which a textnode should be created or overwritten.
332      * @param text The text what should be placed in the textnode.
333      * @param params optional params which should be used in a replace action.
334      */

335     public static void storeText(Node node, String JavaDoc text, Map params) {
336         storeText(node, fillInParams(text, params));
337     }
338
339     /**
340      * Same as above, but without the params.
341      * This method first removes all text/CDATA nodes. It then adds the parsed text as either a text ndoe or a CDATA node.
342      */

343     public static void storeText(Node node, String JavaDoc text) {
344         Node t = node.getFirstChild();
345         while (t!=null) {
346             if ((t.getNodeType()==Node.TEXT_NODE) || (t.getNodeType()==Node.CDATA_SECTION_NODE)) {
347                 node.removeChild(t);
348             }
349             t=t.getNextSibling();
350         }
351         if (text.indexOf("<")!=-1 || text.indexOf("&")!=-1 ) {
352             t=node.getOwnerDocument().createCDATASection(text);
353         } else {
354             t=node.getOwnerDocument().createTextNode(text);
355         }
356         node.appendChild(t);
357     }
358
359     /**
360      * This method clones, imports and places all nodes in the list.
361      *
362      * @return Collection with the new nodes.
363      */

364     public static Collection appendNodeList(NodeList list, Node dest) {
365
366         Collection result = new ArrayList();
367         if (list == null) return result;
368         Document ownerdoc = dest.getOwnerDocument();
369         for (int i=0; i<list.getLength(); i++) {
370             Node n = list.item(i).cloneNode(true);
371             result.add(dest.appendChild(ownerdoc.importNode(n, true)));
372         }
373         return result;
374     }
375
376
377     /**
378      * This method creates a new node, places text and attaches it to the parent.
379      *
380      * @param parentnode Place where new node should be appended
381      * @param nodename the name of the new node
382      * @param nodevalue the new nodevalue
383      * @return the newly created node
384      */

385     public static Node createAndAppendNode(Node parentnode, String JavaDoc nodename, String JavaDoc nodevalue) {
386         Node n = parentnode.getOwnerDocument().createElement(nodename);
387         storeText(n, nodevalue);
388         parentnode.appendChild(n);
389         return n;
390     }
391
392     /**
393      * Following routines are strange but handy for the editwizard
394      */

395
396     /**
397      * This method tags all nodes in the nodelist. Id-counter starts counting with 1.
398      *
399      * @param list the nodelist
400      * @param name the name of the tags
401      * @param pre the prefix what should be used in the tag-values
402      */

403
404
405     public static int tagNodeList(NodeList list, String JavaDoc name, String JavaDoc pre) {
406         return tagNodeList(list, name, pre, 1);
407     }
408
409     /**
410      * Same as above, but now you can supply a startnumber.
411      */

412     public static int tagNodeList(NodeList list, String JavaDoc name, String JavaDoc pre, int start) {
413         for (int i=0; i<list.getLength(); i++) {
414             Node n = list.item(i);
415             Utils.setAttribute(n, name, pre + "_" + (start++) );
416         }
417         return start;
418     }
419
420
421     /**
422      * Copies all attributes from one node to the other.
423      * @param source One node
424      * @param dest The other node
425      */

426     public static void copyAllAttributes(Node source, Node dest) {
427         copyAllAttributes(source,dest,null);
428     }
429
430     /**
431      * Same as above, but now you can supply a Vector with names which should NOT be copied.
432      */

433
434     public static void copyAllAttributes(Node source, Node dest, List except) {
435         NamedNodeMap attrs = source.getAttributes();
436         for (int i=0; i<attrs.getLength(); i++) {
437             String JavaDoc attrname = attrs.item(i).getNodeName();
438             if (except==null || (!except.contains(attrname))) setAttribute(dest, attrname, attrs.item(i).getNodeValue());
439         }
440     }
441
442
443
444     /**
445      * Below are handy XSL(T) Utils
446      */

447
448     /**
449      * This method can set the stylesheetparams for a transformer.
450      *
451      * @param transformer The transformer.
452      * @param params The params to be placed. Standard name/value pairs.
453      */

454     protected static void setStylesheetParams(Transformer transformer, Map params){
455         if (params==null) return;
456
457         Iterator i = params.entrySet().iterator();
458         while (i.hasNext()){
459             Map.Entry entry = (Map.Entry) i.next();
460             log.debug("setting param " + entry.getKey() + " to " + entry.getValue());
461             transformer.setParameter((String JavaDoc) entry.getKey(), entry.getValue());
462         }
463     }
464
465
466
467     /**
468      * This method does a standard XSL(T) transform on a node as a base context node and sends it to the given Result result.
469      *
470      * @param node the base context node to run the xsl(t) against.
471      * @param xslFile the xsl file
472      * @param result The place where to put the result of the transformation
473      * @param params Optional params.
474      */

475     public static void transformNode(Node node, URL xslFile, URIResolver uri, Result result, Map params) throws TransformerException {
476         TemplateCache cache= TemplateCache.getCache();
477         Source xsl;
478         try {
479             xsl = new StreamSource(xslFile.openStream());
480             xsl.setSystemId(ResourceLoader.toInternalForm(xslFile));
481         } catch (IOException io) {
482             throw new TransformerException(io);
483         }
484         Templates cachedXslt = cache.getTemplates(xsl, uri);
485         if (cachedXslt == null) {
486             cachedXslt = FactoryCache.getCache().getFactory(uri).newTemplates(xsl);
487             if (cachedXslt == null) throw new RuntimeException JavaDoc("Could not create template for " + xslFile + " and " + uri);
488             cache.put(xsl, cachedXslt, uri);
489         } else {
490             if (log.isDebugEnabled()) log.debug("Used xslt from cache with " + xsl.getSystemId());
491         }
492         Transformer transformer = cachedXslt.newTransformer();
493         // Set any stylesheet parameters.
494
if (params != null) {
495             setStylesheetParams(transformer, params);
496         }
497         if (log.isDebugEnabled()) log.trace("transforming: \n" + stringFormatted(node));
498         transformer.transform(new DOMSource(node), result);
499     }
500
501
502     /**
503      * For debugging purposes. Return the constructed node as a String.
504      */

505
506     public static String JavaDoc stringFormatted(Node node) {
507         try {
508             if (log.isDebugEnabled()) {
509                 log.debug("node " +node);
510                 log.debug("doc " + node.getOwnerDocument());
511             }
512             Source domSource = new DOMSource(node);
513             StringWriter result = new StringWriter();
514             StreamResult streamResult = new StreamResult(result);
515             TransformerFactory tf = TransformerFactory.newInstance();
516             Transformer serializer = tf.newTransformer();
517             serializer.setOutputProperty(OutputKeys.INDENT,"yes");
518             // Indenting not very nice int all xslt-engines, but well, its better then depending
519
// on a real xslt or lots of code.
520
serializer.transform(domSource, streamResult);
521             return result.toString();
522         } catch (Exception JavaDoc e) {
523             log.error(e + Logging.stackTrace(e));
524             return e.toString();
525         }
526     }
527
528
529
530     /**
531      * same as above, but now the result is returned in a new Node and some less params.
532      *
533      * @param node the base context node.
534      * @param xslFile the xslFile.
535      * @return the documentelement of the resulting xml (of the transformation)
536      */

537
538     public static Node transformNode(Node node, URL xslFile, URIResolver uri) throws TransformerException {
539         DOMResult res = new DOMResult();
540         transformNode(node, xslFile, uri, res, null);
541         return res.getNode();
542     }
543
544     /**
545      * same as above, but now you can supply a params hashtable.
546      */

547     public static Node transformNode(Node node, URL xslFile, URIResolver uri, Map params) throws TransformerException {
548         DOMResult res = new DOMResult();
549         transformNode(node, xslFile, uri, res, params);
550         return res.getNode();
551     }
552
553
554     /**
555      * same as above, but now the result is written to the writer.
556      */

557     public static void transformNode(Node node, URL xslFile, URIResolver uri, Writer out) throws TransformerException {
558         transformNode(node, xslFile, uri, out, null);
559     }
560     /**
561      * same as above, but now the result is written to the writer and you can use params.
562      */

563     public static void transformNode(Node node, URL xslFile, URIResolver uri, Writer out, Map params) throws TransformerException {
564         if (log.isDebugEnabled()) log.trace("transforming: " + node.toString() + " " + params);
565         // UNICODE works like this...
566
StringWriter res = new StringWriter();
567         transformNode(node, xslFile, uri, new javax.xml.transform.stream.StreamResult JavaDoc(res), params);
568         if (log.isDebugEnabled()) log.trace("transformation result " + res.toString());
569         try {
570             out.write(res.toString());
571         } catch (java.io.IOException JavaDoc e) {
572             log.error(e.toString());
573         }
574         //new StreamResult(out), null);
575
}
576
577     public static Node transformNode(Node node, String JavaDoc xslFile, URIResolver uri, Writer out, Map params) throws TransformerException {
578         DOMResult res = new DOMResult();
579         transformNode(node, uri.resolveToURL(xslFile, null), uri, res, params);
580         return res.getNode();
581     }
582
583
584     /**
585      * transforms an attribute. A attributeTemplate is used to place values. with { and } people can place simple xpaths to calculate
586      * values.
587      * @param context the contextnode
588      * @param attributeTemplate the template to evaluate.
589      * @return a string with the result.
590      */

591     public static String JavaDoc transformAttribute(Node context, String JavaDoc attributeTemplate) {
592         return transformAttribute(context,attributeTemplate,false,null);
593     }
594
595     /**
596      * same as above, but now you can supply if the given attributeTemplate is already a xpath or not. (Default should be false).
597      */

598     public static String JavaDoc transformAttribute(Node context, String JavaDoc attributeTemplate, boolean plainTextIsPath) {
599         return transformAttribute(context,attributeTemplate,plainTextIsPath,null);
600     }
601
602     /**
603        Executes an attribute template.
604        example node:
605        <person state='bad'><name>Johnny</name></person>
606        example template:
607        "hi there {person/name}, you're looking {person/@state}"
608
609        @param context the Node on which any xpaths are fired.
610        @param attributeTemplate the String containting an attribute template.
611        @param plainTextIsXpath true means that if the template doesn't contain
612        any curly braces, the template is assumed to be a valid xpath (instead
613        of plain data). Else the template is assumed to be a valid attribute template.
614     */

615     public static String JavaDoc transformAttribute(Node context, String JavaDoc attributeTemplate, boolean plainTextIsXpath, Map params) {
616         if (attributeTemplate == null) return null;
617         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
618         String JavaDoc template = fillInParams(attributeTemplate, params);
619         if (plainTextIsXpath && template.indexOf("{") == -1) {
620             template = "{" + template + "}";
621         }
622         java.util.StringTokenizer JavaDoc templateParts = new java.util.StringTokenizer JavaDoc(template,"{}",true);
623         while (templateParts.hasMoreElements()){
624             String JavaDoc part = templateParts.nextToken();
625             if (part.equals("{") && templateParts.hasMoreElements()){
626                 part = templateParts.nextToken();
627                 part = selectSingleNodeText(context, part,"");
628                 result.append(part);
629             } else if (part.equals("}")){
630                 // Nothing, go to the next part.
631
} else{
632                 result.append(part);
633             }
634         }
635         return result.toString();
636     }
637
638     /**
639      * This method selects a single node using the given contextnode and xpath.
640      * @param contextnode
641      * @param xpath
642      * @return The found node.
643      */

644     public static Node selectSingleNode(Node contextnode, String JavaDoc xpath) {
645         if (contextnode==null) throw new RuntimeException JavaDoc("Cannot execute xpath '" + xpath + "' on dom.Node that is null");
646         try {
647             return XPathAPI.selectSingleNode(contextnode, xpath);
648         } catch (Exception JavaDoc e) {
649             log.error(Logging.stackTrace(e));
650             throw new RuntimeException JavaDoc(Logging.stackTrace(e));
651         }
652     }
653
654     /**
655      * This method selects a multiple nodes using the given contextnode and xpath.
656      * @param contextnode
657      * @param xpath
658      * @return The found nodes in a NodeList.
659      */

660     public static NodeList selectNodeList(Node contextnode, String JavaDoc xpath) {
661         if (contextnode==null) throw new RuntimeException JavaDoc("Cannot execute xpath '" + xpath + "' on dom.Node that is null");
662         try {
663             return XPathAPI.selectNodeList(contextnode, xpath);
664         } catch (Exception JavaDoc e) {
665             log.error(Logging.stackTrace(e));
666             throw new RuntimeException JavaDoc(Logging.stackTrace(e));
667         }
668     }
669
670
671     /**
672      * Below some handy string utils
673      */

674
675     /**
676      * This method fills in params in a string. It uses the params hashtable to do a string replace.
677      * if the name/value: username --> kars is in the hashtable, all $username occurences will be replaced with kars.
678      * Note: #multipleReplace method is used for replacements.
679      *
680      * @param text the source text to be used
681      * @param params the table with params (name/value pairs)
682      * @return The resulting string
683      */

684     public static String JavaDoc fillInParams(String JavaDoc text, Map params) {
685         if (params==null) return text;
686         Iterator i = params.entrySet().iterator();
687         while (i.hasNext()) {
688             Map.Entry entry = (Map.Entry) i.next();
689             // accept both $xxx and {$xxx}
690
text = multipleReplace(text, "{$" + entry.getKey() + "}", (String JavaDoc) entry.getValue());
691             text = multipleReplace(text, "$" + entry.getKey(), (String JavaDoc) entry.getValue());
692         }
693         return text;
694     }
695
696     /**
697      * replaces single or multiple occurences of a string in a given source string.
698      *
699      * Note: if the searchfor-string contains the replacewith-string, no replacement is made. It would result in an inifinite loop!
700      *
701      * @param text the source text (the haystack)
702      * @param searchfor the needle. the this we're looking for
703      * @param replacewith the string which should be placed.
704      */

705     public static String JavaDoc multipleReplace(String JavaDoc text, String JavaDoc searchfor, String JavaDoc replacewith) {
706         if (text==null || searchfor==null || replacewith==null) return null;
707         if (searchfor.indexOf(replacewith)>-1) return text; // cannot replace, would create an infinite loop!
708
int pos=-1;
709         int len=searchfor.length();
710         while ((pos=text.indexOf(searchfor))>-1) {
711             text = text.substring(0,pos) + replacewith + text.substring(pos+len);
712         }
713         return text;
714     }
715
716
717     /**
718      * (Not used) method to post (http-post) xml to a url.
719      *
720      * Since it is 'not used' I made i private for the moment.
721      *
722      * @param xml The main node which should be posted.
723      * @param url The destination url
724      * @return The resulting string sent from the destination after sending.
725      */

726     private static String JavaDoc postXml(Node xml, String JavaDoc url) throws Exception JavaDoc {
727         String JavaDoc inputString = getXML(xml);
728
729         URL downeyjrURL = new URL(url);
730         HttpURLConnection c = (HttpURLConnection)(downeyjrURL.openConnection());
731         c.setDoOutput(true);
732         PrintWriter out = new PrintWriter(c.getOutputStream());
733         // Here's whether the parameter is set.
734
// TODO: replace in 1.4 with:
735
// out.println("xml=" + URLEncoder.encode(inputString,"UTF-8"));
736
out.println("xml=" + URLEncoder.encode(inputString));
737         out.close();
738
739         BufferedReader in2 = new BufferedReader(new InputStreamReader(c.getInputStream()));
740
741         String JavaDoc outputstr = "";
742         String JavaDoc inputLine;
743         while((inputLine = in2.readLine()) != null)
744             outputstr += inputLine;
745         in2.close();
746         return outputstr;
747     }
748 }
749
Popular Tags