1 16 17 package org.springframework.jdbc.datasource; 18 19 import java.sql.Connection ; 20 import java.sql.SQLException ; 21 22 import org.springframework.util.Assert; 23 import org.springframework.util.StringUtils; 24 25 61 public class UserCredentialsDataSourceAdapter extends DelegatingDataSource { 62 63 private String username; 64 65 private String password; 66 67 private final ThreadLocal threadBoundCredentials = new ThreadLocal (); 68 69 70 78 public void setUsername(String username) { 79 this.username = username; 80 } 81 82 90 public void setPassword(String password) { 91 this.password = password; 92 } 93 94 95 105 public void setCredentialsForCurrentThread(String username, String password) { 106 this.threadBoundCredentials.set(new String [] {username, password}); 107 } 108 109 114 public void removeCredentialsFromCurrentThread() { 115 this.threadBoundCredentials.set(null); 116 } 117 118 119 126 public Connection getConnection() throws SQLException { 127 String [] threadCredentials = (String []) this.threadBoundCredentials.get(); 128 if (threadCredentials != null) { 129 return doGetConnection(threadCredentials[0], threadCredentials[1]); 130 } 131 else { 132 return doGetConnection(this.username, this.password); 133 } 134 } 135 136 140 public Connection getConnection(String username, String password) throws SQLException { 141 return doGetConnection(username, password); 142 } 143 144 155 protected Connection doGetConnection(String username, String password) throws SQLException { 156 Assert.state(getTargetDataSource() != null, "'targetDataSource' is required"); 157 if (StringUtils.hasLength(username)) { 158 return getTargetDataSource().getConnection(username, password); 159 } 160 else { 161 return getTargetDataSource().getConnection(); 162 } 163 } 164 165 } 166 | Popular Tags |