KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > web > struts > _DataSource


1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 2 of the License, or
5  * (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU Library General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15  */

16 package web.struts;
17
18 import java.io.Serializable JavaDoc;
19 import java.lang.reflect.*;
20 import java.sql.Connection JavaDoc;
21 import javax.sql.DataSource JavaDoc;
22
23 /**
24  * 数据源对象的接管,由于Struts本身使用的是dbcp连接池
25  * 此类就是接管DataSource接口
26  * @author Winter Lau
27  */

28 class _DataSource implements InvocationHandler, Serializable JavaDoc {
29
30     private final static Class JavaDoc[] infs = new Class JavaDoc[]{DataSource JavaDoc.class};
31     
32     public _DataSource(DataSource JavaDoc ds, boolean encoding) {
33         dataSource = ds;
34         this.encoding = encoding;
35     }
36
37     /**
38      * 获取DataSource的代理
39      * @return
40      */

41     public DataSource JavaDoc getDataSource() {
42         return (DataSource JavaDoc) Proxy.newProxyInstance(
43             dataSource.getClass().getClassLoader(), infs, this);
44     }
45
46     public Object JavaDoc invoke(Object JavaDoc proxy, Method m, Object JavaDoc args[]) throws Throwable JavaDoc
47     {
48         if (METHOD_NAME.equals(m.getName())){
49             try {
50                 Connection JavaDoc conn = (Connection JavaDoc) m.invoke(dataSource, args);
51                 return (conn==null)?null:(new _Connection(conn,encoding)).getConnection();
52             } catch (InvocationTargetException e) {
53                 throw e.getTargetException();
54             }
55         }
56         try {
57             return m.invoke(dataSource, args);
58         } catch (InvocationTargetException e) {
59             throw e.getTargetException();
60         }
61     }
62
63     private DataSource JavaDoc dataSource;
64
65     private boolean encoding;
66
67     private final static String JavaDoc METHOD_NAME = "getConnection";
68 }
Popular Tags