1 23 package javax.persistence; 24 25 import java.io.IOException ; 27 import java.io.BufferedReader ; 28 import java.io.InputStream ; 29 import java.io.InputStreamReader ; 30 import java.util.Set ; 31 import java.util.Map ; 32 import java.util.HashSet ; 33 import java.util.Enumeration ; 34 import java.net.URL ; 35 import java.util.regex.Matcher ; 36 import java.util.regex.Pattern ; 37 38 import javax.persistence.spi.PersistenceProvider; 40 41 46 public class Persistence { 47 48 public static String PERSISTENCE_PROVIDER = "javax.persistence.spi.PeristenceProvider"; 49 protected static final Set <PersistenceProvider> providers = new HashSet <PersistenceProvider>(); 50 51 59 public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName) { 60 return createEntityManagerFactory(persistenceUnitName, null); 61 } 62 63 74 public static EntityManagerFactory createEntityManagerFactory( 75 String persistenceUnitName, Map properties) { 76 EntityManagerFactory emf = null; 77 if (providers.size() == 0) { 78 try{ 79 findAllProviders(); 80 } catch (IOException exc){}; 81 } 82 for (PersistenceProvider provider : providers) { 83 emf = provider.createEntityManagerFactory(persistenceUnitName, properties); 84 if (emf != null){ 85 break; 86 } 87 } 88 if (emf == null) { 89 throw new PersistenceException("No Persistence provider for EntityManager named " + persistenceUnitName); 90 } 91 return emf; 92 } 93 94 96 private static void findAllProviders() throws IOException { 97 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 98 Enumeration <URL > resources = 99 loader.getResources("META-INF/services/" + PersistenceProvider.class.getName()); 100 Set <String > names = new HashSet <String >(); 101 while (resources.hasMoreElements()) { 102 URL url = resources.nextElement(); 103 InputStream is = url.openStream(); 104 try { 105 names.addAll(providerNamesFromReader(new BufferedReader (new InputStreamReader (is)))); 106 } finally { 107 is.close(); 108 } 109 } 110 for (String s : names) { 111 try{ 112 providers.add((PersistenceProvider)loader.loadClass(s).newInstance()); 113 } catch (ClassNotFoundException exc){ 114 } catch (InstantiationException exc){ 115 } catch (IllegalAccessException exc){ 116 } 117 } 118 } 119 120 private static final Pattern nonCommentPattern = Pattern.compile("^([^#]+)"); 121 122 private static Set <String > providerNamesFromReader(BufferedReader reader) throws IOException { 123 Set <String > names = new HashSet <String >(); 124 String line; 125 while ((line = reader.readLine()) != null) { 126 line = line.trim(); 127 Matcher m = nonCommentPattern.matcher(line); 128 if (m.find()) { 129 names.add(m.group().trim()); 130 } 131 } 132 return names; 133 } 134 } 135 | Popular Tags |