Skip to content
parichakraPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

6 Commits

Folders and files

Repository files navigation

ChatApp — Real-Time Chat Application

A full-stack real-time one-on-one chat application built with Spring Boot 3, Spring Security, WebSocket / STOMP, Thymeleaf, and Bootstrap 5.


Table of Contents


Features

Feature Status
Role-based login (Admin / User) ✅
Admin dashboard — create & delete users ✅
One-on-one conversations ✅
Real-time messaging via WebSocket + STOMP ✅
Message history (persisted to DB) ✅
Soft-delete messages ✅
Online / Away / Offline status indicators ✅
Responsive UI (Bootstrap 5) ✅
Auto-generated avatars ✅
H2 in-memory database (dev) ✅
MySQL / PostgreSQL (production-ready) 🔜
Group chat 🔜
File / image attachments 🔜
Typing indicators 🔜
Read receipts 🔜
Push notifications 🔜

Technology Stack

Backend

Technology Version Purpose
Java 21 Language
Spring Boot 3.3.5 Framework
Spring MVC — Web layer
Spring Security — Authentication & authorisation
Spring Data JPA — Database access
Spring WebSocket — Real-time messaging
Hibernate — ORM
Lombok — Boilerplate reduction
H2 Database — In-memory DB (development)
MySQL / PostgreSQL — Production database

Frontend

Technology Purpose
Thymeleaf Server-side templating
Bootstrap 5.3 UI components & responsive layout
Bootstrap Icons 1.11 Icon library
SockJS 1.6 WebSocket fallback transport
STOMP.js 7.0 WebSocket messaging protocol client
Vanilla JavaScript Dynamic UI, real-time rendering

Build

Tool Version
Gradle 9.x (wrapper)
Java toolchain 21

Architecture

Browser
  │
  ├── HTTP (Thymeleaf pages, form submissions)
  │       ↓
  │   Spring MVC Controllers
  │       ↓
  │   Service Layer
  │       ↓
  │   Repository Layer (Spring Data JPA)
  │       ↓
  │   Database (H2 / MySQL)
  │
  └── WebSocket / STOMP (real-time messages)
          ↓
      WsChatController  (@MessageMapping)
          ↓
      Service Layer  (save to DB)
          ↓
      SimpMessagingTemplate  (broadcast to topic)
          ↓
      All subscribers of /topic/conversation.{id}

Layered Design

Presentation  →  Controller  →  Service  →  Repository  →  Database
                     ↑               ↑
                    DTO           Mapper

Project Structure

src/
├── main/
│   ├── java/com/markib/chat/
│   │   ├── ChatApplication.java           # Entry point
│   │   │
│   │   ├── Config/
│   │   │   ├── DataInitializer.java       # Seeds demo users on startup
│   │   │   ├── SecurityConfig.java        # Spring Security rules
│   │   │   └── WebSocketConfig.java       # STOMP / SockJS setup
│   │   │
│   │   ├── Controller/
│   │   │   ├── AdminController.java       # /admin — user management (ADMIN only)
│   │   │   ├── ChatController.java        # /chat/{id} — chat view
│   │   │   ├── ConversationController.java# /conversations
│   │   │   ├── HomeController.java        # / — redirects by role
│   │   │   ├── LoginController.java       # /login
│   │   │   ├── MessageController.java     # /messages/{id}/delete
│   │   │   ├── UserController.java        # /users
│   │   │   └── WsChatController.java      # WebSocket @MessageMapping handler
│   │   │
│   │   ├── Dto/
│   │   │   ├── ChatMessagePayload.java    # Incoming WS message payload
│   │   │   ├── ConversationDto.java
│   │   │   ├── MessageDto.java
│   │   │   └── UserDto.java
│   │   │
│   │   ├── Exception/
│   │   │   ├── GlobalExceptionHandler.java
│   │   │   ├── ConversationNotFoundException.java
│   │   │   ├── MessageNotFoundException.java
│   │   │   └── UserNotFoundException.java
│   │   │
│   │   ├── Mapper/
│   │   │   ├── ConversationMapper.java
│   │   │   ├── MessageMapper.java
│   │   │   └── UserMapper.java
│   │   │
│   │   ├── Model/
│   │   │   ├── BaseEntity.java            # id, createdAt, updatedAt
│   │   │   ├── Conversation.java          # userOne ↔ userTwo
│   │   │   ├── Message.java
│   │   │   ├── MessageStatus.java         # SENT | DELIVERED | READ
│   │   │   ├── MessageType.java           # TEXT | IMAGE | FILE | SYSTEM
│   │   │   ├── Role.java                  # ADMIN | USER
│   │   │   ├── User.java
│   │   │   └── UserStatus.java            # ONLINE | OFFLINE | AWAY
│   │   │
│   │   ├── Repository/
│   │   │   ├── ConversationRepository.java
│   │   │   ├── MessageRepository.java
│   │   │   └── UserRepository.java
│   │   │
│   │   ├── Security/
│   │   │   └── CustomUserDetailsService.java  # Loads user by username for Spring Security
│   │   │
│   │   └── Service/
│   │       ├── ConversationService.java
│   │       ├── MessageService.java
│   │       ├── UserService.java
│   │       └── Impl/
│   │           ├── ConversationServiceImpl.java
│   │           ├── MessageServiceImpl.java
│   │           └── UserServiceImpl.java
│   │
│   └── resources/
│       ├── application.yaml               # App configuration
│       ├── static/
│       │   └── Css/Style.css              # Custom styles
│       └── templates/
│           ├── index.html                 # Home / landing page
│           ├── login.html                 # Login page
│           ├── error.html                 # Global error page
│           ├── admin/
│           │   └── dashboard.html         # Admin user management
│           ├── Chat/
│           │   └── index.html             # Main real-time chat view
│           ├── conversation/
│           │   └── list.html              # Conversation list
│           ├── users/
│           │   ├── list.html              # Browse users
│           │   └── profile.html           # User profile
│           └── Fragments/
│               ├── navbar.html            # Shared navigation bar
│               └── sidebar.html           # Shared sidebar fragment
│
└── test/
    └── java/com/markib/chat/
        └── ChatApplicationTests.java

Data Models

User

Field Type Notes
id Long Auto-generated PK
username String Unique, not null
displayName String
email String Unique
password String BCrypt hashed
role Role ADMIN or USER
avatar String URL (auto-generated if blank)
status UserStatus ONLINE / OFFLINE / AWAY
createdAt LocalDateTime Set on persist
updatedAt LocalDateTime Set on update

Conversation

Field Type Notes
id Long
userOne User ManyToOne
userTwo User ManyToOne
createdAt LocalDateTime

A conversation between the same pair of users is always reused — no duplicates.

Message

Field Type Notes
id Long
conversation Conversation ManyToOne
sender User ManyToOne
content String TEXT column
type MessageType TEXT / IMAGE / FILE / SYSTEM
status MessageStatus SENT / DELIVERED / READ
edited boolean
deleted boolean Soft delete flag
createdAt LocalDateTime

Security & Authentication

Spring Security with form-based login.

Path Access
/login Public
/ws/** Public (WebSocket handshake)
/admin/** ROLE_ADMIN only
All other paths Any authenticated user

Password encoding: BCrypt via BCryptPasswordEncoder.

CSRF: Enabled for all HTTP endpoints. Disabled only for /ws/** (WebSocket STOMP frames use a different transport) and /h2-console/**.


Real-Time Messaging (WebSocket)

The app uses STOMP over SockJS for real-time message delivery.

Flow

1. Browser connects to SockJS endpoint:  ws://host/ws
2. On connect, browser subscribes to:    /topic/conversation.{id}
3. User types and submits message form
4. Browser publishes STOMP message to:   /app/chat.{conversationId}
5. WsChatController receives it, saves to DB, maps to MessageDto
6. Server broadcasts MessageDto to:      /topic/conversation.{id}
7. Both browser tabs (sender + recipient) receive the frame and render the bubble

Endpoints

Direction Destination Description
Client → Server /app/chat.{conversationId} Send a message
Server → Client /topic/conversation.{id} Receive messages for a conversation
Handshake /ws (SockJS) WebSocket connection endpoint

Getting Started

Prerequisites

  • Java 21+
  • Git

Clone & Run

git clone https://github.com/your-username/chat.git
cd chat

# Make Gradle wrapper executable (Linux/macOS)
chmod +x gradlew

# Run the application
./gradlew bootRun

Open your browser at: http://localhost:8000

Build JAR

./gradlew build -x test
java -jar build/libs/chat-0.0.1-SNAPSHOT.jar

Run Tests

./gradlew test

Default Credentials

These are seeded automatically on first startup by DataInitializer.

Username Password Role Notes
admin admin123 ADMIN Full access, can create/delete users
alice alice123 USER Demo chat user
bob bob123 USER Demo chat user
carol carol123 USER Demo chat user

Change these credentials before any deployment outside your local machine.


Configuration

All configuration lives in src/main/resources/application.yaml.

spring:
  datasource:
    url: jdbc:h2:mem:chatdb   # In-memory H2 (data lost on restart)
    username: sa
    password:

  h2:
    console:
      enabled: true           # http://localhost:8000/h2-console

  jpa:
    hibernate:
      ddl-auto: create-drop   # Re-creates schema on every restart

server:
  port: 8000

Switching to MySQL / PostgreSQL

  1. Add the driver dependency to build.gradle:

    runtimeOnly 'com.mysql:mysql-connector-j'
    // or
    runtimeOnly 'org.postgresql:postgresql'
  2. Update application.yaml:

    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/chatdb
        username: your_user
        password: your_password
        driver-class-name: com.mysql.cj.jdbc.Driver
      jpa:
        hibernate:
          ddl-auto: update   # or 'validate' with Flyway migrations
        properties:
          hibernate:
            dialect: org.hibernate.dialect.MySQLDialect
  3. Disable H2 console:

    spring:
      h2:
        console:
          enabled: false

API / URL Reference

Pages (GET)

URL Access Description
/ Authenticated Home — redirects by role
/login Public Login page
/admin ADMIN Admin dashboard
/users USER Browse other users
/users/{id} Authenticated User profile
/users/{id}/chat USER Start/open chat with user
/conversations Authenticated List conversations
/conversations/start?userTwoId={id} Authenticated Create or find conversation
/chat/{conversationId} Authenticated Chat view
/h2-console Public (dev) H2 database console

Actions (POST)

URL Access Description
/login Public Spring Security login processing
/logout Authenticated Spring Security logout
/admin/users ADMIN Create new user
/admin/users/{id}/delete ADMIN Delete user
/messages/{id}/delete Authenticated Soft-delete own message

WebSocket

Destination Direction Description
/ws Handshake SockJS endpoint
/app/chat.{conversationId} Client → Server Send message
/topic/conversation.{conversationId} Server → Client Receive message broadcast

Roadmap

  • MySQL / PostgreSQL support with Flyway migrations
  • Typing indicator over WebSocket
  • Message read receipts
  • User online/offline status via WebSocket presence
  • Image / file attachment upload
  • Emoji reactions
  • Group conversations
  • Search messages and users
  • Docker + Docker Compose setup
  • Unit and integration tests
  • API documentation with Swagger / OpenAPI
  • Email notifications
  • Dark mode

License

This project is open source and available under the MIT License.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages