1 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 ; 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 45 46 public class Utils { 47 48 private static final Logger log = Logging.getLoggerInstance(Utils.class); 49 54 public static DocumentBuilder 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 65 public static Document emptyDocument() { 66 try { 67 DocumentBuilder dBuilder = getDocumentBuilder(false); 68 return dBuilder.newDocument(); 69 } catch (Throwable t) { 70 log.error(Logging.stackTrace(t)); 71 } 72 return null; 73 } 74 75 76 83 public static Document loadXMLFile(URL file) throws WizardException { 84 try { 85 try { 86 DocumentBuilder b = getDocumentBuilder(true); 87 return b.parse(file.openStream(), file.toExternalForm()); 88 } catch (SAXParseException ex) { 89 DocumentBuilder 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 113 public static Document parseXML(String xml) throws WizardException { 114 try { 115 DocumentBuilder b = getDocumentBuilder(false); 116 StringReader reader = new StringReader(xml); 117 return b.parse(new InputSource(reader)); 118 } catch (Exception e) { 119 throw new WizardException("Could not parse schema xml file. xml:"+xml + "\n" + Logging.stackTrace(e)); 120 } 121 } 122 123 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 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 e) { 142 log.error(Logging.stackTrace(e)); 143 throw new RuntimeException (Logging.stackTrace(e)); 144 } 145 } 146 147 152 public static String getSerializedXML(Node node) { 153 StringWriter str = new StringWriter(); 154 printXML(node, str); 155 return str.toString(); 156 } 157 158 164 public static String getXML(Node node) { 165 StringWriter writer = new StringWriter(); 166 printXML(node, writer); 167 return writer.toString(); 168 } 169 170 174 public static String 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 189 public static void setAttribute(Node node, String name, String value) { 190 Attr a = node.getOwnerDocument().createAttribute(name); 191 a.setNodeValue(value); 192 node.getAttributes().setNamedItem(a); 193 } 194 195 202 public static String getAttribute(Node node, String name) { 203 return getAttribute(node, name, ""); 204 } 205 206 214 public static String getAttribute(Node node, String name, String defaultvalue) { 215 try { 216 Node n = node.getAttributes().getNamedItem(name); 217 if (n == null) return defaultvalue; 218 return n.getNodeValue(); 219 } catch (Exception e) { 220 log.debug(Logging.stackTrace(e)); 221 return defaultvalue; 222 } 223 } 224 225 231 public static String getText(Node node) { 232 return getText(node, ""); 233 } 234 235 243 public static String getText(Node node, String defaultvalue, Map params) { 244 return fillInParams(getText(node, defaultvalue), params); 245 } 246 247 254 public static String getText(Node node, String defaultvalue) { 255 try { 256 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 Node childnode=node.getFirstChild(); 264 StringBuffer value = new StringBuffer (); 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 e) { 273 log.warn(e.getMessage()); 274 } 275 return defaultvalue; 276 } 277 278 286 public static String selectSingleNodeText(Node node, String xpath, String defaultvalue) { 287 return selectSingleNodeText(node, xpath, defaultvalue, null); 288 } 289 290 302 public static String selectSingleNodeText(Node node, String xpath, String defaultvalue, Cloud cloud) { 303 try { 304 XObject x = null; 305 if (cloud != null) { 307 x = XPathAPI.eval(node, xpath + "[lang('"+cloud.getLocale().getLanguage()+"')]"); 308 } 309 String xs = (x == null ? "" : x.str()); 310 312 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 e) { 323 log.error(Logging.stackTrace(e) + ", evaluating xpath:" + xpath); 324 } 325 return defaultvalue; 326 } 327 328 335 public static void storeText(Node node, String text, Map params) { 336 storeText(node, fillInParams(text, params)); 337 } 338 339 343 public static void storeText(Node node, String 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 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 385 public static Node createAndAppendNode(Node parentnode, String nodename, String nodevalue) { 386 Node n = parentnode.getOwnerDocument().createElement(nodename); 387 storeText(n, nodevalue); 388 parentnode.appendChild(n); 389 return n; 390 } 391 392 395 396 403 404 405 public static int tagNodeList(NodeList list, String name, String pre) { 406 return tagNodeList(list, name, pre, 1); 407 } 408 409 412 public static int tagNodeList(NodeList list, String name, String 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 426 public static void copyAllAttributes(Node source, Node dest) { 427 copyAllAttributes(source,dest,null); 428 } 429 430 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 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 447 448 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 ) entry.getKey(), entry.getValue()); 462 } 463 } 464 465 466 467 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 ("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 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 505 506 public static String 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 serializer.transform(domSource, streamResult); 521 return result.toString(); 522 } catch (Exception e) { 523 log.error(e + Logging.stackTrace(e)); 524 return e.toString(); 525 } 526 } 527 528 529 530 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 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 557 public static void transformNode(Node node, URL xslFile, URIResolver uri, Writer out) throws TransformerException { 558 transformNode(node, xslFile, uri, out, null); 559 } 560 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 StringWriter res = new StringWriter(); 567 transformNode(node, xslFile, uri, new javax.xml.transform.stream.StreamResult (res), params); 568 if (log.isDebugEnabled()) log.trace("transformation result " + res.toString()); 569 try { 570 out.write(res.toString()); 571 } catch (java.io.IOException e) { 572 log.error(e.toString()); 573 } 574 } 576 577 public static Node transformNode(Node node, String 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 591 public static String transformAttribute(Node context, String attributeTemplate) { 592 return transformAttribute(context,attributeTemplate,false,null); 593 } 594 595 598 public static String transformAttribute(Node context, String attributeTemplate, boolean plainTextIsPath) { 599 return transformAttribute(context,attributeTemplate,plainTextIsPath,null); 600 } 601 602 615 public static String transformAttribute(Node context, String attributeTemplate, boolean plainTextIsXpath, Map params) { 616 if (attributeTemplate == null) return null; 617 StringBuffer result = new StringBuffer (); 618 String template = fillInParams(attributeTemplate, params); 619 if (plainTextIsXpath && template.indexOf("{") == -1) { 620 template = "{" + template + "}"; 621 } 622 java.util.StringTokenizer templateParts = new java.util.StringTokenizer (template,"{}",true); 623 while (templateParts.hasMoreElements()){ 624 String 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 } else{ 632 result.append(part); 633 } 634 } 635 return result.toString(); 636 } 637 638 644 public static Node selectSingleNode(Node contextnode, String xpath) { 645 if (contextnode==null) throw new RuntimeException ("Cannot execute xpath '" + xpath + "' on dom.Node that is null"); 646 try { 647 return XPathAPI.selectSingleNode(contextnode, xpath); 648 } catch (Exception e) { 649 log.error(Logging.stackTrace(e)); 650 throw new RuntimeException (Logging.stackTrace(e)); 651 } 652 } 653 654 660 public static NodeList selectNodeList(Node contextnode, String xpath) { 661 if (contextnode==null) throw new RuntimeException ("Cannot execute xpath '" + xpath + "' on dom.Node that is null"); 662 try { 663 return XPathAPI.selectNodeList(contextnode, xpath); 664 } catch (Exception e) { 665 log.error(Logging.stackTrace(e)); 666 throw new RuntimeException (Logging.stackTrace(e)); 667 } 668 } 669 670 671 674 675 684 public static String fillInParams(String 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 text = multipleReplace(text, "{$" + entry.getKey() + "}", (String ) entry.getValue()); 691 text = multipleReplace(text, "$" + entry.getKey(), (String ) entry.getValue()); 692 } 693 return text; 694 } 695 696 705 public static String multipleReplace(String text, String searchfor, String replacewith) { 706 if (text==null || searchfor==null || replacewith==null) return null; 707 if (searchfor.indexOf(replacewith)>-1) return text; 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 726 private static String postXml(Node xml, String url) throws Exception { 727 String 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 out.println("xml=" + URLEncoder.encode(inputString)); 737 out.close(); 738 739 BufferedReader in2 = new BufferedReader(new InputStreamReader(c.getInputStream())); 740 741 String outputstr = ""; 742 String inputLine; 743 while((inputLine = in2.readLine()) != null) 744 outputstr += inputLine; 745 in2.close(); 746 return outputstr; 747 } 748 } 749 | Popular Tags |