WT Unit 4
WT Unit 4
A Java Bean is a reusable software component that follows certain conventions in the Java
programming language. It is a class that encapsulates multiple objects into a single object (a
bean). Java Beans can be used in a variety of contexts, such as GUI components, business logic,
or enterprise applications. They are particularly useful for representing data and for enabling
the separation of concerns in software design.
To be considered a Java Bean, a class must adhere to the following simple conventions:
1. Private Member Variables: The fields (attributes) of a Java Bean should be private to
promote encapsulation.
2. Public Constructors: It must have a no-argument constructor, which allows easy
instantiation of the Bean.
3. Getter and Setter Methods: It must provide public methods to get and set the values of
its private member variables. These methods are typically called "getters" and "setters"
and are named following a specific pattern.
4. Serializable: A Java Bean must implement the Serializable interface to support
persistence and allow it to be easily transferred over networks or saved to a file.
Java Beans are typically used in Java-based frameworks like Java EE, Spring, and JavaFX where
the beans can be managed and interacted with in various ways.
Java Bean Properties
Java Bean properties are the fields or attributes of a Java Bean class. These properties are
generally encapsulated by private instance variables, and access to them is provided through
getter and setter methods. The properties allow the encapsulation of data and the flexibility of
controlling how the data is accessed or modified.
There are two types of properties in Java Beans:
Simple Properties: These represent a single value (like an int, String, double, boolean, etc.). For
example, a name property in a Person bean.
public class Person{
private String name;
private int age;
public String getName() {
return name; }
public void setName(String name) {
this.name = name;
public int getAge() {
return age; }
public void setAge(int age) {
this.age = age; }}
Indexed Properties: These allow access to a property using an index, usually for handling
collections like arrays or lists within a bean. For example, a Person bean might have a list of
phone numbers.
public class Person implements Serializable {
private List<String> phoneNumbers = new ArrayList<>();
public String getPhoneNumber(int index) {
return phoneNumbers.get(index); }
public void setPhoneNumber(int index, String phoneNumber) {
phoneNumbers.set(index, phoneNumber); }
public int getPhoneNumbersCount() {
return phoneNumbers.size(); }}
In the context of Enterprise JavaBeans (EJBs), there are three primary types of beans: Stateful
Session Beans, Stateless Session Beans, and Entity Beans. Each type serves a different purpose
in enterprise applications, particularly when handling business logic and data persistence.
Below is a detailed explanation of each type:
Stateful Session Bean
A Stateful Session Bean (SFSB) is an EJB that maintains the state of a client across multiple
method invocations. The state is specific to a client and persists for the duration of a session
with that client. This means the server retains the state of the bean for the client between
method calls, allowing the client to interact with the bean in a way that the bean "remembers"
previous interactions.
Client-Specific State: A Stateful Session Bean stores state information between method
invocations for a specific client.
Lifecycle: The bean exists for the duration of the client’s session. It is created when the client
first interacts with it and destroyed when the session ends (either through explicit removal or
timeout).
Serialization: The state of a Stateful Session Bean is often serialized when it is moved between
servers or stored for persistence purposes.
@Stateful
public class ShoppingCartBean implements ShoppingCartRemote {
private List<String> items = new ArrayList<>();
@Override
public void addItem(String item) {
items.add(item); }
@Override
public List<String> getItems() {
return items; }
@Override
public void checkout() {
// Checkout process
items.clear();
}}
Stateless Session Bean
A Stateless Session Bean (SLSB) is an EJB that does not maintain any client-specific state. Each
method invocation is independent, and the bean can be used by multiple clients without
retaining any information between method calls. A Stateless Session Bean can serve any client,
and it does not remember previous interactions.
No Client-Specific State: Stateless Session Beans do not hold any state information between
method calls. Each call to the bean is independent.
Lifecycle: Stateless beans do not have a specific client session. They are created and destroyed
by the container as needed to serve incoming requests. The container may pool instances of
Stateless Beans for reuse.
@Stateless
public class AccountServiceBean implements AccountServiceRemote {
@Override
public void transferMoney(Account from, Account to, double amount) {
from.withdraw(amount);
to.deposit(amount); }}
Entity Bean
An Entity Bean is a type of EJB that represents persistent data, typically mapped to a row in a
database table. Entity Beans are used to interact with databases in a Java EE application. They
allow an object-oriented way to model and manage database records.
public class ProductBean {
private String productId;
private String name;
private double price;
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductId() {
return productId;
}
// Persistence logic...
}
Enterprise JavaBeans (EJBs) are server-side components that are part of the Jakarta EE
(formerly Java EE) specification. They provide a simplified model for building distributed,
transactional, and multi-user enterprise applications. EJBs manage business logic and handle
things like security, transactions, concurrency, and messaging.
@Stateful
public class ShoppingCartBean implements ShoppingCartRemote {
private List<String> items = new ArrayList<>();
@Override
public void addItem(String item) {
items.add(item); }
@Override
public List<String> getItems() {
return items; }
@Override
public void checkout() {
// Process checkout logic
items.clear(); }}
Message-Driven Bean (MDB)
A Message-Driven Bean is used for asynchronous message processing. It listens to a message
queue (e.g., JMS) and processes messages asynchronously.
While an I/O operation is being performed, Node.js doesn’t block the execution of other tasks.
Instead, it registers the callback function to handle the result of the operation once it
completes, enabling asynchronous processing.
Environment Setup for Node.js Development
Setting up a development environment for Node.js is a crucial step to get started with building
applications using Node.js. This process involves installing the necessary software, setting up
development tools, and configuring your system for optimal productivity.
Before you begin setting up Node.js on your machine, ensure the following prerequisites are
met:
Installing Node.js
Node.js can be installed on all major operating systems, including Windows, macOS, and Linux.
node -v
npm -v
o These commands will display the installed versions of Node.js and npm,
confirming the successful installation.
REPL Terminal
A REPL (Read-Eval-Print-Loop) terminal in Node.js is an interactive environment that allows
developers to run JavaScript code directly in the terminal. It provides a way to test snippets of
code, debug, and experiment with functions, objects, and expressions in real-time without
needing to create a file or execute a script.
Read: It reads the input from the user (JavaScript code).
Eval: It evaluates the input and executes the JavaScript code.
Print: It prints the result of the evaluation to the terminal.
Loop: It loops back to read the next input after showing the result.
To start the REPL terminal, simply run the command node in your terminal. The REPL
environment will open, and you can start typing JavaScript code directly.
$ node
> let x = 5
>x+2
7
You can exit the REPL by typing .exit or pressing Ctrl+C twice.
Instant feedback: Test small pieces of code quickly.
Debugging: Useful for testing functions, libraries, or debugging issues.
Learning tool: Ideal for beginners to experiment with JavaScript syntax and concepts.
Node.js REPL is a powerful tool for rapid development and exploration of JavaScript code.
Use Variables
You can make use variables to store values and print later like any conventional script. If var
keyword is not used 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 usind console.log.
Multiline Expression
Node REPL supports multiline expression similar to JavaScript. Let's check the following do-
while
loop in action:
$ node
> var x = 0
undefined
> do {
... x++;
... console.log("x: " + x);
... } while ( x < 5 );
x: 1
x: 2
x: 3
x: 4
x: 5
undefined
>
REPL Commands
ctrl + c - terminate the current command.
ctrl + c twice - terminate the Node REPL.
ctrl + d - terminate the Node REPL.
Up/Down Keys - see command history and modify previous commands.
tab Keys - list of current commands.
.help - list of all commands.
.break - exit from multiline expression.
.clear - exit from multiline expression
.save filename - save current Node REPL session to a file.
.load filename - load file content in current Node REPL session.
WHAT IS NPM?
npm (Node Package Manager) is a popular package manager for JavaScript programming
developers. It was initially released in 2010, and is automatically installed by default whenever
you install Node.js on your system.
Node Package Manager npm provides following two main functionalities:
Attributes of Package.json
Callback Concept: A Callback is a function that is called automatically when a particular task
is completed. The Callback function allows the program to run other code until a certain
task is not completed. The callback function is heavily used in nodeJS. The callback function
allows you to perform a large number of I/O operations that can be handled by your OS
without waiting for any I/O operation to finish. It makes nodeJS highly scalable.
For example: In Node.js, when a function starts reading a file, It’s obviously going to take
some time so without waiting for that function to complete, it returns control to the
execution environment immediately an executes the succeeding instruction. Once file I/O
gets completed, the callback function will be automatically called hence there will be no
waiting or blocking for file I/O.
Note: The callback function is being replaced by async/await these days.
Syntax: Let’s see the syntax of the callback function.
const fs = require("fs");
fs.readFile("file_path", "utf8", function (err, data) {
if (err) {
// Handle the error
} else {
// Process the file text given with data
}
});
Events
Each action on the computer is called an event. In nodeJS objects can fire events. According
to the official documentation of Node.js, it is an asynchronous event-driven JavaScript
runtime. Node.js has an event-driven architecture that can perform asynchronous tasks.
Node.js has an ‘events’ module that emits named events that can cause corresponding
functions or callbacks to be called. Functions(Callbacks) listen or subscribe to a particular
event to occur and when that event triggers, all the callbacks subscribed to that event are
fired one by one in order to which they were registered.
The EventEmmitter class: All objects that emit events are instances of the EventEmitter
class. The event can be emitted or listened to an event with the help of EventEmitter.
Syntax:
const EventEmitter=require('events');
var eventEmitter=new EventEmitter();
The following table lists all the important methods of the EventEmitter class:
Node.js – Packaging
A large-sized Node.js project usually has a number of dependencies and a number of source
files as well as other assets such as images, web pages, setting files etc. To distribute a
Node.js project and deploy it on any other environment becomes difficult, and hence it
needs to packaged so that it can be easily ported to other machine. There are a number of
packaging tools available on NPM repository.
A package in Node.js contains all the files you need for a module.
Download a Package
Open the command line interface and tell NPM to download the package you want.
Express Framework
Express is a minimal and flexible Node.js web application framework that provides a robust
set of features to develop web and mobile applications. It facilitates a rapid development of
Node based Web applications. Following are some of the core features of Express
framework:
Let's implement our first RESTful API listUsers using the following code in a server.js file:
Now try to access defined API using http://127.0.0.1:8081/listUsers on local machine. This should
produce following result: You can change given IP address when you will put the solution in production
environment.
MongoDB
1. Schema-less Database:
o MongoDB is schema-less, meaning each document in a collection can have a
different structure. This allows for greater flexibility when handling diverse data.
2. Document-Oriented Storage:
o Data in MongoDB is stored in BSON (Binary JSON) format. Each document is a set
of key-value pairs and can contain nested arrays or other documents.
3. Collections:
o Documents are stored in collections, which are analogous to tables in relational
databases. A collection can hold multiple documents.
4. Horizontal Scalability:
o MongoDB supports horizontal scaling through sharding. Data can be distributed
across multiple machines, improving performance and handling large-scale data
storage needs.
5. Indexing:
o MongoDB supports various types of indexes (e.g., single-field, compound,
geospatial, and text indexes), which help in improving query performance.
Node.js is a popular JavaScript runtime that enables building scalable and efficient server-side
applications. MongoDB, a NoSQL database, works seamlessly with Node.js due to its JSON-like
document storage, making it an ideal choice for modern web applications. Using MongoDB with
Node.js allows you to create applications that can store, retrieve, and manipulate data
efficiently.
1. Install MongoDB:
MongoDB can be installed locally or used as a cloud service like MongoDB Atlas.
MongoDB Atlas is a fully-managed cloud service for MongoDB, and it's free for small-scale
applications.
2. Install Dependencies:
You need to install the MongoDB Node.js driver or Mongoose (an Object Data Modeling (ODM)
library for MongoDB and Node.js).
MongoDB Driver:
Create a simple Node.js application that connects to MongoDB and performs CRUD operations.
try {
// Connect to MongoDB
await client.connect();
console.log("Connected to MongoDB!");
const db = client.db(dbName);
// Insert a document
await collection.insertOne(user);
console.log("User inserted");
// Find a document
console.log("User updated");
// Delete a document
console.log("User deleted");
} catch (err) {
console.error(err);
} finally {
await client.close();
main().catch(console.error);
Mongoose is a higher-level abstraction over the MongoDB native driver. It provides a schema-
based solution to model the data and offers built-in validation, hooks, and other helpful
features.
1. Create Database
In MongoDB, a database is created when you first insert data into a collection. You don't
explicitly create a database; it is automatically created when you perform an operation like
inserting a document.
use myDatabase; // Switch to the 'myDatabase' database (if it doesn't exist, MongoDB creates
it).
2. Create Collection
MongoDB automatically creates the users collection when you insert data.
3. Insert
Insert is used to add documents to a collection. MongoDB provides methods like insertOne() and
insertMany() to insert single or multiple documents at once.
db.users.insertMany([{ name: 'Alice', age: 30 }, { name: 'Bob', age: 35 }]); // Insert multiple
documents
db.users.deleteOne({ name: 'John' }); // Deletes the first document that matches the filter
db.users.deleteMany({ age: { $gt: 30 } }); // Deletes all documents where age is greater than 30
Update is used to modify the existing documents in a collection. MongoDB offers updateOne(),
updateMany(), and findAndModify() (deprecated) for updating documents.
MongoDB does not support traditional SQL joins. However, embedding documents or
referencing documents can achieve similar results. Additionally, MongoDB provides the $lookup
aggregation operator to join collections in the aggregation pipeline.
db.orders.aggregate([
{
$lookup: {
from: 'products',
localField: 'product_id',
foreignField: '_id',
as: 'productDetails'
}
}
]);
This performs a left outer join between the orders collection and the products collection,
matching the product_id field from orders with the _id field from products.
7. Sort
Sort is used to arrange the documents in a collection in ascending or descending order based on
a specified field.
Query in MongoDB is used to find documents that match specific conditions. MongoDB supports
a rich set of query operators like $gt, $lt, $eq, $in, etc.