- Overview
- Architecture
- Services
- Setup & Deployment
- Database Schema
- API Endpoints
- Frontend
- Development
- Backup System
- Configuration
HabitTracker is a comprehensive habit tracking application built with a microservices architecture. It helps users track daily habits, maintain streaks, and monitor progress over time.
- Daily Habit Tracking: Track completion of habits on a daily basis
- Streak Calculation: Automatic calculation and maintenance of habit streaks
- Flexible Scheduling: Support for different habit frequencies (daily, every N days)
- Web Interface: Clean, responsive web UI for habit management
- Automatic Updates: Background service for maintaining data consistency
- Automated Backups: Regular MongoDB backups to Google Drive
- Backend: Spring Boot (Java 21)
- Database: MongoDB
- Frontend: Thymeleaf templates with vanilla JavaScript
- Containerization: Docker & Docker Compose
- Backup: Python with Google Drive API
The application consists of three main services:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ HabitTracker │ │ Updater │ │ Backup │
│ (Port 8089) │ │ (Port 8087) │ │ Service │
│ │ │ │ │ │
│ • Web Interface │ │ • Daily Updates │ │ • MongoDB Dump │
│ • CRUD Ops │ │ • Streak Calc │ │ • Google Drive │
├─────────────────┤ ├─────────────────┤ │ • Scheduled │
│ │ │ │ │ │
└─────────┬───────┘ └─────────┬───────┘ └─────────────────┘
│ │
└──────────────────────┼──────────────────────┘
│
┌─────────────────┐
│ MongoDB │
│ (Port 27017) │
│ │
│ • habits │
│ • habitStructure│
│ • last_run_date │
└─────────────────┘
Location: habitTracker/
Port: 8089
Purpose: Main web application providing user interface and CRUD operations
Controllers:
HabitController: Handles web page routing and displayHabitWriteController: Handles data modification operations (POST/PUT/DELETE)
Services:
HabitService: Core habit business logicStructureService: Daily habit completion tracking
Models:
Habit: Main habit entity with fields like name, frequency, streak, datesHabitStructure: Daily habit completion records
- Web-based habit management interface
- Real-time habit completion tracking
- Habit creation, editing, and deletion
- Streak display and management
- Responsive design for mobile and desktop
Location: updater/
Port: 8087
Purpose: Background service for maintaining data consistency
The updater has been broken down into focused service classes:
Main Orchestrator:
UpdateScheduler: Coordinates daily updates (runs at 12:05 AM)
Core Services:
LastRunDateService: Manages execution tracking to prevent duplicate runsHabitUpdateService: Updates habit scheduling and current datesHabitDateCalculator: Calculates next occurrence dates based on frequencyHabitStructureManager: Creates daily habit completion recordsStreakCalculationService: Handles all streak calculations and updates
- Startup Check: Runs on application startup to catch up on missed updates
- Daily Execution: Scheduled daily at 12:05 AM
- Duplicate Prevention: Checks if already ran today
- Habit Date Updates: Updates current dates for overdue habits
- Structure Creation: Creates daily completion records for due habits
- Streak Calculation: Updates streaks based on completion history
Location: backup/
Purpose: Automated MongoDB backup to Google Drive
- Scheduled Backups: Daily backups at configurable times
- Google Drive Integration: Secure cloud storage
- Compression: Efficient storage using compressed JSON dumps
- Error Handling: Robust error handling and logging
- Docker Desktop
- PowerShell (Windows)
- Git
-
Clone the repository:
git clone <repository-url> cd HabitTracker
-
Run the automated deployment script:
.\docker-compose-runner-v1.ps1
This script:
- Automatically detects your timezone
- Maps Windows timezone to Linux format
- Builds all Docker containers
- Starts the entire application stack
-
Access the application:
- With domain (recommended): https://habitrackerdima.me (auto HTTPS by Caddy)
- Local/no-domain (dev): http://localhost (Caddy proxies to javaapp)
- Direct service ports (for debugging):
- Main App (Java, host-mapped): http://localhost:8079
- Updater (host-mapped): http://localhost:8087
This stack includes Caddy as an edge proxy that terminates TLS and obtains/renews certificates automatically.
-
Create a
.envfile next todocker-compose.ymlwith your domain and email:CADDY_DOMAIN=habits.example.com CADDY_EMAIL=you@example.com # Optional during first tests to avoid LE rate limits: # ACME_CA=https://acme-staging-v02.api.letsencrypt.org/directory
-
Point your DNS A/AAAA records for the domain to this server's public IP.
-
Start the stack (Caddy is the default public entrypoint on 80/443):
docker compose up -d --build docker compose logs -f caddy
-
Browse to:
- https://habits.example.com (automatic redirect from HTTP)
Notes:
- Caddy is now the sole edge proxy and will automatically obtain/renew certificates.
- If DNS isn’t set yet, Caddy still serves HTTP on :80 and proxies to the app.
- X-Forwarded-Proto is preserved end-to-end so Spring Boot generates correct HTTPS URLs behind proxies.
-
DNS (Namecheap → Domain List → Manage → Advanced DNS):
- A @ →
- CNAME www → @
- TTL: Automatic
-
Oracle Cloud networking:
- Open inbound TCP ports 80 and 443 in your VCN Security List or NSG.
- Ensure the instance OS firewall allows 80/443 (ufw/firewalld/Windows Firewall).
-
Watch Caddy issue certs automatically:
docker compose logs -f caddy -
Optional (initial testing):
- Use Let's Encrypt staging to avoid rate limits once while validating DNS and reachability.
- Uncomment the
acme_caline incaddy/Caddyfile, reload Caddy, then comment it again for production.
If you prefer manual setup:
# Set your timezone environment variable
$env:HOST_TIMEZONE = "America/New_York" # Replace with your timezone
# Build and start services
docker-compose build
docker-compose up -dThe application uses the following environment variables:
HOST_TIMEZONE: Your local timezone (auto-detected by script)MONGO_URI: MongoDB connection stringTZ: Container timezone setting
{
"_id": "ObjectId",
"id": "Integer (auto-increment)",
"name": "String",
"startDate": "LocalDate",
"endDate": "LocalDate (optional)",
"curDate": "LocalDate",
"frequency": "Integer (days between occurrences)",
"streak": "Integer",
"active": "Boolean",
"_class": "habitTracker.Habit.Habit"
}{
"_id": "ObjectId",
"habitId": "Integer",
"structureDate": "LocalDate",
"completed": "Boolean",
"_class": "habitTracker.Structure.HabitStructure"
}{
"_id": "LocalDate",
"_class": "updater.models.LastRunDate"
}- habits ↔ habitStructure: One-to-many relationship via
habitId - last_run_date: Singleton collection tracking updater execution
GET /- Home page with habit listGET /habit/{id}- Individual habit detailsGET /add- Add new habit formGET /edit/{id}- Edit habit form
POST /add- Create new habitPUT /edit/{id}- Update existing habitDELETE /delete/{id}- Delete habitPOST /complete/{habitId}- Mark habit as completed for todayPOST /uncomplete/{habitId}- Mark habit as incomplete for today
GET /habits- Get all habits (JSON)GET /habit/{id}/data- Get specific habit data (JSON)
The updater service primarily runs scheduled tasks and doesn't expose public endpoints. It operates through:
@PostConstructmethod on startup@Scheduledmethod daily at 12:05 AM
- Template Engine: Thymeleaf
- Styling: CSS3 with responsive design
- JavaScript: Vanilla JS for interactivity
- UI Framework: Custom responsive grid system
- Mobile-first approach
- Flexible grid layout
- Touch-friendly buttons and controls
- Habit Completion: Click to toggle completion status
- Real-time Updates: Immediate visual feedback
- Dynamic Streaks: Live streak counter updates
- Form Validation: Client-side and server-side validation
- Intuitive Interface: Clean, minimalist design
- Visual Feedback: Color-coded completion status
- Progress Tracking: Visual representation of streaks
- Easy Navigation: Simple, logical page flow
- Displays all active habits
- Shows current streaks
- Quick completion toggle buttons
- Add new habit button
- Detailed habit information
- Completion history
- Edit and delete options
- Streak analytics
- Form validation
- Date pickers
- Frequency selection
- Active/inactive toggle
HabitTracker/
├── habitTracker/ # Main Spring Boot application
│ ├── src/main/java/
│ │ └── habitTracker/
│ │ ├── Habit/ # Habit entity and service
│ │ ├── Structure/ # HabitStructure entity and service
│ │ └── controllers/
│ ├── src/main/resources/
│ │ ├── templates/ # Thymeleaf templates
│ │ └── static/ # CSS, JS, images
│ └── Dockerfile
│
├── updater/ # Background update service
│ ├── src/main/java/updater/
│ │ ├── services/ # Refactored service classes
│ │ └── models/ # Data models
│ └── Dockerfile
│
├── backup/ # Backup service
│ ├── backup_script.py
│ ├── requirements.txt
│ └── Dockerfile
│
├── docker-compose.yml
└── docker-compose-runner-v1.ps1
-
Local Development:
# Start MongoDB only docker-compose up mongodbHabit -d # Run applications locally for development cd habitTracker && mvn spring-boot:run cd updater && mvn spring-boot:run
-
Testing Changes:
# Rebuild specific service docker-compose build habittracker docker-compose up habittracker -d -
Database Access:
# Connect to MongoDB docker exec -it mongodbHabit mongosh -u root -p example
The updater service has been refactored following these principles:
- Single Responsibility: Each class has one clear purpose
- Dependency Injection: Clear dependencies between services
- Testability: Each service can be unit tested independently
- Maintainability: Changes to one aspect don't affect others
- Error Handling: Specific error handling per service
- UpdateScheduler: Main coordination and scheduling
- LastRunDateService: Execution tracking
- HabitUpdateService: Habit date management
- HabitDateCalculator: Date calculation logic
- HabitStructureManager: Structure creation
- StreakCalculationService: Streak computation
Automated backup system that dumps MongoDB data to Google Drive on a scheduled basis.
- Scheduled Execution: Configurable backup frequency
- Google Drive Integration: Secure cloud storage
- Compression: Efficient data storage
- Error Handling: Comprehensive error logging
- Incremental Backups: Timestamp-based backup naming
The backup system requires Google Drive API credentials (not included in repository for security).
- MongoDB Dump: Export collections to JSON
- Compression: Create compressed archive
- Upload: Secure upload to Google Drive
- Cleanup: Remove local temporary files
- Logging: Record backup status and metrics
- MongoDB: Persistent volume, authentication enabled
- HabitTracker: Port 8089, depends on MongoDB
- Updater: Port 8087, scheduled execution
- Backup: Depends on MongoDB, Google Drive integration
MONGO_URI: Database connection stringTZ: Timezone configuration (auto-detected)JAVA_TOOL_OPTIONS: JVM timezone settings
The application automatically detects and configures timezone settings:
- Detection: PowerShell script detects Windows timezone
- Mapping: Converts to Linux/IANA timezone format
- Configuration: Sets environment variables for all containers
- Consistency: Ensures all services use the same timezone
The system supports major timezones including:
- North America: EST, CST, MST, PST, etc.
- Europe: GMT, CET, EET, etc.
- Asia: JST, CST, IST, etc.
- Australia/Pacific: AEST, NZST, etc.
- Others: Various global timezones
If ports are already in use:
# Check what's using the ports
netstat -ano | findstr :8089
netstat -ano | findstr :8087
netstat -ano | findstr :27017
# Kill processes or change ports in docker-compose.yml# Check MongoDB logs
docker logs mongodbHabit
# Verify connection
docker exec -it mongodbHabit mongosh -u root -p example# Verify timezone setting
docker exec -it updater date
docker exec -it javaapp date
# Check environment variables
docker exec -it updater printenv | grep TZ# Clean rebuild
docker-compose down
docker system prune -f
docker-compose build --no-cache
docker-compose up# View all logs
docker-compose logs -f
# View specific service logs
docker-compose logs -f updater
docker-compose logs -f javaapp
docker-compose logs -f mongodbHabit- Fork the repository
- Create a feature branch
- Make changes following the established patterns
- Test locally using Docker Compose
- Submit a pull request
- Follow Spring Boot conventions
- Use meaningful variable and method names
- Include comprehensive comments
- Follow the refactored service pattern for new features
- Write unit tests for new services
- Test database operations
- Verify timezone handling
- Test Docker container builds
This project is open source. Please ensure you don't include sensitive credentials (like Google API keys) when contributing or sharing.
- Google Drive API credentials are not included in the repository
- MongoDB credentials are for development only
- Change default passwords in production environments
- Use environment variables for sensitive configuration
- Regular security updates for dependencies
- Proper error handling to avoid information disclosure
- Input validation and sanitization
- Secure database connections
- User authentication and multi-user support
- Habit categories and tags
- Advanced analytics and reporting
- Mobile app development
- Social features and habit sharing
- Integration with fitness trackers
- Custom habit frequency patterns
- Habit templates and presets
- Comprehensive test suite
- Performance monitoring
- Enhanced error handling
- API rate limiting
- Caching implementation
- Database optimization
- Security enhancements