View Javadoc
1   /*
2    * Copyright 2001-2008 The Apache Software Foundation.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *
16   */
17  
18  package org.apache.juddi.config;
19  
20  import java.util.Properties;
21  
22  import javax.persistence.EntityManagerFactory;
23  import javax.persistence.Persistence;
24  import javax.persistence.EntityManager;
25  
26  import org.apache.commons.configuration.ConfigurationException;
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  
30  public class PersistenceManager {
31  	private static Log log = LogFactory.getLog(PersistenceManager.class);
32  	
33  	public static final String PERSISTENCE_UNIT_NAME = "juddiDatabase";
34  
35  	private static EntityManagerFactory emf;
36  
37  	public static EntityManager getEntityManager() {
38  		try {
39  			// Now, the factory will be initialized in the config. This will force the config to initialize, thereby initializing emf.
40  			if (emf == null)
41  				AppConfig.getInstance();
42  		} 
43  		catch (ConfigurationException e) {
44  			log.error("Error initializing config in PersistenceManager", e);
45  			throw new ExceptionInInitializerError(e);
46  		}
47  		
48  		return emf.createEntityManager();
49  	}
50  	
51  	public static void closeEntityManager() {
52  		if (emf.isOpen())
53  			emf.close();
54  	}
55  	
56  	protected static void initializeEntityManagerFactory(String persistenceUnitName, Properties properties) {
57  		try {
58  			if (emf == null)
59  				if (properties==null || properties.size()==0) {
60  					emf = Persistence.createEntityManagerFactory(persistenceUnitName);
61  				} else {
62  					emf = Persistence.createEntityManagerFactory(persistenceUnitName, properties);
63  				}
64  		}
65  		catch (Throwable t) {
66  			log.error("entityManagerFactory creation failed", t);
67  			throw new ExceptionInInitializerError(t);
68  		}
69  		
70  	}
71  	
72  }