001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common Development
008: * and Distribution License("CDDL") (collectively, the "License"). You
009: * may not use this file except in compliance with the License. You can obtain
010: * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
011: * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
012: * language governing permissions and limitations under the License.
013: *
014: * When distributing the software, include this License Header Notice in each
015: * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
016: * Sun designates this particular file as subject to the "Classpath" exception
017: * as provided by Sun in the GPL Version 2 section of the License file that
018: * accompanied this code. If applicable, add the following below the License
019: * Header, with the fields enclosed by brackets [] replaced by your own
020: * identifying information: "Portions Copyrighted [year]
021: * [name of copyright owner]"
022: *
023: * Contributor(s):
024: *
025: * If you wish your version of this file to be governed by only the CDDL or
026: * only the GPL Version 2, indicate your decision by adding "[Contributor]
027: * elects to include this software in this distribution under the [CDDL or GPL
028: * Version 2] license." If you don't indicate a single choice of license, a
029: * recipient has the option to distribute your version of this file under
030: * either the CDDL, the GPL Version 2 or to extend the choice of license to
031: * its licensees as provided above. However, if you add GPL Version 2 code
032: * and therefore, elected the GPL Version 2 license, then the option applies
033: * only if the new code is made subject to such option by the copyright
034: * holder.
035: */
036: package javax.persistence;
037:
038: // J2SE imports
039: import java.io.IOException;
040: import java.io.BufferedReader;
041: import java.io.InputStream;
042: import java.io.InputStreamReader;
043: import java.io.PrintWriter;
044: import java.io.StringWriter;
045: import java.util.Set;
046: import java.util.Map;
047: import java.util.HashSet;
048: import java.util.HashMap;
049: import java.util.Enumeration;
050: import java.net.URL;
051: import java.util.regex.Matcher;
052: import java.util.regex.Pattern;
053:
054: // persistence imports
055: import javax.persistence.spi.PersistenceProvider;
056:
057: /**
058: * Bootstrap class that is used to obtain an {@link EntityManagerFactory}.
059: *
060: * @since Java Persistence 1.0
061: */
062: public class Persistence {
063:
064: public static final String PERSISTENCE_PROVIDER = "javax.persistence.spi.PeristenceProvider";
065:
066: //Need to keep this variable for compatibility with signature tests!!!
067: protected static final Set<PersistenceProvider> providers = new HashSet<PersistenceProvider>();
068:
069: //Private variables
070: private static final String SERVICE_NAME = "META-INF/services/"
071: + PersistenceProvider.class.getName();
072: private static final String PERSISTENCE_XML_NAME = "META-INF/persistence.xml";
073:
074: /**
075: * Create and return an EntityManagerFactory for the
076: * named persistence unit.
077: *
078: * @param persistenceUnitName The name of the persistence unit
079: * @return The factory that creates EntityManagers configured
080: * according to the specified persistence unit
081: */
082: public static EntityManagerFactory createEntityManagerFactory(
083: String persistenceUnitName) {
084: return createEntityManagerFactory(persistenceUnitName, null);
085: }
086:
087: /**
088: * Create and return an EntityManagerFactory for the
089: * named persistence unit using the given properties.
090: *
091: * @param persistenceUnitName The name of the persistence unit
092: * @param properties Additional properties to use when creating the
093: * factory. The values of these properties override any values
094: * that may have been configured elsewhere.
095: * @return The factory that creates EntityManagers configured
096: * according to the specified persistence unit.
097: */
098: public static EntityManagerFactory createEntityManagerFactory(
099: String persistenceUnitName, Map properties) {
100: EntityManagerFactory emf = null;
101: Set<PersistenceProvider> providersFound = null;
102:
103: try {
104: providersFound = findAllProviders();
105: } catch (IOException exc) {
106: }
107: ;
108:
109: Map<String, String> errors = new HashMap<String, String>();
110: Set<String> returnedNull = new HashSet<String>();
111: for (PersistenceProvider provider : providersFound) {
112: try {
113: emf = provider.createEntityManagerFactory(
114: persistenceUnitName, properties);
115: if (emf != null) {
116: break;
117: } else {
118: returnedNull.add(provider.getClass().getName());
119: }
120: } catch (Throwable t) {
121: // ignore : according to Spec the provider must return null from
122: // createEntityManagerFactory(), if not the right provider.
123: // But non-compliant provider may throw exception
124: errors.put(provider.getClass().getName(),
125: createErrorMessage(t));
126: }
127: }
128:
129: if (emf == null) {
130: StringBuffer message = new StringBuffer(
131: "No Persistence provider for EntityManager named "
132: + persistenceUnitName + ": ");
133: if (!exists(PERSISTENCE_XML_NAME)) {
134: message
135: .append(" No META-INF/persistence.xml was found in classpath.\n");
136: } else {
137: Map<String, String> reasons = getReasons();
138: for (Map.Entry me : reasons.entrySet()) {
139: message.append("Provider named ");
140: message.append(me.getKey());
141: message
142: .append(" threw exception at initialization: ");
143: message.append(me.getValue() + "\n");
144: }
145:
146: for (Map.Entry me : errors.entrySet()) {
147: message.append("Provider named ");
148: message.append(me.getKey());
149: message
150: .append(" threw unexpected exception at create EntityManagerFactory: \n");
151: message.append(me.getValue() + "\n");
152: }
153:
154: if (!returnedNull.isEmpty()) {
155: message.append(" The following providers:\n");
156: for (String n : returnedNull) {
157: message.append(n + "\n");
158: }
159: message
160: .append("Returned null to createEntityManagerFactory.\n");
161: }
162: }
163: throw new PersistenceException(message.toString());
164: }
165: return emf;
166: }
167:
168: // Helper methods
169:
170: private static Set<PersistenceProvider> findAllProviders()
171: throws IOException {
172: HashSet<PersistenceProvider> providersFound = new HashSet<PersistenceProvider>();
173: ClassLoader loader = Thread.currentThread()
174: .getContextClassLoader();
175: Enumeration<URL> resources = loader.getResources(SERVICE_NAME);
176:
177: if (!resources.hasMoreElements()) {
178: throw new PersistenceException(
179: "No resource files named "
180: + SERVICE_NAME
181: + " were found. Please make sure that the persistence provider jar file is in your classpath.");
182: }
183: Set<String> names = new HashSet<String>();
184: while (resources.hasMoreElements()) {
185: URL url = resources.nextElement();
186: InputStream is = url.openStream();
187: try {
188: names
189: .addAll(providerNamesFromReader(new BufferedReader(
190: new InputStreamReader(is))));
191: } finally {
192: is.close();
193: }
194: }
195:
196: if (names.isEmpty()) {
197: throw new PersistenceException(
198: "No provider names were found in " + SERVICE_NAME);
199: }
200: for (String s : names) {
201: try {
202: providersFound.add((PersistenceProvider) loader
203: .loadClass(s).newInstance());
204: } catch (ClassNotFoundException exc) {
205: } catch (InstantiationException exc) {
206: } catch (IllegalAccessException exc) {
207: }
208: }
209: return providersFound;
210: }
211:
212: private static final Pattern nonCommentPattern = Pattern
213: .compile("^([^#]+)");
214:
215: private static Set<String> providerNamesFromReader(
216: BufferedReader reader) throws IOException {
217: Set<String> names = new HashSet<String>();
218: String line;
219: while ((line = reader.readLine()) != null) {
220: line = line.trim();
221: Matcher m = nonCommentPattern.matcher(line);
222: if (m.find()) {
223: names.add(m.group().trim());
224: }
225: }
226: return names;
227: }
228:
229: private static boolean exists(String fileName) {
230: ClassLoader loader = Thread.currentThread()
231: .getContextClassLoader();
232: Enumeration<URL> resources;
233: try {
234: resources = loader.getResources(fileName);
235: } catch (IOException ex) {
236: resources = null;
237: }
238: return resources == null ? false : resources.hasMoreElements();
239: }
240:
241: private static Map<String, String> getReasons() {
242: Map<String, String> reasons = new HashMap<String, String>();
243: ClassLoader loader = Thread.currentThread()
244: .getContextClassLoader();
245: Set<String> names = new HashSet<String>();
246:
247: try {
248: Enumeration<URL> resources = loader
249: .getResources(SERVICE_NAME);
250: while (resources.hasMoreElements()) {
251: URL url = resources.nextElement();
252: InputStream is = url.openStream();
253: try {
254: names
255: .addAll(providerNamesFromReader(new BufferedReader(
256: new InputStreamReader(is))));
257: } finally {
258: is.close();
259: }
260: }
261: } catch (IOException exc) {
262: }
263: ;
264:
265: for (String s : names) {
266: try {
267: loader.loadClass(s).newInstance();
268: } catch (ClassNotFoundException exc) {
269: reasons.put(s, exc.getClass().getName() + " "
270: + exc.getMessage());
271: } catch (InstantiationException exc) {
272: reasons.put(s, createErrorMessage(exc));
273: } catch (IllegalAccessException exc) {
274: reasons.put(s, createErrorMessage(exc));
275: } catch (RuntimeException exc) {
276: reasons.put(s, createErrorMessage(exc));
277: }
278: }
279: return reasons;
280: }
281:
282: private static String createErrorMessage(Throwable t) {
283: StringWriter errorMessage = new StringWriter();
284: errorMessage.append(t.getClass().getName()).append("\r\n");
285: t.printStackTrace(new PrintWriter(errorMessage));
286: errorMessage.append("\r\n");
287: return errorMessage.toString();
288: }
289: }
|