package datasourcetest;

import java.sql.*;
import javax.naming.*;
import javax.sql.*;
import java.util.Properties;
import javax.rmi.PortableRemoteObject;

public class DSTest {

    private static Context getInitialContext()
  {

   String url="t3://localhost:7001";
   String user="system";
   String password="11111111";
   Properties properties=null;
   Context context=null;

   try
    {
      properties = new Properties();
      properties.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");//com.sun.jndi.dns.DnsContextFactory
      properties.put(Context.PROVIDER_URL,url);
      properties.put(Context.SECURITY_PRINCIPAL,user);
      properties.put(Context.SECURITY_CREDENTIALS,password);
      context = new InitialContext(properties);

    }

    catch(Exception e)
     {
      e.printStackTrace();
     }

     return context;
  }

    public static void main(String[] args) {
        DSTest dstest = new DSTest();

        DataSource ds=null;
        Context ctx=null;
        Connection conn=null;

        try{

            ctx=getInitialContext();
            ds=(DataSource)ctx.lookup("MyDataSource");

        }catch(Exception e){e.printStackTrace();}

        Statement stmt=null;
        ResultSet rs=null;

        try{
            conn=ds.getConnection();
            stmt=conn.createStatement();
            String sql="select * from user";
            rs=stmt.executeQuery(sql);

            while(rs.next())
            {
            System.out.println("username:" + rs.getString("username"));
            System.out.println("password:" + rs.getString("password"));
            }

        }catch(SQLException e){e.printStackTrace();}
        finally{
        try{
        if(stmt!=null){stmt.close();}
        if(conn!=null){conn.close();}

        }catch(SQLException e){e.printStackTrace();}

        }


    }
}
