DB link pool

/*
 * 创建日期 2010-10-22
 *
 * TODO 要更改此生成的文件的模板,请转至
 * 窗口 - 首选项 - Java - 代码样式 - 代码模板
 */
package common.db;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import java.io.File;
import java.util.Hashtable;
import java.util.List;
import java.util.ArrayList;

public class DBPool 
{
	static Logger logger = Logger.getLogger(DBPool.class);
	
	// 为了以后支持多数据库,所以也需要多数据库连接池
	public static String JNDI_ROOT = "D:\\Tomcat 5.0\\conf\\Catalina\\localhost";

	public static String jndiFileName = "hardware.xml";

	private static Hashtable<String, DataSource> poolList = new Hashtable<String, DataSource>();

	static {
		String dbName = "";
		String jndiName = "";

		ArrayList list = getAllDbName();
		
		try {
			InitialContext ctx = new InitialContext();

			for (int i = 0; i < list.size(); i++) {

				dbName=list.get(i).toString();
				
				jndiName = "java:comp/env/jdbc/" + dbName;
				System.out.println("JNDIName:"+jndiName);

				DataSource pool = (DataSource) ctx.lookup(jndiName);
				if (pool != null) {
					poolList.put(dbName, pool);

					//System.out.println("数据库联接成功"+pool.toString());
				} else {
					//System.out.println("数据库联接失败");
				}
			}
		} catch (NamingException ne) {
			ne.printStackTrace();
		}
	}

	public static DataSource getPool(String dbName) {
		return (DataSource) poolList.get(dbName);
	}

	public static ArrayList getAllDbName() {
		ArrayList<String> list = new ArrayList<String>();

		Document doc = null;
		try {
			SAXBuilder builder = new SAXBuilder();
			doc = builder.build(new File(JNDI_ROOT+"\\"+jndiFileName));

			// System.out.println("good");
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		Element root = doc.getRootElement();// 获得根元素element
		// System.out.println(root.getAttribute("docBase").getValue());

		List resourceList = root.getChildren("Resource");

		Element resource;
		String resourceName = "";
		String dbName = "";

		for (int i = 0; i < resourceList.size(); i++) {
			resource = (Element) resourceList.get(i);
			resourceName = resource.getAttribute("name").getValue();
			dbName = resourceName.substring("jdbc/".length(), resourceName
					.length());

			list.add(dbName);
		}

		return list;
	}

	public static void main(String[] args) {
		DBPool.getAllDbName();
	}
}

你可能感兴趣的:(java,sql,tomcat,log4j,jdbc)