View Javadoc
1   package com.github.davidmoten.rx.jdbc;
2   
3   import java.sql.Connection;
4   import java.sql.SQLException;
5   
6   import javax.naming.Context;
7   import javax.naming.InitialContext;
8   import javax.naming.NamingException;
9   import javax.sql.DataSource;
10  
11  import com.github.davidmoten.rx.jdbc.exceptions.SQLRuntimeException;
12  
13  /**
14   * Provides database connections via a JNDI lookup.
15   */
16  public final class ConnectionProviderFromContext implements ConnectionProvider {
17  
18      private final String jndiResource;
19  
20      /**
21       * Constructor.
22       * 
23       * @param jndiResource the name to lookup
24       */
25      public ConnectionProviderFromContext(String jndiResource) {
26          this.jndiResource = jndiResource;
27      }
28  
29      @Override
30      public Connection get() {
31          try {
32              Context ctx = new InitialContext();
33              DataSource ds = (DataSource) ctx.lookup(jndiResource);
34              Connection conn = ds.getConnection();
35              return conn;
36          } catch (SQLException e) {
37              throw new SQLRuntimeException(e);
38          } catch (NamingException e) {
39              throw new RuntimeException(e);
40          }
41      }
42  
43      @Override
44      public void close() {
45          // do nothing
46      }
47  
48  }