package com.ankurm.hibernatedemo.jndi; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import java.sql.SQLException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NameAlreadyBoundException; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import javax.sql.DataSource; import org.h2.jdbcx.JdbcDataSource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Backs docs/10-mocking-jndi-datasources.md (post 4871 rewrite), chapter "Getting simple-jndi 0.25.0 actually * working". Uses {@code org.osjava.sj.MemoryContextFactory} directly -- no root properties * file needed for a pure in-memory bind/lookup within one JVM. Every test here sets * {@code java.naming.factory.initial} itself in {@code @BeforeEach} and clears the JVM-wide * JNDI environment in {@code @AfterEach}, on purpose: JNDI's {@code InitialContext} is backed * by static, JVM-global state (see {@code CrossTestPollutionTest} for what happens when this * discipline is skipped). */ class JndiDataSourceResolutionTest { private static final Logger DEMO = LoggerFactory.getLogger("DEMO"); private static final String JNDI_NAME = "java:comp/env/jdbc/TestDS"; @BeforeEach void setJndiFactory() { System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.osjava.sj.MemoryContextFactory"); // Without this, org.osjava.sj.MemoryContextFactory.getInitialContext() hands back a // BRAND NEW org.osjava.sj.jndi.MemoryContext on every single `new InitialContext()` // call (confirmed via javap -c on MemoryContextFactory.class: it branches on this exact // property name before deciding whether to consult its static, shared context cache). // Real application code calls `new InitialContext()` in more than one place -- a DAO // here, a test's @BeforeAll there -- so without this flag, a bind() in one InitialContext // instance is invisible to a lookup() via a different instance, even in the same test. System.setProperty("org.osjava.sj.jndi.shared", "true"); } @AfterEach void clearJndiFactory() throws NamingException { try { new InitialContext().unbind(JNDI_NAME); } catch (NamingException ignored) { // not bound -- fine } System.clearProperty(Context.INITIAL_CONTEXT_FACTORY); System.clearProperty("org.osjava.sj.jndi.shared"); } @Test void bindDataSourceIntoMockJndi_andLookItUpByName() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:jnditestdb;DB_CLOSE_DELAY=-1"); ds.setUser("sa"); ds.setPassword(""); Context ctx = new InitialContext(); createSubcontextIfAbsent(ctx, "java:"); createSubcontextIfAbsent(ctx, "java:comp"); createSubcontextIfAbsent(ctx, "java:comp/env"); createSubcontextIfAbsent(ctx, "java:comp/env/jdbc"); ctx.rebind(JNDI_NAME, ds); DataSource looked = (DataSource) new InitialContext().lookup(JNDI_NAME); assertThat(looked).isNotNull(); try (var conn = looked.getConnection()) { assertThat(conn.isValid(2)).isTrue(); DEMO.info("looked-up DataSource produced a valid connection: {}", conn.getMetaData().getURL()); } } @Test void noInitialContextFactoryProperty_throwsNoInitialContextException() { System.clearProperty(Context.INITIAL_CONTEXT_FACTORY); javax.naming.NoInitialContextException ex = assertThrows( javax.naming.NoInitialContextException.class, () -> new InitialContext().lookup("java:comp/env/jdbc/Anything")); DEMO.info("verbatim NoInitialContextException message: {}", ex.getMessage()); assertThat(ex.getMessage()).contains("Need to specify class name in environment or system property"); assertThat(ex.getMessage()).contains(Context.INITIAL_CONTEXT_FACTORY); } @Test void lookupOfUnboundName_throwsNameNotFoundException() throws NamingException { Context ctx = new InitialContext(); NameNotFoundException ex = assertThrows(NameNotFoundException.class, () -> ctx.lookup("java:comp/env/jdbc/DoesNotExist")); DEMO.info("verbatim NameNotFoundException message: {}", ex.getMessage()); } // See docs/10-mocking-jndi-datasources.md's cross-test-pollution chapter -- this suite tripped over its own // advice the first time it ran as a whole rather than one class at a time. private static void createSubcontextIfAbsent(Context ctx, String name) throws Exception { try { ctx.createSubcontext(name); } catch (NameAlreadyBoundException alreadyThere) { // fine -- another test in this JVM already created it } } }