Tuesday, March 8, 2016

EJB 3.1 cookbook

Chapter 1: Getting Started with EJBs


Creating a simple session EJB





simple example with @Stateless annotation.

very important is that @Stateless takes a parameter


mappedName is used as a JNDI name.


Accessing a session bean using dependency
injection



as you can see, we inject the bean using @EJB.

and we used here @WebServlet to define a servlet.

Accessing the session bean using JNDI



as you can see, we use InitialContext() and lookup() to find the bean.

we used this path in the code
"java:global/SalutationApplication/SalutationApplication-ejb/Salutation"
which is 
java:global[/<app-name>]/<module-name>/<bean-name>

java:global: means search in all beans that are globally accessable
java:app: means search in all the beans that can be seen in the same application
java:module: means search in all the beans that can be seen in the same module

IMPORTANT: the bean can be packaged in application-ejb.jar, or application-war.war. the application-ejb.jar can be packaged inside application.ear.

so the[<app-name> is when you are packaged inside application.ear
the module-name is the name of the war.war or ejb.jar
the bean-name is the name of the bean.

so if you want to search for beans inside a module :
java:module/<bean-name>

searching inside the application:
java:app/<module-name>/<bean-name>

we will see later that the bean could implement a localInterface and/or RemoteInterface

public class Salutation implements SalutationLocalInterface, SalutationRemoteInterface {
}

in this case you JNDI lookup will be

java:global[/<app-name>]/<module-name>/Salutation/SalutationLocalInterface
java:global[/<app-name>]/<module-name>/Salutation/SalutationRemoteInterface



Creating a simple message-driven bean


as you can see we use @MessageDriven, we implement MessageListner and override onMessage.

mappedName: is the name of the queue that we are gonna listen to
and we added some config which are the acknowledgeMode and the destinationType.


Sending a message to a message-driven bean


as you can see, you need a queueConnectionFactory and a queue.
we create a connection
then we create a session
then we create a producer
then we send the message.


also you can see that we injected the resources (connection factory and queue , which you usually create them in Glassfish) using @Resource 

Accessing an EJB from a web service
(JAX-WS)

firstly we will define a singlton bean


simply we use @Singleton

then we will use this bean inside JAX-WebService


as you can see we use @WebService and @WebMethod to define a service.

and sure to inject the bean we use @EJB.

Accessing an EJB from a web service
(JAX-RS)


firstly we will define a Stateless bean



then we can define


as you can see we define @Path, @GET, @POST ...
and sure to inject the bean @EJB is used.

Accessing an EJB from an Applet


you can access a bean from Applet check the example if you want 

Accessing an EJB from JSP


in this example we will create a Remote Stateless EJB.

to do that, firstly we should define the remote interface:


then we implement the interface in the bean class



no we will use InitialContext to get the bean in JSP.



Calling an EJB from JSF


calling an EJB from JSF is similar to JSP, however before EJB 3.1 we had to define what we call a managedbean which is like a wrapper to the EJB.

in this example we will see how to define a managedbean.

firstly we will define the bean


@Named is similar to @Component in Spring

then we define the managed bean


as you can see the managed bean is just a wrapper for the actual bean

now we can use the bean like this


Accessing an EJB from a Java Application
using JNDI


accessing EJB from Java Application can be done easily by using JNDI



Accessing an EJB from a Java Application using an embeddable container

you can access the EJB using what we call embeddable container, The embeddable EJB container allows EJBs to be executed outside of a Java EE environment.

the code looks like this


Accessing the EJB container

EJB needs to access the container, which means access it to use its services (security, transaction ...).

accessing the container happens through EJBContext Interface.


as you can see we defined SessionContext (which implements EJBContext) and annotated that with @Resource

we have 3 context:

SessionContext for Session Beans
MessageDrivenContext for MDB
EntityContext for an Entity

EJB 3.1 cookbook Chapter 2: Session Bean 2


Session bean has 3 types: Stateless, stateful and Singleton

Stateless: no state
Statefull: keep the state between callse
Singleton: IT IS STATEFULL BUT WE HAVE ONLY ONE PER APPLICATION

Beans can be access locally (No Interface or Interface) or Remotely 
when access locally you should be in the same JVM
parameters will pass by reference when locally, and by value when Remotely.

Creating a stateless session bean




as you can see we use @Stateless, @LocalBean (there is no need to use this one, it is the default value).

The lifecycle of Stateless bean has @PostConstruct and @PreDestroy

Creating a stateful session bean




@Stateful
@PostConstruct
@PrePassivate
@PostActive

Creating a singleton bean



@Singleton
@PostConstruct
@PreDistroy

Using multiple singleton beans




as you can see we used
@Singleton
@Startup: which means initialize the bean as soon as the application starts up
@DependsOn("BEANNAME") it means that PlayerBean should be initialized before this bean
you can wirte @DependsOn("x","y","z")


Using container managed concurrency



by default the container is responsible for handling the Singleton bean concurrent requests, only one client can access the bean at a time whether for read or write

you can change the concurrency behaviour by using @ConcurrencyManagement and @Lock


as you can see we say here that the container (which is the default behaviour) will take care of handling the concurrency, and we limit getState() to just Read lock and setState() to write lock

you can specify also the timeout for a lock by using @AccessTimeout(5000) 

Using bean managed concurrency



with bean managed concurrency, you should handle everything by using synchronized key words.



Using session beans with more than one business interface


you can use multiple interfaces with a bean, 





we used @Named just to use it with JSF


Understanding parameter behavior and granularity



we know that local beans runs on the same JVM and remote beans on different JVM

when you have a class with multiple private variables, then you need one call to get each variable instance ==> in case of local beans, this is fine as we are doing local calls, however in case of remote beans this is a lot of overhead. (FINE GRAINED APPROACH)

you can also pass the whole object ==> only single call, this is good in case of remote call (COARSE GRAINED APPROACH)

we know that passing objects between JVM we are passing by value, it is a good practice to make the object immutable.

lets take an example about fine grained:

we have this interface which represent the Orbit


the implementation for this interface


as you can see, if you want any value from this remote bean you should make a call, so you need to make 6 calls to get all the Orbit informations


in the example above we made a call to get the Eccentricity value, if you want to get the Longitude you should do position.getLonituteof...().

alot of call.


however if you go with the Coarse grained fashion, you can define the remote interface like this


as you can see just one method that return an object


as you can see it return an object

and you can do the call like this


as you can see orbitalElements.getPosition() will return the whole object in one call, no need for other remote calls.
now when you do getEccentricity() you are doing a local call

Using an asynchronous method to create a background process



if you want the bean to run asyncronusly so you dont have to wait for the results, you have 2 options:
1- Invoke and Forget: which means you run the bean and you dont care about the results
2- Invoke and Return in Future: which means you run the bean, the bean will store the results in a Future object which you can access later.

we will see the 2 approaches in this example:


as you can see we use @Asynchronous with printAndForget().
and we return Future<String> in case we want a future object,
as you can see we return new AsyncResult<String>()

to use this bean:


as you can see we do futureResult.get() to get the results and you should handle the exceptions

NOTE: Future object is not just used for getting the results, you can use it to cancel the task, check if it has completed and other thigns


EJB 3.1 cookbook Chapter 3: Message-Driven Beans 3


we know everything about Message Driven Bean, we will start by example directly

Handling a string-based message


for string based message, simply you can write

and you can read the message


Handling a byte-based message



and reading from queue


Handling a stream-based message


and reading


Handling a map-based message




and the read

Handling an object-based message


and you read that


Using an MDB in a point-to-point application


all the previous examples where point to point where we have the following architecture


also consider this architecture, sometimes it is better to have a chain of queues


Using MDB in a publish-and-subscribe application


in case of public subscribe we should create a Topic.


this is how to receive the message, and as you rmember Durability means that the message will stay in the Topic if the subscriber is offline.

and here is how we send a message


Specifying which types of message to receive using the message selector




now to read this specific type of messages



Browsing messages in a message queue


 you can use queuebrowser to browse the queue.


EJB 3.1 cookbook Chapter 4 & Chapter 5 & Chapter 6 : EJB Persistence & JPA Query & Transaction Processing

An entity is a class representing data persisted to a backing store using JPA. The @Entity annotation designates a class as an entity

Entities can also be declared in an orm.xml file

The persistence unit defines mapping between the entity and the data store
The persistence context keeps track of the state and changes made to its entities
The EntityManager manages the entities and their interaction with the data store

Creating an entity



@Entity: for defining an entity
@ID: for setting the primary key
@GeneratedValue: to generate primary key value

Creating an entity facade



the idea is to crate an abstract facade with general functions:


now you start implemnting this facade in your beans


Using the EntityManager


now what you can do is using the bean defined before like this:


Controlling the Object-Relationship Mapping (ORM) process


you define database information and persistence unit in persistence.xml


we have annotations like
@Table
@Column


Using embeddable classes in entities


you can embed entity withen another, and they will be in the same table.

for example, you can have an employee class


and you can define the Address class like this


with @Embaddable 


the table in database will be a single table (EMPLOYEE) with employee and Address fields.

Validating Fields



@NotNull
private String name;

@Null
private String name;

@Size(min=12)
private String name;

@Size(min=12, max=36)
@NotNull
private String name;

@Temporal(javax.persistence.TemporalType.DATE)
private Date dateOfBirth;

@Past // the value should be in the past
@Temporal(javax.persistence.TemporalType.DATE)
private Date dateOfBirth;

@Future // the value should be in the future
@Temporal(javax.persistence.TemporalType.DATE)
private Date dateOfBirth;

@Pattern(regexp="\\d{5}(-\\d{4})?")
private String zipCode;


@AssertTrue// this means resident should be true
private boolean resident;

@Min(12)
@Max(48)
private int monthsToExpire;

you can also use a Validator class to do the validation



Chapter 5 JPA Query



nothing much here we will just add few examples

1- create and run a query
@Override
public List<Patient> findAll() {
Query query = entityManager.createQuery("select p FROM Patient p");
List<Patient> list = query.getResultList();
return list;
}

2- control the number of returned entities
Query query = entityManager.createQuery("SELECT p FROM
Patient p");
query.setMaxResults(querySize);
query.setFirstResult(beginIndex);
List<Patient> list = query.getResultList();

3- delete query
public int delete(String firstName, String lastName) {
Query query = entityManager.createQuery("DELETE FROM Patient p
WHERE p.firstName = '" + firstName + "' AND p.lastName = '" +
lastName + "'");
int numberDeleted = query.executeUpdate();
return numberDeleted;
}

4- update query
 public int updateDosage(String type, int dosage) {
Query query = entityManager.createQuery("UPDATE Medication m " +
"SET m.dosage = " + dosage + " WHERE m.type = '" + type + "'");
int numberUpdated = query.executeUpdate();
return numberUpdated;
}

5- use parameter in query
public List<Patient> findByLastName(String lastName) {
Query query = em.createQuery("SELECT p FROM Patient p WHERE
p.lastName = :lastName");
query.setParameter("lastName", lastName);
List<Patient> list = query.getResultList();
return list;
}

6- using named query
@Entity
@Table(name="MEDICATIONS")
@NamedQuery(name="findByType",
query="SELECT m FROM Medication m WHERE m.type = ?1")
public class Medication implements Serializable { ...}

public List<Medication> findByType(String type) {
Query query = entityManager.createNamedQuery("findByType");
query.setParameter(1,type);
return query.getResultList();
}

7- Using the Criteria API

public void findAllMales(PrintWriter out) {
CriteriaBuilder criteriaBuilder;
criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Patient> criteriaQuery =
criteriaBuilder.createQuery(Patient.class);
Root<Patient> patientRoot = criteriaQuery.from(Patient.class);
criteriaQuery.where(criteriaBuilder.equal(
patientRoot.get("sex"),"M"));
List<Patient> patients =
getEntityManager().createQuery(criteriaQuery).getResultList();
for (Patient p : patients) {
out.println("<h5>" + p.getFirstName() + "</h5>");
}

CMTs can be used with session beans, message-driven beans, and entities. However, BMTs
can only be used with session- and message-driven beans.

CHAPTER 6 Transactions



you have either container managed transaction or bean managed transactions.

by default we have container managed transactions.

Using the SessionSynchronization interface with session beans


if you implement SessionSynchronization interface you can use functions like afterBegin, beforeCompletion, afterCompletion


we have something important which is called TransactionAttributeType which you can set for methods or classes

REQUIRED – Must always be part of a transaction
REQUIRES_NEW – Requires the creation of a new transaction
SUPPORTS – Becomes part of another transaction if present
MANDATORY – Must be used as part of another transaction
NOT_SUPPORTED – May not be used as part of a transaction
NEVER – Similar to NOT_SUPPORTED but will result in an EJBException being thrown


A Message Driven Bean (MDB) only supports the REQUIRED and NOT_SUPPORTED values.

usually the transactionAttirbuteType is set on the method level, it defines how the method will behave in case there is a parent transction or not


Handling transactions manually


firstly


then you should start and commit transactions by your self


NOTE: 

Rolling back a transaction


in case of bean managed transaction you can rollback using these methods
UserTransaction.rollback(): which cause an immediate rollback of the transaction
SessionContext.setRollBackOnly(): which marks the transaction for rollback however the transaction will not be interrupted it will continue to the end.

in case of container managed transaction you can only use setRollBackOnly().

Handling errors in a transaction


If an unchecked exception is thrown, a transaction is automatically rolled back. For checked exceptions, the UserTransaction's rollback method or the SessionContext's setRollbackOnly method are used to explicitly force a rollback.

when you define an exception you can set if it should rollback or not.

Using timeouts with transactions


if you are using container managed transaction you can change the transaction timeout from the container GUI, 


for Bean managed transaction you can use.
UserTransaction.setTransactionTimeout(10);

EJB 3.1 cookbook Chapter 7 EJB Security

you can use annotation to secure access to methods, or you can use some code, use the code when the annotation cannot do what you want (e.g. access is allowed only in the morning).

When we talk about security we talk about REALM, users, groups and roles.
we define the REALM and under it the users and groups in the JAVAEE server (e.g. glassfish), usually they have a GUI for that.



the roles are defined on the application level, we assign the roles to groups and users.



as you can see we defined the roles and security-constraint in web.xml

mapping roles to groups and users should be done in (sun-application.xml, sun-web.xml, or
sun-ejb-jar.xml) depending on how the application is deployed


now when you write code



as you can see you define the roles that the class will handle, then you use @RolesAllowed, @PermitALL and @DenyAll.


Sometimes you need a class to run in a higher Role, so lets say that you have an employee Role and you want to call something which needs a Manager Role, the class itself can allow you to do that by using RunAs annotation


How to control security dynamically
after the user is authenticated by JAVAEE Server, it will be represented as Principal object as part of context, you can use this object for programmatic access.
some of the calls that you might need

Principal principal = sessionContext.getCallerPrincipal();
principal.getName()
sessionContext.isCallerInRole("manager")


EJB 3.1 cookbook Chapter 8 Interceptors 

To use interceptors:
1- define your interceptors class


2- specify where you want to use this interceptor

as you can see here the interceptor is on class level


3- you can define multiple interceptors like this:



4- when you define an interceptor on class level, it will be applied to all methods, if you want to exclude some methods, you write:


5- you can also define an interceptor on method level


6- you can define an interceptor for all EJBs.
you do that by adding <interceptor-binding> in ejb-jar.xml

7- as you can see, in the defined Interceptor method we have, a parameter which is InvocationContext, this parameter has useful methods like:


8- you can annotate methods also with @PreDestroy and @PostConstruct @PrePassivate and @PostActivate

EJB 3.1 cookbook Chapter 9 Timer Service & Chapter 10 Web Services & Chapter 11 Packaging EJB & Chapter 12 EJB Techniques 

To schedual a method to run at specific time



you can also create an event programatically
1- define a time service resource
@Resource
TimerService timerService;
2- create an action timer:
3- create a timeout function


createSingleActionTimer() will create an event for one time
createIntervalTimer() will create interval events
createCalendarTimer() will create calendar event

the Timer object in the timeout function has alot of useful methods


Persistent vs non-persistent timers
persistent timer means if the server is down the server event will be recorded and executed later.
you can define a persistent in @Schedual

@Schedule(second="0", minute="*", hour = "*", info="", persistent=true)


//////////////////////////////////////////////////////////////////////////////////////////////

Chapter 10 Web Services


to define web services you can use JAX-WS 
@WebService, @WebMethod and @WebParam


in order to define RESTFul services, you can use JAX-RS
@Path, @GET, @Produces("text/html"), @QueryParam, 

//////////////////////////////////////

Chapter 11 Packaging the EJB


1- *-ejb.jar: this jar file contains your EJBs, the deployment descriptor is ejb-jar.xml, it will be inside META-INF ( if you annotated your classes then there is no need for ejb-jar.xml ).
2- *.war: host your web application, the deployment descriptor is web.xml, it will be inside WEB-INF.
3- *.ear: put jars and wars inside it, application.xml is the deployment discriptor.
4- *.rar: this is to define resource adapters, this is something related to JAVA EE Connector Architecture, for integration; the deployment descriptor is ra.xml inside META-INF





then the chapter talks about class loading, as we know class loading is vendor specific, it is not a standard specification thing.


///////////////////////////////////////////////

Chapter 12 EJB Techniques



this chapter talks about general things, like using currency, handling exceptions, using interceptors to handle exceptions and logging ....

No comments:

Post a Comment