Skip to content

dolamasa1/Java-Spring-B-messenger-backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

10 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿš€ Java Messenger Backend (Spring Boot)

A high-performance, real-time messaging platform built with Java Spring Boot, featuring comprehensive API endpoints, dual WebSocket implementations, and enterprise-grade security.

Spring Boot Java MySQL WebSocket Socket.IO Status

๐Ÿ“– Overview

Java Messenger Backend is a sophisticated, production-ready messaging platform built with Spring Boot that provides:

  • ๐Ÿ’ฌ Real-time messaging with dual WebSocket implementations
  • ๐Ÿ” JWT authentication with refresh token rotation
  • ๐Ÿ‘ฅ Group chat with member management
  • ๐Ÿ“ File sharing with multiple media types
  • ๐Ÿ‘ค User presence and typing indicators
  • ๐Ÿฅ Health monitoring with connection statistics

Developed by: Ahmed Adel


๐Ÿ› ๏ธ Technology Stack

Layer Technology Purpose
Backend Framework Spring Boot 3.2.0 REST API & WebSocket server
Language Java 17 Core application logic
Database MySQL 8.0 Data persistence
ORM Spring Data JPA / Hibernate Database operations
Security Spring Security + JWT Authentication & authorization
Real-time Spring WebSocket + Socket.IO Dual real-time implementations
File Handling MultipartFile + FileService File upload/download
Build Tool Maven Dependency management
JSON Processing Jackson Data serialization

๐Ÿš€ Quick Start

Prerequisites

  • Java 17 or higher
  • MySQL 8.0 or higher
  • Maven 3.6+

1. Database Setup

CREATE DATABASE messenger_db;
CREATE USER 'messenger_user'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON messenger_db.* TO 'messenger_user'@'localhost';
FLUSH PRIVILEGES;

2. Configuration

Update src/main/resources/application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/messenger_db
spring.datasource.username=messenger_user
spring.datasource.password=password
server.port=8080
app.jwt.secret=your-super-secure-jwt-secret-key-here
app.frontend.url=http://localhost:3000

3. Build & Run

# Build the application
mvn clean install

# Run the application
mvn spring-boot:run

# Or run the JAR directly
java -jar target/raven-messenger-backend-*.jar

Application will be available at: http://localhost:8080


๐Ÿ“ก API Endpoints

๐Ÿ” Authentication Endpoints

Method Endpoint Description Auth Required
POST /api/auth/register User registration โŒ
POST /api/auth/login User login (JSON body or query params) โŒ
POST /api/auth/logout User logout โœ…
POST /api/auth/refresh Refresh JWT token โŒ
GET /api/auth/verify Token verification โœ…

๐Ÿ‘ฅ User Management

Method Endpoint Description Auth Required
GET /api/user/ Get all users with search โœ…
GET /api/user/find Find user/group by ID โœ…
GET /api/user/profile Get user profile by username โœ…
GET /api/user/get Get user by UUID or ID โœ…
GET /api/user/check-exists Check if user exists by ID โœ…

๐Ÿ’ฌ Messaging

Method Endpoint Description Auth Required
GET /api/message/message Get messages (user/group) โœ…
POST /api/message/send Send text message โœ…
POST /api/message/upload Upload file message โœ…
GET /api/message/download Download files โœ…
POST /api/enhanced-message/send Enhanced message with real-time delivery โœ…
POST /api/enhanced-message/typing Send typing indicator โœ…

๐Ÿ‘ค Profile Management

Method Endpoint Description Auth Required
GET /api/profile/ Get my profile โœ…
PUT /api/profile/image Update profile image โœ…
PUT /api/profile/user Update username โœ…
PUT /api/profile/phone Update phone number โœ…
PUT /api/profile/gender Update gender โœ…
PUT /api/profile/bio Update bio โœ…

๐Ÿ‘ฅ Group Management

Method Endpoint Description Auth Required
GET /api/group/check Check group details by UUID โœ…
POST /api/group/create Create new group โœ…
POST /api/group/join Join existing group โœ…
GET /api/group/member Get group members โœ…

๐Ÿฉบ Health & Monitoring

Method Endpoint Description Auth Required
GET /api/health Application health check โŒ
GET /api/check/ Version compatibility โŒ

๐Ÿงช Testing Endpoints

Method Endpoint Description Auth Required
POST /api/test/signin Quick sign-in test โŒ
GET /api/test/users Load users list test โœ…
GET /api/test/open-chat Open chat test โœ…
POST /api/test/send-message Send message test โœ…
GET /api/test/full-flow Complete business flow test โŒ

๐Ÿ”Œ Real-time Communication

โšก Dual WebSocket Implementation

1. Native Spring WebSocket

// Connect to WebSocket endpoint
const ws = new WebSocket('ws://localhost:8080/ws/messages?token=YOUR_JWT_TOKEN');

// Send authentication message
ws.onopen = () => {
  ws.send(JSON.stringify({
    type: 'AUTH',
    token: 'YOUR_JWT_TOKEN'
  }));
};

// Handle incoming messages
ws.onmessage = (event) => {
  const message = JSON.parse(event.data);
  console.log('Received:', message);
};

// Send message
ws.send(JSON.stringify({
  type: 'SEND_MESSAGE',
  toUserId: 123,
  message: 'Hello!'
}));

2. Socket.IO Implementation

const socket = io('http://localhost:5001', {
  query: { token: 'YOUR_JWT_TOKEN' },
  transports: ['websocket', 'polling']
});

// Connection events
socket.on('connect', () => {
  console.log('Connected to Socket.IO server');
});

socket.on('connected', (data) => {
  console.log('Authenticated:', data);
});

// Send message
socket.emit('message', {
  type: 'user',
  target: 123,
  message_type: 't',
  message: 'Hello from Socket.IO!',
  from_name: 'John Doe'
});

// Join room (for group chats)
socket.emit('join_room', {
  roomId: 'group_123'
});

// Typing indicators
socket.emit('typing_start', {
  type: 'USER',
  target: 123
});

socket.emit('typing_stop', {
  type: 'USER', 
  target: 123
});

// Receive messages
socket.on('message', (data) => {
  console.log('New message:', data);
});

// User status updates
socket.on('user_status', (data) => {
  console.log('User status:', data);
});

Real-time Features

  • Message Delivery: Instant message delivery to online users
  • Typing Indicators: Real-time typing notifications
  • User Presence: Online/offline status tracking
  • Message Status: Read receipts and delivery confirmations
  • Offline Queue: Message queuing for offline users

๐Ÿ—ƒ๏ธ Database Schema

Core Entities

  • User - User accounts and profiles with UUID
  • Message - Text and file messages with UUID
  • Group - Chat groups with UUID and JSON profile storage
  • Member - Group membership with join dates
  • FileEntity - File storage metadata
  • RefreshToken - JWT refresh tokens with secure hashing

Entity Relationships

User 1โ”€โ”€โ”€N Message (as sender)
User 1โ”€โ”€โ”€N Member (group membership)  
Group 1โ”€โ”€โ”€N Message
Group 1โ”€โ”€โ”€N Member
Message 1โ”€โ”€1 FileEntity (optional, for file messages)

Key Features

  • UUID Primary Keys: Secure identifier generation
  • JSON Profile Storage: Flexible profile data structure
  • Soft Deletes: Status-based entity management
  • Audit Fields: Automatic timestamp management

๐Ÿ”’ Security Implementation

Authentication & Authorization

  • JWT Authentication with configurable expiration
  • Refresh Token Rotation for secure long-term sessions
  • BCrypt Password Hashing (strength 12)
  • HttpOnly Cookies for secure token storage
  • Bearer Token Support via Authorization header

API Protection

  • Spring Security with method-level security
  • CORS Protection with configurable origins
  • Version Checking middleware for client compatibility
  • Input Validation with comprehensive error handling

Real-time Security

  • JWT WebSocket Authentication for both implementations
  • Session Management with connection tracking
  • Message Validation and permission checking

๐Ÿ“Š Advanced Features

Unified Connection Service

// Send message via best available channel
boolean delivered = unifiedConnectionService.sendToUser(
    userId, 
    "new_message", 
    messageData
);

// Get connection statistics
Map<String, Object> stats = unifiedConnectionService.getConnectionStatistics();

Message Queue Service

  • Offline Message Queuing for disconnected users
  • Automatic Retry Mechanism with exponential backoff
  • Message Expiration (24-hour TTL)
  • Delivery Status Tracking

Enhanced Message Controller

  • Real-time Delivery Confirmation
  • Typing Indicators
  • Message Read Receipts
  • Connection Statistics

๐Ÿงช Testing & Development

Quick Testing Sequence

# 1. Health Check
curl http://localhost:8080/api/health

# 2. Register User
curl -X POST http://localhost:8080/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "userName": "testuser",
    "password": "password123",
    "firstName": "Test",
    "lastName": "User",
    "gender": "M"
  }'

# 3. Login (JSON body)
curl -X POST http://localhost:8080/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "testuser",
    "password": "password123"
  }'

# 4. Login (Node.js style - query params)
curl -X POST "http://localhost:8080/api/auth/login?user=testuser&password=password123"

# 5. Send Message (using JWT from login)
curl -X POST "http://localhost:8080/api/message/send?toUserId=2&message=Hello" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

# 6. Test Complete Flow
curl "http://localhost:8080/api/test/full-flow?username=testuser&password=password123&targetUserId=2&message=Test"

Development Endpoints

  • /api/test/debug-session - Debug current authentication
  • /api/user/debug - Debug user data and serialization
  • /api/message/debug/messages - Debug message functionality

๐Ÿ”ง Configuration

Application Properties

# Server Configuration
server.port=8080

# Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/messenger_db
spring.datasource.username=your_username
spring.datasource.password=your_password

# JWT Configuration
app.jwt.secret=your-super-secure-jwt-secret-key
app.jwt.expiration-ms=86400000  # 24 hours
app.jwt.refresh-expiration-ms=2592000000  # 30 days

# WebSocket Configuration
app.websocket.type=socketio  # native, socketio, both
app.websocket.native.enabled=true
app.websocket.socketio.enabled=true
app.websocket.socketio.port=5001

# CORS Configuration
app.frontend.url=http://localhost:3000

Socket.IO Configuration

  • Port: 5001 (separate from HTTP server)
  • CORS: Configurable origins
  • Transports: WebSocket and HTTP long-polling
  • Authentication: JWT token validation

๐Ÿš€ Deployment

Production Environment Variables

export SPRING_DATASOURCE_URL=jdbc:mysql://your-production-db:3306/messenger_db
export SPRING_DATASOURCE_USERNAME=your_production_user
export SPRING_DATASOURCE_PASSWORD=your_secure_password
export APP_JWT_SECRET=your-very-secure-production-jwt-secret
export APP_FRONTEND_URL=https://your-frontend-domain.com

Docker Deployment

FROM openjdk:17-jdk-slim

# Install necessary packages
RUN apt-get update && apt-get install -y curl

# Create app directory
WORKDIR /app

# Copy JAR file
COPY target/raven-messenger-backend-*.jar app.jar

# Expose ports
EXPOSE 8080 5001

# Health check
HEALTHCHECK --interval=30s --timeout=3s \
  CMD curl -f http://localhost:8080/api/health || exit 1

# Run the application
ENTRYPOINT ["java", "-jar", "app.jar"]

Production Recommendations

  • Use environment-specific configuration profiles
  • Configure database connection pooling
  • Enable SSL/TLS for secure connections
  • Set up proper logging and monitoring
  • Use process manager (systemd, PM2, etc.)
  • Configure reverse proxy (Nginx) for load balancing

๐Ÿ“ˆ Performance Features

โœ… Implemented Optimizations

  • Connection Pooling with HikariCP
  • JPA Lazy Loading for related entities
  • Efficient File Storage with metadata tracking
  • Dual WebSocket Support for client flexibility
  • Message Pagination for large datasets
  • Connection Management with session tracking

๐Ÿ”„ Real-time Performance

  • Unified Connection Service for optimal channel selection
  • Message Queue Service for offline user support
  • Connection Statistics for monitoring and optimization
  • Efficient Broadcasting for group messages

๐Ÿ› Troubleshooting

Common Issues

  1. Database Connection Issues

    # Check MySQL service
    sudo systemctl status mysql
    
    # Test connection
    mysql -u your_user -p your_database
  2. JWT Authentication Issues

    • Verify JWT secret in application properties
    • Check token expiration settings
    • Ensure proper token format in requests
  3. WebSocket Connection Issues

    • Verify CORS configuration
    • Check Socket.IO server on port 5001
    • Validate JWT tokens for WebSocket connections
  4. File Upload Issues

    • Check upload directory permissions
    • Verify multipart configuration
    • Check file size limits

Logs and Monitoring

The application provides comprehensive logging:

  • Request/response logging with timing
  • Database connection events
  • Authentication attempts and failures
  • WebSocket connection status
  • Real-time message delivery tracking

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Guidelines

  • Follow Spring Boot best practices
  • Maintain comprehensive logging
  • Include proper error handling
  • Update documentation for new features
  • Test both REST API and WebSocket functionality
  • Ensure backward compatibility with existing clients

๐Ÿ“„ License

MIT License - see LICENSE file for details.

๐Ÿ‘จโ€๐Ÿ’ป Developer

Ahmed Adel
๐Ÿ“ง Email: [email protected]
๐ŸŒ GitHub: dolamasa1


๐Ÿ”ฎ Roadmap

Next Version (v1.1)

  • Advanced message encryption
  • Push notifications integration
  • Advanced search with message content
  • Admin dashboard for user management
  • Message export functionality

Future Enhancements

  • Microservices architecture exploration
  • Kubernetes deployment configurations
  • Advanced analytics and monitoring
  • Multi-tenant support
  • Advanced caching with Redis

โš ๏ธ Important Notes

  • Production Ready: All core features are implemented and stable
  • Dual Real-time Support: Both Spring WebSocket and Socket.IO implementations
  • Comprehensive Security: JWT authentication with refresh tokens
  • Scalable Architecture: Connection pooling and efficient resource usage
  • Comprehensive Logging: Detailed logging for debugging and monitoring

This project represents a production-grade Spring Boot backend with enterprise-ready messaging capabilities.


Built with โค๏ธ using Spring Boot and Java - Enterprise-ready messaging platform

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages