Xtraction is an enterprise-grade document intelligence platform that combines OCR, AI-powered analysis, multi-gateway payments, real-time messaging, and robust team collaboration into a single REST API β built with Java 25 and Spring Boot 4.
Features β’ Architecture β’ Quick Start β’ Configuration β’ API Reference β’ Contributing
- Overview
- Features
- Architecture
- Project Structure
- Tech Stack
- Prerequisites
- Quick Start
- Configuration
- Docker Deployment
- API Reference
- Database Migrations
- Testing
- CI/CD Pipeline
- Security
- Subscription Plans & Billing
- OCR Processing
- Payment Gateways
- Monitoring & Observability
- Contributing
- License
- Support
Xtraction is an AI-powered document processing and management platform. It provides a comprehensive REST API for:
- Uploading, organizing, and managing documents in collections
- Extracting text from images and scanned documents (OCR) via Tesseract or Google Cloud Vision
- Running AI analysis (summarisation, classification, entity extraction) via OpenAI / Mistral
- Managing Payment subscriptions with Stripe and Paystack
- Handling real-time notifications over WebSocket, Firebase Cloud Messaging, and Kafka
- Performing full-text search across documents, users, and payments using Elasticsearch
It is designed for production at scale: async processing pipelines, circuit breakers, rate limiting, AES-256 document encryption, structured JSON logging, and a fully automated CI/CD pipeline deploying to AWS EC2 via ECR.
New here? Jump straight to Quick Start to run everything locally in three commands.
| Feature | Description |
|---|---|
| Document Collections | Logical grouping of files per user |
| File Uploads | Up to 50 MB per file, 100 MB per request |
| Storage Tracking | Per-user storage limits enforced at every upload |
| AES-256 Encryption | Documents encrypted at rest with per-tenant master key |
| Word Export | Convert processed documents to .docx via Apache POI |
| PDF Processing | Text extraction and analysis via Apache PDFBox |
| Soft Delete | Documents are soft-deleted with scheduled hard-deletion |
| Feature | Description |
|---|---|
| Tesseract OCR | Local OCR engine via Tess4J; no external API needed |
| Google Cloud Vision | Cloud OCR with confidence scores and language detection |
| Provider Fallback | Automatic fallback between OCR providers |
| OpenAI Integration | GPT-4o-mini for document summarisation and classification |
| Mistral AI Integration | Mistral-small as fallback AI provider |
| AI Credit System | Per-operation credit costs with quota enforcement |
| Rich Text Editing | Post-OCR text editor fields on extracted data |
| Feature | Description |
|---|---|
| JWT Auth | Short-lived access tokens + long-lived refresh tokens in secure cookies |
| OAuth 2.0 / OIDC | Social login via Google (extensible to any OAuth2 provider) |
| Role-Based Access Control | USER, ADMIN, and platform-admin roles |
| OTP Verification | Email OTP for registration, team creation, and admin actions |
| Password Reset | Secure token-based reset with email notification |
| Rate Limiting | Bucket4j token-bucket per tier (Free / Starter / Pro / Business) |
| Login Attempt Tracking | Automatic account lockout on repeated failures |
| HTML Sanitization | Jsoup used to strip XSS payloads from user input |
| Feature | Description |
|---|---|
| Stripe | Full subscription + one-time payment, webhooks, receipts |
| Paystack | NGN-primary African payment gateway, webhooks |
| PayPal | Stub implementation ready for activation |
| Promo Codes | Full coupon / promo code lifecycle with analytics |
| Credit Packs | One-off credit purchases with transfer support |
| PDF Receipts | Auto-generated and stored on AWS S3 |
| Currency Conversion | 60+ currencies via exchangerate-api.com, cached 24 h |
| Feature | Description |
|---|---|
| Firebase FCM | Push notifications to mobile/web clients |
| OneSignal | Alternative push provider (configurable) |
| AWS SNS | Alternative push via AWS (configurable) |
| WebSocket | Real-time bidirectional messaging via STOMP |
| Apache Kafka | Durable event streaming for async pipelines |
| Multi-provider (Mailgun primary, AWS SES backup) | |
| SMS / Voice | Twilio integration |
| Thymeleaf Templates | 22 rich HTML email templates |
| Feature | Description |
|---|---|
| Elasticsearch | Full-text search across documents, users, and payments |
| Kibana | Visual dashboard for search indices |
| Kafka UI | Real-time Kafka topic monitoring |
| Micrometer | Metrics exported to Datadog and Prometheus |
| Structured Logging | Logstash JSON encoder for log aggregation |
| Actuator | Health checks, info, and metrics endpoints |
graph TB
subgraph "Client Layer"
WEB[Web Client<br/>Port: 4200]
MOBILE[Mobile Client]
end
subgraph "API Gateway"
API[Spring Boot API<br/>Port: 8080]
end
subgraph "Async Messaging"
KAFKA[Apache Kafka<br/>Port: 9092]
end
subgraph "Data Layer"
PG[(PostgreSQL 17<br/>Port: 5432)]
REDIS[(Redis 7<br/>Port: 6379)]
ES[(Elasticsearch 9<br/>Port: 9200)]
end
subgraph "Cloud Services"
S3[AWS S3<br/>Documents & Receipts]
SES[AWS SES<br/>Email]
CLOUD[Cloudinary<br/>Image CDN]
GCP[Google Cloud Vision<br/>OCR]
FCM[Firebase FCM<br/>Push Notifications]
OPENAI[OpenAI / Mistral<br/>AI Analysis]
end
subgraph "Payment Gateways"
STRIPE[Stripe]
PAYSTACK[Paystack]
PAYPAL[PayPal stub]
end
subgraph "Monitoring"
KIBANA[Kibana<br/>Port: 5601]
KAFKA_UI[Kafka UI<br/>Port: 8090]
DD[Datadog / Prometheus]
end
WEB --> API
MOBILE --> API
API --> PG
API --> REDIS
API --> ES
API --> KAFKA
API --> S3
API --> SES
API --> CLOUD
API --> GCP
API --> FCM
API --> OPENAI
API --> STRIPE
API --> PAYSTACK
API --> PAYPAL
ES --> KIBANA
KAFKA --> KAFKA_UI
API --> DD
The application is split into six top-level modules under com.xtraction.api:
| Module | Responsibility |
|---|---|
core |
Cross-cutting concerns: security, encryption, rate limiting, web filters, global response model |
identity |
Auth (JWT + OAuth2), user management, login attempt tracking |
extraction |
Documents, OCR, AI analysis, Word export, Elasticsearch search, Google Vision |
billing |
Subscriptions, payment gateways (Stripe / Paystack / PayPal), promo codes, credit packs, receipts |
integration |
Kafka broker, email / SMS messaging, push notifications, WebSocket, AWS S3 storage |
admin |
Admin controllers, admin-specific services, audit logging, system stats |
xtraction-api/
βββ .github/
β βββ workflows/
β β βββ test.yml # CI: unit + integration tests on PR
β β βββ linting.yml # Checkstyle code style enforcement
β β βββ security.yml # GitHub CodeQL security scan
β β βββ owasp.yml # OWASP dependency vulnerability scan
β β βββ code-quality.yml # Aggregated quality gate
β β βββ docker.yml # Docker image build & push to ECR
β β βββ deploy.yml # Deploy to AWS EC2 on push to main
β β βββ release.yml # Semantic release & changelog
β β βββ flyway.yml # Manual DB migration trigger
β β βββ labeler.yml # Auto-label PRs by changed paths
β β βββ stale.yml # Mark stale issues/PRs
β βββ scripts/ # Helper automation scripts
β
βββ src/
β βββ main/
β β βββ java/com/xtraction/api/
β β β βββ XtractionApplication.java # Entry point
β β β β
β β β βββ core/ # Cross-cutting infrastructure
β β β β βββ config/ # Spring beans & configs
β β β β βββ encryption/ # AES-256-GCM document encryption
β β β β βββ exceptions/ # Global exception handlers
β β β β βββ metrics/ # Custom Micrometer metrics
β β β β βββ ratelimit/ # Bucket4j rate limiter
β β β β βββ security/ # JWT filter, security config
β β β β βββ utils/ # Shared utility helpers
β β β β βββ web/
β β β β βββ datamodel/ # Generic API response types
β β β β βββ filter/ # Servlet filters
β β β β βββ request/ # Base request DTOs
β β β β βββ response/ # ApiResponse envelope
β β β β
β β β βββ identity/ # Authentication & users
β β β β βββ auth/ # Login, register, refresh, OAuth2
β β β β βββ loginattempts/ # Brute-force protection
β β β β βββ user/ # User CRUD, profile, preferences
β β β β
β β β βββ extraction/ # Document intelligence
β β β β βββ documents/ # Document & collection management
β β β β βββ ocr/ # OCR orchestration + quota
β β β β βββ ai/ # AI summarisation & classification
β β β β βββ vision/ # Google Cloud Vision adapter
β β β β βββ export/ # Word (.docx) export
β β β β βββ search/ # Elasticsearch integration
β β β β
β β β βββ billing/ # Payments & subscriptions
β β β β βββ subscription/ # Plan management, trials, renewals
β β β β βββ payment/
β β β β β βββ common/ # Shared payment abstractions
β β β β β βββ paystack/ # Paystack gateway (full)
β β β β β βββ paypal/ # PayPal gateway (stub)
β β β β β βββ receipt/ # PDF receipt generation
β β β β βββ credit/ # Credit pack purchase & transfer
β β β β βββ promocode/ # Promo code lifecycle & analytics
β β β β
β β β βββ integration/ # External integrations
β β β β βββ broker/ # Kafka producers & consumers
β β β β βββ messaging/ # Email (Mailgun / SES) & SMS (Twilio)
β β β β βββ notification/ # FCM / OneSignal / SNS push
β β β β βββ storage/ # AWS S3 + Cloudinary adapters
β β β β βββ websocket/ # STOMP WebSocket config
β β β β
β β β βββ admin/ # Admin portal
β β β βββ controller/ # Admin REST endpoints
β β β βββ dto/ # Admin request/response DTOs
β β β βββ impl/ # Admin service implementations
β β β βββ interfaces/ # Admin service contracts
β β β βββ repository/ # Admin data repositories
β β β βββ service/ # Admin business logic
β β β βββ events/ # Admin audit events
β β β βββ config/ # Admin-specific beans
β β β βββ api_docs/ # OpenAPI annotations
β β β
β β βββ resources/
β β βββ application.properties # Base config (local dev)
β β βββ application-docker.properties # Docker profile overrides
β β βββ application-production.properties # Production overrides
β β βββ application-example.properties # Annotated template
β β βββ db/migration/ # Flyway SQL migrations
β β βββ elasticsearch/ # ES index mappings
β β βββ templates/ # Thymeleaf HTML email templates
β β βββ google-credentials.json # GCP service account (gitignored in prod)
β β βββ firebase-service-account.json # Firebase credentials (gitignored in prod)
β β
β βββ test/ # Test sources (mirrors main structure)
β
βββ docker-compose.yml # Full local stack: API + all dependencies
βββ Dockerfile # Multi-stage build (JDK 25 build β JRE 25 runtime)
βββ pom.xml # Maven dependencies & plugins
βββ checkstyle.xml # Checkstyle rules (relaxed Sun style)
βββ .env.example # Environment variable template
βββ .env # Your local secrets (never commit!)
βββ .gitignore
| Technology | Version | Purpose |
|---|---|---|
| Java | 25 | Programming language |
| Spring Boot | 4.1.0 | Application framework |
| Spring Security | 6.x | Authentication & authorization |
| Spring Data JPA | 3.x | ORM / data persistence |
| Spring Data Redis | 3.x | Caching & session storage |
| Spring Data Elasticsearch | 3.x | Full-text search |
| Spring Kafka | 3.x | Event streaming |
| Spring WebSocket | 3.x | Real-time messaging (STOMP) |
| Spring AI | 2.0.0-M2 | OpenAI & Mistral AI integration |
| Resilience4j | 2.3.0 | Circuit breakers & retry logic |
| Technology | Version | Purpose |
|---|---|---|
| PostgreSQL | 17 | Primary relational database |
| Redis | 7 Alpine | Caching & rate-limit state |
| Elasticsearch | 9.2.3 | Full-text search & analytics |
| Flyway | 10.x | Database schema migrations |
| HikariCP | (Boot default) | Connection pooling |
| Technology | Version | Purpose |
|---|---|---|
| Apache Kafka | 3.7.0 (KRaft mode) | Async event streaming |
| Service / SDK | Purpose |
|---|---|
| AWS SDK v2 (S3, SES, SNS) | File storage, email, push notifications |
| Spring Cloud AWS 3.3 (S3 starter) | Simplified S3 integration |
| Cloudinary | Image optimization & CDN delivery |
| Google Cloud Vision (Spring Cloud GCP 7.4.1) | Cloud OCR |
| Firebase Admin SDK 9.7.0 | FCM push notifications |
| Library | Version | Purpose |
|---|---|---|
| Tess4J (Tesseract) | 5.15.0 | Local OCR engine |
| Apache PDFBox | 3.0.6 | PDF text extraction |
| Apache POI OOXML | 5.4.1 | Word (.docx) export |
| OpenCV | 4.9.0 | Image pre-processing |
| OpenPDF | 1.3.35 | PDF receipt generation |
| Jsoup | 1.22.1 | HTML sanitization |
| Provider | SDK | Status |
|---|---|---|
| Stripe | stripe-java 31.0.0 | β Full |
| Paystack | Custom HTTP client | β Full |
| Technology | Version | Purpose |
|---|---|---|
| JJWT | 0.12.6 | JWT creation & validation |
| Spring Security OAuth2 Client | Boot default | Social / OIDC login |
| Bucket4j | 8.1.0 | Token-bucket rate limiting |
| Service | SDK | Purpose |
|---|---|---|
| Mailgun | mailgun-java 1.1.6 | Primary transactional email |
| AWS SES | aws-sdk-java v2 | Backup transactional email |
| Twilio | twilio-java 10.7.2 | SMS & voice |
| Firebase FCM | firebase-admin 9.7.0 | Push notifications |
| Tool | Version | Purpose |
|---|---|---|
| Lombok | 1.18.42 | Boilerplate reduction |
| MapStruct | 1.5.5 | Type-safe object mapping |
| SpringDoc OpenAPI | 3.0.0 | Swagger UI & API spec |
| Logstash Logback Encoder | 7.4 | Structured JSON logging |
| Micrometer (Datadog + Prometheus) | Boot default | Metrics & observability |
| JaCoCo | 0.8.13 | Code coverage |
| Checkstyle | 13.2.0 | Code style enforcement |
| Spring Boot DevTools | Boot default | Hot reload during development |
Before you begin, ensure you have the following installed:
| Tool | Minimum Version | Notes |
|---|---|---|
| JDK | 25 | Eclipse Temurin 25 recommended |
| Apache Maven | 3.9.x | Or use the included ./mvnw wrapper |
| Docker | 24.x | |
| Docker Compose | 2.x | Bundled with Docker Desktop |
| Git | any | |
| Tesseract OCR | 5.x | Optional β only for local dev without Docker |
The Docker image installs Tesseract automatically. For local development without Docker:
Linux / macOS:
# Debian/Ubuntu
sudo apt-get install tesseract-ocr tesseract-ocr-eng
# macOS (Homebrew)
brew install tesseractWindows:
- Download the installer from UB Mannheim
- Add the install directory (e.g.
C:\Program Files\Tesseract-OCR) to yourPATH - Note the
tessdatapath β you'll need it forTESSERACT_DATAPATH
The following services require API keys. You can start without them and add them progressively:
| Service | Required For | Where to Get |
|---|---|---|
| Stripe | Payments | stripe.com/docs/keys |
| Paystack | Payments (NGN) | paystack.com/developers |
| Mailgun | Transactional email | mailgun.com |
| AWS (S3, SES) | File storage & email | aws.amazon.com/console |
| Google Cloud Vision | Cloud OCR | console.cloud.google.com |
| OpenAI | AI analysis | platform.openai.com |
| Mistral AI | AI fallback | console.mistral.ai |
| Cloudinary | Image CDN | cloudinary.com |
| Firebase | Push notifications | firebase.google.com |
| exchangerate-api.com | Currency conversion | exchangerate-api.com |
Tip for local development: You can set dummy values for services you don't need. The application starts without crashing on most missing keys. Stripe and Paystack keys are only needed if you test payment flows. OCR works with the free Tesseract engine by default.
This spins up the full stack β API, Redis, Kafka, Elasticsearch, Kibana, and Kafka UI β with a single command.
# 1. Clone the repository
git clone https://github.com/Brints/xtraction-api.git
cd xtraction-api
# 2. Copy the environment template
cp .env.example .env
# 3. Edit .env with your credentials
# At minimum, set your JWT secret and any payment keys you need.
# For local dev, the database/Redis/Kafka defaults work out of the box.
# 4. Start all services (detached mode)
docker compose up -d
# 5. Follow the API logs to confirm startup
docker compose logs -f xtraction-apiOnce started, the API is available at http://localhost:8080.
Useful service URLs:
| Service | URL |
|---|---|
| API (Swagger UI) | http://localhost:8080/swagger-ui |
| Kafka UI | http://localhost:8090 |
| Kibana | http://localhost:5601 |
| Elasticsearch | http://localhost:9200 |
Use this if you want faster hot-reload and IDE debugging with Spring Boot DevTools.
# PostgreSQL
docker run --name xtraction-postgres \
-e POSTGRES_USER=postgres \
-e POSTGRES_PASSWORD=postgres \
-e POSTGRES_DB=xtraction \
-p 5432:5432 -d postgres:17
# Redis
docker run --name xtraction-redis \
-p 6379:6379 -d redis:7-alpine
# Kafka (KRaft mode, no ZooKeeper)
docker run --name xtraction-kafka \
-p 9092:9092 \
-e KAFKA_NODE_ID=1 \
-e KAFKA_PROCESS_ROLES=broker,controller \
-e KAFKA_LISTENERS=PLAINTEXT://0.0.0.0:29092,CONTROLLER://0.0.0.0:9093,EXTERNAL://0.0.0.0:9092 \
-e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://kafka:29092,EXTERNAL://localhost:9092 \
-e KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,EXTERNAL:PLAINTEXT \
-e KAFKA_CONTROLLER_QUORUM_VOTERS=1@kafka:9093 \
-e KAFKA_CONTROLLER_LISTENER_NAMES=CONTROLLER \
-e CLUSTER_ID=MkU3OEVBNTcwNTJENDM2Qk \
-d apache/kafka:3.7.0Edit src/main/resources/application.properties to point to your local services:
# Database (local)
spring.datasource.url=jdbc:postgresql://localhost:5432/xtraction
spring.datasource.username=postgres
spring.datasource.password=postgres
# Redis (local)
spring.data.redis.url=redis://localhost:6379
# Kafka (local)
spring.kafka.bootstrap-servers=localhost:9092
# Elasticsearch (skip if not needed locally)
spring.elasticsearch.uris=http://localhost:9200
# Tesseract (Windows example)
tesseract.datapath=C:/Program Files/Tesseract-OCR/tessdata
# JWT β CHANGE THIS to a strong random string in production
app.jwt-secret=your-very-long-random-base64-secret-key-here# Build (skip tests for faster first start)
./mvnw clean package -DskipTests
# Run with local profile
./mvnw spring-boot:run
# Or run the JAR directly
java -jar target/Xtraction-1.0.0.jarThe API will start on http://localhost:8080 by default (no context path configured in application.properties).
curl http://localhost:8080/
# Expected: {"statusCode":200,"status":"success","message":"Xtraction API is running",...}Copy .env.example to .env and fill in the values. Below is a full reference:
| Variable | Default | Description |
|---|---|---|
APP_BASE_URL |
http://localhost:8080 |
Public API base URL |
APP_FRONTEND_URL |
http://localhost:4200 |
Frontend app URL (used in email links & CORS) |
APP_SUPPORT_EMAIL |
support@xtraction.xyz |
Support email address |
APP_ADMIN_EMAIL |
admin@xtraction.xyz |
Bootstrap admin account email |
APP_ADMIN_PASSWORD |
(required) | Bootstrap admin account password |
| Variable | Default | Description |
|---|---|---|
POSTGRES_HOST |
postgres (Docker) / localhost (local) |
PostgreSQL host |
POSTGRES_PORT |
5432 |
PostgreSQL port |
POSTGRES_DB |
xtraction |
Database name |
POSTGRES_USER |
postgres |
Database user |
POSTGRES_PASSWORD |
postgres |
Database password |
| Variable | Default | Description |
|---|---|---|
REDIS_HOST |
redis (Docker) / localhost (local) |
Redis host |
REDIS_PORT |
6379 |
Redis port |
| Variable | Default | Description |
|---|---|---|
SPRING_KAFKA_BOOTSTRAP_SERVERS |
kafka:29092 (Docker) |
Kafka bootstrap server(s) |
| Variable | Default | Description |
|---|---|---|
APP_JWT_SECRET |
(required) | Base64-encoded JWT signing secret β MUST be changed |
APP_JWT_EXPIRATION_MS |
3600000 |
Access token TTL in milliseconds (1 hour) |
APP_JWT_REFRESH_EXPIRATION_MS |
2592000000 |
Refresh token TTL (30 days) |
| Variable | Description |
|---|---|
AWS_ACCESS_KEY |
AWS access key ID |
AWS_SECRET_KEY |
AWS secret access key |
AWS_S3_REGION |
S3 bucket region (e.g. eu-central-1) |
AWS_S3_BUCKET |
S3 bucket name |
AWS_S3_CLOUDFRONT_URL |
CloudFront distribution domain |
AWS_FROM_EMAIL |
Verified SES sender email |
| Variable | Description |
|---|---|
MAILGUN_API_KEY |
Mailgun private API key |
MAILGUN_DOMAIN |
Mailgun sending domain |
MAILGUN_FROM_EMAIL |
Sender address |
MAILGUN_WEBHOOK_SIGNING_KEY |
Webhook signature verification key |
| Variable | Description |
|---|---|
STRIPE_API_KEY |
Stripe secret key (sk_test_... or sk_live_...) |
STRIPE_WEBHOOK_SECRET |
Stripe webhook signing secret (whsec_...) |
STRIPE_CURRENCY |
Default currency (usd) |
PAYSTACK_SECRET_KEY |
Paystack secret key |
PAYSTACK_WEBHOOK_SECRET |
Paystack webhook secret |
PAYSTACK_CURRENCY |
Default currency (NGN) |
PAYPAL_CLIENT_ID |
PayPal application client ID |
PAYPAL_CLIENT_SECRET |
PayPal application secret |
PAYPAL_MODE |
sandbox or live |
| Variable | Description |
|---|---|
SPRING_AI_OPENAI_API_KEY |
OpenAI API key |
SPRING_AI_MISTRALAI_API_KEY |
Mistral AI API key |
| Variable | Default | Description |
|---|---|---|
OCR_DEFAULT_PROVIDER |
TESSERACT |
Primary OCR engine (TESSERACT or GOOGLE_VISION) |
OCR_FALLBACK_ENABLED |
true |
Enable automatic provider fallback |
TESSERACT_DATAPATH |
C:/Program Files/Tesseract-OCR/tessdata |
Path to Tesseract language data |
OCR_MAX_FILE_SIZE_BYTES |
10485760 |
Max OCR input file size (10 MB) |
OCR_TIMEOUT_SECONDS |
60 |
OCR processing timeout |
| Variable | Default | Description |
|---|---|---|
NOTIFICATION_ACTIVE_PROVIDER |
FCM |
Active provider (FCM, ONESIGNAL, AWS_SNS) |
FIREBASE_ENABLED |
true |
Enable Firebase FCM |
FIREBASE_CREDENTIALS_PATH |
classpath:firebase-service-account.json |
FCM service account JSON path |
| Variable | Default | Description |
|---|---|---|
ELASTICSEARCH_HOST |
elasticsearch (Docker) / localhost (local) |
ES host |
ELASTICSEARCH_PORT |
9200 |
ES HTTP port |
| Variable | Default | Description |
|---|---|---|
CURRENCY_API_KEY |
(required) | exchangerate-api.com API key |
CURRENCY_API_CACHE_TTL_HOURS |
24 |
Rate cache duration |
| Variable | Default | Description |
|---|---|---|
APP_ENCRYPTION_ENABLED |
true |
Enable AES-256 document encryption |
APP_ENCRYPTION_MASTER_KEY |
(required) | Base64-encoded 256-bit master key |
| Profile | Activation | Use Case |
|---|---|---|
| (default) | ./mvnw spring-boot:run |
Local development with local services |
docker |
SPRING_PROFILES_ACTIVE=docker |
Running inside Docker Compose |
production |
SPRING_PROFILES_ACTIVE=production |
Production deployment (strict security settings) |
Profile-specific properties files:
application-docker.propertiesβ overrides hosts to use Docker service namesapplication-production.propertiesβ enables secure cookies, disables SQL logging, tightens actuator exposure
Key settings in application.properties that are most commonly changed:
# Server
server.port=8080 # API port
# File Uploads
spring.servlet.multipart.max-file-size=50MB # Max single file
spring.servlet.multipart.max-request-size=100MB
# Swagger / OpenAPI
springdoc.api-docs.path=/docs
springdoc.swagger-ui.path=/swagger-ui
# JPA
spring.jpa.hibernate.ddl-auto=validate # NEVER use create/drop in prod
# Async Upload Pipeline
upload.pipeline.core-pool-size=4
upload.pipeline.max-pool-size=8
upload.pipeline.queue-capacity=50
# WebSocket CORS
websocket.allowed-origins=${app.frontend.url},http://localhost:4200| Service | Image | Ports | Notes |
|---|---|---|---|
xtraction-api |
Built from ./Dockerfile |
8080 |
Depends on Redis & Kafka health checks |
redis |
redis:7-alpine |
6379 |
Persistent volume redis_data |
kafka |
apache/kafka:3.7.0 |
9092 |
KRaft mode (no ZooKeeper), persistent kafka_data |
kafka-ui |
provectuslabs/kafka-ui:v0.7.2 |
8090 |
Depends on Kafka health |
elasticsearch |
elasticsearch:9.2.3 |
9200, 9300 |
512 MB heap, security disabled by default |
kibana |
kibana:9.2.3 |
5601 |
Depends on Elasticsearch health |
Note: PostgreSQL is not in the Docker Compose file β it is expected to be managed separately or provided via a managed database service in production. For quick local testing, add a
postgresservice or use thedocker runcommand from Local Development.
# Start all services
docker compose up -d
# Start only infrastructure (no API)
docker compose up -d redis kafka elasticsearch
# Follow API logs
docker compose logs -f xtraction-api
# Rebuild and restart API only
docker compose build xtraction-api
docker compose up -d xtraction-api
# Stop everything
docker compose down
# Stop and remove persistent volumes (full reset)
docker compose down -v
# Execute a shell in the running API container
docker compose exec xtraction-api shStage 1 (build): eclipse-temurin:25-jdk
β ./mvnw dependency:go-offline (layer cached unless pom.xml changes)
β ./mvnw package -DskipTests (produces target/Xtraction-1.0.0.jar)
Stage 2 (runtime): eclipse-temurin:25-jre
β apt-get install tesseract-ocr (OCR engine + English language data)
β COPY Xtraction.jar
β EXPOSE 8080
β ENTRYPOINT ["java", "-jar", "Xtraction.jar"]
β ENV SPRING_PROFILES_ACTIVE=production
Every API response is wrapped in a standard envelope:
{
"statusCode": 200,
"status": "success",
"message": "Operation completed successfully",
"data": {},
"timestamp": "2026-07-01T12:00:00.000Z"
}Error responses follow the same shape:
{
"statusCode": 400,
"status": "error",
"message": "Validation failed",
"errors": ["email: must be a valid email address"],
"timestamp": "2026-07-01T12:00:00.000Z"
}Xtraction uses JWT Bearer tokens. The typical flow:
- Register β
POST /api/v1/auth/registerβ creates account, sends OTP email - Verify OTP β
POST /api/v1/auth/verify-emailβ activates the account - Login β
POST /api/v1/auth/loginβ returnsaccessToken+ setsrefreshTokeninHttpOnlycookie - Use token β include
Authorization: Bearer <accessToken>on all protected requests - Refresh β
POST /api/v1/auth/refresh-tokenβ exchange refresh cookie for a new access token - OAuth2 β
GET /oauth2/authorize/googleβ initiate Google social login
For frontend implementation, please refer to the Comprehensive API Documentation detailing all endpoints, request/response models, WebSockets progress tracking, and admin endpoints.
Access the full interactive documentation at http://localhost:8080/swagger-ui once the API is running.
| Category | Base Path | Auth Required | Description |
|---|---|---|---|
| Health | / |
No | API health check |
| Plans | /api/v1/plans |
No | Subscription plan listing with currency conversion |
| Auth | /api/v1/auth |
No (most) | Register, login, OTP, password reset, token refresh |
| Users | /api/v1/users |
Yes | Profile management, preferences, account deletion |
| Documents | /api/v1/documents |
Yes | Upload, read, update, delete documents & collections |
| OCR | /api/v1/ocr |
Yes | Submit OCR jobs, retrieve results, manage quota |
| AI | /api/v1/ai |
Yes | Document summarisation, classification, credit management |
| Search | /api/v1/search |
Yes | Full-text search across documents and data |
| Payments | /api/v1/payments |
Yes | Unified payment operations |
| Stripe | /api/v1/stripe |
Yes / Webhook | Stripe checkout, subscriptions, webhooks |
| Paystack | /api/v1/paystack |
Yes / Webhook | Paystack initialization, verification, webhooks |
| PayPal | /api/v1/paypal |
Yes | PayPal order creation & capture (stub) |
| Subscriptions | /api/v1/subscriptions |
Yes | Individual subscription lifecycle management |
| Teams | /api/v1/teams |
Yes | Team creation, member management, team subscriptions |
| Organizations | /api/v1/organizations |
Yes | Enterprise organization management |
| Storage | /api/v1/storage |
Yes | Storage usage stats and limit queries |
| Credits | /api/v1/credits |
Yes | Credit balance, purchase packs, transfer |
| Promo Codes | /api/v1/promo-codes |
Yes / Admin | Promo code redemption and management |
| Notifications | /api/v1/notifications |
Yes | Device token registration, notification history |
| Admin | /api/v1/admin |
Admin only | User management, system stats, audit log |
| Actuator | /actuator |
Configurable | Health, metrics, info |
curl -X POST http://localhost:8080/api/v1/documents \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-F "file=@/path/to/document.pdf" \
-F "collectionId=your-collection-id"curl -X POST http://localhost:8080/api/v1/ocr/process \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"documentId": "your-document-id", "provider": "TESSERACT"}'Xtraction uses Flyway for versioned database migrations. Migrations are applied automatically on startup.
62 migration scripts live in src/main/resources/db/migration/ and are named V{n}__{description}.sql.
Key milestones:
| Version | Description |
|---|---|
| V1 | User management base tables |
| V6 | Documents table |
| V7 | Document collections and entries |
| V14 | Subscription tables |
| V21βV23 | Stripe and Paystack tables |
| V30βV31 | Organizations and Teams |
| V36 | Storage allocation fields |
| V37 | Push notification tables |
| V40βV48 | Coupon / promo code system |
| V51 | Credit pack tables |
| V53βV55 | AI operations and rich text editing |
| V57βV59 | Rename coupon β promo code |
| V62 | Schema cleanup (drop deprecated tables) |
# Apply pending migrations
./mvnw flyway:migrate \
-Dflyway.url=jdbc:postgresql://localhost:5432/xtraction \
-Dflyway.user=postgres \
-Dflyway.password=postgres
# Validate current state
./mvnw flyway:validate \
-Dflyway.url=jdbc:postgresql://localhost:5432/xtraction \
-Dflyway.user=postgres \
-Dflyway.password=postgres
# View migration history
./mvnw flyway:info \
-Dflyway.url=jdbc:postgresql://localhost:5432/xtraction \
-Dflyway.user=postgres \
-Dflyway.password=postgres
β οΈ Never edit an already-applied migration file. Always create a newV{n+1}__description.sql.
./mvnw test./mvnw test -Dtest=DocumentServiceTest./mvnw test -Dtest=OcrServiceTest#shouldFallbackToTesseract./mvnw test -Dspring.profiles.active=test./mvnw clean verify
# Report: target/site/jacoco/index.htmlOpen target/site/jacoco/index.html in your browser to explore line-by-line coverage.
| Layer | Framework |
|---|---|
| Unit tests | JUnit 5 + Mockito 5.12 |
| Security tests | Spring Security Test |
| Kafka tests | Spring Kafka Test (embedded broker) |
| Integration | Spring Boot Test (@SpringBootTest) |
The CI pipeline (GitHub Actions) runs tests against:
- PostgreSQL service container
- Redis service container
- RabbitMQ service container
All workflows are defined in .github/workflows/.
| Workflow | Trigger | What it Does |
|---|---|---|
test.yml |
PR to main or dev |
Runs full test suite with real PostgreSQL, Redis, and RabbitMQ service containers; uploads coverage to Codecov |
linting.yml |
Push / PR | Checkstyle code style validation |
security.yml |
Push to dev/main, PR to main, weekly Sunday |
GitHub CodeQL static analysis (security-extended queries) |
owasp.yml |
Push / PR | OWASP dependency vulnerability scan |
code-quality.yml |
Push / PR | Aggregated quality gate |
docker.yml |
Push to main |
Build Docker image and push to AWS ECR |
deploy.yml |
Push to main |
Pull ECR image on EC2 and run ./run.sh |
release.yml |
Tag creation | Semantic versioning, changelog generation, GitHub release |
flyway.yml |
Manual dispatch | Run Flyway migrations against a target database |
labeler.yml |
PR open / sync | Auto-label PRs based on changed file paths |
stale.yml |
Scheduled daily | Close stale issues and PRs |
Configure these in Settings β Secrets and variables β Actions:
| Secret | Used By |
|---|---|
AWS_ACCESS_KEY |
deploy.yml, test.yml |
AWS_SECRET_KEY |
deploy.yml, test.yml |
AWS_S3_REGION |
test.yml |
AWS_S3_BUCKET |
test.yml |
AWS_CLOUDFRONT_URL |
test.yml |
EC2_HOST |
deploy.yml |
EC2_USERNAME |
deploy.yml |
EC2_SSH_KEY |
deploy.yml |
GOOGLE_CREDENTIALS_JSON_BASE64 |
deploy.yml (base64 GCP service account JSON) |
CODECOV_TOKEN |
test.yml |
- Access tokens are short-lived JWTs (default: 1 hour). They are returned in the response body.
- Refresh tokens are long-lived (default: 30 days). They are stored in an
HttpOnlysecure cookie β never accessible to client-side JavaScript. - Secure cookie flag is enforced in production. In local development, set
app.cookie-secure=falseif running without HTTPS.
API rate limits are enforced per authenticated user based on their subscription tier:
| Tier | Requests / Minute | Burst | Daily Limit |
|---|---|---|---|
| Free | 5 | 8 | 50 |
| Starter | 15 | 25 | 300 |
| Pro | 30 | 50 | 750 |
| Business | 60 | 100 | 2,000 |
Exceeding the rate limit returns HTTP 429 Too Many Requests.
Documents are encrypted at rest using AES-256 in GCM mode (authenticated encryption). The master key is configured via APP_ENCRYPTION_MASTER_KEY and must be a base64-encoded 256-bit (32-byte) key. Generate one with:
openssl rand -base64 32All user-supplied HTML content passes through Jsoup's HTML sanitizer before persistence, protecting against stored XSS attacks.
The OWASP Dependency-Check plugin scans all Maven dependencies for known CVEs on every push. Suppressions for accepted false positives are configured in .github/owasp-suppressions.xml.
| Plan | Monthly | Yearly | Docs / Month | OCR Pages | Storage |
|---|---|---|---|---|---|
| Free | $0 | β | 5 | 25 | 120 MB |
| Starter | $9.99 | $89.99 | 30 | 150 | 2.66 GB |
| Pro | $19.99 | $189.99 | 100 | 500 | 12.66 GB |
| Business | $49.99 | $489.99 | 500 | 2,500 | 29.66 GB |
Yearly plans save ~17% compared to monthly.
Both team plans include a 10-day free trial that is automatically activated on team creation. Warning emails are sent at 3 days before expiry and again at expiry.
- User selects a plan β chooses monthly or yearly billing
- Payment is collected via Stripe (international) or Paystack (African users)
- A PDF receipt is generated and stored on S3
- Subscription is provisioned in the database
- Kafka emits a
subscription.activatedevent consumed downstream - On cancellation, access continues until the current period ends
- On renewal failure, a grace period email is sent before downgrading
- Admin creates promo code templates (percentage or fixed discount)
- Codes can be single-use or multi-use with optional expiry
- Analytics track redemption counts, revenue impact, and user demographics
| Provider | How It Works | When to Use |
|---|---|---|
| Tesseract (default) | Local JNI via Tess4J β no API call | Free, fast, works offline |
| Google Cloud Vision | REST API call to GCP | Higher accuracy, includes confidence scores and language detection |
# Default provider
ocr.default-provider=TESSERACT
# Automatic fallback if primary fails
ocr.fallback-enabled=true
ocr.fallback-provider=TESSERACT
# Enabled providers (comma-separated)
ocr.enabled-providers=TESSERACT,GOOGLE_VISION
# Tesseract settings
ocr.tesseract.language=eng
ocr.tesseract.page-seg-mode=3 # Fully automatic page segmentation
ocr.tesseract.ocr-engine-mode=3 # Default (best available) engineOCR usage is tracked per user per billing cycle. Quota limits are set per plan (see Subscription Plans). Quota is reset monthly.
Quota settings in .env:
OCR_QUOTA_ENABLED=true
OCR_QUOTA_FREE_TIER_DAILY_LIMIT=50
OCR_QUOTA_PREMIUM_TIER_DAILY_LIMIT=1000
OCR_QUOTA_ENTERPRISE_TIER_DAILY_LIMIT=-1 # -1 = unlimitedXtraction uses Stripe Checkout for seamless payment UI hosted by Stripe.
Flow:
- Client calls
POST /api/v1/stripe/checkout/sessionβ receives a Stripe Checkout URL - User completes payment on Stripe's hosted page
- Stripe sends a webhook to
POST /api/v1/stripe/webhook - The webhook handler verifies the signature and provisions/updates the subscription
Required env vars: STRIPE_API_KEY, STRIPE_WEBHOOK_SECRET
Used for NGN-denominated payments for African users.
Flow:
- Client calls
POST /api/v1/paystack/initializeβ receives an authorization URL - User is redirected to Paystack's checkout page
- On success, Paystack redirects to
PAYSTACK_CALLBACK_URL - Server verifies the payment reference via
GET /api/v1/paystack/verify/{reference} - Paystack also sends webhooks to
POST /api/v1/paystack/webhook
Required env vars: PAYSTACK_SECRET_KEY, PAYSTACK_WEBHOOK_SECRET
Use Stripe's test card numbers:
4242 4242 4242 4242β always succeeds4000 0000 0000 9995β always declines
For Paystack, use test credentials from the Paystack test dashboard.
Stripe webhooks locally:
# Install Stripe CLI, then forward events to your local server
stripe listen --forward-to http://localhost:8080/api/v1/stripe/webhookExposed at /actuator:
# Health
curl http://localhost:8080/actuator/health
# Application info
curl http://localhost:8080/actuator/info
# All metrics
curl http://localhost:8080/actuator/metrics| Destination | Exporter | How to Enable |
|---|---|---|
| Datadog | micrometer-registry-datadog |
Set DATADOG_API_KEY and DATADOG_METRICS_ENABLED=true |
| Prometheus | micrometer-registry-prometheus |
Enabled by default; scrape /actuator/prometheus |
The Logstash Logback Encoder produces JSON-formatted logs, ready for shipping to ELK stack or Datadog.
Example log entry:
{
"@timestamp": "2026-07-01T12:00:00.000Z",
"level": "INFO",
"logger_name": "com.xtraction.api.extraction.ocr.OcrService",
"message": "OCR processing completed",
"documentId": "abc-123",
"provider": "TESSERACT",
"durationMs": 1247
}Resilience4j circuit breakers wrap external API calls (OCR, payment gateways, AI providers). Circuit breaker state is exposed via:
curl http://localhost:8080/actuator/health
# Shows: circuitBreakers.{name}.status = CLOSED | OPEN | HALF_OPENWe welcome contributions! Please follow these steps:
git clone https://github.com/<your-fork>/xtraction-api.git
cd xtraction-apiBranch naming convention:
feature/short-descriptionβ new featuresfix/short-descriptionβ bug fixeschore/short-descriptionβ maintenancedocs/short-descriptionβ documentation only
git checkout -b feature/add-flutterwave-integration- Follow the existing package structure (controller β service interface β impl β repository)
- Write unit tests for all service-layer logic
- Annotate new REST endpoints with SpringDoc
@Operationand@ApiResponse - Add Flyway migrations for any schema changes β never modify existing migration files
The project enforces Checkstyle (relaxed Sun style). Run locally before committing:
./mvnw checkstyle:checkKey rules:
- No tab characters (spaces only)
- Max line length: 150 characters
- No star imports (
import java.util.*) - No unused imports
- Always use braces
{}for control structures - Constants in
UPPER_SNAKE_CASE
We follow Conventional Commits:
feat: add Flutterwave payment gateway
fix: correct OCR quota reset logic
chore: update Stripe SDK to 32.0.0
docs: add WebSocket connection guide
git add .
git commit -m "feat: add Flutterwave payment gateway"
git push origin feature/add-flutterwave-integration- Target the
devbranch (notmaindirectly) - Fill in the PR template with a description, screenshots if applicable, and testing notes
- Ensure all CI checks pass before requesting review
- Link any relevant GitHub issues using
Closes #123
The cleanest way to activate a stub gateway (PayPal, Flutterwave, Chappa):
- Implement the
PaymentGatewayinterface inbilling/payment/{gateway}/ - Add configuration in
billing/payment/{gateway}/config/ - Register it in the gateway factory / strategy selector in
billing/payment/common/ - Add environment variables to
.env.example - Write unit tests covering success, failure, and webhook verification paths
- Add a Flyway migration for any new tables
- Register new endpoints in the OpenAPI docs
This project is licensed under the MIT License β see LICENSE for details.
| Channel | Details |
|---|---|
| π§ Email | support@xtraction.xyz |
| π Bug Reports | GitHub Issues |
| π¬ Discussions | GitHub Discussions |
Built with β€οΈ by the Brints team Β· Β© 2026 Xtraction