Lab Manual - Enterprise Applications

laboredbumbaileyΛογισμικό & κατασκευή λογ/κού

7 Ιουν 2012 (πριν από 5 χρόνια και 12 μέρες)

620 εμφανίσεις

COMPUTER SCIENCE

Lab M
ANUAL

CS313

Enterprise Applications


Binus University

International

Designed

by:


Andrian Kurniady



T
able of Contents


PART 1

Java and Java

Web Programming


1
Web Programming in Java R
evisited

o

Getting started with Netbeans and web proje
cts

o

Creating a simple web application with user states (sessions and URL rewriting)


2
Java Annotations and Reflection

o

Creating an annotation interface

o

Getting to know how to reflect a Java object

o

Modifying object states through reflection



PART

2

Entity
Beans


3
Entity Beans

o

Setting up a persistence unit

o

Creating an entity

o

Accessing the entity manager

o

Simple operations with entity beans


4
Entity Relationships

o

The many
-
to
-
one relationship of entities

o

The one
-
to
-
many relationship of entities

o

Creating an ap
plication with a set of interrelated entities


5
Entity Inheritance and JPQL Queries

o

Entity Inheritance and Mapping Strategies

o

JPQL Queries



PART 3

Enterprise Java Beans


6 Session Beans

o

Creating stateless and stateful Session Beans

o

Accessing the session
beans from a web application

o

Accessing the entity manager from a session bean


7 Message Driven Beans

o

Creating a Message Driven Bean

o

Sending a message through JMS

o

Processing a received message in a MDB








PART 4

Advanced Techniques


8

Timer Service

o

Setti
ng up a timer

o

Deactivating a timer


9

Interceptors

o

Creating an interceptor

o

Retrieving and modifying intercepted method call details


10

Transaction Management

o

Demonstrate the effect of transaction

o

Modifying the transaction properties of session beans








C S 3 1 3

E N T E R P R I S E A P P L I C A T I
O N S

1

Weekly Outline

Week

Topic

Reading

1

Web Programming in Java R
evisited

o

Getting started with Netbeans and web projects

o

Creating a simple web application with user states
(sessions and URL rewriting)


2

Java Annotations and Reflection

o

Creating an annota
tion interface

o

Getting to know how to reflect a Java object

o

Modifying object states through reflection


3

Entity Beans

o

Setting up a persistence unit

o

Creating an entity

o

Accessing the entity manager

o

Simple operations with entity beans

Lecture Week 3

Monson
Haefel Ch

5,6


4

Entity Relationships

o

The many
-
to
-
one relationship of entities

o

The one
-
to
-
many relationship of entities

o

Creating an application with interrelated entities

Lecture Week 3,4

Monson Haefel Ch

7


5

Entity Inheritance and JPQL Queries

o

Entity I
nheritance and Mapping Strategies

o

JPQL Queries

Lecture Week 3,4,5,6

Monson Haefel Ch

8,9

6

Session Beans

o

Creating stateless and stateful Session Beans

o

Session bean access

from a web application

o

Accessing the entity manager from a session bean

Lecture Week

7

Monson Haefel Ch

11

7

Mid Lab Exam

MID SEMESTER EXAM

8

Message Driven Beans

o

Creating a Message Driven Bean

o

Sending a message through JMS

o

Processing a received message in a MDB

Lecture Week 8

Monson Haefel Ch

7


9

Timer Service

o

Setting up a timer

o

Dea
ctivating a timer

Lecture Week 9

Monson Haefel Ch

13

10

Interceptors

o

Creating an interceptor

o

Retrieving and modifying intercepted method call
details

Lecture Week 10

Monson Haefel Ch

15


11

Transaction Management

o

Demonstrate the effect of transaction

o

Mod
ifying
session beans’

transaction properties

Lecture Week 11

Monson Haefel Ch

16

1
2

Project Consultation

1
3

Final Lab Exam

FINAL EXAM

C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O
N S


2

Web Programming in Java Revisited

The exercises in this module is designed to help students recall their
knowledge about
web programming in Java from the course
Web Programming

as a basis for them in
studying the more advanced concepts and technologies later in this course. By
completing this module, the stud
ents are expected to be able to
:




Use Netbeans to w
ork with web applications



Create simple web applications with Java



Instruction


You need to submit the web application project folder (as generated by Netbeans)
including the servlets and JSPs or other files that you have made. Please archive the
folder

in
to a ZIP file before submitting.

Answers to questions, if any, should be
submitted in the form of 1 (one) text file for the entire module.



Lab Setup


To be able to work on this module and all of the following modules, you need to have
the following so
ftware ready in your comput
er
:



Netbeans 6.1 with Enterprise Pack

o

The installer can be downloaded from
http://www.netbeans.org


o

Make sure you have the installer bundled with Enterprise Pack, or you can
al
so use the al
l
-
in
-
one installer.

o

When installing, you should at least select

the components as shown in the
screen below:


Module

1

C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


3



Creating a Web Application Project in Netbeans

This part of the tutorial is aimed to familiarize you with the usage of Netbeans for web
app
lications as well as enterprise applications that will be used throughout this course.
This part contains how to open Netbeans, create a web application project, adding a
servlet, adding a JSP page, and running the created application.




Make sure that Netb
eans 6.1 (with Enterprise Pack) has been successfully installed
on your computer, and start it.





C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


4




Go to
File > New Project,
and choose
Web > Web Application
in the new
project window. Enter the project name and location on the next window. The
server to b
e used should be either Tomcat (for web application only)
or

Glassfish V2
(for enterprise applications).





The new project will show up in the project browser on the left. You will see a
structure containing folders Web Pages, Configuration Files, etc. to

be used in the
web application. That includes an
index.jsp

file inside the Web Pages folder (which
is a sample of a JSP page).




To add a servlet/jsp/anything, right click on the project name, then choose
New

and choose the thing to be added. When adding a

servlet, a wizard will be shown in
which you can enter the servlet name and
Servlet mapping,

etc.


C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


5




Run your web application by pressing
F6,
and a browser window will open to show
the result.


Progress Check

Based on the activity above, you should now

be able to create a simple web application in
Netbeans. You are now expected to create a counting application that starts at 0, and
increase the counter when the
Increment

button is while decreasing the counter when the
Decrement

button is clicked. The co
unter should be reset to 0 when the
Reset
button is
clicked. The sample can be seen as shown below. The counter should be individual to each
users (i.e. two users opening the counter must have two independent counters).

The
following diagram shows the beha
vior that is expected from your web application.


Hint
: you can use HTTP Sessions or URL Rewriting






C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


6



Challenge Problem


If you are done with the previous task, you may attempt to do this challenge task.

Create a calculator
web application that shows an input form for entering two numbers,
choosing one operator out of four ( +
-

* / ) operators and shows the result of the
calculation in another page.




C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


7




C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


8

Java Annotations and Reflection

The exercises in this modul
e are aimed to familiarize students with the usage of
Annotations and Reflection in Java, which are heavily used in Java Enterprise
technologies. By completing this module, the students are expected to be able to:




Create an annotation interface and annota
te it to class



Do a reflection on a Java object to retrieve and modify its properties



Instruction


You need to submit your work in the form of JAVA source files. If you do them in more
than one file, please submit all the files archived in a ZIP file.

An
swers to questions, if
any, should be submitted in the form of 1 (one) text file for the entire module.


References

Before you practice the module, you should have read and reviewed the following
materials:



http://java.sun.com/docs/books/tutorial/reflect/index.html



http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html


Creating an
Annotation Interface and use it on classes

Annotations are basically Java interfaces which can hold values (parameter) and are
used to add some information about a class or its members. Therefore, you can declare
annotations with the @interface keyword. Th
e examples can be seen in the following
code.




public @interface MyAnnotation {


int type();


String title() default “untitled”;

}

Module

2






C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


9

public @interface ThisIsTheTitle {

}

public @interface TypeFunction {

}


By default, annotations are not available during r
untime. You can make it available by
adding the
@Retention

annotation on your annotation interface declaration.


@Retention(
RetentionPolicy
.RUNTIME)

public @interface SomeAnnotation {

}


After declaring your annotations, you can “annotate” it to your class
es to convey some
information that you want.


@MyAnnotation (type=1, title=”Enterprise Applications”)

public class MyBook {



@ThisIsTheTitle


public string iniJudul;



public string author;



@TypeFunction


public string myType(){



return “comic”;


}



p
ublic string someMethod(){


}

}


Try completing the above code snippets into a JAVA file and make sure it compiles
correctly. You may edit some parts of the code to know more about the behavior of the
Annotation interface.


Progress Check

If you followed

until here, you should be able to answer the following questions:

1.

What are annotations?

2.

How are annotations declared and used in Java?



C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


10


Reflecting a Java Object

Reflection is a common feature of most Object
-
oriented programming languages. In short, it

allows programmers to programmatically retrieve the description of an object (the fields,
the methods, etc.) during runtime. This allows the creation of more flexible frameworks
which can handle wider range of user
-
customized modules.

Reflection in Java i
s very simple. You should try this following example.


MyBook buku = new MyBook();

System.out.println("The class name is : " +

buku.getClass().getName());




for (Field f : buku.getClass().getFields()){


System.out.println("Field " + f.getName() );





Sy
stem.out.println("annotated with :");


for (Annotation a : f.getAnnotations()){



System.out.println(a.annotationType().getName());







}


}


Make sure that you put it in a complete JAVA program and that it compiles and runs
correctly.


Progress Check

If you followed until here, you should be able to answer the following questions:

1.

How can we use Java reflection to retrieve annotations that are present in the class
of a certain object that we have?


2.

Why are annotations and reflection important, especial
ly for Java Enterprise edition?











C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


11


Creating the Interrogator

Based on the activities on Annotations and Reflection above, you should now be able to
m
ake an “Interrogator”
object that

when
being
given an Object, wi
ll print out to the
screen it's
:




Cl
ass name



Annotations on the class



Fields (name and type)



Annotations on the fields (name)



Methods (name and return type) and its parameters (types)



Annotations on the methods (name)


It is recommended that you follow this template for the Inte
rrogator (in
Interrogator.java)
:


public class Interrogator {


public void interrogate(Object target){



// your code goes here



// System.out.println ...


}


public static void main (String[] args){



Interrogator inter = new Interrogator();



inter.interrogate(new S
omeObject() );


}

}


Progress Check

Concluding this module, you should now have the answers for the following questions in
mind:


1.

What is the purpose of reflection
?


2.

What is the purpose of annotations
?


Challenge Problem

If you are done with the previ
ous task, you may attempt to do this challenge task.

Create a method that, given any object, will set all of its fields of type
String

to
“helloworld” and all
int

fields to contain value 12345 while also printing its present
value. As a start, you can use
the following structure to build your method.









C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


12

public class Modifier {


public void modify(Object target){



// your code goes here



// System.out.println ...


}


public static void main (String[] args){



// your test code goes here



Modifier mod = new
Modifier();



mod.modify(new SomeObject());


}

}


C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


13

Entity Beans

The exercises in this module are meant to introduce the use of Entity Beans in lieu of
JDBC for database access from a web application. By the end of this module, students
are expe
cted to be able to:




Set up a persistence unit in a web application project



Create entity beans



Be able to access the entity manager from a servlet



Do simple operations with entity beans



Instruction


You need to submit your work in the form of an ZIP
-
arc
hived Netbeans Web application
project.

Answers to questions, if any, should be submitted in the form of 1 (one) text
file for the entire module.


Lab Setup


To be able to work on this module and all of the following modules, you need to have
the following

software ready in your comput
er
:



Netbeans 6.1 with Enterprise Pack



MySQL database server or equivalent


References

Before you practice the module, you should have read and reviewed the following
materials:



Lecture
notes w
eek 3



Monson Haefel Ch 5,6







Module

3



C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


14


Creating the
Entity Bean

Netbeans makes it easy to create an entity bean and wire it up to your project. Please
follow these steps to get yourself familiarized with using that feature.




Right click on the project, choose
New > Entity Class
, a dialog

box will show
up.






Fill the class name and package name, then choose “
Create Persistence Unit

if you don't have it yet.





C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


15




Name your persistence unit, and choose a data source. If you don't have one
yet, just create it from there, which will show you
this following dialog.





Select a JNDI name (whatever you want) for the datasource (basically it's a
JDBC connection), and choose a database connection (create one if you don't
have it in the list yet). The following is the create database connection dial
og.



C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


16




Fill the form based on your database server settings. For simplicity, MySQL is
recommended, as shown above.



Finish the wizard, and your entity bean is ready to use. Browse for your newly
created entity in the corresponding source folder.

Put the fi
elds that you would
like to have on the entity bean and add some of the necessary annotations.

The
code may look like the following.


@Entity

public class Book {


@Id @GeneratedValue


private Long id;



private String title;


// getter and setters

}





Chec
k MySQL to make sure your object is being persisted correctly after you run
your web application project (with F6 on Netbeans).


Progress Check

After finishing the previous activity, you should have the answers of these questions in
mind:




C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


17

1.

What is the de
fault ID field type of the generated entity beans?


2.

What does the @Id and @GeneratedValue annotations translates to the
database tables?




Accessing the EntityManager and doing basic operations on an
entity

After having your entity beans and persisten
ce unit set up, you can now access them during
runtime through the use of EntityManager. Since you’re still working on a servlet, you also
need to wrap your operations with a JTA transaction.

EntityManager can be accessed with a dependency injection in you
r object (servlets).
Just put the following annotated field in your servlet and the entity manager instance
will be provided automatically when your application is deployed. The UserTransaction
(JTA) is also to be accessed the same way.


@PersistenceContex
t

private EntityManager em;


@Resource

private UserTransaction utx;


Transaction is needed for all write operations (i.e. is not really needed for find or
retrieve operations).
With the EntityManager in reach
, operations can be done easily
:


Book b = new B
ook();

b.setTitle("test");



// to save a new book to the database

utx.begin(); // begin a transaction

em.persist(b);

utx.commit(); // committing a transaction



b.setTitle("lala");

// to merge the updated book into the database (update)

utx
.begin(); // begin a transaction

em.merge(b);

utx.commit(); // committing a transaction



// to delete the book from the database

utx.begin(); // begin a transaction

em.remove(b);




C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


18

utx.commit(); // committing a transaction



// to get the boo
k by ID

b = em.find(Book.class, 123);



// to get all books

List<Book> ls = em.createQuery(

"
select b
from Book

b
").getResultList();



Progress Check

Proceeding this far, you should now be able to create this simple web application based
on Entity

Beans.


Make a simple web application with one entity bean named Book, which have the fields
title (String), and author (String). Of course, you should add an ID field in the entity as
well. Your application should be able t
o
:



Create a new book and store
it to the database



List all of the books in the database (id, title, author)



Edit the detail of a book and update the changes into the database

Refer to the diagram below to get an idea of how the application should be made.

Note
: you have to use the entit
y beans,

standard

JDBC coding is NOT permitted.



















C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


19






Challenge Problem

If you are willing to go further, you can attempt to solve this following extension to the task
on the last progress check.

Extend your web application above to

also feature search function which can search:



Books containing a given text in the title (search title) and author (search
author).



All books that do not contain a given text both in the title and in the author
name.



C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


20

Entity Relationships

This

lab module is aimed into giving the students hands
-
on practice on entity
relationships. The students are expected to be able to:




Create many
-
to
-
one relationship of entities



Create one
-
to
-
many relationship of entities



Create many
-
to
-
many relationship of e
ntities



Create a typical application with a set of interrelated entities


Instruction


You need to submit your work in the form of a ZIP
-
archived Netbeans Web application
project.

Answers to questions, if any, should be submitted in the form of 1 (one) tex
t
file for the entire module.

References

Before you practice the module, you should have read and reviewed the following
materials:



Lecture notes week 3,4



Monson Haefel Ch 7


Getting familiar with many
-
to
-
one and one
-
to
-
many relationship

This part wi
ll get you started with the two basic entity relationships. In this case, we
assume that each book has only one author. For the purpose of demonstration, you
need these two entities:


@Entity

public class Book {


@Id @GeneratedValue


private Long id;


priv
ate String title;


@ManyToOne


private Author author;


// getter and setters

}

Module

4






C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


21

@Entity

public class Author {


@Id @GeneratedValue

private Long id;


private String name;


@OneToMany(mappedBy=”author”)


private List<Book> books;


// getter and setters

}


Y
ou are suggested to make these examples above compile and run to see what how
these relationships are being persisted.


Progress Check

By doing the first activity correctly, you should be able to answer:

1.

Which
part of the tables represents the many
-
to
-
on
e relationship?


2.

What is the purpose of mappedBy parameter in the @OneToMany annotation?


Getting familiar with many
-
to
-
many relationship

This part will get you started with the more complex many
-
to
-
many relationship. In this
case, in contrast to the p
revious example, we assume that each book may have more
than one author. For the purpose of demonstration, you need these two entities:


@Entity

public class Book {


@Id @GeneratedValue


private Long id;


private String title;


@ManyToMany


private
List<Au
thor>

author
s
;


// getter and setters

}






C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


22

@Entity

public class Author {


@Id @GeneratedValue

private Long id;


private String name;


@
Many
ToMany(mappedBy=”author
s
”)


private List<Book> books;


// getter and setters

}


You are suggested to make these exampl
es above compile and run to see what how the
relationship is being persisted.


Progress Check

By doing the second activity correctly, you should be able to answer this last question:

1.

How does the JPA persist Many
-
To
-
Many relationships?


Challenge Probl
em

By understanding the principles of one
-
to
-
many, many
-
to
-
one, and many
-
to
-
many
relationships, try create the entities (with relationships) for this following case of an
online store.




There are Products, Manufacturer
s
, and
Categories

in the database.



Eac
h product may belong to more than one category, and each category may
contain any number of products.



However, each product may have only one Manufacturer, but Manufacturers
may produce more than one kind of product.



Each of the entities should have the ap
propriate fields to describe it (e.g.
Products should have name, price, etc.).







C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


23

Entity Inheritance and JPQL Queries

This module is aimed to enhance students’ skill in using entity beans, especially to
enable them to do more complex entity scen
arios such as:



Entity Inheritance



Custom queries with JPQL


Instruction


You need to submit your work in the form of a ZIP
-
archived Netbeans Web application
project.

Answers to questions, if any, should be submitted in the form of 1 (one) text
file for the

entire module.

References

Before you practice the module, you should have read and reviewed the following
materials:



Lecture notes week 3,4,5,6



Monson Haefel Ch 8,9



Entity Inheritance Mapping

This part will show you how entity inheritance is being

handled by JPA. We will start
with an example of three entities:
Course

which is inherited by
ComputerCourse
, and
MathCourse
.
The following code illustrates how to declare the entity inheritance.


@Entity

@Inheritance(strategy = InheritanceType.SINGLE_TAB
LE)

public class Course {


@Id @GeneratedValue


private Long id;



// getter and setters

}




Module

5






C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


24

@Entity

public class ComputerCourse extends Course {


private String computerName;


// getter and setters

}


@Entity

public class MathCourse extends Course {


pri
vate String mathFormula;


// getter and setters

}


Try completing the code above and make it run. Then investigate how JPA persist your
hierarchy of entities. Try also changing the InheritanceType.SINGLE_TABLE to other
possible values: JOINED and TABLE_PER
_CLASS, deploy it and see the difference in
how JPA persists the entities.



Progress Check

The activity with entity inheritance above should allow you answer the following
questions:

1.

How does the JPA persist the entities when using the SINGLE_TABLE stra
tegy?


2.

How does the JPA persist the entities when using the JOINED strategy?


3.

How does the JPA persist the entities when using the TABLE_PER_CLASS
strategy?


Custom Queries

with JPQL

Th
is part will show you how to make custom queries using the SQL
-
like

query language
for entity beans: the Java Persistence Query Language (JPQL). Before you start,
observe the following JPQL syntax definition to know what features are there in JPQL.




SELECT [<result>]


[FROM <candidate
-
class(es)>]


[WHERE <filter>]


[GROUP BY <grouping>]


[HAVING <having>]


[ORDER BY <ordering>]







C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


25

As you may have noticed, the syntax looks just like the plain SQL. To use it, you can
refer to the following example. Suppose we have an entity named Book that has been
persisted t
o the database.


@Entity

public class Book {


@Id @GeneratedValue


private Long id;


private String title;


// getter and setters

}


You can make your query by using the EntityManager.


Query q = em.createQuery("SELECT b FROM Book b WHERE b.title
= ‘Enterp
rise Application’");

List<Book> results = (List<Book>)q.getResultsList();


The list named
results

will then contain all books titled ‘Enterprise Application’. For
more complex queries, you may need to use parameters as well. That is, to embed
some variable

values in the queries. There are two ways of doing it, the first being to
use Named Parameters, while the second is using the Numbered Parameters.


// Named Parameters

Query q = em.createQuery("SELECT b FROM Book b WHERE b.title
=
:title
");

q.setParameter
(“title”, myBookTitle);

List<Book> results = (List<Book>)q.getResultsList();


// Numbered Parameters

Query q = em.createQuery("SELECT b FROM Book b WHERE b.title
=
?1
");

q.setParameter(1, myBookTitle);

List<Book> results = (List<Book>)q.getResultsList();


Both of the methods work

the same way, so you can choose whichever more
convenient in your cases.


Progress Check

By completing the activity about JPQL, you should be able to answer the following
questions:

1.

How to retrieve the books, in such a way that i
t is ordered by its title in an
ascending lexicographic order?


2.

How can you retrieve books with id between 10 and 20, inclusive?



C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


26


Challenge Problem

Going deeper into the JPQL syntaxes, you may want to find out the answer of the
following questions:

1.

If th
e Book have a many
-
to
-
one relationship to Author entity, how can we query
a book which have an author with name ‘Kurniady’ ?


2.

Can we retrieve more than one kind of entities by using one JPQL query?







C S 3 1 3 E N
T E R P R I S E A P P L I C A T I O N
S


27

Session Beans

This module is designed so

that by the end of if, students should be able to:



Create stateless and stateful session beans



Access the session beans from a web application



Work with entity beans from session beans


Instruction


You need to submit your work in the form of a ZIP
-
archiv
ed Netbeans
Enterprise or
Web
application project. Answers to questions, if any, should be submitted in the form
of 1 (one) text file for the entire module.

References

Before you practice the module, you should have read and reviewed the following
materi
als:



Lecture notes week 7



Monson Haefel Ch 11



Creating stateless and stateful session beans

Creating stateless and stateful session beans is quite easy in Netbeans, as you can just
follow the wizard. Right click on your project and select
New > Sessi
on Bean
.

A
wizard like this following one will show.


Module

6






C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


28



Fill up the EJB name, Package name, choose either Stateless or Stateful, and state
whether you want a Remote or a Local interface (or both).
Upon finish, it will create two
files for you like these.


@Local

public interface HelloLocal {



}


@Stateless

public class HelloBean implements HelloLocal {




// Add business logic below. (Right
-
click in editor and
choose


// "EJB Methods > Add Business Method" or "Web Service >
Add Operation")



}


You can start working with your session bean by adding methods in the interface and in
the bean class.


C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


29

Progress Check

Before continuing, you should be able to answer these questions first:

1.

What are the differences between stateless session bean and s
tateful session
bean?


2.

What are the differences between remote and local interface?



Accessing the session bean from a web application

After creating the session beans successfully, it can now be accessed also from the web
application(s) that belongs
to the same enterprise application (EAR). The easiest way to
do that is to use the @EJB annotation in a servlet, like the following:


@EJB

private HelloLocal helloBean;


Thus, you can access the helloBean as if it is a local object. However, this approach
works only with stateless session beans. For stateful session beans, another method is
required, as it relates to the characteristic of a stateful session bean, in which the
container assigns one instance for each reference being created to the bean. The
f
ollowing example code shows you how to grab a reference to one (new) instance of a
stateful session bean.




Context ctx = new InitialContext();

CountLocal count =
(CountLocal)ctx.lookup(“
java:comp/env/
CountBean”);


Also make sure that you add these follow
ing lines to the web.xml of the WAR project.


<ejb
-
local
-
ref>


<ejb
-
ref
-
name>
CountBean
</ejb
-
ref
-
name>


<ejb
-
ref
-
type>Session</ejb
-
ref
-
type>


<local
-
home/>


<local>ejb.
Count
Local</local>


<ejb
-
link>Count
Bean</ejb
-
link>

</e
jb
-
local
-
ref>


Be aware that everytime you get a CountBean by this method, you will get a
new
instance of CountBean
. Therefore, if you want to stick it to a user’s session, you need
to keep the reference available, i.e. by putting it as an attribute of the

HttpSession
object.







C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


30

To get you familiarized, create one stateless and one stateful session bean and
demonstrate how to access it from a servlet by creating a simple web application for it.


Progress Check

By doing the previous activity, you should be a
ble to answer these questions:

1.

Mention a few examples on when to use a stateful and when to use a stateless
session bean.


2.

It is easier to make all session beans stateful (e.g. does not need to confuse
anymore about going stateless or going stateful). Expl
ain why it is not advisable
to do so.


Accessing Entity Beans from Session Beans

Accessing entity beans from the session beans is not really different from the way you
would access it from a servlet. By adding the @PersistenceContext annotation on your

EntityManager field in a session bean, the reference to the EntityManager will be
injected automatically by the container. You can also create the entity beans inside the
JAR project (EJB) the same way you would in the WAR project.


@PersistenceContext

pr
ivate EntityManager em;


The only difference is that, session bean being transactional by default, you no longer
need to use the UserTransaction to start and commit the JTA transaction. Setting the
transaction parameters can be done using annotations which

will be explained in
another lab module.


To get a feel on how to use entity beans in the EJB project, try creating a session bean
and an entity bean, try to persist some entities, and deploy it.


Progress Check

By doing the previous activity, you shoul
d be able to answer this question:

1.

Why is the injection of UserTransaction with @Resource annotation not needed
anymore when accessing the entity beans inside a session bean?


Challenge Problem

To know more about session beans, you can attempt to solve t
his programming task.


Create an Enterprise application consisting of a Stateful Session Bean and a servlet. The
application should display each user a counter (which is independent to other user’s
counter), and the counter should be incremented when the u
ser clicks a button on the









C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


31

page. Please note that, that increment operation should not increment other user’s
counter.


The following screen illustrates how your application should look like.





Note: the use of sta
teful session bean for storing the current count is mandatory.


C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


32

Message Driven Beans

This module on Message Driven Beans (MDB) is aimed to familiarize students with the
usage of MDB and JMS in general. By the end of this module, students are ex
pected to
be able to:



Create a Message Driven Bean



Send a JMS message

to an MDB


Instruction


You need to submit your work in the form of a ZIP
-
archived Netbeans
Enterprise or
Web
application project. Answers to questions, if any, should be submitted in th
e form
of 1 (one) text file for the entire module.

References

Before you practice the module, you should have read and reviewed the following
materials:




Lecture notes week 8



Monson Haefel Ch 7



Creating a Message Driven Bean

As it is with Session B
eans, Netbeans has also a built
-
in wizard for creating MDBs. Right
click on your EJB project, and choose
New > Message Driven Bean
.
A wizard like this
will show up.

Module

7






C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


33



Fill up the EJB Name and Package field. Because MDBs are basically
beans that listen

to
a specific JMS Queue or Topic, you need to create that Queue or Topic first by clicking
Add

next to the Project Destinations.
Choose a name for your Queue (or Topic) and
click OK.




After that, click Finish to have Netbeans create your MDB automatically.

A new Java file
will be created in the package of your choice, which will contain something like these.

Make sure you add the commented lines inside the onMessage method (to be used in
the following activities.




C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


34

@MessageDriven(mappedName = "jms/MyQueue
", activationConfig =
{


@ActivationConfigProperty(propertyName =

"acknowledgeMode", propertyValue = "Auto
-
acknowledge"),


@ActivationConfigProperty(propertyName =
"destinationType", propertyValue = "javax.jms.Queue")


})

public class
MyMDBBean implements MessageListener {




public MyMDBBean() {


}



public void onMessage(Message message) {



// add these please



TextMessage tm = (TextMessage)message;


System.out.println(“Got a message : ”,tm.getText());


}

}


Progress Check

Before continuing, please spend some time figuring out the answers to the following
questions:

1.

When should we use MDBs instead of Session Beans?

2.

What is the difference between JMS Queue and JMS Topic?


Sending a JMS Message

Because
in JMS, clients does not communicate directly to the MDBs, the client can only
contact the MDB by sending JMS Messages to the destination on which the MDB is listening.
Therefore, to be able to use an MDB, we need to know how to send a JMS Message.

To send

a message to JMS, need to grab references to the Queue (or Topic) and it’s
ConnectionFactory. Thanks to the dependency injection, this can be done quite easily.


@Resource(mappedName="jms/MyQueueFactory")

private ConnectionFactory connectionFactory;


@Res
ource(mappedName="jms/MyQueue")

private Queue queue;







C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


35

The code can be put on a session bean, an MDB, but also in a servlet. After having the
reference in hand, sending the message can be done as shown by the following code (which
sends a TextMessage).


Con
nection connection = connectionFactory.createConnection();

Session
session = connection.createSession(false,



Session.AUTO_ACKNOWLEDGE);


MessageProducer producer = session.createProducer(queue);


TextMessage message = session.createTextMessage();

mess
age.setText("Hello there");


producer.send(message);


Complete the example code in a servlet, deploy it, and see if it works.


Progress Check

To conclude this module, please find the answer of the following question:

1.

Briefly explain the steps in sending
a JMS message, as shown by the code in the last
activity.





C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


36

Timer Service

This short module is aimed to introduce students on the usage of timer service with
Session Beans to achieve a timed behaviour.



Instruction


You need to submit your work

in the form of a ZIP
-
archived Netbeans Enterprise or
Web application project. Answers to questions, if any, should be submitted in the form
of 1 (one) text file for the entire module.

References

Before you practice the module, you should have read and r
eviewed the following
materials:



Lecture notes week 9



Monson Haefel Ch 13


Activating a Timer

Activating a timer can be done easily within a Session Bean, by calling the timer service
through the session context. The following example shows you how.


@
Stateless

public class TimedServiceBean implements TimedService {



@Resource


private SessionContext ctx;



public void startTimer() {


ctx.getTimerService().createTimer(300000, 300000,



null);


System.out.println("Ti
mer set");


}



Module

8






C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


37


@Timeout


public void handleTimeout(Timer timer) {


System.out.println("
Timer called
");


}

}


The @Resource annotation is used to grab the reference to the SessionContext, which
would give us the reference to timer servi
ce through the getTimerService() method.
The createTimer() method will set up a timer, which on the example above is set to
every
300 seconds (parameter in milliseconds), and the first execution will be done
afte
r 300 seconds from it being set (The first p
arameter is the


The @Timeout annotation is used to mark the method to be called when the timer is
triggered. Complete the code above and observe the behavior of the timer.


Progress Check

To check about your understanding on the timer services, try to
answer the following
questions.

1.

How can you activate the timer in the actual application, given the session bean
code above?

2.

What are the possible applications of timer in enterprise applications?


Deactivating a Timer

For some circumstances, timers ma
y need to be deactivated. Deactivating timers can
be done in two ways: from the timeout method or by grabbing a reference to the Timer
through the timer service. The following code shows the first method.



@Timeout


public void handleTimeout(Timer t
imer) {


System.out.println("
Timer called
");




// Stop the timer



Timer.cancel();


}


On some occasions, you may need to stop the timer externally. This can be done by
adding another method to the session bean whose task is to stop the ti
mers.











C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


38


public void
stopTimers(
) {


for (Timer t : ctx.getTimerService().getTimers()){


t.cancel();


}


}



Progress Check


This programming task serves as a progress check on your understanding in Timers. As
we know, s
etting a timer will cause the timeout method to be called with uniform
delays, except for the first execution. For this task, you are asked to create a special
timed bean which will print to the console in the nonuniform delays as illustrated below.


<init
ial delay of 10 seconds>


Timeout called!


<delay of 5 seconds>


Timeout called!


<delay of 3 seconds>


Timeout called!


<delay of 5 seconds>


Timeout called!


<delay of 3 seconds>


Timeout called!


<etc…>





C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


39


Interceptors

This module on In
terceptors is aimed to introduce the use of Interceptors in Java
Enterprise applications. By the end of this module, students are expected to be able to:



Create a custom interceptor and use it to intercept a method in session bean



Inspect and modify the in
tercepted call, within the interceptor.



Instruction


You need to submit your work in the form of a ZIP
-
archived Netbeans Enterprise or
Web application project. Answers to questions, if any, should be submitted in the form
of 1 (one) text file for the ent
ire module.

References

Before you practice the module, you should have read and reviewed the following
materials:




Lecture notes week 10



Monson Haefel Ch 15



Creating an Interceptor

Creating an Interceptor, in contrast to the session beans or MBDs,
require no Netbeans
wizard. All you need is to create a new Java class that you want to use as an
interceptor (
New > Java Class
). Every Interceptor class should have one method with
a specific parameter InvocationContext and returning Object. The following

code show
s
how the code should look like:



public class MyInterceptor {


@AroundInvoke


public Object intercept(InvocationContext ic){


System.out.println(“Interceptor called”);


return ic.proceed();


}

}

Module

9






C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


40

The interceptor in the exa
mple does nothing, but you can add code inside the method
to achieve any behavior you like from the interceptor. To use it to intercept a method
call in a session bean, simply annotate the target method with the @Interceptors
annotation, with the list of i
nterceptor classes as its parameter.



@Interceptors({MyInterceptor.class})


public int myMethod(){


System.out.println(“myMethod has been called”);


return 123;


}



Please note that only container
-
managed beans (Session Beans and M
DBs) can be
intercepted. Try completing the code above and make it run properly before continuing.


Progress Check

Before continuing, please spend some time figuring out the answers to the following
questions:

1.

When is the interceptor executed?

2.

What is th
e purpose of ic.proceed() method? What does the method returns?


Things to do in the Interceptor

Being able to intercept the method call, many things can be done inside the interceptor. The
InvocationContext parameter contains all the details about the

method call being
intercepted. The following code shows what you can do with it.


@AroundInvoke

public Object intercept(InvocationContext ic) throws Exception {


// Get the reference to the bean/object whose method


// is being intercepted


Objec
t obj = ic.getTarget();




// Get the method information


Method m = ic.getMethod();




// Get the method call parameters


Object[] params = ic.getParameters();




// Continue to the method and store its result


Obje
ct res = ic.proceed();






C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


41




// the return object can actually be modified here as well


System.out.println("Method "+m+" returned "+res);




return res;

}


Progress Check

To make sure you have understood the Interceptors completely, tr
y creating this “Debug
interceptor”, which, when annotated to ANY method, will print out:



The class name of the target object



The method details (return type, method name, parameters)



The parameters for the method call



The returned value of the method




C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S


42

Transaction Management

This last module in the series is aimed to introduce the use of transactions in enterprise
applications, such that by the end of the module students are expected to be able to:



Understand the use of transaction



Set custom t
ransaction options to session beans’ methods



Instruction


You need to submit your work in the form of a ZIP
-
archived Netbeans Enterprise or
Web application project. Answers to questions, if any, should be submitted in the form
of 1 (one) text file for th
e entire module.

References

Before you practice the module, you should have read and reviewed the following
materials:



Lecture notes week 11



Monson Haefel Ch 16


Understanding Transactions

Transactions are enabled by default in the EJBs, but can also

be managed manually
using the Java Transactions API like the examples in accessing persistence from web
applications. This activity is aimed to demonstrate how transactions work. For this part,
we will be using plain Web Application consisting of an entit
y bean and a servlet. Refer
to the previous modules on entity beans on how to create the entity bean and
its
persistence settings. Create a simple entity bean as described by the code below.


@Entity

public class Book {


@Id @GeneratedValue


private Long i
d;


private String title;


// getter and setters

}

M
odule

10






C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S



43

Now, create a servlet, along with a reference to the UserTransaction. The code should
look like this in the servlet declaration part.


@PersistenceContext

private EntityManager em;


@Resource

private UserT
ransaction utx;


To demonstrate the behavior of a transaction
-
covered code, put the code below in the
servlet and have it executed.


Book b = new Book();

b.setTitle("test");



// to save a new book to the database

utx.begin(); // begin a transaction

em.persist(b);

utx.commit(); // committing a transaction


// now, this part will display a “rolled back transaction”

utx.begin();

b.setTitle(“has this one been rolled back?”);

em.merge(b);

utx.rollback();



Complete the code above into a running w
eb application and see what happened when
it is executed. You may want to check with the stored title in the database of the book
object, whether it has been changed.


// an exception thrown will also break a transaction

utx.begin();

b.setTitle(“has this o
ne been rolled back?”);

throw new Exception(“Something went wrong”);

utx.commit();


Progress Check

The following questions tests your knowledge on transactions, as based on the
demonstration above.

1.

What happened when a transaction is rolled back?

2.

Why are transactions important, especially when updating the database?



C S 3 1 3 E N T E R P R I S E A P P
L I C A T I O N S



44


Setting Custom Transaction Properties in Session Beans

Although session beans are transactional by default (i.e. you do not need to start the
transactions manually), sometimes the

default behavior is not desired in certain
circ
umstances. For this reason, the @TransactionManagement and
@TransactionAttribute annotation is provided. The use of it in the session bean is
demonstrated below.


// Declare the transaction to be container ma
naged (default)

@Stateless

@TransactionManagement(TransactionManagementType.CONTAINER)

public class HelloBean implements HelloLocal {




@TransactionAttribute(


TransactionAttributeType.REQUIRED


)


public int myMethod(){


}

}


There are several
kinds of the TransactionAttributeType, namely the REQUIRED,
REQUIRESNEW, SUPPORTS, MANDATORY, NOTSUPPORTED, NEVER.


Progress Check

By trying around on the last activity and referring to the lecture notes, you should be
able to answer the following questi
on:

1.

What is the difference of the the TransactionAttributeTypes (REQUIRED,
REQUIRESNEW, SUPPORTS, MANDATORY, NOTSUPPORTED, NEVER) ?