Here is the complete class implementation for the EnrollmentBean session bean coded for the session bean application example in Chapter 4. Code Example A.2 EnrollmentBean Source Codepackage com.star.benefits; import javax.ejb.*; import java.util.Date; import java.io.Serializable; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; import java.sql.SQLException; import com.star.benefits.db.DBQueryEmployee; import com.star.benefits.db.DBQuerySelection; import com.star.benefits.db.DBInsertSelection; import com.star.benefits.db.DBUpdateSelection; // The Employee class is used internally to represent the employee // information in the instance's conversational state. // class Employee implements Serializable { int emplNumber; String firstName; String lastName; Date birthDate; Date startDate; } // The Selection class is used internally to represent the benefits // selections in the instance's conversational state. // class Selection implements Serializable { int emplNumber; int coverage; String medicalPlanId; String dentalPlanId; boolean smokerStatus; } // EnrollmentBean is a stateful session bean that implements // the benefits enrollment business process. // public class EnrollmentBean implements SessionBean { private final static String[] coverageDescriptions = { "Employee Only", "Employee and Spouse", "Employee, Spouse, and Children" }; // Tables of Java classes that are used for calculation of // of cost of medical and dental benefits private HealthPlan[] medicalPlans; private HealthPlan[] dentalPlans; // Portion of the benefits cost paid by the employee (A // real-life application would read this value from the // database.) private double employeeCostFactor = 0.10; // Employee number that uniquely identifies an employee private int employeeNumber; // Employee information read from database private Employee employee; // Employee's current benefits selections private Selection selection; // Indication if beans need to create selection record private boolean createSelection; // The following variables are calculated values and are // used for programming convenience. private int age; // employee's age private int medicalSelection = -1; // index to medicalPlans private int dentalSelection = -1; // index to dentalPlans private double totalCost; // total benefits cost private double payrollDeduction; // payroll deduction // JDBC data sources private DataSource employeeDS; // Employee database private DataSource benefitsDS; // Benefits database // public no-arg constructor public EnrollmentBean() { } // business methods // Get employee information. public EmployeeInfo getEmployeeInfo() { return new EmployeeInfo(employeeNumber, employee.firstName, employee.lastName); } // Get coverage options. public Options getCoverageOptions() { Options opt = new Options(coverageDescriptions.length); opt.setOptionDescription(coverageDescriptions); opt.setSelectedOption(selection.coverage); return opt; } // Set selected coverage option. public void setCoverageOption(int choice) throws EnrollmentException { if (choice >= 0 && choice < coverageDescriptions.length) { selection.coverage = choice; } else { throw new EnrollmentException( EnrollmentException.INVAL_PARAM); } } // Get list of available medical options. public Options getMedicalOptions() { Options opt = new Options(medicalPlans.length); for (int i = 0; i < medicalPlans.length; i++) { HealthPlan plan = medicalPlans[i]; opt.setOptionDescription(i, plan.getDescription()); opt.setOptionCost(i, plan.getCost(selection.coverage, age, selection.smokerStatus)); } opt.setSelectedOption(medicalSelection); return opt; } // Set selected medical option. public void setMedicalOption(int choice) throws EnrollmentException { if (choice >= 0 && choice < medicalPlans.length) { medicalSelection = choice; selection.medicalPlanId = medicalPlans[choice].getPlanId(); } else { throw new EnrollmentException( EnrollmentException.INVAL_PARAM); } } // Get list of available dental options. public Options getDentalOptions() { Options opt = new Options(dentalPlans.length); for (int i = 0; i < dentalPlans.length; i++) { HealthPlan plan = dentalPlans[i]; opt.setOptionDescription(i, plan.getDescription()); opt.setOptionCost(i, plan.getCost(selection.coverage, age, selection.smokerStatus)); } opt.setSelectedOption(dentalSelection); return opt; } // Set selected dental option. public void setDentalOption(int choice) throws EnrollmentException { if (choice >= 0 && choice < dentalPlans.length) { dentalSelection = choice; selection.dentalPlanId = dentalPlans[choice].getPlanId(); } else { throw new EnrollmentException( EnrollmentException.INVAL_PARAM); } } // Get smoker status. public boolean getSmokerStatus() { return selection.smokerStatus; } // Set smoker status. public void setSmokerStatus(boolean status) { selection.smokerStatus = status; } // Get summary of selected options and their cost. public Summary getSummary() { calculateTotalCostAndPayrollDeduction(); Summary s = new Summary(); s.setCoverageDescription( coverageDescriptions[selection.coverage]); s.setSmokerStatus(selection.smokerStatus); s.setMedicalDescription( medicalPlans[medicalSelection].getDescription()); s.setMedicalCost( medicalPlans[medicalSelection].getCost( selection.coverage, age, selection.smokerStatus)); s.setDentalDescription( dentalPlans[dentalSelection].getDescription()); s.setDentalCost( dentalPlans[dentalSelection].getCost( selection.coverage, age, selection.smokerStatus)); s.setTotalCost(totalCost); s.setPayrollDeduction(payrollDeduction); return s; } // Update corporate databases with the new selections. public void commitSelections() { // Insert new or update existing benefits selection record. if (createSelection) { DBInsertSelection cmd1 = null; try { cmd1 = new DBInsertSelection(benefitsDS); cmd1.setEmplNumber(employeeNumber); cmd1.setCoverage(selection.coverage); cmd1.setMedicalPlanId(selection.medicalPlanId); cmd1.setDentalPlanId(selection.dentalPlanId); cmd1.setSmokerStatus(selection.smokerStatus); cmd1.execute(); createSelection = false; } catch (SQLException ex) { throw new EJBException(ex); } finally { if (cmd1 != null) cmd1.release(); } } else { DBUpdateSelection cmd2 = null; try { cmd2 = new DBUpdateSelection(benefitsDS); cmd2.setEmplNumber(employeeNumber); cmd2.setCoverage(selection.coverage); cmd2.setMedicalPlanId(selection.medicalPlanId); cmd2.setDentalPlanId(selection.dentalPlanId); cmd2.setSmokerStatus(selection.smokerStatus); cmd2.execute(); } catch (SQLException ex) { throw new EJBException(ex); } finally { if (cmd2 != null) cmd2.release(); } } // Update information in the payroll system. DeductionUpdateBean deductionBean = null; try { deductionBean = new DeductionUpdateBean(); deductionBean.setBenefitsDeduction(employeeNumber, payrollDeduction); deductionBean.execute(); } finally { if (deductionBean != null) deductionBean.release(); } } // Initialize the state of the EmployeeBean instance. public void ejbCreate(int emplNum) throws EnrollmentException { employeeNumber = emplNum; // Obtain values from bean's environment. readEnvironmentEntries(); // Obtain JDBC data sources from environment. getDataSources(); // Read employee information. DBQueryEmployee cmd1 = null; try { cmd1 = new DBQueryEmployee(employeeDS); cmd1.setEmployeeNumber(emplNum); cmd1.execute(); if (cmd1.next()) { employee = new Employee(); employee.emplNumber = emplNum; employee.firstName = cmd1.getFirstName(); employee.lastName = cmd1.getLastName(); employee.startDate = cmd1.getStartDate(); employee.birthDate = cmd1.getBirthDate(); } else { throw new EnrollmentException( "no employee record"); } } catch (SQLException ex) { throw new EJBException(ex); } finally { if (cmd1 != null) cmd1.release(); } // Read the previous benefits selections. DBQuerySelection cmd2 = null; try { cmd2 = new DBQuerySelection(benefitsDS); cmd2.setEmployeeNumber(emplNum); cmd2.execute(); if (cmd2.next()) { selection = new Selection(); selection.emplNumber = emplNum; selection.coverage = cmd2.getCoverage(); selection.medicalPlanId = cmd2.getMedicalPlanId(); selection.dentalPlanId = cmd2.getDentalPlanId(); selection.smokerStatus = cmd2.getSmokerStatus(); createSelection = false; } else { // No previous selections exist in // the database. Initial selections to // default values. selection = new Selection(); selection.emplNumber = emplNum; selection.coverage = 0; selection.medicalPlanId = medicalPlans[0].getPlanId(); selection.dentalPlanId = dentalPlans[0].getPlanId(); selection.smokerStatus = false; createSelection = true; } } catch (SQLException ex) { throw new EJBException(ex); } finally { if (cmd2 != null) cmd2.release(); } // Calculate employee's age. java.util.Date today = new java.util.Date(); age = (int)((today.getTime() - employee.birthDate.getTime()) / ((long)365 * 24 * 60 * 60 * 1000)); // Translate the medical plan ID to an index // into the medicalPlans table. for (int i = 0; i < medicalPlans.length; i++) { if (medicalPlans[i].getPlanId().equals( selection.medicalPlanId)) { medicalSelection = i; break; } } // Translate the dental plan ID to an index // into the dentalPlans table. for (int i = 0; i < dentalPlans.length; i++) { if (dentalPlans[i].getPlanId().equals( selection.dentalPlanId)) { dentalSelection = i; break; } } } // Clean up any resource held by the instance. public void ejbRemove() { } // Release state that cannot be preserved across passivation. public void ejbPassivate() { // All instance variables are either Serializable or one of the // special objects that are managed by the container // (e.g., DataSource). } // Reacquire state released before passivation. public void ejbActivate() { } public void setSessionContext(SessionContext sc) {} // Helper methods follow // Calculate total benefits cost and payroll deduction. private void calculateTotalCostAndPayrollDeduction() { double medicalCost = medicalPlans[medicalSelection].getCost( selection.coverage, age, selection.smokerStatus); double dentalCost = dentalPlans[dentalSelection].getCost( selection.coverage, age, selection.smokerStatus); totalCost = medicalCost + dentalCost; payrollDeduction = totalCost * employeeCostFactor; } // Read and process enterprise bean's environment entries. private void readEnvironmentEntries() { try { Context ictx = new InitialContext(); String medicalPlanList = (String) ictx.lookup("java:comp/env/medicalPlans"); String[] medicalPlanClassNames = parseClassNames(medicalPlanList); medicalPlans = new HealthPlan[medicalPlanClassNames.length]; for (int i = 0; i < medicalPlanClassNames.length; i++) { medicalPlans[i] = (HealthPlan)Class.forName( medicalPlanClassNames[i]).newInstance(); } String dentalPlanList = (String) ictx.lookup("java:comp/env/dentalPlans"); String[] dentalPlanClassNames = parseClassNames(dentalPlanList); dentalPlans = new HealthPlan[dentalPlanClassNames.length]; for (int i = 0; i < dentalPlanClassNames.length; i++) { dentalPlans[i] = (HealthPlan)Class.forName( dentalPlanClassNames[i]).newInstance(); } } catch (Exception ex) { ex.printStackTrace(); throw new EJBException(ex); } } private void getDataSources() { try { Context ictx = new InitialContext(); employeeDS = (DataSource)ictx.lookup( "java:comp/env/jdbc/EmployeeDB"); benefitsDS = (DataSource)ictx.lookup( "java:comp/env/jdbc/BenefitsDB"); } catch (Exception ex) { ex.printStackTrace(); throw new EJBException(ex); } } // Parse ':' separated class names. // private static String[] parseClassNames(String list) { String[] rv = new String[0]; while (list.length() != 0) { int x = list.indexOf(':'); String name; if (x < 0) { name = list; list = ""; } else { name = list.substring(0, x); list = list.substring(x + 1); } if (name.length() == 0) { continue; } String[] orv = rv; rv = new String[rv.length + 1]; for (int i = 0; i < orv.length; i++) rv[i] = orv[i]; rv[rv.length - 1] = name; } return rv; } } |