This backend application was developed using the Java Spring Boot framework and integrates with PostgreSQL with PostGIS extension to handle spatial data operations. It provides a robust RESTful interface for managing geometric data, offering comprehensive support for various geometry types including points, linestrings, polygons, and their multi-geometry counterparts.
The system utilizes Hibernate Spatial for object-relational mapping and LocationTech JTS for core spatial functionality. It features dual input formats: a serializer approach accepting coordinate arrays and a deserializer approach accepting GeoJSON geometry objects. Both formats are converted to JTS geometries and persisted in the PostgreSQL database with proper spatial indexing and SRID configuration.
To ensure clean separation of concerns, the application adopts a layered architecture with Controller, Service, and Repository components. It implements custom JSON serializers/deserializers for seamless conversion between JTS geometries and GeoJSON format, enabling interoperability with modern GIS tools and web mapping libraries.
The application maintains code quality standards through a comprehensive testing strategy using JUnit 5 and Mockito, following the AAA pattern (Arrange-Act-Assert) with enforced code coverage via JaCoCo. This ensures reliability and maintainability while handling complex spatial data transformations.
Beyond basic CRUD operations, the system provides specialized endpoints for retrieving geometries as standardized GeoJSON, supporting visualization in tools like geojson.io. The application demonstrates practical spatial data management patterns including coordinate validation, geometry creation, format transformation between industry standards, and comprehensive error handling for spatial data integrity.
The generated GeoJSON responses can be directly visualized using tools like geojson.io, which provides multiple map visualization options including Standard Satellite view. When using the satellite visualization mode, the map displays the following attribution properties:
Map Visualization Properties (Standard Satellite View):
- Base Map Provider: Β© Mapbox (map rendering and tiles);
- Data Source: Β© OpenStreetMap (open geographic data);
- Satellite Imagery: Β© Maxar (high-resolution satellite imagery);
- Interface: geojson.io web platform with options for Standard, Satellite, Outdoors, and Dark themes;
- Map Improvement: "Improve this map" option for community contributions to OpenStreetMap;
- Platform Features: Open, Save, New, Meta search functionality with Dropbox integration.
Geographic Region Description: The polygon is situated in the municipality of Socorro, SΓ£o Paulo, Brazil, within the Mantiqueira Mountain Range region. In satellite view, this area displays characteristic features of the Brazilian Highlands, including:
Regional Characteristics Visible in Satellite Imagery:
- Topography: Rolling hills and moderate elevation variations typical of the Mantiqueira foothills, with elevations ranging from 700-850 meters above sea level;
- Land Cover: Mixed agricultural patterns with pasturelands, small farming plots, and remnant Atlantic Forest vegetation corridors;
- Urban-Rural Interface: Clear transition from dense urban fabric in Socorro's center to dispersed rural settlements in the OratΓ³rio do Meio neighbourhood;
- Hydrology: Small watercourses and tributaries feeding into the Camanducaia River basin, visible as dendritic drainage patterns;
- Infrastructure: Road networks including SP-139 connecting rural properties to the municipal seat, visible as linear features crossing the undulating terrain;
- Settlement Patterns: Clustered rural properties surrounded by agricultural lands, gradually densifying toward the urban core.
The satellite imagery reveals the polygon's coverage spanning from the OratΓ³rio do Meio neighbourhood in the western rural area (characterized by larger property boundaries and extensive agricultural patterns) toward the urban center of Socorro (showing denser settlement patterns, institutional buildings, and infrastructure development). The visualization clearly demonstrates the geographic relationship between the rural property "SΓtio Lobisomem" and the urban landmark "ParΓ³quia Nossa Senhora do PerpΓ©tuo Socorro" within the polygon's extent.
The Standard Satellite view provides excellent context for understanding the terrain morphology, land use patterns, and spatial relationships within the polygon, making it an ideal tool for validating spatial data accuracy and conducting preliminary geographic analysis of the Socorro region's distinctive landscape characteristics.
Request:
POST /api/spatial-data/serializer
Content-Type: application/json
{
"point": [-46.579236, -22.593365],
"multipoint": [
[-46.579236, -22.593365],
[-46.568894, -22.604582],
[-46.548613, -22.596784],
[-46.537113, -22.601331],
[-46.529434, -22.592137]
],
"linestring": [
[-46.579236, -22.593365],
[-46.568894, -22.604582],
[-46.548613, -22.596784],
[-46.537113, -22.601331],
[-46.529434, -22.592137]
],
"polygon": [
[
[-46.579236, -22.593365],
[-46.568894, -22.604582],
[-46.548613, -22.596784],
[-46.537113, -22.601331],
[-46.529434, -22.592137],
[-46.579236, -22.593365]
]
]
}Response:
{
"id": 1,
"point": {
"type": "Point",
"coordinates": [-46.579236, -22.593365]
},
"multipoint": {
"type": "MultiPoint",
"coordinates": [
[-46.579236, -22.593365],
[-46.568894, -22.604582],
[-46.548613, -22.596784],
[-46.537113, -22.601331],
[-46.529434, -22.592137]
]
},
"linestring": {
"type": "LineString",
"coordinates": [
[-46.579236, -22.593365],
[-46.568894, -22.604582],
[-46.548613, -22.596784],
[-46.537113, -22.601331],
[-46.529434, -22.592137]
]
},
"polygon": {
"type": "Polygon",
"coordinates": [[
[-46.579236, -22.593365],
[-46.568894, -22.604582],
[-46.548613, -22.596784],
[-46.537113, -22.601331],
[-46.529434, -22.592137],
[-46.579236, -22.593365]
]]
}
}The provided polygon encompasses an area within the municipality of Socorro, SΓ£o Paulo, Brazil, representing a significant territorial extent that connects rural and urban landscapes of the region. The geometry spans approximately 5.5 kilometers in length and covers an estimated area of 15-18 square kilometers based on coordinate analysis.
Spatial Coverage Analysis: The polygon's vertices delineate a territory that connects the rural property SΓtio Lobisomem, located in the OratΓ³rio do Meio neighbourhood (western Socorro), with the urban center featuring the ParΓ³quia Nossa Senhora do PerpΓ©tuo Socorro. This creates a geographic corridor that bridges agricultural lands with the municipal seat.
Coordinate Extremes & Dimensions: - Northernmost Point: [-46.529434, -22.592137] - Near SΓtio Lobisomem area; - Southernmost Point: [-46.568894, -22.604582] - Approaching urban center; - Longitudinal Span: ~5.5 km (0.0498Β° longitude); - Latitudinal Span: ~1.3 km (0.0124Β° latitude); - Geometric Shape: Irregular pentagon with concave characteristics.
Geographic Significance: The polygon captures the transitional zone between Socorro's rural hinterlands and urban core, representing typical SΓ£o Paulo interior topography with elevation variations between 700-800 meters above sea level. The area likely includes portions of the Mantiqueira Mountain Range foothills, characterized by rolling hills and small watercourses that feed into the Camanducaia River basin.
Request:
POST /api/spatial-data/deserializer
Content-Type: application/json
{
"point": {
"type": "Point",
"coordinates": [-46.579236, -22.593365]
},
"polygon": {
"type": "Polygon",
"coordinates": [[
[-46.579236, -22.593365],
[-46.568894, -22.604582],
[-46.548613, -22.596784],
[-46.537113, -22.601331],
[-46.529434, -22.592137],
[-46.579236, -22.593365]
]]
}
}Request:
GET /api/spatial-data/1/geojsonResponse:
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [[
[-46.579236, -22.593365],
[-46.568894, -22.604582],
[-46.548613, -22.596784],
[-46.537113, -22.601331],
[-46.529434, -22.592137],
[-46.579236, -22.593365]
]]
},
"properties": {
"description": "Polygon covering Socorro-SP region from SΓtio Lobisomem to urban center",
"id": 1,
"municipality": "Socorro",
"state": "SΓ£o Paulo",
"country": "Brazil",
"area_km2": 16.8,
"landmarks": ["SΓtio Lobisomem", "OratΓ³rio do Meio", "ParΓ³quia Nossa Senhora do PerpΓ©tuo Socorro"]
}
}Request:
GET /api/spatial-dataResponse:
[
{
"id": 1,
"point": {
"type": "Point",
"coordinates": [-46.579236, -22.593365]
},
"polygon": {
"type": "Polygon",
"coordinates": [[
[-46.579236, -22.593365],
[-46.568894, -22.604582],
[-46.548613, -22.596784],
[-46.537113, -22.601331],
[-46.529434, -22.592137],
[-46.579236, -22.593365]
]]
},
"linestring": {
"type": "LineString",
"coordinates": [
[-46.579236, -22.593365],
[-46.568894, -22.604582],
[-46.548613, -22.596784],
[-46.537113, -22.601331],
[-46.529434, -22.592137]
]
}
}
]Topographic Analysis: The polygon's coordinate distribution suggests a terrain with moderate elevation changes, typical of the Brazilian Highlands region. The area likely experiences the Cwb climate classification (subtropical highland climate) characteristic of Socorro municipality, with mild temperatures and well-defined seasonal patterns.
Hydrological Context: Based on the geographic position, the polygon likely encompasses small tributaries feeding into the Camanducaia River system, which is part of the larger Piracicaba River basin - a crucial water resource for SΓ£o Paulo state's interior regions.
Land Use Patterns: The spatial extent captures the transition from agricultural lands (coffee, dairy farming, and mixed agriculture typical of the region) to urban settlement patterns, representing Socorro's economic and social geography where traditional rural activities coexist with growing urban development.
| Technology | Version | Description |
|---|---|---|
| β Java | 21 |
Backend programming language |
| π± Spring Boot | 3.5.7 |
Core framework for building backend services |
| π PostgreSQL | Latest |
Advanced relational database with spatial capabilities |
| πΊοΈ PostGIS | 3.3+ |
Spatial database extender for PostgreSQL |
| πΎ Hibernate Spatial | 6.6.33 |
ORM extension for spatial data types |
| π JTS Topology Suite | 1.19.0 |
Java library for spatial operations and algorithms |
| π SpringDoc OpenAPI | 2.8.14 |
Automatic REST API documentation with Swagger UI |
| π§ͺ JUnit / JaCoCo | - | Testing framework with code coverage reporting |
| π§ Maven | 3.9.9 |
Build automation and dependency management tool |
| Dependency | Category | Description |
|---|---|---|
| π Spring Web | Web | Builds web applications, including RESTful APIs, using Spring MVC. Uses Apache Tomcat as the default container. |
| πΎ Spring Data JPA | SQL | Facilitates database access using JPA with Spring Data and Hibernate. |
| πΊοΈ Hibernate Spatial | Spatial | Provides spatial data types and functions for Hibernate JPA. |
| π PostgreSQL Driver | SQL | JDBC driver enabling Java applications to interact with PostgreSQL database. |
| βοΈ Validation | Validation (I/O) | Enables Java Bean Validation using Jakarta Validator. |
| π SpringDoc OpenAPI | Documentation | Generates Swagger UI automatically for REST API endpoints. |
| π GeoJSON Jackson | Spatial | Library for working with GeoJSON format in Java applications. |
| π Java Dotenv | Configuration | Loads environment variables from .env files for application configuration. |
The application follows a Layered Architecture with clear separation of concerns, ensuring maintainability, testability, and scalability. The architecture is structured around four main layers that handle specific responsibilities in the spatial data processing pipeline.
ββββββββββββββββββββββββββββββββββββββββββββββ
β Application β
ββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββββββββββββββββ
β Rest Controller Layer β
ββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββββββββββββββββ
β Service Layer ββ β
ββββββββββββββββββββββββ Model β
β β (Entity and DTOs) β
ββββββββββββββββββββββββ β
β Repository Layer ββ β
ββββββββββββββββββββββββββββββββββββββββββββββ
The Application Layer serves as the entry point, initializing the Spring Boot context and configuring the runtime environment. It handles dependency injection and application lifecycle management through the @SpringBootApplication annotation.
The REST Controller Layer (SpatialDataController) exposes HTTP endpoints for spatial data operations, handling request validation, content negotiation, and response formatting. It provides two distinct creation endpoints: /serializer for coordinate-based input and /deserializer for GeoJSON geometry input, following RESTful principles.
The Service Layer (SpatialDataService) contains the core business logic for spatial operations. This layer handles geometry creation from coordinates, validation of spatial constraints, transformation between JTS geometries and GeoJSON format, and orchestration of data persistence operations. It implements the spatial algorithms and coordinate processing logic.
The Repository Layer (SpatialDataRepository) abstracts data access using Spring Data JPA with Hibernate Spatial, providing CRUD operations for spatial entities. This layer leverages PostgreSQL's PostGIS extension for spatial indexing and geographic queries.
The Model Layer encompasses both entities (SpatialData) and Data Transfer Objects (DTOs) that define the data structure. The entity model maps to database tables with spatial column definitions, while DTOs handle request/response payloads and ensure clean separation between persistence and API contracts.
This architectural approach ensures that spatial data flows consistently through the application layers, with each layer having well-defined responsibilities and clear boundaries, facilitating testing, maintenance, and future enhancements to the spatial data processing capabilities.
---
The core entity SpatialData encapsulates all supported geometry types within a single table structure, leveraging PostgreSQL's PostGIS extension for spatial storage and operations. Each geometry field uses SRID 4326 (WGS84) for consistent coordinate reference system handling.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SpatialData β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β - id : Long β
β - point : Point (Geometry - SRID 4326) β
β - multiPoint : MultiPoint (Geometry - SRID 4326) β
β - lineString : LineString (Geometry - SRID 4326) β
β - multiLineString : MultiLineString (Geometry - SRID 4326) β
β - polygon : Polygon (Geometry - SRID 4326) β
β - multiPolygon : MultiPolygon (Geometry - SRID 4326) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
β (Contains)
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Geometry Hierarchy β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β <<interface>> β
β Geometry β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β Point β MultiPoint β LineString β
β - coordinate : Coordinate - points : Point[] - coordinates : Coordinate[] β
β - SRID : int - SRID : int - SRID : int β
β β
β β Polygon β MultiLineString β MultiPolygon β
β - shell : LinearRing - lineStrings : LineString[] - polygons : Polygon[] β
β - holes : LinearRing[] - SRID : int - SRID : int β
β - SRID : int β
β β
β β Coordinate β
β - x : double β
β - y : double β
β - z : double β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββββββββββββββββ
β Geometry Types β
ββββββββββββββββββββββββββββ€
β Point β
β MultiPoint β
β LineString β
β MultiLineString β
β Polygon β
β MultiPolygon β
ββββββββββββββββββββββββββββ
ββββββββββββββββββββββββββββ
β SRID 4326 β
ββββββββββββββββββββββββββββ€
β WGS84 Coordinate β
β Reference System β
β (Longitude/Latitude) β
ββββββββββββββββββββββββββββ
The entity design allows for flexible storage of multiple geometry types within a single record, supporting various spatial data scenarios from simple points to complex multi-polygon structures. All geometries adhere to the Open Geospatial Consortium (OGC) standards and can be efficiently queried using PostGIS spatial functions.
Below is a detailed explanation of the core spatial algorithms and business logic implemented in the SpatialDataService, which handles all geometry-related operations including creation, validation, and format transformation.
createFromSerializerFormat(): Accepts coordinate arrays and creates JTS geometries through a multi-step validation and construction process. Validates coordinate dimensions and geometry-specific constraints before geometry creation.createFromDeserializerFormat(): Accepts GeoJSON geometry objects and maps them directly to JTS geometries, leveraging custom deserialization logic.hasValidPointCoordinates(): Ensures point geometries have exactly 2 coordinates (longitude, latitude) following the GeoJSON coordinate order.hasValidPolygonCoordinates(): Validates that polygons contain at least 4 coordinates to form a closed ring, with the first and last coordinates being identical.
createPoint(): Constructs JTS Point geometries from [x,y] coordinate pairs using SRID 4326 (WGS84).createPolygon(): Builds Polygon geometries from coordinate rings, creating exterior rings and validating topological closure.createMultiPoint(): Aggregates multiple points into a single MultiPoint geometry collection.createLineString(): Creates linear geometries from sequences of coordinate pairs.createMultiPolygon(): Constructs complex multi-polygon geometries from multiple polygon definitions.
convertToGeoJsonGeometry(): Transforms JTS geometries into GeoJSON-compliant objects with proper type mapping and coordinate structure.getPolygonAsGeoJson(): Specialized method that retrieves polygon geometries and returns them as standardized GeoJSON Feature objects.createGeoJsonPolygon(): Converts JTS Polygon to GeoJSON Polygon format with proper coordinate array nesting for exterior rings.
GeometrySerializer: Custom Jackson serializer that converts JTS geometries to JSON with proper type information and coordinate arrays.GeometryDeserializer: Custom Jackson deserializer that parses GeoJSON geometry objects and creates corresponding JTS geometry instances.
PostgreSQL with PostGIS was chosen over specialized spatial databases due to its robust spatial capabilities, excellent Spring Boot integration, and widespread adoption. The trade-off includes slightly more complex setup compared to in-memory databases but provides production-ready spatial operations with full OGC standard compliance.
Hibernate Spatial with JTS was selected for ORM spatial support instead of alternative spatial libraries. This provides type-safe spatial operations and seamless JPA integration, though it requires careful configuration of dialect and column definitions for proper geometry type mapping.
Dual Input Format Approach (Serializer/Deserializer) was implemented to support both developer-friendly coordinate arrays and standards-compliant GeoJSON. This increases API complexity but provides flexibility for different client needs and interoperability with GIS tools while maintaining data consistency.
Custom JSON Serialization was developed instead of using out-of-the-box solutions to ensure precise control over GeoJSON output format and proper handling of JTS geometry hierarchy. This requires maintenance of custom serialization logic but guarantees standards compliance and optimal performance for spatial data transformations.
SRID 4326 (WGS84) was standardized for all geometries to ensure consistent coordinate reference system across the application. This aligns with web mapping standards and GeoJSON specifications but may require transformation for applications using other coordinate systems or projections.
Centralized Message Management through the Messages utility class ensures consistent validation messages, error responses, and API documentation. This supports future internationalization and maintainability but adds an abstraction layer that requires disciplined usage across all application components.
AAA Testing Pattern (Arrange-Act-Assert) was adopted throughout the test suite to enforce clarity, readability, and maintainability. This structured approach ensures consistent test organization but requires additional discipline in test setup and may increase initial test development time.
JaCoCo Code Coverage Enforcement with strict thresholds (80% instruction coverage, 70% branch coverage) was implemented to ensure code quality and test completeness. This provides confidence in code reliability but may slow development velocity during initial implementation phases due to coverage requirements.
Mockito-Based Dependency Isolation was chosen for unit testing to enable focused testing of individual components without external dependencies. This provides fast, reliable tests but requires careful mocking strategy to avoid testing implementation details rather than behavior.
Multi-Layer Testing Strategy covering service, controller, configuration, and serialization layers ensures comprehensive quality assurance. This approach provides defense in depth but increases test maintenance overhead and requires coordinated testing practices across the development team.
- PostgreSQL 12+ with PostGIS extension enabled;
- Java 21 Development Kit;
- Maven 3.9+.
-- Create database with PostGIS extension
CREATE DATABASE spatialpostgis;
\c spatialpostgis;
CREATE EXTENSION postgis;
-- Verify PostGIS installation
SELECT PostGIS_Version();Create .env file in project root:
DATABASE_URL=jdbc:postgresql://localhost:5432/spatialpostgis
DATABASE_USERNAME=postgres
DATABASE_PASSWORD=your_password# Clone and navigate to project
git clone https://github.com/souzafcharles/hibernate-spatial-postgis-jts.git
cd spatial-postgis-demo
# Build and run application
mvn clean install
mvn spring-boot:run- API Documentation: http://localhost:8080/swagger-ui.html
- Health Check: http://localhost:8080/api/spatial-data
- GeoJSON Visualization: https://geojson.io
The application implements a comprehensive Test-Driven Development (TDD) approach with extensive unit testing coverage across all layers of the architecture. The testing strategy follows the AAA pattern (Arrange-Act-Assert) and utilizes modern testing frameworks to ensure code quality, reliability, and maintainability.
The test suite employs JUnit 5 as the core testing framework, Mockito for mocking dependencies, and JaCoCo for code coverage analysis. All tests are organized by architectural layer and functionality, providing clear separation of concerns and facilitating targeted testing of specific components.
The testing approach emphasizes behavior verification over implementation details, ensuring that tests remain resilient to refactoring while validating the correct behavior of the spatial data processing pipeline. Each test class focuses on a single responsibility and includes both positive and negative test scenarios.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Testing Pyramid β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Unit Tests (85%) β β
β β - Service Layer: SpatialDataServiceTest β β
β β - Controller Layer: SpatialDataControllerTest β β
β β - Configuration: JacksonConfigTest, OpenApiConfigTest β β
β β - JSON Serialization: Geometry(De)SerializerTest β β
β β - Exception Handling: GlobalExceptionHandlerTest β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Integration Tests (10%) β β
β β - Application Bootstrap: SpringBootAppTest β β
β β - Environment Configuration: LoadEnvironmentTest β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β End-to-End Tests (5%) β β
β β - Postman Collection (API Contract Testing) β β
β β - GeoJSON Visualization Validation β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
The SpatialDataServiceTest class provides comprehensive unit testing for the core business logic, covering all geometry creation, validation, and transformation operations with 98% method coverage and 95% branch coverage.
Key Test Categories:
- Geometry Creation: Tests for both serializer (coordinate arrays) and deserializer (GeoJSON) formats;
- Validation Logic: Coordinate validation, polygon closure verification, and geometry constraints;
- GeoJSON Transformation: Conversion of JTS geometries to standardized GeoJSON format;
- Error Handling: Exception scenarios for invalid inputs and missing data;
- Edge Cases: Empty collections, null values, boundary conditions, and malformed geometries.
Example Test Structure:
@Test
void createFromSerializerFormat_WithValidData_ShouldSaveAndReturnResponse() {
// Arrange
SpatialDataSerializerRequestDTO request = new SpatialDataSerializerRequestDTO(
pointCoordinates, multiPointCoordinates, lineStringCoordinates,
multiLineStringCoordinates, polygonCoordinates, multiPolygonCoordinates
);
// Act
SpatialDataResponseDTO result = spatialDataService.createFromSerializerFormat(request);
// Assert
assertNotNull(result);
assertEquals(1L, result.id());
verify(spatialDataRepository, times(1)).save(any(SpatialData.class));
}
The SpatialDataControllerTest verifies the REST API contract, ensuring proper HTTP status codes, response formats, and exception propagation from the service layer to API consumers.
Test Coverage:
- HTTP Endpoint Validation: All REST endpoints (GET, POST) with correct status codes;
- Request/Response Mapping: Proper DTO serialization and deserialization;
- Exception Propagation: Service layer exceptions correctly mapped to HTTP responses;
- Integration Points: Service method invocation verification with Mockito.
Controller Test Example:
@Test
void createFromSerializer_WithValidRequest_ShouldReturnOk() {
// Arrange
SpatialDataSerializerRequestDTO request = createValidRequest();
when(spatialDataService.createFromSerializerFormat(request))
.thenReturn(mockResponse);
// Act
ResponseEntity<SpatialDataResponseDTO> result =
spatialDataController.createFromSerializer(request);
// Assert
assertEquals(HttpStatus.OK, result.getStatusCode());
verify(spatialDataService, times(1)).createFromSerializerFormat(request);
}The custom JSON serialization components are thoroughly tested to ensure proper conversion between JTS geometries and GeoJSON format, maintaining compliance with OGC standards.
Serialization Test Coverage:
- Point Serialization: Coordinate array generation and type information;
- Polygon Handling: Exterior ring coordinates and proper closure;
- LineString Conversion: Coordinate sequence preservation;
- Null Safety: Graceful handling of null geometries and empty coordinates;
- Error Conditions: Malformed JSON and unsupported geometry types.
Deserialization Test Coverage:
- GeoJSON Parsing: Correct interpretation of GeoJSON geometry objects;
- Coordinate Validation: Proper handling of coordinate arrays and validation;
- Type Mapping: Accurate conversion between GeoJSON types and JTS geometries;
- Edge Cases: Empty arrays, null values, and invalid coordinate structures.
Configuration components are tested to ensure proper application startup and environment configuration, validating Spring Boot context initialization and dependency injection.
Configuration Test Classes:
JacksonConfigTest: ObjectMapper bean configuration with custom geometry modules;OpenApiConfigTest: Swagger/OpenAPI documentation generation;LoadEnvironmentTest: Environment variable loading and system property configuration;SpringBootSpatialPostGisApplicationTest: Application bootstrap and main method execution.
The global exception handler is comprehensively tested to ensure consistent error responses across the API, with proper HTTP status codes and structured error messages.
Exception Test Coverage:
- Entity Not Found: 404 responses with proper messaging;
- Validation Errors: 400 responses for constraint violations;
- Data Access Issues: 500 responses for database errors;
- JSON Parsing Errors: 400 responses for malformed requests.
- Custom Business Logic: Application-specific exception handling.
The test suite employs a consistent data management strategy with reusable test data factories and comprehensive mocking of external dependencies to ensure test isolation and reproducibility.
Mocking Strategy:
- Repository Layer: Complete mocking of
SpatialDataRepositoryto isolate business logic; - Service Dependencies: Mocked service layer in controller tests;
- External Systems: No actual database or external API calls in unit tests;
- Static Methods: Mocked static method calls using Mockito's
mockStatic.
Test Data Patterns:
// Reusable test coordinates
private final List<Double> pointCoordinates = Arrays.asList(1.0, 2.0);
private final List<List<Double>> polygonCoordinates = Arrays.asList(
Arrays.asList(0.0, 0.0), Arrays.asList(0.0, 1.0),
Arrays.asList(1.0, 1.0), Arrays.asList(1.0, 0.0), Arrays.asList(0.0, 0.0)
);The project maintains high code quality standards through automated quality gates and comprehensive coverage requirements enforced by the Maven build process.
JaCoCo Coverage Requirements:
- Instruction Coverage: β₯ 80% (validates line-by-line execution);
- Branch Coverage: β₯ 70% (ensures decision path testing);
- Method Coverage: β₯ 85% (comprehensive API testing);
- Class Coverage: β₯ 90% (architectural completeness).
Quality Gates:
- Build Failure: On coverage threshold violations;
- Test Execution: Mandatory during CI/CD pipeline;
- Report Generation: Automated HTML reports for coverage analysis;
- Integration: Maven Surefire for test execution and reporting.
Test Execution:
# Run all tests with coverage
mvn clean test jacoco:report
# Run specific test class
mvn test -Dtest=SpatialDataServiceTest
# Generate coverage report only
mvn jacoco:reportCoverage Report Location:
# View detailed coverage analysis
open target/site/jacoco/index.htmlThe comprehensive testing strategy ensures that the spatial data application maintains high reliability standards while facilitating continuous integration and deployment practices. The test suite serves as executable documentation, clearly demonstrating the expected behavior of all system components and providing confidence for future enhancements and refactoring efforts.
π Download Brazilian Capitals Collection
A comprehensive Postman collection accompanies this project, providing complete testing coverage for all spatial data operations. Import the collection file into Postman, Insomnia, or Thunder Client to immediately begin testing the API's full capabilities with real geographic data from Brazilian capitals.
The collection includes 12 Brazilian capitals with varying polygon complexities, covering:
- Multiple Geometry Types: Points, MultiPoints, LineStrings, MultiLineStrings, Polygons, and MultiPolygons;
- Diverse Geographic Regions: From Amazon rainforest (Manaus) to southern plains (Porto Alegre);
- Various Polygon Complexities: 5 to 10-point polygons representing different urban patterns;
- Dual Input Formats: Both Serializer (coordinate arrays) and Deserializer (GeoJSON) endpoints.
The collection features spatial data from:
- SΓ£o Paulo (5-point polygon - Centro Expandido);
- Rio de Janeiro (7-point polygon - Zona Sul);
- BrasΓlia (9-point polygon - Plano Piloto);
- Salvador (6-point polygon - Centro HistΓ³rico);
- Fortaleza (8-point polygon - Praia de Iracema);
- Belo Horizonte (10-point polygon - RegiΓ£o Central);
- Manaus (7-point polygon - Centro);
- Recife (6-point polygon - Centro HistΓ³rico);
- Curitiba (8-point polygon - Centro);
- Porto Alegre (7-point polygon - Centro);
- BelΓ©m (6-point polygon - Cidade Velha);
- GoiΓ’nia (8-point polygon - Setor Central).
The collection supports end-to-end spatial data testing:
- Data Creation: Both Serializer (coordinate arrays) and Deserializer (GeoJSON) formats;
- Data Retrieval: Get all records, get by ID, and specialized GeoJSON endpoints;
- Visualization Validation: Direct GeoJSON output compatible with mapping tools;
- Error Scenarios: Invalid coordinates, malformed geometries, and edge cases;
- Performance Testing: Multiple geometry types within single requests.
All generated GeoJSON responses can be directly visualized using tools like geojson.io. Simply copy the GeoJSON response from any /api/spatial-data/{id}/geojson endpoint and paste it into geojson.io to see the spatial features rendered on an interactive map with satellite imagery.
The collection enables testing of complete spatial workflows:
- Geometry Creation β Storage β Retrieval β Visualization pipeline;
- Coordinate System Validation: All geometries use SRID 4326 (WGS84);
- Format Transformation: JTS geometries β GeoJSON standardization;
- Multi-geometry Support: Complex spatial relationships and collections;
- API Contract Validation: RESTful endpoints with proper HTTP status codes.
This comprehensive collection serves as both a testing tool and learning resource, demonstrating practical spatial data management patterns with real-world geographic examples from across Brazil's diverse landscape.
This project implements a comprehensive spatial data management system using Spring Boot, PostgreSQL with PostGIS, and JTS Topology Suite, successfully addressing the challenge of handling geometric data in a Java enterprise application. It demonstrates practical integration of spatial databases with modern web frameworks while maintaining high standards of software quality through rigorous testing practices.
Key achievements:
- Spatial Database Integration using PostgreSQL with PostGIS extension, providing robust spatial indexing and operations with full SRID 4326 support for geographic coordinates.
- Dual Input Format Support offering both coordinate arrays and GeoJSON standards for maximum flexibility and interoperability with various client applications.
- Custom Serialization Architecture enabling seamless bidirectional conversion between JTS geometries and GeoJSON format with proper type mapping and coordinate handling.
- Comprehensive Geometry Support for all OGC simple feature types including points, linestrings, polygons, and their multi-geometry variants with proper validation.
- Production-Ready API with proper validation, centralized exception handling, OpenAPI documentation, and RESTful design principles.
- Visualization Compatibility with standard GIS tools like geojson.io through proper GeoJSON output formatting and spatial data standardization.
- Comprehensive Testing Strategy with 85% unit test coverage, AAA pattern implementation, and multi-layer testing across service, controller, serialization, and configuration components.
- Quality Assurance through JaCoCo code coverage enforcement, Mockito-based dependency isolation, and consistent error response handling.
- Configuration Management with environment-based database configuration, custom Jackson serialization setup, and automated OpenAPI documentation generation.
The testing suite demonstrates exceptional thoroughness, covering 98% of service methods and 95% of decision branches while maintaining clear separation between unit, integration, and end-to-end testing layers. The architecture successfully balances spatial data complexity with clean code principles, providing a maintainable and extensible foundation for geospatial applications.
This solution provides a solid foundation for spatial applications, demonstrating proven patterns for spatial data persistence, format transformation, and web API design that can be extended with additional spatial operations, analysis capabilities, and real-world geographic data processing scenarios. The project stands as a reference implementation for Java-based spatial data management with production-ready quality standards.
LocationTech. (n.d.). JTS Topology Suite. Retrieved from https://locationtech.github.io/jts/
Murat ΓksΓΌzer. (n.d.). Geospatial Workshop [Video playlist]. YouTube. https://www.youtube.com/playlist?list=PLzIvGBaDt2yY5p2JsBJwulNbxbJ_su9op
Nelio Alves. (s.d.). Complete Java Object-Oriented Programming + Projects [Course]. Udemy. https://www.udemy.com/course/java-curso-completo/
PostGIS Documentation. (n.d.). PostGIS Manual. Retrieved from https://postgis.net/documentation/
