Unit 4-JavaBean nodejs mongoDB
Unit 4-JavaBean nodejs mongoDB
In any programming language, reusability is the main concern. To achieve the same concern, Java
introduced the concept of JavaBean. It is a software component that has been designed to be
reusable in a variety of environments. In this section, we will dive into the topic and understand the
horizons of concept in this what is JavaBeans, its advantages, disadvantages, Life cycle.
In other words, JavaBeans are classes that encapsulate multiple objects into a single object. It also
helps in accessing these object from multiple places. It contains several elements like Constructors,
getter and setter methods and much more.
o Serializability (Optional): While not mandatory, they often implement the Serializable
interface to allow object data to be converted into a stream of bytes for storage or
transmission.
o Data Encapsulation: They encapsulate data using private member variables (fields) to store
the object's state.
o Getter and Setter Methods: For each private field, there should be a corresponding public
getter and setter method:
o Getter methods (usually prefixed with get or is for booleans) retrieve the value of a
field.
o Setter methods (usually prefixed with set) modify the value of a field.
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.
//Employee.java
public class Employee implements java.io.Serializable
public Employee()
this.id=id;
return id;
this.name=name;
return name;
e.setId(1);
e.setName("Arjun");
System.out.println(e.getId());
System.out.println(e.getName());
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:
For Boolean properties getter method name can be prefixed with either "get" or "is". But
recommended to use "is".
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.
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:
Disadvantages of JavaBean
o Creating the setter and getter method for each property separately may lead to the
boilerplate code.
1. Reusability: JavaBeans are designed with reusability in mind. Once a bean is created, it can
be used across different applications. It allows developers to build upon existing components
rather than starting from scratch, significantly speeding up the development process.
2. Encapsulation: JavaBeans encapsulate many objects into one, hiding the internal complexity
of individual components from other parts of the program. Encapsulation helps in managing
complexity by exposing only necessary parts of the functionality.
3. Ease of Use: It can be manipulated visually in a builder tool. Most IDEs support JavaBeans by
providing features like dragging and dropping beans into applications, which makes it easier
for non-programmers or developers to build applications.
4. Integration and Flexibility: JavaBeans can be integrated into different environments and can
communicate with other components provided these components adhere to the Beans'
conventions. This flexibility also extends to their capability to operate across different
operating systems and platforms.
5. Customization: JavaBeans can be customized easily using property editors and customizers.
It allows other developers and software tools to configure a bean to fit their specific
environment.
6. Persistence: JavaBeans can be made persistent, meaning their state can be saved to and
restored from storage, without the need for the application to understand the beans'
internals. This persistence is facilitated by the Serializable interface.
7. Security: Beans provide a security framework that supports features like signing, constraints,
and role-based authorization, which can be critical for applications that require high security.
8. Interoperability: Since JavaBeans components are written in Java, they are inherently
interoperable with Java applications. However, with appropriate adapters, JavaBeans can
also be made to work with components written in other languages, promoting cross-
platform interaction.
1. Instantiation
The first stage in the life cycle of a JavaBean is instantiation. During this stage, the JavaBean is
created, usually by calling a no-argument constructor. It is a simple creation step where the bean is
allocated memory and its initial state is set up.
2. Customization (Optional)
After a bean is instantiated, it may undergo customization. It involves configuring the bean's
properties and other settings to suit specific needs. Customization typically happens in two ways:
o Design Time: Using tools such as IDEs where beans can be configured using property sheets.
Once the bean is customized, its properties are set. It is often done through setter methods defined
in the bean.
JavaBeans can be connected to other beans. It can involve setting up event listeners and event
sources, allowing beans to respond to events triggered by other beans.
5. Activation (Optional)
For beans that are serialized and later restored, the activation stage involves restoring the bean from
its serialized state.
6. Introspection
Introspection is a process where the capabilities of a bean are examined dynamically. Tools and
frameworks can inspect a bean to determine its properties, events, and methods.
7. Running
During this stage, the bean is in use and performing its intended tasks. It may handle data processing,
respond to user input, or interact with other components and beans.
8. Passivation (Optional)
In environments where beans are managed (like EJB containers), passivation is a stage where a
bean's state is temporarily stored to free resources.
9. Destruction
The final stage in the lifecycle of a JavaBean is its destruction. Here, the bean is marked for garbage
collection, and any resources it used are released. Before destruction, cleanup methods can be called
to ensure that all resources are freed properly, such as closing database connections or releasing file
handles.
Types of EJB
EJB is an acronym for Enterprise Java Beans. It is a server-side software element. It encapsulates the
business logic of an application. It is a specification for developing a distributed business application
on the Java platform.
There are three types of EJBs: Session Bean, Entity Bean, and Message-Driven Bean. In this section,
we will discuss all types of EJB in detail.
Session Bean
The bean sprout business idea that can be systematically used by customer, remote, and web service.
When a client wants to use an application distributed on a server, then the client uses session bean
methods. This session bean provides services to customers, protecting them from complex problems
by performing business operations within the server.
To get to an application that is conveyed to the worker, the client summons the meeting bean's
strategies. The meeting bean performs work for its client, safeguarding it from intricacy by executing
business errands inside the worker. Remember that session beans are not persistence.
To improve execution, we may choose a stateless session bean in the event that it has any of these
characteristics.
o The state of the bean has no information or data for a particular client.
o In a private method invocation, the bean performs a generic task for all clients.
The state is held for the span of the client/bean session. In case if the client eliminates the bean, the
session closes and the state is omitted. This transient nature of the state isn't an issue, because the
interaction between the client and the beans ends. So, it is not required to hold the state.
Stateful session beans should be used, if any of the following conditions are valid:
o The bean's state denotes the alliance between the bean and a particular client.
o The bean needs to hold data about the customer across method invocations.
o The bean interferes between the customer and different segments of the application,
introducing an improved visible to the client.
o In the background, the bean deals with the workstream of a few enterprise beans.
From that pool, any of the session beans may respond to the client. We can implement it in the web-
service endpoints. It takes care of the state but does not hold the state if unexpected crashes or
shutdown occur. It can be used if we want to perform cleanup tasks on closing the application or shut
down as well. It is because it operates throughout the life cycle of the application.
Singleton session beans are suitable for the following conditions:
o The application needs an enterprise bean to perform undertakings upon application startup
and shutdown.
Entity Bean
An entity bean is an unpredictable business substance. It models a business substance or models
different activities inside a business interaction. It is used to encourage business benefits that include
data and calculations on that data. It can deal with various, needy, diligent articles in playing out its
essential assignments. A substance bean is a far-off object that oversees steady information and
performs complex business rationale. It can be extraordinarily distinguished by an essential key.
It is a far-off object that oversees steady information, performs complex business rationale, possibly
utilizes a few ward Java protests, and can be remarkably distinguished by an essential key. It
ordinarily coarse-grained determined items since they use steady information put away inside a few
fine-grained relentless Java objects. Element beans are diligent on the grounds that they do endure a
worker crash or an organization's disappointment.
Every entity bean has a persistence identity that is associated with it. It means that it comprises a
unique identity that can be fetched if we have a primary key. The type for the unique key is defined
by the bean provider. A client can retrieve the entity bean if the primary has been misplaced. If the
bean is not available, the EJB container first, instantiates the bean and then re-populates the data for
the client.
The diligence for entity bean information is given both to saving state when the bean is passivated
and for improving the state when a failover has detected. It can endure in light of the fact that the
information is put away determinedly by the holder in some type of information stockpiling
framework, like a data set.
Entity beans persist business data by using the following two methods:
Container-Managed Persistence
In container-managed persistence, the EJB container transparently and implicitly handles the
relationship between the bean and the database. Bean developers focus on the data and the
business process. The principal constraint is that the EJB compartment can most likely not produce
information base access articulations with the proficiency of a programmer.
o Runtime Environment: A CMP runtime environment that uses the mapping information to
perform persistence operations on each bean.
Message-Driven Bean (MDB)
MDB is a Java Messaging Service (message listener). It consumes messages from a queue or
subscription of a topic. It provides an easy way to create or implement asynchronous communication
using a JMS message listener. An advantage of using MDB is that it allows us to use the asynchronous
nature of a JMS listener. We can implement message-driven beans with Oracle JMS (Java Messaging
Service).
There is an EJB container (contains MDBs pool) that handles the JMS queue and topic. Each incoming
message is handled by a bean that is invoked by the container. Note that no object invokes an MDB
directly. All invocation for MDB originates from the container. When the container invokes the MDB,
it can invoke other EJBs or Java objects to continue the request.
It is quite similar to stateless session bean. Because it does not save informal state, also used to
handle multiple incoming requests.
EJB has the following benefits over the JMS are as follows:
o It creates a consumer for the listener. It means that the container
creates QueueReceiver or TopicSubscriber is created by the container.
o MDB is registered with the consumer. It means that at deployment time QueueReceiver,
TopicSubscriber, and its factory are registered by the container.
o MDB creates and opens a JMS connection to the database by using the data source (JMS
resource provider). The JDBC driver is used to facilitate the JMS connection.
o If any message for the MDB is routed to the onMessage() method of the MDB from the
queue o topic. Other clients may also access the same queue and topic to put the message
for the MDB.
What is Node.js
Node.js is a cross-platform runtime environment and library for running JavaScript applications
outside the browser. It is used for creating server-side and networking web applications. It is open
source and free to use. It can be downloaded from this link https://nodejs.org/en/
Many of the basic modules of Node.js are written in JavaScript. Node.js is mostly used to run real-
time server applications.
?Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and scalable
network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight
and efficient, perfect for data-intensive real-time applications that run across distributed devices.?
Node.js also provides a rich library of various JavaScript modules to simplify the development of web
applications.
Following is a list of some important features of Node.js that makes it the first choice of software
architects.
1. Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, so its library is very
fast in code execution.
2. I/O is Asynchronous and Event Driven: All APIs of Node.js library are asynchronous i.e. non-
blocking. So a Node.js based server never waits for an API to return data. The server moves
to the next API after calling it and a notification mechanism of Events of Node.js helps the
server to get a response from the previous API call. It is also a reason that it is very fast.
3. Single threaded: Node.js follows a single threaded model with event looping.
4. Highly Scalable: Node.js is highly scalable because event mechanism helps the server to
respond in a non-blocking way.
5. No buffering: Node.js cuts down the overall processing time while uploading audio and
video files. Node.js applications never buffer any data. These applications simply output the
data in chunks.
6. Open source: Node.js has an open source community which has produced many excellent
modules to add additional capabilities to Node.js applications.
Text Editor:
The text editor is used to type your program. For example: Notepad is used in Windows, vim
or vi can be used on Windows as well as Linux or UNIX. The name and version of the text
editor can be different from operating system to operating system.
The files created with text editor are called source files and contain program source code.
The source files for Node.js programs are typically named with the extension ".js".
You can download the latest version of Node.js installable archive file from
https://nodejs.org/en/
1. console.log('Hello JavaTpoint');
1. node console_example1.js
response.end('Hello World\n');
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
So type cd desktop on the command prompt. After that execute the main.js to start the
server as follows:
1. node main.js
Open http://127.0.0.1:8081/ in any browser. You will see the following result.
Node.js Console
The Node.js console module provides a simple debugging console similar to JavaScript
console mechanism provided by web browsers.
There are three console methods that are used to write any node.js stream:
1. console.log()
2. console.error()
3. console.warn()
Node.js console.log()
Node.js REPL
The term REPL stands for Read Eval Print and Loop. It specifies a computer environment like
a window console or a Unix/Linux shell where you can enter the commands and the system
responds with an output in an interactive mode.
REPL Environment
The Node.js or node come bundled with REPL environment. Each part of the REPL
environment has a specific work.
Read: It reads user's input; parse the input into JavaScript data-structure and stores in
memory.
Loop: It loops the above command until user press ctrl-c twice.
You can start REPL by simply running "node" on the command prompt. See this:
You can execute various mathematical operations on REPL Node.js command prompt:
After starting REPL node command prompt put any mathematical expression:
1. Example: >10+20-5
2. 25
Variables are used to store values and print later. If you don't use var keyword then value is
stored in the variable and printed whereas if var keyword is used then value is stored but not
printed. You can print variables using console.log().
Example:
Node REPL supports multiline expressions like JavaScript. See the following do-while loop
example:
1. var x = 0
2. undefined
3. > do {
4. ... x++;
Example:
Commands Description
It is used to terminate the current
ctrl + c
command.
o It also provides command line utility to install Node.js packages, do version management and
dependency management of Node.js packages.
The npm comes bundled with Node.js installables in versions after that v0.6.3. You can check
the version by opening Node.js command prompt and typing the following command:
1. npm version
Open the Node.js command prompt and execute the following command:
You can see the result after installing the "express" framework.
By default, npm installs dependency in local mode. Here local mode specifies the folder
where Node application is present. For example if you installed express module, it created
node_modules directory in the current directory where it installed express module.
You can use npm ls command to list down all the locally installed modules.
Uninstalling a Module
1. npm ls
Searching a Module
There is a wide variety of command line options in Node.js. These options provide multiple
ways to execute scripts and other helpful run-time options.
It is used to print
1. v, --version
node's version.
It is used to print
2. -h, --help node command
line options.
It evaluates the
following argument
as JavaScript. The
3. -e, --eval "script" modules which are
predefined in the
REPL can also be
used in script.
It is identical to -e
4. -p, --print "script" but prints the
result.
It is used to
preload the
specified module
at startup. It
-r, --require follows require()'s
7.
module module resolution
rules. Module may
be either a path to
a file, or a node
module name.
Silence
8. --no-deprecation deprecation
warnings.
It is used to print
9. --trace-deprecation stack traces for
deprecations.
It silence all
process warnings
11. --no-warnings
(including
deprecations).
It prints a stack
trace whenever
synchronous i/o is
13. --trace-sync-io
detected after the
first turn of the
event loop.
Automatically zero-
fills all newly
14. --zero-fill-buffers allocated buffer
and slowbuffer
instances.
It tracks heap
--track-heap- object allocations
15.
objects for heap
snapshots.
It processes V8
profiler output
16. --prof-process generated using
the v8 option --
prof.
It prints V8
17. --V8-options command line
options.
It specifies an
alternative default
tls cipher list.
18. --tls-cipher-list=list (requires node.js to
be built with
crypto support.
(default))
It enables fips-
19. --enable-fips compliant crypto at
startup. (requires
node.js to be built
with ./configure --
openssl-fips)
It forces fips-
compliant crypto
on startup. (cannot
20. --force-fips be disabled from
script code.) (same
requirements as --
enable-fips)
It specifies ICU
data load path.
21. --icu-data-dir=file
(Overrides
node_icu_data)
Open Node.js command prompt and run command node -v or node --version
For Help:
o __dirname
o __filename
o Console
o Process
o Buffer
o clearImmediate(immediateObject)
o clearInterval(intervalObject)
o clearTimeout(timeoutObject)
Node.js __dirname
It is a string. It specifies the name of the directory that currently contains the code.
File: global-example1.js
1. console.log(__dirname);
1. node global-example1.js
Node.js __filename
It specifies the filename of the code being executed. This is the resolved absolute path of this
code file. The value inside a module is the path to that module file.
File: global-example2.js
1. console.log(__filename);
1. node global-example2.js
Node.js Callbacks
Callback is an asynchronous equivalent for a function. It is called at the completion of each
task. In Node.js, callbacks are generally used. All APIs of Node are written in a way to
supports callbacks. For example: when a function start reading file, it returns the control to
execution environment immediately so that the next instruction can be executed.
In Node.js, once file I/O is complete, it will call the callback function. So there is no blocking
or wait for File I/O. This makes Node.js highly scalable, as it can process high number of
request without waiting for any function to return result.
3. console.log(data.toString());
4. console.log("Program Ended");
3. Open the Node.js command prompt and execute the following code.
1. node main.js
1. var fs = require("fs");
2.
5. console.log(data.toString());
6. });
7. console.log("Program Ended");
3. Open the Node.js command prompt and execute the following code.
1. node main.js
Node.js Events
In Node.js applications, Events and Callbacks concepts are used to provide concurrency. As
Node.js applications are single threaded and every API of Node js are asynchronous. So it
uses async function to maintain the concurrency. Node uses observer pattern. Node thread
keeps an event loop and after the completion of any task, it fires the corresponding event
which signals the event listener function to get executed.
Node.js uses event driven programming. It means as soon as Node starts its server, it simply
initiates its variables, declares functions and then simply waits for event to occur. It is the
one of the reason why Node.js is pretty fast compared to other similar technologies.
There is a main loop in the event driven application that listens for events, and then triggers
a callback function when one of those events is detected.
Difference between Events and Callbacks:
Although, Events and Callbacks look similar but the differences lies in the fact that callback
functions are called when an asynchronous function returns its result where as event
handling works on the observer pattern. Whenever an event gets fired, its listener function
starts executing. Node.js has multiple in-built events available through events module and
EventEmitter class which is used to bind events and event listeners.
2. eventEmitter.on('eventName', eventHandler);
To fire an event:
1. // Fire an event
2. eventEmitter.emit('eventName');
File: main.js
5.
6. // Create an event handler as follows
8. console.log('connection succesful.');
9.
11. eventEmitter.emit('data_received');
12. }
13.
19. });
21. eventEmitter.emit('connection');
Now, open the Node.js command prompt and run the following code:
1. node main.js
MONGO-DB
Node.js Create Connection with MongoDB
To create a database in MongoDB, First create a MongoClient object and specify a connection URL
with the correct ip address and the name of the database which you want to create.
Note: MongoDB will automatically create the database if it does not exist, and make a connection to
it.
Example
Create a folder named "MongoDatabase" as a database. Suppose you create it on Desktop. Create a
js file named "createdatabase.js" within that folder and having the following code:
console.log("Database created!");
db.close();
});
Now open the command terminal and set the path where MongoDatabase exists. Now execute the
following command:
1. Node createdatabase.js
Example
7. console.log("Collection is created!");
8. db.close();
9. });
10. });
1. Node employees.js
The insertOne method is used to insert record in MongoDB's collection. The first argument of the
insertOne method is an object which contains the name and value of each field in the record you
want to insert.
Example
db.close();
});
});
1. Node insert.js
You can insert multiple records in a collection by using insert() method. The insert() method uses
array of objects which contain the data you want to insert.
Example
var myobj = [
];
db.close();
});
});
The findOne() method is used to select a single data from a collection in MongoDB. This method
returns the first record of the collection.
Example
console.log(result.name);
db.close();
});
});
1. Node select.js
The find() method is used to select all the records from collection in MongoDB.
Example
Select all the records from "employees" collection.
db.collection("employees").find({}).toArray(function(err, result) {
console.log(result);
db.close();
});
});
1. Node selectall.js
The find() method is also used to filter the result on a specific parameter. You can filter the result by
using a query object.
Example
Filter the records to retrieve the specific employee whose address is "Delhi".
Create a js file named "query1.js", having the following code:
db.collection("employees").find(query).toArray(function(err, result) {
console.log(result);
db.close();
});
});
1. Node query1.js
You can also use regular expression to find exactly what you want to search. Regular expressions can
be used only to query strings.
Example
Retrieve the record from the collection where address start with letter "L".
console.log(result);
db.close();
});
});
1. Node query2.js
2. { name: 1 }
4. { name: -1 }
Example
db.collection("employees").find().sort(mysort).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
1. Node sortasc.js
Example
db.collection("employees").find().sort(mysort).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
1. Node sortdsc.js
In MongoDB, you can delete records or documents by using the remove() method. The first
parameter of the remove() method is a query object which specifies the document to delete.
Example
db.close();
});
});
1. Node remove.js
Verification
You can check that the record having address "Ghaziabad" is deleted and only following records are
available now:
JavaBean
In any programming language, reusability is the main concern. To achieve the same concern, Java
introduced the concept of JavaBean. It is a software component that has been designed to be
reusable in a variety of environments. In this section, we will dive into the topic and understand the
horizons of concept in this what is JavaBeans, its advantages, disadvantages, Life cycle.
In other words, JavaBeans are classes that encapsulate multiple objects into a single object. It also
helps in accessing these object from multiple places. It contains several elements like Constructors,
getter and setter methods and much more.
o Serializability (Optional): While not mandatory, they often implement the Serializable
interface to allow object data to be converted into a stream of bytes for storage or
transmission.
o Data Encapsulation: They encapsulate data using private member variables (fields) to store
the object's state.
o Getter and Setter Methods: For each private field, there should be a corresponding public
getter and setter method:
o Getter methods (usually prefixed with get or is for booleans) retrieve the value of a
field.
o Setter methods (usually prefixed with set) modify the value of a field.
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.
//Employee.java
public class Employee implements java.io.Serializable
public Employee()
this.id=id;
return id;
this.name=name;
return name;
e.setId(1);
e.setName("Arjun");
System.out.println(e.getId());
System.out.println(e.getName());
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:
For Boolean properties getter method name can be prefixed with either "get" or "is". But
recommended to use "is".
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.
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:
Disadvantages of JavaBean
o Creating the setter and getter method for each property separately may lead to the
boilerplate code.
9. Reusability: JavaBeans are designed with reusability in mind. Once a bean is created, it can
be used across different applications. It allows developers to build upon existing components
rather than starting from scratch, significantly speeding up the development process.
10. Encapsulation: JavaBeans encapsulate many objects into one, hiding the internal complexity
of individual components from other parts of the program. Encapsulation helps in managing
complexity by exposing only necessary parts of the functionality.
11. Ease of Use: It can be manipulated visually in a builder tool. Most IDEs support JavaBeans by
providing features like dragging and dropping beans into applications, which makes it easier
for non-programmers or developers to build applications.
12. Integration and Flexibility: JavaBeans can be integrated into different environments and can
communicate with other components provided these components adhere to the Beans'
conventions. This flexibility also extends to their capability to operate across different
operating systems and platforms.
13. Customization: JavaBeans can be customized easily using property editors and customizers.
It allows other developers and software tools to configure a bean to fit their specific
environment.
14. Persistence: JavaBeans can be made persistent, meaning their state can be saved to and
restored from storage, without the need for the application to understand the beans'
internals. This persistence is facilitated by the Serializable interface.
15. Security: Beans provide a security framework that supports features like signing, constraints,
and role-based authorization, which can be critical for applications that require high security.
16. Interoperability: Since JavaBeans components are written in Java, they are inherently
interoperable with Java applications. However, with appropriate adapters, JavaBeans can
also be made to work with components written in other languages, promoting cross-
platform interaction.
1. Instantiation
The first stage in the life cycle of a JavaBean is instantiation. During this stage, the JavaBean is
created, usually by calling a no-argument constructor. It is a simple creation step where the bean is
allocated memory and its initial state is set up.
2. Customization (Optional)
After a bean is instantiated, it may undergo customization. It involves configuring the bean's
properties and other settings to suit specific needs. Customization typically happens in two ways:
o Design Time: Using tools such as IDEs where beans can be configured using property sheets.
o Runtime: Programmatically setting properties through setter methods or configuration files
(XML, JSON, etc.).
JavaBeans can be connected to other beans. It can involve setting up event listeners and event
sources, allowing beans to respond to events triggered by other beans.
5. Activation (Optional)
For beans that are serialized and later restored, the activation stage involves restoring the bean from
its serialized state.
6. Introspection
Introspection is a process where the capabilities of a bean are examined dynamically. Tools and
frameworks can inspect a bean to determine its properties, events, and methods.
7. Running
During this stage, the bean is in use and performing its intended tasks. It may handle data processing,
respond to user input, or interact with other components and beans.
8. Passivation (Optional)
In environments where beans are managed (like EJB containers), passivation is a stage where a
bean's state is temporarily stored to free resources.
9. Destruction
The final stage in the lifecycle of a JavaBean is its destruction. Here, the bean is marked for garbage
collection, and any resources it used are released. Before destruction, cleanup methods can be called
to ensure that all resources are freed properly, such as closing database connections or releasing file
handles.
Types of EJB
EJB is an acronym for Enterprise Java Beans. It is a server-side software element. It encapsulates the
business logic of an application. It is a specification for developing a distributed business application
on the Java platform.
There are three types of EJBs: Session Bean, Entity Bean, and Message-Driven Bean. In this section,
we will discuss all types of EJB in detail.
Session Bean
The bean sprout business idea that can be systematically used by customer, remote, and web service.
When a client wants to use an application distributed on a server, then the client uses session bean
methods. This session bean provides services to customers, protecting them from complex problems
by performing business operations within the server.
To get to an application that is conveyed to the worker, the client summons the meeting bean's
strategies. The meeting bean performs work for its client, safeguarding it from intricacy by executing
business errands inside the worker. Remember that session beans are not persistence.
To improve execution, we may choose a stateless session bean in the event that it has any of these
characteristics.
o The state of the bean has no information or data for a particular client.
o In a private method invocation, the bean performs a generic task for all clients.
The state is held for the span of the client/bean session. In case if the client eliminates the bean, the
session closes and the state is omitted. This transient nature of the state isn't an issue, because the
interaction between the client and the beans ends. So, it is not required to hold the state.
Stateful session beans should be used, if any of the following conditions are valid:
o The bean's state denotes the alliance between the bean and a particular client.
o The bean needs to hold data about the customer across method invocations.
o The bean interferes between the customer and different segments of the application,
introducing an improved visible to the client.
o In the background, the bean deals with the workstream of a few enterprise beans.
From that pool, any of the session beans may respond to the client. We can implement it in the web-
service endpoints. It takes care of the state but does not hold the state if unexpected crashes or
shutdown occur. It can be used if we want to perform cleanup tasks on closing the application or shut
down as well. It is because it operates throughout the life cycle of the application.
Singleton session beans are suitable for the following conditions:
o The application needs an enterprise bean to perform undertakings upon application startup
and shutdown.
Entity Bean
An entity bean is an unpredictable business substance. It models a business substance or models
different activities inside a business interaction. It is used to encourage business benefits that include
data and calculations on that data. It can deal with various, needy, diligent articles in playing out its
essential assignments. A substance bean is a far-off object that oversees steady information and
performs complex business rationale. It can be extraordinarily distinguished by an essential key.
It is a far-off object that oversees steady information, performs complex business rationale, possibly
utilizes a few ward Java protests, and can be remarkably distinguished by an essential key. It
ordinarily coarse-grained determined items since they use steady information put away inside a few
fine-grained relentless Java objects. Element beans are diligent on the grounds that they do endure a
worker crash or an organization's disappointment.
Every entity bean has a persistence identity that is associated with it. It means that it comprises a
unique identity that can be fetched if we have a primary key. The type for the unique key is defined
by the bean provider. A client can retrieve the entity bean if the primary has been misplaced. If the
bean is not available, the EJB container first, instantiates the bean and then re-populates the data for
the client.
The diligence for entity bean information is given both to saving state when the bean is passivated
and for improving the state when a failover has detected. It can endure in light of the fact that the
information is put away determinedly by the holder in some type of information stockpiling
framework, like a data set.
Entity beans persist business data by using the following two methods:
Container-Managed Persistence
In container-managed persistence, the EJB container transparently and implicitly handles the
relationship between the bean and the database. Bean developers focus on the data and the
business process. The principal constraint is that the EJB compartment can most likely not produce
information base access articulations with the proficiency of a programmer.
o Runtime Environment: A CMP runtime environment that uses the mapping information to
perform persistence operations on each bean.
Message-Driven Bean (MDB)
MDB is a Java Messaging Service (message listener). It consumes messages from a queue or
subscription of a topic. It provides an easy way to create or implement asynchronous communication
using a JMS message listener. An advantage of using MDB is that it allows us to use the asynchronous
nature of a JMS listener. We can implement message-driven beans with Oracle JMS (Java Messaging
Service).
There is an EJB container (contains MDBs pool) that handles the JMS queue and topic. Each incoming
message is handled by a bean that is invoked by the container. Note that no object invokes an MDB
directly. All invocation for MDB originates from the container. When the container invokes the MDB,
it can invoke other EJBs or Java objects to continue the request.
It is quite similar to stateless session bean. Because it does not save informal state, also used to
handle multiple incoming requests.
EJB has the following benefits over the JMS are as follows:
o It creates a consumer for the listener. It means that the container
creates QueueReceiver or TopicSubscriber is created by the container.
o MDB is registered with the consumer. It means that at deployment time QueueReceiver,
TopicSubscriber, and its factory are registered by the container.
o MDB creates and opens a JMS connection to the database by using the data source (JMS
resource provider). The JDBC driver is used to facilitate the JMS connection.
o If any message for the MDB is routed to the onMessage() method of the MDB from the
queue o topic. Other clients may also access the same queue and topic to put the message
for the MDB.
What is Node.js
Node.js is a cross-platform runtime environment and library for running JavaScript applications
outside the browser. It is used for creating server-side and networking web applications. It is open
source and free to use. It can be downloaded from this link https://nodejs.org/en/
Many of the basic modules of Node.js are written in JavaScript. Node.js is mostly used to run real-
time server applications.
?Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and scalable
network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight
and efficient, perfect for data-intensive real-time applications that run across distributed devices.?
Node.js also provides a rich library of various JavaScript modules to simplify the development of web
applications.
Following is a list of some important features of Node.js that makes it the first choice of software
architects.
8. Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, so its library is very
fast in code execution.
9. I/O is Asynchronous and Event Driven: All APIs of Node.js library are asynchronous i.e. non-
blocking. So a Node.js based server never waits for an API to return data. The server moves
to the next API after calling it and a notification mechanism of Events of Node.js helps the
server to get a response from the previous API call. It is also a reason that it is very fast.
10. Single threaded: Node.js follows a single threaded model with event looping.
11. Highly Scalable: Node.js is highly scalable because event mechanism helps the server to
respond in a non-blocking way.
12. No buffering: Node.js cuts down the overall processing time while uploading audio and
video files. Node.js applications never buffer any data. These applications simply output the
data in chunks.
13. Open source: Node.js has an open source community which has produced many excellent
modules to add additional capabilities to Node.js applications.
Text Editor:
The text editor is used to type your program. For example: Notepad is used in Windows, vim
or vi can be used on Windows as well as Linux or UNIX. The name and version of the text
editor can be different from operating system to operating system.
The files created with text editor are called source files and contain program source code.
The source files for Node.js programs are typically named with the extension ".js".
You can download the latest version of Node.js installable archive file from
https://nodejs.org/en/
2. console.log('Hello JavaTpoint');
2. node console_example1.js
response.end('Hello World\n');
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
So type cd desktop on the command prompt. After that execute the main.js to start the
server as follows:
2. node main.js
Open http://127.0.0.1:8081/ in any browser. You will see the following result.
Node.js Console
The Node.js console module provides a simple debugging console similar to JavaScript
console mechanism provided by web browsers.
There are three console methods that are used to write any node.js stream:
4. console.log()
5. console.error()
6. console.warn()
Node.js console.log()
Node.js REPL
The term REPL stands for Read Eval Print and Loop. It specifies a computer environment like
a window console or a Unix/Linux shell where you can enter the commands and the system
responds with an output in an interactive mode.
REPL Environment
The Node.js or node come bundled with REPL environment. Each part of the REPL
environment has a specific work.
Read: It reads user's input; parse the input into JavaScript data-structure and stores in
memory.
Loop: It loops the above command until user press ctrl-c twice.
You can start REPL by simply running "node" on the command prompt. See this:
You can execute various mathematical operations on REPL Node.js command prompt:
After starting REPL node command prompt put any mathematical expression:
3. Example: >10+20-5
4. 25
Variables are used to store values and print later. If you don't use var keyword then value is
stored in the variable and printed whereas if var keyword is used then value is stored but not
printed. You can print variables using console.log().
Example:
Node REPL supports multiline expressions like JavaScript. See the following do-while loop
example:
7. var x = 0
8. undefined
9. > do {
10. ... x++;
Example:
Commands Description
It is used to terminate the current
ctrl + c
command.
o It also provides command line utility to install Node.js packages, do version management and
dependency management of Node.js packages.
The npm comes bundled with Node.js installables in versions after that v0.6.3. You can check
the version by opening Node.js command prompt and typing the following command:
2. npm version
Open the Node.js command prompt and execute the following command:
You can see the result after installing the "express" framework.
By default, npm installs dependency in local mode. Here local mode specifies the folder
where Node application is present. For example if you installed express module, it created
node_modules directory in the current directory where it installed express module.
You can use npm ls command to list down all the locally installed modules.
Uninstalling a Module
2. npm ls
Searching a Module
There is a wide variety of command line options in Node.js. These options provide multiple
ways to execute scripts and other helpful run-time options.
It is used to print
1. v, --version
node's version.
It is used to print
2. -h, --help node command
line options.
It evaluates the
following argument
as JavaScript. The
3. -e, --eval "script" modules which are
predefined in the
REPL can also be
used in script.
It is identical to -e
4. -p, --print "script" but prints the
result.
It is used to
preload the
specified module
at startup. It
-r, --require follows require()'s
7.
module module resolution
rules. Module may
be either a path to
a file, or a node
module name.
Silence
8. --no-deprecation deprecation
warnings.
It is used to print
9. --trace-deprecation stack traces for
deprecations.
It silence all
process warnings
11. --no-warnings
(including
deprecations).
It prints a stack
trace whenever
synchronous i/o is
13. --trace-sync-io
detected after the
first turn of the
event loop.
Automatically zero-
fills all newly
14. --zero-fill-buffers allocated buffer
and slowbuffer
instances.
It tracks heap
--track-heap- object allocations
15.
objects for heap
snapshots.
It processes V8
profiler output
16. --prof-process generated using
the v8 option --
prof.
It prints V8
17. --V8-options command line
options.
It specifies an
alternative default
tls cipher list.
18. --tls-cipher-list=list (requires node.js to
be built with
crypto support.
(default))
It enables fips-
19. --enable-fips compliant crypto at
startup. (requires
node.js to be built
with ./configure --
openssl-fips)
It forces fips-
compliant crypto
on startup. (cannot
20. --force-fips be disabled from
script code.) (same
requirements as --
enable-fips)
It specifies ICU
data load path.
21. --icu-data-dir=file
(Overrides
node_icu_data)
Open Node.js command prompt and run command node -v or node --version
For Help:
o __dirname
o __filename
o Console
o Process
o Buffer
o clearImmediate(immediateObject)
o clearInterval(intervalObject)
o clearTimeout(timeoutObject)
Node.js __dirname
It is a string. It specifies the name of the directory that currently contains the code.
File: global-example1.js
2. console.log(__dirname);
2. node global-example1.js
Node.js __filename
It specifies the filename of the code being executed. This is the resolved absolute path of this
code file. The value inside a module is the path to that module file.
File: global-example2.js
2. console.log(__filename);
2. node global-example2.js
Node.js Callbacks
Callback is an asynchronous equivalent for a function. It is called at the completion of each
task. In Node.js, callbacks are generally used. All APIs of Node are written in a way to
supports callbacks. For example: when a function start reading file, it returns the control to
execution environment immediately so that the next instruction can be executed.
In Node.js, once file I/O is complete, it will call the callback function. So there is no blocking
or wait for File I/O. This makes Node.js highly scalable, as it can process high number of
request without waiting for any function to return result.
3. console.log(data.toString());
4. console.log("Program Ended");
6. Open the Node.js command prompt and execute the following code.
1. node main.js
1. var fs = require("fs");
2.
5. console.log(data.toString());
6. });
7. console.log("Program Ended");
6. Open the Node.js command prompt and execute the following code.
1. node main.js
Node.js Events
In Node.js applications, Events and Callbacks concepts are used to provide concurrency. As
Node.js applications are single threaded and every API of Node js are asynchronous. So it
uses async function to maintain the concurrency. Node uses observer pattern. Node thread
keeps an event loop and after the completion of any task, it fires the corresponding event
which signals the event listener function to get executed.
Node.js uses event driven programming. It means as soon as Node starts its server, it simply
initiates its variables, declares functions and then simply waits for event to occur. It is the
one of the reason why Node.js is pretty fast compared to other similar technologies.
There is a main loop in the event driven application that listens for events, and then triggers
a callback function when one of those events is detected.
Difference between Events and Callbacks:
Although, Events and Callbacks look similar but the differences lies in the fact that callback
functions are called when an asynchronous function returns its result where as event
handling works on the observer pattern. Whenever an event gets fired, its listener function
starts executing. Node.js has multiple in-built events available through events module and
EventEmitter class which is used to bind events and event listeners.
4. eventEmitter.on('eventName', eventHandler);
To fire an event:
3. // Fire an event
4. eventEmitter.emit('eventName');
File: main.js
27.
28. // Create an event handler as follows
31.
33. eventEmitter.emit('data_received');
34. }
35.
41. });
43. eventEmitter.emit('connection');
Now, open the Node.js command prompt and run the following code:
2. node main.js
MONGO-DB
Node.js Create Connection with MongoDB
To create a database in MongoDB, First create a MongoClient object and specify a connection URL
with the correct ip address and the name of the database which you want to create.
Note: MongoDB will automatically create the database if it does not exist, and make a connection to
it.
Example
Create a folder named "MongoDatabase" as a database. Suppose you create it on Desktop. Create a
js file named "createdatabase.js" within that folder and having the following code:
console.log("Database created!");
db.close();
});
Now open the command terminal and set the path where MongoDatabase exists. Now execute the
following command:
2. Node createdatabase.js
Example
18. db.close();
19. });
20. });
2. Node employees.js
The insertOne method is used to insert record in MongoDB's collection. The first argument of the
insertOne method is an object which contains the name and value of each field in the record you
want to insert.
Example
db.close();
});
});
2. Node insert.js
You can insert multiple records in a collection by using insert() method. The insert() method uses
array of objects which contain the data you want to insert.
Example
var myobj = [
];
db.close();
});
});
The findOne() method is used to select a single data from a collection in MongoDB. This method
returns the first record of the collection.
Example
console.log(result.name);
db.close();
});
});
2. Node select.js
The find() method is used to select all the records from collection in MongoDB.
Example
Select all the records from "employees" collection.
db.collection("employees").find({}).toArray(function(err, result) {
console.log(result);
db.close();
});
});
2. Node selectall.js
The find() method is also used to filter the result on a specific parameter. You can filter the result by
using a query object.
Example
Filter the records to retrieve the specific employee whose address is "Delhi".
Create a js file named "query1.js", having the following code:
db.collection("employees").find(query).toArray(function(err, result) {
console.log(result);
db.close();
});
});
2. Node query1.js
You can also use regular expression to find exactly what you want to search. Regular expressions can
be used only to query strings.
Example
Retrieve the record from the collection where address start with letter "L".
console.log(result);
db.close();
});
});
2. Node query2.js
6. { name: 1 }
8. { name: -1 }
Example
db.collection("employees").find().sort(mysort).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
2. Node sortasc.js
Example
db.collection("employees").find().sort(mysort).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
2. Node sortdsc.js
In MongoDB, you can delete records or documents by using the remove() method. The first
parameter of the remove() method is a query object which specifies the document to delete.
Example
db.close();
});
});
2. Node remove.js
Verification
You can check that the record having address "Ghaziabad" is deleted and only following records are
available now: