1 19 20 package org.apache.cayenne.jpa.conf; 21 22 import java.net.URL ; 23 import java.util.Collection ; 24 import java.util.Enumeration ; 25 26 import org.apache.cayenne.jpa.JpaUnit; 27 import org.xml.sax.InputSource ; 28 29 34 public class UnitLoader { 35 36 static final String DESCRIPTOR_LOCATION = "META-INF/persistence.xml"; 37 38 protected UnitDescriptorParser parser; 39 40 public UnitLoader(boolean validateDescriptors) { 41 try { 42 this.parser = new UnitDescriptorParser(validateDescriptors); 43 } 44 catch (Exception e) { 45 throw new RuntimeException ("Error creating XML parser", e); 46 } 47 } 48 49 57 public JpaUnit loadUnit(String persistenceUnitName) { 58 59 if (persistenceUnitName == null) { 60 throw new IllegalArgumentException ("Null persistenceUnitName"); 61 } 62 63 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 65 try { 66 Enumeration <URL > descriptors = loader.getResources(DESCRIPTOR_LOCATION); 67 while (descriptors.hasMoreElements()) { 68 69 String descriptorURL = descriptors.nextElement().toExternalForm(); 70 71 73 String descriptorRoot = descriptorURL.substring(0, descriptorURL.length() 74 - DESCRIPTOR_LOCATION.length()); 75 76 Collection <JpaUnit> units = parser.getPersistenceUnits(new InputSource ( 77 descriptorURL), new URL (descriptorRoot)); 78 79 for (JpaUnit unit : units) { 80 if (persistenceUnitName.equals(unit.getPersistenceUnitName())) { 81 return unit; 82 } 83 } 84 } 85 } 86 catch (Exception e) { 87 throw new RuntimeException ("Error loading persistence descriptors", e); 89 } 90 91 return null; 92 } 93 } 94 | Popular Tags |