Navigation Bar

Wednesday, January 23, 2002

java debug code

StockQuoteManagerFactoryIF.java
package org;

public interface StockQuoteManagerFactoryIF {
    public StockQuoteManagerIF createStockQuoteManager();
}


DbStockQuoteManagerFactoryIF.java
package org;

import javax.sql.DataSource;

/*
 * This is a factory for a DVDManager DAO using a database
 */
public interface DbStockQuoteManagerFactoryIF extends StockQuoteManagerFactoryIF {

   public DataSource getDataSource();

}

StockQuoteManagerIF.java
package org;

import java.util.Collection;

/*
 * This is a Data Access Object (DAO)
 */
public interface StockQuoteManagerIF {

   public void createStockQuote(String id, String title) throws DAOException;
   public void updateStockQuote(String id, String title) throws DAOException;
   public void deleteStockQuote(String id) throws DAOException;
   public Stock getStockQuote(String code) throws DAOException;
//   public Collection getAll() throws DAOException;
//   public Collection findStockCodeTitle(String title) throws DAOException;
   
}

CommonAction.java
package org;

import javax.servlet.ServletConfig;
import javax.servlet.http.*;
import javax.sql.DataSource;
import org.apache.log4j.Logger;

import org.apache.struts.action.*;

public abstract class CommonAction extends Action {

       protected final Logger log = Logger.getLogger(getClass());        
       
       public ActionForward execute(
          ActionMapping mapping,
          ActionForm form,
          HttpServletRequest request,
          HttpServletResponse response
          )
          throws DAOException, Exception {

           
          HttpSession session = request.getSession();
          
          if (session.getAttribute("quotefactory") == null) {
              // No factory factory created yet
              ServletConfig conf = servlet.getServletConfig();
              String managerName = conf.getInitParameter("quotefactory");
              
              log.debug("managerName " + managerName);
              
              DbStockQuoteManagerFactoryIF factory= null;
              
              if (managerName.equals("Database")) {
                  DataSource dataSource = getDataSource(request);
                  factory = new DbStockQuoteManagerFactory();
                  log.debug("after factory creation " );
               }else
               throw new DAOException("factory " + managerName + " is not known");
              
              session.setAttribute("managerName", managerName);
              session.setAttribute("quotefactory", factory);
              
          }
          
          log.debug("before commonExecute " );
          return commonExecute(mapping, form, request, response);
       }
       
       public abstract ActionForward commonExecute(
                  ActionMapping mapping,
                  ActionForm form,
                  HttpServletRequest request,
                  HttpServletResponse response) throws Exception;
}

DbStockQuoteManagerFactory.java
package org;

import java.io.PrintWriter;
import java.sql.*;

import javax.sql.DataSource;

/*
 * This is a factory for the StockQuoteManager DAO. It uses plain Db calls
 */
public class DbStockQuoteManagerFactory implements DbStockQuoteManagerFactoryIF {

   private DataSource dataSource;

   public DbStockQuoteManagerFactory() throws DAOException {
      //    Load the MySQL server Db driver
      String driverName = "org.gjt.mm.mysql.Driver";
      try {
         Class.forName(driverName);
      } catch (ClassNotFoundException e) {
         throw new DAOException("Db Driver " + driverName + " could not be loaded");
      }
      dataSource = new MyDataSource();
   }

   public DataSource getDataSource() {
      return dataSource;
   }

   public StockQuoteManagerIF createStockQuoteManager() {
      DatabaseStockQuoteManager manager = new DatabaseStockQuoteManager();
      manager.setDataSource(dataSource);
      return manager;
   }
   
   private class MyDataSource implements DataSource {

       public int getLoginTimeout() throws SQLException {
             return 0;
          }

          public void setLoginTimeout(int arg0) throws SQLException {
          }

          public PrintWriter getLogWriter() throws SQLException {
             return null;
          }

          public void setLogWriter(PrintWriter arg0) throws SQLException {
          }

      public Connection getConnection() throws SQLException {
         //    Create a connection to the database
         Connection conn = null;
         String serverName = "localhost";
         String mydatabase = "stocks";
//         String url = "Db:mysql://" + serverName + "/" + mydatabase;
         String url = "jdbc:mysql://localhost:3306/stocks?autoReconnect=true";
         String username = "root";
         String password = "mysql";
//         conn = DriverManager.getConnection(url, username, password);
         conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/stocks", "root","mysql");
         return conn;
      }
      
      public Connection getConnection(String arg0, String arg1) throws SQLException {
          return null;
       }

      public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; }

   public <T> T unwrap(Class<T> iface) throws SQLException { return null; }
    
   }

}

DatabaseStockQuoteManager.java
package org;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Dictionary;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

public class DatabaseStockQuoteManager implements StockQuoteManagerIF {

   private DataSource dataSource;
   
   protected final Logger log = Logger.getLogger(getClass());

   private static Logger logger =
     Logger.getLogger(DatabaseStockQuoteManager.class.getName());

   // Contains en Exception when an error has occured   
   private Exception error;
   // Contains an error message
   private String message;

   public void setDataSource(DataSource dataSource) {
      this.dataSource = dataSource;
   }

   public void createStockQuote(String id, String title) throws DAOException {
      
      Connection conn = null;
      PreparedStatement pstmt = null;
                     
   }

   
   
   public Stock getStockQuote(String sCode) throws DAOException {
      Connection conn = null;
      PreparedStatement pstmt = null;
      ResultSet result = null;
      error = null;
      Stock stockQuote = null;
      log.debug("DatabaseStockQuoteManager start");
      try {
         conn = dataSource.getConnection();
         if (conn != null && !conn.isClosed()){
            System.out.println("Connection Successful!");
                        
         } else {
            System.out.println("Connection is null or closed!");    
         }        
         log.debug("DatabaseStockQuoteManager.getStockQuote, code = " + sCode);
         String sql = "SELECT stock_name, price FROM stocks WHERE symbol=?";
         pstmt = conn.prepareStatement(sql);
         pstmt.setString(1, sCode);
         result = pstmt.executeQuery();
        
         if (result.next()) {
             log.debug("In getStockQuote " + result.getDouble("price"));
             stockQuote = new Stock();
             stockQuote.setPrice(result.getDouble("price"));
            
         } else {
            log.debug("No stock found for symbol " + sCode);
         }    
 
      } catch (SQLException e) {
         error = e;
         message = "Read failed";
         log.debug("In SQLException" + e.getMessage());
         e.printStackTrace();
      }
   
      closeResult(result);
      closePrep(pstmt);
      closeConnection(conn);
      checkOK();       
      
      return stockQuote;        
   }

   public void updateStockQuote(String id, String title) throws DAOException {
      if (getStockQuote(id) == null) throw new DAOException("Id " + id + " was not found");
      Connection conn = null;
      PreparedStatement pstmt = null;
      error = null;
      
                    
   }

   public void deleteStockQuote(String id) throws DAOException {
      if (getStockQuote(id) == null) throw new DAOException("Id " + id + " was not found");
      Connection conn = null;
      PreparedStatement pstmt = null;
      error = null;
      
                     
      
   }

   private void checkOK() throws DAOException {
      if (error != null) {
         throw new DAOException(message, error);
      }
   }
   
   private void closeConnection(Connection connection) {
      if (connection != null) {
         try {
            connection.close();
         } catch (SQLException e) {
            if (error == null) {
               error = e;
               message = "Close conn failed";
            }
         }
      }
   }

   private void closePrep(PreparedStatement prep) {
      if (prep != null) {
         try {
            prep.close();
         } catch (SQLException e) {
            if (error == null) {
               error = e;
               message = "Close prep failed";
            }
         }
      }
   }
   
   private void closeProc(CallableStatement proc) {
          if (proc != null) {
             try {
                proc.close();
             } catch (SQLException e) {
                if (error == null) {
                   error = e;
                   message = "Close proc failed";
                }
             }
          }
       }
   
   private void closeResult(ResultSet rs) {
      if (rs != null) {
         try {
            rs.close();
         } catch (SQLException e) {
            if (error == null) {
               error = e;
               message = "Close result failed";
            }
         }
      }
   }
   

}


No comments:

Post a Comment