BusinessComponetDevelopmentwithEJB-ActivityGuide

43

Transcript of BusinessComponetDevelopmentwithEJB-ActivityGuide

Page 1: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 1/43

Page 2: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 2/43

Page 3: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 3/43

 About This Course

Course Goals

Upon completion of this course, you should be able to:

Examine the Java™ Platform, Enterprise

Edition (Java EE)Examine a Java EE technology application

Implement Enterprise JavaBeans™ (EJB™) 3.1

session beans

Develop Java EE technology applications using

messaging

Create message-driven beans

Implement interceptor classes and methods

Implement transactions

Implement exception handling for EJB

technology

Create a timer using the Timer Service

Handle timer notification within an EJBcomponent

Implement security for Java EE technology

Evaluate best practices for EJB technology

Topics Not Covered 

This course does not cover the following topics. Many of

these topics are covered in other courses offered by Sun

Learning Services:

Object-oriented concepts - Covered in OO-226:

Object-Oriented Analysis and Design for Java™ Technology (UML)

Distributed programming concepts and support

technologies, such as remote procedure call

(RPC), Remote Method Invocation (RMI),

Internet Inter- ORB Protocol (IIOP), Common

Object Request Broker Architecture (CORBA),

Lightweight Directory Access Protocol

(LDAP), Java Naming and Directory

Interface™ API (JNDI API)

Refer to the Sun Learning Services catalog for specific

information and registration.

How Prepared Are You?

To be sure you are prepared to take this course, can you

answer yes to the following questions?

Can you write a Java technology class?

Can you implement composition, association,

and inheritance relationships?

Can you handle events and exceptions

generated in Java technology classes?

Can you describe the issues associated with

transaction management?

Introductions

 Now that you have been introduced to the course,

introduce yourself to the other students and the

instructor, addressing the following items:

 Name

Company affiliation

Title, function, and job responsibility

Experience related to topics presented in this

courseReasons for enrolling in this course

Expectations for this course

How to Use Course Materials

To enable you to succeed in this course, these course

materials contain a learning module that is composed of

the following components:

Goals - You should be able to accomplish the

goals after finishing this course and meeting all

of its objectives.Objectives - You should be able to accomplish

the objectives after completing a portion of

instructional content. Objectives support goals

and can support other higher-level objectives.

Lecture - The instructor presents information

specific to the objective of the module. This

information helps you obtain the knowledge

and skills necessary to succeed with the

activities.

Activities - The activities take various forms,

such as an exercise, self- check, discussion, and

demonstration. Activities help you facilitate themastery of an objective.

Visual aids - The instructor might use several

visual aids to convey a concept, such as a

 process. Visual aids commonly contain

graphics, animation, and video.

Conventions

The following conventions are used in this course to

represent various training elements and alternative

learning resources.

Icons

Additional resources - Indicates other references that

 provide additional information on the topics described in

the module.

Discussion - Indicates a small-group or class discussion

on the current topic is recommended at this time.

Page 4: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 4/43

Note

Indicates additional information that can help you but

is not crucial to your understanding of the concept

 being described. You should be able to understand the

concept or complete the task without this information.

Examples of notational information include keyword

shortcuts and minor system adjustments.

Typographical Conventions

Cour i er is used for the names of commands, files,

directories, programming code, and on-screen computer

output. For example:

Use l s - al to list all files.

syst em% You have mai l .

Cour i er is also used to indicate programming

constructs, such as class names, methods, and keywords.

For example:

The get Ser vl et I nf o method is used to obtain

author information.

The j ava. awt . Di al og class contains the Di al ogconstructor.

Courier bold is used for characters and numbers

that you type. For example:

To list the files in this directory, type:

# ls

Courier bold is also used for each line of

 programming code that is referenced in a textual

description. For example:

1 i mpor t j ava. i o. *;

2 import javax.servlet.*;

3 i mpor t j avax. ser vl et . ht t p. *;

 Notice that the j avax. ser vl et interface is

imported to allow access to its life-cycle methods (Line

2).

Courier italics is used for variables and

command-line placeholders that are replaced with a real

name or value. For example:

To delete a file, use the r m filename command.

Courier italic bold is used to represent

variables whose values are to be entered as part of an

activity. For example:Type chmod a+rwx filename to grant read,

write, and execute rights for 

filename to the world, group, and users.

Palatino italics is used for book titles, new words or

terms, or words that you want to emphasize. For

example:

Read Chapter 6 in the User’s Guide.

These are called class options.

Additional Conventions

Java programming language examples use the following

additional conventions:

Method names are not followed with

 parentheses unless a formal or actual parameter

list is shown. For example:

“The doI t method...” refers to any method

called doI t .

“The doI t ( ) method...” refers to a method

called doI t that takes no arguments.

Line breaks occur only where there are

separations (commas), conjunctions (operators),or white space in the code. Broken code is

indented four spaces under the starting code.

If a command used in the Solaris™ Operating

System (Solaris OS) is different from a

command used in the Microsoft Windows

 platform, both commands are shown. For

example:

In the Solaris OS:

$>CD SERVER_ROOT/ BI NIn Microsoft Windows:C: \ >CD SERVER_ROOT\ BI N

Page 5: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 5/43

 Lab 1

Examining Enterprise JavaBeans(EJB) Applications

Objectives

Upon completion of this lab, you should be able to:

Complete the review questions

Exercise 1: Completing Review

Questions

In this exercise, you answer questions about the material

covered in Module 1 of the Student Guide.

Complete the following questions:

1.

2.

3.

4.

5.

6.

7.

8.

9.

List four elements contained in the Java EE

 platform.What are the three key components of the Java

EE application architecture?

Which two containers are required to be hosted

 by a Java EE compliant application server?

What type of deployment would you use to

 package an EJB application?

List four services provided by an EJB container.

What is the purpose of an EJB components?

List three characteristics of an EJB.

What are the two types of EJB components?

Which Java EE API would you use to

implement asynchronous communication between Java EE application components?

Page 6: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 6/43

 Lab 2

Implementing Session Beans

Objectives

Upon completion of this lab, you should be able to:

Complete the review questionsCreate a remote session bean

Create a simple application to test the session

 bean

Exercise 1: Completing ReviewQuestions

In this exercise, you answer questions about the material

covered in the Student Guide.

Complete the following questions:

1.

2.

3.

4.

5.

6.

7.

What is a session bean?

 Name the three types of session beans and their

annotations.

List three characteristics of session beans.

Describe the primary difference, in terms of

client access, between the three session bean

types.

Which session bean would you choose if you

needed to store unique client data, per client,

throughout the client-application interactions?

To declare a session EJB as a remote EJB, list

two possible locations where you can place the@Remot e annotation.

List the five essential tasks required to create a

session bean.

Exercise 2: Creating the EJBProject

In this exercise, you create an EJB aware project within

the NetBeans? IDE. This exercise contains the following

sections:

“Task 1 - Create the Project”“Task 2 - Administer the Server”

Preparation

This exercise assumes that the NetBeans IDE has been

installed but not configured with the EJB31 project.

Tool Reference - Tool references used in this exercise

include:

Java EE Development: Enterprise Application

Projects: Creating Enterprise Application

Projects

Java Development: Java Application Projects:

Opening Projects

Java EE Development: Enterprise Application

Projects: Building Java EE Applications

Java EE Development: Enterprise Application

Projects: Verifying Java EE Applications

Java EE Development: Enterprise Application

Projects: Deploying Java EE Applications

Java Development: Java Application Projects:

Running Projects

Server Resources: J2EE Application Servers:Examining Server Log Files

Java Development: Modifying Project Libraries

Java Development: Java Classes: Modifying

Java Classes: Adding Fields

Java Development: Java Classes: Opening Java

Classes

Java Development: Other Files: Opening Files

Java EE Application Servers: Starting

Application Servers

Task 1 - Create the ProjectIn this task, you create an EJB project and configure the

application server.

Tool Reference - Java EE Development: Enterprise

Application Projects: Creating Enterprise Application

Projects

Complete the following steps:

1.

2.

3.

Double-click the NetBeans icon on your

desktop:

a.

 b.

If prompted with a “Start Page”, close

the page.

Otherwise, you are in the primary NetBeans view.

Examine the layout of the primary NetBeans

view. The primary view contains two sections:

a.

 b.

 Navigator section - This section is

 presented using a tab layout view

containing three tabs:

Projects - Shows open or

closed projects

Files - Is a file system

 browser 

Services - Shows the services

available in NetBeansEditor section - This section will

contain open files

Create a new project:

a.

 b.

c.

Use the File menu of the IDE and

choose

Fi l e < New Proj ect .

Create an Enterprise Application. This

is a three-step process defined by the

“New Enterprise Application” wizard.

Step 1 - “Choose Project”:

1. Choose Cat egory < J ava EE

Page 7: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 7/43

4.

d.

e.

2.

3.

Choose Pr oj ect s <Ent er pr i seAppl i cat i onPress the Next button.

Step 2 - “Name and Location”:

1.

2.

3.

Specify EJB31 as the Project

 Name.

Specify D: \ Labs\ st udent \ sol ut i onsdirectory for the Project

Location.Press the Next button.

Step 3 - “Server and Settings”:

1.

2.

3.

4.

5.

6.

Choose GlassFish? v3

Domain as the Server.

Ensure that the Java EE

Version is Java EE 6.

Ensure that the Create EJB

Module check box is selected

and the name of the module is

EJ B31- ej b.

Deselect the Create Web

Application Module check box.

Select the Create Application

Client Module. The name

should automatically be

created and assigned the

value EJ B31- app-cl i ent . After selection the

check box, the Main class

field will be populated with

ej b31. Mai n.

Press the Finish button.

Verify that the project was created properly. In

the Projects tab you should see:

A triangle icon, labeled EJB31 - This

represents the Enterprise Application.

A coffee cup icon, labeled EJB31-app-

client - This represents the client

application module (which will be

 built at a later point).

A bean icon, labeled EJB31-ejb - This

represents the EJB module.

Task 2 - Administer the Server 

Tool Reference - Java EE Application Servers: Starting

Application Servers

Complete the following steps:

1.

2.

Start the application server:

a.

 b.

c.

d.

Click the Services tab of the IDE.

Expand the Servers node.

Right click GlassFish v3 Domain.

Select the Start menu option.

Verify that the application server started

 properly.Within the Glassfish tab of the output console,

3.

you should view log messages showing the

steps GlassFish goes through during its startup

 process.

Additionally, you will notice the icon for

GlassFish under the Servers node change to

include a green arrow. This indicates GlassFish

is running.

Stop the application server:

a.

 b.

c.d.

Select the Services tab of the IDE.

Expand the Servers node.

Right click GlassFish v3 Domain.Select the Stop menu option.

Exercise 3: Creating a Remote

Session Bean

In this exercise, you create a simple “hello world”

session bean that is accessed using the remote client

access mode.

This exercise contains the following sections:

“Task 1 - Create the Hel l oWor l dBean

Session Bean”“Task 2 - Modify the Hel l oWor l dBeanSession Bean”

“Task 3 - Build and Deploy the EJ B31Application”

Preparation

This exercise assumes that the application server is

installed and running. As a review, the steps to create a

session bean are as follows:

Declare a business interface for the session bean or use a no-interface implementation.

Annotate the business interface with the desired

client access mode.

Create a class that implements the business

interface.

Annotate the class with the desired session bean

type.

Package the session bean.

You will be using the EJB creation wizard provided by

the NetBeans IDE.

Tool Reference - Tool references used in this exercise

include:

Java Development: Java Application Projects:

Opening Projects

Java EE Development: Enterprise Application

Projects: Building Java EE Applications

Java EE Development: Enterprise Application

Projects: Verifying Java EE Applications

Java EE Development: Enterprise Application

Projects: Deploying Java EE Applications

Server Resources: Java EE Application Servers:

Examining Server Log Files

Java Development: Java Application Projects:Modifying Project Libraries

Page 8: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 8/43

Java Development: Java Classes: Modifying

Java Classes: Adding Fields

Java Development: Java Classes: Modifying

Java Classes: Adding Methods

Java Development: Java Classes: Opening Java

Classes

Java Development: Other Files: Opening Files

Java EE Application Servers: Starting

Application Servers

Task 1 - Create theHel l oWor l dBean Session Bean

In this task, you create and implement the proverbial

“hello world” bean. In subsequent modules, you will

enhance the functionality of the HelloWorld bean.

Complete the following steps:

1.

2.

3.

Right-click on the EJ B31- ej b module in the

Projects tab and choose:New > Sessi on BeanFill in the EJB information in the wizard to

create a stateless session bean:a.

 b.

c.

d.

e.

Specify Hel l oWor l dBean as the

EJB Name.

Define the package as

hel l owor l d. beans.

Leave Stateless selected for the

Session Type.

Select the check box for the creation

of a Remote interface.

Click the Finish button.

Verify that the EJB was created properly by

examining the Source Packages node of theEJ B31- ej b module in the Projects tab:a.

 b.

hel l owor l dbeans. Hel l oWor l d

BeanRemot e - Represents the

 business interfacehel l owor l dbeans. Hel l oWor l dBean - Represents the EJB

Task 2 - Modify theHel l oWor l dBean Session Bean

In this task, you will modify the generated code for theHel l oWor l d EJB. Complete the following steps:

1. Implement the sayHel l o method in the

Hel l oWor l dBean:

a. Open Hel l oWor l dBean. j ava, if

it is not already open, by double

clicking the file name in the Source

Packages node.

Note

 Notice that the EJB type is

2.

 b.

c.

d.

defined by the @Stat el essannotation.

Right-click in the editor and choose:I nser t code < Add Busi nessMet hodSpecify the method information as

follows:

1.

2.

3.

4.

 Name: sayHel l oReturn Type: St r i ng

Ensure that the Remote radio button is selected.

Click the OK button.

Modify the sayHel l o method

created in the source:

1.

2.

Review the sayHel l omethod.

Change the returnstatement to:r et urn “Hel l o EJ BWor l d” ;

Review the Hel l oWor l dBeanRemot e

interface:a.

 b.

OpenHel l oWor l dBeanRemot e. j avain the editor by double clicking the

filename in the Source Packages node.

The NetBeans IDE should have

created a sayHel l o method in the

interface:Str i ng sayHel l o( ) ;

Task 3 - Build and Deploy the

EJ B31 Application

In this task, you build, verify, and finally deploy the

EJB31 EAR file on a Java EE application server.

Complete the following steps:

1.

2.

Build the EJ B31 application:

a.

 b.

Right-click on the EJ B31 application

and select Build.

Verify that there were no errors during

the build of the EJ B31

application by reviewing the output in

the EJB31 (dist) tab.Verify that a distribution of the application was

created by using the Files tab of the IDE. Check

that the following file has been created:

a.

 b.

c.

EJ B31/ di st / EJ B31. ear - The

applicationEJ B31/ EJ B31- app- cl i ent /di st / EJ B31- app- cl i ent . j ar- The application clientEJ B31/ EJ B31- ej b/ di st /EJ B31- ej b. j ar - The EJB

module (containing

Hel l oWor l dBean)

Page 9: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 9/43

3.

4.

NoteIf the EJ B31. ear file does not

exist, try rebuilding the entire

EJB31 project.

Deploy the EJ B31 application by selecting

Deploy from the context menu that appears

when you right-click on the EJ B31  project inthe IDE Projects tab.

Verify that the deployment of the EJB31

application worked:

a.

 b.

Review the output in the EJB31 (run-

deploy) tab, looking for any

unexpected errors.

Review the deployed Applications of

the GlassFish server:

a.

 b.

c.

In the Services tab, expand

the Servers node.

In the Servers node, expand

the GlassFish v3 Domainnode.

In the GlassFish v3 Domain

node, expand the

Applications node.

You should see EJ B31 as a

deployed application.

Exercise 4: Testing theHel l oWor l dBean

In this exercise, you will build a client to test thefunctionality of the EJB you created. More information

about EJB clients will be discussed in the following

module. For now, let the NetBeans IDE do its magic to

make your client functional.

This exercise contains the following sections:

“Task 1 - Implement the ej b31. Mai n Class”

“Task 2 - Run the Mai n application”

Task 1 - Implement the

ej b31. Mai n ClassIn this task, you create and implement the Mai n class.

The version you create in this module has the minimal

functionality required to test the invocation of the

sayHel l o method of the Hel l oWor l dBean

session bean instance executing in a Java EE application

server.

Complete the following steps:

1. Open the Mai n. j ava class in the source code

editor window.

Click the Projects tab of the IDE, locate and

open the Mai n. j ava file.

2.

3.

EJ B31- app- cl i ent < Sour cePackages < ej b31 < Mai n. j avaInsert the code required to call the EJB:

a.

 b.

c.

d.

e.

Right-click in the main method of the

Main class and select Insert code.

Select Call Enterprise Bean from the

Generate pop-up menu.

Select Hel l oWor l dBean from the

Call Enterprise Bean dialog.

Click the OK button.

Ensure that a static instance variablenamed hel l oWor l dBean was

created.

Modify the mai n method to invoke the EJB.

publ i c st at i c voi d mai n( St r i ng[ ]args) {

Syst em. out . pr i nt l n( "Mai n. mai n: cal l i ngHel l oWor l dBean") ;

St r i ng gr eet i ng =hel l oWor l dBean. sayHel l o( ) ;

Syst em. out . pr i nt l n

( "Mai n. mai n: Hel l oWorl dBeansai d: " +gr eet i ng) ; }

Task 2 - Run the Mai n application

There are multiples ways to test the execution of the

EJ B31 application. For now, we are going to use the

Mai n application you just created in Task 1 to test the

Hel l oWor l dBean.

To execute the Mai n application in NetBeans, complete

the following steps:1.

2.

Verify that the EJ B31 application is deployed

and running in GlassFish.

In the Projects tab, right-click on the EJ B31 project:

a.

 b.

Select Run from the pop-up menu.

Examine the output in the EJB31 (run)

tab.

You should observe the following message in

the EJB31 (run) tab:Mai n. mai n: cal l i ngHel l oWor l dBeanMai n. mai n: Hel l oWor l dBean sai d:Hel l o EJ B Wor l d

Exercise Summary

Discussion - Take a few minutes to discuss what

experiences, issues, or discoveries you had during the

lab exercise:

Experiences

Interpretations

Conclusions

Applications

Page 10: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 10/43

 Lab 3

Accessing Session Beans

Objectives

Upon completion of this lab, you should be able to:

Complete the review questionsCreate a client that uses JNDI

Create a no-interface session bean

Transform the Hel l oWor l dBean into a

session façade

Exercise 1: Completing Review

Questions

In this exercise, you answer questions about the material

covered in the Student Guide.

Complete the following questions:

1.

2.

3.

4.

5.

6.

7.

What is the service called that provides

registry-like functionality to find references of

components within an application?

What are the two ways to find EJB components

in a Java EE application?

What global path would you use to look up the

Hel l oWor l dBean (from the previous lab)?

Remember, the application name is EJ B31.

The EJB module name is EJ B31- ej b. And

the EJB name is Hel l oWor l dBean.

What steps are involved in creating a session bean client?

What are the two ways to create a stand-alone

session bean client?

What is a session façade?

Why would you use a session façade?

Exercise 2: Creating a Stand-AloneJava SE Application

In this exercise, you create a stand-alone Java SE

application that uses JNDI to locate theHel l oWor l dBean created in the previous lab. Once

you have located the Hel l oWor l dBean, you will

invoke the sayHel l o method.

This exercise contains the following sections:

“Task 1 - Create a New Project”

“Task 2 - Download and Install Client

Libraries”

“Task 3 - Create a Stand Alone Java SE

Application”

“Task 4 - Run the Mai n Application”

Preparation

This exercise assumes the application server is installed

and running. It also assumes that you successfully

completed Lab 2, “Implementing Session Beans”. If you

did not complete Lab 2, you can use the solution as your

starting point. Solutions are found in $HOME/sol ut i ons.

As a review, the steps to create a session bean client are

as follows:

Download and install “client view” libraries of

the application.

Declare a reference to the session bean in the

client.

Locate the session bean using JNDI or

dependency injection.

Perform the operation on the session bean.

Tool Reference - Tool references used in this exercise

include:

Java Development: Java Application Projects:

Opening Projects

Java EE Development: Enterprise ApplicationProjects: Building Java EE Applications

Java EE Development: Enterprise Application

Projects: Verifying Java EE Applications

Java EE Development: Enterprise Application

Projects: Deploying Java EE Applications

Server Resources: J2EE Application Servers:

Examining Server Log Files

Java Development: Java Application Projects:

Modifying Project Libraries

Java Development: Java Classes: Modifying

Java Classes: Adding Fields

Java Development: Java Classes: ModifyingJava Classes: Adding Methods

Java Development: Java Classes: Opening Java

Classes

Java Development: Other Files: Opening Files

Java EE Application Servers: Starting

Application Servers

Task 1 - Create a New Project

In this task, you create a Java project that contains a Java

SE application. The Java SE application will referencethe EJ B31 project.

Tool Reference - Java EE Development: Enterprise

Application Projects: Creating Enterprise Application

Projects

Complete the following steps:

1.

2.

Double-click the NetBeans icon on your

desktop:

a.

 b.

If prompted with a “Start Page,” close

the page

Otherwise, you are in the primary

 NetBeans view

Create a new project:

Page 11: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 11/43

3.

a.

 b.

c.

d.

Use the File menu of the IDE and

choose

Fi l e > New Pr oj ect .

Create a Java Application. This is a

two step process defined by the “New

Java Application” wizard.

Step 1 - “Choose Project”:1.2.

3.

Cat egory > J avaPr oj ect s > J avaAppl i cat i on

Click the Next button.Step 2 - “Name and Location”:

1.

2.

3.

4.

Specify St andAl oneAppas the Project Name.

Specify D: \ Labs\ st udent \ sol ut i onsdirectory for the Project

Location.

Use the default values for the

Create Main Class and the

Set as Main Project options.

Click the Finish button.

Verify the project was created properly. In theProjects tab you should see the following:

a.

 b.

c.

d.

A coffee cup icon, labeled

St andAl oneApp - This represents

the Java Application.

Under the Source Packages node, you

should see the Mai n. j ava file.

Edit the mai n method of Mai n to

contain the following code:publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {err . pr i nt l n( "st andal oneapp. Mai n. mai n:St and- al one Appst ar t ed") ; }Run st andal oneapp. Mai n:

1.

2.

3.

Right-click the

St andAl oneApp project.

Select Run from the menu.

Examine the StandAloneApp

(run) output tab for the

message:st andal oneapp. Mai n. mai n:

Stand- al one App st ar t ed

Task 2 - Download and InstallClient Libraries

Because you are using the NetBeans IDE as the

development environment, you do not need to download

the client libraries from the server. Instead, you will need

to configure the St andAl oneApp project to reference

the client libraries (for the EJB module) of the EJ B31 project.

Additionally, you will need to configure the

St andAl oneApp project to reference the GlassFish

runtime libraries. This will enable you to use the

GlassFish JNDI provider implementation:

1.

2.

Add the EJ B31- ej b libraries to

St andAl oneApp:

a.

 b.

c.

d.

e.

Right-click the Libraries node under

St andAl oneApp in the Projects tab

of the NetBeans IDE.

Select Add Project.

In the Add Project dialog, expand the

EJB31 project and select EJ B31-ej b.

Click the Add Project Jar Files button.

Verify the library was added correctly

 by examining the Libraries node.St andAl oneApp > Li br ar i es >EJ B31- ej b - di st / EJ B31- ej b. j arAdd the GlassFish runtime libraries to

St andAl oneApp:

a.

 b.

c.

d.

e.

Right-click the Libraries node under

St andAl oneApp in the Projects tab

of the NetBeans IDE.

Select Add Jar/Folder.

 Navigate to the directory D:\ Progr amFi l es\ sges- v3\ gl assf i sh\ l i b in the file

chooser.

Add the runtime libraries by choosing

the file named 

appser v- r t and clicking the Open

 button. (If appser v- r t is not

 present in the location, use the

windows search to find the file.)

Verify the library was added correctly by examining the Libraries node. You

should see appserv- r t . j ar in the

list.

Task 3 - Create a Stand Alone JavaSE Application

In this task, you will implement the

st andal oneapp. Mai n program to perform the JNDI

global lookup of the Hel l oWor l dBean and invoke the

sayHel l o method.

Complete the following steps:

1.

2.

Open the Mai n. j ava class in the source code

editor window if it is not already open.

Use the Projects tab of the IDE to locate and

open the Mai n. j ava file.

St andAl oneApp > Source Packages> st andal oneapp > Mai n. j avaInclude the following import statements:i mporthel l owor l d. beans. Hel l oWor l dBeanR

emot e;

Page 12: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 12/43

3.

4.

i mpor t j avax. nami ng. *;Declare a static instance variable named

hel l oWor l dBean.

pr i vat e stat i cHel l oWor l dBeanRemot ehel l oWor l dBean;Modify the mai n method to invoke the EJB.publ i c st at i c voi d mai n( St r i ng[ ]ar gs) {St r i ng j ndi Pat h = " j ava: gl obal /

EJ B31/ EJ B31- ej b/ Hel l oWor l dBean" ;t ry {Cont ext ct x = new I ni t i al Cont ext( ) ; Syst em. out . pr i nt l n( "st andal oneapp. Mai n. mai n:l ooki ng up bean at : " + j ndi Pat h) ;hel l oWor l dBean =( Hel l oWor l dBeanRemot e)ctx. l ookup( j ndi Pat h) ;Syst em. out . pr i nt l n( "st andal oneapp. Mai n. mai n: f ound

Hel l oWor l dBean: "+hel l oWor l dBean) ;Syst em. out . pr i nt l n( "st andal oneapp. Mai n. mai n:cal l i ng sayHel l o") ; St r i nggreet i ng =hel l oWor l dBean. sayHel l o() ;Syst em. out . pr i nt l n( "st andal oneapp. Mai n. mai n:Hel l oWor l dBean sai d: " +gr eet i ng) ;} cat ch ( Nami ngExcept i on ex)

{ Syst em. er r . pr i nt l n( "st andal oneapp. Mai n. mai n: Coul dnot f i ndHel l oWor l dBeanRemot e") ;er r . pr i nt l n( "st andal oneapp. Mai n. mai n: J NDIpath used f or l ookup: " + j ndi Pat h) ;pr i nt St ackTr ace( ) ;}}}

Task 4 - Run the Mai n Application

There are multiples ways to test the execution of the

EJ B31 application. For now, we are going to use the

Mai n application you just created in ??Task 1 - Create a

 New Project?? on page L3-4 to test the

Hel l oWor l dBean.

To execute the Mai n application in NetBeans, complete

the following steps:

1. Verify that the EJ B31 application is deployed

and running in GlassFish.

2. In the Projects tab, right-click on the

St andAl oneApp project:

a.

 b.

Select Run from the pop-up Menu.

Examine the output in the

StandAloneApp (run) tab.

You should observe output similar to the

following in the StandAloneApp (run) tab:

st andal oneapp. Mai n. mai n: l ooki ng upbean at : j ava: gl obal / EJ B31/ EJ B31- ej b/

Hel l oWor l dBeanMai n. mai n: f ound Hel l oWorl dBean:hel l owor l d. beans. _Hel l oWorl dRemot e_Wr apper@2c9b19dfst andal oneapp. Mai n. mai n: cal l i ng

sayHel l o st andal oneapp. Mai n. mai n:Hel l oWor l dBean sai d: Hel l o EJ B Wor l d

Note

The number inhel l oworl d. beans. _Hel l oWor l dRemot e_Wr apper@2c9b19df may vary.

Exercise 3: Creating a SessionFaçade

In this exercise, you will transform the

Hel l oWor l dBean into a session façade. The session

façade will delegate the sayHel l o functionality to the

local stateless session bean.This exercise contains the following sections:

“Task 1 - Create

 Ti meBasedHel l oWor l dBean”

“Task 2 - Modify Hel l oWor l dBean”

“Task 3 - Build and Deploy the EJ B31Application”

“Task 4 - Test the Session Façade”

Preparation

This exercise assumes that the application server isinstalled and running. As a review, the steps to create a

session bean are as follows:

1.

2.

3.

4.

5.

Declare a business interface for the session

 bean or use a no-interface implementation.

Annotate the business interface with the desired

client access mode.

Create a class that implements the business

interface.

Annotate the class with the desired session bean

type.

Package the session bean.

You will be using the EJB creation wizard provided by

Page 13: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 13/43

the NetBeans IDE.

Task 1 - Create Ti meBasedHel l oWor l dBean

In this task, you create and implement a local stateless

session bean named Ti meBasedHel l oWor l dBean.

 Ti meBasedHel l oWor l dBean generates a greeting

 based on the period of day.

 Ti meBasedHel l oWor l dBean is accessed byHel l oWor l dBean:

1.

2.

3.

4.

5.

6.

Right-click on the EJ B31- ej b module in the

Projects tab and choose:New > Sessi on BeanFill in the EJB information in the wizard to

create a no-interface stateless session bean:

a.

 b.

c.

d.

Specify

 Ti meBasedHel l oWor l dBean as

the EJB Name.

Define the package as

hel l owor l d. beans.

Leave Stateless selected for the

Session Type.

Click the Finish button.

Verify the EJB was created properly by

examining the Source Packages node of the

EJ B31- ej b module in the Projects tab:a.

 b.

hel l owor l dbeans. Ti meBasedHel l oWor l dBean - Represents the

 business interface and the

implementation of the EJB.

@Local Bean(within the

 Ti meBasedHel l oWor l dBean. j ava) - Denotes the EJB is a no-

interface, local bean.

Add an import statement for

 j ava. ut i l . Cal endar .i mpor t j ava. ut i l . Cal endar ;Implement the sayHel l o method in the

 Ti meBasedHel l oWor l dBean:

a.

 b.

Right-click in the editor and chooseI nser t Code > Add Busi nessMet hodSpecify the method information as

follows:1.

2.

3.

 Name: sayHel l oReturn Type: St r i ngClick the OK button.

Modify the sayHel l o method created in the

source to return a time- sensitive greeting, as

follows:publ i c St r i ng sayHel l o( ) {St r i ng gr eet i ng = " Zzzzzzz" ;Cal endar cal =Cal endar . get I nst ance( ) ;

i nt hour Of Day = cal . get( Cal endar . HOUR_OF_DAY) ;

i f ( hour Of Day > 6 && hour Of Day <12) {

gr eet i ng = "Good Morni ng" ;} el se i f ( hourOf Day >= 12 &&hourOf Day < 16) {

gr eet i ng = "Good Af t ernoon" ;} el se i f ( hourOf Day >= 16 &&hourOf Day < 19) {

gr eet i ng = "Good Eveni ng" ;} el se i f ( hourOf Day >= 19 &&hourOf Day < 22) {

gr eet i ng = "Good Ni ght " ;}

r et ur n gr eet i ng;}

Task 2 - ModifyHel l oWor l dBean

In this task, you will transform the Hel l oWor l dBeaninto a session façade.

Complete the following steps:1.

2.

3.

Open the Hel l oWor l dBean. j ava file in the

source code editor window.

Add a reference to

 Ti meBasedHel l oWor l dBean:

a.

 b.

c.

d.

Right-click in the editor and chooseI nsert Code > Cal lEnt er pr i se Bean.

Select Ti meBasedHel l oWor l dBeanfrom the list.

Click the OK button.

Review the @EJ B declaration that was

inserted.@EJ Bpr i vat e Ti meBasedHel l oWor l dBeant i meBasedHel l oWor l dBean;

Modify the sayHel l o method to invoke the

sayHel l o method of the

 Ti meBasedHel l oWor l d and return the

result.publ i c St r i ng sayHel l o( ) {

returnt i meBasedHel l oWorl dBean. sayHel l o( ) ; }

Task 3 - Build and Deploy theEJ B31 Application

In this task, you build, verify, and deploy the EJB31

EAR file on a Java EE application server.

Complete the following steps:

1. Build the EJ B31 application:

a. Right-click on the EJ B31 application

Page 14: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 14/43

2.

3.

4.

 b.

and select Build.

Verify there were no errors during the

 build of the EJ B31 application by

reviewing the output in the EJB31

(dist) tab.

Verify that a distribution of the application was

created by using the Files tab of the IDE. Check

that the following file has been created:

a.

 b.

c.

EJ B31/ di st / EJ B31. ear - the

application

EJ B31- app- cl i ent / di st /EJ B31- app- cl i ent . j ar - the

application clientEJ B31- ej b/ di st / EJ B31-ej b. j ar - the EJB module

(containing Hel l oWor l dBean)

Note

If the EJ B31. ear file does not exist, try

rebuilding the entire EJB31 project.

Deploy the EJ B31 application.

IDE Proj ect s tab > Right-click EJ B31 >Depl oyVerify the deployment of the EJB31 application

worked:

a.

 b.

Review the output in the EJB31 (run-

deploy) tab, looking for any

unexpected errors.

Review the deployed Applications of

the GlassFish server.:

1.

2.

3.

In the Services tab, expandthe Servers node.

In the Servers node, expand

the GlassFish v3 Domain

node.

In the GlassFish v3 Domain

node, expand the

Applications node.

You should see EJ B31 as a deployed

application.

Task 4 - Test the Session FaçadeThere are two applications that can be used to test the

execution of the session façade:

st andal oneapp. Mai n and ej b31. Mai n. You will

use both applications to test the façade functionality.

They should yield the same results.

You do not need to make any modifications to either

application to test the newly created

 Ti meBasedHel l oWor l dBean.

To execute the ej b31. Mai n application in NetBeans,

complete the following steps:

1. Verify that the EJ B31 application is deployed

2.

and running in GlassFish.

In the Projects tab, right-click on the EJ B31 project:

a.

 b.

Select Run from the pop-up menu.

Examine the output in the EJB31 (run)

tab.

You should observe the output similar to the

following:Mai n. mai n: cal l i ngHel l oWor l dBean

mai n: Hel l oWor l dBean sai d: GoodAf t er noonTo execute the st andal oneapp.Mai n application in

 NetBeans, complete the following steps:

1.

2.

Verify the EJ B31 application is deployed and

running in GlassFish

In the Projects tab, right-click on the

St andAl oneApp project:

a.

 b.

Select Run from the pop-up Menu

Examine the output in the

St andAl oneApp ( r un) tab

You should observe the output similar to the

following:st andal oneapp. Mai n. mai n: l ooki ngup bean at : j ava: gl obal / EJ B31/EJ B31- ej b/ Hel l oWor l dBeanMai n. mai n: f ound Hel l oWor l dBean:hel l owor l d. beans. _Hel l oWor l dRemot e_Wr apper @2c9b19df st andal oneapp. Mai n. mai n: cal l i ngsayHel l ost andal oneapp. Mai n. mai n:Hel l oWor l dBean sai d: GoodAf t er noon

Note

The message may differ based on the time of

day.

Exercise Summary

Discussion - Take a few minutes to discuss what

experiences, issues, or discoveries you had during thelab exercise:

Experiences

Interpretations

Conclusions

Applications

Page 15: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 15/43

 Lab 4

Advanced Session Beans

Objectives

Upon completion of this lab, you should be able to:

Complete the review questionsTest the identity of a session bean

Write a session bean that performs life cycle

callback processing

Exercise 1: Completing ReviewQuestions

In this exercise, you answer questions about the material

covered in the Student Guide.

Complete the following questions:

1.

2.

3.

4.

5.

6.

What is the role of an EJB container?

List three characteristics of an EJB component.

What method is used to test the identify of

session beans?

List the five life cycle annotations associated

with session beans. Using a matrix, identify

which annotations apply to stateless, stateful,

and singleton session beans.

Which life cycle callback would you implement

to receive notification when a stateful session

 bean transitions from a pooled-state to the

ready- state?How do you make a method call on a session

 bean execute asynchronously?

Exercise 2: Testing the Identity of aSession Bean

In this exercise, you will modify the ej b31. Mai napplication to test the identity of the

Hel l oWor l dBean. The identity test will demonstrate

how a stateless session bean, regardless of how it?s

retrieved from the underlying naming system, has thesame identify. You will add the manual JNDI lookup to

find the Hel l oWor l dBean.

This exercise contains the following sections:

“Task 1 - Look Up Hel l oWor l dBean Using

JNDI”

“Task 2 - Test the Identity of the Beans”

“Task 3 - Run the Mai n Application”

Preparation

This exercise assumes the application server is installed

and running. It also assumes you successfully completed

Lab 2, “Implementing Session Beans,” and Lab 3,

“Accessing Session Beans,”. If you did not complete

those labs, you can use the solution as your starting

 point. Solutions are found in D: \ Labs\ st udent s\ sol ut i ons .

Task 1 - Look UpHel l oWor l dBean Using JNDI

In this task, you modify the Java EE application client

container application (ej b31. Mai n) to perform an

additional JNDI lookup of the Hel l oWor l dBean. If

the EJ B31 project is not open, reopen it before you

 begin.

Complete the following steps:

1.

2.

3.

4.

Close all of the open documents in the editor.

Open ej b31. Mai n.

EJ B31- app- cl i ent > Sour cePackages > ej b31 > Mai n. j avaAdd an import statement for the JNDI API.i mpor t j avax. nami ng. *;Add a f i ndHel l oWor l dBeanmethod to the

Mai n class that performs the JNDI lookup.

pr i vat e stat i cHel l oWor l dBeanRemot ef i ndHel l oWor l dBean( ) {St r i ng j ndi Pat h = " j ava: gl obal /EJ B31/ EJ B31- ej b/ Hel l oWorl dBean" ;Hel l oWor l dBeanRemot e bean2 =nul l ;t ry {

Cont ext ct x = new I ni t i al Cont ext( ) ;bean2 = ( Hel l oWor l dBeanRemot e)ct x. l ookup( j ndi Pat h) ;} catch ( Nami ngExcept i on ex){ Syst em. er r . pr i nt l n( "ej b31. Mai n. f i ndHel l oWor l dBean:Coul d not f i ndHel l oWor l dBeanRemot e") ;System. er r . pr i nt l n( "ej b31. Mai n. f i ndHel l oWor l dBean:

 J NDI pat h used f or l ookup: " +

 j ndi Pat h) ;ex. pr i nt St ackTr ace( ) ;}r etur n bean2;}

Task 2 - Test the Identity of theBeans

 Now that you have written the code to perform the JNDI

lookup, you will need to test the identity of the bean

reference initialized through dependency injection

Page 16: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 16/43

against the bean reference found in JNDI.

Modify the mai n method to test the identity of the

dependency injection EJB reference and the reference

returned from the f i ndHel l oWorl dBean method.

Complete the following steps:

1.

2.

3.

Add a local variable called bean2 and

initialize it with the return value of the

f i ndHel l oWor l dBean method.Hel l oWor l dBeanRemot e bean2 =f i ndHel l oWor l dBean( ) ;

Test the identity based on reference value and print the result.bool ean equal = ( hel l oWor l dBean== bean2) ; Syst em. out . pr i nt l n( "Mai n. mai n: hel l oWor l dBean ==bean2: " + equal ) ;Test the identity based on object value and print

the result.bool ean equal s =( hel l oWor l dBean. equal s( bean2) ) ;Syst em. out . pr i nt l n( "Mai n. mai n:hel l oWor l dBean. equal s( bean2) : "

+ equal s) ;

Task 3 - Run the Mai n Application

To test the identity of the two bean references

(hel l oWor l dBean and bean2), you need to run the

ej b31. Mai n method.

To execute the Mai n application in NetBeans, complete

the following steps:

1.

2.

Verify the EJ B31 application is deployed and

running in GlassFish.

In the Projects tab, right-click on the EJ B31 project:

a.

 b.

Select Run from the pop-up menu

Examine the output in the EJB31 (run)

tab

You should observe output similar to:Mai n. mai n: cal l i ngHel l oWor l dBeanMai n. mai n: Hel l oWor l dBean sai d:Good Eveni ngMai n. mai n: hel l oWor l dBean ==bean2: f al seMai n. mai n: hel l oWor l dBean. equal s( bean2) : t r ue

Exercise 3: Creating a Stateful

Session Bean

In this exercise, you will create a stateful session bean

that demonstrates the transition state transitions.

This exercise contains the following sections:

“Task 1 - Create a Gr eet i ngRequest

Object”

“Task 2 - Create a Stateful Session Bean”

“Task 3 - Add Stateful Business Logic”

“Task 4 - Iteratively Test Bean”

“Task 5 - Test Bean State”

“Task 6 - Add Callbacks to

St atef ul Hel l oWor l dBean”

Preparation

This exercise assumes that the application server is

installed and running. As a review, the steps to create a

session bean are as follows:

Declare a business interface for the session

 bean or use a no-interface implementation.

Annotate the business interface with the desired

client access mode.

Create a class that implements the business

interface.

Annotate the class with the desired session bean

type.

Package the session bean.

You will be using the EJB creation wizard provided bythe NetBeans IDE.

Task 1 - Create aGr eet i ngRequest Object

In this task, you will create an object that represents a

greeting request. A greeting request is comprised of a

timestamp and the greeting.

Complete the following steps:

1.

2.

3.

Right-click on the EJ B31- ej b module in the

Projects tab and choose:New > J ava Cl assFill in the wizard to create the Java class:

a.

 b.

c.

Specify Gr eet i ngRequest as the

Class Name.

Define the package as

hel l owor l d. vo.

Click the Finish button.

Modify Gr eet i ngRequest as follows:

1 package hel l owor l d. vo;23 i mpor t j ava. ut i l . Cal endar ;4 i mpor t

 j ava. t ext . Si mpl eDat eFor mat ;5 i mpor t

 j ava. i o. Ser i al i zabl e;67 publ i c cl assGr eet i ngRequest i mpl ement sSeri al i zabl e {89 pr i vat e Cal endarr equest Ti me;10 pr i vat e St r i ng gr eet i ng;11

Page 17: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 17/43

12 publ i c Gr eet i ngRequest( St r i ng gr eet ) {13 requestTi me =Cal endar . get I nst ance( ) ;14 gr eet i ng = gr eet ;15 }1617 publ i c St r i ng t oSt r i ng( ){18 Si mpl eDat eFor matdat eFor mat = newSi mpl eDat eFor mat ( ) ;19 St r i ng dat eAsSt r =dateFormat . f or mat( r equest Ti me. get Ti me( ) ) ;20 r et ur n"hel l owor l d. vo. Gr eet i ngRequest[ r equest Ti me="+ dat eAsSt r +21 " , greet i ng="+greet i ng+"] " ;22 }23 }

Task 2 - Create a Stateful Session

Bean

In this task, you create and implement a remote stateful

session bean named Stat ef ul Hel l oWor l dBean.

St at ef ul Hel l oWor l dBean keeps track of the

number times it has been asked for a greeting from one

 particular client.

Complete the following steps:

1.

2.

3.

Right-click on the EJ B31- ej b module in the

Projects tab and choose:New > Sessi on BeanFill in the EJB information in the wizard to

create a stateless session bean:

a.

 b.

c.

d.

e.

Specify

St at ef ul Hel l oWor l dBean as

the EJB Name

Define the package ashel l owor l d. beansSelect the Stateful Session Type

Select Remote Interface of the Create

Interfaces check boxes.

Click the Finish button.

Implement the sayHel l o method in the

St at ef ul Hel l oWor l dBean:

a.

 b.

Right-click in the editor and choose:I nser t Code > Add Busi nessMet hodSpecify the method information as

follows:

1.

2.

3.

 Name: sayHel l oReturn Type:Gr eet i ngRequest

Ensure the Remote radio

4.

c.

4.

 button is selected.

Click the OK button.

Add an import statement for the

GreetingRequest to

St at ef ul Hel l oWor l dBean and

St at ef ul Hel l oWor l dBeanRemot e.i mporthel l owor l d. vo. Gr eet i ngRequest;

Implement the sayGoodBye method in theSt at ef ul Hel l oWor l dBean:

a.

 b.

Right-click in the editor and choose:I nser t Code > Add Busi nessMet hodSpecify the method information as

follows:

1.

2.

3.

4.5.

 Name: sayGoodByeReturn Type:Gr eet i ngRequest [ ]Ensure the Remote radio

 button is selected 

Click the OK button.Review the modifications

made to the remote interface.

Task 3 - Add Stateful BusinessLogic

In this task, you will create and implement the business

logic that tracks the number of times and when a client

asks for a greeting.

Complete the following steps:

1.

2.

3.

4.

5.

Add the following import statements if they do

not exist:i mporthel l owor l d. vo. Gr eet i ngRequest ;i mpor t j avax. ej b. St at ef ul ;i mpor t j ava. ut i l . *;Declare an instance variable for the no-interface

stateless bean.i mpor t j avax. ej b. EJ B;@EJ Bpr i vat e Ti meBasedHel l oWor l dBeant i meBasedHel l oWor l dBean;

Declare an instance variable of type Li st .

pr i vat e Li st <Gr eet i ngRequest >greet i ngRequest s;Add a constructor to initialize the

greet i ngRequest .

publ i c Stat ef ul Hel l oWor l dBean( ){gr eet i ngRequest s = newAr r ayLi st <Gr eet i ngRequest >( ) ;}Modify the sayHel l o method as follows.

publ i c Gr eet i ngRequest sayHel l o

Page 18: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 18/43

6.

( ) {St r i ng greet i ng =t i meBasedHel l oWor l dBean. sayHel l o( ) ;Gr eet i ngRequest r equest = newGr eet i ngRequest ( gr eet i ng) ;greet i ngRequest s. add( r equest ) ;r et ur n r equest ;}Modify the sayGoodBye method to be the

@Remove method for the stateful session bean.a.

 b.

c.

d.

Import the @Remove annotation.i mpor t j avax. ej b. Remove;Annotate sayGoodBye with

@Remove.

Convert the gr eet i ngRequest slist into a type-safe array.

Return the type-safe array.@Remove

publ i c Gr eet i ngRequest [ ]sayGoodBye( ) {

return

greet i ngRequest s. t oAr r ay(newGr eet i ngRequest [ ] {}) ;}

Task 4 - Iteratively Test Bean

In this task, you will perform an interative test of the

code written so far. While this task does not follow a true

test-driven development process, it allows you to

 perform a sanity check before instrumenting the session

 bean with life cycle callbacks.

To perform this task, you will create a stand-aloneapplication that performs a unit test.

Complete the following steps:

1.

2.

3.

4.

5.

6.

Close all open documents in the editor.

Right-click StandAloneApp project and select:New > Ot her > J ava Cl assFill in the wizard to create the Java class:

a.

 b.

c.

SpecifySt at ef ul Hel l oWor l dBeanTestas the Class Name

Define the package asst andal oneapp

Click the Finish button.Open the

St at ef ul Hel l oWor l dBeanTest . j avaclass in the source code editor window.

Include the following import statement:i mpor thel l owor l d. vo. Gr eet i ngRequest ;i mpor thel l owor l d. beans. St at ef ul Hel l oWor l dBeanRemot e;i mpor t j avax. nami ng. *;Declare a static instance variable named

hel l oWor l dBean.

7.

8.

9.

pr i vat e st at i cSt at ef ul Hel l oWor l dBeanRemot ehel l oWor l dBean;Open st andal oneapp. Mai n. j ava:

a.

 b.

c.

Copy the entire mai n method.

ReplaceSt at ef ul Hel l oWor l dBeanTest. mai n with the copied method.

Close

st andal oneapp. Mai n. j ava.

ModifySt at ef ul Hel l oWor l dBeanTest . mai n:

a.

 b.

c.

Modify the follow variables:

1.

2.

3.

 j ndi Path - Use the

following path:St r i ng j ndi Pat h =" j ava: gl obal / EJ B31/EJ B31- ej b/St at ef ul Hel l oWor l dBean";hel l oWor l dBean - Fix the

cast as part of the JNDI

lookup:hel l oWor l dBean =( Stat ef ul Hel l oWor l dBeanRemot e)ct x. l ookup( j ndi Pat h) ;gr eet i ng - Fix the type to

 be Gr eet i ngRequest :Gr eet i ngRequestgreet i ng =hel l oWor l dBean. sayHel l o( ) ;

Modify the Syst em. out call to

reflect the correct class name.

Remove the stateful bean by calling

sayGoodBye as the last step in the

test.Gr eet i ngRequest [ ]greet i ngs =hel l oWor l dBean. sayGoodBye( )

Run St at ef ul Hel l oWor l dBeanTest :

a.

 b.

Right-click in the editor tab.

Select Run File.You should see output similar to the following:st andal oneapp. St at ef ul Hel l oWor l dBeanTest . mai n: l ooki ng up beanat : j ava: gl obal / EJ B31/ EJ B31- ej b/St at ef ul Hel l oWor l dBeanst andal oneapp. St at ef ul Hel l oWor l dBeanTest . mai n: f oundHel l oWor l dBean:hel l owor l d. beans. _St at ef ul Hel l oWor l dBeanRemot e_Wr apper @c594c19bst andal oneapp. St at ef ul Hel l oWor l d

BeanTest . mai n: cal l i ng sayHel l o

Page 19: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 19/43

st andal oneapp. Stat ef ul Hel l oWor l dBeanTest . mai n: Hel l oWor l dBeansai d:hel l owor l d. vo. Gr eet i ngRequest[ r equest Ti me=11/ 5/ 09 2: 10PM, gr eet i ng=Good Af t er noon]

Task 5 - Test Bean State

The state of the St at ef ul Hel l oWor l dBean is the

gr eet i ngRequest s list. This task will ensure thatthe stateful bean is maintaining and managing its state

correctly. A simple way to test this is to create a f orloop. Within the body of the f or loop, call the

sayHel l o method of the bean.

Complete the following steps:

1.

2.

3.

Modify the main method to include a f or loop,

handling any exceptions generated:Gr eet i ngRequest greet i ng =hel l oWor l dBean. sayHel l o( ) ;Syst em. out . pr i nt l n

( "st andal oneapp. St at ef ul Hel l oWorl dBeanTest . mai n: Hel l oWor l dBeansai d: " + greet i ng) ;f or ( i nt i =0; i <5; i ++){ hel l oWor l dBean. sayHel l o( ) ; t r y{

 Thread. sl eep( 5000) ;} cat ch( I nt er r upt edExcept i on ex){}}Gr eet i ngRequest [ ] gr eet i ngs =hel l oWor l dBean. sayGoodBye( ) ;

Modify the mai n method to print off thegreetings returned from the

sayGoodBye method.f or ( Gr eet i ngRequest gr :gr eet i ngs) {Syst em. out . pr i nt l n( gr ) ;}Run Stat ef ul Hel l oWor l dBeanTest . A

list of all your greeting requests should be

 printed.

As an example:hel l owor l d. vo. Gr eet i ngRequest

[ r equest Ti me=11/ 5/ 09 2: 48PM, gr eet i ng=GoodAf t ernoon]hel l owor l d. vo. Gr eet i ngRequest[ r equest Ti me=11/ 5/ 09 2: 48PM, gr eet i ng=GoodAf t ernoon]hel l owor l d. vo. Gr eet i ngRequest[ r equest Ti me=11/ 5/ 09 2: 48PM, gr eet i ng=GoodAf t ernoon]hel l owor l d. vo. Gr eet i ngRequest

[ r equest Ti me=11/ 5/ 09 2: 48

PM, gr eet i ng=GoodAf t ernoon]hel l owor l d. vo. Gr eet i ngRequest[ r equest Ti me=11/ 5/ 09 2: 48PM, gr eet i ng=GoodAf t ernoon]hel l owor l d. vo. Gr eet i ngRequest[ r equest Ti me=11/ 5/ 09 2: 48PM, gr eet i ng=GoodAf t ernoon]

Task 6 - Add Callbacks toSt at ef ul Hel l oWor l dBean

In this task, you will add life cycle callback methods to

St at ef ul Hel l oWor l dBean. When a life cycle

callback method is invoked, the

St at ef ul Hel l oWor l dBean should print the list of

greeting requests.

Complete the following steps:

1.

2.

Create a method called pr i nt Li st that prints

the list of greeting requests in theSt at ef ul Hel l oWor l dBean.

pr i vat e voi d pr i nt Li st ( ){ Syst em. out . pr i nt l n( "hel l owor l d. beans. Stat ef ul Hel l oWor l dBean:greet i ngRequest s. si ze - " +gr eet i ngRequest s. si ze( ) ) ;f or ( Gr eet i ngRequest gr :greet i ngRequest s){ Syst em. out . pr i nt l n( "hel l owor l d. beans. Stat ef ul Hel l o

Wor l dBean: " + gr ) ;}}Create methods for the following life cycle

callbacks:

@Post Const r uct@Pr eDest r oy@Pr ePassi vat e@Post Act i ve

Each life cycle callback method should identify

which life cycle transition the bean is going

through and print it to the standard out.

The PrePassi vat e, Post Act i ve, and

PreDest ory methods should print off the list.

The following is an example of what a

PrePassi vate callback method could look

like:

a. Import the include statementi mport

 j avax. annot at i on. Post Construct;i mpor t

 j avax. annot at i on. Pr eDest r o

y;

Page 20: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 20/43

3.

 b.

i mpor t j avax. ej b. Post Act i vat e;i mpor t

 j avax. ej b. Pr ePass i vat e;Create the methods@Pr ePassi vat epr i vate voi d dei ni t i al i ze( ) { Syst em. out . pr i nt l n( "hel l owor l d. beans. St atef ul Hel l oWor l dBean:@PrePassi vate") ;pr i nt Li st ( ) ;};

Run thest andal oneapp. Stat ef ul Hel l oWor l dBeanTest application:

a.

 b.

Examine the StandAloneApp (run)

tab. The results should be similar to

what you experienced in Exercise 3.

Examine the GlassFish v3 Domain

tab. You should see log messages

representing the print statements ofyour life cycle call back methods.

As an example:I NFO:hel l owor l d. beans. St at ef ul Hel l oWor l dBean: sayi ng goodbyeI NFO:hel l owor l d. beans. St at ef ul Hel l oWor l dBean: @Pr eDest r oy

Exercise Summary

Discussion - Take a few minutes to discuss what

experiences, issues, or discoveries you had during the

lab exercise:

Experiences

Interpretations

Conclusions

Applications

Page 21: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 21/43

 Lab 5

Singleton Session Bean

Objectives

Upon completion of this lab, you should be able to:

Complete the review questionsCreate a singleton session bean

Manage singleton dependencies

Exercise 1: Completing ReviewQuestions

In this exercise, you answer questions about the material

covered in Module 5, “Singleton Session Bean,” of the

Student Guide.

Complete the following questions:

1.

2.

3.

4.

5.

What is a singleton session bean?

What client-access modes does a singleton

session bean support?

Describe the singleton life cycle.

What types of concurrency are supported with

singleton session beans?

Without specifying any concurrency modifiers,

what is the default concurrency type and

strategy?

Exercise 2: Creating the SingletonIn this exercise, you will create a singleton session bean

that performs similar functionality to that of the

St at ef ul Hel l oWor l dBean.

Remember, the St at ef ul Hel l oWor l dBeanrecorded each sayHel l o method call as

aGr eet i ngRequest stored in a list. However, the

St at ef ul Hel l oWor l dBean only recorded requests

for a specific client.

In this exercise, you will create a session bean thatrecords sayHello method calls for all clients.

This exercise contains the following sections:

“Task 1 - Create the Singleton Bean”

“Task 2 - Add Tracking to Singleton”

“Task 3 - Test the SingletonHelloWorldBean”

“Task 4 - Run the Application”

Preparation

This exercise assumes that you have are familiar with

and completed Lab 4, “Advanced Session Beans,”successfully. If you have not completed Lab 4, you will

need to copy hel l owor l d. vo. Gr eet i ngRequestfrom the solutions directory into your project.

Task 1 - Create the Singleton Bean

In this task, you will create a singleton EJB using the

 NetBeans IDE. Complete the following steps:

1.

2.

3.

Right-click on the EJ B31- ej b module in the

Projects tab and select:New > Sessi on BeanFill in the EJB information in the wizard to

create a stateless session bean.

a.

 b.

c.

d.

e.

Specify

Si ngl et onHel l oWor l dBean as

the EJB Name.

Define the package as

hel l owor l d. beans.

Select Singleton for the Session Type.

Select the check box labeled Create

Remote Interface

Click the Finish button.

Review the createdSi ngl et onHel l oWor l dBean.

Make sure to note the @Si ngl et onannotation.

Task 2 - Add Tracking to Singleton

In this task, you will modify the

Si ngl et onHel l oWor l dBean to implement

functionality similar to that found in the

St at ef ul Hel l oWor l dBean. In particular, you will

create sayHel l o and sayGoodBye methods.Complete the following steps:

1.

2.

3.

4.

5.

Add the following import statements:i mpor t j avax. ej b. EJ B; i mpor t

 j ava. ut i l . *;i mport hel l owor l d. vo. *;i mport

 j avax. annot at i on. Pr eDest r oy;Declare an instance variable for the no-interface

stateless bean.@EJ Bpr i vat e Ti meBasedHel l oWor l dBean

t i meBasedHel l oWor l dBean;Declare an instance variable of type List.pr i vat e Li st <Gr eet i ngRequest >greet i ngRequest s;Add a constructor to initialize the

greet i ngRequest .publ i c Si ngl et onHel l oWor l dBean( ){gr eet i ngRequest s = newAr r ayLi st <Gr eet i ngRequest >( ) ;}Implement the sayHel l o method in the

Si ngl et onHel l oWor l dBean.

Page 22: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 22/43

6.

7.

8.

a.

 b.

c.

Right-click in the editor and chooseI nser t Code > Add Busi nessMet hod

Specify the method information as

follows:

1.

2.

3.

4.

 Name: sayHel l oReturn Type:Gr eet i ngRequestEnsure that the Remote radio

 button is selected 

Click the OK button.Modify the sayHel l o method as

follows:publ i c Gr eet i ngRequestsayHel l o( ) {St r i ng gr eet i ng =t i meBasedHel l oWor l dBean. sayHel l o( ) ;Gr eet i ngRequest r equest =new Gr eet i ngRequest( gr eeti ng) ;greet i ngRequest s. add

( r equest ) ;r et ur n r equest ;}

OpenSi ngl et onHel l oWor l dBeanRemot e. j ava and add the following import statement

i mpor thel l owor l d. vo. Gr eet i ngRequest ;Implement the auditRequests method in theSi ngl et onHel l oWor l dBean

a.

 b.

c.

Right-click in the editor and chooseI nser t Code > Add Busi ness

Met hodSpecify the method information as

follows:

1.

2.

3.

4.

5.

 Name: audi t Request sReturn Type:Gr eet i ngRequest [ ]Ensure the Remote radio

 button is selected.

Click the OK button.

Review the modifications

made to the remote interface.

Modify the audi t Request method

to return a current snapshot of the list

elements.publ i c Gr eet i ngRequest [ ]audi t Request s( ) {r et ur ngreet i ngRequest s. t oAr r ay( new Gr eet i ngRequest [ ]{}) ;}

Implement a @Pr eDest r oy life cycle

callback named destroy:

a. Iterate through the list of greetingrequest.

 b.

c.

Print each request in the list.

 Nullify the list.@Pr eDest r oypr i vat e voi d dest r oy( ) {Syst em. out . pr i nt l n( "hel l owor l d. beans. Si ngl etonHel l oWor l dBean:@PreDest r oy") ;f or ( Gr eet i ngRequest gr :greet i ngRequest s) {Syst em. out . pr i nt l n( gr ) ;}greet i ngRequest s = nul l ;}

Task 3 - Test theSi ngl et onHel l oWor l dBean

In this task, you will do an iterative test of the code

written so far. While this task does not follow a true test-

driven development process, it allows you to perform a

sanity check before instrumenting the session bean withlife cycle callbacks.

To perform this task, you will create a stand-alone

application that performs a unit test.

Complete the following steps:

1.

2.

3.

4.

5.

6.

7.

Right-click StandAloneApp project and selectNew > Ot her > J ava Mai n Cl ass

Fill in the wizard to create the Java class:

a.

 b.

c.

SpecifySi ngl et onHel l oWor l dBeanTest as the Class Name.

Define the package as standaloneapp.

Click the Finish button.Open theSi ngl et onHel l oWor l dBeanTest . j avaclass in the source code editor window.

Include the following import statement:i mporthel l owor l d. vo. Gr eet i ngRequest ;i mporthel l owor l d. beans. Si ngl et onHel l oWor l dBeanRemot e;i mpor t j avax. nami ng. *;Declare a static instance variable named

helloWorldBean.pr i vat e st at i cSi ngl et onHel l oWor l dBeanRemot ehel l oWor l dBean;Open st andal oneapp. Mai n. j ava.

a.

 b.

c.

Copy the entire main method.

Replace the

SingletonHelloWorldBeanTest.main

method with the copied method.

Close standaloneapp.Main.java.

Modify the

SingletonHelloWorldBeanTest.main.a. Modify the following variables:

Page 23: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 23/43

 b.

c.

1.

2.

3.

 j ndi Pat h - Use the

following path:St r i ng j ndi Pat h =" j ava: gl obal / EJ B31/EJ B31- ej b/Si ngl et onHel l oWor l dBean";hel l oWor l dBean - Fix the

cast as part of the JNDI

lookup.

hel l oWor l dBean =( Si ngl et onHel l oWor l dBeanRemot e)ct x. l ookup( j ndi Path) ;gr eet i ng - Fix the type to

 be GreetingRequest.Gr eet i ngRequestgreet i ng =hel l oWor l dBean. sayHel l o( ) ;

Modify the Syst em. out call to

reflect the correct class nameAudit the singleton bean by calling the

audi t Request s method Gr eet i ngRequest [ ] audi t =hel l oWor l dBean. audi t Request s ( ) ;Syst em. out . pr i nt l n( "Si ngl et onHel l oWor l dBeanTest . mai n: number ofsayHel l or equest s made onSi ngl et on: " +

audi t . l ength) ;

Note

Before running the application, make sure appserv-

rt.jar is included as one of the libraries for your

 project.

Task 4 - Run the Application

To execute the application in NetBeans, complete the

following steps:

1.

2.

Verify that the EJB31 application is deployed

and running in GlassFish.

In the Editor tab, right-click on the

SingletonHelloWorldBeanTest.

a.

 b.

Select Run from the pop-up menu

Examine the output in the

StandAloneApp (run) tab.

You should observe a message similar to the

following in the tab:

Si ngl et onHel l oWor l dBeanTest . mai n

: l ooki ng up bean at : j ava: gl obal / EJ B31/ EJ B31- ej b/Si ngl et onHel l oWor l dBean

Si ngl et onHel l oWor l dBeanTest . mai n: f ound Si ngl et onHel l oWor l dBean:

hel l owor l d. beans. _Si ngl et onHel l oWor l dBeanRemot e_Wr apper @5aeef f c8Si ngl et onHel l oWor l dBeanTest . mai n

: cal l i ng sayHel l oSi ngl et onHel l oWor l dBeanTest . mai n: bean sai d:hel l owor l d. vo. Gr eet i ngRequest[ r equest Ti me=11/ 6/ 09 10: 23AM, gr eet i ng=GoodMor ni ng]Si ngl et onHel l oWor l dBeanTest . mai n: number of sayHel l o r equest smade onSi ngl et on: 1

Note

To experience the Singleton aspect of the

 bean, try running the

SingletonHelloWorldBeanTest multiple

times. You will see the the number of

requests increase.

Exercise 3: Managing Singleton

DependenciesThe previous exercise and previous labs referenced the

TimeBasedHelloWorldBean to derive a time-sensitive

greeting. Even though the TimeBasedHelloWorldBean is

stateless, under certain circumstances and load, more

instances of the bean may exist in memory than is

necessary.

In this lab, you will modify the

 Ti meBasedHel l oWor l dBean to function as a

@Singleton. Additionally, you will manage the singleton

initialization dependency between the

Si ngl et onHel l oWor l dBean and the Ti meBasedHel l oWor l dBean.

Functionally, you should not see any difference in the

execution of the test program created in Exercise 2.

This exercise contains the following sections:

“Task 1 - Modify

 Ti meBasedHel l oWor l dBean”

“Task 2 - Manage Singleton Dependencies”

“Task 3 - Run the Application”

Task 1 - Modi f y

Page 24: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 24/43

 Ti meBasedHel l oWor l dBean

The purpose of this task is to convert the

TimeBasedHelloWorldBean into a singleton. In this task,

you will modify the TimeBasedHelloWorldBean created

in Lab 3, Exercise 3, “Creating a Session Façade”.

Complete the following steps:

1.

2.

3.

4.

5.

Close all open documents in the Editor.

Open TimeBasedHelloWorldBean.javaEJ B31- ej b > Sour ce Packages >

hel l owor l d. beans>Ti meBasedHel l oWor l dBean. j avaConvert the EJB to a singleton.

a.

 b.

Comment out the @Stat el essannotation./ *@St atel ess* /Add a @Si ngl et on annotation.

Add a @Post Const r uct method to print

when the EJB is created.pr i vat e voi d post Const r uct ( ) {Syst em. out . pr i nt l n( "Ti meBasedHel l oWor l dBean. post Co

nstruct");}Add the appropriate import statements.i mpor t j avax. ej b. Si ngl eton;i mpor t

 j avax. annot at i on. Post Const r uct ;

Task 2 - Manage SingletonDependencies

The purpose of this task is to illustrate how to manage

the singleton initialization dependencies.

In this task, you will manage the initialization

dependencies between the

Si ngl et onHel l oWor l dBean and the

 Ti meBasedHel l oWor l dBean into a singleton.

Because the Si ngl et onHel l oWor l dBean’ sexistence is dependent on the existence of the

 Ti meBasedHel l oWor l dBean, the

 Ti meBasedHel l oWor l dBean needs to be created

first.

Complete the following steps:

1.

2.

OpenSi ngl et onHel l oWor l dBean. j ava.EJ B31- ej b > Sour ce Packages >hel l owor l d. beans>Si ngl et onHel l oWor l dBean. j avaAnnotate the EJB to define its initialization

dependency.@Si ngl et on@DependsOn( "Ti meBasedHel l oWor l dBean" )publ i c cl assSi ngl et onHel l oWor l dBean

i mpl ement s . . .

3.

4.

Add a @Post Const r uct method to print

when the EJB is created.@Post Const r uctpr i vat e voi d post Const r uct ( ) {Syst em. out . pr i nt l n( "Si ngl et onHel l oWor l dBean. post Construct");}Add the appropriate import statements.

i mport j avax. annot at i on. Post Const r uct ;i mpor t j avax. ej b. DependsOn;

Task 3 - Run the Application

To execute the application in NetBeans, complete the

following steps:

1.

2.

Redeploy the EJ B31 application to GlassFish.

a.

 b.

Examine the GlassFish v3 Domain

tab.

You should see the

@Post Const r uct messages for the

two EJBs. Ti meBasedHel l oWor l dBean. post Const r uctSi ngl et onHel l oWor l dBean. post Const r uct

Note

If you don’t see the @PostConstruct

messages upon deployment, the server is performing lazy instantiation. Check the

output again after running the

SingletonHelloWorldBeanTest.

Run the

Si ngl et onHel l oWor l dBeanTest .a.

 b.

OpenSi ngl et onHel l oWor l dBeanTest . j ava.

In the Editor tab, right-click on theSi ngl et onHel l oWor l dBeanTes

t 1.

2.

Select Run from the pop-up

menu.

Examine the output in the

StandAloneApp (run) tab.

You should observe

something like the following

message:Si ngl et onHel l oWor l dBeanTest . mai n: l ooki ng up bean at :

 j ava: gl obal / EJ B31/ EJ B31- ej b/Si ngl et onHel l oWor l dBean

Si ngl et onHel l oWor l dBeanTest . mai n

Page 25: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 25/43

: f ound Si ngl et onHel l oWor l dBean:hel l owor l d. beans. _Si ngl et onHel l oWor l dBeanRemot e_Wr apper @5aeef f c8Si ngl et onHel l oWor l dBeanTest . mai n: cal l i ng sayHel l oSi ngl et onHel l oWor l dBeanTest . mai n: bean sai d:hel l owor l d. vo. Gr eet i ngRequest[ r equest Ti me=11/ 6/ 09 10: 23AM, gr eet i ng=GoodMor ni ng]Si ngl et onHel l oWor l dBeanTest . mai n: number of sayHel l o r equest smade onSi ngl et on: 3

Exercise Summary

Discussion - Take a few minutes to discuss what

experiences, issues, or discoveries you had during the

lab exercise:

Experiences

InterpretationsConclusions

Applications

Page 26: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 26/43

 Lab 6 

Developing Java EE ApplicationsUsing Messaging

Objectives

Upon completion of this lab, you should be able to:

Complete the review questions

Use the JMS API to create and send a message

Exercise 1: Completing ReviewQuestions

In this exercise, you answer questions about the material

covered in Module 6, “Developing Java EE Applications

Using Messaging,” of the Student Guide.

Complete the following questions:1.

2.

3.

4.

5.

What is the Java Messaging System?

List the five key concepts found in a messaging

solution.

List the JMS API components that correspond

to the five key messaging concepts.

What are the two types of destinations in JMS?

What is the structure of a Message?

Exercise 2: Preparing the Exercise

EnvironmentIn this exercise, you will create the necessary JMS

connections and destinations required to build a JMS

solution.

This exercise contains the following sections:

“Task 1 - Create Server Resources”

“Task 2 - Verify the JMS Resources”

Preparation

This exercise assumes the application server is installed

and running.Tool Reference - Tool references used in this exercise

include:

Server Resources: Messaging: JMS Resource

Server Resources: Java EE Application Servers:

Administrating JMS: Creating Physical

Destinations

Server Resources: Configuring Java EE

Resources: Configuring JMS Connection

Factories

Server Resources: Configuring Java EE

Resources: Configuring JMS Destination

Resources

Task 1 - Create Server Resources

In this task, you will use the NetBeans IDE to create the

necessary server resources. Specifically, you will create

a Connect i onFact ory and a Dest i nat i on.

Note

Setting up JMS resources can also be performed

through the server administration console. Refer to the

GlassFish documentation for more information.

Complete the following steps:

1.

2.

3.

Create a new JMS Physical Destination.

a.

 b.

c.

d.

Right-click the EJB31 project and

selectNew > Ot herIn the New File dialog, (Step 1 of 3):

1.

2.

Choose the GlassFish

category.

Select JMS Resource from

the File Types.

In the New JMS Resource dialog (Step

2 of 3):

1.

2.

3.

Specify j ms/Hel l oWor l dQueue as the

JNDI Name,

Select j avax. j ms. Queuefrom Admin Object Resource.

Click the Next button.

In the JMS Properties view (Step 3 of

3):1.

2.

Specify

Hel l oWor l dQueue as the

Value

Click the Finish button.

Create a new JMS Connection Factory.

a.

 b.

c.

Right-click the EJB31 project and

selectNew > Ot herIn the New File dialog, (Step 1 of 3):

1.

2.

Choose the GlassFish

category.

Select JMS Resource fromthe File Types.

In the New JMS Resource dialog (Step

2 of 3):

1.

2.

3.

Specify j ms/Hel l oWor l dQueueFact or y as the JNDI Name.

Select j avax. j ms. QueueConnect i onFact or y as the

Connection Resource.

Click the Finish button.

Build and Deploy the EJ B31 application

Page 27: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 27/43

Task 2 - Verify the JMS Resources

In this task, you will verify the JMS resources were

created properly. You can either log in to the

administration console of GlassFish or perform the

verification using NetBeans.

Complete the following steps:

1.

2.

Verify that the EJ B31 application deployed

 properly.

Click the Services tab.

a.

 b.

c.

Expand Ser vers > Gl assFi shv3 Domai n > Resour ces >Connect ors .

To verify that the JMS Queue was

created, expand Admi n Obj ectResour ces. You should see j ms/Hel l oWor l dQueueTo verify that the JMS Connection

Factory was created, expandConnect or Connect i on

Pool s . You should see j ms/Hel l oWor l dQueueFact or y.

Note

If you do not see the JMS resources, try restarting and

redeploying your application.

Exercise 3: Write a JMS Message

ProducerIn this exercise, you will create a Java EE application

client container application. The client application will

function as a JMS Message producer. In the next Lab

“Developing Message-Driven Beans,” you will write a

JMS message consumer as a message-driven bean.

This exercise contains the following sections:

“Task 1 - Create a Message Producer

Application”

“Task 2 - Modify the

MessagePr oducer App”

“Task 3 - Run the Application”

Preparation

This exercise assumes you completed Exercise 2

successfully.

Task 1 - Create a Message ProducerApplication

Complete the following steps:

1.

2.

Right-click EJB31-app-client and selectNew > J ava Mai n Cl ass

a.

 b.

Class Name:MessagePr oducer AppPackage: ej b31

Edit MessageProducer App. j ava.

a.

 b.

c.

d.

e.

f.

Right-click in the editor within the

main method and selectI nser t Code > Send J MSMessage

In the Send JMS Message Dialog,select the following options:

1.

2.

Server Destinations: j ms/Hel l oWor l dQueueConnection Factory: j ms/Hel l oWor l dQueueFact or y

Modify the @Resource annotations;

change mappedName to l ookup.@Resour ce( l ookup = "j ms/Hel l oWor l dQueue" )Modify

sendJ MSMessageToHel l oWor l dQueue andcr eat eJ MSMessageFor j msHel loWor l dQueue to be st at i c.

Review the generated methodssendJ MSMessageToHel l oWor l d

Queue andcr eat eJ MSMessageFor j msHel loWor l dQueue.

Replace the logger output with

Syst em. out or Syst em. errcalls.Syst em. er r . pr i nt l n( "Cannotcl ose sessi on - " + e) ;

Task 2 - Modify theMessagePr oducer App

In this task, you will modify the

MessageProducer App to invoke the sayHel l omethod of the Si ngl et onHel l oWor l dBean.

The Gr eet i ngRequest returned from the bean will

 be used as the message body.Complete the following steps:

1.

2.

Add a reference to the EJB.

a.

 b.

Right-click in the editor and selectI nser t Code > Cal lEnt erpr i se BeanSelectSi ngl et onHel l oWor l dBeanfrom the list.

Add the following logic to the mai n method:

a. Within the main method, invoke the

sayHel l o method of the bean.

Gr eet i ngRequest r esul t =

Page 28: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 28/43

 b.

c.

d.

si ngl et onHel l oWor l dBean. sayHel l o( ) ;Import the

helloworld.vo.GreetingRequest;i mpor thel l owor l d. vo. Gr eet i ngRequest;

Convert the Gr eet i ngRequestinto a Str i ng.St r i ng r esul t St r =

r esul t . toSt r i ng( ) ;Invoke thesendJ MSMessageToHel l oWor l dQueue method.t ry{ sendJ MSMessageToHel l oWorl dQueue( r esul t St r ) ;Syst em. out . pr i nt l n( "MessagePr oducer App. mai n:sent message - " +r esul tSt r ) ;} cat ch ( J MSExcept i on ex)

{System. er r . pr i nt l n( “MessagePr oducer App. mai n:f ai l ed t o send message - ”+ ex) ;

Task 3 - Run the Application

In order to run the application, you will need to change

the Run properties of the EJ B31- app- cl i entmodule.

Complete the following steps:1.

2.

Change the run configuration.

a.

 b.

c.

d.

Right-click EJ B31- app- cl i entand select Properties.

Select Run in the Categories pane.

Modify the Main Class to

ej b31. MessagePr oducer App.

Click the OK button.

Run the application.

You should see output similar to the following:

MessagePr oducer App. mai n: sent message- hel l owor l d. vo. Gr eet i ngRequest

[ r equest Ti me=11/ 9/ 09 11: 10AM, greet i ng=Good Mor ni ng]

Exercise Summary

Discussion - Take a few minutes to discuss what

experiences, issues, or discoveries you had during the

lab exercise:

Experiences

Interpretations

Conclusions

Applications

Page 29: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 29/43

Page 30: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 30/43

2.

3.

4.

5.

i mpor t j avax. j ms. J MSExcept i on;i mpor t j avax. j ms. Message;i mpor t

 j avax. j ms. MessageLi st ener ;i mpor t j avax. j ms. Obj ect Message;i mpor t j avax. j ms. Text Message;Include the methods to prove out the life cycle

of the MDB:

a.

 b.

Create a @Post Const r uct method.@Post Const r uct

pr i vat e voi d post Const r uct( ) {Syst em. out . pr i nt l n( "Hel l oWor l dMDB:@Post Const r uct " ) ;}Create a @Pr eDest or y method.@Pr eDest r oypr i vate voi d dest r oy( ) {Syst em. out . pr i nt l n( "Hel l oWor l dMDB:@PreDest r oy") ;

}Modify the onMessage method to only

handle messages of type Text Message. This

represents a simple message filtering technique.publ i c voi d onMessage( Messagemessage) {i f ( message i nst anceof

 Text Message) {} el se {/ / do nothi ng}}

Perform the MDB business logic:a.

 b.

c.

Convert Message into a

 Text Message using a cast.

 Text Message t ext Message =( Text Message) message;Retrieve the message value from the

 Text Message using the get Textmethod.St r i ng messageVal ue =t extMessage. getText ( ) ;Print off the message value.Syst em. out . pr i nt l n

( "Hel l oWor l dMDB. onMessage:r ecei ved t ext message - "+ messageVal ue) ;

Handle the J MSExcept i on appropriately.

Have NetBeans generate the t r y/ cat ch block on your behalf.

Task 3 - Test the MDB

In this task, you will test the MDB. Remember, a client

application cannot directly interact with the MDB. The

client application interacts with an MDB by sending a

message to a destination associated with the MDB.

In the previous lab, you created a client application

called MessageProducer App. You will use this

application to test the MDB.

Complete the following steps:

1.

2.

Verify the run configuration of the project:

a.

 b.

c.

d.

Right-click EJ B31- app- cl i ent ,

select Properties.

Select Run in the Categories pane.

Verify the Main Class is

ej b31. MessagePr oducer App.Click the OK button.

Run the application:

a.

 b.

Right-click EJ B31.

Select Run.

Click the GlassFish v3 Domain tab to see output from

the MessageProducer App similar to the following:

MessagePr oducer App. mai n: sent message- hel l owor l d. vo. Gr eet i ngRequest

[ r equest Ti me=11/ 9/ 09 12: 11

PM, greet i ng=Good Af t er noon]

You should see output from Hel l oWor l dMDB similar

to the following:

Hel l oWor l dMDB: @Post Const r uctHel l oWor l dMDB. onMessage: r ecei vedmessage -hel l owor l d. vo. Gr eet i ngRequest[ r equest Ti me=11/ 9/ 09 12: 11PM, greet i ng=Good Af t er noon]

Exercise 3: Create a MessageFaçade

In this exercise, you will create a stateless session bean

that functions as a façade to the messaging system. The

message façade will abstract the mechanics required to

send a message to the correct MDB. The

MessageFacade bean will function like all other

“hello world” beans, and provide a sayHel l o method.

Additionally, you will modify the Hel l oWor l dMDB tosupport messages of type Obj ect Message.

This exercise contains the following sections:

“Task 1 - Modify the

Si ngl et onHel l oWor l dBean ”

“Task 2 - Create a Message Façade”

“Task 3 - Modify the MDB”

“Task 4 - Test the Message Fa?ade”

Preparation

This exercise assumes you successfully completed the

Page 31: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 31/43

 previous lab.

Task 1 - Modify theSi ngl et onHel l oWor l dBean

In this task, you will modify the

Si ngl etonHel l oWor l dBean to support both

remote and no-interface client access modes. The

message fa?ade will use the no- interface client access

mode to interact with theSi ngl etonHel l oWor l dBean.

Complete the following steps:

1.

2.

Open

Si ngl et onHel l oWor l dBean. j ava.

Modify the EJB to support no-interface client

access by adding the @Local Bean annotation.

i mpor t j avax. ej b. Local Bean;

. . .

@Si ngl eton

@DependsOn( "Ti meBasedHel l oWor l dBean")

@Local Bean

publ i c cl ass Si ngl etonHel l oWor l dBeani mpl ement s . . .

Task 2 - Create a Message Façade

In this task, you will create a stateless session bean that

functions as an abstraction layer to the messaging

system.

Complete the following steps:

1.

2.

Create a remote stateless session bean called

MessageFacade within the

hel l owor l d. beans package:

a.

 b.

c.

d.

e.

Right-click on helloworld.beans >

 New > Session Bean

 Name: MessageFacadePackage: hel l oworl d. beansSession Type: Stateless

Create Interface: Remote

Modify the MessageFacade to have a

reference to the

Si ngl et onHel l oWor l dBean:

a.

 b.

c.

Ri ght - cl i ck > I nser t Code> Cal l Ent er pr i se BeanSelectSi ngl et onHel l oWor l dBeanfrom the list.

Verify that the “No Inteface” radio

 button is selected.

3.

4.

d. Click the OK button.

This should add the following line of

code to your EJB:@EJ B pr i vat eSi ngl etonHel l oWor l dBeansi ngl etonHel l oWor l dBean;

Modify the MessageFacade to have

references to the JMS destination and

connection factory:a.

 b.

c.

Ri ght - cl i ck > I nser t Code

> Send J MS MessageSelect Message Driven Bean:Hel l oWor l dMDBClick the OK button.

The following two instances variables

should be created:

@Resour ce( name = " j ms/Hel l oWor l dQueue")pr i vat e Queuehel l oWor l dQueue;@Resour ce( name = " j ms/Hel l oWor l dQueueFact ory")

pr i vat e Connect i onFact oryhel l oWor l dQueueFact ory;

 The f ol l owi ng t wo met hodsshoul d be creat ed:pr i vat e Messagecr eat eJ MSMessageFor j msHel loWor l dQueue( Sessi onsessi on, Obj ectmessageDat a) t hrows

 J MSExcept i on { . . . }pr i vat e voi dsendJ MSMessageToHel l oWor l d

Queue( Obj ect messageDat a)t hr ows

 J MSExcept i on { . . . }Modify thecr eat eJ MSMessageFor j msHel l oWor l dQueue:

a.

 b.

c.

d.

Change the method signature to return

an Obj ect Message.

Change the parameter list to accept

 j ava. i o. Ser i al i zabl e instead

of Obj ect .

Add the appropriate import statements.

i mporthel l owor l d. vo. Gr eet i ngRequest;i mport

 j ava. i o. Ser i al i zabl e;i mport

 j avax. j ms. Obj ect Message;Re-write the method to create and

return an Obj ect Message.

pri vat e Obj ect Messagecr eat eJ MSMessageFor j msHel loWor l dQueue( Sessi onsessi on, Ser i al i zabl e

Page 32: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 32/43

5.

6.

messageDat a) t hrows J MSExcept i on {Obj ect Message om =sessi on. cr eat eObj ect Message( messageDat a) ;r et urn om;}

Modify the argument list ofsendJ MSMessageToHel l oWor l dQueueto accept Ser i al i zabl e.

pr i vat e voi dsendJ MSMessageToHel l oWor l dQueue( Ser i al i zabl e messageData)t hr ows J MSExcept i on { . . . }Add the sayHel l o business logic:

a.

 b.

c.

d.

Ri ght - cl i ck > I nser t Code> Add Busi ness Met hod:

1.

2.

Define the method name as

sayHel l o.

Specify

Gr eet i ngRequest as the

return type.

Use the singleton reference to retrievea Gr eet i ngRequest .

Gr eet i ngRequest r esul t =si ngl et onHel l oWor l dBean. sayHel l o( ) ;Send the Gr eet i ngRequest to

JMS.t ry{ sendJ MSMessageToHel l oWorl dQueue( r esul t ) ;Syst em. out . pr i nt l n( "MessageFacade. sayHel l o:

sent message - " +r esul t ) ;} cat ch ( J MSExcept i on ex){System. er r . pr i nt l n( "MessageFacade. sayHel l o:err or sendi ng message - "+ex) ;}r et ur n r esul t ;Return the Gr eet i ngRequest

r esul t .

Task 3 - Modify the MDB

In this task, you will modify the Hel l oWor l dMDB to

support both messages of type TextMessage and

Obj ect Message.

If an Obj ect Message is delivered to the MDB, the

MDB should ensure that the contents are a

Gr eet i ngRequest  before processing the message.

Complete the following steps:

1.

2.

3.

4.

Open Hel l oWor l dMDB. j ava.

Modify the onMessage method to handle

messages of type Obj ect Message.

Implement the message-driven bean business

logic.} el se i f ( message i nst anceofObj ect Message) {t ry {Obj ect Message obj Message =( Obj ect Message) message; Obj ect

cont ent s = obj Message. get Obj ect( ) ;i f ( cont ent s i nst anceofGr eet i ngRequest ) { St r i ngmessageVal ue = cont ent s. t oSt r i ng( ) ; System. out . pr i nt l n( "Hel l oWor l dMDB. onMessage:r ecei ved obj ectmessage - " + messageVal ue) ;}} catch ( J MSExcept i on ex) {/ / . . .

}} el se { / / . . .Make the neccesary imports.i mporthel l owor l d. vo. Gr eet i ngRequest ;i mpor t j ava. ut i l . l oggi ng. Level ;i mpor t j ava. ut i l . l oggi ng. Logger ;i mpor t j avax. j ms. J MSExcept i on;i mport j avax. j ms. Obj ect Message;i mport j avax. j ms. TextMessage;

Task 4 - Test the Message FaçadeIn this task, you will create a simple application to test

the MessageFacade. Complete the following steps:

1.

2.

Right-click EJ B31- app- cl i ent , select

New > J ava Mai n Cl ass:

a.

 b.

Class Name:

MessageFacadeTest .

Package: ej b31.

Edit MessageFacadeTest . j ava:

a.

 b.

c.

d.

Right-click in the editor and selectI nsert Code > Cal l

Ent er pr i se BeanSelect MessageFacade from the

list.

Modify the mai n method to call

sayHel l o of the

MessageFacade.

Print the result.Gr eet i ngRequest r equest =messageFacade. sayHel l o( ) ;Syst em. out . pr i nt l n( "MessageFacadeTest . mai n:f acade sai d - " +r equest ) ;

Page 33: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 33/43

3.

4.

e. Importhel l owor l d. vo. Gr eet i ngRequest to

MessageFacadeTest andMessageFacadeTest Remot ei mpor thel l owor l d. vo. Gr eet i ngRequest;

Modify the Mai n class of the EJ B31 project to

MessageFacadeTest :

a.

 b.

c.

d.

Right-click EJ B31- app- cl i ent ,select Properties.

Select Run in the Categories pane.

Verify the Main Class is

ej b31. MessageFacadeTest .

Click the OK button.

Run the application.

You should see the output from the

MessageFacadeTest , MessageFacade ,

and the Hel l oWor l dMDB.

Example output from MessageFacadeTestmay be similar to the following:

MessageFacadeTest . mai n: f acadesai d -hel l owor l d. vo. Gr eet i ngRequest[ r equest Ti me=11/ 9/ 09 1: 09PM, gr eet i ng=Good Af t er noon]Example output from MessageFacade may

 be similar to the following:MessageFacade. sayHel l o: sentmessage -hel l owor l d. vo. Gr eet i ngRequest[ r equest Ti me=11/ 9/ 09 1: 09

PM, gr eet i ng=Good Af t er noon]Exampl e out put f r omHel l oWor l dMDB may be si mi l ar t ot he f ol l owi ng:Hel l oWor l dMDB: @Post Const r uctHel l oWor l dMDB. onMessage:r ecei ved obj ect message -hel l owor l d. vo. Gr eet i ngRequest[ r equest Ti me=11/ 9/ 09 1: 09PM, gr eet i ng=Good Af t er noon]

Exercise SummaryDiscussion - Take a few minutes to discuss what

experiences, issues, or discoveries you had during the

lab exercise:

Experiences

Interpretations

Conclusions

Applications

Page 34: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 34/43

 Lab 8

Using Timer Services

Objectives

Upon completion of this lab, you should be able to:

Complete the review questionsCreate an automatic schedule-based timer 

Create an interval-based timer to perform timer

management

Exercise 1: Completing ReviewQuestions

In this exercise, you answer questions about the material

covered in the Student Guide.

Complete the following questions:

1.

2.

3.

4.

5.

6.

What is the timer service?

What are the two ways to create a Ti mer ?

List the three ways to define a timer callback

method in an EJB.

Which EJBs can use timers?

List the three types of timers.

How do you configure a timer to live beyond

server crashes?

Exercise 2: Creating an Automatic

Timer In this exercise, you will create an automatic timer.

Remember, automatic timers are created on your behalf

 by the container.

This exercise contains the following sections:

“Task 1 - Create a Singleton Bean”

“Task 2 - Create an Automatic Timer”

“Task 3 - Test the Timer”

Task 1 - Create a Singleton Bean

In this task, you will create a singleton bean. The

singleton bean will function as a timer.

Complete the following steps:

1.

2.

Right-click on EJB31-ejb and create a singleton

session bean named

Automat i cSayHel l oBean:

Package: hel l owor l d. beans.

Session Type: Si ngl et on.

Create Interface: <none>.

Modify the bean to support eager initialization

at startup:

a. Import j avax. ej b. St ar t up.

 b. Annotate the EJB with @Star t up.

Task 2 - Create an Automatic Timer 

In this task, you will modify the

Aut omat i cSayHel l oBean. The EJB will cause the

container to automatically create a timer based on a

schedule.

The schedule will cause a timer notification to occur

ever 5 seconds. Complete the following steps:

1.

2.

3.

Declare a reference to

Si ngl et onHel l oWor l dBean:

a.

 b.

c.

Ri ght - cl i ck > I nser t Code> Cal l Ent er pr i se BeanSelect

Si ngl et onHel l oWor l dBean.

Choose the “No Interface” reference

type.

Implement a sayHel l o method:

a.

 b.

c.

d.

e.

Right-click > I nser t Code >Add Busi ness Met hod

Specify sayHel l o as the methodname.

Specify voi d as the return type.

Click the OK button.

Retrieve a Gr eet i ngRequest fromSi ngl et onHel l oWor l dBeanGr eet i ngRequest r equest =si ngl et onHel l oWor l dBean. sayHel l o( ) ;

Modify the sayHel l o method to support

timer notification:

a.

 b.

c.

d.

Change the parameter list to include a

 Ti mer .

Annotate the sayHel l o method with

@Schedul e.

Define a schedule so the timer expires

every five seconds.@Schedul e( second="*/ 5" ,mi nut e="*" , hour ="*")publ i c voi d sayHel l o( Ti mert i mer) {Gr eet i ngRequest r equest =si ngl et onHel l oWor l dBean. sayHel l o( ) ;Syst em. out . pr i nt l n( "Automat i cSayHel l oBean. sayHel l o: - " + r equest ) ;}Import the following:i mpor t j avax. ej b. Schedul e;i mporthel l owor l d. vo. Gr eet i ngRequest;i mpor t j avax. ej b. Ti mer ;

Task 3 - Test the Timer 

Page 35: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 35/43

In this task, you will test the automatic timer.

You do not need to write a client to schedule the timer

with the timer service. The creation of the timer will

automatically happen on startup.

Complete the following steps:

1.

2.

Build and deploy the application to the server.

Click the GlassFish v3 Domain tab to examine

the output.

You should see a message from the

Aut omat i cSayHel l oBean every 5 seconds.

Exercise 3: Performing TimerManagement (Optional)

In this exercise, you will create a session bean that

manages the life span of a timer. The session bean

simulates a monitoring and management application.

The session bean does not start monitoring the

Aut omat i cSayHel l oBean until it is instructed to by

a client application. Once instructed, the session bean

will monitor the Aut omat i cSayHel l oBean until it

 processes 50 notifications. At that point, the session bean

will cancel the Automat i cSayHel l oBean timer

as well as cancel the interval timer associated with

itself.

This exercise contains the following sections:

“Task 1 - Prepare

Aut omat i cSayHel l oBean for

Management”

“Task 2 - Create the

Aut omat i cManager Bean”

“Task 3 - Manage the Timer”

Preparation

This exercise assumes that you have successfully

completed Exercise 2.

Task 1 - PrepareAut omat i cSayHel l oBean for

Management

In this task, you will modify the

Aut omat i cSayHel l oBean to support monitoring

and management.

To facilitate monitoring, you will create a

get Not i f i cat i onCount method, which returns the

number of times the timer has notified the bean.

To facilitate management, you will create a

cancel Ti mer method. Complete the following steps:

1. Declare the instance variables used for

monitoring and management.pr i vat e i nt t i merNot i f i cat i ons;

pr i vat e bool ean cancel Ti mer ;

2.

3.

4.

Create the methods to support monitoring and

management:

a.

 b.

i nt get Not i f i cat i onCount -

Returns the number of notifications

that have occurred.

voi d cancel Ti mer - Changes the

cancel Ti mer variable to t rue.

Modify sayHel l o to support monitoring by

incrementing

t i merNot i f i cat i ons in every method

invocation.Modify sayHel l o to support management of

the timer.i f ( cancel Ti mer ) {t i mer . cancel ( ) ;Syst em. out . pr i nt l n( "Aut omat i cSayHel l oBean. sayHel l o: cancel l ed t i mer" ) ;}

Task 2 - Create the

Aut omat i cManager BeanIn this task, you will create a stateless session bean that

functions as monitor and management tool for

Aut omat i cSayHel l oBean. The

Aut omat i cManager Bean has one single method,

manageTi mer .

Complete the following steps:

1.

2.

3.

4.

5.

Create a remote stateless bean called

Automat i cManager Bean in the

hel l owor l d. beans package.

Add an instance variable for theAutomat i cSayHel l oBean using

dependency injection.@EJ B pr i vat eAutomat i cSayHel l oBeanaut omat i cSayHel l oBean;Add an instance variable for the

 Ti mer Servi ce using dependency injection.

@Resour ce pr i vat e Ti mer Servi cet i merServi ce;Add an instance variable for the t hreshol d.pr i vat e i nt t hreshol d;

Add a business method called manageTi merand implement it as follows:publ i c voi d manageTi mer ( i nti nt erval , i nt t hr eshol d) {t hi s. t hr eshol d = threshol d;i nt curr ent Count =automat i cSayHel l oBean. getNot i f i cat i onCount ( ) ;i f ( cur r ent Count >= t hr eshol d) {aut omat i cSayHel l oBean. cancel Ti mer ( ) ;} el se {

t i merServi ce. cr eateI nt er val Ti mer

Page 36: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 36/43

6.

7.

( i nterval , i nt erval , nul l ) ;}}Add a business method called

moni t orAut omat i cTi mer and implement

it as follows:@Ti meoutpr i vat e voi dmoni t orAut omat i cTi mer( Ti mert i mer ) {

i nt cur r ent Count =aut omat i cSayHel l oBean. get Not i f i cat i onCount ( ) ;i f ( cur r ent Count >= t hr eshol d){ aut omat i cSayHel l oBean. cancel Timer ( ) ; t i mer . cancel ( ) ;}}Import the following:i mpor t

 j avax. annot at i on. Resource;i mpor t j avax. ej b. EJ B; i mpor t

 j avax. ej b. Ti meout ; i mpor t j avax. ej b. Ti mer ;i mpor t j avax. ej b. Ti mer Ser vi ce;

Task 3 - Manage the Timer 

In this task, you will create an application that represents

a monitoring and management console. The application

will execute within a Java EE application client

container.

Complete the following steps:

1.

2.

3.

4.

Right-click EJB31-app-client > New > JavaMain class:

a.

 b.

 Name: MaMApp.

Package: ej b31.

Edit MaMApp. j ava:

a.

 b.

c.

Right-click in the editor and selectI nser t Code > Cal lEnt er pr i se BeanSelect Aut omat i cManager Beanfrom the list.

Modify the mai n method to call

manageTi mer of the

Aut omat i cManager with athreshold and interval of your choice.publ i c st at i c voi d mai n( St r i ng[ ] args) {aut omat i cManagerBean. manageTi mer( 1000 * 60, 50) ;Syst em. out . pr i nt l n( "MaMApp. mai n: st ar t edmanagement process" ) ;}

Modify the Mai n class of the EJ B31 project to

MaMApp.

Run the application.

Once the Aut omat i cSayHel l oBean has

exceeded its threshold, you should experience

its cancellation through the lack of messages

 printed to the console.

Exercise Summary

Discussion Take a few minutes to discuss what

experiences, issues, or discoveries you had during the

lab exercise:

Experiences

Interpretations

Conclusions

Applications

Page 37: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 37/43

 Lab 9

Implementing Interceptor Classesand Methods

Objectives

Upon completion of this lab, you should be able to:

Complete the review questions

Create an interceptor that performs auditing

Exercise 1: Completing ReviewQuestions

In this exercise, you answer questions about the material

covered in the Student Guide.

Complete the following questions:

1.

2.

3.

4.

5.

What software architecture design dointerceptors provide to EJBs?

List the three types of interceptors.

What annotation is used to create a business

method interceptor?

What annotation is used to associate an

interceptor with a bean?

True or False: Can you have multiple

interceptors associated with an EJB

component?

Exercise 2: Implement a TimeoutInterceptor 

In this exercise, you will create an interceptor for

Aut omat i cSayHel l o.

The interceptor will perform monitoring of the

sayHel l o method, keeping track of the number of

method calls.

This exercise contains the following sections:

“Task 1 - Create an Interceptor Class”

“Task 2 - Add Interceptor to

Aut omat i cSayHel l oBean”“Task 3 - Test the Interceptor”

Preparation

This exercise assumes you have successfully completed

Lab 8 successfully.

Task 1 - Create an Interceptor Class

In this task, you will create a class that represents an

interceptor. Complete the following steps:

1.

2.

3.

4.

Create a new Java class in the

hel l owor l d. i nt ercept ors package

called PMI nt ercept or  by right-clicking on

EJB31-ejb > New > Java class.

Create an l ong instance variable in the class

called PMI nt ercept or .pr i vat e l ongnumberOf I nvocat i ons;Implement an @Ar oundTi meout interceptor

method as follows:

@Ar oundTi meoutpubl i c Obj ect moni t or I nvocat i ons( I nvocat i onCont ext i c) t hr owsExcept i on {t ry {Obj ect r et urnVal ue = i c. proceed( ) ; i nvocat i onCount ++;Syst em. out . pr i nt f ( "PMI ntercept or . moni t or I nvocat i ons: i nvocat i on count- " , i nvocat i onCount ) ;r etur n r et ur nVal ue;

} catch ( Except i on ex){ Syst em. er r . pr i nt l n( "PMI ntercept or . moni t or I nvocat i ons: er r or occur r ed- " + ex) ;}r etur n nul l ;}Add the appropriate imports.i mport

 j avax. i nt er cept or . Ar oundTi meout ;i mport

 j avax. i nt er cept or . I nvocat i onContext ;

Task 2 - Add Interceptor toAut omat i cSayHel l oBean

In this task, you will modify the

Aut omat i cSayHel l oBean to include a method

level interceptor.

Complete the following steps:

1.

2.

3.

Open Aut omat i cSayHel l oBean. j avaImport the @I nt er cept ors annotation.i mport

 j avax. i nt er cept or . I nt er cept or s;Annotate the sayHel l o method with

@I nt er cept ors.

@I nt er cept ors( hel l owor l d. i nterceptor s. PMI nt ercept or . cl ass)@Schedul e( second="*/ 5" ,mi nut e="*" , hour ="*" )pr i vat e voi d sayHel l o( Ti mer

t i mer ) { . . . }

Page 38: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 38/43

Task 3 - Test the Interceptor 

In this task you will test the interceptor by deploying the

EJ B31 application. Once the application is deployed,

you should see the following output.

I NFO: Aut omat i cSayHel l oBean. sayHel l o:- hel l owor l d. vo. Gr eet i ngRequest

[ r equest Ti me=11/ 10/ 09 11: 07: 45PM, gr eet i ng=Zzzzzzz]

I NFO:PMI nt er cept or . moni t or I nvocat i ons:i nvocat i on count - 24

Remember, to shut down the automatic timer, either run

the MaMApp created in Lab 8, or undeploy the EJ B31application.

Exercise SummaryDiscussion - Take a few minutes to discuss what

experiences, issues, or discoveries you had during the

lab exercise:

Experiences

Interpretations

Conclusions

Applications

Page 39: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 39/43

 Lab 10

Implementing Transactions

Objectives

Upon completion of this lab, you should be able to:

Complete the review questionsImplement a mandatory transaction strategy

Create and manage a bean-managed transaction

Exercise 1: Completing ReviewQuestions

In this exercise, you answer questions about the material

covered in the Student Guide.

Complete the following questions:

1.

2.

3.

4.

5.

6.

7.

8.

Which EJB components support transactions?

What are the two types of transaction

management strategies available to an EJB?

Which of the two strategies is the default

strategy?

What annotation is used to define the

transaction management strategy for an EJB?

List three of the six transaction demarcation

 policies.

Do message-driven beans support the

SUPPORTS transaction demarcation policy?

How do you retrieve a User Transact i on

associated with bean-managed transactions?Which method of the EJ BCont ext object

would you use to request a rollback of a

transaction?

Exercise 2: Implementing aTransaction Policy

In this exercise, you will implement a MANDATORYtransaction policy on the

Aut omat i cSayHel l oBean’s cancel Ti mer

method.In order to accommodate the transaction policy, you will

modify the Automat i cManager Bean to utilize bean-

managed transactions.

This exercise contains the following sections:

“Task 1 - Specify the Transaction Policy”

“Task 2 - Verify the Transaction Policy”

“Task 3 - Implement a Bean-Managed

Transaction”

Preparation

This exercise assumes you have successfully completed

‘‘Exercise 3: Performing

Timer Management (Optional)’’ on page L8-5

successfully.

Task 1 - Specify the TransactionPolicy

In this task, you will specify the transaction policy of the

Aut omat i cSayHel l oBean.Complete the following steps:

1.

2.

3.

Open Aut omat i cSayHel l oBean. j ava.

Import the required packages to support

transactions:i mport

 j avax. ej b. Tr ansact i onAt t r i but e;i mport st at i c

 j avax. ej b. Tr ansact i onAt t r i but eType. *;Specify the MANDATORY transaction policy on

the cancel Ti mer method as follows:

@Tr ansact i onAt t r i but e( MANDATORY)publ i c voi d cancel Ti mer ( ){ . . . }

Task 2 - Verify the Transaction

Policy

In this task, you will verify the MANDATORY transaction

 policy is being enforced by the container.

To verify the transaction policy is being enforced, you

will invoke a method on a bean, without an activetransaction. This should result in an exception being

generated by the container.

Complete the following steps:

1.

2.

3.

Run the MaMApp:

a.

 b.

c.

Clean and Build the EJ B31application.

Right-click on the EJ B31 project and

select Run.

MaMApp should run unaffected by the

MANDATORY policy.

Add the following imports to the

Automat i cmanager Bean.i mport

 j avax. ej b. Tr ansact i onManagement ;i mport

 j avax. ej b. Tr ansact i onManagementType;i mport

 j avax. t r ansact i on. User Tr ansact i on;Change the Tr ansact i onManagement

 policy of the Aut omat i cManager Bean to

 be bean-managed.@Tr ansact i onManagement

Page 40: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 40/43

4.

( Tr ansact i onManagementType. BEAN)@Stat el esspubl i c cl assAutomat i cManager Bean i mpl ement sAutomat i cManager BeanRemot e {By doing this, you will prevent the container

from automatically creating a transaction on

your behalf.

Re-run the MaMApp.

This time you should see an exception

generated in the GlassFish v3 Domain outputwindow. If you see the exception output, the

MANDATORY policy is being enforced.

The exception output should look something

like:WARNI NG: A syst em except i onoccur r ed duri ng an i nvocat i on onEJ B Aut omat i cSayHel l oBean met hodpubl i c voi dhel l owor l d. beans. Automat i cSayHell oBean. cancel Ti mer ( )

 j avax. ej b. Tr ansact i onRequi r edLoc

al Except i on

Task 3 - Implement a Bean-Managed Transaction

In this task, you will expand on the bean-managed

annotation applied to the Automat i cManager Bean.

Specifically, you will create and manage a transaction to

satisfy the MANDATORY transaction policy.

Complete the following steps:

1.

2.

3.

4.

Add the following imports to

Automat i cManager Bean:i mpor t

 j avax. t r ansact i on. User Tr ansact i on;i mpor t j avax. ej b. Sess i onContext ;Add the resource injection code for the

Sessi onCont ext .@Resource pr i vat e Sessi onContextcont ext ;Create a pr i vat e method called

cancel Aut omat i cTi mer . Implement the

method as follows:pr i vat e voi d cancel SayHel l oTi mer( ) t hr ows Except i on{ User Transact i on ut =cont ext . getUser Tr ansact i on( ) ;ut . begi n( ) ;aut omat i cSayHel l oBean. cancel Ti mer ( ) ;ut . commi t ( ) ;}Modify the manageTi mer and

moni t or Aut omat i cTi mer methods to call

cancel SayHel l oTi mer  based on the

5.

 previously defined rules.

Run the MaMApp.

You should see the

Automat i cManager Bean cancel the

Automat i cSayHel l oBean timer as

expected, within the context of a transaction

without exception.

Exercise Summary

Discussion - Take a few minutes to discuss what

experiences, issues, or discoveries you had during the

lab exercise.

Experiences

Interpretations

Conclusions

Applications

Page 41: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 41/43

 Lab 11

Implementing Security

Objectives

Upon completion of this lab, you should be able to:

Complete the review questions

Exercise 1: Completing ReviewQuestions

In this exercise, you answer questions about the material

covered in the Student Guide.

Complete the following questions:

1.

2.

List the identities recognized in a Java EE

application.

 Name the annotation used to declare roles in a

Java EE application.

Exercise Summary

Discussion - Take a few minutes to discuss what

experiences, issues, or discoveries you had during the

lab exercise.

Experiences

Interpretations

ConclusionsApplications

Page 42: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 42/43

 Lab 12

Using EJB Technology BestPractices

Objectives

Upon completion of this lab, you should be able to:

Complete the review questions

Exercise 1: Completing Review

Questions

In this exercise, you answer questions about the material

covered in the Student Guide.

Complete the following questions:

1.

2.

Which EJB component is best suited to model

the business process?Which component is best suited to model

 business data?

Exercise Summary

Discussion - Take a few minutes to discuss what

experiences, issues, or discoveries you had during the

lab exercise.

ExperiencesInterpretations

Conclusions

Applications

Page 43: BusinessComponetDevelopmentwithEJB-ActivityGuide

8/10/2019 BusinessComponetDevelopmentwithEJB-ActivityGuide

http://slidepdf.com/reader/full/businesscomponetdevelopmentwithejb-activityguide 43/43