ambercontainer.java

来自「RESIN 3.2 最新源码」· Java 代码 · 共 1,170 行 · 第 1/2 页

JAVA
1,170
字号
    listenerList.add(listenerType);  }  /**   * Initialize the entity homes.   */  public void initEntityHomes()  {    throw new UnsupportedOperationException();  }  public AmberPersistenceUnit createPersistenceUnit(String name)  {    AmberPersistenceUnit unit = new AmberPersistenceUnit(this, name);    _unitMap.put(unit.getName(), unit);    return unit;  }  public void start()  {    configurePersistenceRoots();    startPersistenceUnits();  }  public AmberPersistenceUnit getPersistenceUnit(String name)  {    if (_exception != null)      throw new AmberRuntimeException(_exception);    return _unitMap.get(name);  }  public EntityManagerFactory getEntityManagerFactory(String name)  {    if (_exception != null)      throw new AmberRuntimeException(_exception);    EntityManagerFactory factory = _factoryMap.get(name);    if (factory != null)      return factory;    if (_pendingRootList.size() > 0)      configurePersistenceRoots();    factory = _factoryMap.get(name);    if (factory != null)      return factory;        AmberPersistenceUnit amberUnit = _unitMap.get(name);    if (amberUnit != null) {      factory = new AmberEntityManagerFactory(amberUnit);      _factoryMap.put(name, factory);      return factory;    }    if ("".equals(name) && _factoryMap.size() == 1)      return _factoryMap.values().iterator().next();    if ("".equals(name) && _unitMap.size() == 1) {      amberUnit = _unitMap.values().iterator().next();            factory = new AmberEntityManagerFactory(amberUnit);      _factoryMap.put(name, factory);      return factory;    }    if (_parentAmberContainer != null)      return _parentAmberContainer.getEntityManagerFactory(name);    else      return null;  }    public EntityManager getPersistenceContext(String name)  {    if (_exception != null)      throw new AmberRuntimeException(_exception);    if ("".equals(name) && _unitConfigList.size() > 0)      name = _unitConfigList.get(0).getName();    EntityManager context = _persistenceContextMap.get(name);    if (context != null)      return context;    if (_pendingRootList.size() > 0)      configurePersistenceRoots();    if ("".equals(name) && _unitConfigList.size() > 0)      name = _unitConfigList.get(0).getName();    context = _persistenceContextMap.get(name);    if (context != null)      return context;        AmberPersistenceUnit amberUnit = _unitMap.get(name);    if (amberUnit != null) {      context = new EntityManagerProxy(amberUnit);      _persistenceContextMap.put(name, context);            return context;    }    return null;  }    public EntityManager getExtendedPersistenceContext(String name)  {    if (_exception != null)      throw new AmberRuntimeException(_exception);    if ("".equals(name) && _unitConfigList.size() > 0)      name = _unitConfigList.get(0).getName();    if (_pendingRootList.size() > 0)      configurePersistenceRoots();    if ("".equals(name) && _unitConfigList.size() > 0)      name = _unitConfigList.get(0).getName();        AmberPersistenceUnit amberUnit = _unitMap.get(name);    if (amberUnit != null) {      return new EntityManagerExtendedProxy(amberUnit);    }    return null;  }  /**   * Adds a persistence root.   */  public void addPersistenceUnit(Path root)  {    if (_persistenceRootMap.get(root) != null)      return;    RootContext context = new RootContext(root);    _persistenceRootMap.put(root, context);    _pendingRootList.add(context);  }    /**   * Adds the URLs for the classpath.   */  public void configurePersistenceRoots()  {    Thread thread = Thread.currentThread();    ClassLoader oldLoader = thread.getContextClassLoader();    try {      // jpa/1630      // thread.setContextClassLoader(_tempLoader);      thread.setContextClassLoader(_parentLoader);      ArrayList<RootContext> rootList	= new ArrayList<RootContext>(_pendingRootList);      _pendingRootList.clear();            for (RootContext rootContext : rootList) {	configureRoot(rootContext);      }    } finally {      thread.setContextClassLoader(oldLoader);    }  }  private void configureRoot(RootContext rootContext)  {    Path root = rootContext.getRoot();    try {      Path ormXml = root.lookup("META-INF/orm.xml");      EntityMappingsConfig entityMappings        = configureMappingFile(root, ormXml);      ArrayList<PersistenceUnitConfig> unitList = parsePersistenceConfig(root);      if (unitList == null)	return;      HashMap<String,Class> classMap = new HashMap<String,Class>();      for (PersistenceUnitConfig unitConfig : unitList) {	Class provider = unitConfig.getProvider();	if (provider != null	    && ! AmberPersistenceProvider.class.equals(provider)) {	  addProviderUnit(unitConfig);	  	  continue;	}		if (log.isLoggable(Level.CONFIG))	  log.config("Amber PersistenceUnit[" + unitConfig.getName() + "] configuring " + rootContext.getRoot().getURL());	  	if (! unitConfig.isExcludeUnlistedClasses()) {	  classMap.clear();	    	  for (String className : rootContext.getClassNameList())	    lookupClass(className, classMap, entityMappings);	    	  unitConfig.addAllClasses(classMap);	}	ArrayList<EntityMappingsConfig> entityMappingsList	  = new ArrayList<EntityMappingsConfig>();	if (entityMappings != null)	  entityMappingsList.add(entityMappings);	// jpa/0s2n: <jar-file>	for (String fileName : unitConfig.getJarFiles()) {	  JarPath jarFile;	  Path parent = root;	  if (root instanceof JarPath) {	    parent = ((JarPath) root).getContainer().getParent();	  }	  jarFile = JarPath.create(parent.lookup(fileName));	  classMap.clear();	  // lookupJarClasses(jarFile, classMap, entityMappings);	  unitConfig.addAllClasses(classMap);	}	// jpa/0s2l: custom mapping-file.	for (String fileName : unitConfig.getMappingFiles()) {	  Path mappingFile = root.lookup(fileName);	  EntityMappingsConfig mappingFileConfig	    = configureMappingFile(root, mappingFile);	  if (mappingFileConfig != null) {	    entityMappingsList.add(mappingFileConfig);	    classMap.clear();	    /*	      lookupClasses(root.getPath().length(), root, classMap,	      mappingFileConfig);	    */	    unitConfig.addAllClasses(classMap);	  }	}	AmberPersistenceUnit unit	  = unitConfig.init(this, entityMappingsList);	_pendingUnitList.add(unit);	_unitMap.put(unit.getName(), unit);      }    } catch (Exception e) {      addException(e);      throw ConfigException.create(e);    }  }    /**   * Adds the URLs for the classpath.   */  public void startPersistenceUnits()  {    Thread thread = Thread.currentThread();    ClassLoader oldLoader = thread.getContextClassLoader();    try {      // jpa/1630      // thread.setContextClassLoader(_tempLoader);      thread.setContextClassLoader(_parentLoader);      ArrayList<AmberPersistenceUnit> unitList	= new ArrayList<AmberPersistenceUnit>(_pendingUnitList);      _pendingUnitList.clear();      ArrayList<LazyEntityManagerFactory> lazyEmfList	= new ArrayList<LazyEntityManagerFactory>(_pendingFactoryList);      _pendingFactoryList.clear();            for (LazyEntityManagerFactory lazyEmf : lazyEmfList) {	lazyEmf.init();      }            for (AmberPersistenceUnit unit : unitList) {	unit.initEntityHomes();      }    } finally {      thread.setContextClassLoader(oldLoader);    }  }  private void addProviderUnit(PersistenceUnitConfig unit)  {    try {      Class cl = unit.getProvider();	        if (log.isLoggable(Level.CONFIG)) {	log.config("JPA PersistenceUnit[" + unit.getName() + "] handled by "		   + cl.getName());      }      PersistenceProvider provider = (PersistenceProvider) cl.newInstance();      String unitName = unit.getName();      Map props = null;            synchronized (this) {	LazyEntityManagerFactory lazyFactory	  = new LazyEntityManagerFactory(unit, provider, props);		_pendingFactoryList.add(lazyFactory);      }            EntityManagerTransactionProxy persistenceContext	= new EntityManagerTransactionProxy(this, unitName, props);            _persistenceContextMap.put(unitName, persistenceContext);      WebBeansContainer webBeans = WebBeansContainer.create(_parentLoader);      webBeans.addComponent(new EntityManagerFactoryComponent(this, provider, unit));      webBeans.addComponent(new PersistenceContextComponent(unitName, persistenceContext));    } catch (RuntimeException e) {      throw e;    } catch (Exception e) {      throw ConfigException.create(e);    }  }  /**   * Adds a persistence root.   */  private ArrayList<PersistenceUnitConfig> parsePersistenceConfig(Path root)  {    Path persistenceXml = root.lookup("META-INF/persistence.xml");    if (! persistenceXml.canRead())      return null;    persistenceXml.setUserPath(persistenceXml.getURL());    if (log.isLoggable(Level.FINE))      log.fine(this + " parsing " + persistenceXml.getURL());    InputStream is = null;    try {      is = persistenceXml.openRead();      PersistenceConfig persistence = new PersistenceConfig(this);      persistence.setRoot(root);      new Config().configure(persistence, is,                             "com/caucho/amber/cfg/persistence-30.rnc");      ArrayList<PersistenceUnitConfig> unitList = persistence.getUnitList();      _unitConfigList.addAll(unitList);      return unitList;    } catch (RuntimeException e) {      throw e;    } catch (Exception e) {      throw LineConfigException.create(e);    } finally {      try {        if (is != null)          is.close();      } catch (Exception e) {      }    }  }  //  // private  //  // Configures the default orm.xml or mapping files specified with  // mapping-file tags within a persistence-unit.  //  private EntityMappingsConfig configureMappingFile(Path root,                                                    Path xmlFile)    throws Exception  {    EntityMappingsConfig entityMappings = null;    if (xmlFile.exists()) {      InputStream is = xmlFile.openRead();      entityMappings = new EntityMappingsConfig();      entityMappings.setRoot(root);      new Config().configure(entityMappings, is,                             "com/caucho/amber/cfg/mapping-30.rnc");    }    return entityMappings;  }  private void lookupClass(String className,                           HashMap<String,Class> classMap,                           EntityMappingsConfig entityMappings)    throws Exception  {    Class type = loadTempClass(className);    if (type != null) {      boolean isEntity        = type.getAnnotation(javax.persistence.Entity.class) != null;      boolean isEmbeddable        = type.getAnnotation(javax.persistence.Embeddable.class) != null;      boolean isMappedSuperclass        = type.getAnnotation(javax.persistence.MappedSuperclass.class) != null;      MappedSuperclassConfig mappedSuperclassOrEntityConfig = null;      if (entityMappings != null) {        mappedSuperclassOrEntityConfig = entityMappings.getEntityConfig(className);        if (mappedSuperclassOrEntityConfig == null)          mappedSuperclassOrEntityConfig = entityMappings.getMappedSuperclass(className);      }      if (isEntity || isEmbeddable || isMappedSuperclass	  || (mappedSuperclassOrEntityConfig != null)) {        classMap.put(className, type);      }    }  }  //  // ScanListener  //  /**   * Since Amber enhances it's priority 0   */  public int getPriority()  {    return 0;  }  /**   * Returns true if the root is a valid scannable root.   */  public boolean isRootScannable(Path root)  {    if (! root.lookup("META-INF/persistence.xml").canRead())      return false;    RootContext context = _persistenceRootMap.get(root);    if (context == null) {      context = new RootContext(root);      _pendingRootList.add(context);      _persistenceRootMap.put(root, context);    }    if (context.isScanComplete())      return false;    else {      if (log.isLoggable(Level.FINER))	log.finer(this + " scanning " + root);      context.setScanComplete(true);            return true;    }  }  public boolean isScanMatch(CharBuffer annotationName)  {    if (annotationName.matches("javax.persistence.Entity"))      return true;    else if (annotationName.matches("javax.persistence.Embeddable"))      return true;    else if (annotationName.matches("javax.persistence.MappedSuperclass"))      return true;    else      return false;  }    /**   * Callback to note the class matches   */  public void classMatchEvent(EnvironmentClassLoader loader,			      Path root,			      String className)  {    RootContext context = _persistenceRootMap.get(root);    if (context == null) {      context = new RootContext(root);      _persistenceRootMap.put(root, context);      _pendingRootList.add(context);    }          context.addClassName(className);  }  //  // EnvironmentListener  //    /**   * Handles the environment config phase   */  public void environmentConfigure(EnvironmentClassLoader loader)  {    configurePersistenceRoots();  }    /**   * Handles the environment config phase   */  public void environmentBind(EnvironmentClassLoader loader)  {    // configurePersistenceRoots();  }   /**   * Handles the case where the environment is starting (after init).   */  public void environmentStart(EnvironmentClassLoader loader)  {    start();  }  /**   * Handles the case where the environment is stopping   */  public void environmentStop(EnvironmentClassLoader loader)  {  }  public String toString()  {    return "AmberContainer[" + _parentLoader.getId() + "]";  }  class LazyEntityManagerFactory {    private final PersistenceUnitConfig _unit;    private final PersistenceProvider _provider;    private final Map _props;    LazyEntityManagerFactory(PersistenceUnitConfig unit,			     PersistenceProvider provider,			     Map props)    {      _unit = unit;      _provider = provider;      _props = props;    }    void init()    {      synchronized (AmberContainer.this) {	String unitName = _unit.getName();		EntityManagerFactory factory = _factoryMap.get(unitName);	if (factory == null) {	  factory	    = _provider.createContainerEntityManagerFactory(_unit, _props);	  if (factory == null)	    throw new ConfigException(L.l("'{0}' must return an EntityManagerFactory",					  _provider.getClass().getName()));	  if (log.isLoggable(Level.FINE)) {	    log.fine(L.l("Amber creating persistence unit '{0}' created with provider '{1}'",			 unitName, _provider.getClass().getName()));	  }	  _factoryMap.put(unitName, factory);	}      }    }  }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?