Last active
March 14, 2019 16:35
-
-
Save srcmaxim/bb667cb1ad91329a16c1596093735681 to your computer and use it in GitHub Desktop.
JNDI DataSource implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.microsoft.sqlserver.jdbc.SQLServerDataSource; | |
import javax.naming.Context; | |
import javax.naming.InitialContext; | |
import javax.naming.NamingException; | |
import javax.naming.spi.InitialContextFactory; | |
import javax.sql.DataSource; | |
import java.util.Hashtable; | |
public class DataSourceHierarchyContextFactory implements InitialContextFactory { | |
private final Context hierarchy; | |
public DataSourceHierarchyContextFactory() { | |
DataSource dataSource = getDataSource("localhost", 0, "database", "username", "password"); | |
try { | |
hierarchy = getContextWrapper(getContextWrapper(dataSource)); | |
} catch (NamingException e) { | |
throw new IllegalStateException("Can't create Context", e); | |
} | |
} | |
@Override | |
public Context getInitialContext(Hashtable<?, ?> environment) { | |
return hierarchy; | |
} | |
private Context getContextWrapper(Object object) throws NamingException { | |
return new InitialContext(true) { | |
public Object lookup(String name) { | |
return object; | |
} | |
}; | |
} | |
private static DataSource getDataSource(String host, int port, String database, String user, String password) { | |
SQLServerDataSource ds = new SQLServerDataSource(); | |
ds.setServerName(host); | |
ds.setPortNumber(port); | |
ds.setDatabaseName(database); | |
ds.setUser(user); | |
ds.setPassword(password); | |
return ds; | |
} | |
} | |
import org.junit.BeforeClass; | |
import javax.naming.Context; | |
import javax.naming.NamingException; | |
public class JndiDataSourceTest { | |
@BeforeClass | |
public static void setup() throws NamingException { | |
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, DataSourceHierarchyContextFactory.class.getCanonicalName()); | |
} | |
@Test | |
public void createDataSource throws SQLException { | |
Context initContext = new InitialContext(); | |
Context envContext = (Context) initContext.lookup("java:/contexts/database"); | |
DataSource dataSource = (DataSource) envContext.lookup("application-connection"); | |
ResultSet resultSet = dataSource.getConnection().createStatement().executeQuery("SELECT 1"); | |
resultSet.next(); | |
int one = resultSet.getInt(1); | |
Assert.assertEquals(1, one); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Steps to create JNDI:
true
for lazy loading)