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

package org.huihoo.jfox.datasource;

import org.huihoo.jfox.datasource.PoolDataSource;
import org.huihoo.jfox.jndi.JNDIProperties;

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

/**
 *
 * @author <a href="mailto:kelvin_wym@hotmail.com">Kelvin Wu</a>
 */
public class Test {
  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 {
    System.setProperty("java.naming.factory.initial", JNDIProperties.INITIAL_CONTEXT_FACTORY);
    System.setProperty("java.naming.factory.url.pkgs", "org.huihoo.jfox.jndi");
    System.setProperty("java.naming.provider.url", JNDIProperties.PROVIDER_URL);
    Context ctx = new InitialContext();

    System.out.println("createSubcontext: yyy/zzz");
		ctx.createSubcontext("yyy/zzz");

    System.out.println("createSubcontext: yyy/zzz/aaa");
		ctx.createSubcontext("yyy/zzz/aaa");

    System.out.println("rebind: /yyy/zzz/mysqlDS");
    ctx.rebind("/yyy/zzz/mysqlDS",getDataSource());

    System.out.println("lookup: yyy/zzz/mysqlDS");
    Object ref = ctx.lookup("yyy/zzz/mysqlDS");

    System.out.println("Invoke method: ");
		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://192.168.0.2/mysql", "root", "");
    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));
    }
  }
}
