KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > dinamica > Jndi


1 package dinamica;
2
3 import java.text.MessageFormat JavaDoc;
4 import javax.sql.DataSource JavaDoc;
5 import javax.naming.*;
6
7 /**
8  * Provides easy API to obtain a datasource via JNDI
9  * <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     /**
20      * Obtain a DataSource object using its JNDI name
21      * @param name Name of the DataSource like "jdbc/demo" or "java:comp/env/jdbc/demo"
22      * depending on your Server/JNDI provider<br>
23      * <br>
24      * <b>Sample code:</b><br>
25      * <pre>
26      * javax.sql.DataSource ds = Jndi.getDataSource("java:comp/env/jdbc/demo");
27      * java.sql.Connection conn = ds.getConnection();
28      * </pre>
29      * <br>
30      * Please keep in mind that some servers only accept "jdbc/demo" excluding
31      * the prefix "java:comp/env/", and may throw errors if you try to use the prefix,
32      * so it is a good idea to keep this String in a configuration file, like a context
33      * parameter in WEB.XML and load it at runtime, to make your WebApp more flexible and portable.
34      * @return DataSource to provide access to a connection pool
35      * @throws Throwable
36      */

37     public static DataSource JavaDoc getDataSource(String JavaDoc name) throws Throwable JavaDoc
38     {
39
40         DataSource JavaDoc source = null;
41
42         try
43         {
44             Context ctx = new InitialContext();
45             source = (DataSource JavaDoc) ctx.lookup( name );
46             if (source==null)
47             {
48                 String JavaDoc args[] = { name };
49                 String JavaDoc msg = Errors.DATASOURCE_NOT_FOUND;
50                 msg = MessageFormat.format(msg, args);
51                 throw new Throwable JavaDoc(msg);
52             }
53             else
54             {
55                 return source;
56             }
57         }
58         catch ( Throwable JavaDoc e )
59         {
60            throw e;
61         }
62                 
63     }
64
65 }
66
Popular Tags