1   package org.davidmoten.rxjava3.jdbc;
2   
3   import java.sql.Connection;
4   import java.sql.DriverManager;
5   import java.sql.SQLException;
6   import java.util.Properties;
7   
8   import javax.annotation.Nonnull;
9   
10  import org.davidmoten.rxjava3.jdbc.exceptions.SQLRuntimeException;
11  import org.davidmoten.rxjava3.jdbc.internal.SingletonConnectionProvider;
12  
13  import com.github.davidmoten.guavamini.Preconditions;
14  
15  
16  
17  
18  
19  
20  public interface ConnectionProvider {
21  
22      
23  
24  
25  
26  
27      @Nonnull
28      Connection get();
29  
30      
31  
32  
33  
34  
35  
36      void close();
37  
38      
39  
40  
41  
42  
43  
44  
45  
46  
47      static ConnectionProvider from(@Nonnull Connection connection) {
48          Preconditions.checkNotNull(connection, "connection  cannot be null");
49          return new SingletonConnectionProvider(connection);
50      }
51  
52      static ConnectionProvider from(@Nonnull String url) {
53          Preconditions.checkNotNull(url, "url cannot be null");
54          return new ConnectionProvider() {
55  
56              @Override
57              public Connection get() {
58                  try {
59                      return DriverManager.getConnection(url);
60                  } catch (SQLException e) {
61                      throw new SQLRuntimeException(e);
62                  }
63              }
64  
65              @Override
66              public void close() {
67                  
68              }
69          };
70      }
71  
72      static ConnectionProvider from(@Nonnull String url, String username, String password) {
73          Preconditions.checkNotNull(url, "url cannot be null");
74          return new ConnectionProvider() {
75  
76              @Override
77              public Connection get() {
78                  try {
79                      return DriverManager.getConnection(url, username, password);
80                  } catch (SQLException e) {
81                      throw new SQLRuntimeException(e);
82                  }
83              }
84  
85              @Override
86              public void close() {
87                  
88              }
89          };
90      }
91      
92      static ConnectionProvider from(@Nonnull String url, Properties properties) {
93          Preconditions.checkNotNull(url, "url cannot be null");
94          Preconditions.checkNotNull(properties, "properties cannot be null");
95          return new ConnectionProvider() {
96  
97              @Override
98              public Connection get() {
99                  try {
100                     return DriverManager.getConnection(url, properties);
101                 } catch (SQLException e) {
102                     throw new SQLRuntimeException(e);
103                 }
104             }
105 
106             @Override
107             public void close() {
108                 
109             }
110         };
111     }
112 
113 }