(no commit message)
[utils] / test / toplink-essentials / src / main / java / org / wamblee / support / persistence / toplink / JndiSessionCustomizer.java
1 package org.wamblee.support.persistence.toplink;
2
3 import javax.naming.Context;
4 import javax.naming.InitialContext;
5
6 import oracle.toplink.essentials.jndi.JNDIConnector;
7 import oracle.toplink.essentials.sessions.DatabaseLogin;
8 import oracle.toplink.essentials.sessions.Session;
9 import oracle.toplink.essentials.threetier.ServerSession;
10 import oracle.toplink.essentials.tools.sessionconfiguration.SessionCustomizer;
11  
12 /**
13  * See http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG) Use for clients that would like to use a
14  * JTA SE pu instead of a RESOURCE_LOCAL SE pu.
15  * 
16  * This utility also makes sure that using a persistence.xml with a JTA datasource works in a standalone Java SE 
17  * environment together with our JNDI stub. 
18  */
19 public class JndiSessionCustomizer
20     implements SessionCustomizer {
21         
22         public JndiSessionCustomizer() {
23                 // Empty.
24         }
25  
26   /**
27    * Get a dataSource connection and set it on the session with lookupType=STRING_LOOKUP
28    */
29   public void customize(Session session) throws Exception {
30     JNDIConnector connector = null;
31     Context context = null;
32     try {
33       context = new InitialContext();
34       if(null != context) {
35         connector = (JNDIConnector)session.getLogin().getConnector(); // possible CCE
36         // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP
37         // Note: if both jta and non-jta elements exist this will only change the first one - and may still result in
38         // the COMPOSITE_NAME_LOOKUP being set
39         // Make sure only jta-data-source is in persistence.xml with no non-jta-data-source property set
40         connector.setLookupType(JNDIConnector.STRING_LOOKUP);
41  
42         // Or, if you are specifying both JTA and non-JTA in your persistence.xml then set both connectors to be safe
43         JNDIConnector writeConnector = (JNDIConnector)session.getLogin().getConnector();
44         writeConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
45         JNDIConnector readConnector =
46             (JNDIConnector)((DatabaseLogin)((ServerSession)session).getReadConnectionPool().getLogin()).getConnector();
47         readConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
48  
49         System.out.println("JndiSessionCustomizer: configured " + connector.getName());
50       }
51       else {
52         throw new Exception("JndiSessionCustomizer: Context is null");
53       }
54     }
55     catch(Exception e) {
56       e.printStackTrace();
57     }
58   }
59 }