01: package dinamica;
02:
03: import java.text.MessageFormat;
04: import javax.sql.DataSource;
05: import javax.naming.*;
06:
07: /**
08: * Provides easy API to obtain a datasource via JNDI
09: * <br>
10: * Creation date: 10/09/2003<br>
11: * Last Update: 10/09/2003<br>
12: * (c) 2003 Martin Cordova<br>
13: * This code is released under the LGPL license<br>
14: * @author Martin Cordova (dinamica@martincordova.com)
15: */
16: public class Jndi {
17:
18: /**
19: * Obtain a DataSource object using its JNDI name
20: * @param name Name of the DataSource like "jdbc/demo" or "java:comp/env/jdbc/demo"
21: * depending on your Server/JNDI provider<br>
22: * <br>
23: * <b>Sample code:</b><br>
24: * <pre>
25: * javax.sql.DataSource ds = Jndi.getDataSource("java:comp/env/jdbc/demo");
26: * java.sql.Connection conn = ds.getConnection();
27: * </pre>
28: * <br>
29: * Please keep in mind that some servers only accept "jdbc/demo" excluding
30: * the prefix "java:comp/env/", and may throw errors if you try to use the prefix,
31: * so it is a good idea to keep this String in a configuration file, like a context
32: * parameter in WEB.XML and load it at runtime, to make your WebApp more flexible and portable.
33: * @return DataSource to provide access to a connection pool
34: * @throws Throwable
35: */
36: public static DataSource getDataSource(String name)
37: throws Throwable {
38:
39: DataSource source = null;
40:
41: try {
42: Context ctx = new InitialContext();
43: source = (DataSource) ctx.lookup(name);
44: if (source == null) {
45: String args[] = { name };
46: String msg = Errors.DATASOURCE_NOT_FOUND;
47: msg = MessageFormat.format(msg, (Object[]) args);
48: throw new Throwable(msg);
49: } else {
50: return source;
51: }
52: } catch (Throwable e) {
53: throw e;
54: }
55:
56: }
57:
58: }
|