A high-performance, real-time messaging platform built with Java Spring Boot, featuring comprehensive API endpoints, dual WebSocket implementations, and enterprise-grade security.
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
| 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 |
- Java 17 or higher
- MySQL 8.0 or higher
- Maven 3.6+
CREATE DATABASE messenger_db;
CREATE USER 'messenger_user'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON messenger_db.* TO 'messenger_user'@'localhost';
FLUSH PRIVILEGES;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# Build the application
mvn clean install
# Run the application
mvn spring-boot:run
# Or run the JAR directly
java -jar target/raven-messenger-backend-*.jarApplication will be available at: http://localhost:8080
| 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 | โ |
| 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 | โ |
| 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 | โ |
| 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 | โ |
| 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 | โ |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
GET |
/api/health |
Application health check | โ |
GET |
/api/check/ |
Version compatibility | โ |
| 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 | โ |
// 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!'
}));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);
});- 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
User- User accounts and profiles with UUIDMessage- Text and file messages with UUIDGroup- Chat groups with UUID and JSON profile storageMember- Group membership with join datesFileEntity- File storage metadataRefreshToken- JWT refresh tokens with secure hashing
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)
- UUID Primary Keys: Secure identifier generation
- JSON Profile Storage: Flexible profile data structure
- Soft Deletes: Status-based entity management
- Audit Fields: Automatic timestamp management
- 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
- Spring Security with method-level security
- CORS Protection with configurable origins
- Version Checking middleware for client compatibility
- Input Validation with comprehensive error handling
- JWT WebSocket Authentication for both implementations
- Session Management with connection tracking
- Message Validation and permission checking
// Send message via best available channel
boolean delivered = unifiedConnectionService.sendToUser(
userId,
"new_message",
messageData
);
// Get connection statistics
Map<String, Object> stats = unifiedConnectionService.getConnectionStatistics();- Offline Message Queuing for disconnected users
- Automatic Retry Mechanism with exponential backoff
- Message Expiration (24-hour TTL)
- Delivery Status Tracking
- Real-time Delivery Confirmation
- Typing Indicators
- Message Read Receipts
- Connection Statistics
# 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"/api/test/debug-session- Debug current authentication/api/user/debug- Debug user data and serialization/api/message/debug/messages- Debug message functionality
# 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- Port: 5001 (separate from HTTP server)
- CORS: Configurable origins
- Transports: WebSocket and HTTP long-polling
- Authentication: JWT token validation
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.comFROM 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"]- 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
- 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
- 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
-
Database Connection Issues
# Check MySQL service sudo systemctl status mysql # Test connection mysql -u your_user -p your_database
-
JWT Authentication Issues
- Verify JWT secret in application properties
- Check token expiration settings
- Ensure proper token format in requests
-
WebSocket Connection Issues
- Verify CORS configuration
- Check Socket.IO server on port 5001
- Validate JWT tokens for WebSocket connections
-
File Upload Issues
- Check upload directory permissions
- Verify multipart configuration
- Check file size limits
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
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- 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
MIT License - see LICENSE file for details.
Ahmed Adel
๐ง Email: [email protected]
๐ GitHub: dolamasa1
- Advanced message encryption
- Push notifications integration
- Advanced search with message content
- Admin dashboard for user management
- Message export functionality
- Microservices architecture exploration
- Kubernetes deployment configurations
- Advanced analytics and monitoring
- Multi-tenant support
- Advanced caching with Redis
- 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