0% found this document useful (0 votes)
8 views24 pages

Java Cat 2

k

Uploaded by

preethinathan91
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)
8 views24 pages

Java Cat 2

k

Uploaded by

preethinathan91
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/ 24

COIMBATORE INSTITUTE OF TECHNOLOGY

(An Autonomous Institution Affiliated to Anna University)


COIMBATORE – 641014.

PROJECT TITLE:
"LIBRARY MANAGEMENT SYSTEM"

TEAM MEMBERS : POOJITHA T 2303717672622042


PREETHI NATHAN S 2303717672622044
DEPARTMENT : MSc SOFTWARE SYSTEMS
BATCH : 2023 – 2028
COURSE CODE : 20MSS48
COURSE NAME : JAVA PROGRAMMING LABORATORY
ABSTRACT:
The Library Management System (LMS) is designed to streamline the
management of library operations, enhance user experience, and facilitate
effective tracking of books and user activities within a library setting. This
system is built using Java, Java Swing, and MySQL database to manage users,
books, and borrowing activities. The system provides a graphical user interface
(GUI) for both administrators and regular users, enabling them to interact
seamlessly with the library's resources.
The LMS is structured into several key components:
1. Database Integration: A robust MySQL database stores data related to
users, books, borrowed books, and user roles. The system interacts with
the database using SQL queries to perform operations such as adding,
removing, borrowing, and returning books.
2. User Authentication: Users can log into the system via a login screen,
where they enter their credentials (username and password). A secure
password hashing mechanism is employed to ensure user data safety.
New users can register by providing a username, password, and role
(admin or user).
3. Book Management: Books can be added, deleted, and borrowed by
users. The system tracks the availability of books in real-time, ensuring
that users are aware of the current status of book availability before
borrowing. The available copies of each book are updated dynamically as
books are borrowed or returned.
4. Role-based Access: The system includes role-based access control where
the administrator has additional privileges such as adding or deleting
books, while regular users are limited to borrowing, returning, and
viewing books.
5. Borrowing and Returning Books: The system provides functionalities for
users to borrow books and track their due dates. Books are reserved for
a 14-day period, after which the user can either return the book or
extend the borrowing period.
6. Borrowed Books Management: A section allows users to view their
borrowed books and check their due dates, ensuring proper
management and timely return of books.
7. Error Handling: The system has been designed to handle potential errors
such as incorrect login credentials, duplicate usernames during
registration, and attempts to borrow unavailable books, providing useful
feedback to users for an enhanced experience.
The system’s design is flexible and scalable, allowing for easy addition of new
features, such as overdue book management, fines, or integration with online
catalogs. Through its user-friendly interface and efficient database
management, the Library Management System simplifies the day-to-day tasks
of library administrators and enhances the reading experience for users. This
LMS also aims to promote efficient book usage, reduce human errors, and
ensure better inventory control for libraries.
In conclusion, this Library Management System aims to automate the majority
of administrative tasks in a library setting while offering an intuitive user
interface for both users and administrators. By integrating a relational database,
role-based access, and real-time book tracking, it offers an effective solution to
modernize library management systems and improve overall operational
efficiency.

SOURCE CODE:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.util.Random;

public class LibraryManagementSystem {


private static Connection connection;
private static JFrame frame;
private static String currentUsername;
private static String currentRole;
private static DefaultListModel<Book> bookListModel;
private static JList<Book> bookJList;

public static void main(String[] args) {


connectDatabase();
showWelcomeScreen();
}

// --- Database Connection ---


private static void connectDatabase() {
try {
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/library_db", "root", "preethi123");
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Database Connection Failed!\n"
+ e.getMessage());
System.exit(1);
}
}

// --- Book Class ---


static class Book {
String id;
String title;
String author;
int availableCopies;
int totalCopies;

Book(String id, String title, String author, int availableCopies, int


totalCopies) {
this.id = id;
this.title = title;
this.author = author;
this.availableCopies = availableCopies;
this.totalCopies = totalCopies;
}

public String toString() {


return String.format("%-4s %-30s %-20s [%d/%d]", id, title, author,
availableCopies, totalCopies);
}
}

// --- Welcome Screen ---


private static void showWelcomeScreen() {

frame = new JFrame("� Library Management System �");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLayout(new GridLayout(4, 1, 10, 10));
frame.setLocationRelativeTo(null);
JLabel title = new JLabel("Welcome to Library", SwingConstants.CENTER);
title.setFont(new Font("Verdana", Font.BOLD, 20));
frame.add(title);

JButton loginButton = new JButton("Login");


JButton signupButton = new JButton("Signup");
JButton exitButton = new JButton("Exit");

loginButton.addActionListener(e -> showLoginScreen());


signupButton.addActionListener(e -> showSignupScreen());
exitButton.addActionListener(e -> System.exit(0));

frame.add(loginButton);
frame.add(signupButton);
frame.add(exitButton);

frame.setVisible(true);
}

// --- Login Screen ---


private static void showLoginScreen() {
JTextField usernameField = new JTextField();
JPasswordField passwordField = new JPasswordField();

Object[] fields = {
"Username:", usernameField,
"Password:", passwordField
};

int option = JOptionPane.showConfirmDialog(frame, fields, "Login",


JOptionPane.OK_CANCEL_OPTION);

if (option == JOptionPane.OK_OPTION) {
String username = usernameField.getText().trim();
String password = String.valueOf(passwordField.getPassword()).trim();

if (username.isEmpty() || password.isEmpty()) {
JOptionPane.showMessageDialog(frame, "Fields cannot be empty!");
return;
}

try {
String query = "SELECT * FROM users WHERE username = ?";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, username);
ResultSet rs = stmt.executeQuery();

if (rs.next()) {
String storedHash = rs.getString("password_hash");
String role = rs.getString("role");

if (storedHash.equals(hashPassword(password))) {
currentUsername = username;
currentRole = role;
JOptionPane.showMessageDialog(frame, "Login Successful!");
showLibraryDashboard();
} else {
JOptionPane.showMessageDialog(frame, "Incorrect password!");
}
} else {
JOptionPane.showMessageDialog(frame, "User not found!");
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(frame, "Database error: " +
ex.getMessage());
}
}
}

// --- Signup Screen ---


private static void showSignupScreen() {
JTextField usernameField = new JTextField();
JPasswordField passwordField = new JPasswordField();
JComboBox<String> roleBox = new JComboBox<>(new String[] { "user",
"admin" });

Object[] fields = {
"Username:", usernameField,
"Password:", passwordField,
"Role:", roleBox
};

int option = JOptionPane.showConfirmDialog(frame, fields, "Signup",


JOptionPane.OK_CANCEL_OPTION);

if (option == JOptionPane.OK_OPTION) {
String username = usernameField.getText().trim();
String password = String.valueOf(passwordField.getPassword()).trim();
String role = (String) roleBox.getSelectedItem();

if (username.isEmpty() || password.isEmpty()) {
JOptionPane.showMessageDialog(frame, "Fields cannot be empty!");
return;
}

try {
String checkQuery = "SELECT * FROM users WHERE username = ?";
PreparedStatement checkStmt =
connection.prepareStatement(checkQuery);
checkStmt.setString(1, username);
ResultSet rs = checkStmt.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(frame, "Username already
exists!");
return;
}
String query = "INSERT INTO users (username, password_hash, role)
VALUES (?, ?, ?)";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, username);
stmt.setString(2, hashPassword(password));
stmt.setString(3, role);
stmt.executeUpdate();

JOptionPane.showMessageDialog(frame, "Signup Successful! Now


login.");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(frame, "Database error: " +
ex.getMessage());
}
}
}

// --- Dashboard ---


private static void showLibraryDashboard() {
frame.getContentPane().removeAll();
frame.setLayout(new BorderLayout(10, 10));
frame.setSize(900, 500);

JLabel welcomeLabel = new JLabel("Welcome " + currentUsername + " (" +


currentRole + ")",
SwingConstants.CENTER);
welcomeLabel.setFont(new Font("Arial", Font.BOLD, 20));
frame.add(welcomeLabel, BorderLayout.NORTH);

bookListModel = new DefaultListModel<>();


bookJList = new JList<>(bookListModel);
bookJList.setFont(new Font("Monospaced", Font.PLAIN, 14));
JScrollPane scrollPane = new JScrollPane(bookJList);
frame.add(scrollPane, BorderLayout.CENTER);

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


frame.add(buttonPanel, BorderLayout.SOUTH);

JButton borrowButton = new JButton("Borrow Book");


JButton returnButton = new JButton("Return Book");
JButton addButton = new JButton("Add Book");
JButton deleteButton = new JButton("Delete Book");
JButton viewBorrowedButton = new JButton("View Borrowed Books");
JButton logoutButton = new JButton("Logout");

borrowButton.addActionListener(e -> borrowBook());


returnButton.addActionListener(e -> returnBook());
viewBorrowedButton.addActionListener(e -> viewBorrowedBooks());
addButton.addActionListener(e -> addBook());
deleteButton.addActionListener(e -> deleteBook());
logoutButton.addActionListener(e -> logout());
buttonPanel.add(borrowButton);
buttonPanel.add(returnButton);
buttonPanel.add(viewBorrowedButton);
if (currentRole.equals("admin")) {
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
}
buttonPanel.add(logoutButton);

loadBooks();
frame.revalidate();
frame.repaint();
}

// --- Load Books ---


private static void loadBooks() {
try {
bookListModel.clear();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM books ORDER BY id
ASC");

while (rs.next()) {
bookListModel.addElement(new Book(
rs.getString("id"),
rs.getString("title"),
rs.getString("author"),
rs.getInt("available_copies"),
rs.getInt("total_copies")));
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(frame, "Error loading books: " +
e.getMessage());
}
}

// --- Borrow Book ---


private static void borrowBook() {
Book selected = bookJList.getSelectedValue();
if (selected == null) {
JOptionPane.showMessageDialog(frame, "Select a book first!");
return;
}
if (selected.availableCopies <= 0) {
JOptionPane.showMessageDialog(frame, "No copies available!");
return;
}

try {
String query = "INSERT INTO borrowed_books (user_id, book_id,
borrow_date, due_date) VALUES ((SELECT id FROM users WHERE username
= ?), ?, ?, ?)";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, currentUsername);
stmt.setString(2, selected.id);
stmt.setDate(3, java.sql.Date.valueOf(LocalDate.now()));
stmt.setDate(4, java.sql.Date.valueOf(LocalDate.now().plusDays(14)));
stmt.executeUpdate();

String updateQuery = "UPDATE books SET available_copies =


available_copies - 1 WHERE id = ?";
PreparedStatement updateStmt =
connection.prepareStatement(updateQuery);
updateStmt.setString(1, selected.id);
updateStmt.executeUpdate();

JOptionPane.showMessageDialog(frame, "Book Borrowed!");


loadBooks();
} catch (SQLException e) {
JOptionPane.showMessageDialog(frame, "Error borrowing book: " +
e.getMessage());
}
}

// --- Return Book ---


private static void returnBook() {
Book selected = bookJList.getSelectedValue();
if (selected == null) {
JOptionPane.showMessageDialog(frame, "Select a book first!");
return;
}
try {
String query = "DELETE FROM borrowed_books WHERE user_id =
(SELECT id FROM users WHERE username = ?) AND book_id = ? LIMIT 1";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, currentUsername);
stmt.setString(2, selected.id);
int rows = stmt.executeUpdate();

if (rows == 0) {
JOptionPane.showMessageDialog(frame, "You have not borrowed this
book!");
return;
}

String updateQuery = "UPDATE books SET available_copies =


available_copies + 1 WHERE id = ?";
PreparedStatement updateStmt =
connection.prepareStatement(updateQuery);
updateStmt.setString(1, selected.id);
updateStmt.executeUpdate();

JOptionPane.showMessageDialog(frame, "Book Returned!");


loadBooks();
} catch (SQLException e) {
JOptionPane.showMessageDialog(frame, "Error returning book: " +
e.getMessage());
}
}

// --- Add Book (Admin) ---


private static void addBook() {
JTextField titleField = new JTextField();
JTextField authorField = new JTextField();
JTextField copiesField = new JTextField();

Object[] fields = {
"Title:", titleField,
"Author:", authorField,
"Copies:", copiesField
};

int option = JOptionPane.showConfirmDialog(frame, fields, "Add New


Book", JOptionPane.OK_CANCEL_OPTION);

if (option == JOptionPane.OK_OPTION) {
String title = titleField.getText().trim();
String author = authorField.getText().trim();
int copies;
try {
copies = Integer.parseInt(copiesField.getText().trim());
if (copies <= 0)
throw new Exception();
} catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Invalid number of copies!");
return;
}

try {
String bookId = generateBookId();
String query = "INSERT INTO books (id, title, author, available_copies,
total_copies) VALUES (?, ?, ?, ?, ?)";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, bookId);
stmt.setString(2, title);
stmt.setString(3, author);
stmt.setInt(4, copies);
stmt.setInt(5, copies);
stmt.executeUpdate();

JOptionPane.showMessageDialog(frame, "Book added! ID: " + bookId);


loadBooks();
} catch (SQLException e) {
JOptionPane.showMessageDialog(frame, "Error adding book: " +
e.getMessage());
}
}
}

// --- Delete Book (Admin) ---


private static void deleteBook() {
Book selected = bookJList.getSelectedValue();
if (selected == null) {
JOptionPane.showMessageDialog(frame, "Select a book first!");
return;
}

int confirm = JOptionPane.showConfirmDialog(frame, "Are you sure you


want to delete this book?",
"Confirm Delete", JOptionPane.YES_NO_OPTION);
if (confirm != JOptionPane.YES_OPTION)
return;

try {
String deleteQuery = "DELETE FROM books WHERE id = ?";
PreparedStatement deleteStmt =
connection.prepareStatement(deleteQuery);
deleteStmt.setString(1, selected.id);
deleteStmt.executeUpdate();

JOptionPane.showMessageDialog(frame, "Book deleted!");


loadBooks();
} catch (SQLException e) {
JOptionPane.showMessageDialog(frame, "Error deleting book: " +
e.getMessage());
}
}

// --- View Borrowed Books ---


private static void viewBorrowedBooks() {
try {
String query = "SELECT b.title, bb.borrow_date, bb.due_date " +
"FROM borrowed_books bb JOIN books b ON bb.book_id = b.id " +
"WHERE bb.user_id = (SELECT id FROM users WHERE username
= ?)";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, currentUsername);
ResultSet rs = stmt.executeQuery();

StringBuilder borrowedList = new StringBuilder();


while (rs.next()) {
borrowedList.append("Title: ").append(rs.getString("title"))
.append("\nBorrowed On: ").append(rs.getDate("borrow_date"))
.append("\nDue On: ").append(rs.getDate("due_date"))
.append("\n\n");
}

if (borrowedList.length() == 0) {
JOptionPane.showMessageDialog(frame, "You have not borrowed any
books!");
} else {
JTextArea textArea = new JTextArea(borrowedList.toString());
textArea.setEditable(false);
JOptionPane.showMessageDialog(frame, new JScrollPane(textArea),
"Your Borrowed Books",
JOptionPane.INFORMATION_MESSAGE);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(frame, "Error fetching borrowed
books: " + e.getMessage());
}
}

// --- Logout ---


private static void logout() {
currentUsername = null;
currentRole = null;
frame.dispose();
showWelcomeScreen();
}

// --- Hash Password ---


private static String hashPassword(String password) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest(password.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hash)
hexString.append(String.format("%02x", b));
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
return null;
}
}
// --- Generate Random Book ID ---
private static String generateBookId() {
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder id = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 4; i++) {
id.append(chars.charAt(random.nextInt(chars.length())));
}
return id.toString();
}
}

OUTPUT:

You might also like