Chapter 3
Chapter 5
Chapter 7
Chapter 8
Chapter 9
Download All Code
Home
 
Chapter 8 Examples
8.1 to 8.12   8.13 to 8.24   8.25 to 8.35

Download all Chapter 8 code

View code examples 8.25 to 8.35
8.25   8.26   8.27   8.28   8.29   8.30
8.31   8.32   8.33   8.34   8.35


Example 8.25 TaskResourceVO Class

public class TaskResourceVO {
  public String projectId;
  public String taskId;
  public String name;
  public String description;
  public Date startDate;
  public Date endDate;
  public ResourceVO assignedResource;
  ...

  public TaskResourceVO(String projectId, 
    String taskId, String name, String description, 
    Date startDate, Date endDate, ResourceVO 
    assignedResource) {
        this.projectId = projectId;
        this.taskId = taskId;
        ...
        this.assignedResource = assignedResource;
    }
    ...
}

Example 8.26 TaskVO Class

public class TaskVO {
  public String projectId;
  public String taskId;
  public String name;
  public String description;
  public Date startDate;
  public Date endDate;
  public assignedResourceId;

  public TaskVO(String projectId, String taskId, 
      String name, String description, Date startDate, 
      Date endDate, String assignedResourceId) {
        this.projectId = projectId;
        this.taskId = taskId;
        ...
        this.assignedResource = assignedResource;
    }
    ...
}

Example 8.27 ResourceVO Class

public class ResourceVO {
  public String resourceId;
  public String resourceName;
  public String resourceEmail;
  ...
  
  public ResourceVO (String resourceId, String 
    resourceName, String resourceEmail, ...) {
      this.resourceId = resourceId;
      this.resourceName = resourceName;
      this.resourceEmail = resourceEmail;
      ...
  }
}

Example 8.28 Implementing the Value Object Assembler

public class ProjectDetailsAssembler 
  implements javax.ejb.SessionBean {

  ...

  public ProjectDetailsData getData(String projectId){ 

    // Construct the composite value object
    ProjectDetailsData pData = new 
                      ProjectDetailsData();

    //get the project details; 
    ProjectHome projectHome = 
        ServiceLocator.getInstance().getHome(
          "Project", ProjectEntityHome.class);
    ProjectEntity project = 
      projectHome.findByPrimaryKey(projectId);
    ProjectVO projVO = project.getData();
  
    // Add Project Info to ProjectDetailsData
    pData.projectData = projVO;

    //get the project manager details;
    ProjectManagerHome projectManagerHome =
      ServiceLocator.getInstance().getHome( 
        "ProjectManager", ProjectEntityHome.class);
  
    ProjectManagerEntity projectManager = 
      projectManagerHome.findByPrimaryKey(
        projVO.managerId);

    ProjectManagerVO projMgrVO = 
      projectManager.getData();
  
    // Add ProjectManager info to ProjectDetailsData
    pData.projectManagerData = projMgrVO;

    // Get list of TaskVOs from the Project
    Collection projTaskList = project.getTasksList();

    // construct a list of TaskResourceVOs
    ArrayList listOfTasks = new ArrayList();
  
    Iterator taskIter = projTaskList.iterator();
    while (taskIter.hasNext()) {
      TaskVO task = (TaskVO) taskIter.next();

      //get the Resource details; 
      ResourceHome resourceHome = 
      ServiceLocator.getInstance().getHome( 
        "Resource",         ResourceEntityHome.class);
  
      ResourceEntity resource = 
        resourceHome.findByPrimaryKey(
          task.assignedResourceId);

      ResourceVO resVO = resource.getResourceData();

      // construct a new TaskResourceVO using Task
      // and Resource data
      TaskResourceVO trVO = new TaskResourceVO( 
              task.projectId, task.taskId,
              task.name, task.description,
              task.startDate, task.endDate,
              resVO);

      // add TaskResourceVO to the list
      listOfTasks.add(trVO);
    }
    
    // add list of tasks to ProjectDetailsData
    pData.listOfTasks = listOfTasks;

    // add any other data to the value object
    ...
  
    // return the composite value object
    return pData;

  }

  ...
}

Example 8.29 Implementing Value List Handler Pattern

package corepatterns.apps.psa.handlers;

import java.util.*;
import corepatterns.apps.psa.dao.*;
import corepatterns.apps.psa.util.*;
import corepatterns.apps.psa.core.*;

public class ProjectListHandler 
extends ValueListHandler {

  private ProjectDAO dao = null;
  // use ProjectVO as a template to determine
  // search criteria
  private ProjectVO projectCriteria = null;

  // Client creates a ProjectVO instance, sets the 
  // values to use for search criteria and passes 
  // the ProjectVO instance as projectCriteria
  // to the constructor and to setCriteria() method
  public ProjectListHandler(ProjectVO projectCriteria) 
  throws ProjectException, ListHandlerException {
    try {
      this.projectCriteria = projectCriteria;
      this.dao = PSADAOFactory.getProjectDAO();
      executeSearch();
    } catch (Exception e) {
      // Handle exception, throw ListHandlerException
    }
  }

  public void setCriteria(ProjectVO projectCriteria) {
    this.projectCriteria = projectCriteria;
  }

  // executes search. Client can invoke this
  // provided that the search criteria has been
  // properly set. Used to perform search to refresh
  // the list with the latest data.
  public void executeSearch()   
  throws ListHandlerException {
    try {
      if (projectCriteria == null) {
        throw new ListHandlerException(
          "Project Criteria required...");
      }
      List resultsList = 
        dao.executeSelect(projectCriteria);        
      setList(resultsList);
    } catch (Exception e) {
      // Handle exception, throw ListHandlerException
    }
  }
}

Example 8.30 Implementing Generic ValueListHandler Class

package corepatterns.apps.psa.util;

import java.util.*;

public class ValueListHandler
implements ValueListIterator {

  protected List list;
  protected ListIterator listIterator;

  public ValueListHandler() {
  }

  protected void setList(List list) 
  throws IteratorException {
    this.list = list;
    if(list != null)
      listIterator =  list.listIterator();
    else
      throw new IteratorException("List empty");
  }

  public Collection getList(){
    return list;
  }
    
  public int getSize() throws IteratorException{
    int size = 0;
        
    if (list != null)
      size = list.size();
    else
      throw new IteratorException(...); //No Data

    return size;
  }
    
  public Object getCurrentElement() 
  throws IteratorException {

    Object obj = null;
    // Will not advance iterator
    if (list != null)
    {
      int currIndex = listIterator.nextIndex();
      obj = list.get(currIndex);
    }
    else
      throw new IteratorException(...);
    return obj;

  }
    
  public List getPreviousElements(int count) 
  throws IteratorException {
    int i = 0;
    Object object = null;
    LinkedList list = new LinkedList();
    if (listIterator != null) {
      while (listIterator.hasPrevious() && (i < count)){
        object = listIterator.previous();
        list.add(object);
        i++;
      }
    }// end if
    else
      throw new IteratorException(...); // No data

    return list;
  }
    
  public List getNextElements(int count) 
  throws IteratorException {
    int i = 0;
    Object object = null;
    LinkedList list = new LinkedList();
    if(listIterator != null){
      while(  listIterator.hasNext() && (i < count) ){
        object = listIterator.next();
        list.add(object);
        i++;
      }
    } /  / end if
    else
      throw new IteratorException(...); // No data

    return list;
  }
    
  public void resetIndex() throws IteratorException{
    if(listIterator != null){
      listIterator = list.ListIterator();
    }
    else
      throw new IteratorException(...); // No data
  }
  ...
}

Example 8.31 ProjectDAO Class

package corepatterns.apps.psa.dao;

public class ProjectDAO {
  final private String tableName = "PROJECT";

  // select statement uses fields
  final private String fields = "project_id, name," +
      "project_manager_id, start_date, end_date, " + 
      " started, completed, accepted, acceptedDate," + 
      " customer_id, description, status";

  // the methods relevant to the ValueListHandler
  // are shown here.
  // See Data Access Object pattern for other details.
  ...
  private List executeSelect(ProjectVO projCriteria) 
  throws SQLException {

    Statement stmt= null;
    List list = null;
    Connection con = getConnection();
    StringBuffer selectStatement =   new StringBuffer();
    selectStatement.append("SELECT "+ fields + 
          " FROM " + tableName + "where 1=1");

    // append additional conditions to where clause
    // depending on the values specified in 
    // projCriteria
    if (projCriteria.projectId != null) {
      selectStatement.append (" AND PROJECT_ID = '" + 
        projCriteria.projectId + "'");
    }
    // check and add other fields to where clause
    ...
    
    try {
      stmt = con.prepareStatement(selectStatement);
      stmt.setString(1, resourceID);
      ResultSet rs = stmt.executeQuery();
      list = prepareResult(rs);
      stmt.close();
    }
    finally {
      con.close();
    }
    return list;
  }

  private List prepareResult(ResultSet rs) 
  throws SQLException {
    ArrayList list = new ArrayList();
    while(rs.next()) {
      int i = 1;
      ProjectVO proj = new 
        ProjectVO(rs.getString(i++));
      proj.projectName = rs.getString(i++);
      proj.managerId = rs.getString(i++);
      proj.startDate = rs.getDate(i++);
      proj.endDate = rs.getDate(i++);
      proj.started = rs.getBoolean(i++);
      proj.completed = rs.getBoolean(i++);
      proj.accepted = rs.getBoolean(i++);
      proj.acceptedDate = rs.getDate(i++);
      proj.customerId = rs.getString(i++);
      proj.projectDescription = rs.getString(i++);
      proj.projectStatus = rs.getString(i++);
      list.add(proj);

    }
    return list;
  }
  ...
}

Example 8.32 ValueListIterator Class

package corepatterns.apps.psa.util;

import java.util.List;

public interface ValueListIterator {
    
  public int getSize() 
    throws IteratorException;
    
  public Object getCurrentElement() 
    throws IteratorException;
    
  public List getPreviousElements(int count) 
    throws IteratorException;
    
  public List getNextElements(int count) 
    throws IteratorException;
    
  public void resetIndex()
    throws IteratorException;

  // other common methods as required
  ...
}

Example 8.33 Implementing Service Locator

package corepatterns.apps.psa.util;
import java.util.*;
import javax.naming.*;
import java.rmi.RemoteException;
import javax.ejb.*;
import javax.rmi.PortableRemoteObject;
import java.io.*;

public class ServiceLocator {
  private static ServiceLocator me;
  InitialContext context = null;
    
  private ServiceLocator() 
  throws ServiceLocatorException {
    try {
      context = new InitialContext();
    } catch(NamingException ne) {
      throw new ServiceLocatorException(...);
    }
  }
    
  // Returns the instance of ServiceLocator class
  public static ServiceLocator getInstance() 
  throws ServiceLocatorException {
    if (me == null) {
      me = new ServiceLocator();
    }
    return me;
  }
    
  // Converts the serialized string into EJBHandle 
  // then to EJBObject.
  public EJBObject getService(String id) 
  throws ServiceLocatorException {
    if (id == null) {
      throw new ServiceLocatorException(...);
    }
    try {
      byte[] bytes = new String(id).getBytes();
      InputStream io = new 
        ByteArrayInputStream(bytes);
      ObjectInputStream os = new 
        ObjectInputStream(io);
      javax.ejb.Handle handle = 
        (javax.ejb.Handle)os.readObject();
      return handle.getEJBObject();
    } catch(Exception ex) {
      throw new ServiceLocatorException(...);
    }
  }
    
  // Returns the String that represents the given 
  // EJBObject's handle in serialized format.
  protected String getId(EJBObject session) 
  throws ServiceLocatorException {
    try {
      javax.ejb.Handle handle = session.getHandle();
      ByteArrayOutputStream fo = new 
        ByteArrayOutputStream();
      ObjectOutputStream so = new 
        ObjectOutputStream(fo);
      so.writeObject(handle);
      so.flush();
      so.close();
      return new String(fo.toByteArray());
    } catch(RemoteException ex) {
      throw new ServiceLocatorException(...);
    } catch(IOException ex) {
      throw new ServiceLocatorException(...);
    }
    return null;
  }
    
  // Returns the EJBHome object for requested service 
  // name. Throws ServiceLocatorException If Any Error 
  // occurs in lookup
  public EJBHome getHome(String name, Class clazz) 
  throws ServiceLocatorException {
    try {
      Object objref = context.lookup(name);
      EJBHome home = (EJBHome) 
        PortableRemoteObject.narrow(objref, clazz);
      return home;
    } catch(NamingException ex) {
      throw new ServiceLocatorException(...);
    }
  }
}

Example 8.34 Implementing Type Checked Service Locator Strategy

package corepatterns.apps.psa.util;
// imports
...
public class ServiceLocator {
  // singleton's private instance 
  private static ServiceLocator me;
  
  static {
    me = new ServiceLocator();
  }
    
  private ServiceLocator() {}

  // returns the Service Locator instance 
  static public ServiceLocator getInstance() { 
    return me;
  }

  
  // Services Constants Inner Class - service objects
  public class Services {
    final public static int PROJECT  = 0;
    final public static int RESOURCE = 1;
  }    

  // Project EJB related constants
  final static Class  PROJECT_CLASS = ProjectHome.class;                      
  final static String PROJECT_NAME  = "Project";

  // Resource EJB related constants
  
  final static Class  RESOURCE_CLASS = ResourceHome.class;                        
  final static String RESOURCE_NAME  = "Resource";

  // Returns the Class for the required service 
  static private Class getServiceClass(int service){
    switch( service ) {
      case Services.PROJECT:
        return PROJECT_CLASS;
      case Services.RESOURCE:
      return RESOURCE_CLASS;
    }
    return null;
  }
    
  // returns the JNDI name for the required service 
  static private String getServiceName(int service){
    switch( service ) {
      case Services.PROJECT:
        return PROJECT_NAME;
      case Services.RESOURCE:
        return RESOURCE_NAME;
    }
    return null;
  }
    
  /* gets the EJBHome for the given service using the 
  ** JNDI name and the Class for the EJBHome
  */
  public EJBHome getHome( int s ) 
    throws ServiceLocatorException {
    EJBHome home = null;
    try {
        Context initial  = new InitialContext();

      // Look up using the service name from 
      // defined constant
      Object objref = 
        initial.lookup(getServiceName(s));

      // Narrow using the EJBHome Class from 
      // defined constant
      Object obj = PortableRemoteObject.narrow( 
                objref, getServiceClass(s));
      home = (EJBHome)obj;
    }
    catch( NamingException ex ) {
        throw new ServiceLocatorException(...);
    }
    catch( Exception ex ) {
        throw new ServiceLocatorException(...);
    }
    return home;
  }
}

Example 8.35 Client Code for Using the Service Locator

public class ServiceLocatorTester {
  public static void main( String[] args ) {
    ServiceLocator serviceLocator = 
      ServiceLocator.getInstance();
    try {
      ProjectHome projectHome = (ProjectHome)
        serviceLocator.getHome(
          ServiceLocator.Services.PROJECT );
    }
    catch( ServiceException ex ) {
      // client handles exception
      System.out.println( ex.getMessage( ));
    }
  }
}
Ex. 8.1 to 8.12 | Ex 8.13 to 8.24 | Ex. 8.25 to 8.35