ecom lec3 16_ej_bs

36
E-commerce Systems Instructor: Dr. Zainab Khallouf Enterprise JavaBeans (EJB 3.1) Acknowledgements: Lecture notes adapted from: The Java EE 7 Tutorial. http://docs.oracle.com/javaee/7/tutorial/doc/javaeetutorial7.pdf Lecture References: [1]. docs.oracle.com/javaee/7/tutorial/doc/ [2]. http://netbeans.org/kb/docs/javaee/ecommerce [3]. Enterprise JavaBeans 3.1, sixth edition, by Andrew Lee Rubinger, Bill Burke, O'Reilly Media. [4]. Chapter 4 from Distributed Systems Principles and Paradigms, by A. Tanenbaum and M. Van Steen. ... ة ق ساب ل ا رة ض حا م ل ا ن م ر كي ذ ت ات وت ك م ل اّ م ض ي ات ق ب لط اُ عذد ب م ة ي ن رو كي ل ا ارة ح ت ق ي6 ب ط ي ق ي ق ح تر:ر مق ل ا ن مأ@ ول الُ م س ق ل ا: ي ل ا ت ل ل ا كJ ش ل ا ي ف ةّ ح ض و م ل ا1 | Page

Upload: zainab-khallouf

Post on 27-Jan-2017

42 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Ecom lec3 16_ej_bs

E-commerce SystemsInstructor: Dr. Zainab Khallouf

Enterprise JavaBeans (EJB 3.1)Acknowledgements:Lecture notes adapted from: The Java EE 7 Tutorial.http://docs.oracle.com/javaee/7/tutorial/doc/javaeetutorial7.pdfLecture References:[1]. docs.oracle.com/javaee/7/tutorial/doc/[2]. http://netbeans.org/kb/docs/javaee/ecommerce[3]. Enterprise JavaBeans 3.1, sixth edition, by Andrew Lee Rubinger, Bill Burke, O'Reilly Media.[4]. Chapter 4 from Distributed Systems Principles and Paradigms, by A. Tanenbaum and M. Van Steen.

تذكير من المحاضرة السابقة... القسُم األول من المقرر: تحقيق تطبيق تجارة الكترونية

متعددُ الطبقات يضمّ المكونات الموضّحة في الشكلالتالي:

...Session Beansمحاضرة اليوم عن :Enterprise JavaBeans (EJBs)تعريف

1 | P a g e

Page 2: Ecom lec3 16_ej_bs

Enterprise JavaBeans (EJBs) are server-side Java EE components run in the EJB container and encapsulate the business logic of an application.

:بكلمات بسيطةEJBs حقول ) هي صفوف جافا تتضمنfields طرق لتحقق منطق العمل في التطبيق، يضاف( و

annotationsإلى هذه الصفوف بعض الترميزات اإلضافية منEJBs container أو EJBsحتى يتمكن حاوي مكونات

إدارة هذه المكونات وتقديم خدمات لها.Benefits of Enterprise Beans (Enterprise Beans فوائد استخدام )Enterprise beans can simplify the development of large, distributed applications.

1. Because the EJBs container provides system-level services such as security, transaction management, Java Naming and Directory Interface (JNDI) API lookups, and remote connectivity to enterprise beans, the bean developer can concentrate on solving business problems.

2. The enterprise beans are reusable components, and the application assembler can build new applications from existing beans.

3. Scalability can be achieved by distributing an application’s components across multiple machines. The enterprise beans of an application can run on different machines, and their location will remain transparent to the clients.

Types of Java Enterprise Beans (EJBs):1. Session beans. 2. Message-driven beans.

Session Beans

2 | P a g e

Page 3: Ecom lec3 16_ej_bs

What is a Session Bean? A session bean is a component that encapsulates business

logic and include methods that can be invoked by a client. Session beans are of three types:

1. stateless, 2. stateful, 3. singleton.

Developing Enterprise Application with Session Beans Using Netbeans:Step 1:

Creating new enterprise application in Netbeans.

Step 2:

Name and Location.

3 | P a g e

Page 4: Ecom lec3 16_ej_bs

Step 3:Server and Settings.

Step 4:4 | P a g e

Page 5: Ecom lec3 16_ej_bs

The new project.

Step 5:Adding Libraries to CounterBeanFall16-ejb.

Step 6:Add session beans.

5 | P a g e

Page 6: Ecom lec3 16_ej_bs

6 | P a g e

Page 7: Ecom lec3 16_ej_bs

Step 7:Clean and Build.

7 | P a g e

Page 8: Ecom lec3 16_ej_bs

The generated .ear (Enterprise Archive) file.

We can explore the content of .ear files using (e.g. WinRAR).

8 | P a g e

Page 9: Ecom lec3 16_ej_bs

Step 8:Deploy.

9 | P a g e

Page 10: Ecom lec3 16_ej_bs

Server log.

...

INFO: EJB5181:Portable JNDI names for EJB CounterSession: [java:global/CounterBeanFall16/CounterBeanFall16-ejb/CounterSession, java:global/CounterBeanFall16/CounterBeanFall16-ejb/CounterSession!ejb.CounterSessionRemote]

INFO: EJB5182:Glassfish-specific (Non-portable) JNDI names for EJB CounterSession: [ejb.CounterSessionRemote, ejb.CounterSessionRemote#ejb.CounterSessionRemote]

INFO: CounterBeanFall16 was successfully deployed in 1,738 milliseconds.

...Accessing Session Beans

يمكن لـ (Session Bean( أن يعرض الطرق )Methods) Businessإّما من خالل واجهة )التي يمكن أن تستدعى

Interface( أو بدون استخدام واجهة )No-interface view) وفي الحالة الثانية يمكن استدعاء الطرق العامة فقط

.(Session Beanمن صف )( يمكن أن يكون الوصول إلى Session Bean)عن بعد(:)

remote )محلي( ،local )أو )كخدمة وب ،web service( ًعلما أّن موضوع خدمات الوب سيكون موضوع محاضرة

(.مستقلة

10 | P a g e

Page 11: Ecom lec3 16_ej_bs

لتوضيح الفرق بين الوصول عن بعد و الوصول المحلي دعنا نرى الفرق بين المستدعين المحليين و المستدعين

(.Session Beanالبعيدين لـ )

Local Clients

A local client has these characteristics. It must run in the same application as the enterprise bean it

accesses. It can be a web component or another enterprise bean.

To build an enterprise bean that allows only local access, you may do one of the following:

Create an enterprise bean implementation class that does not implement a business interface.

For example:@Statelesspublic class MyBean { ... }

Annotate the business interface of the enterprise bean as a @Local interface.

For example: @Local public interface InterfaceName { ... }

Specify the interface by decorating the bean class with @Local and specify the interface name.

For example:@Local(InterfaceName.class)public class BeanName implements InterfaceName { ... }

Remote Clients

A remote client of an enterprise bean has the following traits:

11 | P a g e

Page 12: Ecom lec3 16_ej_bs

It can run on a different machine and a different JVM from the enterprise bean it accesses. (It is not required to run on a different JVM.)

It can be a web component, an application client, or another enterprise bean.

In this case, the session bean must implement a business interface.

To create an enterprise bean that allows remote access, you must either

Decorate the business interface of the enterprise bean with the @Remote annotation:

@Remote

public interface InterfaceName { ... }

Decorate the bean class with @Remote, specifying the business interface or interfaces:

@Remote(InterfaceName.class)

public class BeanName implements InterfaceName { ... }

Using Enterprise Beans in Clients The client of an enterprise bean obtains a reference to an

instance of an enterprise bean through either:1. Dependency injection o Dependency injection uses the @EJB annotation from

javax.ejb.EJBo And specify the enterprise bean's implementation class

or enterprise bean's local business interface name (local or remote)

12 | P a g e

Page 13: Ecom lec3 16_ej_bs

o Can be used by local clients (i.e. must run in the same application as the enterprise bean it accesses) or remote clients that run within a Java EE server-managed environment. Examples:

Web tier components. Business tier compononts.

2. JNDI Syntax دعنا نأخذ فكرة عن كيفيةJNDIقبل عرض كيفية استخدام

JAVA EE(تطبيق Packagingتوضيب )Note About Packaging:

A Java EE application is delivered in a Java Archive (JAR) file, a Web Archive (WAR) file, or an Enterprise Archive (EAR) file. o A WAR or EAR file is a standard JAR (.jar) file with a .war

or .ear extension. An EAR file can contain Java EE modules of the following

types: o EJB modules , which contain class files for enterprise

beans and, optionally, an EJB deployment descriptor (A deployment descriptor, an XML document with an .xml extension, describes the deployment settings of an application, a module, or a component. ). EJB modules are packaged as JAR files with a .jar extension.

o Web modules , which contain servlet class files, web files, supporting class files, GIF and HTML files, and, optionally, a web application deployment descriptor. Web modules are packaged as JAR files with a .war (web archive) extension.

o Application client modules , which contain class files and, optionally, an application client deployment descriptor.

13 | P a g e

Page 14: Ecom lec3 16_ej_bs

Application client modules are packaged as JAR files with a .jar extension.

o Resource adapter modules , (A resource adapter is a Java EE component that implements the Java EE Connector Architecture for a specific EIS-like enterprise resource planning). Resource adapter modules are packaged as JAR files with an .rar (resource adapter archive) extension.

Packaging Enterprise Beans in WAR Modules:o Enterprise beans often provide the business logic of a web

application. In these cases, packaging the enterprise bean within the web application's WAR module simplifies deployment and application organization.

o Web Module Structure

14 | P a g e

Page 15: Ecom lec3 16_ej_bs

classes: A directory that contains server-side classes: servlets, enterprise bean class files, utility classes, and JavaBeans components.

lib: A directory that contains JAR files that contain enterprise beans, and JAR archives of libraries called by server-side classes.

Deployment descriptors, such as web.xml (the web application deployment descriptor) and ejb-jar.xml (an EJB deployment descriptor).

Example 1:

Example 2:

15 | P a g e

Page 16: Ecom lec3 16_ej_bs

Three JNDI namespaces are used for portable JNDI lookups:

o java:global: JNDI global addresses are of the following form:

java:global[/application name]/module name /enterprise bean name[/interface name ]

Application name is required only if the application is packaged within an Enterprise Archive.

The interface name is required only if the enterprise bean implements more than one business interface.

o java:module JNDI namespace used to look up local enterprise beans within the same module. JNDI addresses using the java:module namespace are of the following form:

java:module/enterprise bean name/[interface name] The interface name is required only if the

enterprise bean implements more than one business interface.

o java:app JNDI namespace used to look up local enterprise beans packaged within the same application.

16 | P a g e

Page 17: Ecom lec3 16_ej_bs

JNDI addresses using the java:app namespace are of the following form:

java:app[/module name]/enterprise bean name [/interface name] The module name is optional. The interface name is

required only if the enterprise bean implements more than one business interface.

o Example:If an enterprise bean, CounterSession.java, from an application CounterBean (EAR archive)is packaged within the module CounterBean-ejb.jar.

The JNDI name using the java:global namespace is:

We can verify this name from the server log.INFO: EJB5181:Portable JNDI names for EJB CounterSession: [java:global/CounterBean/CounterBean-ejb/CounterSession!ejb.CounterSessionRemote, java:global/CounterBean/CounterBean-ejb/CounterSession]INFO: EJB5182:Glassfish-specific (Non-portable) JNDI names for EJB CounterSession: [ejb.CounterSessionRemote, ejb.CounterSessionRemote#ejb.CounterSessionRemote]

17 | P a g e

Page 18: Ecom lec3 16_ej_bs

INFO: CounterBean a été déployé en 875 ms.INFO: set()INFO: count()Return to page 454 from the JEE 7 Tutorial for further details.Stateless Session Bean (SLSB)

The SLSB class is annotated with: @Stateless A stateless session bean does not maintain a conversational

state with the client. When a client invokes the methods of a stateless bean, the bean's instance variables may contain a state specific to that client but only for the duration of the invocation.

Stateless session bean can be easily pooled . Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client.

Clients may, however, change the state of instance variables in pooled stateless beans, and this state is held over to the next invocation of the pooled stateless bean.

Stateless Session Bean Example Application: -This application includes a counter SLSB CounterSession, this bean exposes two methods in a remote interface CounterSessionRemote: set(int val): set the initial value of the counter and count() increases by one the value of the counter.-The client is a JAVA SE application.

18 | P a g e

Page 19: Ecom lec3 16_ej_bs

The CounterSession SLSB and its remote interface CounterSessionRemote:

The client:

19 | P a g e

Page 20: Ecom lec3 16_ej_bs

The output:

Note 1: in netbeans, every time you change in the code of the bean you need to “clean and build” then “deploy”Note 2: About integrating EJB project in the client application.

20 | P a g e

Page 21: Ecom lec3 16_ej_bs

Example 2

Stateful Session Bean (SFSB) The SFSB class is annotated with: @Stateful Stateful session beans maintain conversational state, which

means that the instance variables of the bean class can maintain data specific to a unique client between method invocations. When the client terminates, its session bean appears to terminate and is no longer associated with the client.

Stateful session beans are managed using cache; the size of the cache specifies the maximum number of session beans that are held in cache.

21 | P a g e

Page 22: Ecom lec3 16_ej_bs

If the cache overflows (when the number of beans exceeds max-cache-size), the container then passivate some beans or writes out the serialized state of the bean into a file.

Stateful Session Bean Example Application: o This application includes a counter SFSB CounterSession,

this bean exposes three methods in a remote interface CounterSessionRemote, these methods are: set(int val): set the initial value of the counter and count() increases by one the value of the counter, and remove() remove the SFSB instance.

o The client is a JAVA SE application.

The CounterSession SFSB: package ejb;22 | P a g e

Page 23: Ecom lec3 16_ej_bs

import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;import javax.ejb.PostActivate;import javax.ejb.PrePassivate;import javax.ejb.Remove;import javax.ejb.Stateful;@Statefulpublic class CounterSession implements CounterSessionRemote { private int val; @Override public int count() { System.out.println("count()"); val = val + 1; return val; } @Remove @Override public void remove() { System.out.println("remove()"); } @Override public void set(int val) { this.val = val; System.out.println("set()"); } @PostConstruct public void construct() { System.out.println("construct()"); }

23 | P a g e

Page 24: Ecom lec3 16_ej_bs

@PostActivate public void activate() { System.out.println("activate()"); } @PrePassivate public void passivate() { System.out.println("passivate()"); } @PreDestroy public void destroy() { System.out.println("destroy()"); }}

The callbacks of the Lifecycles of Enterprise Beans:The callbacks :طرق تسمح بتنفيذ مهام معينة في مراحل

.Enterprise Beansمختلفة من حياة o @PostConstruct: Methods annotated with

@PostConstruct are invoked by the container on newly constructed bean instances (used for stateless , stateful session bean, and message driven bean)

o @PreDestroy: Methods annotated with @PreDestroy are invoked after any method annotated @Remove has completed and before the container removes the enterprise bean instance. (used for stateless , stateful session bean, and message driven bean)

o @PostActivate: denote method to be invoked after the stateful session activation.

o @PrePassivate: denote method to be invoked before the stateful session passivation.

24 | P a g e

Page 25: Ecom lec3 16_ej_bs

o @Remove: remove the bean after calling the method annotated by @Remove (Used with stateful session bean).

The client:

Output

And the server log

25 | P a g e

Page 26: Ecom lec3 16_ej_bs

Singleton Session Beans A singleton session bean is instantiated once per application and

exists for the lifecycle of the application. Singleton session bean is shared and concurrently accessed by

clients.Creating a Singleton Session Bean The javax.ejb.Singleton annotation is used to specify that the

enterprise bean implementation class is a singleton session bean:@Singletonpublic class SingletonBean { ... }

Initializing Singleton Session Beans The EJB container is responsible for determining when to

initialize a singleton session bean instance unless the singleton session bean implementation class is annotated with the javax.ejb.Startup annotation.

The @javax.ejb.Startup annotation marks that the container must start the bean instance alongside application startup.

@Startup@Singleton

26 | P a g e

Page 27: Ecom lec3 16_ej_bs

public class StatusBean {...}

Managing Concurrent Access in a Singleton Session Bean Singleton session beans are designed for concurrent access. Concurrent access to the singleton’s business methods can be

controlled in two ways: 1. Container-managed concurrency.2. Bean-managed concurrency.

The javax.ejb.ConcurrencyManagement annotation is used to specify container-managed or bean-managed concurrency for the singleton like this:

-avax.ejb.ConcurrencyManagementType.CONTAINER -javax.ejb.ConcurrencyManagementType.BEAN

By default the container-managed concurrency is used.Container-Managed Concurrency

1. Annotate a singleton’s business method with:o @Lock(READ) if the method can be concurrently

accessed with many clients. o Annotate the business method with @Lock(WRITE) if

the singleton session bean should be locked to other clients while a client is calling that method.

o If no @Lock annotation is present on the singleton class, the default lock type, @Lock(WRITE), is applied to all business methods.

Bean-Managed Concurrency2. Developers who create singletons with bean-managed

concurrency are allowed to use the Java programming language synchronization primitives.

27 | P a g e

Page 28: Ecom lec3 16_ej_bs

Singleton Session Bean Example Applicationo A simple singleton with one method, getHits, that increments a

counter representing the number of times the method has been accessed.

o The client is a standalone java client application.

The singleton bean CounterBean

The following version of CounterBean is equivalent to the preceding version:package counter.ejb;import javax.ejb.Singleton;import javax.ejb.ConcurrencyManagement;import javax.ejb.ConcurrencyManagementType.CONTAINER;

28 | P a g e

Page 29: Ecom lec3 16_ej_bs

import javax.ejb.Lock;import javax.ejb.LockType.WRITE;@Singleton@ConcurrencyManagement(CONTAINER)public class CounterBean {

private int hits = 1;// Increment and return the number of hits@Lock(WRITE)public int getHits() {

return hits++;}

}The client:

Output:

29 | P a g e

Page 30: Ecom lec3 16_ej_bs

30 | P a g e