KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > server > PersistenceUnitInfoImpl


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24
25 package com.sun.enterprise.server;
26
27 import com.sun.enterprise.connectors.ConnectorRuntime;
28 import com.sun.enterprise.deployment.PersistenceUnitDescriptor;
29 import com.sun.enterprise.deployment.deploy.shared.FileArchive;
30 import com.sun.enterprise.deployment.deploy.shared.OutputJarArchive;
31 import com.sun.enterprise.loader.InstrumentableClassLoader;
32 import com.sun.enterprise.util.io.FileUtils;
33 import com.sun.enterprise.util.shared.ArchivistUtils;
34 import com.sun.logging.LogDomains;
35
36 import javax.naming.NamingException JavaDoc;
37 import javax.persistence.spi.PersistenceUnitInfo;
38 import javax.persistence.spi.PersistenceUnitTransactionType;
39 import javax.persistence.spi.ClassTransformer;
40 import javax.sql.DataSource JavaDoc;
41 import java.io.File JavaDoc;
42 import java.io.IOException JavaDoc;
43 import java.io.InputStream JavaDoc;
44 import java.io.OutputStream JavaDoc;
45 import java.net.MalformedURLException JavaDoc;
46 import java.net.URL JavaDoc;
47 import java.util.ArrayList JavaDoc;
48 import java.util.Enumeration JavaDoc;
49 import java.util.List JavaDoc;
50 import java.util.Properties JavaDoc;
51 import java.util.logging.Level JavaDoc;
52 import java.util.logging.Logger JavaDoc;
53
54 /**
55  * This class implements {@link PersistenceUnitInfo} interface.
56  *
57  * @author Sanjeeb.Sahoo@Sun.COM
58  */

59 public class PersistenceUnitInfoImpl implements PersistenceUnitInfo {
60     /* This class is public because it is used in verifier */
61
62     // TODO: i18n compliance
63
private static final String JavaDoc DEFAULT_PROVIDER_NAME =
64             "oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider"; // NOI18N
65

66     private static final String JavaDoc DEFAULT_DS_NAME = "jdbc/__default"; // NOI18N
67

68     // We allow the default provider to be specified using -D option.
69
private static String JavaDoc defaultProvider;
70
71     private static Logger JavaDoc logger = LogDomains.getLogger(
72             LogDomains.LOADER_LOGGER);;
73
74     private PersistenceUnitDescriptor persistenceUnitDescriptor;
75
76     private String JavaDoc applicationLocation;
77
78     private File JavaDoc absolutePuRootFile;
79
80     private DataSource JavaDoc jtaDataSource;
81
82     private DataSource JavaDoc nonJtaDataSource;
83
84     private List JavaDoc<URL JavaDoc> jarFiles;
85
86     private InstrumentableClassLoader classLoader;
87
88     public PersistenceUnitInfoImpl(
89             PersistenceUnitDescriptor persistenceUnitDescriptor,
90             String JavaDoc applicationLocation,
91             InstrumentableClassLoader classLoader) {
92         this.persistenceUnitDescriptor = persistenceUnitDescriptor;
93         this.applicationLocation = applicationLocation;
94         this.classLoader = classLoader;
95         jarFiles = _getJarFiles();
96         jtaDataSource = _getJtaDataSource();
97         nonJtaDataSource = _getNonJtaDataSource();
98     }
99
100     // Implementation of PersistenceUnitInfo interface
101

102     /**
103      * {@inheritDoc}
104      */

105     public String JavaDoc getPersistenceUnitName() {
106         return persistenceUnitDescriptor.getName();
107     }
108
109     /**
110      * {@inheritDoc}
111      */

112     public String JavaDoc getPersistenceProviderClassName() {
113         return getPersistenceProviderClassNameForPuDesc(persistenceUnitDescriptor);
114     }
115
116     /**
117      * {@inheritDoc}
118      */

119     public PersistenceUnitTransactionType getTransactionType() {
120         return PersistenceUnitTransactionType.valueOf(
121                 persistenceUnitDescriptor.getTransactionType());
122     }
123
124     /**
125      * {@inheritDoc}
126      */

127     public DataSource JavaDoc getJtaDataSource() {
128         return jtaDataSource;
129     }
130
131     /**
132      * {@inheritDoc}
133      */

134     public DataSource JavaDoc getNonJtaDataSource() {
135         return nonJtaDataSource;
136     }
137
138     public URL JavaDoc getPersistenceUnitRootUrl() {
139         try {
140             return getAbsolutePuRootFile().toURI().toURL();
141         } catch (MalformedURLException JavaDoc e) {
142             throw new RuntimeException JavaDoc(e);
143         }
144     }
145
146     /**
147      * {@inheritDoc}
148      */

149     public List JavaDoc<String JavaDoc> getMappingFileNames() {
150         return persistenceUnitDescriptor.getMappingFiles(); // its already unmodifiable
151
}
152
153     /**
154      * {@inheritDoc}
155      */

156     public List JavaDoc<URL JavaDoc> getJarFileUrls() {
157         return jarFiles;
158     }
159
160     /**
161      * {@inheritDoc}
162      */

163     public List JavaDoc<String JavaDoc> getManagedClassNames() {
164         return persistenceUnitDescriptor.getClasses(); // its already unmodifiable
165
}
166
167     public boolean excludeUnlistedClasses() {
168         return persistenceUnitDescriptor.isExcludeUnlistedClasses();
169     }
170
171     /**
172      * {@inheritDoc}
173      */

174     public Properties JavaDoc getProperties() {
175         return persistenceUnitDescriptor.getProperties(); // its already a clone
176
}
177
178     /**
179      * {@inheritDoc}
180      */

181     public ClassLoader JavaDoc getClassLoader() {
182         return ClassLoader JavaDoc.class.cast(classLoader);
183     }
184
185     /**
186      * {@inheritDoc}
187      */

188     public void addTransformer(ClassTransformer transformer) {
189         classLoader.addTransformer(transformer);
190     }
191
192     /**
193      * {@inheritDoc}
194      */

195     public ClassLoader JavaDoc getNewTempClassLoader() {
196         return classLoader.copy();
197     }
198
199     @Override JavaDoc public String JavaDoc toString() {
200         /*
201          * This method is used for debugging only.
202          */

203         StringBuilder JavaDoc result = new StringBuilder JavaDoc("<persistence-unit>"); // NOI18N
204
result.append("\n\t<PURoot>" + getPersistenceUnitRootUrl() + "</PURoot>"); // NOI18N
205
result.append("\n\t<name>" + getPersistenceUnitName() + "</name>"); // NOI18N
206
result.append("\n\t<provider>" + getPersistenceProviderClassName() + // NOI18N
207
"</provider>"); // NOI18N
208
result.append("\n\t<transaction-type>" + getTransactionType() + // NOI18N
209
"</transaction-type>"); // NOI18N
210
result.append("\n\t<jta-data-source>" + getJtaDataSource() + // NOI18N
211
"</jta-data-source>"); // NOI18N
212
result.append("\n\t<non-jta-data-source>" + getNonJtaDataSource() + // NOI18N
213
"</non-jta-data-source>"); // NOI18N
214
for (URL JavaDoc jar : getJarFileUrls()) {
215             result.append("\n\t<jar-file>" + jar + "</jar-file>"); // NOI18N
216
}
217         for (String JavaDoc mappingFile : getMappingFileNames()) {
218             result.append("\n\t<mapping-file>" + mappingFile + // NOI18N
219
"</mapping-file>"); // NOI18N
220
}
221         for (String JavaDoc clsName : getManagedClassNames()) {
222             result.append("\n\t<class-name>" + clsName + "</class-name>"); // NOI18N
223
}
224         result.append("\n\t<exclude-unlisted-classes>" + excludeUnlistedClasses() + // NOI18N
225
"</exclude-unlisted-classes>"); // NOI18N
226
result.append("\n\t<properties>" + getProperties() + "</properties>"); // NOI18N
227
result.append("\n\t<class-loader>" + getClassLoader() + // NOI18N
228
"</class-loader>"); // NOI18N
229
result.append("\n</persistence-unit>\n"); // NOI18N
230
return result.toString();
231     }
232
233     protected DataSource JavaDoc _getJtaDataSource() {
234         /*
235          * Use DEFAULT_DS_NAME iff user has not specified jta-ds-name
236          * and user has specified transaction-type as JTA.
237          */

238         if (getTransactionType() != PersistenceUnitTransactionType.JTA) {
239             PersistenceUnitInfoImpl.logger.logp(Level.FINE,
240                     "PersistenceUnitInfoImpl", // NOI18N
241
"_getJtaDataSource", // NOI18N
242
"This PU is configured as non-jta, so jta-data-source is null"); // NOI18N
243
return null; // this is a non-jta-data-source
244
}
245         String JavaDoc DSName;
246         String JavaDoc userSuppliedJTADSName = persistenceUnitDescriptor.getJtaDataSource();
247         if (!isNullOrEmpty(userSuppliedJTADSName)) {
248             DSName = userSuppliedJTADSName; // use user supplied jta-ds-name
249
} else {
250             DSName = DEFAULT_DS_NAME;
251         }
252         try {
253             logger.logp(Level.FINE, "PersistenceUnitLoaderImpl", // NOI18N
254
"_getJtaDataSource", "JTADSName = {0}", // NOI18N
255
DSName);
256             return DataSource JavaDoc.class.cast(
257                     ConnectorRuntime.getRuntime().lookupPMResource(DSName));
258         } catch (NamingException JavaDoc e) {
259             PersistenceUnitInfoImpl.logger.log(Level.SEVERE,
260                     "Error looking up jta-datasource by name : " + DSName, e);
261             throw new RuntimeException JavaDoc(e);
262         }
263     }
264
265     protected DataSource JavaDoc _getNonJtaDataSource() {
266         /*
267          * If non-JTA name is *not* provided
268          * - use the JTA DS name (if supplied) to call lookupNonTxResource
269          * If non-JTA name is provided
270          * - use non-JTA DS name to call lookupNonTxResource
271          * (this is done for ease of use, because user does not have to
272          * explicitly mark a connection pool as non-transactional.
273          * Calling lookupNonTxResource() with a resource which is
274          * already configured as non-transactional has no side effects.)
275          * If neither non-JTA nor JTA name is provided
276          * use DEFAULT_DS_NAME to call lookupNonTxResource
277          */

278         String JavaDoc DSName;
279         String JavaDoc userSuppliedNonJTADSName = persistenceUnitDescriptor.getNonJtaDataSource();
280         if (!isNullOrEmpty(userSuppliedNonJTADSName)) {
281             DSName = userSuppliedNonJTADSName;
282         } else {
283             String JavaDoc userSuppliedJTADSName = persistenceUnitDescriptor.getJtaDataSource();
284             if (!isNullOrEmpty(userSuppliedJTADSName)) {
285                 DSName = userSuppliedJTADSName;
286             } else {
287                 DSName = DEFAULT_DS_NAME;
288             }
289         }
290         try {
291             logger.logp(Level.FINE,
292                     "PersistenceUnitInfoImpl", // NOI18N
293
"_getNonJtaDataSource", "nonJTADSName = {0}", // NOI18N
294
DSName);
295             return DataSource JavaDoc.class.cast(
296                     ConnectorRuntime.getRuntime().lookupNonTxResource(DSName));
297         } catch (NamingException JavaDoc e) {
298             PersistenceUnitInfoImpl.logger.log(Level.SEVERE,
299                     "Error looking up non-jta-datasource by name : " + DSName,
300                     e);
301             throw new RuntimeException JavaDoc(e);
302         }
303     }
304
305     private List JavaDoc<URL JavaDoc> _getJarFiles() {
306         List JavaDoc<String JavaDoc> jarFileNames = new ArrayList JavaDoc<String JavaDoc>(
307                 persistenceUnitDescriptor.getJarFiles());
308         List JavaDoc<URL JavaDoc> jarFiles = new ArrayList JavaDoc<URL JavaDoc>(jarFileNames.size() + 1);
309         String JavaDoc absolutePuRoot = getAbsolutePuRootFile().getAbsolutePath();
310         for (String JavaDoc jarFileName : jarFileNames) {
311             String JavaDoc nativeJarFileName = jarFileName.replace('/',
312                     File.separatorChar);
313             final File JavaDoc parentFile = new File JavaDoc(absolutePuRoot).getParentFile();
314             // only components are exploded, hence first look for original archives.
315
File JavaDoc jarFile = new File JavaDoc(parentFile, nativeJarFileName);
316             if (!jarFile.exists()) {
317                 // if the referenced jar is itself a component, then
318
// it might have been exploded, hence let's see
319
// if that is the case.
320

321                 // let's calculate the name component and path component from this URI
322
// e.g. if URI is ../../foo_bar/my-ejb.jar,
323
// name component is foo_bar/my-ejb.jar and
324
// path component is ../../
325
// These are my own notions used here.
326
String JavaDoc pathComponent = "";
327                 String JavaDoc nameComponent = jarFileName;
328                 if(jarFileName.lastIndexOf("../") != -1) {
329                     final int separatorIndex = jarFileName.lastIndexOf("../")+3;
330                     pathComponent = jarFileName.substring(0,separatorIndex);
331                     nameComponent = jarFileName.substring(separatorIndex);
332                 }
333                 logger.fine("For jar-file="+ jarFileName+ ", " +
334                         "pathComponent=" +pathComponent +
335                         ", nameComponent=" + nameComponent);
336                 jarFile = new File JavaDoc(new File JavaDoc(parentFile, pathComponent),
337                         FileUtils.makeFriendlyFileName(nameComponent));
338             }
339             if (jarFile.exists()) {
340                 try {
341                     jarFiles.add(jarFile.toURI().toURL());
342                 } catch (MalformedURLException JavaDoc e) {
343                     throw new RuntimeException JavaDoc(e);
344                 }
345             } else {
346                 // Should be a caught by verifier. So, just log a message
347
PersistenceUnitInfoImpl.logger.logp(Level.WARNING,
348                         "PersistenceUnitInfoImpl",
349                         "initJarFiles", "For pu-root {0}, \n" +
350                         "a jar-file specified in persistence.xml is not found.\n" +
351                         "Original name = {1}, and looked up name = {2}.",
352                         new Object JavaDoc[]{absolutePuRoot, jarFileName, jarFile});
353             }
354         }
355         return jarFiles;
356     }
357
358     private File JavaDoc getAbsolutePuRootFile() {
359         if (absolutePuRootFile == null) {
360             absolutePuRootFile = new File JavaDoc(applicationLocation,
361                     persistenceUnitDescriptor.getAbsolutePuRoot().replace('/',
362                             File.separatorChar));
363             if (!absolutePuRootFile.exists()) {
364                 throw new RuntimeException JavaDoc(
365                         absolutePuRootFile.getAbsolutePath() + " does not exist!");
366             }
367         }
368         return absolutePuRootFile;
369     }
370
371     /**
372      * This method first checks if default provider is specified in the
373      * environment (e.g. using -D option in domain.xml). If so, we use that.
374      * Else we defaults to TopLink.
375      *
376      * @return
377      */

378     private static String JavaDoc getDefaultprovider() {
379         final String JavaDoc DEFAULT_PERSISTENCE_PROVIDER_PROPERTY =
380                 "com.sun.persistence.defaultProvider"; // NOI18N
381
if(defaultProvider == null) {
382             defaultProvider =
383                     System.getProperty(DEFAULT_PERSISTENCE_PROVIDER_PROPERTY,
384                         DEFAULT_PROVIDER_NAME);
385         }
386
387         return defaultProvider;
388     }
389
390     /**
391      * Utility method to create a Jar file out of a directory.
392      * Right now this not used because TopLink Essential can handle
393      * exploded directories, but for better pluggability with different provoder
394      * we may have to do use this method to create a jar out of exploded dir.
395      *
396      * @param sourcePath is the source dir name.
397      * @param destinationPath is the target jar file that's going to be created.
398      * destinationPath first gets deleted if already
399      * exists.
400      * @throws java.io.IOException
401      */

402     private static void createJar(String JavaDoc sourcePath, String JavaDoc destinationPath)
403             throws IOException JavaDoc {
404         FileArchive source = new FileArchive();
405         OutputJarArchive destination = new OutputJarArchive();
406         try {
407             source.open(sourcePath);
408             destination.create(destinationPath);
409             for (Enumeration JavaDoc entries = source.entries();
410                  entries.hasMoreElements();) {
411                 String JavaDoc entry = String JavaDoc.class.cast(entries.nextElement());
412                 InputStream JavaDoc is = null;
413                 OutputStream JavaDoc os = null;
414                 try {
415                     is = source.getEntry(entry);
416                     os = destination.putNextEntry(entry);
417                     ArchivistUtils.copyWithoutClose(is, os);
418                 } finally {
419                     if (is != null) is.close();
420                     if (os != null) destination.closeEntry();
421                 }
422             }
423         } finally {
424             source.close();
425             destination.close();
426         }
427     }
428
429     private static boolean isNullOrEmpty(String JavaDoc s) {
430         return s == null || s.length() == 0;
431     }
432     
433     public static String JavaDoc getPersistenceProviderClassNameForPuDesc(
434             PersistenceUnitDescriptor persistenceUnitDescriptor) {
435         String JavaDoc provider = persistenceUnitDescriptor.getProvider();
436         if (isNullOrEmpty(provider)) {
437             provider = getDefaultprovider();
438         }
439         return provider;
440     }
441     
442 }
443
Popular Tags