package ejava.examples.ejb.session.bean;

import ejava.examples.ejb.session.dao.AccountDAO;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.EJBException;
import javax.naming.*;
import javax.sql.DataSource;
import java.sql.*;
import java.util.*;

public class QueryEJB implements SessionBean {
   transient Connection connection_;
   transient AccountDAO dao_;
   
   public Collection getAllAccounts(int maxrows) {
      try {
         Collection accounts = null;
         if (dao_ != null) {
            accounts = dao_.getAll(connection_, maxrows);
            if (accounts.size() < maxrows) { close(); }
	 }
	 else {
	    accounts = new Vector();
	 }
         return accounts;
      }
      catch (SQLException sqlex) {
         close();
         throw new EJBException(sqlex);
      }
   }

   public Collection getNext(int maxrows) {
      try {
         Collection accounts = null;
         if (dao_ != null) {
            accounts = dao_.getNext(maxrows);
            if (accounts.size() < maxrows) { close(); }
         }
	 else {
	    accounts = new Vector();
	 }
         return accounts;
      }
      catch (SQLException sqlex) {
         close();
	 throw new EJBException(sqlex);
      }
   }

   public void ejbCreate() {
      try {
         dao_ = new AccountDAO();
	 Context jndi = new InitialContext();
	 DataSource dataSource =
	    (DataSource)jndi.lookup("java:comp/env/jdbc/mydb");
         connection_ = dataSource.getConnection();
	 connection_.setAutoCommit(false);
      }
      catch (NamingException ex) {
         close();
         throw new EJBException(ex);
      }
      catch (SQLException ex) {
         close();
         throw new EJBException(ex);
      }
   }

   public void ejbActivate() { throw new EJBException("bean timed out"); }
   public void ejbPassivate() { close(); }
   public void ejbRemove() { close(); }
   
   public void close() {
      try { if (dao_ != null) dao_.close(); } 
      catch (Exception ignored) {}
      try { if (connection_ != null) connection_.close(); }
      catch (Exception ignored) {}
      dao_ = null;
      connection_ = null;
   }

   public void setSessionContext(SessionContext ctx) { }
}

