1 19 20 package org.apache.cayenne.jpa.conf; 21 22 import java.io.IOException ; 23 import java.io.InputStreamReader ; 24 import java.io.Reader ; 25 import java.net.URL ; 26 27 import javax.xml.XMLConstants ; 28 import javax.xml.parsers.SAXParserFactory ; 29 import javax.xml.transform.stream.StreamSource ; 30 import javax.xml.validation.Schema ; 31 import javax.xml.validation.SchemaFactory ; 32 33 import org.apache.cayenne.jpa.map.JpaEntityMap; 34 import org.apache.cayenne.xml.XMLDecoder; 35 import org.xml.sax.SAXException ; 36 37 43 public class EntityMapXMLLoader { 44 45 static final String XML_CODER_MAPPING = "META-INF/cayenne/orm-coder.xml"; 46 static final String ORM_SCHEMA = "META-INF/schemas/orm_1_0.xsd"; 47 48 Schema schema; 49 50 protected ClassLoader classLoader; 51 52 public EntityMapXMLLoader() { 53 this(Thread.currentThread().getContextClassLoader(), false); 54 } 55 56 public EntityMapXMLLoader(ClassLoader classLoader, boolean validateDescriptors) { 57 58 this.classLoader = classLoader; 59 60 if (validateDescriptors) { 62 SAXParserFactory parserFactory = SAXParserFactory.newInstance(); 63 parserFactory.setNamespaceAware(true); 64 65 71 URL schemaURL = classLoader.getResource(ORM_SCHEMA); 72 73 SchemaFactory factory = SchemaFactory 74 .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 75 StreamSource ss = new StreamSource (schemaURL.toExternalForm()); 76 77 try { 78 this.schema = factory.newSchema(ss); 79 } 80 catch (Exception e) { 81 throw new RuntimeException ("Error loading ORM schema", e); 82 } 83 } 84 } 85 86 90 91 public JpaEntityMap getEntityMap(URL resource) { 92 93 URL mappingURL = classLoader.getResource(XML_CODER_MAPPING); 96 if (mappingURL == null) { 97 throw new RuntimeException ("No code mapping found: " + XML_CODER_MAPPING); 98 } 99 100 validate(resource); 101 102 try { 103 104 Reader in = new InputStreamReader (resource.openStream(), "UTF-8"); 105 106 109 XMLDecoder decoder = new XMLDecoder(); 110 JpaEntityMap entityMap = (JpaEntityMap) decoder.decode(in, mappingURL 111 .toExternalForm()); 112 113 return entityMap; 114 } 115 catch (Exception e) { 116 throw new RuntimeException ("Error processing ORM mapping " + resource, e); 117 } 118 } 119 120 void validate(URL resource) { 122 if (schema != null) { 123 try { 124 schema.newValidator().validate(new StreamSource (resource.openStream())); 125 } 126 catch (SAXException e) { 127 throw new RuntimeException ("Error validating ORM mapping " + resource, e); 128 } 129 catch (IOException e) { 130 throw new RuntimeException ("Error processing ORM mapping " + resource, e); 131 } 132 } 133 } 134 } 135 | Popular Tags |