Skip to main content

PixelSense API Code

INDEX
S.NOSectionSub-Section
1IntroductionPurpose of this module
2Project OverviewFeatures & Responsibilities
3Technology StackPackages & Layers
4Security ConfigurationSecurityConfig, JWT
ControllersList of Controllers
AdminController
UserController
CompareController
ComparisonController
  1. 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
  1. 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:

  1. Receive incoming HTTP POST requests at the /compare endpoint.
  2. Validate and extract the multipart files (baseFiles, compareFile) and the optional region JSON string.
  3. Delegate the core business logic (comparison) to the CompareService.
  4. Handle potential exceptions and return a consistent ResponseEntity.
DetailValue
Class NameCompareController
Endpoint/compare
MethodPOST
PurposeAPI entry point for image comparison.
SecurityRequires X-API-KEY header.

2. Spring Boot and Annotation Breakdown​

AnnotationTypePurpose
@RestControllerClassMarks the class as a Spring controller where methods return JSON/XML responses directly (combines @Controller and @ResponseBody).
@RequestMapping("/compare")ClassMaps all methods in this controller to the base path /compare.
@AutowiredFieldInjects the CompareService dependency, enabling access to the comparison logic.
@PostMappingMethodMaps the compareImages method to handle HTTP POST requests at the base path (/compare).
@RequestPartParameterBinds parts of a multipart request to the method parameters (used for MultipartFiles).
@RequestParamParameterBinds 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.

AnnotationPurpose
@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.
@ApiResponseExplicitly 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(...)
StepActionCode Implication
1. LoggingLogs the start of the comparison request, including the number of baseFiles received.logger.info("Received request to compare {} base files", baseFiles.length);
1. DelegationCalls 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 HandlingIf any exception occurs during the comparison process (e.g., file IO error, OpenCV processing error), the catch block executes.catch (Exception e)
1. Error ResponseLogs 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:

  1. CompareService: Injected via @Autowired, this is the service responsible for executing the actual OpenCV image comparison logic.
  2. 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​

DetailValue
Class NameCompareService
Type@Service (Spring Component)
DependenciesQuadTreeService, ContourService, RegionMaskService
Key Functioncompare(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​

  1. Start Timer: Records System.nanoTime() to calculate the total execution duration for performance logging.
  2. Comparison Image Loading:
    • The compareFile (img2) is temporarily saved to the file system using Files.createTempFile().
    • OpenCV reads the file into a Mat object using Imgcodecs.imread().
    • Validation: Checks if img2 is empty (img2.empty()), returning an error if the file is corrupt or not an image.

2.2 Region Mask Application​

  1. The regionJson string (defining select or ignore areas) is passed to the RegionMaskService.apply().
  2. 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.

StepService/Function UsedDescription
1. Load Base ImageImgcodecs.imread()Loads each baseFile (img1) into an OpenCV Mat.
1. Pre-Checkimg1.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 DifferencequadTree.diff(img1, img2)The QuadTreeService runs its recursive algorithm to generate a diffMask (a binary image where white pixels indicate differences).
1. Apply Region FiltercontourService.applyRegionMask(diffMask, regionMask)The initial diffMask is filtered by the regionMask to ignore or select differences based on user configuration.
1. Calculate ScoreCore.countNonZero(masked)Calculates the final diffScore by counting the total number of non-zero pixels (differences) in the filtered mask.
1. Best Match UpdateInternal LogicIf 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​

  1. Contour Detection: The final bestMask is passed to the ContourService.findContours(). This process groups neighboring difference pixels into bounding boxes.
  2. Drawing Boxes: The comparison image (img2.clone()) is passed to ContourService.drawTransparentBoxes(), which draws semi-transparent rectangles over the detected differences (bounding boxes).
  3. Performance: The total execution time is calculated and stored in the timings map.
  4. Response:
    • If bestDiff == 0 (no differences found), ResponseHandler.identical() is called.
    • Otherwise, ResponseHandler.different() is called, using the final output image with the drawn boxes and the list of bounding boxes.

3. Service Dependencies​

DependencyResponsibility
QuadTreeServiceExecutes the pixel-level difference calculation, returning a raw binary mask of differences.
RegionMaskServiceParses user JSON input to create an OpenCV binary mask for selective comparison areas.
ContourServiceConverts scattered difference pixels (diffMask) into grouped, rectangular bounding boxes and draws these boxes onto the final output image.
ResponseHandlerUtility 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​

DetailValueDescription
Class NameQuadTreeServiceImplements the quadtree comparison logic.
MIN_SIZE16The minimum block size (16×16) where recursion stops, forcing a full pixel difference check.
SENSITIVITY5The threshold used in the diffGray method. Pixel differences below this intensity value are ignored.
Key Functiondiff(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.

StepOpenCV FunctionPurpose
1. Absolute DifferenceCore.absdiff(a, b, diff)Calculates the absolute difference between every pixel in a and b (preserving color channels).
1. Grayscale ConversionImgproc.cvtColor(diff, gray, ...)Converts the color difference image to a single-channel grayscale image.
1. ThresholdingImgproc.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:

  1. No Difference Found:
    • Checks if the current block pair (block1, block2) has any difference pixels using Core.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.
  2. Minimum Size Reached:
    • Checks if the block width or height (w or h) is less than or equal to MIN_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).

3.2 Recursive Step​

If neither base case is met, the algorithm proceeds to split the block:

  1. Split: The block is split into four Rect objects (quads), representing the top-left, top-right, bottom-left, and bottom-right quadrants.
  2. Recurse: The quadtreeDiff function is called recursively for each of the four quadrants. This is the mechanism for the tree-like traversal.
  3. Combine Results: The difference masks (sub Mat) returned from the recursive calls are copied back into the appropriate section of the main mask Mat for the current level.
  4. 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​

DetailValueDescription
Class NameRegionMaskServiceGenerates a binary image mask from JSON input.
InputregionJson (String), h (Height), w (Width)User-defined regions and the target image dimensions.
OutputMat (OpenCV Binary Mask)A black-and-white image where White (255) means COMPARE and Black (0) means IGNORE.
Dependenciesorg.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​

  1. Creation: An initial mask (mask) is created using Mat.ones(h, w, CvType.CV_8U). CV_8U indicates an 8-bit, single-channel (grayscale) image.
  2. 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.
  3. No JSON Check: If regionJson is 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:

  1. Ignore Mode (Default): If only ignore regions are present, the mask remains white (compare all), and the ignore areas are marked black.
  2. Select Mode: If at least one select region is found (hasSelect is true), the interpretation changes:
    • The entire mask is first reset to black (0).
    • Only the explicit select areas 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 TypeActionOpenCV OperationEffect on Comparison
selectSets the region in the mask to White (255).mask.submat(...) is set to Scalar(255).Includes this area for difference checking.
ignoreSets 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​

DetailValueDescription
Class NameResponseHandlerUtility class for standardizing API responses.
Design PatternUtility ClassPrivate constructor (private ResponseHandler()) prevents instantiation; all methods are static.
Core FunctionsGenerates 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)​

  1. Encode to JPEG: Uses Imgcodecs.imencode(".JPEG", image, buffer) to encode the OpenCV Mat object into a byte array format (JPEG) and stores it in a MatOfByte buffer.
  2. Base64 Conversion: The byte array from the buffer is then converted into a Base64 string using Base64.getEncoder().encodeToString().
  3. 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 ValueDescription
"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 Status200 OK

different(...)​

This method includes the encoded difference image and details about the detected regions.

Key ValueDescription
"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 Status200 OK

4. Error and Status Handlers​

These methods ensure API failure responses are consistent and map to appropriate HTTP status codes.

MethodHTTP StatusStatus KeyPurpose
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 MethodPurpose
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​

MethodEndpointDescription
POST/api/admin/settingsSaves 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​

ParameterDescription
p_AdminUserIdAdmin ID
p_BaselineLimitMaximum baseline images allowed
p_HighlightColorColor 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​

MethodEndpointDescription
GET/baselineFetch all baseline images
POST/baseline/deleteDelete 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​

FieldDescription
TestIdTest identifier
BaselineImgIdBaseline image ID
BaselineNameName of baseline
FeatureNameFeature associated
BaselineImageImage (Base64 encoded)
BaselineCountTotal baseline images
VariantCountNumber of variants
LastUpdatedDateLast 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
  1. 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​

MethodEndpointDescription
POST/variant/insertInsert a new variant
POST/variant/updateUpdate variant name
DELETE*/variant/deleteDelete a variant (documented feature)

1. Insert Variant​

Request (Query Params)​

POST /variant/insert
ParamDescription
baselineImgIdBaseline image ID
checkpointIdCheckpoint ID
variantNameName of variant
createdByUser ID

Response​

{
"success": true
}

Error Response​

{
"error": "Variant name is required"
}

2. Update Variant​

Request​

POST /variant/update
ParamDescription
variantIdVariant ID
newNameUpdated 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​

MethodEndpointDescription
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:

ParameterDescription
p_BaselineImgIdBaseline ID
p_CheckpointIdCheckpoint ID
p_VariantNameVariant name
p_CreatedByCreated user

2. Delete Variant​

  • Stored Procedure: sp_DeleteBaselineVariant
ParameterDescription
p_VariantIdVariant ID

3. Update Variant Name​

  • Stored Procedure: sp_UpdateBaselineVariantName
ParameterDescription
p_VariantIdVariant ID
p_NewVariantNameNew 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​

MethodEndpointDescription
POST/api/checkpointsCreate a new checkpoint
POST/api/checkpoints/{checkId}/accept-baselineAccept checkpoint as baseline
POST/api/checkpoints/{checkId}/jsonInsert JSON data
POST/api/checkpoints/{checkId}/assignAssign checkpoint to user
PATCH/api/checkpoints/{checkId}/reviewUpdate review status
PATCH/api/checkpoints/user/{userId}/last-loginUpdate last login time

1. Create Checkpoint​

Request​

POST /api/checkpoints
ParamDescription
nidNode/Test ID
userIdCreated user
imageImage (byte array)

Response​

101

Returns checkId


2. Accept Checkpoint as Baseline​

Request​

POST /api/checkpoints/{checkId}/accept-baseline
ParamDescription
checkIdCheckpoint ID
userIdUser performing action
regionsJsonOptional 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
ParamDescription
assignedToUser assigned
assignedByAssigning user
remarksOptional notes

Response​

{
"id": 2,
"name": "John",
"email": "john@example.com"
}

5. Update Review Status​

Request​

PATCH /api/checkpoints/{checkId}/review
ParamDescription
statusapproved / rejected / pending
userIdReviewer

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​

FieldRule
checkId / nidMust be > 0
userIdMust be valid
imageRequired, max 5MB
JSONMust be valid & < 200KB
statusapproved / rejected / pending
remarksMax 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
  • Email

5. Update Review Status​

  • Direct SQL update on checkpoints table

6. Update Last Login Time​

  • Updates user table
  • 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​

MethodEndpointDescription
GET/api/featuresGet all features
POST/api/features/deleteDelete features (batch)
POST/api/features/updateUpdate feature details
GET/api/features/summaryGet image run summary
GET/api/features/imagesGet 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_features table
  • 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_entities table

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​

MethodEndpointDescription
GET/profile/user/{id}Get user details
GET/profile/image/{id}Get profile image
POST/profile/imageUpload profile image
POST/profile/change-passwordChange 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​

  1. Fetch user from DB
  2. Validate current password
  3. Encode new password (BCrypt)
  4. Update in DB

Security (Important 🔐)​

  • Uses PasswordEncoder (BCrypt)
  • Password is never stored in plain text
  • Uses matches() for validation

Validation Rules​

FieldRule
userIdMust be valid
profile imageMust not be empty
currentPasswordMust match DB
newPasswordMust not be empty

Repository Layer (Database Operations)​


Stored Procedures Used​

ProcedurePurpose
sp_GetUserByIdFetch user details
sp_GetProfileImageFetch image
sp_UpdateProfileImageUpdate image
sp_UpdatePasswordUpdate 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​

MethodEndpointDescription
POST/api/regions/saveSave regions
DELETE/api/regions/deleteDelete 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&regionId=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:

ParameterDescription
p_entityTypebaseline / variant / checkpoint
p_entityIdEntity ID
p_regions_jsonJSON string

2. Delete Region​

  • Stored Procedure: sp_DeleteRegion

Parameters:

ParameterDescription
p_entityTypeEntity type
p_entityIdEntity ID
p_regionIdRegion ID