PixelSense API Code
| INDEX |
|---|
| S.NO | Section | Sub-Section |
|---|---|---|
| 1 | Introduction | Purpose of this module |
| 2 | Project Overview | Features & Responsibilities |
| 3 | Technology Stack | Packages & Layers |
| 4 | Security Configuration | SecurityConfig, JWT |
| Controllers | List of Controllers | |
| AdminController | ||
| UserController | ||
| CompareController | ||
| ComparisonController |
- Introduction
Purpose of This Module
The **Image Compare Service** is a Java Spring Boot microservice that creates REST API endpoints for automated visual regression testing. It provides 50+ HTTP endpoints that allow external applications to compare baseline (reference) images against checkpoint (current) images to detect unintended visual changes automatically.
This is an API-based image comparison service. Instead of integrating comparison logic directly into your app, you call this service via REST endpoints
The service exposes endpoints like:
```
POST /api/compare/run → Compare two images
POST /api/baselines/save → Save baseline image
POST /api/checkpoints/save → Save checkpoint image
GET /api/comparisons/{id} → Get comparison result
POST /api/visual-locators/save → Save element locations
POST /api/user/login → Authenticate user
GET /api/test-runs/{id} → Get test run details
... and 40+ more endpoints
External applications call these endpoints instead of building comparison logic themselves.
** Who Uses It**
- QA Engineers – Run tests and review differences
- Developers – Catch regressions before committing code
- DevOps Teams – Block PRs with visual issues
- Product Teams – Verify changes before release
- Module Overview
CompareController.java
This document explains the functionality, structure, and integration of the CompareController class within the Image Comparison API.
1. Overview and Purpose
The CompareController acts as the Controller Layer entry point for the image comparison microservice. Its primary responsibility is to:
- Receive incoming HTTP
POSTrequests at the/compareendpoint. - Validate and extract the multipart files (
baseFiles,compareFile) and the optionalregionJSON string. - Delegate the core business logic (comparison) to the
CompareService. - Handle potential exceptions and return a consistent
ResponseEntity.
| Detail | Value |
| Class Name | CompareController |
| Endpoint | /compare |
| Method | POST |
| Purpose | API entry point for image comparison. |
| Security | Requires X-API-KEY header. |
2. Spring Boot and Annotation Breakdown
| Annotation | Type | Purpose |
@RestController | Class | Marks the class as a Spring controller where methods return JSON/XML responses directly (combines @Controller and @ResponseBody). |
@RequestMapping("/compare") | Class | Maps all methods in this controller to the base path /compare. |
@Autowired | Field | Injects the CompareService dependency, enabling access to the comparison logic. |
@PostMapping | Method | Maps the compareImages method to handle HTTP POST requests at the base path (/compare). |
@RequestPart | Parameter | Binds parts of a multipart request to the method parameters (used for MultipartFiles). |
@RequestParam | Parameter | Binds a query parameter (region) to the method parameter. required = false makes it optional. |
3. Open API (Swagger) Integration
The controller is fully annotated to integrate with springdoc-openapi, generating interactive and secure API documentation.
| Annotation | Purpose |
@Tag(name = "Image Comparison", ...) | Groups this controller's endpoints under the "Image Comparison" category in the Swagger UI. |
@SecurityRequirement(name = "apiKeyScheme") | Enforces API Key security for all endpoints in this controller, causing a lock icon to appear next to the endpoint in Swagger UI. |
@Operation(...) | Provides a detailed summary, description, and defines expected HTTP status codes and responses for the POST /compare endpoint. |
@ApiResponse | Explicitly documents the possible HTTP response codes (200, 400, 401, 500) for client consumption. |
4. compareImages Method Logic
The main method handles the core request flow:
Java
public ResponseEntity<?> compareImages(...)
| Step | Action | Code Implication |
| 1. Logging | Logs the start of the comparison request, including the number of baseFiles received. | logger.info("Received request to compare {} base files", baseFiles.length); |
| 1. Delegation | Calls the compareService.compare() method, passing all request parts. The service returns the final ResponseEntity (which is often a JSON structure prepared by ResponseHandler). | return compareService.compare(baseFiles, compareFile, regionJson); |
| 1. Error Handling | If any exception occurs during the comparison process (e.g., file IO error, OpenCV processing error), the catch block executes. | catch (Exception e) |
| 1. Error Response | Logs the error details and uses the utility ResponseHandler.error() to generate a consistent ResponseEntity (typically HTTP 500 Internal Server Error) containing the failure message. | logger.error(...) and return ResponseHandler.error(... |
5. Dependency
The controller relies on two key dependencies:
CompareService: Injected via@Autowired, this is the service responsible for executing the actual OpenCV image comparison logic.ResponseHandler: A static utility used to format and return standardized error responses, maintaining API consistency.
CompareService.java
The CompareService is the core engine of the Image Comparison API, orchestrating the entire workflow from file handling to difference calculation and result preparation using OpenCV.
1. Overview and Initialization
| Detail | Value |
| Class Name | CompareService |
| Type | @Service (Spring Component) |
| Dependencies | QuadTreeService, ContourService, RegionMaskService |
| Key Function | compare(MultipartFile[] baseFiles, MultipartFile compareFile, String regionJson) |
Export to Sheets
OpenCV Native Library: The static block ensures the native OpenCV library is loaded exactly once when the class is initialized, which is mandatory for all org.opencv.* functions to work.
Java
static { System.loadLibrary(org.opencv.core.Core.NATIVE_LIBRARY_NAME); }
2. The compare Method Workflow
The compare method executes a linear flow, primarily managing file I/O, delegation to specialized services, and tracking the best match.
2.1 File Preparation and Validation
- Start Timer: Records
System.nanoTime()to calculate the total execution duration for performance logging. - Comparison Image Loading:
- The
compareFile(img2) is temporarily saved to the file system usingFiles.createTempFile(). - OpenCV reads the file into a
Matobject usingImgcodecs.imread(). - Validation: Checks if
img2is empty (img2.empty()), returning an error if the file is corrupt or not an image.
- The
2.2 Region Mask Application
- The
regionJsonstring (definingselectorignoreareas) is passed to theRegionMaskService.apply(). - The service returns a binary
regionMask** Mat**, which will be used later to filter the detected differences.
2.3 Base Image Iteration and Best Match Logic
The service iterates through all baseFiles to find the one that is the closest match to the compareFile.
| Step | Service/Function Used | Description |
| 1. Load Base Image | Imgcodecs.imread() | Loads each baseFile (img1) into an OpenCV Mat. |
| 1. Pre-Check | img1.size().equals(img2.size()) | Skips comparison if the base image is empty or has a different resolution than the comparison image (size mismatch). |
| 1. Compute Difference | quadTree.diff(img1, img2) | The QuadTreeService runs its recursive algorithm to generate a diffMask (a binary image where white pixels indicate differences). |
| 1. Apply Region Filter | contourService.applyRegionMask(diffMask, regionMask) | The initial diffMask is filtered by the regionMask to ignore or select differences based on user configuration. |
| 1. Calculate Score | Core.countNonZero(masked) | Calculates the final diffScore by counting the total number of non-zero pixels (differences) in the filtered mask. |
| 1. Best Match Update | Internal Logic | If the current diffScore is lower than bestDiff, the current base image (img1), its mask, and its name are stored as the new best match. |
2.4 Final Output Generation
- Contour Detection: The final
bestMaskis passed to theContourService.findContours(). This process groups neighboring difference pixels into bounding boxes. - Drawing Boxes: The comparison image (
img2.clone()) is passed toContourService.drawTransparentBoxes(), which draws semi-transparent rectangles over the detected differences (bounding boxes). - Performance: The total execution time is calculated and stored in the
timingsmap. - Response:
- If
bestDiff == 0(no differences found),ResponseHandler.identical()is called. - Otherwise,
ResponseHandler.different()is called, using the finaloutputimage with the drawn boxes and the list of bounding boxes.
- If
3. Service Dependencies
| Dependency | Responsibility |
QuadTreeService | Executes the pixel-level difference calculation, returning a raw binary mask of differences. |
RegionMaskService | Parses user JSON input to create an OpenCV binary mask for selective comparison areas. |
ContourService | Converts scattered difference pixels (diffMask) into grouped, rectangular bounding boxes and draws these boxes onto the final output image. |
ResponseHandler | Utility to construct standardized ResponseEntity objects for success, difference, and error conditions. |
QuadTreeService.java
The QuadTreeService implements the recursive QuadTree algorithm for efficiently detecting and isolating pixel-level differences between two images. This method significantly speeds up comparison by avoiding pixel-by-pixel checks in large, uniform areas.
1. Overview and Constants
| Detail | Value | Description |
| Class Name | QuadTreeService | Implements the quadtree comparison logic. |
MIN_SIZE | 16 | The minimum block size (16×16) where recursion stops, forcing a full pixel difference check. |
SENSITIVITY | 5 | The threshold used in the diffGray method. Pixel differences below this intensity value are ignored. |
| Key Function | diff(Mat img1, Mat img2) | The public entry point for the comparison. |
Export to Sheets
2. Difference Calculation: diffGray
This private utility function calculates the raw pixel difference between two image blocks and applies a sensitivity threshold.
| Step | OpenCV Function | Purpose |
| 1. Absolute Difference | Core.absdiff(a, b, diff) | Calculates the absolute difference between every pixel in a and b (preserving color channels). |
| 1. Grayscale Conversion | Imgproc.cvtColor(diff, gray, ...) | Converts the color difference image to a single-channel grayscale image. |
| 1. Thresholding | Imgproc.threshold(gray, thresh, SENSITIVITY, ...) | Creates a binary mask (thresh). Any pixel whose difference intensity is greater than SENSITIVITY (5) is set to white (255); all others are set to black (0). This filters out minor, imperceptible differences (noise). |
Export to Sheets
The resulting thresh is a difference mask: a black and white image where only the significant differences are visible as white pixels.
3. Recursive QuadTree Algorithm: quadtreeDiff
This is the core recursive function that divides the image block into four quadrants.
3.1 Base Cases (Stopping Recursion)
The recursion stops under two main conditions, based on the current block being processed:
- No Difference Found:
- Checks if the current block pair (
block1,block2) has any difference pixels usingCore.countNonZero(diffGray(block1, block2)). - If the count is 0, the block is identical. The function immediately returns a black
Mat(zero difference), avoiding further recursion.
- Checks if the current block pair (
- Minimum Size Reached:
- Checks if the block width or height (
worh) is less than or equal toMIN_SIZE(16). - If the minimum size is hit, the block is too small to split further. The function returns the full difference mask for this block via
diffGray(block1, block2).
- Checks if the block width or height (
3.2 Recursive Step
If neither base case is met, the algorithm proceeds to split the block:
- Split: The block is split into four
Rectobjects (quads), representing the top-left, top-right, bottom-left, and bottom-right quadrants. - Recurse: The
quadtreeDifffunction is called recursively for each of the four quadrants. This is the mechanism for the tree-like traversal. - Combine Results: The difference masks (
subMat) returned from the recursive calls are copied back into the appropriate section of the mainmaskMat for the current level. - Return: The combined mask for the current block is returned up the recursion chain.
This approach ensures that only blocks containing significant differences (i.e., blocks that cannot pass the "No Difference Found" check) are split and processed down to the minimum size, optimizing performance over areas of the image that are static.
RegionMaskService.java
The RegionMaskService is responsible for generating a binary mask based on user-defined JSON coordinates. This mask allows the comparison logic (in CompareService and QuadTreeService) to either selectively compare certain regions or ignore specific dynamic areas.
1. Overview and Purpose
| Detail | Value | Description |
| Class Name | RegionMaskService | Generates a binary image mask from JSON input. |
| Input | regionJson (String), h (Height), w (Width) | User-defined regions and the target image dimensions. |
| Output | Mat (OpenCV Binary Mask) | A black-and-white image where White (255) means COMPARE and Black (0) means IGNORE. |
| Dependencies | org.json package for JSON parsing. |
Export to Sheets
2. The apply Method Workflow
The method constructs a mask (Mat) that matches the dimensions of the images being compared, and then overlays the user-defined regions.
2.1 Initialization and Default Mask
- Creation: An initial mask (
mask) is created usingMat.ones(h, w, CvType.CV_8U).CV_8Uindicates an 8-bit, single-channel (grayscale) image. - Default White: The mask is initialized completely white (255) using
mask.setTo(new org.opencv.core.Scalar(255)). This represents the default state: compare the entire image. - No JSON Check: If
regionJsonis null or empty, the full white mask is immediately returned, meaning no filtering will occur.
2.2 Handling 'Select' Regions (Mode Switching)
The service supports two complementary modes:
- Ignore Mode (Default): If only
ignoreregions are present, the mask remains white (compare all), and theignoreareas are marked black. - Select Mode: If at least one
selectregion is found (hasSelectis true), the interpretation changes:- The entire mask is first reset to black (0).
- Only the explicit
selectareas will be marked white. Everything else is ignored.
Java
if (hasSelect) {
// If 'select' regions exist, we start with a black mask
mask.setTo(new org.opencv.core.Scalar(0));
}
2.3 Processing Region List
The method iterates through the JSONArray parsed from regionJson, processing each rectangle defined by its coordinates (x,y,width,height) and its type.
| Region Type | Action | OpenCV Operation | Effect on Comparison |
select | Sets the region in the mask to White (255). | mask.submat(...) is set to Scalar(255). | Includes this area for difference checking. |
ignore | Sets the region in the mask to Black (0). | mask.submat(...) is set to Scalar(0). | Excludes this area from difference checking. |
Export to Sheets
The submat method is key here, as it creates a view of a specific rectangular area of the mask, allowing the setTo operation to efficiently apply the scalar value (0 or 255) only to that rectangle.
Example JSON Structure:
JSON
[
{"type": "select", "x": 100, "y": 100, "width": 50, "height": 50},
{"type": "ignore", "x": 500, "y": 50, "width": 80, "height": 20}
]
ResponseHandler.java
The ResponseHandler is a utility class designed to standardize all API responses, ensuring consistency in format (Map<String, Object>), HTTP status codes, and content across successful outcomes, errors, and specific comparison results. It also handles the crucial task of Base64 encoding the resulting difference image.
1. Overview and Design
| Detail | Value | Description |
| Class Name | ResponseHandler | Utility class for standardizing API responses. |
| Design Pattern | Utility Class | Private constructor (private ResponseHandler()) prevents instantiation; all methods are static. |
| Core Functions | Generates ResponseEntity for identical, different, and error states. Encodes Mat to Base64. |
2. Core Image Encoding Function
This function integrates OpenCV with Java I/O to prepare the difference image for JSON transmission.
matToBase64(Mat image)
- Encode to JPEG: Uses
Imgcodecs.imencode(".JPEG", image, buffer)to encode the OpenCVMatobject into a byte array format (JPEG) and stores it in aMatOfBytebuffer. - Base64 Conversion: The byte array from the buffer is then converted into a Base64 string using
Base64.getEncoder().encodeToString(). - Output: Returns the Base64 string, which is included in the JSON response body under the key
"image_base64".
3. Comparison Result Handlers (HTTP 200 OK)
These methods structure the successful comparison results, including detailed metadata and performance metrics.
identical(...)
| Key Value | Description |
"status" | "identical" |
"message" | "Provided images are identical" |
"image_id" | The name/identifier of the matching base image. |
"regions" | The raw JSON string of regions used for the comparison. |
"timings_ms" | A map containing performance metrics (e.g., total_comparison_ms). |
| HTTP Status | 200 OK |
different(...)
This method includes the encoded difference image and details about the detected regions.
| Key Value | Description |
"status" | "different" |
"message" | "Images differ" |
"image_id" | The identifier of the best-matching base image. |
"image_base64" | The Base64 encoded string of the output image, which has semi-transparent boxes drawn over the differences. |
"region_metadata" | An array of bounding box coordinates (if available) found by the ContourService. |
| HTTP Status | 200 OK |
4. Error and Status Handlers
These methods ensure API failure responses are consistent and map to appropriate HTTP status codes.
| Method | HTTP Status | Status Key | Purpose |
invalidImage() | 400 Bad Request | "error" | Returned when uploaded files are corrupt, missing, or cannot be processed by OpenCV. |
shapeMismatch() | 400 Bad Request | "error" | Returned when the base image and compare image do not have the same dimensions (if required by the comparison logic). |
error(String message) | 500 Internal Server Error | "error" | Catch-all for unexpected exceptions and internal processing failures within the Service Layer. |
5. Utility Helpers
| Helper Method | Purpose |
ok(...) | A generic wrapper for simple 200 OK responses with custom data, used less often than identical/different. |
timings(...) | A helper to conveniently build a structured Map of timing data (e.g., load time, diff time) for inclusion in the final response body. |
boxesToMapList(...) | Converts a List of OpenCV's org.opencv.core.Rect objects into a list of simple JSON-compatible maps ({x: 10, y: 10, width: 50, height: 50}). |
Admin Module Documentation
1. AdminController
Purpose
The AdminController is responsible for handling admin-related API requests.
It exposes endpoints to manage system-level configurations such as baseline limits and highlight color used in image comparison.
API: Save Admin Settings
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/admin/settings | Saves admin configuration settings |
Request Body
{
"adminId": 1,
"baselineLimit": 10,
"highlightColor": "#FF0000"
}
Response
"Settings saved successfully"
Controller Flow
Client Request → AdminController → AdminService → Repository → Database
AdminService
Purpose
The AdminService contains the business logic for admin operations.
It validates input data before saving it to the database.
Main Method
saveAdminSettings(int adminId, int baselineLimit, String highlightColor)
Responsibilities
- Validate admin ID
- Validate baseline limit
- Validate highlight color format
- Call repository layer to persist data
Repository Layer (Database Call)
Purpose
Handles database interaction using stored procedures.
Method
saveAdminSettings(...)
Implementation Details
- Uses
SimpleJdbcCall - Calls stored procedure:
sp_SaveAdminSettings
Database Parameters
| Parameter | Description |
|---|---|
| p_AdminUserId | Admin ID |
| p_BaselineLimit | Maximum baseline images allowed |
| p_HighlightColor | Color used for highlighting differences |
2. Baseline Module
** BaselineController**
Purpose
The BaselineController handles all operations related to baseline images.
It allows users to view all baselines and perform operations like deleting selected baselines.
APIs
| Method | Endpoint | Description |
|---|---|---|
| GET | /baseline | Fetch all baseline images |
| POST | /baseline/delete | Delete selected baselines |
1. Get Baselines
Request
GET /baseline
Response
[
{
"baselineImgId": 101,
"baselineName": "Login Page",
"featureName": "Authentication",
"baselineCount": 5,
"variantCount": 2,
"lastUpdatedDate": "2025-05-01T10:15:30"
}
]
2. Delete Baselines
Request
[101, 102, 103]
Response
{
"success": true
}
Error Response
{
"success": false,
"message": "Invalid baseline ID"
}
Controller Flow
Client → BaselineController → BaselineService → Repository → Database
** BaselineService**
Purpose
The BaselineService contains business logic for baseline operations such as fetching and deleting baseline images.
Methods
getBaselines()
- Fetches all baseline images from database
- Returns list of
BaselineImageDetails
deleteBaselines(List<Integer> ids)
Responsibilities
- Validate input IDs
- Call repository to delete records
- Return operation status
Repository Layer (Database Operations)
1. Get All Baselines
Stored Procedure
sp_GetAllBaselineImages
Returned Data Includes
| Field | Description |
|---|---|
| TestId | Test identifier |
| BaselineImgId | Baseline image ID |
| BaselineName | Name of baseline |
| FeatureName | Feature associated |
| BaselineImage | Image (Base64 encoded) |
| BaselineCount | Total baseline images |
| VariantCount | Number of variants |
| LastUpdatedDate | Last modified date |
Important Processing
- Image is converted to Base64 string
- Null values are handled safely
- Date is converted to
LocalDateTime
2. Delete Baselines
Stored Procedure
sp_DeleteBaselineImages
Input Format
- List of IDs converted to JSON string
[101,102,103]
Variant Support
- Each baseline can contain multiple variants
- Variant count is shown in the baseline list
- Users can expand/view variants within a baseline
- Variant Module
VariantController
Purpose
The VariantController manages operations related to variants of baseline images.
Variants represent different versions of a baseline image associated with checkpoints.
APIs
| Method | Endpoint | Description |
|---|---|---|
| POST | /variant/insert | Insert a new variant |
| POST | /variant/update | Update variant name |
| DELETE* | /variant/delete | Delete a variant (documented feature) |
1. Insert Variant
Request (Query Params)
POST /variant/insert
| Param | Description |
|---|---|
| baselineImgId | Baseline image ID |
| checkpointId | Checkpoint ID |
| variantName | Name of variant |
| createdBy | User ID |
Response
{
"success": true
}
Error Response
{
"error": "Variant name is required"
}
2. Update Variant
Request
POST /variant/update
| Param | Description |
|---|---|
| variantId | Variant ID |
| newName | Updated variant name |
Response
{
"success": true
}
3. Delete Variant (Documented Feature)
Expected API
DELETE /variant/delete?variantId=101
Response
{
"success": true
}
Controller Flow
Client → VariantController → VariantService → Repository → Database
VariantService
Purpose
Handles business logic for variant operations including insert, update, and delete.
Methods
1. InsertBaselineVariant(...)
- Inserts a new variant
- Validates all input fields
2. UpdateVariantName(...)
- Updates variant name
- Returns success status
3. DeleteVariant(...)
- Deletes variant by ID
- Returns true if successful
VariantImageController
Purpose
Fetches variant images associated with a test.
API
| Method | Endpoint | Description |
|---|---|---|
| GET | /variant-image/{testId} | Get variant images by test ID |
Request
GET /variant-image/10
Response
[
{
"variantId": 1,
"baselineImgId": 101,
"testId": 10,
"createdByName": "Admin",
"variantImage": "Base64EncodedImage"
}
]
VariantImageService
Purpose
Handles fetching variant image data from repository.
Method
getVariantImagesByTest(testId)
Responsibilities
- Validate testId
- Fetch data from DB
- Return empty list if null
Repository Layer (Database Operations)
1. Insert Variant
- Stored Procedure:
sp_InsertBaselineVariant
Parameters:
| Parameter | Description |
|---|---|
| p_BaselineImgId | Baseline ID |
| p_CheckpointId | Checkpoint ID |
| p_VariantName | Variant name |
| p_CreatedBy | Created user |
2. Delete Variant
- Stored Procedure:
sp_DeleteBaselineVariant
| Parameter | Description |
|---|---|
| p_VariantId | Variant ID |
3. Update Variant Name
- Stored Procedure:
sp_UpdateBaselineVariantName
| Parameter | Description |
|---|---|
| p_VariantId | Variant ID |
| p_NewVariantName | New name |
4. Get Variant Images
- Stored Procedure:
sp_GetVariantsForTest
Important Processing
- Image converted to Base64 string
- Null-safe handling
- Data mapped to DTO
Variant Functionality (UI / Config Behavior)
Purpose
Variants allow multiple versions of a baseline image for comparison.
Features
- Add new variant to a baseline
- Update variant name
- Delete variant
- View all variants under a baseline
- Fetch variant images by test
4.Checkpoint Module
CheckpointController
Purpose
The CheckpointController manages operations related to checkpoints.
A checkpoint represents an image captured for comparison, which can later be accepted as a baseline.
APIs
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/checkpoints | Create a new checkpoint |
| POST | /api/checkpoints/{checkId}/accept-baseline | Accept checkpoint as baseline |
| POST | /api/checkpoints/{checkId}/json | Insert JSON data |
| POST | /api/checkpoints/{checkId}/assign | Assign checkpoint to user |
| PATCH | /api/checkpoints/{checkId}/review | Update review status |
| PATCH | /api/checkpoints/user/{userId}/last-login | Update last login time |
1. Create Checkpoint
Request
POST /api/checkpoints
| Param | Description |
|---|---|
| nid | Node/Test ID |
| userId | Created user |
| image | Image (byte array) |
Response
101
Returns checkId
2. Accept Checkpoint as Baseline
Request
POST /api/checkpoints/{checkId}/accept-baseline
| Param | Description |
|---|---|
| checkId | Checkpoint ID |
| userId | User performing action |
| regionsJson | Optional region data |
Response
5001
Returns baselineImgId
3. Insert JSON Data
Request
POST /api/checkpoints/{checkId}/json
{
"regions": [
{ "x": 10, "y": 20, "width": 50, "height": 50 }
]
}
Response
2001
Returns jsonId
4. Assign Checkpoint
Request
POST /api/checkpoints/{checkId}/assign
| Param | Description |
|---|---|
| assignedTo | User assigned |
| assignedBy | Assigning user |
| remarks | Optional notes |
Response
{
"id": 2,
"name": "John",
"email": "john@example.com"
}
5. Update Review Status
Request
PATCH /api/checkpoints/{checkId}/review
| Param | Description |
|---|---|
| status | approved / rejected / pending |
| userId | Reviewer |
Response
"Checkpoint review updated successfully"
6. Update Last Login Time
Request
PATCH /api/checkpoints/user/{userId}/last-login
Response
"Last login time updated successfully"
Controller Flow
Client → CheckpointController → CheckpointService → Repository → Database
CheckpointService
Purpose
Handles business logic, validation, and processing of checkpoint operations.
Main Methods
1. InsertCheckpoint(...)
- Creates a checkpoint
- Validates image and user
2. AcceptCheckpointAsBaseline(...)
- Converts checkpoint → baseline
- Accepts optional region JSON
3. InsertJsonData(...)
- Stores JSON metadata for checkpoint
4. AssignCheckpoint(...)
- Assigns checkpoint to user
- Returns assigned user details
5. updateCheckpointReview(...)
- Updates review status
- Tracks reviewer and timestamp
6. UpdateLastLoginTime(...)
- Updates user's last login time
Validation Rules
| Field | Rule |
|---|---|
| checkId / nid | Must be > 0 |
| userId | Must be valid |
| image | Required, max 5MB |
| JSON | Must be valid & < 200KB |
| status | approved / rejected / pending |
| remarks | Max 500 characters |
Repository Layer (Database Operations)
1. Insert Checkpoint
- Stored Procedure:
sp_InsertCheckpoint
Output: checkId
2. Accept as Baseline
- Stored Procedure:
sp_AcceptCheckpointAsBaseline
Output: baselineImgId
3. Insert JSON
- Stored Procedure:
InsertJsonData
Output: jsonId
4. Assign Checkpoint
- Stored Procedure:
sp_AssignCheckpoint
Returns:
- ID
- Name
5. Update Review Status
- Direct SQL update on
checkpointstable
6. Update Last Login Time
- Updates
usertable - Sets
LastLoginTime = NOW()
Flow
Service → Repository → Stored Procedure / SQL → Database
4. Checkpoint Functionality (UI / Flow Behavior)
Purpose
Checkpoint acts as an intermediate stage before baseline creation
** 5. Feature Module**
FeatureController
Purpose
The FeatureController manages features in the system.
A Feature acts as a container/group that holds multiple tests (images).
In the UI, selecting a feature displays all related tests and their execution details.
APIs
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/features | Get all features |
| POST | /api/features/delete | Delete features (batch) |
| POST | /api/features/update | Update feature details |
| GET | /api/features/summary | Get image run summary |
| GET | /api/features/images | Get images under a feature |
1. Get All Features
Request
GET /api/features
Response
[
{
"featureId": 1,
"featureName": "Login Feature",
"productName": "PixelSense",
"createdDate": "2025-05-01T10:00:00"
}
]
2. Delete Features
Request
[1, 2, 3]
Response
{
"success": true,
"message": "Deleted successfully"
}
3. Update Feature
Request
{
"featureId": 1,
"featureName": "Login Updated",
"productName": "PixelSense"
}
Response
{
"success": true,
"message": "Feature updated successfully"
}
4. Image Run Summary
Request
GET /api/features/summary?featureId=1
Response
[
{
"nid": 101,
"imageName": "Login Page",
"totalRuns": 10,
"passedRuns": 8,
"unresolvedRuns": 1,
"newRuns": 1
}
]
5. Get Images by Feature
Request
GET /api/features/images?featureId=1
Response
[
{
"nid": 101,
"imageName": "Login Page",
"createdDate": "2025-05-01T10:00:00"
}
]
FeatureService
Purpose
Handles business logic for feature operations such as fetching, updating, and deleting features.
Main Methods
1. GetAllFeatures()
- Fetches all features
- Uses caching for performance
2. DeleteFeatures(ids)
- Deletes multiple features
- Clears cache
3. UpdateFeature(...)
- Updates feature name & product
- Returns success status
4. GetImageRunSummaryByFeature(featureId)
- Returns execution summary of images
5. GetImagesByFeature(featureId)
- Returns all images under a feature
Repository Layer (Database Operations)
1. Get All Features
- Query: Fetch from
test_featurestable - Sorted by latest created
2. Delete Features
- Batch delete using
FeatureId
3. Update Feature
- Updates name and product
4. Image Run Summary
- Stored Procedure:
sp_GetImageRunSummaryByFeature
5. Get Images by Feature
- Fetches images from
image_entitiestable
Feature Functionality (UI Behavior)
Purpose
Feature acts as a parent container for grouping tests/images.
Structure
Feature → Multiple Tests (Images) → Each Test has Runs & Results
UI Behavior
- Feature panel shows list of features
- Clicking a feature:
- Displays all related tests/images
- Shows execution summary
- Allows navigation to comparison
6.Profile (Settings) Module
ProfileController
Purpose
The ProfileController manages user profile-related operations.
It allows users to:
- View profile details
- View and upload profile image
- Change password
APIs
| Method | Endpoint | Description |
|---|---|---|
| GET | /profile/user/{id} | Get user details |
| GET | /profile/image/{id} | Get profile image |
| POST | /profile/image | Upload profile image |
| POST | /profile/change-password | Change password |
1. Get User Details
Request
GET /profile/user/1
Response
{
"id": 1,
"name": "Mrunali",
"email": "user@example.com",
"role": "Admin"
}
2. Get Profile Image
Request
GET /profile/image/1
Response
- Returns image as byte stream (JPEG)
- Content-Type:
image/jpeg
3. Upload Profile Image
Request
POST /profile/image
Form Data:
profileImage→ Image file
Authentication
- Uses logged-in user (
CustomUserDetails) - User ID extracted from token
Response
"Image Uploaded Successfully"
Error Response
"Upload Failed: <error message>"
4. Change Password
Request
POST /profile/change-password
{
"currentPassword": "old123",
"newPassword": "new123"
}
Response
"Password updated"
Error Response
"Current password incorrect"
ProfileService
Purpose
Handles business logic for profile operations such as fetching user data, uploading images, and updating passwords.
Main Methods
1. getUserById(userId)
- Fetches user details
2. getProfileImage(userId)
- Retrieves profile image
- Returns byte array
3. uploadProfileImage(userId, image)
- Validates file
- Stores image in DB
4. changePassword(userId, dto)
Flow
- Fetch user from DB
- Validate current password
- Encode new password (BCrypt)
- Update in DB
Security (Important 🔐)
- Uses PasswordEncoder (BCrypt)
- Password is never stored in plain text
- Uses
matches()for validation
Validation Rules
| Field | Rule |
|---|---|
| userId | Must be valid |
| profile image | Must not be empty |
| currentPassword | Must match DB |
| newPassword | Must not be empty |
Repository Layer (Database Operations)
Stored Procedures Used
| Procedure | Purpose |
|---|---|
| sp_GetUserById | Fetch user details |
| sp_GetProfileImage | Fetch image |
| sp_UpdateProfileImage | Update image |
| sp_UpdatePassword | Update password |
Data Handling
- Image stored as byte[]
- Password stored as hashed value
- Uses
SimpleJdbcCall
Profile Page (UI Behavior)
Purpose
Allows users to manage their personal account settings.
Features
1. View Profile
- Displays user name, email, role
2. Profile Image
- View current profile image
- Upload new image
3. Change Password
- Enter current password
- Enter new password
- Update securely
** 6.Region Module**
Purpose
The Region Module allows users to draw and manage regions on images.
These regions are used to ignore specific areas during image comparison.
Functionality
- Draw region on image
- Save region
- Delete region
- Ignore selected area in comparison
RegionController
Purpose
Handles API requests for saving and deleting regions.
APIs
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/regions/save | Save regions |
| DELETE | /api/regions/delete | Delete a region |
1. Save Regions
Request
POST /api/regions/save?entityType=baseline&entityId=101
Body
[
{ "x": 10, "y": 20, "width": 50, "height": 50 },
{ "x": 100, "y": 120, "width": 30, "height": 30 }
]
Response
true
Behavior
- Saves multiple regions at once
- Overwrites or updates existing regions
- Empty JSON → clears regions
2. Delete Region
Request
DELETE /api/regions/delete?entityType=baseline&entityId=101®ionId=5
Response
true
RegionService
Purpose
Handles business logic, validation, and security for region operations.
Main Methods
1. SaveRegions(...)
- Validates entity type
- Validates JSON structure
- Saves regions in DB
2. DeleteRegion(...)
- Validates inputs
- Deletes specific region
Repository Layer (Database Operations)
1. Save Regions
- Stored Procedure:
sp_SaveRegions
Parameters:
| Parameter | Description |
|---|---|
| p_entityType | baseline / variant / checkpoint |
| p_entityId | Entity ID |
| p_regions_json | JSON string |
2. Delete Region
- Stored Procedure:
sp_DeleteRegion
Parameters:
| Parameter | Description |
|---|---|
| p_entityType | Entity type |
| p_entityId | Entity ID |
| p_regionId | Region ID |