1 25 26 package org.objectweb.easybeans.util.xml; 27 28 import java.io.IOException ; 29 import java.io.InputStreamReader ; 30 import java.io.Reader ; 31 import java.net.URL ; 32 import java.net.URLConnection ; 33 34 import javax.xml.parsers.DocumentBuilder ; 35 import javax.xml.parsers.DocumentBuilderFactory ; 36 import javax.xml.parsers.ParserConfigurationException ; 37 38 import org.w3c.dom.Document ; 39 import org.xml.sax.EntityResolver ; 40 import org.xml.sax.InputSource ; 41 import org.xml.sax.SAXException ; 42 43 47 public final class DocumentParser { 48 49 52 private DocumentParser() { 53 54 } 55 56 66 public static Document getDocument(final URL url, final boolean isValidating, final EntityResolver entityResolver) 67 throws DocumentParserException { 68 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 70 71 factory.setNamespaceAware(true); 73 factory.setValidating(isValidating); 74 75 if (isValidating) { 77 factory.setIgnoringElementContentWhitespace(isValidating); 78 factory.setAttribute("http://apache.org/xml/features/validation/schema", new Boolean (isValidating)); 79 factory.setAttribute("http://apache.org/xml/features/validation/schema-full-checking", Boolean.valueOf(true)); 80 } 81 82 factory.setAttribute("http://apache.org/xml/properties/schema/external-schemaLocation", 85 "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"); 86 87 88 DocumentBuilder builder = null; 90 try { 91 builder = factory.newDocumentBuilder(); 92 } catch (ParserConfigurationException e) { 93 throw new DocumentParserException("Cannot build a document builder", e); 94 } 95 96 builder.setErrorHandler(new EasyBeansErrorHandler()); 98 99 if (factory.isValidating()) { 101 builder.setEntityResolver(entityResolver); 102 } 103 104 URLConnection urlConnection = null; 106 try { 107 urlConnection = url.openConnection(); 108 } catch (IOException e) { 109 throw new DocumentParserException("Cannot open a connection on URL '" + url + "'", e); 110 } 111 urlConnection.setDefaultUseCaches(false); 112 Reader reader = null; 113 try { 114 reader = new InputStreamReader (urlConnection.getInputStream()); 115 } catch (IOException e) { 116 throw new DocumentParserException("Cannot build an input stream reader on URL '" + url + "'", e); 117 } 118 119 InputSource inputSource = new InputSource (reader); 120 Document document = null; 121 try { 122 document = builder.parse(inputSource); 123 } catch (SAXException e) { 124 throw new DocumentParserException("Cannot parse the XML file '" + url + "'.", e); 125 } catch (IOException e) { 126 throw new DocumentParserException("Cannot parse the XML file '" + url + "'.", e); 127 } finally { 128 try { 130 reader.close(); 131 } catch (IOException e) { 132 throw new DocumentParserException("Cannot close the inputsource of the XML file'" + url + "'.", e); 133 } 134 } 135 136 return document; 137 } 138 139 } 140 | Popular Tags |