Source Code Cross Referenced for Persistence.java in  » Database-ORM » toplink » javax » persistence » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Database ORM » toplink » javax.persistence 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


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:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.