A.4 Entity Application EnrollmentBean Implementation

A.4 Entity Application EnrollmentBean Implementation

Here is the complete implementation of the EnrollmentBean session bean class for the entity application example in Chapter 8.

Code Example A.4 EnrollmentBean Implementation for Entity Application
 package com.wombat.benefits; import java.util.Collection; import javax.ejb.*; import javax.naming.Context; import javax.naming.InitialContext; import com.wombat.plan.Plan; import com.wombat.plan.PlanHome; import com.wombat.plan.PlanException; // EnrollmentBean 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"     };     // Employee number that uniquely identifies an employee     private int employeeNumber;     private EmployeeHome employeeHome;     private Employee employee;     private SelectionHome selectionHome;     private Selection selection;     private SelectionCopy selCopy;     // Portion of the benefits cost paid by the employee     // (A real-life application would read this value from     // a benefits plan configuration database.)     private double employeeCostFactor = 0.10;     // Indication if a selection record exists for an employee     private boolean recordDoesNotExist = false;     // 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     private PlanHome planHome;     // Arrays of local references to PlanEJB objects     private Plan[] medicalPlans;     private Plan[] dentalPlans;     private Class deductionBeanClass;     // public no-arg constructor     public EnrollmentBean() { } /***************************************************************** / /* business methods * / /***************************************************************** /     // Get employee information.     public EmployeeInfo getEmployeeInfo() {     return new EmployeeInfo(employeeNumber,                employee.getFirstName(),                employee.getLastName());     }     // Get coverage options.     public Options getCoverageOptions() {         Options opt = new Options(coverageDescriptions.length);         opt.setOptionDescription(coverageDescriptions);         opt.setSelectedOption(selCopy.getCoverage());         return opt;     }     // Set selected coverage option.     public void setCoverageOption(int choice)             throws EnrollmentException {         if (choice >= 0 && choice < coverageDescriptions.length) {             selCopy.setCoverage(choice);         } else {             throw new EnrollmentException(                 EnrollmentException.INVAL_PARAM);         }     }     // Get list of available medical options.     public Options getMedicalOptions() throws EnrollmentException {         Options opt = new Options(medicalPlans.length);         for (int i = 0; i < medicalPlans.length; i++) {             Plan plan = medicalPlans[i];             try {                 opt.setOptionDescription(i, plan.getPlanName());                 opt.setOptionCost(i, plan.getCost(                     selCopy.getCoverage(),                     age, selCopy.isSmoker()));             } catch ( PlanException ex ) {                 throw new EnrollmentException(                   "Error obtaining cost for plan "                   + plan.getPlanName());             }         }         opt.setSelectedOption(medicalSelection);         return opt;     }     // Set selected medical option.     public void setMedicalOption(int choice)             throws EnrollmentException     {         if (choice >= 0 && choice < medicalPlans.length) {             medicalSelection = choice;             selCopy.setMedicalPlan(medicalPlans[choice]);         } else {             throw new EnrollmentException(                 EnrollmentException.INVAL_PARAM);         }     }     // Get list of available dental options.     public Options getDentalOptions() throws EnrollmentException {         Options opt = new Options(dentalPlans.length);         for (int i = 0; i < dentalPlans.length; i++) {             Plan plan = dentalPlans[i];             try {                 opt.setOptionDescription(i, plan.getPlanName());                 opt.setOptionCost(i, plan.getCost(                     selCopy.getCoverage(),                     age, selCopy.isSmoker()));             } catch ( PlanException ex ) {                 throw new EnrollmentException(                   "Error obtaining cost for plan "                   + plan.getPlanName());             }         }         opt.setSelectedOption(dentalSelection);         return opt;     }     // Set selected dental option.     public void setDentalOption(int choice)             throws EnrollmentException     {         if (choice >= 0 && choice < dentalPlans.length) {             dentalSelection = choice;             selCopy.setDentalPlan(dentalPlans[choice]);         } else {             throw new EnrollmentException(                 EnrollmentException.INVAL_PARAM);         }     }     // Get smoker status.     public boolean isSmoker() {         return selCopy.isSmoker();     }     // Set smoker status.     public void setSmoker(boolean status) {         selCopy.setSmoker(status);     }     // Get summary of selected options and their cost.     public Summary getSummary() {         calculateTotalCostAndPayrollDeduction();     try {         Summary s = new Summary();        s.setCoverageDescription(            coverageDescriptions[selCopy.getCoverage()]);        s.setSmoker(selCopy.isSmoker());        s.setMedicalDescription(             medicalPlans[medicalSelection].getPlanName());        s.setMedicalCost(            medicalPlans[medicalSelection].getCost(                selCopy.getCoverage(),                age, selCopy.isSmoker()));        s.setDentalDescription(            dentalPlans[dentalSelection].getPlanName());        s.setDentalCost(            dentalPlans[dentalSelection].getCost(                selCopy.getCoverage(),                age, selCopy.isSmoker()));        s.setTotalCost(totalCost);        s.setPayrollDeduction(payrollDeduction);        return s;    } catch (Exception ex) {        throw new EJBException(ex);    }     }     // Update corporate databases with the new selections.     public void commitSelections() {         try {             if (recordDoesNotExist) {                 selection = selectionHome.create(selCopy);                 recordDoesNotExist = false;             } else {                 selection.updateFromCopy(selCopy);             }         DeductionUpdateBean deductionBean = null;         try {         deductionBean = (DeductionUpdateBean)                    deductionBeanClass.newInstance();         deductionBean.setBenefitsDeduction(employeeNumber,                   payrollDeduction);         deductionBean.execute();         } finally {         if (deductionBean != null)            deductionBean.release();         }          } catch (Exception ex) {             throw new EJBException(ex);         }     } /******************************************************************/ /* EJB life-cycle methods */ /***************************************************************** /     // Initialize the state of the EmployeeBean instance.     public void ejbCreate(int emplNum) throws EnrollmentException {         employeeNumber = emplNum;         // Obtain values from bean's environment.         readEnvironmentEntries();         try {             Collection coll = planHome.findMedicalPlans();             medicalPlans = new Plan[coll.size()];             medicalPlans = (Plan[])coll.toArray(medicalPlans);             coll = planHome.findDentalPlans();             dentalPlans = new Plan[coll.size()];             dentalPlans = (Plan[])coll.toArray(dentalPlans);             try {                 employee = employeeHome.findByPrimaryKey(                         new Integer(emplNum));             } catch (ObjectNotFoundException ex) {                 throw new EnrollmentException(                     "employee not found");             }         try {         selection = selectionHome.findByPrimaryKey(                            new Integer(emplNum));         } catch ( FinderException ex ) {}             if (selection == null) {                 // This is the first time that the employee                 // runs this application. Use default values                 // for the selections.                 selCopy = new SelectionCopy();                 selCopy.setEmployee(employee);                 selCopy.setCoverage(0);                 selCopy.setMedicalPlan(medicalPlans[0]);                 selCopy.setDentalPlan(dentalPlans[0]);                 selCopy.setSmoker(false);                 recordDoesNotExist = true;             } else {                 selCopy = selection.getCopy();             }             // Calculate employee's age.             java.util.Date today = new java.util.Date();             age = (int)((today.getTime() -                 employee.getBirthDate().getTime()) /                   ((long)365 * 24 * 60 * 60 * 1000));             // Translate the medical plan ID to an index             // into the medicalPlans table.             String medicalPlanId = (String)                 selCopy.getMedicalPlan().getPrimaryKey();             for (int i = 0; i < medicalPlans.length; i++) {                 if (medicalPlans[i].getPlanId().                         equals(medicalPlanId)) {                     medicalSelection = i;                     break;                 }             }             // Translate the dental plan ID to an index             // into the dentalPlans table.             String dentalPlanId = (String)                 selCopy.getDentalPlan().getPrimaryKey();             for (int i = 0; i < dentalPlans.length; i++) {                 if (dentalPlans[i].getPlanId().                         equals(dentalPlanId)) {                     dentalSelection = i;                     break;                 }             }         } catch (Exception ex) {             throw new EJBException(ex);         }     }     // Clean up any resource held by the instance.     public void ejbRemove() {}     public void ejbPassivate() {}     public void ejbActivate() {}     public void setSessionContext(SessionContext sc) {} /******************************************************************/ /* Helper methods */ /******************************************************************/     // Calculate total benefits cost and payroll deduction.     private void calculateTotalCostAndPayrollDeduction() {         try {             double medicalCost =                 medicalPlans[medicalSelection].getCost(                     selCopy.getCoverage(),                     age, selCopy.isSmoker());             double dentalCost =                 dentalPlans[dentalSelection].getCost(                     selCopy.getCoverage(),                     age, selCopy.isSmoker());             totalCost = medicalCost + dentalCost;             payrollDeduction = totalCost * employeeCostFactor;         } catch (Exception ex) {             throw new EJBException(ex);         }     }     // Read and process enterprise bean's environment entries.     private void readEnvironmentEntries() {         try {             Context ictx = new InitialContext();             planHome = (PlanHome)ictx.lookup(                     "java:comp/env/ejb/PlanEJB");             employeeHome = (EmployeeHome)ictx.lookup(                     "java:comp/env/ejb/EmployeeEJB");             selectionHome = (SelectionHome)ictx.lookup(                     "java:comp/env/ejb/SelectionEJB");             String deductionBeanName = (String)ictx.lookup(                       "java:comp/env/DeductionBeanClass");         deductionBeanClass = Class.forName(deductionBeanName);         } catch (Exception ex) {             throw new EJBException(ex);         }     } } 


Applying Enterprise Javabeans
Applying Enterprise JavaBeans(TM): Component-Based Development for the J2EE(TM) Platform
ISBN: 0201702673
EAN: 2147483647
Year: 2003
Pages: 110

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net