1    package com.instantbank.collections.util;
2    
3    /**
4     * Service Locator.
5     *
6     * Encapsulates the lookup and creation of Enterprise Java Beans
7     *
8     * @author Guillermo Posse
9     */
10   
11   import java.sql.Connection;
12   import java.sql.SQLException;
13   import java.util.Properties;
14   import javax.naming.Context;
15   import javax.naming.InitialContext;
16   import javax.naming.NamingException;
17   import javax.rmi.PortableRemoteObject;
18   import javax.sql.DataSource;
19   
20   public class ServiceLocator extends Object {
21     private String dataSource = "instantbank";
22     private String providerUrl = "t3://localhost:7017";
23     private String jndiEjbPath = "instantbank/EJB";
24     private static ServiceLocator theServiceLocator = new ServiceLocator();
25   
26   
27     public ServiceLocator() { }
28   
29   
30     public static ServiceLocator instance() {
31       return theServiceLocator;
32     }
33   
34   
35     public Object createEJB(String home, Class theClass, boolean local) throws Exception {
36       // local argument true forced to true because application integrated in .ear file
37       Context ctx = getInitialContext(true);
38       Object ref = ctx.lookup(jndiEjbPath + "/" + home);
39       if(local) {
40         return ref;
41       }
42       else {
43         return PortableRemoteObject.narrow(ref, theClass);
44       }
45     }
46   
47   
48     public Connection getConnection() throws NamingException, SQLException {
49       Connection conn = null;
50       InitialContext initCtx = null;
51       try {
52         initCtx = new InitialContext();
53         DataSource ds = (javax.sql.DataSource)initCtx.lookup(dataSource);
54         conn = ds.getConnection();
55         return conn;
56       }
57       catch(NamingException ne) {
58         throw ne;
59       }
60       catch(SQLException se) {
61         throw se;
62       }
63       finally {
64         if(initCtx != null) {
65           initCtx.close();
66         }
67       }
68     }
69   
70   
71     private Context getInitialContext(boolean local) throws Exception {
72       if(local) {
73         return new InitialContext();
74       }
75       else {
76         Properties p = new Properties();
77         p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
78         p.put(Context.PROVIDER_URL, providerUrl);
79         return new InitialContext(p);
80       }
81     }
82   
83   
84     public void setDataSource(String dataSource) {
85       this.dataSource = dataSource;
86     }
87   
88   
89     public void setJndiEjbPath(String jndiEjbPath) {
90       this.jndiEjbPath = jndiEjbPath;
91     }
92   
93   
94     public void setProviderUrl(String providerUrl) {
95       this.providerUrl = providerUrl;
96     }
97   }
98   
99