Your First Cup: An Introduction to the Java EE Platform

ProcedureModify DukesBirthdayBean.java

Add the enterprise bean annotations and a method that calculates the difference in age in years between Duke and the user.

  1. Annotate the class with the javax.ejb.Stateless annotation.

    @Stateless
    public class DukesAgeBean {
    ...
    }

    The @Stateless annotation marks the class as a stateless session bean.

  2. Directly after the class declaration, paste in the following code:

    private static Logger logger = 
    		Logger.getLogger("com.sun.firstcup.ejb.DukesBirthdayBean");
    public int getAgeDifference(Date date) {
    	int ageDifference;
    
    	Calendar theirBirthday = new GregorianCalendar();
    	Calendar dukesBirthday = new GregorianCalendar(1995, Calendar.MAY, 23);
    
    	// Set the Calendar object to the passed in Date
    	theirBirthday.setTime(date);
    
    	// Subtract the user's age from Duke's age
    	ageDifference = dukesBirthday.get(Calendar.YEAR) - 
    	theirBirthday.get(Calendar.YEAR);
    	logger.info("Raw ageDifference is: " + ageDifference);
    	// Check to see if Duke's birthday occurs before the user's. If so, 
    	// subtract one from the age difference
    	if (dukesBirthday.before(theirBirthday) && (ageDifference > 0)) {
    		ageDifference--;
    	}
    	logger.info("Final ageDifference is: " + ageDifference);
    
    	return ageDifference;
    }

    This code creates a logger for the session bean, creates the Calendar objects used to calculate the difference in age between the user and Duke, and adds a method, getAgeDifference, that does the actual calculation of the difference in age.

    Similar to the DukesAgeResource.getText code, getAgeDifference subtracts Duke's birthday year from the user's birthday year to get a raw age difference. If Duke's birthday falls before the users, and the raw difference is more than 0, subtract one year from the age difference. The final age difference is returned as an int.

  3. Right-click in the editor window and select Format.

  4. Right-click in the editor window and select Fix Imports.

  5. Choose the java.util.logging.Logger fully-qualified name for the Logger class.

  6. Choose the java.util.Date fully-qualified name for the Date class.

  7. Click OK.

  8. Select File->Save.