UNIT -4
Lecture-27
4.1 ENTERPRISE JAVA BEANS (EJB):
4.1.1 What is EJB?
EJB is an acronym for enterprise java bean. It is a specification provided by Sun
Microsystems to develop secured, robust and scalable distributed applications.
To get information about distributed applications, visit RMI Tutorial first.
To run EJB application, you need an application server (EJB Container) such as
Jboss, Glassfish, Web logic, Web sphere etc.
4.1.2 Applications of EJB?
It performs:
a. life cycle management,
b. security,
c. transaction management, and
d. object pooling.
EJB application is deployed on the server, so it is called server side component also.
EJB is like COM (Component Object Model) provided by Microsoft. But, it is
different from Java Bean, RMI and Web Services.
4.1.3 Introduction to JavaBean
A JavaBean is a Java class that should follow the following conventions:
o It should have a no-arg constructor.
o It should be Serializable.
o It should provide methods to set and get the values of the properties, known
as getter and setter methods.
213
4.1.4 Creating a JavaBean
According to Java white paper, it is a reusable software component. A bean
encapsulates many objects into one object so that we can access this object from
multiple places. Moreover, it provides easy maintenance.
Simple example of JavaBean class
1. //[Link]
2.
3. package mypack;
4. public class Employee implements [Link]{
5. private int id;
6. private String name;
7. public Employee(){}
8. public void setId(int id){[Link]=id;}
9. public int getId(){return id;}
10. public void setName(String name){[Link]=name;}
11. public String getName(){return name;}
12. }
How to access the JavaBean class?
To access the JavaBean class, we should use getter and setter methods.
1. package mypack;
2. public class Test{
3. public static void main(String args[]){
4. Employee e=new Employee();//object is created
5. [Link]("Arjun");//setting value to the object
6. [Link]([Link]());
7. }}
4.1.5 JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the
object. The feature can be of any Java data type, containing the classes that you
define.
A JavaBean property may be read, write, read-only, or write-only. JavaBean features
are accessed through two methods in the JavaBean's implementation class:
214
1. getPropertyName ()
For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.
Advantages of JavaBean
The following are the advantages of JavaBean:/p>
o The JavaBean properties and methods can be exposed to another application.
o It provides an easiness to reuse the software components.
Disadvantages of JavaBean
The following are the disadvantages of JavaBean:
o JavaBeans are mutable. So, it can't take advantages of immutable objects.
o Creating the setter and getter method for each property separately may lead to
the boilerplate code.
LECTURE-28
4.1.6 Types of Enterprise Java Bean
There are 3 types of enterprise bean in java.
1. Session Bean
Session bean contains business logic that can be invoked by local, remote or
webservice client.
2. Message Driven Bean
Like Session Bean, it contains the business logic but it is invoked by passing
message.
215
3. Entity Bean
It encapsulates the state that can be persisted in the database. It is deprecated. Now,
it is replaced with JPA (Java Persistent API).
4.1.7 Session Bean
Session bean encapsulates business logic only, it can be invoked by local, remote
and webservice client.
It can be used for calculations, database access etc.
The life cycle of session bean is maintained by the application server (EJB
Container).
Types of Session Bean
There are 3 types of session bean.
1) Stateless Session Bean: It doesn't maintain state of a client between multiple
method calls.
2) Stateful Session Bean: It maintains state of a client across multiple requests.
3) Singleton Session Bean: One instance per application, it is shared between clients
and supports concurrent access.
Stateful Session Bean
The state of an object consists of the values of its instance variables. In a stateful
session bean, the instance variables represent the state of a unique client/bean
session. Because the client interacts (“talks”) with its bean, this state is often called
the conversational state.
As its name suggests, a session bean is similar to an interactive session. A session
bean is not shared; it can have only one client, in the same way that an interactive
session can have only one user. When the client terminates, its session bean appears
to terminate and is no longer associated with the client.
The state is retained for the duration of the client/bean session. If the client removes
the bean, the session ends and the state disappear. This transient nature of the state
is not a problem, however, because when the conversation between the client and
the bean ends, there is no need to retain the state.
216
The Life Cycle of a Stateful Session Bean:-
The stages that a session bean passes through during its lifetime. The client
initiates the life cycle by invoking the create method. The EJB container
instantiates the bean and then invokes
the setSessionContext and ejbCreate methods in the session bean. The bean is now
ready to have its business methods invoked.
Figure 4.1 Lifecycle of stateful Session Bean
While in the ready stage, the EJB container may decide to deactivate, or passivate,
the bean by moving it from memory to secondary storage. (Typically, the EJB
container uses a least-recently-used algorithm to select a bean for passivation.) The
EJB container invokes the bean's ejbPassivate method immediately before
passivating it. If a client invokes a business method on the bean while it is in the
passive stage, the EJB container activates the bean, calls the
bean's ejbActivate method, and then moves it to the ready stage.
At the end of the life cycle, the client invokes the remove method, and the EJB
container calls the bean's ejbRemove method. The bean's instance is ready for
garbage collection.
Your code controls the invocation of only two life-cycle methods:
the create and remove methods in the client. All other methods are invoked by the
EJB container. The ejbCreate method, for example, is inside the bean class, allowing
you to perform certain operations right after the bean is instantiated. For example,
you might wish to connect to a database in the ejbCreate method..
217
LECTURE-29
4.1.8 Stateless Session Bean
Stateless Session bean is a business object that represents business logic only. It
doesn't have state (data).
In other words, conversational state between multiple method calls is not maintained
by the container in case of stateless session bean.
The stateless bean objects are pooled by the EJB container to service the request on
demand.
It can be accessed by one client at a time. In case of concurrent access, EJB container
routes each request to different instance.
Life cycle of Stateless Session Bean
There are only two states of stateless session bean: does not exist and ready. It is
explained by the figure given below.
Figure 4.2 Life cycle of Stateless Session Bean
218
EJB Container creates and maintains a pool of session bean first. It injects the
dependency if then calls the @PostConstruct method if any. Now actual business
logic method is invoked by the client. Then, container calls @PreDestory method if
any. Now bean is ready for garbage collection.
4.1.9 Entity Bean:
An entity bean represents a business object in a persistent storage mechanism. Some
examples of business objects are customers, orders, and products. In the Application
Server, the persistent storage mechanism is a relational database. Typically, each
entity bean has an underlying table in a relational database, and each instance of the
bean corresponds to a row in that table
You should probably use an entity bean under the following conditions:
● The bean represents a business entity and not a procedure. For
example, CreditCardBean would be an entity bean,
but CreditCardVerifierBean would be a session bean.
● The bean's state must be persistent. If the bean instance terminates or if the
Application Server is shut down, the bean's state still exists in persistent
storage (a database).
The Life Cycle of an Entity Bean
the stages that an entity bean passes through during its lifetime. After the EJB
container creates the instance, it calls the setEntityContext method of the entity bean
class. The setEntityContext method passes the entity context to the bean.
After instantiation, the entity bean moves to a pool of available instances. While in
the pooled stage, the instance is not associated with any particular EJB object
identity. All instances in the pool are identical. The EJB container assigns an identity
to an instance when moving it to the ready stage.
There are two paths from the pooled stage to the ready stage. On the first path, the
client invokes the create method, causing the EJB container to call
the ejbCreate and ejbPostCreate methods. On the second path, the EJB container
invokes the ejbActivate method. While an entity bean is in the ready stage, an it's
business methods can be invoked.
There are also two paths from the ready stage to the pooled stage. First, a client can
invoke the remove method, which causes the EJB container to call
219
the ejbRemove method. Second, the EJB container can invoke
the ejbPassivate method.
Figure 4.3 The Life Cycle of an Entity Bean
At the end of the life cycle, the EJB container removes the instance from the pool
and invokes the unsetEntityContext method.
In the pooled state, an instance is not associated with any particular EJB object
identity. With bean-managed persistence, when the EJB container moves an instance
from the pooled state to the ready state, it does not automatically set the primary key.
Therefore, the ejbCreate and ejbActivate methods must assign a value to the primary
key. If the primary key is incorrect, the ejbLoad and ejbStore methods cannot
synchronize the instance variables with the database. In the section The
SavingsAccountBean Example, the ejbCreate method assigns the primary key from
one of the input parameters.
4.1.10 Message-Driven Bean
A message-driven bean is an enterprise bean that allows J2EE applications to
process messages asynchronously. It normally acts as a JMS message listener, which
220
is similar to an event listener except that it receives JMS messages instead of events.
The messages can be sent by any J2EE component--an application client, another
enterprise bean, or a web component--or by a JMS application or system that does
not use J2EE technology. Message-driven beans can process either JMS messages
or other kinds of messages.
Session beans and entity beans allow you to send JMS messages and to receive them
synchronously, but not asynchronously. To avoid tying up server resources, you may
prefer not to use blocking synchronous receives in a server-side component. To
receive messages asynchronously, use a message-driven bean.
The Life Cycle of a Message-Driven Bean
The EJB container usually creates a pool of message-driven bean instances. For each
instance, the EJB container instantiates the bean and performs these tasks:
1. It calls the setMessageDrivenContext method to pass the context object to the
instance.
2. It calls the instance's ejbCreate method.
Figure 4.4 The Life Cycle of a Message-Driven Bean
Like a stateless session bean, a message-driven bean is never passivated, and it has
only two states: nonexistent and ready to receive messages.
221
At the end of the life cycle, the container calls the ejbRemove method. The bean's
instance is then ready for garbage collection.
Java database connectivity: (jdbc)
LECTURE-30
4.2What is [Link]
[Link] is an open-source, cross-platform JavaScript runtime environment that
executes JavaScript code outside of a browser. Built on Chrome's V8 JavaScript
engine, [Link] enables developers to use JavaScript for server-side scripting,
allowing for the creation of dynamic web content on the server before it is sent to
the client.
4.2.1 Key Features and Benefits of [Link]
1. Asynchronous and Event-Driven: Non-blocking I/O operations allow for
handling multiple requests simultaneously.
2. Single-Threaded but Scalable: Despite being single-threaded, [Link] can
efficiently handle many concurrent connections.
3. Fast Execution: Built on the V8 engine, [Link] is optimized for high-speed
execution.
4. Cross-Platform: Works on Windows, MacOS, and Linux, with a large
community and extensive libraries.
5. JavaScript Everywhere: Allows developers to use JavaScript for both
frontend and backend development, simplifying full-stack development.
4.2.2 [Link] Environment Setup
222
● Installation Process
To get started with [Link], follow these steps:
1. Download [Link]: Go to [Link] official website and download the installer
for your operating system (Windows, MacOS, or Linux).
2. Install [Link]:
o For Windows or MacOS, run the installer and follow the installation
wizard steps.
o For Linux, you can use the package manager:
# For Debian/Ubuntu
sudo apt-get install -y nodejs
sudo apt-get install -y npm
# For Red Hat/CentOS
sudo yum install -y nodejs
sudo yum install -y npm
● Verify Installation:
node -v # to check [Link] version
npm -v # to check NPM version
2. REPL (Read-Eval-Print-Loop) Terminal
The REPL terminal in [Link] is an interactive shell that allows users to quickly
test and run JavaScript code line-by-line.
● Usage: Open the terminal and type node to enter the REPL.
● Features:
223
❖ Evaluates code as it’s typed.
❖ Provides access to variables and functions on the fly.
❖ Great for testing small JavaScript snippets quickly.
Advantages:
● Fast testing and debugging for small snippets.
● Immediate feedback on code execution.
Disadvantages:
● Not suitable for large codebases or complex applications.
LECTURE-31
4.2.3 NPM (Node Package Manager)
NPM is the default package manager for [Link], managing dependencies and
libraries required for [Link] applications.
Features
● Install Libraries: Provides access to over a million open-source packages.
● Dependency Management: Maintains and updates packages.
● Global and Local Installations: Install packages globally for CLI tools or
locally for individual projects.
Key Commands
● npm install <package>: Installs a package locally.
● npm install -g <package>: Installs a package globally.
224
● npm update: Updates all packages in the current project.
Advantages:
● Simplifies dependency management.
● Encourages code reuse through open-source libraries.
● Supports version control and project consistency.
Disadvantages:
● Can lead to “dependency hell” if poorly managed.
● Package vulnerabilities can expose security risks.
4.2.4Callbacks Concept
In [Link], callbacks are functions passed as arguments to other functions and are
invoked after the main function completes its execution. This is critical in
asynchronous programming.
const fs = require('fs');
[Link]('[Link]', 'utf8', (err, data) => {
if (err) throw err;
[Link](data);
});
Advantages:
● Non-blocking I/O operations improve performance.
● Essential for asynchronous operations.
Disadvantages:
225
● Can result in “callback hell,” where multiple nested callbacks make code
harder to read and maintain.
● More complex debugging in asynchronous code.
4.2.5 Events
[Link] is event-driven, utilizing an event loop that handles asynchronous
operations.
Event Emitter
● EventEmitter is a core module used to manage and trigger events in [Link].
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
[Link]('greet', () => {
[Link]('Hello World!');
});
[Link]('greet');
Advantages:
● Supports asynchronous event handling.
● Efficiently handles multiple concurrent connections.
Disadvantages:
● Complex event chains can make debugging harder.
● Increased learning curve for those unfamiliar with event-driven programming.
226