if (name == null){
name = "";
}
JavaSECMPInitializer initializer = JavaSECMPInitializer.getJavaSECMPInitializer();
EntityManagerSetupImpl emSetupImpl = null;
ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
try {
Enumeration<URL> resources = currentLoader.getResources("META-INF/persistence.xml");
boolean initialized = false;
while (resources.hasMoreElements()) {
String puName = PersistenceUnitProcessor.buildPersistenceUnitName(PersistenceUnitProcessor.computePURootURL(resources.nextElement()), name);
synchronized (EntityManagerFactoryProvider.emSetupImpls){
emSetupImpl = EntityManagerFactoryProvider.getEntityManagerSetupImpl(puName);
if (emSetupImpl == null || emSetupImpl.isUndeployed()){
if (!initialized) {
initializer.initialize(nonNullProperties, this);
initialized = true;
}
emSetupImpl = EntityManagerFactoryProvider.getEntityManagerSetupImpl(puName);
}
}
// We found a match, stop looking.
if (emSetupImpl != null) {
break;
}
}
} catch (Exception e){
throw PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(currentLoader, e);
}
//gf bug 854 Returns null if EntityManagerSetupImpl for the name doesn't exist (e.g. a non-existant PU)
if (emSetupImpl == null) {
return null;
}
if (!isPersistenceProviderSupported(emSetupImpl.getPersistenceUnitInfo().getPersistenceProviderClassName())){
return null;
}
// synchronized to prevent overriding of the class loader
// and also calls to predeploy and undeploy by other threads -
// the latter may alter result of shouldRedeploy method.
synchronized(emSetupImpl) {
if(emSetupImpl.shouldRedeploy()) {
SEPersistenceUnitInfo persistenceInfo = (SEPersistenceUnitInfo)emSetupImpl.getPersistenceUnitInfo();
persistenceInfo.setClassLoader(JavaSECMPInitializer.getMainLoader());
// if we are in undeployed state, this is a redeploy of an initial deployment that worked
// so if weaving were going to occur, it already occured. Therefore we can use the main classloader
if (emSetupImpl.isUndeployed()){
persistenceInfo.setNewTempClassLoader(JavaSECMPInitializer.getMainLoader());
}
}
// call predeploy
// this will just increment the factory count since we should already be deployed
emSetupImpl.predeploy(emSetupImpl.getPersistenceUnitInfo(), nonNullProperties);
}
EntityManagerFactoryImpl factory = null;
try {
factory = new EntityManagerFactoryImpl(emSetupImpl, nonNullProperties);
// This code has been added to allow validation to occur without actually calling createEntityManager
if (emSetupImpl.shouldGetSessionOnCreateFactory(nonNullProperties)) {
factory.getServerSession();
}
return factory;
} catch (RuntimeException ex) {
if(factory != null) {
factory.close();
} else {
emSetupImpl.undeploy();
}
throw ex;
}
}