/* JFox, the OpenSource J2EE Application Server
 *
 * Copyright (C) 2002 huihoo.com
 * Distributable under GNU LGPL license
 * See the GNU Lesser General Public License for more details.
 */

package org.jfox.jdbc.datasource;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;

import org.jfox.jdbc.datasource.PoolDataSource;

/**
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class DataSourceTest {
  public static void main(String[] args) throws Exception {
    System.out.println("Test Generic Usage:");
    testGenericUsage();
    System.out.println();System.out.println();
    System.out.println("Test JNDI Usage:");
    testJNDIUsage();
  }

  public static void testGenericUsage() throws Exception {
    DataSource ds = getDataSource();
    Connection conn = ds.getConnection();
    executeSQL(conn);
  }

  public static void testJNDIUsage() throws Exception {
    Context ctx = new InitialContext();
    ctx.rebind("/yyy/zzz/mysqlDS",getDataSource());
    Object ref = ctx.lookup("yyy/zzz/mysqlDS");
        DataSource ds = (DataSource)(ref);
    Connection conn = ds.getConnection();
    executeSQL(conn);
    Connection conn2 = ds.getConnection();
    executeSQL(conn2);

  }

  public static DataSource getDataSource() throws Exception {
    PoolDataSource ds = new PoolDataSource("org.gjt.mm.mysql.Driver",
        "jdbc:mysql://localhost/mysql", "root", "");
    ds.init();
    return ds;
//    return new PoolDataSource();
  }

  public static void executeSQL(Connection conn) throws Exception {
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select * from user");
    while (rs.next()) {
      System.out.println(rs.getString(2));
    }
  }
}