package datasourcetest;


import java.sql.*;
import javax.transaction.*;
import javax.naming.Context;
import javax.sql.DataSource;
import java.util.Properties;
import javax.naming.InitialContext;


public class UserDAO {

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

   public UserDAO(){}


   public UserDTO getUserByName(String _username){
        UserDTO user=new UserDTO();
        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 where username='"+_username+"'";
            rs=stmt.executeQuery(sql);

            while(rs.next())
            {
            user.setUserName(rs.getString("username"));
            user.setPassword(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();}

        }
   return user;

   }

    public void insertUser(UserDTO user){}   //ÏêÏ¸¼û¹âÅÌ´úÂë
   public void updateUser(UserDTO user){}
   public void deleteUser(UserDTO user){}


   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");
     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;
  }
}
