[oak perl] Abstract Factory pattern source code

Edwin s edwincime at yahoo.com
Wed Aug 13 18:23:42 CDT 2003


Skipped content of type multipart/alternative-------------- next part --------------
/**
 * Author:      http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
 * Date:
 * Purpose:  Implementing Factory for Data Access Objects Strategy
 *           This encapsulates the details of the database implementation
 *
 * Design Pattern "Abstract Factory"
 *
 * Using the terms from Design Patterns book, here are the participants
 * AbstractFactory    - DAOFactory
 * ConcreteFactory    - MysqlDAOFactory, XmlDAOFactory, PostgresDAOFactory
 * AbstractProduct    - LoginDAO, CompanyDAO
 * ConcreteProduct    - MysqlLoginDAO, MysqlCompanyDAO, etc
 *
 *
 * Design Patterns, Gamma, Helm, Johnson, Vlissides,  pages 87 - 95
 * see also Java Design Patterns, James Cooper, pages 33 - 38
*/
// Abstract class DAO Factory
public abstract class DAOFactory {

  // List of DAO types supported by the factory
  public static final int MYSQL       = 1;
  public static final int XML         = 2;
  public static final int POSTGRES    = 3; // tdb
  //...

  // There will be a method for each DAO that can be
  // created. The concrete factories will have to
  // implement these methods.
  public abstract LoginDAO   getLoginDAO();
  public abstract CompanyDAO getCompanyDAO();
  //...

  public static int getConstant (String value) {
    if (value.equalsIgnoreCase("MYSQL")) return MYSQL;
    if (value.equalsIgnoreCase("XML")) return XML;
    return 0;
  }

  public static DAOFactory getDAOFactory(
      int whichFactory) {

    switch (whichFactory) {
      case MYSQL:
          return new MysqlDAOFactory();
      case XML:
          return new XmlDAOFactory();
      //case POSTGRES:
      //    return new PostgresDAOFactory();
      //...
      default           :
          return null;
    }
  }
}

"DAOFactory.java" 57L, 1749C                                  57,0-1        Bot

********************************************************************************************
********************************************************************************************
********************************************************************************************

import java.sql.Connection;
import java.sql.SQLException;

public class MysqlDAOFactory extends DAOFactory {
    private static ConnectionPool connectionPool;

    // class constants
    // Candidate for putting into a config file or constants class
    //
    // Move this up to the class MysqlDAOFactory
    private static final String dbUrl = "jdbc:mysql://";
    private static final String hostName = "localhost";
    private static final String databaseName = "sampledb";
    private static final String connName = dbUrl + hostName+"/"+databaseName;
    private static final String connectURL = dbUrl + hostName+"/"+databaseName;
    private static final String uName = "root";
    private static final String pWord = "r8ssi2n";
    private static final String driverName = "org.gjt.mm.mysql.Driver";

    public MysqlDAOFactory() {
    }

    // uses singleton pattern
    public static Connection getConnection() {
        if (connectionPool==null) {
            connectionPool = new ConnectionPool(connectURL,
                                                uName,
                                                pWord,
                                                driverName);
        } // end if stmt
        return connectionPool.getConnection();
    }

    public static void closeConnection(Connection conn) {
        if (connectionPool!=null) {
            connectionPool.closeConnection(conn);  // closes a connection
        }
    }

    public static void release() throws ApplicationException {
        try {
            if (connectionPool!=null) {
                connectionPool.release();  // closes all connections opened
            }
        }
        catch (SQLException e) {
            throw new ApplicationException(e.getMessage());
        }
    }

    public LoginDAO getLoginDAO() {
        return new MysqlLoginDAO();
    }

    public CompanyDAO getCompanyDAO() {
        return new MysqlCompanyDAO();
    }
}
"MysqlDAOFactory.java" 59L, 1954C                             59,1          Bot

********************************************************************************************
********************************************************************************************
********************************************************************************************
public class XmlDAOFactory extends DAOFactory {

    private static DocumentBuilderFactory documentBuilderFactory;
    private static DocumentBuilder documentBuilder;
    private static Document document;

    public final static String LOCATION = "/usr/jwsdp11/webapps/ado/xml/company.xml";

    private static void init() throws ApplicationException {
        try {
            documentBuilderFactory = DocumentBuilderFactory.newInstance();
            //documentBuilderFactory.setValidating(true);
            documentBuilder = documentBuilderFactory.newDocumentBuilder();

            ErrorHandler h = new MyErrorHandler();
            documentBuilder.setErrorHandler(h);
            File file = new File(LOCATION);
            document = documentBuilder.parse(file);
        }
        catch (SAXException e) {
            throw new ApplicationException (e.getMessage());
        }
        catch (ParserConfigurationException e) {
            throw new ApplicationException (e.getMessage());
        }
        catch (IOException e) {
            throw new ApplicationException (e.getMessage());
        }
    }

    // class constants
    // Candidate for putting into a config file or constants class
    //
    // Move this up to the class MysqlDAOFactory

    public XmlDAOFactory() {
    }

    public static void release() {
    }

    public static void close() {
    }

    // uses singleton pattern
    public static Document getDocument() throws ApplicationException {
        if (document==null) {
            init();
        }
        return document;
    }


    public LoginDAO getLoginDAO() {
        return null;
    }

    public CompanyDAO getCompanyDAO() {
        return new XmlCompanyDAO();
    }

    public static void main (String args[]) {

        System.out.println ("----- XmlDAOFactory.main() ----- ");

      try {
        Document doc = XmlDAOFactory.getDocument();
        NodeList nl = doc.getElementsByTagName("company_record");
        System.out.println ("Number of nodes in nl list = " + nl.getLength());
        Node node0 = nl.item(0);
        System.out.println (" ====== node0 ===== ");
        System.out.println (node0);
        Node node1 = nl.item(1);
        System.out.println (" ====== node1 ===== ");
        System.out.println (node1);
        NodeList n2 = doc.getElementsByTagName("company_record");
        //System.out.println ("Number of nodes in n2 list = " + n2.getLength());
        System.out.println (" ============= output of doc.write ============== " );

        String location = "/usr/jwsdp11/webapps/ado/src/company.xml";
        File file = new File(location);
        InputSource input = Resolver.createInputSource(file);
        XmlDocument xmlDoc = XmlDocument.createXmlDocument(input, true);
        xmlDoc.getDocumentElement().normalize();
        xmlDoc.write (System.out);
      }
      catch (Exception e) {
      }

    }

    // private class
    private static class MyErrorHandler implements ErrorHandler {
      public void warning(SAXParseException e) throws SAXException {
         System.out.println("Warning: ");
         printInfo(e);
      }
      public void error(SAXParseException e) throws SAXException {
         System.out.println("Error: ");
         printInfo(e);
      }
      public void fatalError(SAXParseException e) throws SAXException {
         System.out.println("Fattal error: ");
         printInfo(e);
      }
      private void printInfo(SAXParseException e) {
         System.out.println("   Public ID: "+e.getPublicId());
         System.out.println("   System ID: "+e.getSystemId());
         System.out.println("   Line number: "+e.getLineNumber());
         System.out.println("   Column number: "+e.getColumnNumber());
         System.out.println("   Message: "+e.getMessage());
      }
   }


}
"XmlDAOFactory.java" 135L, 4299C                              135,1         Bot

********************************************************************************************
********************************************************************************************
********************************************************************************************

// MysqlCompanyDAO implementation of the
// CompanyDAO interface. This class can contain all
// MySQL specific code and SQL statements.
// The client is thus shielded from knowing
// these implementation details.

import java.sql.*;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Collection;

public class MysqlCompanyDAO implements
    CompanyDAO {

    public MysqlCompanyDAO() {
        // initialization
    }

    public int insertCompany(Company company) throws ApplicationException {
        Connection connection = MysqlDAOFactory.getConnection();
        String ps = "insert into company values (?, ?, ?, ?, ?, ?, ?, ?)";
        int result = 0;
        try {
            PreparedStatement pStatement = connection.prepareStatement(ps);
            pStatement.setString(1, company.getCompany());
            pStatement.setString(2, company.getEmail());
            pStatement.setString(3, company.getJobTitle());
            pStatement.setString(4, company.getDescription());
            pStatement.setString(5, company.getDate());
            pStatement.setString(6, company.getSource());
            pStatement.setString(7, company.getContact());
            pStatement.setString(8, company.getComment());
            result = pStatement.executeUpdate();
            if (pStatement!=null) pStatement.close();
            if (connection!=null) MysqlDAOFactory.closeConnection(connection);
        }
        catch (SQLException e) {
            throw new ApplicationException(e.getMessage());
        }
        return result;
    }

    public int deleteCompany(String company) throws ApplicationException {
        Connection connection = MysqlDAOFactory.getConnection();
        String ps = "delete from company where company = ?";
        int result = 0;
        try {
            PreparedStatement pStatement = connection.prepareStatement(ps);
            pStatement.setString(1, company);
            result = pStatement.executeUpdate();
            if (pStatement!=null) pStatement.close();
            if (connection!=null) MysqlDAOFactory.closeConnection(connection);
        }
        catch (SQLException e) {
            throw new ApplicationException(e.getMessage());
        }
        return result;
    }

    public Company findCompany(String company) throws ApplicationException {
        Company companyData = new Company();
        Connection connection = MysqlDAOFactory.getConnection();
        String ps = "select * from company where company = ?";
        try {
            PreparedStatement pStatement = connection.prepareStatement(ps);
            pStatement.setString(1, company);
            ResultSet rs = pStatement.executeQuery();
            if (rs!=null) {
                rs.next(); // move into 1st position
                companyData.setCompany(rs.getString("company"));
                companyData.setEmail(rs.getString("email"));
                companyData.setJobTitle(rs.getString("jobTitle"));
                companyData.setDescription(rs.getString("description"));
                companyData.setDate(rs.getDate("date").toString());
                companyData.setSource(rs.getString("source"));
                companyData.setContact(rs.getString("contact"));
                companyData.setComment(rs.getString("comment"));
            }
            if (rs!=null) rs.close();
            if (pStatement!=null) pStatement.close();
            if (connection!=null) MysqlDAOFactory.closeConnection(connection);
        }
        catch (SQLException e) {
            throw new ApplicationException(e.getMessage());
        }
        return companyData;

    }

    public int updateCompany(Company company) throws ApplicationException {
        Connection connection = MysqlDAOFactory.getConnection();
        String ps = "update company set email = ?, jobTitle = ?, description = ?, date = ?, source = ?, contact = ?, comment = ? where company = ?";
        int result = 0;
        try {
            PreparedStatement pStatement = connection.prepareStatement(ps);
            pStatement.setString(1, company.getEmail());
            pStatement.setString(2, company.getJobTitle());
            pStatement.setString(3, company.getDescription());
            pStatement.setString(4, company.getDate());
            pStatement.setString(5, company.getSource());
            pStatement.setString(6, company.getContact());
            pStatement.setString(7, company.getComment());
            pStatement.setString(8, company.getCompany());
            result = pStatement.executeUpdate();
            if (pStatement!=null) pStatement.close();
            if (connection!=null) MysqlDAOFactory.closeConnection(connection);
        }
        catch (SQLException e) {
            throw new ApplicationException(e.getMessage());
        }
        return result;
    }



    public Collection getAllCompany() throws ApplicationException {
        Connection connection = MysqlDAOFactory.getConnection();
        String ps = "select * from company";
        ArrayList arrayList = new ArrayList();
        try {
            PreparedStatement pStatement = connection.prepareStatement(ps);
            ResultSet rs = pStatement.executeQuery();
            while (rs.next()) {
                Company company = new Company();
                company.setCompany(rs.getString("company"));
                company.setEmail(rs.getString("email"));
                company.setJobTitle(rs.getString("jobTitle"));
                company.setDescription(rs.getString("description"));
                company.setDate(rs.getDate("date").toString());
                company.setSource(rs.getString("source"));
                company.setContact(rs.getString("contact"));
                company.setComment(rs.getString("comment"));
                arrayList.add(company);
            }
            if (rs!=null) rs.close();
            if (pStatement!=null) pStatement.close();
            if (connection!=null) MysqlDAOFactory.closeConnection(connection);
        }
        catch (SQLException e) {
            throw new ApplicationException(e.getMessage());
        }
        return arrayList;
    }

********************************************************************************************
********************************************************************************************
********************************************************************************************

public class XmlCompanyDAO implements
    CompanyDAO {

    public XmlCompanyDAO() {
        // initialization
    }

    public int insertCompany(Company companyData) throws ApplicationException {
        int result = 0;
        try {
            Document doc = XmlDAOFactory.getDocument();
            Node rootNode = doc.getDocumentElement();


            Element element = doc.createElement("company_record");

            Element element1 = doc.createElement("company");
            element1.appendChild(doc.createTextNode(companyData.getCompany()));

            Element element2 = doc.createElement("email");
            element2.appendChild(doc.createTextNode(companyData.getEmail()));

            Element element3 = doc.createElement("jobTitle");
            element3.appendChild(doc.createTextNode(companyData.getJobTitle()));

            Element element4 = doc.createElement("description");
            element4.appendChild(doc.createTextNode(companyData.getDescription()));

            Element element5 = doc.createElement("date");
            element5.appendChild(doc.createTextNode(companyData.getDate()));

            Element element6 = doc.createElement("source");
            element6.appendChild(doc.createTextNode(companyData.getSource()));

            Element element7 = doc.createElement("contact");
            element7.appendChild(doc.createTextNode(companyData.getContact()));

            Element element8 = doc.createElement("comment");
            element8.appendChild(doc.createTextNode(companyData.getComment()));

            element.appendChild(doc.createTextNode("\n        "));
            element.appendChild(element1);
            element.appendChild(doc.createTextNode("\n        "));
            element.appendChild(element2);
            element.appendChild(doc.createTextNode("\n        "));
            element.appendChild(element3);
            element.appendChild(doc.createTextNode("\n        "));
            element.appendChild(element4);
            element.appendChild(doc.createTextNode("\n        "));
            element.appendChild(element5);
            element.appendChild(doc.createTextNode("\n        "));
            element.appendChild(element6);
            element.appendChild(doc.createTextNode("\n        "));
            element.appendChild(element7);
            element.appendChild(doc.createTextNode("\n        "));
            element.appendChild(element8);
            element.appendChild(doc.createTextNode("\n    "));

            rootNode.appendChild(doc.createTextNode("    "));
            rootNode.appendChild(element);
            rootNode.appendChild(doc.createTextNode("\n"));
            result = 1;
        }
        catch (ApplicationException e){
            throw new ApplicationException("XmlCompanyDAO.insert():" + e.getMessage());
        }
        return result;
    }


    public int deleteCompany(String company) throws ApplicationException {
        int result = 0;
        try {
            ArrayList arrayList = new ArrayList();
            Document doc = XmlDAOFactory.getDocument();
            NodeList nl =  doc.getElementsByTagName("company_record");
            int nodeCount = 0;
            Node deleteNode = null;
            boolean found = false;
            while (!found && nodeCount<nl.getLength()) {
                Node node = nl.item(nodeCount);
                NodeList childNodesList = node.getChildNodes();
                int j = 0;
                while (!found && j<childNodesList.getLength()) {
                    Node current = childNodesList.item(j);
                    if (current.getNodeType() == Node.ELEMENT_NODE) {
                        if (current.getNodeName().equalsIgnoreCase("company")){
                            Node child = current.getFirstChild();
                            String fieldValue = child.getNodeValue();
                            if (fieldValue.equalsIgnoreCase(company)) {
                                deleteNode = current;
                                found = true;
                            }
                        }
                    }
                    j++;
                }
                nodeCount++;
            }
            // here's where the delete occurs
            if (deleteNode!=null) {
                Node rootNode = doc.getDocumentElement();
                rootNode.removeChild(deleteNode.getParentNode());
                result = 1;
            }
        }
        catch (ApplicationException e) {
            throw new ApplicationException ("XmlCompanyDAO.deleteCompany() " +
                                             e.getMessage());
        }
        return result;
    }

    public Company findCompany(String company) throws ApplicationException {
      Company companyData = new Company();
      try {
        Document doc = XmlDAOFactory.getDocument();
        NodeList nl =  doc.getElementsByTagName("company_record");
        boolean found = false;
        int nodeCount = 0;
        NodeList childNodesList = null;
        while (!found && nodeCount<nl.getLength()) {
            Node node = nl.item(nodeCount);
            childNodesList = node.getChildNodes();
            int j = 0;
            while (!found && j<childNodesList.getLength()) {
                Node current = childNodesList.item(j);
                if (current.getNodeType() == Node.ELEMENT_NODE) {
                    String fieldName = current.getNodeName();
                    Node child = current.getFirstChild();
                    String fieldValue = child.getNodeValue();
                    if (fieldName.equalsIgnoreCase("company") &&
                        fieldValue.equalsIgnoreCase(company)) {
                        found = true;
                    }
                }
                j++;
            }
            nodeCount++;
        }
        if (found && childNodesList!=null) {
            companyData = null; // allow for garbage collection
            companyData = getCompany(childNodesList);
        }
        else {
            throw new ApplicationException("XmlCompanyDAO.findCompany 1 Error: found but nodelist is null");
        }
      }
      catch (ApplicationException e ) {
          throw new ApplicationException("XmlCompanyDAO.findCompany 2 Error: found but nodelist is null");
      }
      return companyData;

    }

    public int updateCompany(Company companyData) throws ApplicationException {
        int result = 0;
        String company = null;
        if (companyData!=null) {
            company = companyData.getCompany();
            if (company!=null && company.length()>0) {
                deleteCompany(company);
                insertCompany(companyData);
                result = 1;  // successful update
            }
        }
        return result;
    }


    // chk 8/11
    public Collection getAllCompany() throws ApplicationException {
        ArrayList arrayList = new ArrayList();
        Document doc = XmlDAOFactory.getDocument();
        NodeList nl =  doc.getElementsByTagName("company_record");
        int nodeCount = 0;
        while (nodeCount<nl.getLength()) {
            Node node = nl.item(nodeCount);
            NodeList childNodesList = node.getChildNodes();
            int j = 0;
            while (j<childNodesList.getLength()){
                Node current = childNodesList.item(j);
                if (current.getNodeType() == Node.ELEMENT_NODE) {
                    if (current.getNodeName().equalsIgnoreCase("company")){
                        Node child = current.getFirstChild();
                        String fieldValue = child.getNodeValue();
                        Company company = findCompany(fieldValue);
                        arrayList.add(company);
                    }
                }
                j++;
            }
            nodeCount++;
        }
        return arrayList;
    }

    // chk, 8/11
    private Company getCompany(NodeList childNodesList) {
        int j = 0;
        Company company = new Company();
        while (j<childNodesList.getLength()) {
            Node current = childNodesList.item(j);
            if (current.getNodeType() == Node.ELEMENT_NODE) {
                String fieldName = current.getNodeName();
                Node child = current.getFirstChild();
                String fieldValue = child.getNodeValue();
                if (fieldName.equalsIgnoreCase("company")) {
                    company.setCompany(fieldValue);
                }
                if (fieldName.equalsIgnoreCase("email")) {
                    company.setEmail(fieldValue);
                }
                if (fieldName.equalsIgnoreCase("jobTitle")) {
                    company.setJobTitle(fieldValue);
                }
                if (fieldName.equalsIgnoreCase("description")) {
                    company.setDescription(fieldValue);
                }
                if (fieldName.equalsIgnoreCase("date")) {
                    company.setDate(fieldValue);
                }
                if (fieldName.equalsIgnoreCase("source")) {
                    company.setSource(fieldValue);
                }
                if (fieldName.equalsIgnoreCase("contact")) {
                    company.setContact(fieldValue);
                }
                if (fieldName.equalsIgnoreCase("comment")) {
                    company.setComment(fieldValue);
                }
            }
            j++;
        }
        return company;
    }

















More information about the Oakland mailing list