0% found this document useful (0 votes)
18 views44 pages

Final Clothing Store Management Report

The document is a project report for the 'Clothing Store Management System' developed during a summer training program at Lovely Professional University. It details the project's objectives, methodologies, and implementation, highlighting the use of Java and MySQL for inventory and user management in a retail setting. The report includes acknowledgments, a table of contents, and various chapters covering training overview, project details, implementation, and results.

Uploaded by

rishav9031888
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views44 pages

Final Clothing Store Management Report

The document is a project report for the 'Clothing Store Management System' developed during a summer training program at Lovely Professional University. It details the project's objectives, methodologies, and implementation, highlighting the use of Java and MySQL for inventory and user management in a retail setting. The report includes acknowledgments, a table of contents, and various chapters covering training overview, project details, implementation, and results.

Uploaded by

rishav9031888
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

SUMMER TRAINING/INTERNSHIP

PROJECT REPORT
(Term June-August 2025)

ONLINE CLOTHING STORE MANAGEMENT SYSTEM

Submitted By

Name Registration Number


Aman Saxena 12309630
Mridulika Sharma 12320295
Vansham 12302303

COURSE CODE: PETV74

Under The Guidance Of

Mr. Sarvesh Chopra

School of Computer Science and Engineering

i
CERTIFICATE

ii
Acknowledgement

I would like to express my deep gratitude to Lovely Professional University for giving me the valuable
opportunity to undergo summer training and work on the project titled “Clothing Store Management
System.”
I am especially thankful to my project guide, Mr. Sarvesh Chopra, for his insightful guidance, timely
feedback, and continuous encouragement throughout the development of this project. His mentorship
played a crucial role in shaping my learning experience.
I sincerely appreciate the Department of Computer Science and Engineering for fostering a learning
environment that encouraged creativity, technical exploration, and practical application of knowledge.
I would also like to extend my thanks to my fellow students and friends who offered support, suggestions,
and motivation during different phases of this project.
Lastly, I am deeply thankful to my family for their patience, inspiration, and unwavering support
throughout the training period.
This summer training has greatly enhanced my practical understanding of Java programming and
database management, and I am confident it will serve as a strong foundation for my future endeavors.

Aman Saxena
B.Tech – Computer Science and Engineering
Lovely Professional University

iii
Table of Contents
Chapter 1: Introduction ........................................................................................................... 1
1.1 University Introduction................................................................................................................................. 1
1.2 Overview of training domain ....................................................................................................................... 1
1.3 Objective of the project ................................................................................................................................ 1

Chapter 2: Training Overview ................................................................................................ 3


2.1 Tools C technologies used.............................................................................................................................. 3
2.2 Areas covered during training ...................................................................................................................... 3
2.3 Daily/weekly work summary .................................................................................................... 4
Chapter 3: Project Details ....................................................................................................... 5
3.1 Title of the project ........................................................................................................................................ 5
3.2 Problem definition ........................................................................................................................................ 5
3.3 Scope and objectives .................................................................................................................................... 5
3.3.1 Scope .............................................................................................................................................. 5
3.3.2 Objectives ....................................................................................................................................... 5
3.4 System requirements .................................................................................................................................... 6
3.4.1 Hardware requirement..................................................................................................................... 6
3.4.2 Software requirement ...................................................................................................................... 6
3.5 Data flow ...................................................................................................................................................... 7
Chapter 4: Implementation ..................................................................................................... 8
4.1 Methodology ................................................................................................................................................ 8
4.2 Modules/Screenshots............................................................................................................... 8
4.2.1 Login modules ................................................................................................................................ 8
4.2.2 Admin dashboard(StoreFrame) ....................................................................................................... 9
4.2.3 Product management module(CRUD) ............................................................................................ 9
4.2.4 System Logs Module ....................................................................................................................... 9
4.2.5 Search and Report Features .......................................................................................................... 10
4.2.5 Billing and Inventory Monitoring ................................................................................................. 10
4.2.6 User Registration and Password Recovery ..................................................................... 11
Chapter 5: Results and Discussion ........................................................................................ 12
5.1 Output/Report ............................................................................................................................................. 12
5.2 Challenges faced ........................................................................................................................................ 12
5.3 Learnings.................................................................................................................................................... 13

Chapter 6: Conclusion ........................................................................................................... 14


6.1 Summary .................................................................................................................................... 14
Chapter 7: Coding Section……………………………………………………………………………….15
iv
7.1 Login Page Code…………………………………………………………………………………15
7.2 Crud Page Code…………………………………………………………………………………..15
7.3 Applogger Page Code……………………………………………………………………………..16

iv
CHATER 1: INTRODUCTION
1.1 University introduction

Lovely Professional University (LPU), one of India’s top private institutions, is committed to
fostering academic excellence and practical learning. Through initiatives like summer training
programs, LPU equips students with the technical and project development skills necessary for
real-world success. The Clothing Store Management System project was undertaken as part of
this initiative to bridge theoretical knowledge with software implementation practices.

1.2 OVERVIEW OF TRAINING DOMAIN

The training program centered around desktop application development using Java and
MySQL. Java, with its strong object-oriented capabilities and platform independence,
combined with MySQL, a robust open-source relational database system, provided the
technical foundation for this project. The major areas of learning included:

• Object-Oriented Programming in Java

• Swing for GUI development

• JDBC for database connectivity

• Software design and modularization

• Real-time data management and logging

• CRUD operations

This domain is crucial for developing enterprise-level applications like ERP systems, POS
systems, and inventory management software.

1.3 OBJECTIVE OF THE PROJECT

The core objective of this project is to build a Java-based desktop application named "Clothing
Store Management System" which enables inventory and user management for a retail clothing
store. The solution simulates key operations of a retail system such as:
▪ Providing secure login functionality with password masking and
attempt limits
▪ Enabling CRUD operations on product records (add, view, update,
delete)
▪ Allowing user registration and password reset functionalities
▪ Incorporating real-time product search and inventory alerts
▪ Maintaining detailed logs of actions and transactions
▪ Providing a user-friendly and responsive GUI using Java Swing
This project consolidates the skills acquired during training and provides a practical
demonstration of using Java and MySQL for developing real-world business software
applications.

2
CHAPTER 2: TRAINING OVERVIEW
2.1 TOOLS AND TECHNOLOGY USED

During the training, the following tools and technologies were used to build the Clothing Store
Management System :

Table 1: Tools and Technology used

Tool/Technology Description
Core programming language used for building
Java (JDK 8+)
the entire application logic.
Used to create the Graphical User Interface
Java Swing
(GUI) for the system.
Open-source relational database used to store
MySql
users, products, and sales.
Used to connect Java applications with the
JDBC
MySQL database.

2.2 AREAS COVERED DURING TRAINING

Throughout the summer training program, the following key areas were covered:

• Core Java fundamentals and OOP concepts


• GUI application development using Java Swing
• Performing database operations (CRUD) via JDBC
• Implementing login systems with password masking and attempt limitations
• Registering users and enabling password reset features
• Searching product inventory by ID, brand, or price
• Real-time product stock management and alert system
• Creating and accessing daily log files using Java Logger
• Debugging and exception handling in Java desktop applications
These topics equipped students with skills to design and build complete, functional software
solutions for retail environments.

3
2.3 DAILY AND WEEKLY WORK SUMMARY

Week 1: Oops principles and java class Libraries,token

Week 2: Inheritance and nested classes

Week 3: Exception Handling and Design Patterns

Week 4: Java Collections

Week 5: Threads and GUI and JDBC

4
CHAPTER 3: PROJECT DETAILS
3.1 TITLE OF THE PROJECTS

Clothing Store Management System using Java and MySQL

3.2 PROBLEM DEFINITIONS

Managing a clothing store manually can be inefficient, error-prone, and time-consuming. Tasks
such as tracking inventory, registering users, securing login credentials, updating stock, and
logging user activities become difficult to manage without an automated system.

The absence of an integrated software solution leads to issues such as inconsistent stock records,
unauthorized access, delayed customer service, and lack of transaction tracking.

Hence, there is a need for a comprehensive Clothing Store Management System that automates
product management, supports secure user authentication, logs application events, and offers a
user-friendly interface to improve efficiency and accuracy in retail operations.

3.3 SCOPE AND OBJECTIVES


3.3.1 SCOPE

The Clothing Store Management System is designed as a standalone desktop application to


manage product inventory and user access securely. The system keeps track of data through
structured MySQL tables that store information about products, user credentials, and logs of user
actions. Each interaction—whether it's adding a new product, updating stock, or logging in—is
handled through Java JDBC and is logged using a custom logging utility.
The application distinguishes between different types of users by implementing role-specific
privileges at the interface level. While the current version supports basic user functionality,
administrative privileges allow access to features such as viewing logs, updating or deleting
inventory, and performing critical operations.
The scope includes:
• Managing inventory through Create, Read, Update, Delete (CRUD) operations.
• Handling user login, registration, and password recovery securely.
• Storing and tracking changes in product details and user activity logs.

5
• Offering low-stock alerts and real-time search to support better inventory decisions.
• Providing a user-friendly GUI for ease of operation by both new and experienced users.

3.3.2 OBJECTIVES

• Develop a GUI-based inventory management system using Java Swing

• Implement secure login functionality with registration and password reset options

• Allow administrators to manage products (add, update, delete, view)

• Incorporate product search and low-stock alert features

• Store all data in a MySQL database with structured schema

• Log important events such as user actions, logins, and errors using Java Logging API for
auditing and debugging

These objectives were designed to ensure the project aligned with real-world retail software
needs while reinforcing core programming concepts.

6
3.4 SYSTEM REQUIREMENTS
3.4.1 HARDWARE REQUIREMENTS

Table 2: Hardware Requirements

Component Minimum Requirement

Processor Intel Core i3 or equivalent

RAM 4 GB or higher

Storage 500 MB free disk space

Display 1024x768 resolution

3.4.2 SOFTWARE REQUIREMENTS

Table 3: Software requirements

Component Description

Operating System Windows 10 / Linux / macOS

Java Development Kit JDK 8 or later

Database MySQL 5.7 or above

7
3.5 DATAFLOW

8
CHAPTER 4: IMPLEMENTATION
4.1 METHODOLOGY

We followed the modular programming approach and object-oriented design principles. The
project was broken down into distinct components including:

• User Authentication

• Product Management

• Inventory Search and Alert System

The development phases included:

1. Designing database schema and setting up MySQL tables


2. Developing user interface components using Java Swing
3. Writing business logic using Java classes
4. Connecting Java to MySQL using JDBC
5. Implementing logging with Java Logging API for tracking actions
6. Testing workflows including login, CRUD operations, and logging

Methodology Diagram
9
4.1.1 Thread Handling

To ensure smooth user experience and prevent the GUI from freezing during time-
consuming operations (such as log file access or database queries), the project uses basic
thread handling mechanisms provided by Java. For example:

• SwingUtilities.invokeLater is used to launch the main GUI thread safely.


• Background threads are triggered for non-blocking operations like opening log files,
especially when using Desktop.getDesktop().open() for viewing logs.
• The design ensures that all UI interactions remain responsive while background operations
are performed asynchronously where necessary.

This threading approach supports a more efficient and user-friendly system, especially
when managing file I/O and database tasks.

4.2 MODULES

4.2.1 Login Module

The login module is responsible for user authentication, allowing only authorized users to
access the system. It supports the following functionalities:

• Username and password validation using data stored in the MySQL database.

• Password masking and a checkbox to show/hide password text.

• Login attempt limitation (3 tries) to prevent brute-force access.

• Forgot password feature that allows password reset after verifying the username.

• User registration module for new users with password confirmation validation.

• All login activities (success or failure) are logged using Java Logging API for monitoring
and auditing.

10
This module ensures secure access and establishes the user context for accessing other
modules in the application.

Figure 1. Login Frame

Figure 1.1.1 Use of Password show checkbox.

11
Figure 1.1.2 Login Successful.

Figure 1.1.3 Register New User.

Figure 1.1.4 Registered Successful.

12
Figure 1.1.5 Enter Username for New Password

Figure 1.1.6 Enter New Password

Figure 1.1.7 Password Updated Successfully

13
Figure 1.1.8 Attempts 1

Figure 1.1.9 Attempts 2

Figure 1.1.10 Last Attempts Failed

14
4.2.2 Admin Dashboard

The Admin Dashboard serves as the central control panel for managing inventory-related
tasks within the Clothing Store Management System. Upon successful login, the user
(admin) is redirected to the main interface (StoreFrame) that functions as the dashboard.
This interface allows the administrator to interact with the core functionalities of the
application through an intuitive GUI built with Java Swing.
Key Functionalities of the Admin Dashboard:
• Product Management: The admin can perform all CRUD (Create, Retrieve, Update,
Delete) operations on product data. Product fields include ID, name, category, quantity,
and price. These actions are handled through dedicated buttons and text fields.
• Search and Filter: A real-time search feature enables the admin to look up products by ID,
name, or price. The results are displayed dynamically in a JTable.
• Log Viewer: A "View Logs" button allows the admin to access the application log file.
This feature uses Java's Desktop.getDesktop().open() method to open the log file created
by the AppLogger utility. The log file records all significant events such as logins,
product changes, and system warnings.
• Low-Stock Alerts: During data retrieval, the system checks inventory levels and
automatically notifies the admin of any product whose stock is below the predefined
threshold (e.g., quantity < 5). This helps in proactive stock management.
• UI Navigation and Usability: Buttons like “Clear” and “Exit” help streamline workflow.
All actions are executed in real time with visual feedback via JOptionPane dialogues.
Security and Logging:
• All actions performed on this dashboard (e.g., product creation, update, deletion, and
search) are logged using the Java Logging API (AppLogger). This provides traceability
and accountability for administrative operations.
This module reflects core principles of usability, modularity, and maintainability while
offering complete control over the inventory management lifecycle.

15
Figure 2 Admin Dashboard

Figure 2.1.1 Create(Add) Product vivo phone.

16
Figure 2.1.2 Product Added successfully.

Figure 2.1.3 Retrieve.

Figure 2.1.4 Quantity Update.

17
Figure 2.1.5 Product Quantity Updated.

Figure 2.1.6 Delete button use.

18
Figure 2.1.7 Product vivo phone Deleted Successfully.

Figure 2.1.8 Use of Clear Button.

19
4.2.3 System Logs

The System Logs module ensures that all major events within the application are
persistently recorded. Logging is handled by the AppLogger utility, which uses
Java's built-in Logging API to write entries into a date-wise .log file.

Key Features:

• Captures login attempts, both successful and failed, by users including time and
username.

• Logs product operations such as add, update, and delete actions by the admin.

• Tracks exceptional conditions or application warnings to help with debugging.

• Stores logs in external .log files (e.g., app_log_YYYY-MM-DD.log) generated daily.

• Allows the admin to view log files through the dashboard using system file open
feature.

This module significantly contributes to application monitoring, auditing, and security


by enabling post-event analysis and ensuring that sensitive actions are traceable.

Figure 3 System logs.

20
4.2.4 Inventory Management Module

This module provides comprehensive inventory tracking and product control features that are
accessible to the admin.

• Admin can add new products or update/delete existing ones.

• Inventory levels are constantly monitored, and low-stock alerts are generated.

• Search options allow filtering by product ID or brand.

• All inventory operations are logged using Java Logging API.

21
CHAPTER 5: RESULT AND DISCUSSION
5.1 OUTPUT/REPORT

The final output of the Clothing Store Management System achieved the key project goals:
• Login Module: Secure login, registration, and password recovery features function as expected.
• Admin Dashboard: The administrator can add, update, delete, and search products. Log files can
be opened and reviewed. Low stock alerts assist in inventory decision-making.
• Logging System: All key user actions, such as logins and inventory updates, are recorded in
timestamped log files using Java Logging API.

5.2 CHALLENGES FACED

• Database Connectivity Issues: JDBC driver configuration required careful matching between
Java and MySQL versions.
• Swing UI Alignment: Creating a responsive and organized interface layout across screen sizes
took effort.
• Role-based Access: Implementing access controls and UI differences based on login roles
(admin vs others) added extra logic.
• Log Synchronization: Ensuring logs are written only after successful DB operations required
precise handling.

5.3 LEARNINGS

Through this project, several technical and professional skills were developed:
• Practical use of Java Swing for desktop application design
• Use of JDBC for database operations with MySQL
• Hands-on application of CRUD techniques and user input handling
• Modular design using object-oriented programming
• Logging and monitoring via Java Logging API
• Debugging complex UI and DB workflows

22
CHAPTER 6: CONCLUSION
SUMMARY

The Clothing Store Management System developed as part of the summer training
successfully meets the core objectives of enabling secure login, product inventory control,
and activity logging.
Built using Java Swing and MySQL, the application demonstrates effective use of object-
oriented principles, JDBC database connectivity, and real-time inventory control. With a
focus on modularity and logging, it helps simulate a basic retail environment.
Key Features Achieved:
• Secure login with registration and forgot password
• CRUD-based inventory operations for admin
• Inventory alerts for low stock
• Log file creation and viewing for audits
The project enabled practical application of training concepts and serves as a strong
foundation for enhancements like billing features, cashier-specific dashboards, and sales
analytics in future versions.

7. CODING SECTION

7.1 LOGIN PAGE CODE :-

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

class LoginFrame extends JFrame implements ActionListener {


JTextField usernameField;
JPasswordField passwordField;
JCheckBox showPasswordCheckBox;
JButton loginButton, forgotPasswordBtn, registerBtn;
JLabel messageLabel;

23
String url = "jdbc:mysql://localhost:3306/clothing_store";
String dbUser = "root";
String dbPassword = "Engineer@#4599";

int attempts = 0;
final int MAX_ATTEMPTS = 3;

public LoginFrame() {
setTitle("Login - Clothing Store");
setSize(350, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

JPanel panel = new JPanel(new GridLayout(6, 2, 10, 10));


panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

usernameField = new JTextField(20);


passwordField = new JPasswordField(20);
showPasswordCheckBox = new JCheckBox("Show");
loginButton = new JButton("Login");
forgotPasswordBtn = new JButton("Forgot Password?");
registerBtn = new JButton("Register");
messageLabel = new JLabel("");

panel.add(new JLabel("Username:"));
panel.add(usernameField);

panel.add(new JLabel("Password:"));
JPanel passPanel = new JPanel(new BorderLayout());
passPanel.add(passwordField, BorderLayout.CENTER);
passPanel.add(showPasswordCheckBox, BorderLayout.EAST);
panel.add(passPanel);

panel.add(loginButton);

24
panel.add(forgotPasswordBtn);

panel.add(new JLabel("New user?"));


panel.add(registerBtn);

panel.add(new JLabel());
panel.add(messageLabel);

add(panel);

loginButton.addActionListener(this);
forgotPasswordBtn.addActionListener(e -> forgotPassword());
registerBtn.addActionListener(e -> registerUser());

showPasswordCheckBox.addActionListener(e -> {
passwordField.setEchoChar(showPasswordCheckBox.isSelected() ? (char) 0 :
'\u2022');
});
}

@Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText().trim();
String password = new String(passwordField.getPassword());

if (username.isEmpty() || password.isEmpty()) {
JOptionPane.showMessageDialog(this, "Please fill both fields!", "Warning",
JOptionPane.WARNING_MESSAGE);
return;
}

if (authenticate(username, password)) {
AppLogger.getLogger().info("Login successful for user: " + username);
JOptionPane.showMessageDialog(this, " Login Successful!");

25
StoreFrame frame = new StoreFrame();
frame.setSize(700, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.dispose();
} else {
attempts++;
AppLogger.getLogger().warning("Failed login attempt for user: " + username + "
(Attempt " + attempts + ")");
if (attempts >= MAX_ATTEMPTS) {
JOptionPane.showMessageDialog(this, " Too many failed attempts. Exiting.");
System.exit(0);
} else {
JOptionPane.showMessageDialog(this, " Invalid Username or
Password\nAttempts: " + attempts + "/" + MAX_ATTEMPTS, "Login Failed",
JOptionPane.ERROR_MESSAGE);
}
}
}

private boolean authenticate(String username, String password) {


try (Connection con = DriverManager.getConnection(url, dbUser, dbPassword);
PreparedStatement stmt = con.prepareStatement("SELECT * FROM logins WHERE
uname = ? AND password = ?")) {

stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
return rs.next();

} catch (SQLException ex) {


AppLogger.getLogger().severe("Database error during login: " + ex.getMessage());
JOptionPane.showMessageDialog(this, "Database Error: " + ex.getMessage());
return false;
26
}
}

private void forgotPassword() {


String username = JOptionPane.showInputDialog(this, "Enter your username:");
if (username == null || username.trim().isEmpty()) return;

try (Connection con = DriverManager.getConnection(url, dbUser, dbPassword);


PreparedStatement checkStmt = con.prepareStatement("SELECT * FROM logins
WHERE uname = ?")) {

checkStmt.setString(1, username.trim());
ResultSet rs = checkStmt.executeQuery();

if (rs.next()) {
String newPassword = JOptionPane.showInputDialog(this, "Enter your new
password:");
if (newPassword == null || newPassword.trim().isEmpty()) {
JOptionPane.showMessageDialog(this, " Password cannot be empty.");
return;
}

PreparedStatement updateStmt = con.prepareStatement("UPDATE logins SET


password = ? WHERE uname = ?");
updateStmt.setString(1, newPassword.trim());
updateStmt.setString(2, username.trim());
int updated = updateStmt.executeUpdate();

if (updated > 0) {
AppLogger.getLogger().info("Password updated for user: " + username);
JOptionPane.showMessageDialog(this, " Password updated successfully!");
} else {
JOptionPane.showMessageDialog(this, " Failed to update password.");
}
27
} else {
JOptionPane.showMessageDialog(this, " Username not found.");
}

} catch (SQLException ex) {


AppLogger.getLogger().severe("Error updating password: " + ex.getMessage());
JOptionPane.showMessageDialog(this, "Database Error: " + ex.getMessage());
}
}

private void registerUser() {


JTextField newUserField = new JTextField();
JPasswordField newPassField = new JPasswordField();
JPasswordField confirmPassField = new JPasswordField();

JPanel panel = new JPanel(new GridLayout(3, 2));


panel.add(new JLabel("Username:"));
panel.add(newUserField);
panel.add(new JLabel("Password:"));
panel.add(newPassField);
panel.add(new JLabel("Confirm Password:"));
panel.add(confirmPassField);

int result = JOptionPane.showConfirmDialog(this, panel, "Register New User",


JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

if (result == JOptionPane.OK_OPTION) {
String uname = newUserField.getText().trim();
String pass = new String(newPassField.getPassword()).trim();
String confirm = new String(confirmPassField.getPassword()).trim();

if (uname.isEmpty() || pass.isEmpty() || confirm.isEmpty()) {


JOptionPane.showMessageDialog(this, " All fields are required!");
28
return;
}

if (!pass.equals(confirm)) {
JOptionPane.showMessageDialog(this, " Passwords do not match!");
return;
}

try (Connection con = DriverManager.getConnection(url, dbUser, dbPassword);


PreparedStatement checkStmt = con.prepareStatement("SELECT * FROM logins
WHERE uname = ?")) {

checkStmt.setString(1, uname);
ResultSet rs = checkStmt.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(this, " Username already exists!");
return;
}

PreparedStatement insertStmt = con.prepareStatement("INSERT INTO logins


(uname, password) VALUES (?, ?)");
insertStmt.setString(1, uname);
insertStmt.setString(2, pass);
insertStmt.executeUpdate();

AppLogger.getLogger().info("New user registered: " + uname);


JOptionPane.showMessageDialog(this, " User registered successfully!");
} catch (SQLException ex) {
AppLogger.getLogger().severe("Registration error: " + ex.getMessage());
JOptionPane.showMessageDialog(this, "Database Error: " + ex.getMessage());
}
}
}

29
public static void main(String[] args) {
AppLogger.setupLogger(); // Initialize logger before anything else
SwingUtilities.invokeLater(() -> {
AppLogger.getLogger().info("LoginFrame launched");
new LoginFrame().setVisible(true);
});
}
}

7.2 CRUD Page Code:


import java.awt.*;
import java.io.File;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

class StoreAppMain {
public static void main(String args[]) {
AppLogger.setupLogger(); // Initialize logger
StoreFrame frame = new StoreFrame();
frame.setSize(700, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

class StoreFrame extends JFrame {


JButton createBtn, retrieveBtn, updateBtn, deleteBtn, clearBtn, exitBtn, searchBtn,
viewLogsBtn;
JTextField tf1, tf2, tf4, tf5, tf6, searchField;
JComboBox<String> categoryBox;
JTable table;
DefaultTableModel model;

30
String url = "jdbc:mysql://localhost:3306/clothing_store";
String user = "root";
String pass = "Engineer@#4599";

public StoreFrame() {
setTitle(" Clothing Store Management System");
setLayout(new BorderLayout());

JPanel inputPanel = new JPanel(new GridLayout(8, 2, 5, 5));


tf1 = new JTextField();
tf2 = new JTextField();
String[] categories = {"T-Shirts", "Jeans", "Shoes", "Jackets", "Accessories"};
categoryBox = new JComboBox<>(categories);
tf4 = new JTextField();
tf5 = new JTextField();
tf6 = new JTextField();

inputPanel.add(new JLabel("Product ID:"));


inputPanel.add(tf1);
inputPanel.add(new JLabel("Product Name:"));
inputPanel.add(tf2);
inputPanel.add(new JLabel("Category:"));
inputPanel.add(categoryBox);
inputPanel.add(new JLabel("Quantity:"));
inputPanel.add(tf4);
inputPanel.add(new JLabel("Price (₹):"));
inputPanel.add(tf5);
inputPanel.add(new JLabel("Update/Delete Product ID:"));
inputPanel.add(tf6);

add(inputPanel, BorderLayout.NORTH);

model = new DefaultTableModel(new String[]{"ID", "Name", "Category", "Qty",


"Price"}, 0);

31
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);

JPanel buttonPanel = new JPanel(new FlowLayout());


createBtn = new JButton("Create");
retrieveBtn = new JButton("Retrieve");
updateBtn = new JButton("Update");
deleteBtn = new JButton("Delete");
clearBtn = new JButton("Clear");
exitBtn = new JButton("Exit");
viewLogsBtn = new JButton("View Logs");

buttonPanel.add(createBtn);
buttonPanel.add(retrieveBtn);
buttonPanel.add(updateBtn);
buttonPanel.add(deleteBtn);
buttonPanel.add(clearBtn);
buttonPanel.add(exitBtn);
buttonPanel.add(viewLogsBtn);

add(buttonPanel, BorderLayout.SOUTH);

JPanel searchPanel = new JPanel();


searchPanel.add(new JLabel("Search Product:"));
searchField = new JTextField(15);
searchBtn = new JButton("Search");
searchPanel.add(searchField);
searchPanel.add(searchBtn);

add(searchPanel, BorderLayout.WEST);

createBtn.addActionListener(e -> createProduct());


retrieveBtn.addActionListener(e -> retrieveProducts());

32
updateBtn.addActionListener(e -> updateProduct());
deleteBtn.addActionListener(e -> deleteProduct());
clearBtn.addActionListener(e -> clearFields());
exitBtn.addActionListener(e -> dispose());
searchBtn.addActionListener(e -> searchProducts());
viewLogsBtn.addActionListener(e -> openLogFile());
}

void openLogFile() {
try {
String logFileName = AppLogger.getCurrentLogFileName();
File logFile = new File(logFileName);
if (logFile.exists()) {
Desktop.getDesktop().open(logFile);
} else {
JOptionPane.showMessageDialog(this, "Log file not found.");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error opening log file: " + ex.getMessage());
}
}

void createProduct() {
try (Connection con = DriverManager.getConnection(url, user, pass)) {
if (tf1.getText().isEmpty() || tf2.getText().isEmpty() || tf4.getText().isEmpty() ||
tf5.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "Please fill all fields!", "Warning",
JOptionPane.WARNING_MESSAGE);
return;
}
int id = Integer.parseInt(tf1.getText());
String name = tf2.getText();
String category = categoryBox.getSelectedItem().toString();
int qty = Integer.parseInt(tf4.getText());

33
float price = Float.parseFloat(tf5.getText());

String query = "INSERT INTO products VALUES (?, ?, ?, ?, ?)";


PreparedStatement stmt = con.prepareStatement(query);
stmt.setInt(1, id);
stmt.setString(2, name);
stmt.setString(3, category);
stmt.setInt(4, qty);
stmt.setFloat(5, price);
stmt.executeUpdate();

JOptionPane.showMessageDialog(this, " Product added successfully!");


AppLogger.getLogger().info("Product created: " + name);
retrieveProducts();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, " Error: " + ex.getMessage());
AppLogger.getLogger().warning("Error creating product: " + ex.getMessage());
}
}

void retrieveProducts() {
model.setRowCount(0);
try (Connection con = DriverManager.getConnection(url, user, pass);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM products")) {

float totalValue = 0;
while (rs.next()) {
int qty = rs.getInt("quantity");
float price = rs.getFloat("price");
totalValue += qty * price;

model.addRow(new Object[]{
rs.getInt("product_id"),
34
rs.getString("product_name"),
rs.getString("category"),
qty,
price
});

if (qty < 5) {
JOptionPane.showMessageDialog(this, " Low Stock Alert: " +
rs.getString("product_name"), "Stock Warning", JOptionPane.WARNING_MESSAGE);
}
}
JOptionPane.showMessageDialog(this, " Total Inventory Value: ₹" + totalValue);
AppLogger.getLogger().info("Products retrieved. Total value: ₹" + totalValue);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, " Error: " + ex.getMessage());
AppLogger.getLogger().warning("Error retrieving products: " + ex.getMessage());
}
}

void updateProduct() {
try (Connection con = DriverManager.getConnection(url, user, pass)) {
if (tf6.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "Enter Product ID to update", "Warning",
JOptionPane.WARNING_MESSAGE);
return;
}

String name = tf2.getText();


String category = categoryBox.getSelectedItem().toString();
int qty = Integer.parseInt(tf4.getText());
float price = Float.parseFloat(tf5.getText());
int id = Integer.parseInt(tf6.getText());

String query = "UPDATE products SET product_name=?, category=?, quantity=?,


35
price=? WHERE product_id=?";
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, category);
stmt.setInt(3, qty);
stmt.setFloat(4, price);
stmt.setInt(5, id);

int updated = stmt.executeUpdate();


JOptionPane.showMessageDialog(this, updated > 0 ? " Product updated!" : " No
product found.");
AppLogger.getLogger().info("Product updated: ID " + id);
retrieveProducts();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, " Error: " + ex.getMessage());
AppLogger.getLogger().warning("Error updating product: " + ex.getMessage());
}
}

void deleteProduct() {
try (Connection con = DriverManager.getConnection(url, user, pass)) {
if (tf6.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "Enter Product ID to delete", "Warning",
JOptionPane.WARNING_MESSAGE);
return;
}

int id = Integer.parseInt(tf6.getText());
String query = "DELETE FROM products WHERE product_id=?";
PreparedStatement stmt = con.prepareStatement(query);
stmt.setInt(1, id);
int deleted = stmt.executeUpdate();
JOptionPane.showMessageDialog(this, deleted > 0 ? " Product deleted!" : " No
product found.");
36
AppLogger.getLogger().info("Product deleted: ID " + id);
retrieveProducts();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, " Error: " + ex.getMessage());
AppLogger.getLogger().warning("Error deleting product: " + ex.getMessage());
}
}

void searchProducts() {
String searchTerm = searchField.getText().trim().toLowerCase();
if (searchTerm.isEmpty()) {
retrieveProducts();
return;
}

model.setRowCount(0);
try (Connection con = DriverManager.getConnection(url, user, pass)) {
PreparedStatement stmt;

if (searchTerm.matches("\\d+")) {
stmt = con.prepareStatement("SELECT * FROM products WHERE product_id = ?
OR price = ?");
stmt.setInt(1, Integer.parseInt(searchTerm));
stmt.setFloat(2, Float.parseFloat(searchTerm));
} else if (searchTerm.matches("\\d+\\.\\d+")) {
stmt = con.prepareStatement("SELECT * FROM products WHERE price = ?");
stmt.setFloat(1, Float.parseFloat(searchTerm));
} else {
stmt = con.prepareStatement("SELECT * FROM products WHERE
LOWER(product_name) LIKE ?");
stmt.setString(1, "%" + searchTerm + "%");
}

ResultSet rs = stmt.executeQuery();

37
while (rs.next()) {
model.addRow(new Object[]{
rs.getInt("product_id"),
rs.getString("product_name"),
rs.getString("category"),
rs.getInt("quantity"),
rs.getFloat("price")
});
}
AppLogger.getLogger().info("Search performed for: " + searchTerm);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, " Error: " + ex.getMessage());
AppLogger.getLogger().warning("Search error: " + ex.getMessage());
}
}

void clearFields() {
tf1.setText(""); tf2.setText(""); tf4.setText("");
tf5.setText(""); tf6.setText(""); searchField.setText("");
model.setRowCount(0);
JOptionPane.showMessageDialog(this, " All fields cleared!");
AppLogger.getLogger().info("Fields cleared.");
}
}

7.3 Applogger Page Code:

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

38
public class AppLogger {
private static final Logger appLog = Logger.getLogger("CRUDAppLogger");
private static FileHandler fh;

public static void setupLogger() {


try {
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String logFileName = "app_log_" + date + ".log";

fh = new FileHandler(logFileName, true);


fh.setFormatter(new SimpleFormatter());

appLog.addHandler(fh);
appLog.setUseParentHandlers(false);
appLog.info("Logger initialized for session.");
} catch (IOException e) {
e.printStackTrace();
appLog.warning("Failed to set up file logger: " + e.getMessage());
appLog.setUseParentHandlers(true);
}
}

public static Logger getLogger() {


return appLog;
}

public static String getCurrentLogFileName() {


return "app_log_" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) +
".log";
}
}

39

You might also like