1 24 package org.ofbiz.base.util; 25 26 import java.io.ByteArrayInputStream ; 27 import java.io.ByteArrayOutputStream ; 28 import java.io.File ; 29 import java.io.FileOutputStream ; 30 import java.io.IOException ; 31 import java.io.InputStream ; 32 import java.io.OutputStream ; 33 import java.net.URL ; 34 import java.util.List ; 35 import java.util.Set ; 36 37 import javax.xml.parsers.DocumentBuilder ; 38 import javax.xml.parsers.DocumentBuilderFactory ; 39 import javax.xml.parsers.ParserConfigurationException ; 40 41 import javolution.util.FastList; 42 43 import org.apache.xml.serialize.OutputFormat; 44 import org.apache.xml.serialize.XMLSerializer; 45 import org.w3c.dom.Document ; 46 import org.w3c.dom.Element ; 47 import org.w3c.dom.Node ; 48 import org.xml.sax.EntityResolver ; 49 import org.xml.sax.ErrorHandler ; 50 import org.xml.sax.InputSource ; 51 import org.xml.sax.SAXException ; 52 import org.xml.sax.SAXParseException ; 53 import org.xml.sax.helpers.DefaultHandler ; 54 55 62 public class UtilXml { 63 64 public static final String module = UtilXml.class.getName(); 65 66 public static String writeXmlDocument(Document document) throws java.io.IOException { 67 if (document == null) { 68 Debug.logWarning("[UtilXml.writeXmlDocument] Document was null, doing nothing", module); 69 return null; 70 } 71 return writeXmlDocument(document.getDocumentElement()); 72 } 73 74 public static String writeXmlDocument(Element element) throws java.io.IOException { 75 if (element == null) { 76 Debug.logWarning("[UtilXml.writeXmlDocument] Element was null, doing nothing", module); 77 return null; 78 } 79 80 ByteArrayOutputStream bos = new ByteArrayOutputStream (); 81 writeXmlDocument(bos, element); 82 String outString = bos.toString("UTF-8"); 83 84 if (bos != null) bos.close(); 85 return outString; 86 } 87 88 public static void writeXmlDocument(String filename, Document document) 89 throws java.io.FileNotFoundException , java.io.IOException { 90 if (document == null) { 91 Debug.logWarning("[UtilXml.writeXmlDocument] Document was null, doing nothing", module); 92 return; 93 } 94 writeXmlDocument(filename, document.getDocumentElement()); 95 } 96 97 public static void writeXmlDocument(String filename, Element element) 98 throws java.io.FileNotFoundException , java.io.IOException { 99 if (element == null) { 100 Debug.logWarning("[UtilXml.writeXmlDocument] Element was null, doing nothing", module); 101 return; 102 } 103 if (filename == null) { 104 Debug.logWarning("[UtilXml.writeXmlDocument] Filename was null, doing nothing", module); 105 return; 106 } 107 108 File outFile = new File (filename); 109 FileOutputStream fos = null; 110 fos = new FileOutputStream (outFile); 111 112 try { 113 writeXmlDocument(fos, element); 114 } finally { 115 if (fos != null) fos.close(); 116 } 117 } 118 119 public static void writeXmlDocument(OutputStream os, Document document) throws java.io.IOException { 120 if (document == null) { 121 Debug.logWarning("[UtilXml.writeXmlDocument] Document was null, doing nothing", module); 122 return; 123 } 124 writeXmlDocument(os, document.getDocumentElement()); 125 } 126 public static void writeXmlDocument(OutputStream os, Element element) throws java.io.IOException { 127 if (element == null) { 128 Debug.logWarning("[UtilXml.writeXmlDocument] Element was null, doing nothing", module); 129 return; 130 } 131 if (os == null) { 132 Debug.logWarning("[UtilXml.writeXmlDocument] OutputStream was null, doing nothing", module); 133 return; 134 } 135 136 OutputFormat format = new OutputFormat(element.getOwnerDocument()); 144 format.setIndent(2); 145 146 XMLSerializer serializer = new XMLSerializer(os, format); 147 serializer.asDOMSerializer(); 148 serializer.serialize(element); 149 } 151 152 public static Document readXmlDocument(String content) 153 throws SAXException , ParserConfigurationException , java.io.IOException { 154 return readXmlDocument(content, true); 155 } 156 157 public static Document readXmlDocument(String content, boolean validate) 158 throws SAXException , ParserConfigurationException , java.io.IOException { 159 if (content == null) { 160 Debug.logWarning("[UtilXml.readXmlDocument] content was null, doing nothing", module); 161 return null; 162 } 163 ByteArrayInputStream bis = new ByteArrayInputStream (content.getBytes("UTF-8")); 164 return readXmlDocument(bis, validate, "Internal Content"); 165 } 166 167 public static Document readXmlDocument(URL url) 168 throws SAXException , ParserConfigurationException , java.io.IOException { 169 return readXmlDocument(url, true); 170 } 171 172 public static Document readXmlDocument(URL url, boolean validate) 173 throws SAXException , ParserConfigurationException , java.io.IOException { 174 if (url == null) { 175 Debug.logWarning("[UtilXml.readXmlDocument] URL was null, doing nothing", module); 176 return null; 177 } 178 return readXmlDocument(url.openStream(), validate, url.toString()); 179 } 180 181 184 public static Document readXmlDocument(InputStream is) 185 throws SAXException , ParserConfigurationException , java.io.IOException { 186 return readXmlDocument(is, true, null); 187 } 188 189 public static Document readXmlDocument(InputStream is, String docDescription) 190 throws SAXException , ParserConfigurationException , java.io.IOException { 191 return readXmlDocument(is, true, docDescription); 192 } 193 194 public static Document readXmlDocument(InputStream is, boolean validate, String docDescription) 195 throws SAXException , ParserConfigurationException , java.io.IOException { 196 if (is == null) { 197 Debug.logWarning("[UtilXml.readXmlDocument] InputStream was null, doing nothing", module); 198 return null; 199 } 200 201 long startTime = System.currentTimeMillis(); 202 203 206 Document document = null; 207 208 219 220 221 DocumentBuilderFactory factory = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl(); 222 factory.setValidating(validate); 223 factory.setNamespaceAware(true); 224 225 factory.setAttribute("http://xml.org/sax/features/validation", Boolean.TRUE); 226 factory.setAttribute("http://apache.org/xml/features/validation/schema", Boolean.TRUE); 227 228 DocumentBuilder builder = factory.newDocumentBuilder(); 232 if (validate) { 233 LocalResolver lr = new LocalResolver(new DefaultHandler ()); 234 ErrorHandler eh = new LocalErrorHandler(docDescription, lr); 235 236 builder.setEntityResolver(lr); 237 builder.setErrorHandler(eh); 238 } 239 document = builder.parse(is); 240 241 double totalSeconds = (System.currentTimeMillis() - startTime)/1000.0; 242 if (Debug.timingOn()) Debug.logTiming("XML Read " + totalSeconds + "s: " + docDescription, module); 243 return document; 244 } 245 246 public static Document makeEmptyXmlDocument() { 247 return makeEmptyXmlDocument(null); 248 } 249 250 public static Document makeEmptyXmlDocument(String rootElementName) { 251 Document document = null; 252 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 253 254 factory.setValidating(true); 255 try { 257 DocumentBuilder builder = factory.newDocumentBuilder(); 258 259 document = builder.newDocument(); 260 } catch (Exception e) { 261 Debug.logError(e, module); 262 } 263 264 if (document == null) return null; 265 266 if (rootElementName != null) { 267 Element rootElement = document.createElement(rootElementName); 268 document.appendChild(rootElement); 269 } 270 271 return document; 272 } 273 274 275 public static Element addChildElement(Element element, String childElementName, Document document) { 276 Element newElement = document.createElement(childElementName); 277 278 element.appendChild(newElement); 279 return newElement; 280 } 281 282 285 public static Element addChildElementValue(Element element, String childElementName, 286 String childElementValue, Document document) { 287 Element newElement = addChildElement(element, childElementName, document); 288 289 newElement.appendChild(document.createTextNode(childElementValue)); 290 return newElement; 291 } 292 293 296 public static Element addChildElementCDATAValue(Element element, String childElementName, 297 String childElementValue, Document document) { 298 Element newElement = addChildElement(element, childElementName, document); 299 300 newElement.appendChild(document.createCDATASection(childElementValue)); 301 return newElement; 302 } 303 304 305 public static List childElementList(Element element) { 306 if (element == null) return null; 307 308 List elements = FastList.newInstance(); 309 Node node = element.getFirstChild(); 310 311 if (node != null) { 312 do { 313 if (node.getNodeType() == Node.ELEMENT_NODE) { 314 Element childElement = (Element ) node; 315 316 elements.add(childElement); 317 } 318 } while ((node = node.getNextSibling()) != null); 319 } 320 return elements; 321 } 322 323 326 public static List childElementList(Element element, String childElementName) { 327 if (element == null) return null; 328 329 List elements = FastList.newInstance(); 330 Node node = element.getFirstChild(); 331 332 if (node != null) { 333 do { 334 if (node.getNodeType() == Node.ELEMENT_NODE && (childElementName == null || 335 childElementName.equals(node.getNodeName()))) { 336 Element childElement = (Element ) node; 337 338 elements.add(childElement); 339 } 340 } while ((node = node.getNextSibling()) != null); 341 } 342 return elements; 343 } 344 345 348 public static List childElementList(Element element, Set childElementNames) { 349 if (element == null) return null; 350 351 List elements = FastList.newInstance(); 352 if (childElementNames == null) return elements; 353 Node node = element.getFirstChild(); 354 355 if (node != null) { 356 do { 357 if (node.getNodeType() == Node.ELEMENT_NODE && childElementNames.contains(node.getNodeName())) { 358 Element childElement = (Element ) node; 359 360 elements.add(childElement); 361 } 362 } while ((node = node.getNextSibling()) != null); 363 } 364 return elements; 365 } 366 367 369 public static Element firstChildElement(Element element, Set childElementNames) { 370 if (element == null) return null; 371 Node node = element.getFirstChild(); 373 374 if (node != null) { 375 do { 376 if (node.getNodeType() == Node.ELEMENT_NODE && childElementNames.contains(node.getNodeName())) { 377 Element childElement = (Element ) node; 378 379 return childElement; 380 } 381 } while ((node = node.getNextSibling()) != null); 382 } 383 return null; 384 } 385 386 388 public static Element firstChildElement(Element element) { 389 if (element == null) return null; 390 Node node = element.getFirstChild(); 392 393 if (node != null) { 394 do { 395 if (node.getNodeType() == Node.ELEMENT_NODE) { 396 Element childElement = (Element ) node; 397 398 return childElement; 399 } 400 } while ((node = node.getNextSibling()) != null); 401 } 402 return null; 403 } 404 405 407 public static Element firstChildElement(Element element, String childElementName) { 408 if (element == null) return null; 409 Node node = element.getFirstChild(); 411 412 if (node != null) { 413 do { 414 if (node.getNodeType() == Node.ELEMENT_NODE && (childElementName == null || 415 childElementName.equals(node.getNodeName()))) { 416 Element childElement = (Element ) node; 417 418 return childElement; 419 } 420 } while ((node = node.getNextSibling()) != null); 421 } 422 return null; 423 } 424 425 427 public static Element firstChildElement(Element element, String childElementName, String attrName, String attrValue) { 428 if (element == null) return null; 429 Node node = element.getFirstChild(); 431 432 if (node != null) { 433 do { 434 if (node.getNodeType() == Node.ELEMENT_NODE && (childElementName == null || 435 childElementName.equals(node.getNodeName()))) { 436 Element childElement = (Element ) node; 437 438 String value = childElement.getAttribute(attrName); 439 440 if (value != null && value.equals(attrValue)) { 441 return childElement; 442 } 443 } 444 } while ((node = node.getNextSibling()) != null); 445 } 446 return null; 447 } 448 449 450 public static String childElementValue(Element element, String childElementName) { 451 if (element == null) return null; 452 Element childElement = firstChildElement(element, childElementName); 454 455 return elementValue(childElement); 456 } 457 458 459 public static String childElementValue(Element element, String childElementName, String defaultValue) { 460 if (element == null) return defaultValue; 461 Element childElement = firstChildElement(element, childElementName); 463 String elementValue = elementValue(childElement); 464 465 if (elementValue == null || elementValue.length() == 0) 466 return defaultValue; 467 else 468 return elementValue; 469 } 470 471 472 public static String elementValue(Element element) { 473 if (element == null) return null; 474 element.normalize(); 476 Node textNode = element.getFirstChild(); 477 478 if (textNode == null) return null; 479 480 StringBuffer valueBuffer = new StringBuffer (); 481 do { 482 if (textNode.getNodeType() == Node.CDATA_SECTION_NODE || textNode.getNodeType() == Node.TEXT_NODE) { 483 valueBuffer.append(textNode.getNodeValue()); 484 } 485 } while ((textNode = textNode.getNextSibling()) != null); 486 return valueBuffer.toString(); 487 } 488 489 public static String checkEmpty(String string) { 490 if (string != null && string.length() > 0) 491 return string; 492 else 493 return ""; 494 } 495 496 public static String checkEmpty(String string1, String string2) { 497 if (string1 != null && string1.length() > 0) 498 return string1; 499 else if (string2 != null && string2.length() > 0) 500 return string2; 501 else 502 return ""; 503 } 504 505 public static String checkEmpty(String string1, String string2, String string3) { 506 if (string1 != null && string1.length() > 0) 507 return string1; 508 else if (string2 != null && string2.length() > 0) 509 return string2; 510 else if (string3 != null && string3.length() > 0) 511 return string3; 512 else 513 return ""; 514 } 515 516 public static boolean checkBoolean(String str) { 517 return checkBoolean(str, false); 518 } 519 520 public static boolean checkBoolean(String str, boolean defaultValue) { 521 if (defaultValue) { 522 return !"false".equals(str); 524 } else { 525 return "true".equals(str); 527 } 528 } 529 530 536 public static class LocalResolver implements EntityResolver { 537 538 private boolean hasDTD = false; 539 private EntityResolver defaultResolver; 540 541 public LocalResolver(EntityResolver defaultResolver) { 542 this.defaultResolver = defaultResolver; 543 } 544 545 552 public InputSource resolveEntity(String publicId, String systemId) throws SAXException , IOException { 553 hasDTD = false; 555 String dtd = UtilProperties.getSplitPropertyValue(UtilURL.fromResource("localdtds.properties"), publicId); 556 if (UtilValidate.isNotEmpty(dtd)) { 557 if (Debug.verboseOn()) Debug.logVerbose("[UtilXml.LocalResolver.resolveEntity] resolving DTD with publicId [" + publicId + 558 "], systemId [" + systemId + "] and the dtd file is [" + dtd + "]", module); 559 try { 560 URL dtdURL = UtilURL.fromResource(dtd); 561 if (dtdURL == null) { 562 throw new GeneralException("Local DTD not found - " + dtd); 563 } 564 InputStream dtdStream = dtdURL.openStream(); 565 InputSource inputSource = new InputSource (dtdStream); 566 567 inputSource.setPublicId(publicId); 568 hasDTD = true; 569 if (Debug.verboseOn()) Debug.logVerbose("[UtilXml.LocalResolver.resolveEntity] got LOCAL DTD input source with publicId [" + 570 publicId + "] and the dtd file is [" + dtd + "]", module); 571 return inputSource; 572 } catch (Exception e) { 573 Debug.logWarning(e, module); 574 } 575 } else { 576 int lastSlash = systemId.lastIndexOf("/"); 578 String filename = null; 579 if (lastSlash == -1) { 580 filename = systemId; 581 } else { 582 filename = systemId.substring(lastSlash + 1); 583 } 584 585 URL resourceUrl = UtilURL.fromResource(filename); 586 587 if (resourceUrl != null) { 588 InputStream resStream = resourceUrl.openStream(); 589 InputSource inputSource = new InputSource (resStream); 590 591 if (UtilValidate.isNotEmpty(publicId)) { 592 inputSource.setPublicId(publicId); 593 } 594 hasDTD = true; 595 if (Debug.verboseOn()) Debug.logVerbose("[UtilXml.LocalResolver.resolveEntity] got LOCAL DTD/Schema input source with publicId [" + 596 publicId + "] and the file/resource is [" + filename + "]", module); 597 return inputSource; 598 } else { 599 Debug.logWarning("[UtilXml.LocalResolver.resolveEntity] could not find LOCAL DTD/Schema with publicId [" + 600 publicId + "] and the file/resource is [" + filename + "]", module); 601 return null; 602 } 603 } 604 return defaultResolver.resolveEntity(publicId, systemId); 607 } 608 609 613 public boolean hasDTD() { 614 return hasDTD; 615 } 616 } 617 618 619 622 public static class LocalErrorHandler implements ErrorHandler { 623 624 private String docDescription; 625 private LocalResolver localResolver; 626 627 public LocalErrorHandler(String docDescription, LocalResolver localResolver) { 628 this.docDescription = docDescription; 629 this.localResolver = localResolver; 630 } 631 632 public void error(SAXParseException exception) { 633 if (localResolver.hasDTD()) { 634 Debug.logError("XmlFileLoader: File " 635 + docDescription 636 + " process error. Line: " 637 + String.valueOf(exception.getLineNumber()) 638 + ". Error message: " 639 + exception.getMessage(), module 640 ); 641 } 642 } 643 644 public void fatalError(SAXParseException exception) { 645 if (localResolver.hasDTD()) { 646 Debug.logError("XmlFileLoader: File " 647 + docDescription 648 + " process fatal error. Line: " 649 + String.valueOf(exception.getLineNumber()) 650 + ". Error message: " 651 + exception.getMessage(), module 652 ); 653 } 654 } 655 656 public void warning(SAXParseException exception) { 657 if (localResolver.hasDTD()) { 658 Debug.logError("XmlFileLoader: File " 659 + docDescription 660 + " process warning. Line: " 661 + String.valueOf(exception.getLineNumber()) 662 + ". Error message: " 663 + exception.getMessage(), module 664 ); 665 } 666 } 667 } 668 } 669 | Popular Tags |