Skip to content

About

Xtraction is a comprehensive, enterprise-grade document processing and management platform designed for extracting insights from documents with OCR

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

500 Commits

Folders and files

Repository files navigation

πŸ“„ Xtraction API

Java Spring Boot License Build PostgreSQL Docker Kafka Elasticsearch

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


πŸ“‘ Table of Contents

  1. Overview
  2. Features
  3. Architecture
  4. Project Structure
  5. Tech Stack
  6. Prerequisites
  7. Quick Start
  8. Configuration
  9. Docker Deployment
  10. API Reference
  11. Database Migrations
  12. Testing
  13. CI/CD Pipeline
  14. Security
  15. Subscription Plans & Billing
  16. OCR Processing
  17. Payment Gateways
  18. Monitoring & Observability
  19. Contributing
  20. License
  21. Support

πŸ”­ Overview

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.


✨ Features

πŸ“ Document Management

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

πŸ” OCR & AI Extraction

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

πŸ” Identity & Security

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

πŸ’³ Payments & Subscriptions

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

πŸ”” Notifications & Messaging

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
Email Multi-provider (Mailgun primary, AWS SES backup)
SMS / Voice Twilio integration
Thymeleaf Templates 22 rich HTML email templates

πŸ”Ž Search & Analytics

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

πŸ— Architecture

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
Loading

Module Decomposition

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

πŸ“ Project Structure

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

πŸ›  Tech Stack

Core Framework

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

Database & Storage

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

Message Brokers

Technology Version Purpose
Apache Kafka 3.7.0 (KRaft mode) Async event streaming

Cloud & Infrastructure

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

Document Processing

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

Payment Gateways

Provider SDK Status
Stripe stripe-java 31.0.0 βœ… Full
Paystack Custom HTTP client βœ… Full

Security

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

Communication

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

Developer Tooling

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

πŸ“‹ Prerequisites

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

Tesseract Installation (Local Dev Only)

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 tesseract

Windows:

  1. Download the installer from UB Mannheim
  2. Add the install directory (e.g. C:\Program Files\Tesseract-OCR) to your PATH
  3. Note the tessdata path β€” you'll need it for TESSERACT_DATAPATH

Required External API Keys

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.


πŸš€ Quick Start

Option A: Docker Compose (Recommended)

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-api

Once 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

Option B: Local Development

Use this if you want faster hot-reload and IDE debugging with Spring Boot DevTools.

Step 1 β€” Start only the infrastructure services

# 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.0

Step 2 β€” Configure the application

Edit 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

Step 3 β€” Build and run

# 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.jar

The API will start on http://localhost:8080 by default (no context path configured in application.properties).

Step 4 β€” Verify startup

curl http://localhost:8080/
# Expected: {"statusCode":200,"status":"success","message":"Xtraction API is running",...}

βš™οΈ Configuration

Environment Variables Reference

Copy .env.example to .env and fill in the values. Below is a full reference:

Application

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

Database

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

Cache

Variable Default Description
REDIS_HOST redis (Docker) / localhost (local) Redis host
REDIS_PORT 6379 Redis port

Message Broker

Variable Default Description
SPRING_KAFKA_BOOTSTRAP_SERVERS kafka:29092 (Docker) Kafka bootstrap server(s)

JWT Tokens

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)

AWS

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

Email (Mailgun)

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

Payments

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

AI

Variable Description
SPRING_AI_OPENAI_API_KEY OpenAI API key
SPRING_AI_MISTRALAI_API_KEY Mistral AI API key

OCR

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

Push Notifications

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

Elasticsearch

Variable Default Description
ELASTICSEARCH_HOST elasticsearch (Docker) / localhost (local) ES host
ELASTICSEARCH_PORT 9200 ES HTTP port

Currency Exchange

Variable Default Description
CURRENCY_API_KEY (required) exchangerate-api.com API key
CURRENCY_API_CACHE_TTL_HOURS 24 Rate cache duration

Encryption

Variable Default Description
APP_ENCRYPTION_ENABLED true Enable AES-256 document encryption
APP_ENCRYPTION_MASTER_KEY (required) Base64-encoded 256-bit master key

Spring Profiles

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 names
  • application-production.properties β€” enables secure cookies, disables SQL logging, tightens actuator exposure

Application Properties Overview

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

🐳 Docker Deployment

Services Included in docker-compose.yml

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 postgres service or use the docker run command from Local Development.

Common Docker Commands

# 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 sh

Multi-Stage Dockerfile Summary

Stage 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

πŸ“š API Reference

Response Envelope

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"
}

Authentication

Xtraction uses JWT Bearer tokens. The typical flow:

  1. Register β†’ POST /api/v1/auth/register β€” creates account, sends OTP email
  2. Verify OTP β†’ POST /api/v1/auth/verify-email β€” activates the account
  3. Login β†’ POST /api/v1/auth/login β€” returns accessToken + sets refreshToken in HttpOnly cookie
  4. Use token β†’ include Authorization: Bearer <accessToken> on all protected requests
  5. Refresh β†’ POST /api/v1/auth/refresh-token β€” exchange refresh cookie for a new access token
  6. OAuth2 β†’ GET /oauth2/authorize/google β€” initiate Google social login

Endpoint Overview

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

Example: Upload a Document

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"

Example: Run OCR on a Document

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"}'

πŸ—„ Database Migrations

Xtraction uses Flyway for versioned database migrations. Migrations are applied automatically on startup.

Migration Files

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)

Running Migrations Manually

# 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 new V{n+1}__description.sql.


πŸ§ͺ Testing

Run All Tests

./mvnw test

Run a Specific Test Class

./mvnw test -Dtest=DocumentServiceTest

Run a Specific Test Method

./mvnw test -Dtest=OcrServiceTest#shouldFallbackToTesseract

Run with Active Profile

./mvnw test -Dspring.profiles.active=test

Generate JaCoCo Coverage Report

./mvnw clean verify
# Report: target/site/jacoco/index.html

Open target/site/jacoco/index.html in your browser to explore line-by-line coverage.

What is Tested

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

πŸ”„ CI/CD Pipeline

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

Required GitHub Secrets

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

πŸ”’ Security

Authentication & Tokens

  • 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 HttpOnly secure cookie β€” never accessible to client-side JavaScript.
  • Secure cookie flag is enforced in production. In local development, set app.cookie-secure=false if running without HTTPS.

Rate Limiting

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.

Document Encryption

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 32

Input Sanitization

All user-supplied HTML content passes through Jsoup's HTML sanitizer before persistence, protecting against stored XSS attacks.

Dependency Security

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.


πŸ’° Subscription Plans & Billing

Individual Plans

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.

Free Trial

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.

Billing Lifecycle

  1. User selects a plan β†’ chooses monthly or yearly billing
  2. Payment is collected via Stripe (international) or Paystack (African users)
  3. A PDF receipt is generated and stored on S3
  4. Subscription is provisioned in the database
  5. Kafka emits a subscription.activated event consumed downstream
  6. On cancellation, access continues until the current period ends
  7. On renewal failure, a grace period email is sent before downgrading

Promo Codes

  • 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

πŸ” OCR Processing

Providers

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

Configuration

# 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) engine

Quota

OCR 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 = unlimited

πŸ’³ Payment Gateways

Stripe

Xtraction uses Stripe Checkout for seamless payment UI hosted by Stripe.

Flow:

  1. Client calls POST /api/v1/stripe/checkout/session β†’ receives a Stripe Checkout URL
  2. User completes payment on Stripe's hosted page
  3. Stripe sends a webhook to POST /api/v1/stripe/webhook
  4. The webhook handler verifies the signature and provisions/updates the subscription

Required env vars: STRIPE_API_KEY, STRIPE_WEBHOOK_SECRET

Paystack

Used for NGN-denominated payments for African users.

Flow:

  1. Client calls POST /api/v1/paystack/initialize β†’ receives an authorization URL
  2. User is redirected to Paystack's checkout page
  3. On success, Paystack redirects to PAYSTACK_CALLBACK_URL
  4. Server verifies the payment reference via GET /api/v1/paystack/verify/{reference}
  5. Paystack also sends webhooks to POST /api/v1/paystack/webhook

Required env vars: PAYSTACK_SECRET_KEY, PAYSTACK_WEBHOOK_SECRET

Testing Payments Locally

Use Stripe's test card numbers:

  • 4242 4242 4242 4242 β€” always succeeds
  • 4000 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/webhook

πŸ“Š Monitoring & Observability

Spring Boot Actuator

Exposed 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

Metrics Export

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

Structured Logging

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
}

Circuit Breakers

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_OPEN

🀝 Contributing

We welcome contributions! Please follow these steps:

1. Fork & Clone

git clone https://github.com/<your-fork>/xtraction-api.git
cd xtraction-api

2. Create a Branch

Branch naming convention:

  • feature/short-description β€” new features
  • fix/short-description β€” bug fixes
  • chore/short-description β€” maintenance
  • docs/short-description β€” documentation only
git checkout -b feature/add-flutterwave-integration

3. Develop

  • Follow the existing package structure (controller β†’ service interface β†’ impl β†’ repository)
  • Write unit tests for all service-layer logic
  • Annotate new REST endpoints with SpringDoc @Operation and @ApiResponse
  • Add Flyway migrations for any schema changes β€” never modify existing migration files

4. Code Style

The project enforces Checkstyle (relaxed Sun style). Run locally before committing:

./mvnw checkstyle:check

Key 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

5. Commit & Push

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

6. Open a Pull Request

  • Target the dev branch (not main directly)
  • 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

Adding a New Payment Gateway

The cleanest way to activate a stub gateway (PayPal, Flutterwave, Chappa):

  1. Implement the PaymentGateway interface in billing/payment/{gateway}/
  2. Add configuration in billing/payment/{gateway}/config/
  3. Register it in the gateway factory / strategy selector in billing/payment/common/
  4. Add environment variables to .env.example
  5. Write unit tests covering success, failure, and webhook verification paths
  6. Add a Flyway migration for any new tables
  7. Register new endpoints in the OpenAPI docs

πŸ“„ License

This project is licensed under the MIT License β€” see LICENSE for details.


πŸ“ž Support

Channel Details
πŸ“§ Email support@xtraction.xyz
πŸ› Bug Reports GitHub Issues
πŸ’¬ Discussions GitHub Discussions

Built with ❀️ by the Brints team · © 2026 Xtraction

About

Xtraction is a comprehensive, enterprise-grade document processing and management platform designed for extracting insights from documents with OCR

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages