1.    EJB components are server-side components

2.    EJB components contain business logic only – no system-level programming & services, such as transactions, security, life-cycle, threading, persistence, etc. are automatically managed for the EJB component by the EJB server.

  1. EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and secure.
  2. EJB components are fully portable across any EJB server
  3. Instantiation of EJB is handled by container
  4. Container determines when and how many
  5. Lifecycle of an instance is managed by container
  6. EJB instance access is controlled by container
  7. There is no direct client access

 

 

How EJB Invocation happens?

 

1.    Retrieve Home Object reference from Naming Service via JNDI.

2.    Return Home Object reference to the client.

3.    Create me a new EJB Object through Home Object interface.

4.    Create EJB Object reference from the Ejb Object.

5.    Return EJB Object reference to the client.

6.    Invoke business method using EJB Object reference.

7.    Delegate request to Bean (Enterprise Bean).

 

How can I call one EJB from inside of another EJB?

EJBs can be clients of other EJBs. It just works.

Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth.

 

What is an EJB Context?


EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract.

Entity beans use a subclass of EJBContext called EntityContext.

Session beans use a subclass called SessionContext

 

What is the difference between session and entity beans? When should I use one or the other?


An entity bean represents persistent global data from the database; a session bean represents transient user-specific data that will die when the user disconnects (ends his session).

Generally, the session beans implement business methods (e.g. Bank.transferFunds) that call entity beans (e.g. Account.deposit, Account.withdraw)

 

Does Stateful Session bean support instance pooling?
Stateful Session Bean conceptually doesn’t have instance pooling.

 

Can I map more than one table in a CMP?
No, you cannot map more than one table to a single CMP Entity Bean. CMP has been, in fact, designed to map a single table

 


 

 

 

 

 

 

 

 

 

 

 

 

Session façade.

Calling entity bean indirectly via session bean is called as session façade.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Scope

Name pattern

Global

java:global[/<app-name>]/<module-name>/<bean-name>[!<fully-qualified-interface-name>]

Application

java:app/<module-name>/<bean-name>[!<fully-qualified-interface-name>]

Module

java:module/<bean-name>[!<fully-qualified-interface-name>]

 

CustomerServiceLocal customerService =

    (CustomerServiceLocal) new InitialContext().lookup("java:module/CustomerService");

 

java:global/Working-with-EJB3-Tutorials/EJB3/HelloWorld!com.saravan.tutorials.ejb3.HelloWorld

 

java:global/Working-with-EJB3-Tutorials/EJB3/HelloWorld

 

java:app/EJB3/HelloWorld!com.saravan.tutorials.ejb3.HelloWorld

 

java:app/EJB3/HelloWorld

 

java:module/HelloWorld!com.saravan.tutorials.ejb3.HelloWorld

 

java:module/HelloWorld

2003 –

 

 

 

 

 

 

 

MANDATORY

If the client has not started a transaction, an exception is thrown. Otherwise the client's transaction is used.

REQUIRED

If the client has started a transaction, it is used. Otherwise a new transaction is started. (this is the default when no explicit type has been specified)

REQUIRES_NEW

If the client has started a transaction, it is suspended. A new transaction is always started.

NOT_SUPPORTED

If the client has started a transaction, it is suspended. No new transaction is started.

SUPPORTS

If the client has started a transaction, it is used. Otherwise, no transaction is used.

NEVER

If the client has started a transaction, an exception is thrown. No new transaction is started.

 

 

EJB2

EJB3+

Deployment descriptors (DD)

Annotation

Home and Remote interfaces

Not required

ejbPassivate, ejbActivate, ejbLoad, ejbStore, methods

Not required

JNDI or DD

POJO and entity manager

 

entity beans/JPA becomes local.

Remote annotations are not at all supported for entity beans.

 

 

no need to implement container call back methods like ejbActivate()

 

Query is very flexible. Multiple levels of joins are enabled through the refined EJB-QL 

 

 

Easy to convert from DAO to Entity bean

 

The business interface does not need to extend the EJBObject or theEJBLocalObject interface;

Need EJB container

It can run JVM without EJB container

 

 

 

 

 

 



 

 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

In-Container DI [EJB -> Servlet DI]

 

Session Façade Implementation

Façade Delegate

Stateless session bean identity

@EJB MyBean bean1;

@EJB MyBean bean2;

if(bean1.equals(bean1)) // true

if(bean1.equals(bean2)) //true

Stateful session bean identity

@EJB MyBean bean1;

@EJB MyBean bean2;

if(bean1.equals(bean1)) // true

if(bean1.equals(bean2)) //false

Singleton session bean identity

@EJB MyBean bean1;

@EJB MyBean bean2;

if(bean1.equals(bean1)) // true

if(bean1.equals(bean2)) //true

Eager Initialization using @Startup

 

Key Messaging Concepts

 

Message – encapsulates data passed during

communication

Message Producer – creator of the message

Messaging System – responsible for routing and

delivery of message

Destination – delivery endpoint for message

Message Consumer – end recipient of message

A message contains:

Header fields: priority, timestamp, etc.

Optional message body

Optional properties

JMS Destination

 

javax.jms.Destination

javax.jms.Queue

javax.jms.Topic

 

 

Dependency Injection examples:

@Resource(mappedName="jms/Queue")

private Queue queue;

@Resource(mappedName="jms/Topic")

private Topic topic;

@Resource(mappedName="jms/Queue")

private Destination topic;

JMS Connection

javax.jms.Connection - physical

connection to the underlying JMS

implementation

Connections are retrieved through a

javax.jms.ConnectionFactory

Two types of connection factories:

javax.jms.QueueConnectionFactory

javax.jms.TopicConnectionFactory

 

Getting a JMS Connection

@Resource(mappedName="jms/ConnectionFactory")

private ConnectionFactoryconFactory;

Connection con = conFactory.createConnection();

con.close();

JMS Session

Session session = con.createSession(txn-support, acknowledgement);

Sessions support transactions

Transacted (true): messages are not sent until the session

closes

Not transacted (false): messages are sent immediately

Session support acknowledgement

AUTO_ACKNOWLEDGE

CLIENT_ACKNOWLEDGE

DUPS_OK_ACKNOWLEDGE

 

MessageProducer

javax.jms.MessageProducer

Associated with a specific Destination

Created from Session

MessageProducer producer = session.createProducer(destination);

MessageProducer producer = session.createProducer(queue);

MessageProducer producer = session.createProducer(topic);

Used to send messages to a Destination

producer.send(message);

 

Message

javax.jms.Message described by:

·    Header – name-value pairs used by messaging

system and message consumer

·    Properties – name-value pairs to specify

additional information

·    Body – payload of the message

·    Type - of message being transported

 

Common Message Header Fields

 

Message Types

\

Message Type Contents of Body

TextMessage message = session.createTextMessage();

message.setText(“Hello Messaging World”);

producer.send(message);

Creating a Message Producer

Steps to create a Message Producer

1. Create Destination in Messaging System

2. Create Client

1. Get Destination

2. Create Connection

3. Create Session

4. Create MessageProducer

5. Create Message

6. Send Message

7. Close Session

8. Close Connection

 

 

6 Key Concepts in JMS Solutions

Message Producer

Message System

Message Consumer

Message

Destination

Session

 

 

jms-based-mdb

Inheritance Based Example

import javax.ejb.*;

import javax.jms.*;

@MessageDriven

public class MyMDB implements MessageListener {

public void onMessage(Messagemsg) {

System.out.println("Got message!");

}

}

Annotation Based Example

import javax.ejb.*;

import javax.jms.*;

@MessageDriven(messageListenerInterface=javax.jms.MessageListener.class)

public class MyMDB {

public void onMessage(MessageinMessage) {

System.out.println("Got message!");

}

}

 

Simple configuration

@MessageDriven(mappedName = "jms/HelloMDBQueue”)

Complete configuration

@MessageDriven(activationConfig =

{@ActivationConfigProperty(

 propertyName="destination",

 propertyValue = "jms/HelloMDBQueue"),

 @ActivationConfigProperty(

 propertyName="destinationType”,

 propertyValue = "javax.jms.Queue")

}

)

 

 

 

 

 

Message Selector Identifiers

Potential identifiers for a message selector

·   JMS Headers

·    JMSDeliveryMode

·    JMSPriority

·    JMSMessageID

·    JMSTimestamp

·    JMSCorrelationID

·    JMSType

JMS Properties

   setStringProperty, setBooleanProperty,setIntProperty, etc.

 

Common comparison operators:

Algebraic comparison operators

LIKE operator

BETWEEN operator

IN operator

NOT operator

IS NULL operator

 

Message Selector Examples

Only add operations

ActivationConfigProperty(propertyName="messageSelector",

propertyValue = "Operation = 'add‘}

Only multiply operations with a result equal to100

ActivationConfigProperty(propertyName="messageSelector",

propertyValue = "Operation = ‘multiply‘ AND Result = 100}

Only multiply or add operations with a result greater than 100

ActivationConfigProperty(propertyName="messageSelector",

propertyValue = "Operation IN (‘multiply‘,‘add‘) AND Result > 100}

 

 

 

Default – AUTO_ACKNOWLEDGE

Non-Default Example:

@MessageDriven( activationConfig={

@ActivationConfigProperty(

propertyName=”acknowledgeMode”,

propertyValue=“Dups-ok-acknowledge)

}

)

 

Simplest way to implement an MDB

·     @MessageDriven(mappedName=queue/Example

·     implements MessageListener

·     onMessage(Messagem)

 

 

Managing Singleton Concurrency

Aspect-Oriented Programming with Interceptors

EJB Transactions

EJB Security

Web Service Development using EJBs

 

@Lock

Used to define method-level locking strategies

·     Bean can have a concurrent-safe methods

·     Or, concurrent unsafe methods

·     Or, a mixture of the two

Locking strategy is applied using:

·     @LOCK(LockType.READ) – supports concurrency

·     @LOCK(LockType.WRITE) – does not support concurrency

Locking strategy can be applied to:

·     Class – defines general locking strategy for all methods

·     Method – defines specific locking strategy for method

 

Singleton Concurrency Example

Controlling Dead Lock

·    Deadlock - is a situation where in two or more competing

actions are each waiting for the other to finish, and thus

neither ever does

·    Deadlock can occur in every concurrent system

·    In singletons, may be caused by long-running operations

·    Manage wait-times using

 

 

 

Aspect Oriented Programming

Definition: is a programming paradigm which aims to increase

modularity by allowing the separation of crosscutting concerns

 

Common cross-cutting concerns:

·     Logging, Security

·     Validation, Transformation

Advantages of AOP

·     Reusability

·     Separation of Concern

·    Consistency

 

What is an Interceptor?

Interceptor functionality enables Aspect-oriented

programming within Java EE

 

Interceptors can be associated with methods or

an entire class

 

Interceptors intercept interactions with bean

·    Can forward the call to the bean

·    Can process the call directly

·    Can process and forward the call

 

Interceptor Characteristics

 

 

Types of EJB Interceptors

1. Business Method level interceptors

Apply to a single method in a class

Or, apply to all methods in a call

2. Lifecycle Callback Interceptors

3. Timer Timeout Interceptors

 

Redundant Concern

 

Refactored Concern

 

 

Externalizing the Concern

Better approach is to externalize the concern

Create a class that is an Interceptor

·    Declare a Java technology class

·    Include a public no-arg constructor

·    Declare an interceptor method class

@AroundInvoke

public Object methName(InvocationContextic)throws Exception { . . }

·    Invokes the InvocationContextobject‘s proceed

return ic.proceed();

Associate interceptor with EJB

 

Associating an Interceptor

With a class:

@Stateless

@Interceptors(MyInterceptor.class)

public class MyBean { . . . }

With a specific method

@Stateless

public class MyBean {

@Interceptors(MyInterceptor.class)

public void someMeth() { . . . }

}

 

EJB with Interceptor Example

 

 

Lifecycle Interceptors

Timeout Interceptors

Class-level interceptors are executed first, then method

level interceptors

LogInterceptor Example

ejb-jar.xml

 

 

Transactions

Purpose of transactions:

·    Treat multiple operations as if they were one

·    All succeed together or fail together

ACID of transactions:

·    Automicity – all operations succeed or none do

·    Consistency – system will be consistent before and after

request

·    Isolation – txns are not seen outside of their scope until

completed

·   Durability – once a txn successfully completes, client

must commit to its changes

 

@TransactionManagement(TransactionManagementType.BEAN)

@TransactionManagement(TransactionManagementType.CONTAINER)

 

·    NOT_SUPPORTED – method can not operate correctly

within a txn; container possibly suspends current txn

when performing operation

·    SUPPORTS – method can operate correctly within a txn

·    REQUIRED – method requires txn, but doesn‘t need to

be new

·    REQUIRES_NEW – method requires txn, creates new

txn, possibly suspending current txn until operation

completes

·    MANDATORY – method can only operate within txn; if

method is invoked without txn, an exception is generated

·    NEVER – method can not operate within txn; if method is

invoked within txn, an exception is generated

 

 

@TransactionAttribute(REQUIRED)

public class MyEJB implements MyI {

}

 

Method level:

public class MyEJB implements MyI {

@TransactionAttribute(REQUIRED)

public void doSomething() { . . . }

}

 

JSR250 Security Annotations

 

EJB Web Services Support

EJB supports three types of web services:

JAX-RPC

Creates Web Service Endpoints defined by WSDL

Uses SOAP as transport mechanism

JAX-WS

New version of JAX-RPC

Better support for more modern web service

development

JAX-RS

REST-based web services

Simple to implement and use

Two ways to develop web services

Manually assemble web service

o WSDL

o Java Interface

o Bindings

Automatically

o Translate an EJB into a Web Service

o Annotation driven

 

JAX-WS Web Service Annotations

@WebService

javax.jws.WebService

Apply to EJB class

Exposes all public methods

@WebMethod

javax.jws.WebMethod

Apply to specific methods to expose within bean

SOAP Configuration annotations

@SOAPBinding

@WebParam

@WebResult

 

 

JAX-RS Annotations

@Path – entry point for REST service

HTTP request methods

@Get

@Post

@Put

@Delete

@Produces / @Consumes – data transfers

@Produces(application/xml)

@Consumes(application/xml)

@Produces(application/json)

@Consumes(application/json)

@Produces(text/plain)

@Consumes(text/plain)

 

Simple REST EJB

 

 

·   AOP can be applied using Interceptors

·   Transactions can be managed by the container

or the bean

·   Java EE is focused on authorization, not

authentication

·   Stateless and MDBs can be converted to web

services with the @WebServiceannotation

 

 

Image result for soap vs rest difference

 

 

JAX-WS

JAX-RS

 

Soap uses services intrfaces

URiS

 

Permits XML format

Lot of formats JSON, XML, HTML, text, RSS, etc

 

It is like envelope

It is like postcard, so simple

 

Cannot be cached

Can be cached

 

ENDPOINT

It supports PUT, DELETE

 

It can be HTTP, TCP or SMTP, FTP, JMS, MIME

HTTP or HTTPS only

 

It has both stateless and stateful

It is stateless

 

Supports async

 

 

Security and authorization are part of the protocol

 

 

Enterprise approach

Open web

 

Used in financial services / payment gateways / telcom services

Used in social media, web chat, mobile

 

Defining Schedules

Schedules consist of 7 attributes:

Time components

second – [0,59]

minute – [0,59]

hour – [0,23]

Calendar components:

dayOfMonth – [1,31], Last, Sun, Mon, Tue, etc.

month – [1,12], Jan, Feb, Mar, etc.

dayOfWeek – [0,7], Mon, Tue, etc.

year – [2001]

Every Tuesday at Midnight

ScheduleExpression schedule = new ScheduleExpression();

schedule.setDayOfWeek(Tue);

schedule.setHour(0);

Every Weekday at 3:15 AM

ScheduleExpression schedule = new ScheduleExpression();

schedule.setDayOfWeek(Mon-Fri);

schedule.setHour(3);

schedule.setMinute(15);

Every 15 minutes of Every Hour Every Day

ScheduleExpression schedule = new ScheduleExpression();

schedule.setHour(*);

schedule.setMinute(*/15);

 

@Schedule(dayOfWeek=Mon)

public void listOrders(Timer timer) {

// do something fancy

}