1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.dbcp2;
19
20 import static org.junit.jupiter.api.Assertions.fail;
21
22 import java.util.Hashtable;
23
24 import javax.naming.Context;
25 import javax.naming.InitialContext;
26 import javax.naming.NamingException;
27 import javax.sql.DataSource;
28
29 import org.apache.commons.dbcp2.datasources.PerUserPoolDataSource;
30 import org.apache.commons.dbcp2.datasources.SharedPoolDataSource;
31 import org.junit.jupiter.api.AfterEach;
32 import org.junit.jupiter.api.BeforeEach;
33 import org.junit.jupiter.api.Test;
34
35
36
37
38
39 public class TestJndi {
40
41
42
43 protected static final String JNDI_SUBCONTEXT = "jdbc";
44
45
46
47
48 protected static final String JNDI_PATH = JNDI_SUBCONTEXT + "/"
49 + "jndiTestDataSource";
50
51
52 protected Context context;
53
54
55
56
57
58
59 protected void bindDataSource(final DataSource dataSource) throws Exception {
60 context.bind(JNDI_PATH, dataSource);
61 }
62
63
64
65
66
67
68
69 protected void checkBind(final DataSource dataSource) throws Exception {
70 bindDataSource(dataSource);
71 retrieveDataSource();
72 }
73
74
75
76
77
78
79
80
81 protected InitialContext getInitialContext() throws NamingException {
82 final Hashtable<String, String> environment = new Hashtable<>();
83 environment.put(Context.INITIAL_CONTEXT_FACTORY,
84 org.apache.naming.java.javaURLContextFactory.class.getName());
85 return new InitialContext(environment);
86 }
87
88
89
90
91
92
93 protected DataSource retrieveDataSource() throws Exception {
94 final Context ctx = getInitialContext();
95 final DataSource dataSource = (DataSource) ctx.lookup(JNDI_PATH);
96
97 if (dataSource == null) {
98 fail("DataSource should not be null");
99 }
100 return dataSource;
101 }
102
103 @BeforeEach
104 public void setUp() throws Exception {
105 context = getInitialContext();
106 context.createSubcontext(JNDI_SUBCONTEXT);
107 }
108
109 @AfterEach
110 public void tearDown() throws Exception {
111 context.unbind(JNDI_PATH);
112 context.destroySubcontext(JNDI_SUBCONTEXT);
113 }
114
115
116
117
118
119
120 @Test
121 public void testBasicDataSourceBind() throws Exception {
122 final BasicDataSource dataSource = new BasicDataSource();
123 checkBind(dataSource);
124 }
125
126
127
128
129
130
131 @Test
132 public void testPerUserPoolDataSourceBind() throws Exception {
133 final PerUserPoolDataSource dataSource = new PerUserPoolDataSource();
134 checkBind(dataSource);
135 }
136
137
138
139
140
141
142 @Test
143 public void testSharedPoolDataSourceBind() throws Exception {
144 final SharedPoolDataSource dataSource = new SharedPoolDataSource();
145 checkBind(dataSource);
146 }
147 }