Preparatory Notes_ FSW
Preparatory Notes_ FSW
1. Java Networking
Java networking enables communication between devices and applications over a network. It
allows the exchange of data using standard protocols. Here’s a breakdown of the key
components and classes involved in Java Networking:
Sockets are endpoints for communication between two machines. Java provides the Socket
and ServerSocket classes for implementing client-server communication.
Key Classes:
1. Server-Side:
○ Create a ServerSocket object.
○ Wait for a connection using accept().
○ Communicate with the client via input/output streams.
2. Client-Side:
○ Create a Socket object to connect to the server.
○ Use input/output streams for communication.
java
Copy code
import java.io.*;
import java.net.*;
socket.close();
serverSocket.close();
}
}
Client Code:
java
Copy code
import java.io.*;
import java.net.*;
socket.close();
}
}
The URL class in Java represents a Uniform Resource Locator, which is used to locate
resources on the internet.
Usage:
java
Copy code
import java.net.*;
● Protocol: https
● Host: www.example.com
● Port: 80
● File: /index.html?query=java
● Reference: section
The URLConnection class represents a connection to a URL. It can be used to read/write data
to/from a URL.
Example:
java
Copy code
import java.io.*;
import java.net.*;
1.5 HttpURLConnection
java
Copy code
import java.io.*;
import java.net.*;
Methods:
Example:
java
Copy code
import java.net.*;
This class is used for sending and receiving data packets using the UDP protocol. UDP is faster
but less reliable compared to TCP.
Example: Server:
java
Copy code
import java.net.*;
serverSocket.close();
}
}
Client:
java
Copy code
import java.net.*;
clientSocket.close();
}
}
RMI is a mechanism in Java that allows objects to communicate and invoke methods remotely.
This is especially useful for distributed applications.
RMI enables Java objects to communicate and invoke methods on remote objects over a
network, allowing distributed applications to run seamlessly. It abstracts the complexity of
communication between JVMs.
1. Remote Interface:
○ Defines the methods that can be invoked remotely.
○ It extends java.rmi.Remote.
○ All methods must declare throws RemoteException.
2. Remote Object:
○ Implements the remote interface.
○ Defines the behavior for the methods.
3. Stub and Skeleton:
○ Stub: Client-side proxy for the remote object that forwards the method calls to
the server.
○ Skeleton: Server-side helper (used in Java versions prior to 1.5) that dispatches
the request to the actual remote object.
4. RMI Registry:
○ A naming service that allows clients to look up remote objects.
5. RMI Server and Client:
○ Server: Registers the remote object with the RMI registry.
○ Client: Looks up the object in the RMI registry and invokes methods.
The remote interface declares the methods that can be invoked remotely.
Example:
java
Copy code
import java.rmi.Remote;
import java.rmi.RemoteException;
Example:
java
Copy code
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
@Override
public int add(int a, int b) throws RemoteException {
return a + b;
}
@Override
public int subtract(int a, int b) throws RemoteException {
return a - b;
}
}
Step 3: Create the RMI Server
The server program creates an instance of the remote object and registers it with the RMI
registry.
Example:
java
Copy code
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
The client program looks up the remote object and invokes methods on it.
Example:
java
Copy code
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
1.
Generate the stub file (only needed for Java versions < 1.5):
bash
Copy code
rmic CalculatorImpl
2.
3.
4.
5.
RMI can be extended to access a database. For example, you can create a remote interface for
querying data from a database.
java
Copy code
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;
Example Implementation:
java
Copy code
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
@Override
public List<String> getData() throws RemoteException {
List<String> data = new ArrayList<>();
data.add("Record 1");
data.add("Record 2");
return data;
}
}
Summary
RMI is a powerful feature of Java for developing distributed systems, allowing remote method
calls between JVMs. With RMI, you can easily build applications that communicate over a
network while keeping the complexity of underlying protocols hidden.
3. JavaFX
JavaFX is a powerful framework for building rich, modern, and visually appealing desktop
applications. It provides a wide range of tools and libraries for GUI (Graphical User Interface)
development.
3.1 Introduction
JavaFX is the successor to Swing, providing a more modern and flexible platform for GUI
development. It uses:
● FXML: An XML-based markup language to design UI.
● CSS: To style applications, similar to web development.
● Scene Graph: A hierarchical tree of nodes (UI components) for building the GUI.
1. Stage:
○ Represents the top-level container (window).
○ Created by the JavaFX runtime when the application starts.
2. Scene:
○ Represents the content inside the stage.
○ Contains a tree of nodes (Scene Graph).
3. Nodes:
○ The building blocks of JavaFX applications (e.g., buttons, text fields, shapes).
4. Event Handling:
○ Mechanism to respond to user actions like button clicks or mouse events.
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
3.4 2D Shapes
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
3.5 Transformations
Example:
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
// Apply transformations
rectangle.setRotate(45); // Rotates by 45 degrees
3.6 Animation
JavaFX provides built-in support for animations to create dynamic and visually appealing
interfaces. Examples include:
java
Copy code
import javafx.animation.FadeTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
JavaFX supports multimedia (audio and video) playback using the Media and MediaPlayer
classes.
Example:
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
Event handling in JavaFX is based on the Event-Driven Programming model. Commonly used
event classes:
Example:
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
4. Java Struts
Java Struts is a popular open-source framework used for building Java-based web applications.
It follows the MVC (Model-View-Controller) architecture, which separates the application logic
into three interconnected components, making it easier to maintain and scale.
Struts is built on top of Servlets and JSP (JavaServer Pages) and provides a robust framework
to manage user input, process business logic, and display the output in a structured way.
1. MVC Architecture:
○ Separates application into:
■ Model: Represents the application's data and business logic.
■ View: Handles presentation (e.g., JSP pages).
■ Controller: Manages user requests and responses (e.g., Action classes).
2. Action Classes:
○ Encapsulates business logic.
○ Processes user requests.
3. Tag Libraries:
○ Simplify JSP coding with pre-defined tags for HTML forms, data display, etc.
4. Validation Framework:
○ Provides built-in support for validating user inputs.
5. Extensibility:
○ Developers can extend Struts' classes and functionality as needed.
6. Integration:
○ Easily integrates with other frameworks like Hibernate and Spring.
1. Controller (ActionServlet):
○ A core component of Struts that handles incoming requests.
○ Maps requests to appropriate Action classes.
2. Action Classes:
○ Represent business logic.
○ Use helper classes to interact with the model layer.
3. Model:
○ Represents the application's data.
○ Can integrate with databases or external APIs.
4. View:
○ The user interface built using JSP or other presentation technologies.
Workflow of Struts:
1. ActionServlet:
○ Main controller that routes HTTP requests to appropriate Action classes.
○ Defined in the web.xml file.
Example (web.xml):
xml
Copy code
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
2.
3. struts-config.xml:
○ Central configuration file for Struts.
○ Maps user requests to Action classes and specifies forward navigation.
Example (struts-config.xml):
xml
Copy code
<action-mappings>
<action path="/login"
type="com.example.LoginAction"
name="loginForm"
scope="request"
validate="true">
<forward name="success" path="/welcome.jsp" />
<forward name="failure" path="/login.jsp" />
</action>
</action-mappings>
4.
5. ActionForm:
○ Represents the form data submitted by the user.
○ Populates Action classes with the submitted data.
Example:
java
Copy code
public class LoginForm extends ActionForm {
private String username;
private String password;
6.
7. Action Classes:
○ Handle user requests and business logic.
Example:
java
Copy code
public class LoginAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm
form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
LoginForm loginForm = (LoginForm) form;
if ("admin".equals(loginForm.getUsername()) &&
"password".equals(loginForm.getPassword())) {
return mapping.findForward("success");
} else {
return mapping.findForward("failure");
}
}
}
8.
9. Tag Libraries:
○ Provides reusable components for JSP.
○ Common tags:
■ <html:form>: Creates a form.
■ <html:text>: Creates a text field.
■ <html:submit>: Creates a submit button.
Example JSP:
jsp
Copy code
<html:form action="/login">
Username: <html:text property="username" /><br>
Password: <html:password property="password" /><br>
<html:submit value="Login" />
</html:form>
10.
4.5 Interceptors
1. Custom Interceptor:
○ Used to execute logic before or after the Action class executes.
2.
3. Built-in Interceptors:
○ File Upload: Handles file uploads.
○ Exception Handling: Captures exceptions and processes them.
Struts provides a built-in validation framework for form data. You can define validation rules in
an XML file or directly in the ActionForm class.
xml
Copy code
<form-beans>
<form-bean name="loginForm" type="com.example.LoginForm" />
</form-beans>
<form-validation>
<formset>
<form name="loginForm">
<field property="username" depends="required">
<arg0 key="error.username.required" />
</field>
<field property="password" depends="required">
<arg0 key="error.password.required" />
</field>
</form>
</formset>
</form-validation>
Summary
Struts is a robust framework for building scalable and maintainable web applications using Java.
Its MVC architecture, validation framework, and integration capabilities make it ideal for
enterprise-level projects.
5. Bundled Validation
In frameworks like Java Struts, bundled validation provides out-of-the-box validators that can
be easily integrated into your application.
5.1 Introduction
Validation ensures that user input matches the expected format or criteria before processing it.
Bundled validation saves time by offering pre-implemented validators for common input types
like:
● Strings
● Numbers
● Dates
● Emails
● URLs
● Regular expressions (Regex)
1. StringLength Validator:
○ Ensures that a string has a minimum and/or maximum length.
○ Commonly used for validating names, usernames, etc.
Example Configuration:
xml
Copy code
<field property="username" depends="required,stringlength">
<arg0 key="error.username.length" />
<var>
<var-name>minlength</var-name>
<var-value>5</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<var-value>15</var-value>
</var>
</field>
2.
3. Email Validator:
○ Ensures that input is a valid email address format.
Example Configuration:
xml
Copy code
<field property="email" depends="required,email">
<arg0 key="error.email.invalid" />
</field>
4.
5. Date Validator:
○ Ensures that the input is a valid date and optionally within a certain range.
Example Configuration:
xml
Copy code
<field property="birthDate" depends="required,date">
<arg0 key="error.birthDate.invalid" />
</field>
6.
7. URL Validator:
○ Ensures that the input is a valid URL format.
Example Configuration:
xml
Copy code
<field property="website" depends="url">
<arg0 key="error.website.invalid" />
</field>
8.
9. Regex Validator:
○ Validates input against a regular expression.
Example Configuration:
xml
Copy code
<field property="zipcode" depends="mask">
<arg0 key="error.zipcode.invalid" />
<var>
<var-name>mask</var-name>
<var-value>^[0-9]{5}(?:-[0-9]{4})?$</var-value>
</var>
</field>
10.
11. Int/Double Validator:
○ Ensures that the input is a valid integer or decimal number.
Example Configuration:
xml
Copy code
<field property="age" depends="int">
<arg0 key="error.age.invalid" />
</field>
12.
While bundled validators handle common cases, some applications may require custom
validation logic. Struts allows developers to create their own validators.
java
Copy code
public class CustomValidationForm extends ValidatorForm {
private String username;
@Override
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
1. Validation.xml:
○ Central file for defining validation rules for ActionForms.
○ Includes bundled validators and their configurations.
Example:
xml
Copy code
<form-validation>
<formset>
<form name="userForm">
<field property="email" depends="required,email">
<arg0 key="error.email.invalid" />
</field>
<field property="age" depends="int">
<arg0 key="error.age.invalid" />
</field>
</form>
</formset>
</form-validation>
2.
3. Application Resource File:
○ Contains error messages associated with validation.
Example:
properties
Copy code
error.username.length=Username must be between 5 and 15 characters.
error.email.invalid=Please enter a valid email address.
error.age.invalid=Age must be a valid number.
4.
struts-config.xml:
xml
Copy code
<action-mappings>
<action path="/login"
type="com.example.LoginAction"
name="loginForm"
scope="request"
validate="true">
<forward name="success" path="/welcome.jsp" />
<forward name="failure" path="/login.jsp" />
</action>
</action-mappings>
Validation.xml:
xml
Copy code
<form-validation>
<formset>
<form name="loginForm">
<field property="username"
depends="required,stringlength">
<arg0 key="error.username.length" />
<var>
<var-name>minlength</var-name>
<var-value>5</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<var-value>15</var-value>
</var>
</field>
<field property="email" depends="required,email">
<arg0 key="error.email.invalid" />
</field>
<field property="age" depends="int">
<arg0 key="error.age.invalid" />
</field>
</form>
</formset>
</form-validation>
properties
Copy code
error.username.length=Username must be between 5 and 15 characters.
error.email.invalid=Invalid email format.
error.age.invalid=Age must be a number.
Summary
Bundled validation in frameworks like Struts simplifies input validation by providing reusable and
standardized validators. These validators help maintain consistent and error-free user input
while allowing customization for unique requirements.
6. AngularJS
AngularJS extends HTML by adding custom tags and attributes, enabling the creation of
interactive and dynamic web interfaces. It integrates seamlessly with RESTful APIs and
promotes a clean MVC architecture for structuring applications.
1. Two-Way Data Binding: Automatically synchronizes data between the model and the
view.
2. Dependency Injection (DI): Provides a mechanism to inject dependencies into
components, making the application more modular and testable.
3. Directives: Custom HTML attributes that define behavior or structure in the DOM.
4. Filters: Transform data for display in views.
5. Routing: Facilitates SPA development by loading views dynamically based on URL
changes.
1. Modules:
○ Containers for different parts of an application (e.g., controllers, services, filters).
○ Defined using angular.module.
Example:
javascript
Copy code
var app = angular.module('myApp', []);
2.
3. Controllers:
○ JavaScript functions that define the business logic for a specific view.
○ Attached to HTML elements using the ng-controller directive.
Example:
javascript
Copy code
app.controller('myCtrl', function($scope) {
$scope.greeting = "Hello, AngularJS!";
});
HTML:
html
Copy code
<div ng-controller="myCtrl">
{{greeting}}
</div>
4.
5. Directives:
○ Special markers in the DOM that AngularJS uses to attach behavior.
○ Examples:
■ ng-model: Binds input values to the model.
■ ng-repeat: Repeats elements for each item in a collection.
■ ng-click: Binds click events to functions.
Example:
html
Copy code
<input ng-model="name">
<p>Hello, {{name}}</p>
6.
7. Filters:
○ Used to format data displayed in the view.
○ Examples:
■ currency: Formats numbers as currency.
■ uppercase: Converts text to uppercase.
■ date: Formats dates.
Example:
html
Copy code
<p>{{price | currency}}</p>
8.
9. Services:
○ Singleton objects responsible for managing data and reusable functionality.
○ Examples:
■ $http: For making HTTP requests.
■ $timeout: For delays.
■ $routeParams: For routing.
Example Service:
javascript
Copy code
app.service('myService', function() {
this.sayHello = function(name) {
return "Hello, " + name + "!";
};
});
10.
Two-way data binding ensures that changes in the model reflect automatically in the view and
vice versa.
Example:
html
Copy code
<div ng-controller="myCtrl">
<input ng-model="message">
<p>You typed: {{message}}</p>
</div>
Here, the value typed into the input field updates message in the model, and the paragraph
content reflects these changes in real-time.
Directives are the building blocks of AngularJS and can be used to create dynamic, reusable
components.
1. Built-In Directives:
○ ng-app: Initializes an AngularJS application.
○ ng-bind: Binds expressions to HTML elements.
○ ng-init: Initializes variables in the scope.
2. Custom Directives:
○ Developers can create their own directives to encapsulate reusable components.
Example:
javascript
Copy code
app.directive('myDirective', function() {
return {
template: "<h1>Custom Directive!</h1>"
};
});
Usage in HTML:
html
Copy code
<div my-directive></div>
3.
AngularJS simplifies form creation and validation using directives and built-in validators.
html
Copy code
<form name="myForm">
<input type="text" name="username" ng-model="username" required>
<span ng-show="myForm.username.$error.required">Username is
required.</span>
</form>
Here:
Routing allows developers to build SPAs by dynamically loading views based on the URL.
1. Setting Up Routing:
○ Add the ngRoute module.
○ Define routes using $routeProvider.
Example:
javascript
Copy code
app.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'homeCtrl'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'aboutCtrl'
});
});
2.
HTML Example:
html
Copy code
<a href="#!/home">Home</a>
<a href="#!/about">About</a>
<div ng-view></div>
3.
Example:
javascript
Copy code
app.controller('myCtrl', function($scope, $http) {
$http.get('https://api.example.com/data')
.then(function(response) {
$scope.data = response.data;
});
});
HTML:
html
Copy code
<ul>
<li ng-repeat="item in data">{{item.name}}</li>
</ul>
AngularJS can handle CRUD (Create, Read, Update, Delete) operations efficiently.
Example:
javascript
Copy code
app.controller('crudCtrl', function($scope) {
$scope.items = [];
$scope.addItem = function(item) {
$scope.items.push(item);
$scope.newItem = "";
};
$scope.removeItem = function(index) {
$scope.items.splice(index, 1);
};
});
HTML:
html
Copy code
<div ng-controller="crudCtrl">
<input ng-model="newItem">
<button ng-click="addItem(newItem)">Add</button>
<ul>
<li ng-repeat="item in items">
{{item}} <button
ng-click="removeItem($index)">Remove</button>
</li>
</ul>
</div>
1. Simplifies Development: Features like two-way binding and directives reduce coding
effort.
2. Reusable Components: Directives and services promote code reuse.
3. Dynamic UI: Enables the creation of interactive and responsive interfaces.
4. Testability: Dependency injection and modularity simplify testing.
Summary
7. MongoDB
MongoDB is a NoSQL database that provides high performance, high availability, and
scalability. Unlike traditional relational databases, MongoDB stores data in a flexible, JSON-like
document format, allowing developers to work with unstructured or semi-structured data
seamlessly.
Use Cases:
● Real-time analytics
● Content management systems
● Internet of Things (IoT) applications
● E-commerce platforms
1. Schema-less Design:
○ No rigid table structure; documents in a collection can have different fields.
2. Scalability:
○ Supports sharding, which splits data across multiple servers for load balancing.
3. Faster Queries:
○ Optimized for unstructured data, making queries faster in some use cases.
4. Flexibility:
○ Handles complex hierarchical data directly in a single document.
5. Ease of Use:
○ No need for complex JOIN operations.
1. Download MongoDB:
○ Visit MongoDB Downloads and choose the appropriate version for your OS.
2. Installation:
○ Follow the instructions for your operating system (Windows, Linux, macOS).
3. Run MongoDB Server:
○ Use the command mongod to start the MongoDB server.
4. Connect to MongoDB:
○ Use the command-line tool mongo or a GUI client like MongoDB Compass.
1. Document Structure:
○ Documents are JSON-like objects with key-value pairs.
Example Document:
json
Copy code
{
"_id": "12345",
"name": "Alice",
"email": "[email protected]",
"orders": [
{ "order_id": "1", "item": "Laptop", "price": 1200 },
{ "order_id": "2", "item": "Phone", "price": 800 }
]
}
○
2. Collections:
○ Collections group related documents.
○ Unlike tables, collections do not enforce a schema.
3. Data Relationships:
○ Embedded Documents: Data is nested within a single document.
○ References: Documents reference other documents by their IDs.
1. Create (Insert):
○ Adds new documents to a collection.
Example:
javascript
Copy code
db.users.insertOne({ name: "Alice", age: 30 });
db.users.insertMany([
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 35 }
]);
2.
3. Read (Find):
○ Retrieves documents from a collection.
Example:
javascript
Copy code
db.users.find(); // Fetch all documents
db.users.find({ age: { $gt: 25 } }); // Fetch users older than 25
4.
5. Update:
○ Modifies existing documents.
Example:
javascript
Copy code
db.users.updateOne(
{ name: "Alice" }, // Filter
{ $set: { age: 31 } } // Update
);
db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "young" } }
);
6.
7. Delete:
○ Removes documents from a collection.
Example:
javascript
Copy code
db.users.deleteOne({ name: "Charlie" });
db.users.deleteMany({ age: { $gt: 50 } });
8.
1. Comparison Operators:
○ $gt (greater than), $lt (less than), $gte (greater than or equal), $lte (less
than or equal), $eq (equal), $ne (not equal).
Example:
javascript
Copy code
db.users.find({ age: { $gte: 30 } });
2.
3. Logical Operators:
○ $and, $or, $not, $nor.
Example:
javascript
Copy code
db.users.find({ $or: [{ age: { $lt: 25 } }, { name: "Alice" }] });
4.
5. Array Operators:
○ $in, $nin, $all, $size.
Example:
javascript
Copy code
db.orders.find({ items: { $all: ["laptop", "mouse"] } });
6.
7. Update Operators:
○ $set, $unset, $inc, $push, $pull.
Example:
javascript
Copy code
db.users.updateOne({ name: "Alice" }, { $inc: { age: 1 } });
8.
1. Node.js Integration:
○ MongoDB integrates with Node.js using the mongodb or mongoose library.
mongoose.connect('mongodb://localhost:27017/mydb', { useNewUrlParser:
true });
2.
3. Using MongoDB Compass:
○ GUI tool for managing MongoDB databases visually.
7.9 Summary of Key Commands
Operation Command Example
Insert db.collection.insertOne({...})
Summary
MongoDB's flexibility, scalability, and document-oriented approach make it ideal for modern web
applications handling large and diverse datasets. Its seamless integration with tools like Node.js
further enhances its utility for developers.