ERP Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

PARUL INSTITUTE OF ENGINEERING AND TECH

5th SEMSTER CSE-BDA


ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

FACULTY OF ENGINEERING AND TECHNOLOGY

BACHELOR OF TECHNOLOGY
COMPUTER SCIENCE AND ENGINEERING
JAVA ENTERPRISE PROGRAMMING
(203105372)
5th SEMESTER
BATCH 5B1

NAME :
ENROLLMENT
NUMBER :

LABORATORY MANUAL

CERTIFICATE

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

This is to certify Ms.K.SUKRUTHA REDDY with Enrollment Number:


210303125051 has successfully complemented his laboratory
experiments in the JAVA ENTERPRISE PROGRAMMING (203105372)
from the department of COMPUTER SCIENCE AND ENGINEERING
during the year 2023-2024.

Date of
Staff in charge HOD
submission

INDEX

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

EXPERIMENT-1

AIM : Database Connectivity with JDBC


Write a program to retrieve the data and managing DML operation using JDBC.

PRACTICAL - 1
AIM

● Database Connectivity with JDBC


● Understanding the Java Database Connectivity (JDBC) API.
● Establishing database connections and perform CRUD operations using MySql server

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

● Handling result sets and managing transactions using JDBC.


● Perform CURD operations.

Student Class

Explanation:
 The class Student has three non-static attributes: rollNo, name, and cgpa.
 It has one constructor: Student(name: String, cgpa: float) which takes the name and CGPA as
parameters and assigns them to the corresponding attributes.
 Additionally, the class has two static attributes: id and college.

CODE:
package com;

public class Student {

static int id;


static String college;

int rollNo;
String name;
float cgpa;

static {
id = 3000;
college = "PIET";
}

public Student(String name, float cgpa) {


this.name = name;
this.cgpa = cgpa;
this.rollNo = ++id;
}

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

Database Class

Explanation:
 The Database class represents a database with attributes url, uname, pass, db, query, and
con. It is responsible for interacting with the database and performing various operations like
creating a database, creating a table, inserting, updating, and retrieving data from the
database.
 The class has constructors to initialize the url, uname, and pass attributes and establish a
connection to the database.
 The createDatabase method creates a new database if it does not exist.
 The createTable method creates a new table in the database if it does not exist.
 The insert method inserts data into the table using a simple SQL query.
 The insertVar method inserts data into the table using a parameterized SQL query.
 The delete method deletes data from the table based on the given rollNo.
 The update method updates the cgpa for a specific rollNo.
 The retrieve method fetches all data from the specified table and prints it.
 The Database class interacts with the Student class in the insert and insertVar methods,
where it retrieves data from the Student object to insert into the database.

import java.sql.*;

public class Database {

String url, uname, pass, db;


String query;
Connection con;

public Database(String url, String uname, String pass) throws SQLException {

this.url = url;
this.uname = uname;
this.pass = pass;
con = DriverManager.getConnection(url, uname, pass);
}

public void createDatabase(String db) throws SQLException {

this.db = db;
query = "create database if not exists " + this.db;

Statement st = con.createStatement();
st.executeUpdate(query);

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

System.out.println(this.db + " database created.");


con.close();
}

public void createTable(String table) throws SQLException {

url += db;
con = DriverManager.getConnection(url, uname, pass);

query = "create table if not exists " + table + "(" +


"rollno integer primary key," +
"name varchar(40)," +
"cgpa float," +
"college varchar(20))";

Statement st = con.createStatement();
st.executeUpdate(query);
System.out.println(table + " table created");
}

public void insert(String table, Student stu) throws SQLException {

this.query = "insert into " + table + " values(" + stu.rollNo + ",'" + stu.name + "'," +
stu.cgpa + ",'" + Student.college + "');";

con = DriverManager.getConnection(url, uname, pass);

Statement st = con.createStatement();

int row = st.executeUpdate(query);

System.out.println(row + " row/s inserted.");


con.close();
}

public void insertVar(String table, Student stu) throws SQLException {

this.query = "insert into " + table + " values(?, ?, ?, ?)";


con = DriverManager.getConnection(url, uname, pass);

PreparedStatement st = con.prepareStatement(query);
st.setInt(1, stu.rollNo);
st.setString(2, stu.name);
st.setFloat(3, stu.cgpa);
st.setString(4, Student.college);

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

int row = st.executeUpdate();


System.out.println(row + " row/s inserted.");
con.close();
}

public void delete(String table, int rollNo) throws SQLException {

con = DriverManager.getConnection(url, uname, pass);

this.query = "delete from " + table + " where rollno=" + rollNo;

Statement st = con.createStatement();

int row = st.executeUpdate(query);


System.out.println(row + " row/s inserted.");
con.close();
}

public void update(String table, int rollNo, float cgpa) throws SQLException {

con = DriverManager.getConnection(url, uname, pass);

this.query = "update "+ table +" set cgpa=? where rollNo=?";

PreparedStatement st = con.prepareStatement(query);
st.setInt(2, rollNo);
st.setFloat(1, cgpa);

int row = st.executeUpdate();


System.out.println(row + " row/s inserted.");
con.close();
}

public void retreive(String table) throws SQLException {

con = DriverManager.getConnection(url, uname, pass);


this.query = "select * from " + table;

Statement st = con.createStatement();

ResultSet result = st.executeQuery(query);

while(result.next()) {
System.out.print(result.getInt(1) + " ");
System.out.print(result.getString(2) + " ");

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

System.out.println(result.getFloat(3) + " ");


System.out.println(result.getString(4));
}
con.close();
}

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

Main Class:

package com;

import java.sql.*;
import java.util.Scanner;

public class JDBCDemo {

public static void main(String[] args) throws SQLException {

String url, uname, pass;


url = "jdbc:mysql://localhost:3306/";
uname = "root";
pass = "darwin";
Database db = null;

Scanner scan = new Scanner(System.in);


String table = null;

while(true) {

System.out.println("1.Create Database\n2.Create Table\n3.Insert\


n4.Delete\n5.Update\n6.Retreive\n7.Exit");
int action = scan.nextInt();

switch(action) {
case 1:
db = new Database(url, uname, pass);
System.out.println("Database Name:");
db.createDatabase(scan.next());
break;

case 2:
try {
System.out.println("Table Name:");
table = scan.next();
db.createTable(table);
}
catch(NullPointerException e) {
System.out.println("Database not created");
}
break;

case 3:

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

if(table.equals(null)) {
System.out.println("Table not exist");
break;
}
System.out.println("Enter student details:");
System.out.println("Name & CGPA");
db.insertVar(table, new Student(scan.next(),
scan.nextFloat()));
break;
case 4:
if(table.equals(null)) {
System.out.println("Table not exist");
break;
}
db.delete(table, 1001);
break;
case 5:
if(table.equals(null)) {
System.out.println("Table not exist");
break;
}
db.update(table, 1002, 9.2f);
break;
case 6:
if(table.equals(null)) {
System.out.println("Table not exist");
break;
}
db.retreive(table);
break;
case 7:
System.out.println("Thank you!");
System.exit(0);
}
}

}
}

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

OUTPUT:

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

Practical – 02

AIM : Introduction to Enterprise Programming Setting up the development


environment (JDK,Eclipse/IntelliJ….etc.,).

Setting up the development environment for enterprise programming involves


configuring essential tools like the Java Development Kit (JDK) and Integrated
Development Environments (IDEs) such as Eclipse or IntelliJ IDEA. This process
ensures that you have the necessary tools to efficiently create, debug, and manage
large-scale enterprise applications. Here's a detailed guide to setting up the
development environment:

Java Development Kit (JDK) Installation:


The JDK is the core software package required for Java development. It includes the
Java Runtime Environment (JRE), compilers, and tools needed to develop Java
applications. Follow these steps to install the JDK:

Visit the official Oracle JDK download page or OpenJDK website.


Download the JDK installer suitable for your operating system (Windows, macOS,
Linux).
Run the installer and follow the installation prompts to complete the setup.
Integrated Development Environment (IDE) Installation:
IDEs provide a comprehensive development environment with features like code
editing, debugging, version control, and more. Eclipse and IntelliJ IDEA are popular
choices:

a. Eclipse:

Visit the Eclipse Downloads page (https://www.eclipse.org/downloads/).


Download the Eclipse IDE for Java Developers package.
Extract the downloaded archive to a directory of your choice.
Run the Eclipse executable (eclipse.exe on Windows) to start the IDE.
b. IntelliJ IDEA:

Visit the IntelliJ IDEA Download page (https://www.jetbrains.com/idea/download/).

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

Download the Community (free) or Ultimate (paid) edition based on your


preference.
Run the installer and follow the installation prompts.
Configuring the IDE:

a. Eclipse:

When you first launch Eclipse, you'll be asked to select a workspace directory. This is
where your projects will be stored.
You can customize the IDE's appearance, plugins, and settings through the
Preferences menu.
b. IntelliJ IDEA:

On launching IntelliJ IDEA, you'll need to set up your preferences and keymap.
Create or import a project and define its settings like SDK (JDK), dependencies, and
version control.
Project Setup:
Create a new project or import an existing one:

a. Creating a New Project:

In Eclipse, use the File > New > Java Project option.
In IntelliJ IDEA, select File > New > Project and choose a Java project template.
b. Importing an Existing Project:

In Eclipse, use the File > Import option and select General > Existing Projects into
Workspace.
In IntelliJ IDEA, select File > New > Project from Existing Sources and navigate to your
project's root directory.
Adding External Libraries:
Enterprise applications often rely on external libraries and frameworks. You can add
these dependencies to your project:

In Eclipse, right-click your project, choose Build Path > Configure Build Path, and add
external JARs or libraries.

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

In IntelliJ IDEA, open your project's settings (File > Project Structure), navigate to
Libraries, and add the necessary JARs or dependencies.
Version Control Integration:
It's essential to use version control systems like Git to manage your codebase:

Both Eclipse and IntelliJ IDEA have built-in Git integration. You can clone repositories,
commit changes, and manage branches directly from the IDE.
Coding and Development:
With your IDE and project set up, you can start coding enterprise applications.
Leverage the IDE's features for code completion, debugging, testing, and more.

Building and Running:


You can build and run your applications within the IDE:

Eclipse and IntelliJ IDEA provide buttons to build and run your code. You can also
configure run configurations to specify how your application should run.
Deployment and Testing:
Depending on your enterprise application, you might need to deploy it to a server or
test various deployment scenarios.

Continuous Integration (CI) and Deployment:


For enterprise projects, setting up CI/CD pipelines using tools like Jenkins, Travis CI,
or GitHub Actions can automate build, test, and deployment processes.

In summary, setting up the development environment for enterprise programming


involves installing the JDK, choosing an IDE (Eclipse or IntelliJ IDEA), configuring the
IDE, setting up projects, managing dependencies, integrating version control, coding,
building, running, testing, and potentially deploying through CI/CD pipelines. This
environment provides the foundation for efficient and effective enterprise software
development.

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

PRACTICAL -3

AIM
 Building a Web Application with Java EE
 Introduction to Java Servlets
 Creating a basic web application using Servlets
 Handling user requests and generating dynamic web content.

STUDENT LOGIN PORTAL

1.1 Flow Chart – Login Page

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

1.2 Login Servlet Source Code


LoginServlet Class

Explanation:
 The LoginServlet class is a Servlet class responsible for handling the login functionality.
 It extends HttpServlet to handle HTTP requests and responses.
 The class has a service method, which is the entry point for processing client requests.
 The service method takes two parameters: request of type HttpServletRequest and response
of type HttpServletResponse.
 Inside the service method, it retrieves the database connection information (url, username,
and password) from the ServletContext using getInitParameter.
 It then establishes a connection to the database using the retrieved credentials.
 The method prepares and executes a SQL query to fetch the password from the database for
the given username provided in the HTTP request.
 If the query returns a result (i.e., the provided username exists in the database) and the
provided password matches the fetched password, it forwards the request to the
"dashboard" URL using RequestDispatcher to redirect the user to the dashboard.
 If the login is unsuccessful, it displays an error message on the response page and provides a
link to go back to the login page.

package com.auth;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.*;
import java.sql.*;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

String url, uname, pass;

ServletContext ctx = request.getServletContext();

url = ctx.getInitParameter("url");
uname = ctx.getInitParameter("uname");

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

pass = ctx.getInitParameter("pass");

PrintWriter out = response.getWriter();


out.println("<html><body bgcolor='lightblue'>");
try {
Connection con = DriverManager.getConnection(url, uname, pass);

String query = "select pass from student where uname=?";

PreparedStatement st = con.prepareStatement(query);
st.setString(1, request.getParameter("uname"));

ResultSet result = st.executeQuery();

if(result.next() && request.getParameter("pass").equals(result.getString(1)))


{

RequestDispatcher rd =
request.getRequestDispatcher("dashboard");
rd.forward(request, response);
}
else {
String msg = "username or password is wrong";
out.println("<h1>" + "username or password is wrong" + "</h1>");
out.println("<a href='login.html'>" + "Click here to login" + "</a>");
}

con.close();
}

catch(SQLException se) {}
out.println("</body></html>");
}
}

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

1.3 Dashboard Servlet Source Code


DashboardServlet Class

Explanation:
 The DashboardServlet class is another Servlet class responsible for displaying the dashboard
information.
 It also extends HttpServlet to handle HTTP requests and responses.
 The class has a service method, which is the entry point for processing client requests.
 The service method takes two parameters: request of type HttpServletRequest and
response of type HttpServletResponse.
 Inside the service method, it retrieves the database connection information (url, username,
and password) from the ServletContext using getInitParameter.
 It then establishes a connection to the database using the retrieved credentials.
 The method prepares and executes a SQL query to fetch all information from the database
for the given username provided in the HTTP request.
 It iterates over the result set and prints the fetched information on the response page,
representing the dashboard content.
 The DashboardServlet does not perform any specific forwarding or redirecting; it simply
generates the content and sends it as a response to the client.

package com.auth;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.*;
import java.sql.*;

@WebServlet("/dashboard")
public class DashboardServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String url, uname, pass;


ServletContext ctx = request.getServletContext();

url = ctx.getInitParameter("url");
uname = ctx.getInitParameter("uname");
pass = ctx.getInitParameter("pass");

PrintWriter out = response.getWriter();

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

out.println("<html><body bgcolor='lightgreen'>");
try {
Connection con = DriverManager.getConnection(url, uname, pass);

String query = "select * from student where uname = ?";

PreparedStatement st = con.prepareStatement(query);
st.setString(1, request.getParameter("uname"));

ResultSet result = st.executeQuery();

while(result.next()) {
out.print(result.getString(1) + " ");
out.print(result.getString(3) + " ");
out.print(result.getString(4) + " ");
out.println(result.getString(5));
}
con.close();

}
catch(SQLException se) {}
out.println("</body></html>");
}
}

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

2.1 Flow Chart – Registration Page

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

2.2 Register Servlet Source Code


RegisterServlet Class

Explanation:
 The RegisterServlet class is a Servlet responsible for registering new students and saving
their information in the database.
 It extends HttpServlet to handle HTTP requests and responses.
 The class overrides the service method, which is the entry point for processing client
requests.
 The service method takes two parameters: req of type HttpServletRequest and res of type
HttpServletResponse.
 Inside the service method, it retrieves the database connection information (url, username,
and password) from the ServletContext using getInitParameter.
 It then establishes a connection to the database using the retrieved credentials.
 The method prepares and executes an SQL query to insert new student information into the
database based on the information received in the HTTP request parameters (e.g., uname,
pass, email, dob, and gender).
 After successful registration, it redirects the client to the "login.html" page using
HttpServletResponse's sendRedirect method.
 The RegisterServlet class does not display any content directly; its main purpose is to process
the registration request and save the information in the database.

package com.auth;
import java.io.*;
import java.sql.*;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException {

String url, uname, pass;


ServletContext ctx = req.getServletContext();

url = ctx.getInitParameter("url");
uname = ctx.getInitParameter("uname");
pass = ctx.getInitParameter("pass");

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

PrintWriter out = res.getWriter();

try {
Connection con = DriverManager.getConnection(url, uname, pass);

String query = "insert into student values(?, ?, ?, ?, ?)";

PreparedStatement st = con.prepareStatement(query);

st.setString(1, req.getParameter("uname"));
st.setString(2, req.getParameter("pass"));
st.setString(3, req.getParameter("email"));
st.setString(4, req.getParameter("dob"));
st.setString(5, req.getParameter("gender"));

con.close();

res.sendRedirect("login.html");

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

3.1 web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://jakarta.ee/xml/ns/jakartaee"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd" id="WebApp_ID" version="6.0">
<display-name>studentPortal</display-name>

<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>

<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/student</param-value>
</context-param>

<context-param>
<param-name>uname</param-name>
<param-value>root</param-value>
</context-param>

<context-param>
<param-name>pass</param-name>
<param-value>darwin</param-value>
</context-param>

</web-app>

210303125051
Output:
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

PRACTICAL -4

AIM : Introduction to Design Patterns


Implementing a simple example using a factory design pattern

DESIGN PATTERN
Each pattern describes a problem which occurs over and over again in
our environment, and then describes the core of the solution to that
problem, in such a way that you can use this solution a million times
over, without ever doing it the same way twice
FACTORY DESIGN PATTERN
The factory design pattern says that define an interface (A java
interface) for creating object and let the subclasses decide which class
to instantiate. 
IMPLEMENTATION – Factory Design
Class Diagram

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

Code:
package com;

import java.util.Scanner;

public class FactoryDesign {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.println("Juice Catalog\n1.Apple\n2.Banana\n3.Orange");
String fruit = scan.next();
scan.close();

FruitFactory fruitJuice = new FruitFactory();


Fruit juice = fruitJuice.produceFruit(fruit.toLowerCase());

juice.produceJuice();
}
}

interface Fruit{
void produceJuice();
}

class Apple implements Fruit{

@Override
public void produceJuice() {
System.out.println("Have Apple Juice");
}
}

class Banana implements Fruit{

@Override
public void produceJuice() {
System.out.println("Have Banana Juice");

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

}
}

class Orange implements Fruit{

@Override
public void produceJuice() {
System.out.println("Have Orange Juice");
}
}

class Water implements Fruit{

@Override
public void produceJuice() {
System.out.println("Have Water");
}
}

class FruitFactory{

Fruit produceFruit(String fruit) {

switch(fruit){

case "apple":
return new Apple();

case "banana":
return new Banana();

case "orange":
return new Orange();

default:
return new Water();
}
}
}

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

Output:

PRACTICAL - 05

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

AIM
 Unit Testing in Java Enterprise Applications
 Importance of unit testing in enterprise programming.
 Introduction to JUnit framework for Java unit testing.
 Writing unit tests for UserAuthentication class to validate the username and
password with database.

AuthenticationTest Class

Explanation:
 The AuthenticationTest class is a test class that contains two test cases:

testcase_1 and testcase_2.


 Each test case uses JUnit's @Test annotation to mark it as a test method.
 In each test case, an instance of the Authentication class is created.
 The logIn method is called on the Authentication instance with specific

username and password values.


 The Assert.assertEquals method is used to check if the result of the logIn

method is true, which the expected result for both test cases is.

CODE:
package accounts.student;

import org.junit.*;

public class AuthenticationTest {


@Test
public void testcase_1() {

Authentication app = new Authentication();

Assert.assertEquals(true, app.logIn("ddd", "ddd@676"));


}

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

@Test
public void testcase_2() {

Authentication app = new Authentication();

Assert.assertEquals(true, app.logIn("ddd", "ddd@676"));


}
}
Authentication Class

Explanation:
 The Authentication class has one method logIn, which takes two parameters

uname (username) and pass (password) as input and returns a boolean value.
 The logIn method is responsible for authenticating the user by checking the

provided username and password against the database.


 The method uses a ResourceBundle named "credentials" to retrieve the

database connection information such as url, username, and password.


 Inside the method, it establishes a database connection using the provided

credentials.
 It prepares and executes a SQL query to fetch the password from the database

for the given uname.


 If the query returns a result (i.e., the provided uname exists in the database), it

compares the fetched password with the provided password (pass) to


determine if the login is successful.
 The method returns true if the login is successful, and false otherwise.

package accounts.student;

import java.sql.*;
import java.util.ResourceBundle;

public class Authentication {

public boolean logIn(String uname, String pass){

boolean res = false;

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

ResourceBundle resource = ResourceBundle.getBundle("credentials");

String url, username, password;

url = resource.getString("url");
username = resource.getString("uname");
password = resource.getString("pass");

try {
Connection con = DriverManager.getConnection(url, username,
password);

String query = "select pass from student where uname=?";

PreparedStatement st = con.prepareStatement(query);
st.setString(1, uname);

ResultSet result = st.executeQuery();


if(result.next()) {
res = pass.equals(result.getString(1));
}

con.close();
}

catch(SQLException se) {}

return res;
}
}

credential.properties

url = jdbc:mysql://localhost:3306/student
uname = root
pass = sukrutha

210303125051
PARUL INSTITUTE OF ENGINEERING AND TECH
5th SEMSTER CSE-BDA
ENTERPRISE PROGRAMMING LABORATORY
SUB CODE: 203105375

OUTPUT:

210303125051

You might also like