diff --git a/.gitignore b/.gitignore index 9134dbe6f4..a8776789a9 100644 --- a/.gitignore +++ b/.gitignore @@ -26,15 +26,18 @@ test.txt .vscode authentication-demo-ui/keys/ -# Local / IDE (Eclipse, STS, IntelliJ) +# Local run artifacts (run-local) and IDEs (Eclipse, STS, IntelliJ) .local/ -.local +**/.local/ .idea/ -.idea +**/.idea/ .classpath .project .settings/ */.classpath */.project */.settings/ +**/.classpath +**/.project +**/.settings/ .sts4-cache/ \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index 3e94775dc2..5a6d736910 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,10 +13,10 @@ mosip-ref-impl/ │ ├── kernel-smsserviceprovider-msg91/ SMS SPI → AGENTS.md │ └── kernel-virusscanner-clamav/ VirusScanner → AGENTS.md ├── keycloak/ login FTL → AGENTS.md -├── pre-registration-booking-service/ /appointment/** → AGENTS.md +├── pre-registration-booking-service/ /appointment/** run-local → AGENTS.md ├── registration-processor/ registration-processor-ref-parent → AGENTS.md -│ ├── registration-processor-external-stage/ Vert.x → EIS → AGENTS.md -│ └── registration-processor-external-integration-service/ EIS stub REST → AGENTS.md +│ ├── registration-processor-external-stage/ Vert.x → EIS run-local → AGENTS.md +│ └── registration-processor-external-integration-service/ EIS stub REST run-local → AGENTS.md ├── helm/prereg-booking/ javaOpts → JDK_JAVA_OPTIONS → AGENTS.md ├── licenses/ NOTICE texts ├── .github/ CI; never read keys/ → AGENTS.md diff --git a/README.md b/README.md index f9ddc5aa9a..1d79f6166c 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ There is **no repo-root POM** and **no `kernel-bom`**. Standalone modules parent - [Prerequisites](#prerequisites) - [Shared facts](#shared-facts) - [Build](#build) +- [Local testing (run-local)](#local-testing-run-local) - [Tests and coverage](#tests-and-coverage) - [Configuration](#configuration) - [Swagger UI (Authorize)](#swagger-ui-authorize) @@ -92,7 +93,7 @@ Each module has its own `README.md` with artifact id, build, config, and (where | Docker | latest stable (optional) | | PostgreSQL | **16.0** (booking / MOSIP stack) | | Keycloak | [mosip/keycloak](https://github.com/mosip/keycloak/tree/master) | -| Spring Cloud Config | required for services (see [Configuration](#configuration)) | +| Spring Cloud Config | required **on cluster** (see [Configuration](#configuration)). Laptop smoke uses profile `local` — see [Local testing (run-local)](#local-testing-run-local) | ### Runtime JARs for services @@ -137,12 +138,141 @@ Run a single test class: mvn test -Dtest=ClassName[#method] ``` -Start a Boot service from the IDE (`BookingApplication`, `ExternalIntegrationServiceApplication`) or: +For a laptop process **without** config-server, use the module `run-local` scripts (next section). Cluster / Docker still starts the JAR with the Dockerfile config-server flags and **does not** activate profile `local`. + +## Local testing (run-local) + +The three runnable services ship the same command shape as commons `kernel-notification-service`: `init`, `start`, `smoke`, `stop`, `test`, `all`. Each module keeps laptop-only settings in `src/main/resources/application-local.properties` and activates them with **`-Dspring.profiles.active=local`**. Packaged `bootstrap.properties` is unchanged. Dockerfiles still pass `spring_config_url_env` / `active_profile_env` / config label — they never set profile `local`, so a cluster node does not read these files. + +Artifacts, PIDs, and logs go under each module’s `.local/` (gitignored). + +### Prerequisites + +- JDK **21** and Maven **3.9.6** on `PATH` +- `curl` on Windows `smoke` (Git for Windows / Windows 10+). Linux/macOS smoke also accepts `python3` +- Unpublished MOSIP SNAPSHOTs installed locally if they are not on Central (booking: `pre-registration-core`; external-stage: `registration-processor-core`, status-service-impl, rest-client) + +### Commands (same on every module) + +| Command | What it does | +|---|---| +| `init` | Stops a leftover process, then `mvn clean package` (skip tests, skip GPG/Javadoc) | +| `test` | `mvn test` for that module | +| `start` | `java -jar` with profile `local`, waits until ready, prints URLs | +| `smoke` | HTTP checks (health + OpenAPI for Boot services) | +| `stop` | Kills the PID recorded under `.local/pids/` | +| `all` | `init` + `test` + `start` + `smoke` | + +Windows **cmd** (not PowerShell as the entrypoint): `run-local.bat `. Linux / macOS / Git Bash: `chmod +x run-local.sh` once, then `./run-local.sh `. + +### pre-registration-booking-service + +Standalone Boot app (run Maven **in this folder**). In-memory **H2**; masterdata / demographic / notification URLs are stubs. Method security is off; tokens are not validated against IAM. + +```text +cd pre-registration-booking-service +run-local.bat all +``` + +```text +cd pre-registration-booking-service +./run-local.sh all +``` + +| | | +|---|---| +| Port | **9095** (`BOOKING_PORT`) | +| Context | `/preregistration/v1` | +| Health | `http://127.0.0.1:9095/preregistration/v1/actuator/health` | +| Swagger | `http://127.0.0.1:9095/preregistration/v1/appointment/booking-service/swagger-ui.html` | +| OpenAPI | `http://127.0.0.1:9095/preregistration/v1/appointment/booking-service/v3/api-docs` | +| Properties | `src/main/resources/application-local.properties` | +| Logs / PID | `.local/logs/booking.log`, `.local/pids/booking.pid` | + +Step by step: `run-local.bat init` then `start` then `smoke`. `stop` when finished. Override the port with `set BOOKING_PORT=9195` (cmd) or `BOOKING_PORT=9195 ./run-local.sh start`. + +### registration-processor-external-integration-service + +Country EIS stub. Maven runs from `registration-processor/` with `-pl registration-processor-external-integration-service`. + +```text +cd registration-processor/registration-processor-external-integration-service +run-local.bat all +``` + +```text +cd registration-processor/registration-processor-external-integration-service +./run-local.sh all +``` + +| | | +|---|---| +| Port | **8201** (`EIS_PORT`) | +| Servlet path | `/registrationprocessor/v1/eis` | +| Health | `http://127.0.0.1:8201/registrationprocessor/v1/eis/actuator/health` | +| Swagger | `http://127.0.0.1:8201/registrationprocessor/v1/eis/swagger-ui.html` | +| OpenAPI | `http://127.0.0.1:8201/registrationprocessor/v1/eis/v3/api-docs` | +| Stub POST | `http://127.0.0.1:8201/registrationprocessor/v1/eis/registration-processor/external-integration-service/v1.0` | +| Properties | `src/main/resources/application-local.properties` | +| Logs / PID | `.local/logs/eis.log`, `.local/pids/eis.pid` | + +`smoke` checks health and OpenAPI. To hit the stub yourself: + +```text +curl -sS -H "Content-Type: application/json" -d "{\"id\":\"io.mosip.registrationprocessor\",\"version\":\"1.0\",\"request\":[\"10002100770001520240708000001\"]}" http://127.0.0.1:8201/registrationprocessor/v1/eis/registration-processor/external-integration-service/v1.0 +``` + +A non-null `request` body returns `true`. + +### registration-processor-external-stage + +Vert.x stage (`ExternalStageApplication`), not a servlet Boot app. Maven runs from `registration-processor/` with `-pl registration-processor-external-stage -am`. `start` loads `application-local.properties` only when profile `local` is set (the main class registers that file because there is no `SpringApplication`). + +```text +cd registration-processor/registration-processor-external-stage +run-local.bat init +run-local.bat test +run-local.bat start +run-local.bat smoke +run-local.bat stop +``` ```text -java -jar target/-1.4.1-SNAPSHOT.jar +cd registration-processor/registration-processor-external-stage +./run-local.sh init +./run-local.sh test +./run-local.sh start +./run-local.sh smoke +./run-local.sh stop ``` +`run-local.bat all` is init + test + start + smoke. + +| | | +|---|---| +| HTTP port | **8095** (`STAGE_PORT`) | +| Eventbus | **5736** | +| Servlet path | `/registrationprocessor/v1/external` | +| Health | `http://127.0.0.1:8095/registrationprocessor/v1/external/actuator/health` | +| Properties | `src/main/resources/application-local.properties` | +| Logs / PID | `.local/logs/external-stage.log`, `.local/pids/external-stage.pid` | + +**`init` and `test`** are the reliable laptop checks (unit tests mock Vert.x / EIS). **`start` / `smoke` / `all`** try to boot the real stage without config-server (`ConfigPropertyReader` / Vert.x SpringConfigServerStore are skipped). Packet processing still needs Kafka, registration-status DB, and a running EIS. If MOSIP status beans cannot load, the process prints `EXTERNAL_STAGE_STARTUP_FAILED` and exits (scripts no longer wait 120s). Use `test` for CI-style verification. + +`smoke` accepts Actuator 200 if present, otherwise a listening HTTP port or the `Started ExternalStageApplication` log line (this stage does not publish Springdoc). + +### What local vs cluster uses + +| | Laptop `run-local` | Cluster / Docker | +|---|---|---| +| Profile | `local` | `active_profile_env` (typically `default` / env name) | +| Config | `application-local.properties` + `-Dspring.cloud.config.enabled=false` | Config server URI/label/name from the Dockerfile `CMD` | +| Booking DB | H2 in-memory | PostgreSQL from MOSIP config | +| IAM / issuer | Offline token validation; no Eureka lookup of IAM | Config-server IAM URLs | +| Artifacts | `.local/` | container logs | + +Do not copy `application-local.properties` keys into `bootstrap.properties`. Do not activate profile `local` in Helm or the Dockerfile. + ## Tests and coverage `mvn clean verify` runs tests, writes JaCoCo HTML at `target/site/jacoco/index.html`, and enforces **LINE covered ratio 0.90** (`jacoco-check`), using the same package excludes as `sonar.coverage.exclusions`. diff --git a/pre-registration-booking-service/AGENTS.md b/pre-registration-booking-service/AGENTS.md index 39132cc224..410f735d10 100644 --- a/pre-registration-booking-service/AGENTS.md +++ b/pre-registration-booking-service/AGENTS.md @@ -4,7 +4,7 @@ ``` pre-registration-booking-service/ -├── pom.xml Dockerfile README.md AGENTS.md +├── pom.xml Dockerfile README.md AGENTS.md run-local.bat run-local.sh └── src/ ├── main/java/io/mosip/preregistration/booking/ │ ├── BookingApplication.java @@ -19,7 +19,7 @@ pre-registration-booking-service/ │ ├── errorcodes/ErrorCodes.java ErrorMessages.java │ ├── dto/ │ └── exception/ util/BookingExceptionCatcher.java BookingExceptionHandler.java - ├── main/resources/ bootstrap.properties logback.xml + ├── main/resources/ bootstrap.properties application-local.properties logback.xml └── test/ ├── java/.../booking/config/BookingApplicationComponentScanTest.java BookingConfigOpenApiTest.java ├── java/.../booking/test/BookingApplicationTest.java diff --git a/pre-registration-booking-service/README.md b/pre-registration-booking-service/README.md index 0daf3bf5bd..2cedd94b5d 100644 --- a/pre-registration-booking-service/README.md +++ b/pre-registration-booking-service/README.md @@ -21,8 +21,33 @@ Refer to the required released tagged version [SQL scripts](https://github.com/m - JDK **21.0.3** - Maven **3.9.6** -- Spring Cloud Config server (see Configuration) -- PostgreSQL 16 (typical MOSIP stack) +- Cluster: Spring Cloud Config + PostgreSQL 16. Laptop: `run-local` (H2, no config-server) + +## Local testing (run-local) + +Laptop runner (same commands as commons `kernel-notification-service`). Profile **`local`** reads `src/main/resources/application-local.properties` (H2, config-server off). Cluster Docker does **not** set this profile. + +Windows cmd: + +```text +cd pre-registration-booking-service +run-local.bat init +run-local.bat test +run-local.bat start +run-local.bat smoke +run-local.bat stop +``` + +`run-local.bat all` is init + test + start + smoke. Linux / macOS / Git Bash: `./run-local.sh `. + +| | | +|---|---| +| Port | `9095` (`BOOKING_PORT`) | +| Health | `http://127.0.0.1:9095/preregistration/v1/actuator/health` | +| Swagger | `http://127.0.0.1:9095/preregistration/v1/appointment/booking-service/swagger-ui.html` | +| Logs | `.local/logs/booking.log` (gitignored) | + +Full command table: [repo README — Local testing](../README.md#local-testing-run-local). ## Build & run (for developers) @@ -31,12 +56,14 @@ cd pre-registration-booking-service mvn clean install -Dmaven.javadoc.skip=true -Dgpg.skip=true ``` -Run `BookingApplication` from the IDE or: +Cluster-style JAR (expects config-server via `bootstrap.properties` / Docker env): ```text java -jar target/pre-registration-booking-service-1.4.1-SNAPSHOT.jar ``` +Or run `BookingApplication` from the IDE. For a laptop process without config-server, use `run-local` above. + ### Docker ```text diff --git a/pre-registration-booking-service/pom.xml b/pre-registration-booking-service/pom.xml index e88ad826b4..259e9121da 100644 --- a/pre-registration-booking-service/pom.xml +++ b/pre-registration-booking-service/pom.xml @@ -240,7 +240,7 @@ runtime com.h2database diff --git a/pre-registration-booking-service/run-local.bat b/pre-registration-booking-service/run-local.bat new file mode 100644 index 0000000000..f832594abc --- /dev/null +++ b/pre-registration-booking-service/run-local.bat @@ -0,0 +1,324 @@ +@echo off +setlocal EnableExtensions EnableDelayedExpansion +REM Standalone Windows cmd runner for pre-registration-booking-service (no .ps1). +REM Linux / macOS / Git Bash: use run-local.sh +REM +REM run-local.bat init | start | smoke | stop | test | all + +set "MODULE_DIR=%~dp0" +if "%MODULE_DIR:~-1%"=="\" set "MODULE_DIR=%MODULE_DIR:~0,-1%" + +set "LOCAL_DIR=%MODULE_DIR%\.local" +set "LOG_DIR=%LOCAL_DIR%\logs" +set "PID_DIR=%LOCAL_DIR%\pids" +set "PID_FILE=%PID_DIR%\booking.pid" +set "LOG_FILE=%LOG_DIR%\booking.log" +set "ERR_FILE=%LOG_DIR%\booking.err.log" +set "MODULE=pre-registration-booking-service" +set "CONTEXT=/preregistration/v1" +set "STARTED=Started BookingApplication" +set "SWAGGER=%CONTEXT%/appointment/booking-service/swagger-ui.html" +set "OPENAPI=%CONTEXT%/appointment/booking-service/v3/api-docs" + +if not defined BOOKING_PORT set "BOOKING_PORT=9095" + +set "CMD=%~1" +if "%CMD%"=="" goto :usage +if /I "%CMD%"=="-h" goto :usage +if /I "%CMD%"=="--help" goto :usage +if /I "%CMD%"=="help" goto :usage +if /I "%CMD%"=="init" goto :init +if /I "%CMD%"=="test" goto :test +if /I "%CMD%"=="start" goto :start +if /I "%CMD%"=="stop" goto :stop +if /I "%CMD%"=="smoke" goto :smoke +if /I "%CMD%"=="all" goto :all + +echo error: unknown command '%CMD%' +goto :usage + +:usage +echo Local pre-registration-booking-service ^(local profile, :9095 /preregistration/v1^) +echo. +echo run-local.bat init package this module +echo run-local.bat start run and wait until Spring Boot is ready +echo run-local.bat smoke GET health + OpenAPI +echo run-local.bat stop +echo run-local.bat test Maven tests +echo run-local.bat all init + test + start + smoke +echo. +echo Port: %BOOKING_PORT% ^(override with set BOOKING_PORT=...^) +echo Config: src\main\resources\application-local.properties +echo Cluster: Dockerfile still uses config-server; it does not activate profile local +exit /b 1 + +:port_in_use +netstat -ano | findstr /R /C:":%BOOKING_PORT% .*LISTENING" >nul 2>&1 +exit /b %ERRORLEVEL% + +:pid_on_port +set "PORT_PID=" +for /f "tokens=5" %%P in ('netstat -ano ^| findstr /R /C:":%BOOKING_PORT% .*LISTENING"') do set "PORT_PID=%%P" +exit /b 0 + +:ensure_dirs +if not exist "%LOG_DIR%" mkdir "%LOG_DIR%" +if not exist "%PID_DIR%" mkdir "%PID_DIR%" +exit /b 0 + +:check_prereqs +where java >nul 2>&1 +if errorlevel 1 ( + echo error: java is required on PATH + exit /b 1 +) +where mvn >nul 2>&1 +if errorlevel 1 ( + echo error: mvn is required on PATH + exit /b 1 +) +exit /b 0 + +:find_jar +set "BOOT_JAR=" +for %%F in ("%MODULE_DIR%\target\%MODULE%-*.jar") do ( + set "CAND=%%~nxF" + echo !CAND! | findstr /I /C:".original" /C:"sources" /C:"javadoc" >nul + if errorlevel 1 ( + set "BOOT_JAR=%%~fF" + goto :find_jar_done + ) +) +:find_jar_done +if not defined BOOT_JAR ( + echo error: no boot jar in target. Run: %~nx0 init + exit /b 1 +) +exit /b 0 + +:is_running +if not exist "%PID_FILE%" exit /b 1 +set /p CHECK_PID=<"%PID_FILE%" +if not defined CHECK_PID exit /b 1 +tasklist /FI "PID eq !CHECK_PID!" 2>nul | findstr /I "!CHECK_PID!" >nul +if errorlevel 1 exit /b 1 +exit /b 0 + +:init +call :check_prereqs +if errorlevel 1 exit /b 1 +call :stop +ping -n 3 127.0.0.1 >nul +echo ==^> packaging %MODULE% ^(skip tests^) +pushd "%MODULE_DIR%" +call mvn clean package -DskipTests "-Dgpg.skip=true" "-Dmaven.javadoc.skip=true" +set "RC=%ERRORLEVEL%" +popd +if not "%RC%"=="0" exit /b %RC% +echo init complete +exit /b 0 + +:test +call :check_prereqs +if errorlevel 1 exit /b 1 +echo ==^> maven tests +pushd "%MODULE_DIR%" +call mvn test "-Dgpg.skip=true" "-Dmaven.javadoc.skip=true" +set "RC=%ERRORLEVEL%" +popd +exit /b %RC% + +:print_urls +echo health http://127.0.0.1:%BOOKING_PORT%%CONTEXT%/actuator/health +echo swagger http://127.0.0.1:%BOOKING_PORT%%SWAGGER% +echo openapi http://127.0.0.1:%BOOKING_PORT%%OPENAPI% +exit /b 0 + +:start +echo. +echo ==^> run-local start +call :ensure_dirs +call :check_prereqs +if errorlevel 1 exit /b 1 +call :is_running +if not errorlevel 1 ( + set /p OLD_PID=<"%PID_FILE%" + echo booking already running ^(pid !OLD_PID!^) on port %BOOKING_PORT% + call :print_urls + exit /b 0 +) +call :port_in_use +if not errorlevel 1 ( + call :pid_on_port + echo booking already listening on port %BOOKING_PORT% ^(pid !PORT_PID!^) + if defined PORT_PID > "%PID_FILE%" echo !PORT_PID! + call :print_urls + exit /b 0 +) +if exist "%PID_FILE%" del /q "%PID_FILE%" >nul 2>&1 +if exist "%LOG_FILE%" del /q "%LOG_FILE%" >nul 2>&1 +if exist "%ERR_FILE%" del /q "%ERR_FILE%" >nul 2>&1 + +call :find_jar +if errorlevel 1 exit /b 1 + +echo ==^> starting booking from %BOOT_JAR% +echo profile=local +echo port=%BOOKING_PORT% +echo context=%CONTEXT% +echo properties=src\main\resources\application-local.properties + +set "LAUNCH_PS1=%LOCAL_DIR%\launch-booking.ps1" +> "%LAUNCH_PS1%" echo $ErrorActionPreference = 'Stop' +>> "%LAUNCH_PS1%" echo $argList = @^('-Dspring.profiles.active=local','-Dserver.port=%BOOKING_PORT%','-Dspring.cloud.config.enabled=false','-jar','%BOOT_JAR%'^) +>> "%LAUNCH_PS1%" echo $p = Start-Process -FilePath 'java' -ArgumentList $argList -WorkingDirectory '%MODULE_DIR%' -RedirectStandardOutput '%LOG_FILE%' -RedirectStandardError '%ERR_FILE%' -WindowStyle Hidden -PassThru +>> "%LAUNCH_PS1%" echo Set-Content -LiteralPath '%PID_FILE%' -Value $p.Id -Encoding ascii +powershell -NoProfile -ExecutionPolicy Bypass -File "%LAUNCH_PS1%" +if errorlevel 1 ( + echo error: failed to start java process + exit /b 1 +) + +echo ==^> waiting for Spring Boot startup on port %BOOKING_PORT% ^(up to 90s^) ... +call :wait_ready 90 +if errorlevel 1 exit /b 1 + +if exist "%PID_FILE%" ( + set /p STARTED_PID=<"%PID_FILE%" + echo pid !STARTED_PID! log %LOG_FILE% +) else ( + call :pid_on_port + if defined PORT_PID ( + > "%PID_FILE%" echo !PORT_PID! + echo pid !PORT_PID! log %LOG_FILE% + ) else ( + echo warn: ready but PID for port %BOOKING_PORT% not resolved + ) +) +echo. +echo booking ready +echo port %BOOKING_PORT% +call :print_urls +exit /b 0 + +:wait_ready +set /a WAIT_MAX=%~1 +if "!WAIT_MAX!"=="" set /a WAIT_MAX=90 +set /a WAIT_ELAPSED=0 +:wait_ready_loop +if !WAIT_ELAPSED! GEQ !WAIT_MAX! goto :wait_ready_fail + +call :port_in_use +if not errorlevel 1 ( + if exist "%LOG_FILE%" ( + findstr /C:"%STARTED%" "%LOG_FILE%" >nul 2>&1 + if not errorlevel 1 exit /b 0 + ) +) + +if exist "%LOG_FILE%" ( + findstr /C:"APPLICATION FAILED TO START" /C:"Port %BOOKING_PORT% was already in use" "%LOG_FILE%" >nul 2>&1 + if not errorlevel 1 ( + echo error: startup failed. See %LOG_FILE% + type "%LOG_FILE%" + exit /b 1 + ) +) + +echo ... still starting ^(!WAIT_ELAPSED!s / !WAIT_MAX!s^) +ping -n 3 127.0.0.1 >nul +set /a WAIT_ELAPSED+=2 +goto :wait_ready_loop + +:wait_ready_fail +echo error: Spring Boot did not become ready within !WAIT_MAX!s on port %BOOKING_PORT% +if exist "%LOG_FILE%" type "%LOG_FILE%" +exit /b 1 + +:stop +call :ensure_dirs +set "STOP_PID=" +if exist "%PID_FILE%" set /p STOP_PID=<"%PID_FILE%" +if not defined STOP_PID ( + call :pid_on_port + set "STOP_PID=!PORT_PID!" +) +if not defined STOP_PID ( + echo booking is not running + exit /b 0 +) +echo ==^> stopping booking ^(%STOP_PID%^) on port %BOOKING_PORT% +taskkill /PID %STOP_PID% /T /F >nul 2>&1 +del /q "%PID_FILE%" >nul 2>&1 +echo stopped. +exit /b 0 + +:http_ok +set "HTTP_CODE=000" +set "HTTP_URL=%~1" +set "HTTP_CODE_FILE=%LOCAL_DIR%\http-code.txt" +curl.exe -sS -o NUL -w "%%{http_code}" --connect-timeout 2 --max-time 3 "%HTTP_URL%" > "%HTTP_CODE_FILE%" 2>nul +if exist "%HTTP_CODE_FILE%" ( + for /f "usebackq delims=" %%C in ("%HTTP_CODE_FILE%") do set "HTTP_CODE=%%C" + del /q "%HTTP_CODE_FILE%" >nul 2>&1 +) +if not defined HTTP_CODE set "HTTP_CODE=000" +if "!HTTP_CODE!"=="" set "HTTP_CODE=000" +exit /b 0 + +:smoke +call :ensure_dirs +echo ==^> waiting for booking ^(up to 60s^) +set /a ELAPSED=0 +:smoke_loop +if %ELAPSED% GEQ 60 goto :smoke_fail +if exist "%PID_FILE%" ( + call :is_running + if errorlevel 1 ( + echo error: process exited. See %LOG_FILE% + if exist "%LOG_FILE%" type "%LOG_FILE%" + if exist "%ERR_FILE%" type "%ERR_FILE%" + exit /b 1 + ) +) +call :http_ok "http://127.0.0.1:%BOOKING_PORT%%CONTEXT%/actuator/health" +if "%HTTP_CODE%"=="200" ( + set "HEALTH_URL=http://127.0.0.1:%BOOKING_PORT%%CONTEXT%/actuator/health" + goto :smoke_ok +) +call :http_ok "http://127.0.0.1:%BOOKING_PORT%/actuator/health" +if "%HTTP_CODE%"=="200" ( + set "HEALTH_URL=http://127.0.0.1:%BOOKING_PORT%/actuator/health" + goto :smoke_ok +) +ping -n 3 127.0.0.1 >nul +set /a ELAPSED+=2 +goto :smoke_loop + +:smoke_ok +echo healthy %HEALTH_URL% +call :http_ok "http://127.0.0.1:%BOOKING_PORT%%OPENAPI%" +echo openapi http://127.0.0.1:%BOOKING_PORT%%OPENAPI% HTTP %HTTP_CODE% +if not "%HTTP_CODE%"=="200" ( + echo error: openapi endpoint not healthy + exit /b 1 +) +echo smoke ok +exit /b 0 + +:smoke_fail +echo error: not healthy. See %LOG_FILE% +if exist "%LOG_FILE%" type "%LOG_FILE%" +if exist "%ERR_FILE%" type "%ERR_FILE%" +exit /b 1 + +:all +echo ==^> all: init + test + start + smoke +call :init +if errorlevel 1 exit /b 1 +call :test +if errorlevel 1 exit /b 1 +call :start +if errorlevel 1 exit /b 1 +call :smoke +exit /b %ERRORLEVEL% diff --git a/pre-registration-booking-service/run-local.sh b/pre-registration-booking-service/run-local.sh new file mode 100644 index 0000000000..50571d69b1 --- /dev/null +++ b/pre-registration-booking-service/run-local.sh @@ -0,0 +1,306 @@ +#!/usr/bin/env bash +# pre-registration-booking-service local runner — Linux, macOS, Windows Git Bash/MSYS. +# Windows cmd: use run-local.bat (standalone; no .ps1). +# +# Uses src/main/resources/application-local.properties (profile local). +# No config-server required. Cluster Docker does not activate profile local. +set -euo pipefail + +MODULE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +LOCAL_DIR="${MODULE_DIR}/.local" +LOG_DIR="${LOCAL_DIR}/logs" +PID_DIR="${LOCAL_DIR}/pids" +PORT="${BOOKING_PORT:-9095}" +PID_FILE="${PID_DIR}/booking.pid" +LOG_FILE="${LOG_DIR}/booking.log" +MODULE="pre-registration-booking-service" +UNAME_S="$(uname -s 2>/dev/null || echo unknown)" +CONTEXT="/preregistration/v1" +STARTED="Started BookingApplication" +SWAGGER="${CONTEXT}/appointment/booking-service/swagger-ui.html" +OPENAPI="${CONTEXT}/appointment/booking-service/v3/api-docs" + +MVN_SKIP=( + "-DskipTests" + "-Dgpg.skip=true" + "-Dmaven.javadoc.skip=true" +) + +usage() { + cat <<'EOF' +Local pre-registration-booking-service (local profile, :9095 /preregistration/v1) + + Linux / macOS / Git Bash: + ./run-local.sh init | start | smoke | stop | test | all + + Windows cmd: + run-local.bat init | start | smoke | stop | test | all + +Config: src/main/resources/application-local.properties +Cluster: Dockerfile still uses config-server; it does not activate profile local + + all = init + test + start + smoke +EOF + exit "${1:-0}" +} + +need_cmd() { + command -v "$1" >/dev/null 2>&1 || { + echo "error: '$1' is required on PATH" >&2 + exit 1 + } +} + +ensure_dirs() { + mkdir -p "$LOG_DIR" "$PID_DIR" +} + +check_prereqs() { + need_cmd java + need_cmd mvn + echo "os: ${UNAME_S}" + local ver + ver="$(java -version 2>&1 | head -n 1 || true)" + echo "java: $ver" + if ! echo "$ver" | grep -E '"21[\. "]' >/dev/null 2>&1; then + echo "warn: JDK 21 is required. Continuing anyway." >&2 + fi +} + +find_boot_jar() { + local target="${MODULE_DIR}/target" + local jar + if [[ ! -d "$target" ]]; then + echo "error: not packaged. Run: $0 init" >&2 + exit 1 + fi + for jar in "$target"/${MODULE}-*.jar; do + [[ -f "$jar" ]] || continue + case "$jar" in + *.original|*sources*|*javadoc*) continue ;; + esac + echo "$jar" + return 0 + done + echo "error: no boot jar in ${target}. Run: $0 init" >&2 + exit 1 +} + +is_running() { + [[ -f "$PID_FILE" ]] || return 1 + kill -0 "$(cat "$PID_FILE")" 2>/dev/null +} + +print_urls() { + echo " health http://127.0.0.1:${PORT}${CONTEXT}/actuator/health" + echo " swagger http://127.0.0.1:${PORT}${SWAGGER}" + echo " openapi http://127.0.0.1:${PORT}${OPENAPI}" +} + +cmd_init() { + check_prereqs + cmd_stop + echo "==> packaging ${MODULE} (skip tests)" + (cd "$MODULE_DIR" && mvn clean package "${MVN_SKIP[@]}") + echo "init complete" +} + +cmd_test() { + check_prereqs + echo "==> maven tests" + (cd "$MODULE_DIR" && mvn test "-Dgpg.skip=true" "-Dmaven.javadoc.skip=true") +} + +cmd_start() { + echo + echo "==> run-local start" + ensure_dirs + check_prereqs + if is_running; then + echo "booking already running (pid $(cat "$PID_FILE")) on port ${PORT}" + print_urls + return 0 + fi + rm -f "$LOG_FILE" + local jar + jar="$(find_boot_jar)" + echo "==> starting booking from $(basename "$jar")" + echo " profile=local" + echo " port=${PORT}" + echo " context=${CONTEXT}" + echo " properties=src/main/resources/application-local.properties" + local java_args=( + "-Dspring.profiles.active=local" + "-Dserver.port=${PORT}" + "-Dspring.cloud.config.enabled=false" + ) + java_args+=(-jar "$jar") + nohup java "${java_args[@]}" >"$LOG_FILE" 2>&1 & + echo $! >"$PID_FILE" + echo "pid $(cat "$PID_FILE") log ${LOG_FILE}" + echo "==> waiting for Spring Boot startup on port ${PORT} (up to 90s) ..." + wait_ready 90 + echo + echo "booking ready" + echo " port ${PORT}" + print_urls +} + +wait_ready() { + local timeout="${1:-90}" + local elapsed=0 + local code + while [[ "$elapsed" -lt "$timeout" ]]; do + if ! is_running; then + echo "error: process exited during startup. See ${LOG_FILE}" >&2 + tail -n 80 "$LOG_FILE" >&2 || true + return 1 + fi + if grep -q "${STARTED}" "$LOG_FILE" 2>/dev/null; then + code="$(http_ok "http://127.0.0.1:${PORT}${CONTEXT}/actuator/health")" + if [[ "$code" == "200" ]]; then + return 0 + fi + code="$(http_ok "http://127.0.0.1:${PORT}/actuator/health")" + if [[ "$code" == "200" ]]; then + return 0 + fi + fi + code="$(http_ok "http://127.0.0.1:${PORT}${CONTEXT}/actuator/health")" + if [[ "$code" == "200" ]]; then + return 0 + fi + if grep -q "APPLICATION FAILED TO START\|Port ${PORT} was already in use" "$LOG_FILE" 2>/dev/null; then + echo "error: startup failed. See ${LOG_FILE}" >&2 + tail -n 80 "$LOG_FILE" >&2 || true + return 1 + fi + echo " ... still starting (${elapsed}s / ${timeout}s)" + sleep 2 + elapsed=$((elapsed + 2)) + done + echo "error: Spring Boot did not become ready within ${timeout}s on port ${PORT}" >&2 + tail -n 80 "$LOG_FILE" >&2 || true + return 1 +} + +http_ok() { + local url="$1" + local code + if command -v curl >/dev/null 2>&1; then + code="$(curl -sS -o /dev/null -w "%{http_code}" --connect-timeout 2 --max-time 3 "$url" 2>/dev/null || true)" + [[ -n "$code" ]] || code="000" + printf '%s' "$code" + return 0 + fi + if command -v python3 >/dev/null 2>&1; then + python3 -c 'import sys,urllib.request +try: + urllib.request.urlopen(sys.argv[1], timeout=3) + print("200") +except Exception: + print("000")' "$url" + return 0 + fi + if command -v python >/dev/null 2>&1; then + python -c 'import sys,urllib.request +try: + urllib.request.urlopen(sys.argv[1], timeout=3) + print("200") +except Exception: + print("000")' "$url" + return 0 + fi + echo "error: install curl or python3 for smoke checks" >&2 + printf '%s' "000" +} + +cmd_stop() { + ensure_dirs + if ! is_running; then + rm -f "$PID_FILE" + echo "booking is not running" + return 0 + fi + local pid + pid="$(cat "$PID_FILE")" + echo "==> stopping booking (${pid}) on port ${PORT}" + kill "$pid" 2>/dev/null || true + local i + for i in 1 2 3 4 5 6 7 8 9 10; do + kill -0 "$pid" 2>/dev/null || break + sleep 1 + done + if kill -0 "$pid" 2>/dev/null; then + kill -9 "$pid" 2>/dev/null || true + fi + rm -f "$PID_FILE" + echo "stopped." +} + +cmd_smoke() { + ensure_dirs + local timeout="${1:-60}" + local elapsed=0 + echo "==> waiting for booking (up to ${timeout}s)" + while [[ "$elapsed" -lt "$timeout" ]]; do + if [[ -f "$PID_FILE" ]] && ! is_running; then + echo "error: process exited. See ${LOG_FILE}" >&2 + tail -n 40 "$LOG_FILE" >&2 || true + return 1 + fi + local url code health_url="" + for url in \ + "http://127.0.0.1:${PORT}${CONTEXT}/actuator/health" \ + "http://127.0.0.1:${PORT}/actuator/health" + do + code="$(http_ok "$url")" + if [[ "$code" == "200" ]]; then + health_url="$url" + break + fi + done + if [[ -n "$health_url" ]]; then + echo "healthy ${health_url}" + code="$(http_ok "http://127.0.0.1:${PORT}${OPENAPI}")" + echo "openapi http://127.0.0.1:${PORT}${OPENAPI} HTTP ${code}" + if [[ "$code" != "200" ]]; then + echo "error: openapi endpoint not healthy" >&2 + return 1 + fi + echo "smoke ok" + return 0 + fi + sleep 2 + elapsed=$((elapsed + 2)) + done + echo "error: not healthy. See ${LOG_FILE}" >&2 + tail -n 80 "$LOG_FILE" >&2 || true + return 1 +} + +cmd_all() { + echo "==> all: init + test + start + smoke" + cmd_init + cmd_test + cmd_start + cmd_smoke +} + +main() { + local cmd="${1:-}" + shift || true + case "$cmd" in + -h|--help|help) usage 0 ;; + init) cmd_init ;; + test) cmd_test ;; + start) cmd_start ;; + stop) cmd_stop ;; + smoke) cmd_smoke "${1:-60}" ;; + all) cmd_all ;; + "") usage 1 ;; + *) echo "error: unknown command '$cmd'" >&2; usage 1 ;; + esac +} + +main "$@" diff --git a/pre-registration-booking-service/src/main/resources/application-local.properties b/pre-registration-booking-service/src/main/resources/application-local.properties new file mode 100644 index 0000000000..ea26f93e49 --- /dev/null +++ b/pre-registration-booking-service/src/main/resources/application-local.properties @@ -0,0 +1,168 @@ +# Local profile for pre-registration-booking-service (run-local.sh / run-local.bat). +# Activate with: -Dspring.profiles.active=local +# Cluster Docker does not set this profile; it uses bootstrap + config-server env. +# No config-server, authmanager, or PostgreSQL required. H2 is in-memory. + +server.port=9095 +server.servlet.context-path=/preregistration/v1 +application.env.local=true + +spring.http.converters.preferred-json-mapper=jackson2 + +# Boot 4 local run (no config-server) +spring.cloud.config.enabled=false +spring.cloud.config.fail-fast=false +spring.config.import=optional:configserver: +health.config.enabled=false +management.health.config.enabled=false +management.endpoint.health.show-details=always +management.endpoints.web.exposure.include=info,health,refresh +spring.info.git.location=classpath:service-git.properties + +# Auth adapter (offline; do not point issuer at localhost or a Eureka service name) +mosip.auth.adapter.impl.basepackage=io.mosip.kernel.auth.defaultadapter +auth.server.admin.offline.token.validate=true +auth.server.validate.url=http://127.0.0.1:8091/authmanager/authorize/validateToken +auth.role.prefix=ROLE_ +auth.header.name=Authorization +spring.security.method-security.enabled=false +spring.mvc.pathmatch.matching-strategy=ant_path_matcher +mosip.global.end-points=/** +mosip.service.end-points=/** +mosip.kernel.auth.appids.realm.map={prereg:'preregistration'} +mosip.iam.adapter.clientid=mosip-prereg-client +mosip.iam.adapter.clientsecret=local +mosip.iam.adapter.appid=prereg +prereg.auth.jwt.secret=Yn2kjibddFAWtnPJ2AFlL8WXmohJMCvigQggaEypa5E= +mosip.security.authentication.provider.beans.list.pre-registration-booking-service=customJWTAuthProvider + +# H2: entities live in schema prereg. INIT creates it before Hibernate ddl-auto. +spring.datasource.url=jdbc:h2:mem:booking;DB_CLOSE_DELAY=-1;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;INIT=CREATE SCHEMA IF NOT EXISTS prereg +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.hibernate.ddl-auto=update +spring.jpa.properties.hibernate.hbm2ddl.create_namespaces=true +spring.jpa.show-sql=false +javax.persistence.jdbc.driver=org.h2.Driver +javax.persistence.jdbc.url=jdbc:h2:mem:booking;DB_CLOSE_DELAY=-1;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;INIT=CREATE SCHEMA IF NOT EXISTS prereg +javax.persistence.jdbc.user=sa +javax.persistence.jdbc.password= +hibernate.hbm2ddl.auto=update + +mosip.prereg.pii.backward.compatibility=true +mosip.utc-datetime-pattern=yyyy-MM-dd'T'HH:mm:ss.SSS'Z' +version=1.0 +id=mosip.pre-registration.booking.book +mosip.preregistration.booking.id.book=mosip.pre-registration.booking.book +mosip.id.preregistration.booking.book=mosip.pre-registration.booking.book +mosip.preregistration.booking.availability.sync.id=mosip.preregistration.booking.availability.sync +mosip.preregistration.booking.fetch.booking.id=mosip.preregistration.booking.fetch.booking +mosip.preregistration.booking.cancel.id=mosip.preregistration.booking.cancel +mosip.preregistration.booking.delete.id=mosip.preregistration.booking.delete +mosip.preregistration.booking.fetch.availability.id=mosip.preregistration.booking.fetch.availability +mosip.preregistration.booking.fetchPreidByDate.id=mosip.preregistration.booking.fetchPreidByDate +mosip.preregistration.booking.availability.increase.id=mosip.preregistration.booking.availability.increase +mosip.preregistration.booking.availability.check.id=mosip.preregistration.booking.availability.check +mosip.preregistration.booking.delete.old.id=mosip.preregistration.booking.delete.old +mosip.preregistration.booking.exception.id=mosip.preregistration.booking.parse.exception + +preregistration.availability.sync=7 +preregistration.availability.noOfDays=7 +preregistration.booking.offset=2 +preregistration.timespan.cancel=24 +preregistration.timespan.rebook=24 +preregistration.rebook.timespan=24 +preregistration.cancel.timespan=24 + +regCenter.url=http://127.0.0.1:8086/masterdata/v1.0/registrationcenters +holiday.url=http://127.0.0.1:8086/masterdata/v1.0/getregistrationcenterholidays/ +demographic.resource.url=http://127.0.0.1:9092/pre-registration/v1.0/applications +booking.resource.url=http://127.0.0.1:9095/preregistration/v1 +documentUrl=http://127.0.0.1:9093/demographic/v0.1/getDocument +mosip.io.prid.url=http://127.0.0.1:8100/v1/pridgenerator/prid +service.version=v1.0 +master.service.env=masterdata +demographic.service.env=demographic +demographic.service.version=v0.1 +document.service.env=demographic +document.service.version=v0.1 +notification.url=http://127.0.0.1:8083/v1/notifier/notify +resource.template.url=http://127.0.0.1:8086/masterdata/v1.0/templates +cryptoResource.url=http://127.0.0.1:8097/cryptomanager/v1.0 +audit.url=http://127.0.0.1:8098/auditmanager/v1.0/audits +emailResourse.url=http://127.0.0.1:8083/v1/notifier/email/send +smsResourse.url=http://127.0.0.1:8083/v1/notifier/sms/send +mosip.notification.timezone=GMT+05:30 +mosip.supported-languages=eng,ara,fra +mosip.primary-language=eng +mosip.mandatory-languages=eng +mosip.optional-languages=ara,fra + +preregistration.crypto.referenceId=INDIVIDUAL +preregistration.crypto.PrependThumbprint=false +preregistration.crypto.applicationId=PRE_REGISTRATION + +mosip.kernel.objectstore.account-name=prereg +cancel.appoinment.template=cancel-appointment +email.acknowledgement.template=Email-Acknowledgement +email.acknowledgement.subject.template=Acknowledgement-email-subject +sms.acknowledgement.template=SMS-Acknowledgement +cancel.appointment.email.subject=cancel-appointment-email-subject +noOfKiosks=10 +prereg_id.length=16 +preregistration.preid.regex=+[0-9] +timeSpanCheckForRebook=24 +timeSpanCheckForCancel=24 +mosip.kernel.prid.length=14 +mosip.kernel.prid.sequence-limit=3 +mosip.kernel.prid.repeating-block-limit=3 +mosip.kernel.prid.repeating-limit=2 +mosip.kernel.prid.not-start-with=0,1 +mosip.kernel.prid.restricted-numbers=786,666 +mosip.postal.code.length=6 +mosip.mobile.length=10 +mosip.email.length=50 +mosip.CINE.length=30 +auth-token-generator.rest.issuerUrl=http://127.0.0.1:8091 + +# ValidationUtil / idobjectvalidator (pre-registration-core) +mosip.kernel.idobjectvalidator.masterdata.documenttypes.rest.uri=http://127.0.0.1:8086/v1/masterdata/documenttypes/{documentcategorycode}/{langcode} +mosip.kernel.masterdata.validdoc.rest.uri=http://127.0.0.1:8086/v1/masterdata/validdocuments +mosip.id.validation.identity.dateOfBirth= +mosip.id.validation.identity.phone= +mosip.id.validation.identity.email= +mosip.id.validation.identity.postalCode= +mosip.id.validation.identity.CNIENumber= +mosip.id.validation.identity.phone.length=10 +mosip.id.validation.identity.email.length=50 +mosip.id.validation.identity.postalCode.length=6 +mosip.id.validation.identity.CNIENumber.length=30 + +mosip.role.preregistration.getappointmentavailability=INDIVIDUAL,PRE_REGISTRATION_ADMIN +mosip.role.preregistration.postappointmentpreregistrationid=INDIVIDUAL,PRE_REGISTRATION_ADMIN +mosip.role.preregistration.postappointment=INDIVIDUAL,PRE_REGISTRATION_ADMIN +mosip.role.preregistration.getappointmentpreregistrationid=INDIVIDUAL,PRE_REGISTRATION_ADMIN +mosip.role.preregistration.putappointmentpreregistrationid=INDIVIDUAL,PRE_REGISTRATION_ADMIN +mosip.role.preregistration.putbatchappointmentpreregistrationid=INDIVIDUAL,PRE_REGISTRATION_ADMIN +mosip.role.preregistration.deleteappointment=INDIVIDUAL,PRE_REGISTRATION_ADMIN +mosip.role.preregistration.getappointmentpreregistrationidregistrationcenterid=INDIVIDUAL,PRE_REGISTRATION_ADMIN +mosip.role.preregistration.getappointmentregistrationcenterid=INDIVIDUAL,PRE_REGISTRATION_ADMIN + +openapi.info.title=Pre-Registration-Booking +openapi.info.description=Pre-Registration-Booking Service +openapi.info.version=1.0 +openapi.info.license.name=Mosip +openapi.info.license.url=https://docs.mosip.io/platform/license +openapi.service.servers[0].url=${server.servlet.context-path} +openapi.service.servers[0].description=Pre-Registration-Booking Service +openapi.group.name=${openapi.info.title} +openapi.group.paths[0]=/** +springdoc.swagger-ui.disable-swagger-default-url=true +springdoc.swagger-ui.tagsSorter=alpha +springdoc.swagger-ui.operationsSorter=alpha +springdoc.swagger-ui.syntaxHighlight.activated=false +springdoc.swagger-ui.validator-url=none +springdoc.swagger-ui.persistAuthorization=true +springdoc.swagger-ui.path=/appointment/booking-service/swagger-ui.html +springdoc.api-docs.path=/appointment/booking-service/v3/api-docs diff --git a/registration-processor/AGENTS.md b/registration-processor/AGENTS.md index 431f5f83f0..79a1c574e6 100644 --- a/registration-processor/AGENTS.md +++ b/registration-processor/AGENTS.md @@ -5,8 +5,8 @@ ``` registration-processor/ ├── pom.xml README.md AGENTS.md -├── registration-processor-external-stage/ Vert.x → EIS → AGENTS.md -└── registration-processor-external-integration-service/ EIS stub REST → AGENTS.md +├── registration-processor-external-stage/ Vert.x → EIS run-local → AGENTS.md +└── registration-processor-external-integration-service/ EIS stub REST run-local → AGENTS.md ``` ```bash diff --git a/registration-processor/README.md b/registration-processor/README.md index 594026c557..7ed1c94c91 100644 --- a/registration-processor/README.md +++ b/registration-processor/README.md @@ -18,6 +18,10 @@ Pins (Boot parent, MOSIP jars, plugins, JaCoCo gate) and the module description Prefix for stage properties: `mosip.regproc.external.` +## Local testing (run-local) + +Each child has `run-local.bat` / `run-local.sh` (`init` `start` `smoke` `stop` `test` `all`) and `src/main/resources/application-local.properties` (profile `local` only). Usage: [repo README — Local testing](../README.md#local-testing-run-local). + ## Build From this directory: diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index d2c9cbeebf..0d55bd2dfc 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -83,7 +83,7 @@ 4.5.34 1 - **/constant/**,**/config/**,**/httpfilter/**,**/cache/**,**/entity/**,**/model/**,**/exception/**,**/repository/**,**/verticle/**,**/spi/**,**/proxy/**,**/entities/**,**/filter/**,**/util/**,**/verifier/**,**/*Application.java + **/constant/**,**/config/**,**/httpfilter/**,**/cache/**,**/entity/**,**/model/**,**/exception/**,**/repository/**,**/verticle/**,**/spi/**,**/proxy/**,**/entities/**,**/filter/**,**/util/**,**/verifier/**,**/*Application.java,**/org/springframework/boot/web/client/** **/dto/**,**/entity/**,**/config/** ${project.build.directory}/site/jacoco/jacoco.xml 0.90 @@ -276,6 +276,7 @@ **/util/** **/verifier/** **/*Application.class + **/org/springframework/boot/web/client/** diff --git a/registration-processor/registration-processor-external-integration-service/AGENTS.md b/registration-processor/registration-processor-external-integration-service/AGENTS.md index 0411347510..1ba0171561 100644 --- a/registration-processor/registration-processor-external-integration-service/AGENTS.md +++ b/registration-processor/registration-processor-external-integration-service/AGENTS.md @@ -4,7 +4,7 @@ EIS stub. `POST .../v1.0` → `true` if body non-null. Swagger Authorize = `Auth ``` registration-processor-external-integration-service/ -├── pom.xml Dockerfile README.md AGENTS.md +├── pom.xml Dockerfile README.md AGENTS.md run-local.bat run-local.sh └── src/ ├── main/ │ ├── java/io/mosip/registrationprocessor/eis/ @@ -12,7 +12,7 @@ registration-processor-external-integration-service/ │ │ ├── controller/ExternalController.java │ │ ├── config/SwaggerConfig.java OpenApiProperties.java │ │ └── entity/BaseRestRequestDTO.java MessageRequestDTO.java - │ └── resources/bootstrap.properties + │ └── resources/bootstrap.properties application-local.properties └── test/ ├── java/.../eis/ │ ├── ExternalIntegrationControllerTest.java diff --git a/registration-processor/registration-processor-external-integration-service/README.md b/registration-processor/registration-processor-external-integration-service/README.md index e97395f2a5..95fd61fe63 100644 --- a/registration-processor/registration-processor-external-integration-service/README.md +++ b/registration-processor/registration-processor-external-integration-service/README.md @@ -34,7 +34,33 @@ See [bootstrap.properties](src/main/resources/bootstrap.properties). - JDK **21.0.3** - Maven **3.9.6** -- Spring Cloud Config +- Cluster: Spring Cloud Config. Laptop: `run-local` (no config-server) + +## Local testing (run-local) + +Laptop runner (same commands as commons `kernel-notification-service`). Profile **`local`** reads `src/main/resources/application-local.properties` (config-server off). Cluster Docker does **not** set this profile. + +Windows cmd (from this module directory): + +```text +run-local.bat init +run-local.bat test +run-local.bat start +run-local.bat smoke +run-local.bat stop +``` + +`run-local.bat all` is init + test + start + smoke. Linux / macOS / Git Bash: `./run-local.sh `. Maven is invoked from `registration-processor/` with `-pl registration-processor-external-integration-service`. + +| | | +|---|---| +| Port | `8201` (`EIS_PORT`) | +| Health | `http://127.0.0.1:8201/registrationprocessor/v1/eis/actuator/health` | +| Swagger | `http://127.0.0.1:8201/registrationprocessor/v1/eis/swagger-ui.html` | +| Stub POST | `/registrationprocessor/v1/eis/registration-processor/external-integration-service/v1.0` | +| Logs | `.local/logs/eis.log` (gitignored) | + +Full command table: [repo README — Local testing](../../README.md#local-testing-run-local). ## Build & run @@ -43,10 +69,14 @@ cd registration-processor mvn -pl registration-processor-external-integration-service clean install -Dmaven.javadoc.skip=true -Dgpg.skip=true ``` +Cluster-style JAR (expects config-server): + ```text java -jar target/registration-processor-external-integration-service-1.4.1-SNAPSHOT.jar ``` +Laptop without config-server: `run-local` above. + ### Docker ```text diff --git a/registration-processor/registration-processor-external-integration-service/run-local.bat b/registration-processor/registration-processor-external-integration-service/run-local.bat new file mode 100644 index 0000000000..ceb293d395 --- /dev/null +++ b/registration-processor/registration-processor-external-integration-service/run-local.bat @@ -0,0 +1,327 @@ +@echo off +setlocal EnableExtensions EnableDelayedExpansion +REM Standalone Windows cmd runner for registration-processor-external-integration-service. +REM Linux / macOS / Git Bash: use run-local.sh +REM +REM run-local.bat init | start | smoke | stop | test | all + +set "MODULE_DIR=%~dp0" +if "%MODULE_DIR:~-1%"=="\" set "MODULE_DIR=%MODULE_DIR:~0,-1%" +for %%I in ("%MODULE_DIR%\..") do set "PARENT_DIR=%%~fI" + +set "LOCAL_DIR=%MODULE_DIR%\.local" +set "LOG_DIR=%LOCAL_DIR%\logs" +set "PID_DIR=%LOCAL_DIR%\pids" +set "PID_FILE=%PID_DIR%\eis.pid" +set "LOG_FILE=%LOG_DIR%\eis.log" +set "ERR_FILE=%LOG_DIR%\eis.err.log" +set "MODULE=registration-processor-external-integration-service" +set "CONTEXT=/registrationprocessor/v1/eis" +set "STARTED=Started ExternalIntegrationServiceApplication" +set "SWAGGER=%CONTEXT%/swagger-ui.html" +set "OPENAPI=%CONTEXT%/v3/api-docs" +set "EIS_POST=%CONTEXT%/registration-processor/external-integration-service/v1.0" + +if not defined EIS_PORT set "EIS_PORT=8201" + +set "CMD=%~1" +if "%CMD%"=="" goto :usage +if /I "%CMD%"=="-h" goto :usage +if /I "%CMD%"=="--help" goto :usage +if /I "%CMD%"=="help" goto :usage +if /I "%CMD%"=="init" goto :init +if /I "%CMD%"=="test" goto :test +if /I "%CMD%"=="start" goto :start +if /I "%CMD%"=="stop" goto :stop +if /I "%CMD%"=="smoke" goto :smoke +if /I "%CMD%"=="all" goto :all + +echo error: unknown command '%CMD%' +goto :usage + +:usage +echo Local registration-processor-external-integration-service ^(local profile, :8201 /registrationprocessor/v1/eis^) +echo. +echo run-local.bat init package this module +echo run-local.bat start run and wait until Spring Boot is ready +echo run-local.bat smoke GET health + OpenAPI +echo run-local.bat stop +echo run-local.bat test Maven tests +echo run-local.bat all init + test + start + smoke +echo. +echo Port: %EIS_PORT% ^(override with set EIS_PORT=...^) +echo Config: src\main\resources\application-local.properties +echo Cluster: Dockerfile still uses config-server; it does not activate profile local +exit /b 1 + +:port_in_use +netstat -ano | findstr /R /C:":%EIS_PORT% .*LISTENING" >nul 2>&1 +exit /b %ERRORLEVEL% + +:pid_on_port +set "PORT_PID=" +for /f "tokens=5" %%P in ('netstat -ano ^| findstr /R /C:":%EIS_PORT% .*LISTENING"') do set "PORT_PID=%%P" +exit /b 0 + +:ensure_dirs +if not exist "%LOG_DIR%" mkdir "%LOG_DIR%" +if not exist "%PID_DIR%" mkdir "%PID_DIR%" +exit /b 0 + +:check_prereqs +where java >nul 2>&1 +if errorlevel 1 ( + echo error: java is required on PATH + exit /b 1 +) +where mvn >nul 2>&1 +if errorlevel 1 ( + echo error: mvn is required on PATH + exit /b 1 +) +exit /b 0 + +:find_jar +set "BOOT_JAR=" +for %%F in ("%MODULE_DIR%\target\%MODULE%-*.jar") do ( + set "CAND=%%~nxF" + echo !CAND! | findstr /I /C:".original" /C:"sources" /C:"javadoc" >nul + if errorlevel 1 ( + set "BOOT_JAR=%%~fF" + goto :find_jar_done + ) +) +:find_jar_done +if not defined BOOT_JAR ( + echo error: no boot jar in target. Run: %~nx0 init + exit /b 1 +) +exit /b 0 + +:is_running +if not exist "%PID_FILE%" exit /b 1 +set /p CHECK_PID=<"%PID_FILE%" +if not defined CHECK_PID exit /b 1 +tasklist /FI "PID eq !CHECK_PID!" 2>nul | findstr /I "!CHECK_PID!" >nul +if errorlevel 1 exit /b 1 +exit /b 0 + +:init +call :check_prereqs +if errorlevel 1 exit /b 1 +call :stop +ping -n 3 127.0.0.1 >nul +echo ==^> packaging %MODULE% ^(skip tests^) +pushd "%PARENT_DIR%" +call mvn -pl %MODULE% clean package -DskipTests "-Dgpg.skip=true" "-Dmaven.javadoc.skip=true" +set "RC=%ERRORLEVEL%" +popd +if not "%RC%"=="0" exit /b %RC% +echo init complete +exit /b 0 + +:test +call :check_prereqs +if errorlevel 1 exit /b 1 +echo ==^> maven tests +pushd "%PARENT_DIR%" +call mvn -pl %MODULE% test "-Dgpg.skip=true" "-Dmaven.javadoc.skip=true" +set "RC=%ERRORLEVEL%" +popd +exit /b %RC% + +:print_urls +echo health http://127.0.0.1:%EIS_PORT%%CONTEXT%/actuator/health +echo swagger http://127.0.0.1:%EIS_PORT%%SWAGGER% +echo openapi http://127.0.0.1:%EIS_PORT%%OPENAPI% +echo stub POST http://127.0.0.1:%EIS_PORT%%EIS_POST% +exit /b 0 + +:start +echo. +echo ==^> run-local start +call :ensure_dirs +call :check_prereqs +if errorlevel 1 exit /b 1 +call :is_running +if not errorlevel 1 ( + set /p OLD_PID=<"%PID_FILE%" + echo eis already running ^(pid !OLD_PID!^) on port %EIS_PORT% + call :print_urls + exit /b 0 +) +call :port_in_use +if not errorlevel 1 ( + call :pid_on_port + echo eis already listening on port %EIS_PORT% ^(pid !PORT_PID!^) + if defined PORT_PID > "%PID_FILE%" echo !PORT_PID! + call :print_urls + exit /b 0 +) +if exist "%PID_FILE%" del /q "%PID_FILE%" >nul 2>&1 +if exist "%LOG_FILE%" del /q "%LOG_FILE%" >nul 2>&1 +if exist "%ERR_FILE%" del /q "%ERR_FILE%" >nul 2>&1 + +call :find_jar +if errorlevel 1 exit /b 1 + +echo ==^> starting eis from %BOOT_JAR% +echo profile=local +echo port=%EIS_PORT% +echo context=%CONTEXT% +echo properties=src\main\resources\application-local.properties + +set "LAUNCH_PS1=%LOCAL_DIR%\launch-eis.ps1" +> "%LAUNCH_PS1%" echo $ErrorActionPreference = 'Stop' +>> "%LAUNCH_PS1%" echo $argList = @^('-Dspring.profiles.active=local','-Dserver.port=%EIS_PORT%','-Dspring.cloud.config.enabled=false','-jar','%BOOT_JAR%'^) +>> "%LAUNCH_PS1%" echo $p = Start-Process -FilePath 'java' -ArgumentList $argList -WorkingDirectory '%MODULE_DIR%' -RedirectStandardOutput '%LOG_FILE%' -RedirectStandardError '%ERR_FILE%' -WindowStyle Hidden -PassThru +>> "%LAUNCH_PS1%" echo Set-Content -LiteralPath '%PID_FILE%' -Value $p.Id -Encoding ascii +powershell -NoProfile -ExecutionPolicy Bypass -File "%LAUNCH_PS1%" +if errorlevel 1 ( + echo error: failed to start java process + exit /b 1 +) + +echo ==^> waiting for Spring Boot startup on port %EIS_PORT% ^(up to 90s^) ... +call :wait_ready 90 +if errorlevel 1 exit /b 1 + +if exist "%PID_FILE%" ( + set /p STARTED_PID=<"%PID_FILE%" + echo pid !STARTED_PID! log %LOG_FILE% +) else ( + call :pid_on_port + if defined PORT_PID ( + > "%PID_FILE%" echo !PORT_PID! + echo pid !PORT_PID! log %LOG_FILE% + ) else ( + echo warn: ready but PID for port %EIS_PORT% not resolved + ) +) +echo. +echo eis ready +echo port %EIS_PORT% +call :print_urls +exit /b 0 + +:wait_ready +set /a WAIT_MAX=%~1 +if "!WAIT_MAX!"=="" set /a WAIT_MAX=90 +set /a WAIT_ELAPSED=0 +:wait_ready_loop +if !WAIT_ELAPSED! GEQ !WAIT_MAX! goto :wait_ready_fail + +call :port_in_use +if not errorlevel 1 ( + if exist "%LOG_FILE%" ( + findstr /C:"%STARTED%" "%LOG_FILE%" >nul 2>&1 + if not errorlevel 1 exit /b 0 + ) +) + +if exist "%LOG_FILE%" ( + findstr /C:"APPLICATION FAILED TO START" /C:"Port %EIS_PORT% was already in use" "%LOG_FILE%" >nul 2>&1 + if not errorlevel 1 ( + echo error: startup failed. See %LOG_FILE% + type "%LOG_FILE%" + exit /b 1 + ) +) + +echo ... still starting ^(!WAIT_ELAPSED!s / !WAIT_MAX!s^) +ping -n 3 127.0.0.1 >nul +set /a WAIT_ELAPSED+=2 +goto :wait_ready_loop + +:wait_ready_fail +echo error: Spring Boot did not become ready within !WAIT_MAX!s on port %EIS_PORT% +if exist "%LOG_FILE%" type "%LOG_FILE%" +exit /b 1 + +:stop +call :ensure_dirs +set "STOP_PID=" +if exist "%PID_FILE%" set /p STOP_PID=<"%PID_FILE%" +if not defined STOP_PID ( + call :pid_on_port + set "STOP_PID=!PORT_PID!" +) +if not defined STOP_PID ( + echo eis is not running + exit /b 0 +) +echo ==^> stopping eis ^(%STOP_PID%^) on port %EIS_PORT% +taskkill /PID %STOP_PID% /T /F >nul 2>&1 +del /q "%PID_FILE%" >nul 2>&1 +echo stopped. +exit /b 0 + +:http_ok +set "HTTP_CODE=000" +set "HTTP_URL=%~1" +set "HTTP_CODE_FILE=%LOCAL_DIR%\http-code.txt" +curl.exe -sS -o NUL -w "%%{http_code}" --connect-timeout 2 --max-time 3 "%HTTP_URL%" > "%HTTP_CODE_FILE%" 2>nul +if exist "%HTTP_CODE_FILE%" ( + for /f "usebackq delims=" %%C in ("%HTTP_CODE_FILE%") do set "HTTP_CODE=%%C" + del /q "%HTTP_CODE_FILE%" >nul 2>&1 +) +if not defined HTTP_CODE set "HTTP_CODE=000" +if "!HTTP_CODE!"=="" set "HTTP_CODE=000" +exit /b 0 + +:smoke +call :ensure_dirs +echo ==^> waiting for eis ^(up to 60s^) +set /a ELAPSED=0 +:smoke_loop +if %ELAPSED% GEQ 60 goto :smoke_fail +if exist "%PID_FILE%" ( + call :is_running + if errorlevel 1 ( + echo error: process exited. See %LOG_FILE% + if exist "%LOG_FILE%" type "%LOG_FILE%" + if exist "%ERR_FILE%" type "%ERR_FILE%" + exit /b 1 + ) +) +call :http_ok "http://127.0.0.1:%EIS_PORT%%CONTEXT%/actuator/health" +if "%HTTP_CODE%"=="200" ( + set "HEALTH_URL=http://127.0.0.1:%EIS_PORT%%CONTEXT%/actuator/health" + goto :smoke_ok +) +call :http_ok "http://127.0.0.1:%EIS_PORT%/actuator/health" +if "%HTTP_CODE%"=="200" ( + set "HEALTH_URL=http://127.0.0.1:%EIS_PORT%/actuator/health" + goto :smoke_ok +) +ping -n 3 127.0.0.1 >nul +set /a ELAPSED+=2 +goto :smoke_loop + +:smoke_ok +echo healthy %HEALTH_URL% +call :http_ok "http://127.0.0.1:%EIS_PORT%%OPENAPI%" +echo openapi http://127.0.0.1:%EIS_PORT%%OPENAPI% HTTP %HTTP_CODE% +if not "%HTTP_CODE%"=="200" ( + echo error: openapi endpoint not healthy + exit /b 1 +) +echo smoke ok +exit /b 0 + +:smoke_fail +echo error: not healthy. See %LOG_FILE% +if exist "%LOG_FILE%" type "%LOG_FILE%" +if exist "%ERR_FILE%" type "%ERR_FILE%" +exit /b 1 + +:all +echo ==^> all: init + test + start + smoke +call :init +if errorlevel 1 exit /b 1 +call :test +if errorlevel 1 exit /b 1 +call :start +if errorlevel 1 exit /b 1 +call :smoke +exit /b %ERRORLEVEL% diff --git a/registration-processor/registration-processor-external-integration-service/run-local.sh b/registration-processor/registration-processor-external-integration-service/run-local.sh new file mode 100644 index 0000000000..c5437fb3c1 --- /dev/null +++ b/registration-processor/registration-processor-external-integration-service/run-local.sh @@ -0,0 +1,309 @@ +#!/usr/bin/env bash +# registration-processor-external-integration-service local runner — Linux, macOS, Git Bash. +# Windows cmd: use run-local.bat (standalone; no .ps1). +# +# Uses src/main/resources/application-local.properties (profile local). +# No config-server required. Cluster Docker does not activate profile local. +set -euo pipefail + +MODULE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PARENT_DIR="$(cd "${MODULE_DIR}/.." && pwd)" +LOCAL_DIR="${MODULE_DIR}/.local" +LOG_DIR="${LOCAL_DIR}/logs" +PID_DIR="${LOCAL_DIR}/pids" +PORT="${EIS_PORT:-8201}" +PID_FILE="${PID_DIR}/eis.pid" +LOG_FILE="${LOG_DIR}/eis.log" +MODULE="registration-processor-external-integration-service" +UNAME_S="$(uname -s 2>/dev/null || echo unknown)" +CONTEXT="/registrationprocessor/v1/eis" +STARTED="Started ExternalIntegrationServiceApplication" +SWAGGER="${CONTEXT}/swagger-ui.html" +OPENAPI="${CONTEXT}/v3/api-docs" +EIS_POST="${CONTEXT}/registration-processor/external-integration-service/v1.0" + +MVN_SKIP=( + "-DskipTests" + "-Dgpg.skip=true" + "-Dmaven.javadoc.skip=true" +) + +usage() { + cat <<'EOF' +Local registration-processor-external-integration-service (local profile, :8201 /registrationprocessor/v1/eis) + + Linux / macOS / Git Bash: + ./run-local.sh init | start | smoke | stop | test | all + + Windows cmd: + run-local.bat init | start | smoke | stop | test | all + +Config: src/main/resources/application-local.properties +Cluster: Dockerfile still uses config-server; it does not activate profile local + + all = init + test + start + smoke +EOF + exit "${1:-0}" +} + +need_cmd() { + command -v "$1" >/dev/null 2>&1 || { + echo "error: '$1' is required on PATH" >&2 + exit 1 + } +} + +ensure_dirs() { + mkdir -p "$LOG_DIR" "$PID_DIR" +} + +check_prereqs() { + need_cmd java + need_cmd mvn + echo "os: ${UNAME_S}" + local ver + ver="$(java -version 2>&1 | head -n 1 || true)" + echo "java: $ver" + if ! echo "$ver" | grep -E '"21[\. "]' >/dev/null 2>&1; then + echo "warn: JDK 21 is required. Continuing anyway." >&2 + fi +} + +find_boot_jar() { + local target="${MODULE_DIR}/target" + local jar + if [[ ! -d "$target" ]]; then + echo "error: not packaged. Run: $0 init" >&2 + exit 1 + fi + for jar in "$target"/${MODULE}-*.jar; do + [[ -f "$jar" ]] || continue + case "$jar" in + *.original|*sources*|*javadoc*) continue ;; + esac + echo "$jar" + return 0 + done + echo "error: no boot jar in ${target}. Run: $0 init" >&2 + exit 1 +} + +is_running() { + [[ -f "$PID_FILE" ]] || return 1 + kill -0 "$(cat "$PID_FILE")" 2>/dev/null +} + +print_urls() { + echo " health http://127.0.0.1:${PORT}${CONTEXT}/actuator/health" + echo " swagger http://127.0.0.1:${PORT}${SWAGGER}" + echo " openapi http://127.0.0.1:${PORT}${OPENAPI}" + echo " stub POST http://127.0.0.1:${PORT}${EIS_POST}" +} + +cmd_init() { + check_prereqs + cmd_stop + echo "==> packaging ${MODULE} (skip tests)" + (cd "$PARENT_DIR" && mvn -pl "$MODULE" clean package "${MVN_SKIP[@]}") + echo "init complete" +} + +cmd_test() { + check_prereqs + echo "==> maven tests" + (cd "$PARENT_DIR" && mvn -pl "$MODULE" test "-Dgpg.skip=true" "-Dmaven.javadoc.skip=true") +} + +cmd_start() { + echo + echo "==> run-local start" + ensure_dirs + check_prereqs + if is_running; then + echo "eis already running (pid $(cat "$PID_FILE")) on port ${PORT}" + print_urls + return 0 + fi + rm -f "$LOG_FILE" + local jar + jar="$(find_boot_jar)" + echo "==> starting eis from $(basename "$jar")" + echo " profile=local" + echo " port=${PORT}" + echo " context=${CONTEXT}" + echo " properties=src/main/resources/application-local.properties" + local java_args=( + "-Dspring.profiles.active=local" + "-Dserver.port=${PORT}" + "-Dspring.cloud.config.enabled=false" + ) + java_args+=(-jar "$jar") + nohup java "${java_args[@]}" >"$LOG_FILE" 2>&1 & + echo $! >"$PID_FILE" + echo "pid $(cat "$PID_FILE") log ${LOG_FILE}" + echo "==> waiting for Spring Boot startup on port ${PORT} (up to 90s) ..." + wait_ready 90 + echo + echo "eis ready" + echo " port ${PORT}" + print_urls +} + +wait_ready() { + local timeout="${1:-90}" + local elapsed=0 + local code + while [[ "$elapsed" -lt "$timeout" ]]; do + if ! is_running; then + echo "error: process exited during startup. See ${LOG_FILE}" >&2 + tail -n 80 "$LOG_FILE" >&2 || true + return 1 + fi + if grep -q "${STARTED}" "$LOG_FILE" 2>/dev/null; then + code="$(http_ok "http://127.0.0.1:${PORT}${CONTEXT}/actuator/health")" + if [[ "$code" == "200" ]]; then + return 0 + fi + code="$(http_ok "http://127.0.0.1:${PORT}/actuator/health")" + if [[ "$code" == "200" ]]; then + return 0 + fi + fi + code="$(http_ok "http://127.0.0.1:${PORT}${CONTEXT}/actuator/health")" + if [[ "$code" == "200" ]]; then + return 0 + fi + if grep -q "APPLICATION FAILED TO START\|Port ${PORT} was already in use" "$LOG_FILE" 2>/dev/null; then + echo "error: startup failed. See ${LOG_FILE}" >&2 + tail -n 80 "$LOG_FILE" >&2 || true + return 1 + fi + echo " ... still starting (${elapsed}s / ${timeout}s)" + sleep 2 + elapsed=$((elapsed + 2)) + done + echo "error: Spring Boot did not become ready within ${timeout}s on port ${PORT}" >&2 + tail -n 80 "$LOG_FILE" >&2 || true + return 1 +} + +http_ok() { + local url="$1" + local code + if command -v curl >/dev/null 2>&1; then + code="$(curl -sS -o /dev/null -w "%{http_code}" --connect-timeout 2 --max-time 3 "$url" 2>/dev/null || true)" + [[ -n "$code" ]] || code="000" + printf '%s' "$code" + return 0 + fi + if command -v python3 >/dev/null 2>&1; then + python3 -c 'import sys,urllib.request +try: + urllib.request.urlopen(sys.argv[1], timeout=3) + print("200") +except Exception: + print("000")' "$url" + return 0 + fi + if command -v python >/dev/null 2>&1; then + python -c 'import sys,urllib.request +try: + urllib.request.urlopen(sys.argv[1], timeout=3) + print("200") +except Exception: + print("000")' "$url" + return 0 + fi + echo "error: install curl or python3 for smoke checks" >&2 + printf '%s' "000" +} + +cmd_stop() { + ensure_dirs + if ! is_running; then + rm -f "$PID_FILE" + echo "eis is not running" + return 0 + fi + local pid + pid="$(cat "$PID_FILE")" + echo "==> stopping eis (${pid}) on port ${PORT}" + kill "$pid" 2>/dev/null || true + local i + for i in 1 2 3 4 5 6 7 8 9 10; do + kill -0 "$pid" 2>/dev/null || break + sleep 1 + done + if kill -0 "$pid" 2>/dev/null; then + kill -9 "$pid" 2>/dev/null || true + fi + rm -f "$PID_FILE" + echo "stopped." +} + +cmd_smoke() { + ensure_dirs + local timeout="${1:-60}" + local elapsed=0 + echo "==> waiting for eis (up to ${timeout}s)" + while [[ "$elapsed" -lt "$timeout" ]]; do + if [[ -f "$PID_FILE" ]] && ! is_running; then + echo "error: process exited. See ${LOG_FILE}" >&2 + tail -n 40 "$LOG_FILE" >&2 || true + return 1 + fi + local url code health_url="" + for url in \ + "http://127.0.0.1:${PORT}${CONTEXT}/actuator/health" \ + "http://127.0.0.1:${PORT}/actuator/health" + do + code="$(http_ok "$url")" + if [[ "$code" == "200" ]]; then + health_url="$url" + break + fi + done + if [[ -n "$health_url" ]]; then + echo "healthy ${health_url}" + code="$(http_ok "http://127.0.0.1:${PORT}${OPENAPI}")" + echo "openapi http://127.0.0.1:${PORT}${OPENAPI} HTTP ${code}" + if [[ "$code" != "200" ]]; then + echo "error: openapi endpoint not healthy" >&2 + return 1 + fi + echo "smoke ok" + return 0 + fi + sleep 2 + elapsed=$((elapsed + 2)) + done + echo "error: not healthy. See ${LOG_FILE}" >&2 + tail -n 80 "$LOG_FILE" >&2 || true + return 1 +} + +cmd_all() { + echo "==> all: init + test + start + smoke" + cmd_init + cmd_test + cmd_start + cmd_smoke +} + +main() { + local cmd="${1:-}" + shift || true + case "$cmd" in + -h|--help|help) usage 0 ;; + init) cmd_init ;; + test) cmd_test ;; + start) cmd_start ;; + stop) cmd_stop ;; + smoke) cmd_smoke "${1:-60}" ;; + all) cmd_all ;; + "") usage 1 ;; + *) echo "error: unknown command '$cmd'" >&2; usage 1 ;; + esac +} + +main "$@" diff --git a/registration-processor/registration-processor-external-integration-service/src/main/resources/application-local.properties b/registration-processor/registration-processor-external-integration-service/src/main/resources/application-local.properties new file mode 100644 index 0000000000..ff4606f20b --- /dev/null +++ b/registration-processor/registration-processor-external-integration-service/src/main/resources/application-local.properties @@ -0,0 +1,44 @@ +# Local profile for registration-processor-external-integration-service (run-local.sh / run-local.bat). +# Activate with: -Dspring.profiles.active=local +# Cluster Docker does not set this profile; it uses bootstrap + config-server env. +# No config-server required. Stub POST always returns true when the body is non-null. + +server.port=8201 +server.servlet.path=/registrationprocessor/v1/eis +spring.mvc.servlet.path=${server.servlet.path} + +spring.http.converters.preferred-json-mapper=jackson2 + +spring.cloud.config.enabled=false +spring.cloud.config.fail-fast=false +spring.config.import=optional:configserver: +health.config.enabled=false +management.health.config.enabled=false +management.endpoint.health.show-details=always +management.endpoints.web.exposure.include=info,health,refresh +spring.info.git.location=classpath:service-git.properties + +mosip.auth.adapter.impl.basepackage=io.mosip.kernel.auth.defaultadapter +auth.server.admin.offline.token.validate=true +spring.security.method-security.enabled=false +spring.mvc.pathmatch.matching-strategy=ant_path_matcher +mosip.global.end-points=/** +mosip.service.end-points=/** + +openapi.info.title=External Integration Service +openapi.info.description=External Integration Service +openapi.info.version=1.0 +openapi.info.license.name=Mosip +openapi.info.license.url=https://docs.mosip.io/platform/license +openapi.service.servers[0].url=${server.servlet.path} +openapi.service.servers[0].description=External Integration Service +openapi.group.name=${openapi.info.title} +openapi.group.paths[0]=/** +springdoc.swagger-ui.disable-swagger-default-url=true +springdoc.swagger-ui.tagsSorter=alpha +springdoc.swagger-ui.operationsSorter=alpha +springdoc.swagger-ui.syntaxHighlight.activated=false +springdoc.swagger-ui.validator-url=none +springdoc.swagger-ui.persistAuthorization=true +springdoc.swagger-ui.path=/swagger-ui.html +springdoc.api-docs.path=/v3/api-docs diff --git a/registration-processor/registration-processor-external-stage/AGENTS.md b/registration-processor/registration-processor-external-stage/AGENTS.md index e88d1cf6af..cd0d7d7375 100644 --- a/registration-processor/registration-processor-external-stage/AGENTS.md +++ b/registration-processor/registration-processor-external-stage/AGENTS.md @@ -4,7 +4,7 @@ Vert.x `ExternalStage`. `EXTERNAL_STAGE_BUS_IN` → POST EIS → `EXTERNAL_STAGE ``` registration-processor-external-stage/ -├── pom.xml Dockerfile README.md AGENTS.md +├── pom.xml Dockerfile README.md AGENTS.md run-local.bat run-local.sh └── src/ ├── main/ │ ├── java/io/mosip/registrationprocessor/externalstage/ @@ -13,7 +13,9 @@ registration-processor-external-stage/ │ │ ├── config/Externalconfig.java │ │ ├── entity/BaseRestRequestDTO.java MessageRequestDTO.java │ │ └── utils/StatusMessage.java - │ └── resources/ bootstrap.properties logback.xml + │ ├── java/io/mosip/registration/processor/status/entity/ BasePacketEntity BaseRegistrationEntity (Hibernate 7) + │ ├── java/org/springframework/boot/web/client/ RestTemplateBuilder RestTemplateCustomizer + │ └── resources/ bootstrap.properties application-local.properties hazelcast-local.xml logback.xml └── test/java/.../externalstage/ ├── ExternalStageApplicationTests.java └── stage/ExternalStageTest.java diff --git a/registration-processor/registration-processor-external-stage/README.md b/registration-processor/registration-processor-external-stage/README.md index 2cd2549a32..406af6d8c4 100644 --- a/registration-processor/registration-processor-external-stage/README.md +++ b/registration-processor/registration-processor-external-stage/README.md @@ -50,7 +50,44 @@ External validation by sending the packet id list to EIS (`ApiName.EISERVICE`). - JDK **21.0.3** - Maven **3.9.6** -- Config server + Kafka/Vert.x cluster as in MOSIP registration-processor +- Cluster: config-server + Kafka/Vert.x. Laptop: `run-local` (`init`/`test` without that stack) + +## Local testing (run-local) + +Laptop runner (same commands as commons `kernel-notification-service`). Profile **`local`** loads `src/main/resources/application-local.properties` from `ExternalStageApplication` (this is Vert.x, not `SpringApplication`). Cluster Docker does **not** set this profile. + +Windows cmd (from this module directory): + +```text +run-local.bat init +run-local.bat test +run-local.bat start +run-local.bat smoke +run-local.bat stop +``` + +| Command | What it does | +|---|---| +| `init` | Stops a leftover process, then `mvn clean package` (skip tests, skip GPG/Javadoc) | +| `test` | `mvn test` for this module | +| `start` | Fat JAR with profile `local`, waits until HTTP `:8095` (or `EXTERNAL_STAGE_STARTUP_FAILED`) | +| `smoke` | GET health if present, else port listening / `Started ExternalStageApplication` | +| `stop` | Kills the PID under `.local/pids/` | +| `all` | `init` + `test` + `start` + `smoke` | + +Linux / macOS / Git Bash: `./run-local.sh `. Maven is invoked from `registration-processor/` with `-pl registration-processor-external-stage -am`. Override the port with `set STAGE_PORT=8095` (cmd) or `STAGE_PORT=8095 ./run-local.sh start`. + +Profile `local` skips config-server (`ConfigPropertyReader` / Vert.x `SpringConfigServerStore`), Hazelcast cluster (`getEventBus`), and Brave 5 `postUrl` tracing. H2 supplies `javax.persistence.jdbc.*`. This module shadows MOSIP `BasePacketEntity` / `BaseRegistrationEntity` (Hibernate 7 forbids `@Inheritance` on `@MappedSuperclass`). Packet processing still needs Kafka, a status DB, and EIS. `init` / `test` work without that stack. + +| | | +|---|---| +| HTTP | `8095` (`STAGE_PORT`) | +| Eventbus | `5736` | +| Health | `http://127.0.0.1:8095/registrationprocessor/v1/external/actuator/health` | +| Logs | `.local/logs/external-stage.log` (gitignored) | +| PID | `.local/pids/external-stage.pid` | + +Full command table: [repo README — Local testing](../../README.md#local-testing-run-local). ## Build & run diff --git a/registration-processor/registration-processor-external-stage/run-local.bat b/registration-processor/registration-processor-external-stage/run-local.bat new file mode 100644 index 0000000000..a71cb6943d --- /dev/null +++ b/registration-processor/registration-processor-external-stage/run-local.bat @@ -0,0 +1,346 @@ +@echo off +setlocal EnableExtensions EnableDelayedExpansion +REM Standalone Windows cmd runner for registration-processor-external-stage. +REM Linux / macOS / Git Bash: use run-local.sh +REM +REM run-local.bat init | start | smoke | stop | test | all + +set "MODULE_DIR=%~dp0" +if "%MODULE_DIR:~-1%"=="\" set "MODULE_DIR=%MODULE_DIR:~0,-1%" +for %%I in ("%MODULE_DIR%\..") do set "PARENT_DIR=%%~fI" + +set "LOCAL_DIR=%MODULE_DIR%\.local" +set "LOG_DIR=%LOCAL_DIR%\logs" +set "PID_DIR=%LOCAL_DIR%\pids" +set "PID_FILE=%PID_DIR%\external-stage.pid" +set "LOG_FILE=%LOG_DIR%\external-stage.log" +set "ERR_FILE=%LOG_DIR%\external-stage.err.log" +set "MODULE=registration-processor-external-stage" +set "CONTEXT=/registrationprocessor/v1/external" +set "STARTED=Started ExternalStageApplication" + +if not defined STAGE_PORT set "STAGE_PORT=8095" + +set "CMD=%~1" +if "%CMD%"=="" goto :usage +if /I "%CMD%"=="-h" goto :usage +if /I "%CMD%"=="--help" goto :usage +if /I "%CMD%"=="help" goto :usage +if /I "%CMD%"=="init" goto :init +if /I "%CMD%"=="test" goto :test +if /I "%CMD%"=="start" goto :start +if /I "%CMD%"=="stop" goto :stop +if /I "%CMD%"=="smoke" goto :smoke +if /I "%CMD%"=="all" goto :all + +echo error: unknown command '%CMD%' +goto :usage + +:usage +echo Local registration-processor-external-stage ^(local profile, HTTP :8095, eventbus :5736^) +echo. +echo run-local.bat init package this module ^(plus reactor^) +echo run-local.bat start run Vert.x stage and wait until ready +echo run-local.bat smoke GET health if present, else port listening +echo run-local.bat stop +echo run-local.bat test Maven tests +echo run-local.bat all init + test + start + smoke +echo. +echo Port: %STAGE_PORT% ^(override with set STAGE_PORT=...^) +echo Config: src\main\resources\application-local.properties +echo Packet hop needs Kafka, status DB, and EIS. init/test do not. +echo Cluster: Dockerfile still uses config-server; it does not activate profile local +exit /b 1 + +:port_in_use +netstat -ano | findstr /R /C:":%STAGE_PORT% .*LISTENING" >nul 2>&1 +exit /b %ERRORLEVEL% + +:pid_on_port +set "PORT_PID=" +for /f "tokens=5" %%P in ('netstat -ano ^| findstr /R /C:":%STAGE_PORT% .*LISTENING"') do set "PORT_PID=%%P" +exit /b 0 + +:ensure_dirs +if not exist "%LOG_DIR%" mkdir "%LOG_DIR%" +if not exist "%PID_DIR%" mkdir "%PID_DIR%" +exit /b 0 + +:check_prereqs +where java >nul 2>&1 +if errorlevel 1 ( + echo error: java is required on PATH + exit /b 1 +) +where mvn >nul 2>&1 +if errorlevel 1 ( + echo error: mvn is required on PATH + exit /b 1 +) +exit /b 0 + +:find_jar +set "BOOT_JAR=" +for %%F in ("%MODULE_DIR%\target\%MODULE%-*.jar") do ( + set "CAND=%%~nxF" + echo !CAND! | findstr /I /C:".original" /C:"sources" /C:"javadoc" >nul + if errorlevel 1 ( + set "BOOT_JAR=%%~fF" + goto :find_jar_done + ) +) +:find_jar_done +if not defined BOOT_JAR ( + echo error: no boot jar in target. Run: %~nx0 init + exit /b 1 +) +exit /b 0 + +:is_running +if not exist "%PID_FILE%" exit /b 1 +set /p CHECK_PID=<"%PID_FILE%" +if not defined CHECK_PID exit /b 1 +tasklist /FI "PID eq !CHECK_PID!" 2>nul | findstr /I "!CHECK_PID!" >nul +if errorlevel 1 exit /b 1 +exit /b 0 + +:init +call :check_prereqs +if errorlevel 1 exit /b 1 +call :stop +ping -n 3 127.0.0.1 >nul +echo ==^> packaging %MODULE% ^(skip tests, -am^) +pushd "%PARENT_DIR%" +call mvn -pl %MODULE% -am clean package -DskipTests "-Dgpg.skip=true" "-Dmaven.javadoc.skip=true" +set "RC=%ERRORLEVEL%" +popd +if not "%RC%"=="0" exit /b %RC% +echo init complete +exit /b 0 + +:test +call :check_prereqs +if errorlevel 1 exit /b 1 +echo ==^> maven tests +pushd "%PARENT_DIR%" +call mvn -pl %MODULE% -am test "-Dgpg.skip=true" "-Dmaven.javadoc.skip=true" +set "RC=%ERRORLEVEL%" +popd +exit /b %RC% + +:print_urls +echo health http://127.0.0.1:%STAGE_PORT%%CONTEXT%/actuator/health +echo eventbus 5736 +exit /b 0 + +:start +echo. +echo ==^> run-local start +call :ensure_dirs +call :check_prereqs +if errorlevel 1 exit /b 1 +call :is_running +if not errorlevel 1 ( + set /p OLD_PID=<"%PID_FILE%" + echo external-stage already running ^(pid !OLD_PID!^) on port %STAGE_PORT% + call :print_urls + exit /b 0 +) +call :port_in_use +if not errorlevel 1 ( + call :pid_on_port + echo external-stage already listening on port %STAGE_PORT% ^(pid !PORT_PID!^) + if defined PORT_PID > "%PID_FILE%" echo !PORT_PID! + call :print_urls + exit /b 0 +) +if exist "%PID_FILE%" del /q "%PID_FILE%" >nul 2>&1 +if exist "%LOG_FILE%" del /q "%LOG_FILE%" >nul 2>&1 +if exist "%ERR_FILE%" del /q "%ERR_FILE%" >nul 2>&1 + +call :find_jar +if errorlevel 1 exit /b 1 + +echo ==^> starting external-stage from %BOOT_JAR% +echo profile=local +echo port=%STAGE_PORT% +echo context=%CONTEXT% +echo properties=src\main\resources\application-local.properties + +set "LAUNCH_PS1=%LOCAL_DIR%\launch-external-stage.ps1" +> "%LAUNCH_PS1%" echo $ErrorActionPreference = 'Stop' +>> "%LAUNCH_PS1%" echo $argList = @^('-Dspring.profiles.active=local','-Dserver.port=%STAGE_PORT%','-Dspring.cloud.config.enabled=false','-Dmosip.auth.adapter.impl.basepackage=io.mosip.kernel.auth.defaultadapter','-jar','%BOOT_JAR%'^) +>> "%LAUNCH_PS1%" echo $p = Start-Process -FilePath 'java' -ArgumentList $argList -WorkingDirectory '%MODULE_DIR%' -RedirectStandardOutput '%LOG_FILE%' -RedirectStandardError '%ERR_FILE%' -WindowStyle Hidden -PassThru +>> "%LAUNCH_PS1%" echo Set-Content -LiteralPath '%PID_FILE%' -Value $p.Id -Encoding ascii +powershell -NoProfile -ExecutionPolicy Bypass -File "%LAUNCH_PS1%" +if errorlevel 1 ( + echo error: failed to start java process + exit /b 1 +) + +echo ==^> waiting for Vert.x stage on port %STAGE_PORT% ^(up to 120s^) ... +call :wait_ready 120 +if errorlevel 1 ( + call :stop + exit /b 1 +) + +if exist "%PID_FILE%" ( + set /p STARTED_PID=<"%PID_FILE%" + echo pid !STARTED_PID! log %LOG_FILE% +) else ( + call :pid_on_port + if defined PORT_PID ( + > "%PID_FILE%" echo !PORT_PID! + echo pid !PORT_PID! log %LOG_FILE% + ) else ( + echo warn: ready but PID for port %STAGE_PORT% not resolved + ) +) +echo. +echo external-stage ready +echo port %STAGE_PORT% +call :print_urls +exit /b 0 + +:wait_ready +set /a WAIT_MAX=%~1 +if "!WAIT_MAX!"=="" set /a WAIT_MAX=120 +set /a WAIT_ELAPSED=0 +:wait_ready_loop +if !WAIT_ELAPSED! GEQ !WAIT_MAX! goto :wait_ready_fail + +if exist "%LOG_FILE%" ( + findstr /C:"%STARTED%" "%LOG_FILE%" >nul 2>&1 + if not errorlevel 1 exit /b 0 +) + +call :port_in_use +if not errorlevel 1 ( + if exist "%LOG_FILE%" ( + findstr /C:"%STARTED%" "%LOG_FILE%" >nul 2>&1 + if not errorlevel 1 exit /b 0 + ) +) + +if exist "%LOG_FILE%" ( + findstr /C:"EXTERNAL_STAGE_STARTUP_FAILED" /C:"APPLICATION FAILED TO START" /C:"Exception in thread" /C:"Failed to introspect" /C:"cancelling refresh attempt" /C:"Invalid url for the spring server" /C:"Port %STAGE_PORT% was already in use" "%LOG_FILE%" >nul 2>&1 + if not errorlevel 1 ( + echo error: startup failed. See %LOG_FILE% + type "%LOG_FILE%" + if exist "%ERR_FILE%" type "%ERR_FILE%" + exit /b 1 + ) +) +if exist "%ERR_FILE%" ( + findstr /C:"EXTERNAL_STAGE_STARTUP_FAILED" /C:"APPLICATION FAILED TO START" /C:"Exception in thread" /C:"URI is not absolute" "%ERR_FILE%" >nul 2>&1 + if not errorlevel 1 ( + echo error: startup failed. See %ERR_FILE% + type "%ERR_FILE%" + exit /b 1 + ) +) + +echo ... still starting ^(!WAIT_ELAPSED!s / !WAIT_MAX!s^) +ping -n 3 127.0.0.1 >nul +set /a WAIT_ELAPSED+=2 +goto :wait_ready_loop + +:wait_ready_fail +echo error: external-stage did not become ready within !WAIT_MAX!s on port %STAGE_PORT% +if exist "%LOG_FILE%" type "%LOG_FILE%" +if exist "%ERR_FILE%" type "%ERR_FILE%" +exit /b 1 + +:stop +call :ensure_dirs +set "STOP_PID=" +if exist "%PID_FILE%" set /p STOP_PID=<"%PID_FILE%" +if not defined STOP_PID ( + call :pid_on_port + set "STOP_PID=!PORT_PID!" +) +if not defined STOP_PID ( + echo external-stage is not running + exit /b 0 +) +echo ==^> stopping external-stage ^(%STOP_PID%^) on port %STAGE_PORT% +taskkill /PID %STOP_PID% /T /F >nul 2>&1 +del /q "%PID_FILE%" >nul 2>&1 +echo stopped. +exit /b 0 + +:http_ok +set "HTTP_CODE=000" +set "HTTP_URL=%~1" +set "HTTP_CODE_FILE=%LOCAL_DIR%\http-code.txt" +curl.exe -sS -o NUL -w "%%{http_code}" --connect-timeout 2 --max-time 3 "%HTTP_URL%" > "%HTTP_CODE_FILE%" 2>nul +if exist "%HTTP_CODE_FILE%" ( + for /f "usebackq delims=" %%C in ("%HTTP_CODE_FILE%") do set "HTTP_CODE=%%C" + del /q "%HTTP_CODE_FILE%" >nul 2>&1 +) +if not defined HTTP_CODE set "HTTP_CODE=000" +if "!HTTP_CODE!"=="" set "HTTP_CODE=000" +exit /b 0 + +:smoke +call :ensure_dirs +echo ==^> waiting for external-stage ^(up to 60s^) +set /a ELAPSED=0 +:smoke_loop +if %ELAPSED% GEQ 60 goto :smoke_fail +if exist "%PID_FILE%" ( + call :is_running + if errorlevel 1 ( + echo error: process exited. See %LOG_FILE% + if exist "%LOG_FILE%" type "%LOG_FILE%" + if exist "%ERR_FILE%" type "%ERR_FILE%" + exit /b 1 + ) +) +call :http_ok "http://127.0.0.1:%STAGE_PORT%%CONTEXT%/actuator/health" +if "%HTTP_CODE%"=="200" ( + echo healthy http://127.0.0.1:%STAGE_PORT%%CONTEXT%/actuator/health + echo smoke ok + exit /b 0 +) +call :http_ok "http://127.0.0.1:%STAGE_PORT%/actuator/health" +if "%HTTP_CODE%"=="200" ( + echo healthy http://127.0.0.1:%STAGE_PORT%/actuator/health + echo smoke ok + exit /b 0 +) +call :port_in_use +if not errorlevel 1 ( + echo listening on port %STAGE_PORT% ^(Vert.x HTTP; actuator optional^) + echo smoke ok + exit /b 0 +) +if exist "%LOG_FILE%" ( + findstr /C:"%STARTED%" "%LOG_FILE%" >nul 2>&1 + if not errorlevel 1 ( + echo started marker in log + echo smoke ok + exit /b 0 + ) +) +ping -n 3 127.0.0.1 >nul +set /a ELAPSED+=2 +goto :smoke_loop + +:smoke_fail +echo error: not healthy. See %LOG_FILE% +if exist "%LOG_FILE%" type "%LOG_FILE%" +if exist "%ERR_FILE%" type "%ERR_FILE%" +exit /b 1 + +:all +echo ==^> all: init + test + start + smoke +call :init +if errorlevel 1 exit /b 1 +call :test +if errorlevel 1 exit /b 1 +call :start +if errorlevel 1 exit /b 1 +call :smoke +exit /b %ERRORLEVEL% diff --git a/registration-processor/registration-processor-external-stage/run-local.sh b/registration-processor/registration-processor-external-stage/run-local.sh new file mode 100644 index 0000000000..468916ba3c --- /dev/null +++ b/registration-processor/registration-processor-external-stage/run-local.sh @@ -0,0 +1,302 @@ +#!/usr/bin/env bash +# registration-processor-external-stage local runner — Linux, macOS, Git Bash. +# Windows cmd: use run-local.bat (standalone; no .ps1). +# +# Uses src/main/resources/application-local.properties (profile local). +# Cluster Docker does not activate profile local. +set -euo pipefail + +MODULE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PARENT_DIR="$(cd "${MODULE_DIR}/.." && pwd)" +LOCAL_DIR="${MODULE_DIR}/.local" +LOG_DIR="${LOCAL_DIR}/logs" +PID_DIR="${LOCAL_DIR}/pids" +PORT="${STAGE_PORT:-8095}" +PID_FILE="${PID_DIR}/external-stage.pid" +LOG_FILE="${LOG_DIR}/external-stage.log" +MODULE="registration-processor-external-stage" +UNAME_S="$(uname -s 2>/dev/null || echo unknown)" +CONTEXT="/registrationprocessor/v1/external" +STARTED="Started ExternalStageApplication" + +MVN_SKIP=( + "-DskipTests" + "-Dgpg.skip=true" + "-Dmaven.javadoc.skip=true" +) + +usage() { + cat <<'EOF' +Local registration-processor-external-stage (local profile, HTTP :8095, eventbus :5736) + + Linux / macOS / Git Bash: + ./run-local.sh init | start | smoke | stop | test | all + + Windows cmd: + run-local.bat init | start | smoke | stop | test | all + +Config: src/main/resources/application-local.properties +Packet hop needs Kafka, status DB, and EIS. init/test do not. +Cluster: Dockerfile still uses config-server; it does not activate profile local + + all = init + test + start + smoke +EOF + exit "${1:-0}" +} + +need_cmd() { + command -v "$1" >/dev/null 2>&1 || { + echo "error: '$1' is required on PATH" >&2 + exit 1 + } +} + +ensure_dirs() { + mkdir -p "$LOG_DIR" "$PID_DIR" +} + +check_prereqs() { + need_cmd java + need_cmd mvn + echo "os: ${UNAME_S}" + local ver + ver="$(java -version 2>&1 | head -n 1 || true)" + echo "java: $ver" + if ! echo "$ver" | grep -E '"21[\. "]' >/dev/null 2>&1; then + echo "warn: JDK 21 is required. Continuing anyway." >&2 + fi +} + +find_boot_jar() { + local target="${MODULE_DIR}/target" + local jar + if [[ ! -d "$target" ]]; then + echo "error: not packaged. Run: $0 init" >&2 + exit 1 + fi + for jar in "$target"/${MODULE}-*.jar; do + [[ -f "$jar" ]] || continue + case "$jar" in + *.original|*sources*|*javadoc*) continue ;; + esac + echo "$jar" + return 0 + done + echo "error: no boot jar in ${target}. Run: $0 init" >&2 + exit 1 +} + +is_running() { + [[ -f "$PID_FILE" ]] || return 1 + kill -0 "$(cat "$PID_FILE")" 2>/dev/null +} + +print_urls() { + echo " health http://127.0.0.1:${PORT}${CONTEXT}/actuator/health" + echo " eventbus 5736" +} + +cmd_init() { + check_prereqs + cmd_stop + echo "==> packaging ${MODULE} (skip tests, -am)" + (cd "$PARENT_DIR" && mvn -pl "$MODULE" -am clean package "${MVN_SKIP[@]}") + echo "init complete" +} + +cmd_test() { + check_prereqs + echo "==> maven tests" + (cd "$PARENT_DIR" && mvn -pl "$MODULE" -am test "-Dgpg.skip=true" "-Dmaven.javadoc.skip=true") +} + +cmd_start() { + echo + echo "==> run-local start" + ensure_dirs + check_prereqs + if is_running; then + echo "external-stage already running (pid $(cat "$PID_FILE")) on port ${PORT}" + print_urls + return 0 + fi + rm -f "$LOG_FILE" + local jar + jar="$(find_boot_jar)" + echo "==> starting external-stage from $(basename "$jar")" + echo " profile=local" + echo " port=${PORT}" + echo " context=${CONTEXT}" + echo " properties=src/main/resources/application-local.properties" + local java_args=( + "-Dspring.profiles.active=local" + "-Dserver.port=${PORT}" + "-Dspring.cloud.config.enabled=false" + "-Dmosip.auth.adapter.impl.basepackage=io.mosip.kernel.auth.defaultadapter" + ) + java_args+=(-jar "$jar") + nohup java "${java_args[@]}" >"$LOG_FILE" 2>&1 & + echo $! >"$PID_FILE" + echo "pid $(cat "$PID_FILE") log ${LOG_FILE}" + echo "==> waiting for Vert.x stage on port ${PORT} (up to 120s) ..." + if ! wait_ready 120; then + cmd_stop + return 1 + fi + echo + echo "external-stage ready" + echo " port ${PORT}" + print_urls +} + +wait_ready() { + local timeout="${1:-120}" + local elapsed=0 + while [[ "$elapsed" -lt "$timeout" ]]; do + if ! is_running; then + echo "error: process exited during startup. See ${LOG_FILE}" >&2 + tail -n 80 "$LOG_FILE" >&2 || true + return 1 + fi + if grep -q "${STARTED}" "$LOG_FILE" 2>/dev/null; then + return 0 + fi + if grep -q "EXTERNAL_STAGE_STARTUP_FAILED\|APPLICATION FAILED TO START\|Exception in thread\|Failed to introspect\|cancelling refresh attempt\|Invalid url for the spring server\|Port ${PORT} was already in use" "$LOG_FILE" 2>/dev/null; then + echo "error: startup failed. See ${LOG_FILE}" >&2 + tail -n 80 "$LOG_FILE" >&2 || true + return 1 + fi + echo " ... still starting (${elapsed}s / ${timeout}s)" + sleep 2 + elapsed=$((elapsed + 2)) + done + echo "error: external-stage did not become ready within ${timeout}s on port ${PORT}" >&2 + tail -n 80 "$LOG_FILE" >&2 || true + return 1 +} + +http_ok() { + local url="$1" + local code + if command -v curl >/dev/null 2>&1; then + code="$(curl -sS -o /dev/null -w "%{http_code}" --connect-timeout 2 --max-time 3 "$url" 2>/dev/null || true)" + [[ -n "$code" ]] || code="000" + printf '%s' "$code" + return 0 + fi + if command -v python3 >/dev/null 2>&1; then + python3 -c 'import sys,urllib.request +try: + urllib.request.urlopen(sys.argv[1], timeout=3) + print("200") +except Exception: + print("000")' "$url" + return 0 + fi + if command -v python >/dev/null 2>&1; then + python -c 'import sys,urllib.request +try: + urllib.request.urlopen(sys.argv[1], timeout=3) + print("200") +except Exception: + print("000")' "$url" + return 0 + fi + echo "error: install curl or python3 for smoke checks" >&2 + printf '%s' "000" +} + +cmd_stop() { + ensure_dirs + if ! is_running; then + rm -f "$PID_FILE" + echo "external-stage is not running" + return 0 + fi + local pid + pid="$(cat "$PID_FILE")" + echo "==> stopping external-stage (${pid}) on port ${PORT}" + kill "$pid" 2>/dev/null || true + local i + for i in 1 2 3 4 5 6 7 8 9 10; do + kill -0 "$pid" 2>/dev/null || break + sleep 1 + done + if kill -0 "$pid" 2>/dev/null; then + kill -9 "$pid" 2>/dev/null || true + fi + rm -f "$PID_FILE" + echo "stopped." +} + +cmd_smoke() { + ensure_dirs + local timeout="${1:-60}" + local elapsed=0 + echo "==> waiting for external-stage (up to ${timeout}s)" + while [[ "$elapsed" -lt "$timeout" ]]; do + if [[ -f "$PID_FILE" ]] && ! is_running; then + echo "error: process exited. See ${LOG_FILE}" >&2 + tail -n 40 "$LOG_FILE" >&2 || true + return 1 + fi + local url code + for url in \ + "http://127.0.0.1:${PORT}${CONTEXT}/actuator/health" \ + "http://127.0.0.1:${PORT}/actuator/health" + do + code="$(http_ok "$url")" + if [[ "$code" == "200" ]]; then + echo "healthy ${url}" + echo "smoke ok" + return 0 + fi + done + if command -v ss >/dev/null 2>&1 && ss -ltn 2>/dev/null | grep -q ":${PORT} "; then + echo "listening on port ${PORT} (Vert.x HTTP; actuator optional)" + echo "smoke ok" + return 0 + fi + if command -v netstat >/dev/null 2>&1 && netstat -ano 2>/dev/null | grep -E ":${PORT} .*LISTENING" >/dev/null; then + echo "listening on port ${PORT} (Vert.x HTTP; actuator optional)" + echo "smoke ok" + return 0 + fi + if grep -q "${STARTED}" "$LOG_FILE" 2>/dev/null; then + echo "started marker in log" + echo "smoke ok" + return 0 + fi + sleep 2 + elapsed=$((elapsed + 2)) + done + echo "error: not healthy. See ${LOG_FILE}" >&2 + tail -n 80 "$LOG_FILE" >&2 || true + return 1 +} + +cmd_all() { + echo "==> all: init + test + start + smoke" + cmd_init + cmd_test + cmd_start + cmd_smoke +} + +main() { + local cmd="${1:-}" + shift || true + case "$cmd" in + -h|--help|help) usage 0 ;; + init) cmd_init ;; + test) cmd_test ;; + start) cmd_start ;; + stop) cmd_stop ;; + smoke) cmd_smoke "${1:-60}" ;; + all) cmd_all ;; + "") usage 1 ;; + *) echo "error: unknown command '$cmd'" >&2; usage 1 ;; + esac +} + +main "$@" diff --git a/registration-processor/registration-processor-external-stage/src/main/java/io/mosip/registration/processor/status/entity/BasePacketEntity.java b/registration-processor/registration-processor-external-stage/src/main/java/io/mosip/registration/processor/status/entity/BasePacketEntity.java new file mode 100644 index 0000000000..6dcb3df765 --- /dev/null +++ b/registration-processor/registration-processor-external-stage/src/main/java/io/mosip/registration/processor/status/entity/BasePacketEntity.java @@ -0,0 +1,32 @@ +package io.mosip.registration.processor.status.entity; + +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.MappedSuperclass; + +/** + * Shadows MOSIP status-service-impl {@code BasePacketEntity}. Hibernate 7 rejects + * {@code @MappedSuperclass} plus {@code @Inheritance}; Boot 4.1.1 uses Hibernate 7. + * Fat-JAR {@code BOOT-INF/classes} is loaded before nested MOSIP jars. + * + * @param embedded id type + */ +@MappedSuperclass +public class BasePacketEntity { + + @EmbeddedId + protected C id; + + /** + * @return composite id + */ + public C getId() { + return id; + } + + /** + * @param id composite id + */ + public void setId(C id) { + this.id = id; + } +} diff --git a/registration-processor/registration-processor-external-stage/src/main/java/io/mosip/registration/processor/status/entity/BaseRegistrationEntity.java b/registration-processor/registration-processor-external-stage/src/main/java/io/mosip/registration/processor/status/entity/BaseRegistrationEntity.java new file mode 100644 index 0000000000..deb8c35ad4 --- /dev/null +++ b/registration-processor/registration-processor-external-stage/src/main/java/io/mosip/registration/processor/status/entity/BaseRegistrationEntity.java @@ -0,0 +1,31 @@ +package io.mosip.registration.processor.status.entity; + +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.MappedSuperclass; + +/** + * Shadows MOSIP status-service-impl {@code BaseRegistrationEntity}. Same Hibernate 7 + * {@code @MappedSuperclass} / {@code @Inheritance} restriction as {@link BasePacketEntity}. + * + * @param embedded id type + */ +@MappedSuperclass +public class BaseRegistrationEntity { + + @EmbeddedId + protected C id; + + /** + * @return composite id + */ + public C getId() { + return id; + } + + /** + * @param id composite id + */ + public void setId(C id) { + this.id = id; + } +} diff --git a/registration-processor/registration-processor-external-stage/src/main/java/io/mosip/registrationprocessor/externalstage/ExternalStageApplication.java b/registration-processor/registration-processor-external-stage/src/main/java/io/mosip/registrationprocessor/externalstage/ExternalStageApplication.java index 33e3446d91..795817632f 100644 --- a/registration-processor/registration-processor-external-stage/src/main/java/io/mosip/registrationprocessor/externalstage/ExternalStageApplication.java +++ b/registration-processor/registration-processor-external-stage/src/main/java/io/mosip/registrationprocessor/externalstage/ExternalStageApplication.java @@ -1,6 +1,21 @@ package io.mosip.registrationprocessor.externalstage; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.io.support.ResourcePropertySource; +import org.springframework.core.type.filter.RegexPatternTypeFilter; import io.mosip.registration.processor.core.config.reader.ConfigPropertyReader; import io.mosip.registrationprocessor.externalstage.stage.ExternalStage; @@ -11,6 +26,14 @@ */ public class ExternalStageApplication { + private static final String LOCAL = "local"; + + private static final String DEFAULT_AUTH_ADAPTER = "io.mosip.kernel.auth.defaultadapter"; + + /** Vert.x config-server store under core.config; skipped for profile {@code local}. */ + private static final Pattern CONFIG_SERVER_LOADER = Pattern + .compile("io\\.mosip\\.registration\\.processor\\.core\\.config\\.configserverloader\\..*"); + /** * Boots Spring, then deploys {@link ExternalStage}. * @@ -18,14 +41,138 @@ public class ExternalStageApplication { */ public static void main(String[] args) { AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext(); - configApplicationContext.scan("io.mosip.registration.processor.core.config", - ConfigPropertyReader.getConfig("mosip.auth.adapter.impl.basepackage"), + applyLocalProfile(configApplicationContext); + try { + scanStage(configApplicationContext); + skipVertxConfigServerStore(configApplicationContext); + configApplicationContext.refresh(); + ExternalStage externalStage = (ExternalStage) configApplicationContext.getBean(ExternalStage.class); + externalStage.deployVerticle(); + System.out.println("Started ExternalStageApplication"); + } catch (Exception e) { + System.out.println("EXTERNAL_STAGE_STARTUP_FAILED"); + System.err.println("EXTERNAL_STAGE_STARTUP_FAILED"); + Throwable root = e; + while (root.getCause() != null && root.getCause() != root) { + root = root.getCause(); + } + System.err.println(root.toString()); + e.printStackTrace(); + System.exit(1); + } + } + + /** + * Loads {@code application-local.properties} when {@code spring.profiles.active=local}. + * Vert.x stages do not use {@code SpringApplication}, so Boot would otherwise skip that file. + * + * @param ctx annotation config context before {@code scan} + */ + static void applyLocalProfile(AnnotationConfigApplicationContext ctx) { + if (!localProfile()) { + return; + } + ctx.getEnvironment().setActiveProfiles(LOCAL); + try { + ctx.getEnvironment().getPropertySources() + .addFirst(new ResourcePropertySource("application-local", "classpath:application-local.properties")); + installLocalHazelcastXml(ctx); + } catch (IOException e) { + throw new IllegalStateException("Failed to load application-local.properties", e); + } + } + + /** + * MOSIP {@code MosipVerticleManager#getEventBus} loads Hazelcast via + * {@code UrlXmlConfig}. {@code localhost} is not an absolute URI (see + * {@code URI is not absolute} on deploy). Profile {@code local} writes + * {@code hazelcast-local.xml} and sets {@code vertx.cluster.configuration} + * to its {@code file:} URI. + * + * @param ctx context after application-local was added + * @throws IOException if the XML cannot be copied + */ + static void installLocalHazelcastXml(AnnotationConfigApplicationContext ctx) throws IOException { + Path dest = Path.of(System.getProperty("user.dir"), ".local", "hazelcast-local.xml"); + Files.createDirectories(dest.getParent()); + try (InputStream in = ExternalStageApplication.class.getResourceAsStream("/hazelcast-local.xml")) { + if (in == null) { + throw new IllegalStateException("classpath hazelcast-local.xml is missing"); + } + Files.copy(in, dest, StandardCopyOption.REPLACE_EXISTING); + } + Map props = new HashMap<>(); + props.put("vertx.cluster.configuration", dest.toUri().toString()); + ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("local-hazelcast", props)); + } + + static boolean localProfile() { + return LOCAL.equals(System.getProperty("spring.profiles.active", "")); + } + + /** + * {@code CoreConfigBean} is still scanned (TokenValidator, MosipRouter, event bus). + * Its {@code getPropertiesFromConfigServer} @Bean talks to Vert.x + * {@code SpringConfigServerStore} using bootstrap {@code spring.cloud.config.uri=localhost} + * (no scheme). That URL is invalid; the exception is logged and JDBC keys never load. + * {@code KernelConfig#getCbeffUtil} constructs {@code CbeffImpl}, whose + * {@code @PostConstruct} opens {@code mosip.kernel.xsdstorage-uri} + xsd file + * (config-server). External-stage does not use CBEFF. Profile {@code local} + * drops both beans before refresh. + * + * @param ctx context after {@link #scanStage} + */ + static void skipVertxConfigServerStore(AnnotationConfigApplicationContext ctx) { + if (!localProfile()) { + return; + } + ctx.addBeanFactoryPostProcessor(beanFactory -> { + if (!(beanFactory instanceof BeanDefinitionRegistry registry)) { + return; + } + for (String name : beanFactory.getBeanDefinitionNames()) { + BeanDefinition bd = beanFactory.getBeanDefinition(name); + String factory = bd.getFactoryMethodName(); + if ("getPropertiesFromConfigServer".equals(factory) || "getCbeffUtil".equals(factory)) { + registry.removeBeanDefinition(name); + } + } + }); + } + + /** + * Auth adapter package. Profile {@code local} never calls {@link ConfigPropertyReader} + * (that boots Vert.x SpringConfigServerStore against bootstrap {@code localhost}). + * + * @return scan base package for kernel-auth-adapter + */ + static String authAdapterPackage() { + String fromSys = System.getProperty("mosip.auth.adapter.impl.basepackage"); + if (fromSys != null && !fromSys.isBlank()) { + return fromSys; + } + if (localProfile()) { + return DEFAULT_AUTH_ADAPTER; + } + return ConfigPropertyReader.getConfig("mosip.auth.adapter.impl.basepackage"); + } + + static void scanStage(AnnotationConfigApplicationContext ctx) { + String adapter = authAdapterPackage(); + if (localProfile()) { + ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx); + scanner.addExcludeFilter(new RegexPatternTypeFilter(CONFIG_SERVER_LOADER)); + scanner.scan("io.mosip.registration.processor.core.config", adapter, + "io.mosip.registrationprocessor.externalstage.config", + "io.mosip.registration.processor.status.config", + "io.mosip.registration.processor.core.kernel.beans", + "io.mosip.registration.processor.rest.client.config"); + return; + } + ctx.scan("io.mosip.registration.processor.core.config", adapter, "io.mosip.registrationprocessor.externalstage.config", "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.core.kernel.beans", "io.mosip.registration.processor.rest.client.config"); - configApplicationContext.refresh(); - ExternalStage externalStage = (ExternalStage) configApplicationContext.getBean(ExternalStage.class); - externalStage.deployVerticle(); } -} \ No newline at end of file +} diff --git a/registration-processor/registration-processor-external-stage/src/main/java/io/mosip/registrationprocessor/externalstage/stage/ExternalStage.java b/registration-processor/registration-processor-external-stage/src/main/java/io/mosip/registrationprocessor/externalstage/stage/ExternalStage.java index f4be21e9da..050f999322 100644 --- a/registration-processor/registration-processor-external-stage/src/main/java/io/mosip/registrationprocessor/externalstage/stage/ExternalStage.java +++ b/registration-processor/registration-processor-external-stage/src/main/java/io/mosip/registrationprocessor/externalstage/stage/ExternalStage.java @@ -3,6 +3,7 @@ import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CompletableFuture; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -15,6 +16,7 @@ import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; import io.mosip.registration.processor.core.abstractverticle.MosipRouter; import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.eventbus.MosipEventBusFactory; import io.mosip.registration.processor.core.code.ApiName; import io.mosip.registration.processor.core.code.EventId; import io.mosip.registration.processor.core.code.EventName; @@ -39,6 +41,10 @@ import io.mosip.registration.processor.status.dto.RegistrationStatusDto; import io.mosip.registration.processor.status.service.RegistrationStatusService; import io.mosip.registrationprocessor.externalstage.entity.MessageRequestDTO; +import io.vertx.core.Vertx; +import io.vertx.core.VertxOptions; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.handler.BodyHandler; /** * Vert.x external stage: consumes {@code EXTERNAL_STAGE_BUS_IN}, POSTs registration @@ -53,6 +59,8 @@ public class ExternalStage extends MosipVerticleAPIManager { private static Logger regProcLogger = RegProcessorLogger.getLogger(ExternalStage.class); private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.external."; + + private static final String LOCAL = "local"; /** request id */ private static final String ID = "io.mosip.registrationprocessor"; @@ -68,6 +76,10 @@ public class ExternalStage extends MosipVerticleAPIManager { @Value("${server.port}") private String port; + /** HTTP path used by run-local smoke ({@code .../actuator/health}). */ + @Value("${server.servlet.path:/registrationprocessor/v1/external}") + private String servletPath; + /** worker pool size. */ @Value("${worker.pool.size}") private Integer workerPoolSize; @@ -102,27 +114,86 @@ public class ExternalStage extends MosipVerticleAPIManager { @Autowired RegistrationExceptionMapperUtil registrationStatusMapperUtil; + @Autowired + private MosipEventBusFactory mosipEventBusFactory; + /** * Deploys this verticle, then consumes {@code EXTERNAL_STAGE_BUS_IN} and sends * {@code EXTERNAL_STAGE_BUS_OUT}. */ public void deployVerticle() { + if (LOCAL.equals(System.getProperty("spring.profiles.active", ""))) { + deployLocalVerticle(); + return; + } this.mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); this.consumeAndSend(mosipEventBus, MessageBusAddress.EXTERNAL_STAGE_BUS_IN, MessageBusAddress.EXTERNAL_STAGE_BUS_OUT, messageExpiryTimeLimit); } + /** + * Profile {@code local} skips MOSIP {@code getEventBus} (Hazelcast cluster + * manager from {@code vertx-hazelcast} needs {@code MembershipListener} in + * {@code com.hazelcast.core}, which current Hazelcast no longer has). In-process + * Vert.x still binds {@link #start()} on {@code server.port}. + */ + void deployLocalVerticle() { + int workers = workerPoolSize != null ? workerPoolSize : 10; + Vertx vertx = Vertx.vertx(new VertxOptions().setWorkerPoolSize(workers)); + CompletableFuture deployed = new CompletableFuture<>(); + vertx.deployVerticle(this, ar -> { + if (ar.succeeded()) { + deployed.complete(ar.result()); + } else { + deployed.completeExceptionally(ar.cause()); + } + }); + try { + deployed.get(); + this.mosipEventBus = mosipEventBusFactory.getEventBus(vertx, "vertx", this.getClass().getSimpleName()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Local Vert.x deploy interrupted", e); + } catch (Exception e) { + throw new IllegalStateException("Local Vert.x deploy failed", e); + } + this.consumeAndSend(this.mosipEventBus, MessageBusAddress.EXTERNAL_STAGE_BUS_IN, + MessageBusAddress.EXTERNAL_STAGE_BUS_OUT, messageExpiryTimeLimit); + } + /** * Registers HTTP routes for the stage and starts the Vert.x HTTP server. */ @Override public void start() { - + if (LOCAL.equals(System.getProperty("spring.profiles.active", ""))) { + startLocalHttp(); + return; + } router.setRoute( this.postUrl(getVertx(), MessageBusAddress.EXTERNAL_STAGE_BUS_IN, MessageBusAddress.EXTERNAL_STAGE_BUS_OUT)); this.createServer(router.getRouter(), Integer.parseInt(port)); } + /** + * Profile {@code local} skips {@code postUrl}. MOSIP {@code VertxWebTracingLocal} + * needs Brave 5 {@code brave.http.HttpServerAdapter}; Boot 4 ships Brave 6, + * which dropped that class. Binds the same port and a JSON health GET for + * run-local smoke. + */ + void startLocalHttp() { + Router localRouter = Router.router(getVertx()); + localRouter.route().handler(BodyHandler.create()); + String path = servletPath == null || servletPath.isBlank() ? "/registrationprocessor/v1/external" : servletPath; + localRouter.get(path + "/actuator/health").handler(ctx -> ctx.response() + .putHeader("content-type", "application/json") + .end("{\"status\":\"UP\"}")); + if (router != null) { + router.setRoute(localRouter); + } + this.createServer(localRouter, Integer.parseInt(port)); + } + /** * POSTs the registration id to EIS, updates status, and sets {@code isValid}. * diff --git a/registration-processor/registration-processor-external-stage/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java b/registration-processor/registration-processor-external-stage/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java new file mode 100644 index 0000000000..1f9ada2e4a --- /dev/null +++ b/registration-processor/registration-processor-external-stage/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java @@ -0,0 +1,16 @@ +package org.springframework.boot.web.client; + +/** + * Boot 4 no longer ships this type. MOSIP {@code RegistrationStatusBeanConfig#getRestTemplateBuilder} + * still does {@code new RestTemplateBuilder()}. + */ +public class RestTemplateBuilder { + + /** + * Matches the Boot 3 constructor invoked by MOSIP status-service-impl. + * + * @param customizers unused + */ + public RestTemplateBuilder(RestTemplateCustomizer... customizers) { + } +} diff --git a/registration-processor/registration-processor-external-stage/src/main/java/org/springframework/boot/web/client/RestTemplateCustomizer.java b/registration-processor/registration-processor-external-stage/src/main/java/org/springframework/boot/web/client/RestTemplateCustomizer.java new file mode 100644 index 0000000000..c2d872c9d2 --- /dev/null +++ b/registration-processor/registration-processor-external-stage/src/main/java/org/springframework/boot/web/client/RestTemplateCustomizer.java @@ -0,0 +1,16 @@ +package org.springframework.boot.web.client; + +/** + * Boot 4 no longer ships this type. MOSIP {@code RegistrationStatusBeanConfig} + * still constructs it ({@code new RestTemplateBuilder()}). + */ +@FunctionalInterface +public interface RestTemplateCustomizer { + + /** + * Customize a RestTemplate. Unused by the MOSIP bean factory method. + * + * @param restTemplate template to customize + */ + void customize(Object restTemplate); +} diff --git a/registration-processor/registration-processor-external-stage/src/main/resources/application-local.properties b/registration-processor/registration-processor-external-stage/src/main/resources/application-local.properties new file mode 100644 index 0000000000..00a535eeb0 --- /dev/null +++ b/registration-processor/registration-processor-external-stage/src/main/resources/application-local.properties @@ -0,0 +1,80 @@ +# Local profile for registration-processor-external-stage (run-local.sh / run-local.bat). +# Activate with: -Dspring.profiles.active=local +# Cluster Docker does not set this profile; it uses bootstrap + config-server env. +# Vert.x stage still needs Kafka / status DB / EIS for packet processing. +# init and test work without that stack. start/smoke only prove the JVM comes up +# if MOSIP registration-processor SNAPSHOTs can bind with these stubs. + +server.port=8095 +eventbus.port=5736 +server.servlet.path=/registrationprocessor/v1/external +worker.pool.size=10 +mosip.regproc.external.message.expiry-time-limit=1500 +spring.application.name=registration-processor +# MosipVerticleAPIManager @Value — unresolved leaves the literal ${...} which is not a Boolean +registration.processor.signature.isEnabled=false +mosip.registration.processor.digital.signature.id=mosip.digital.signature +mosip.registration.processor.datetime.pattern=yyyy-MM-dd'T'HH:mm:ss.SSS'Z' +mosip.registration.processor.application.version=1.0 +mosip.utc-datetime-pattern=yyyy-MM-dd'T'HH:mm:ss.SSS'Z' +# RegistrationExternalStatusUtility / RegistrationStatusServiceImpl (ints and SpEL lists) +registration.processor.max.retry=5 +registration.processor.reprocess.elapse.time=21600 +registration.processor.main-processes=NEW,UPDATE,LOST,RES_UPDATE,ACTIVATE,DEACTIVATE +registration.processor.sub-processes=BIOMETRIC_CORRECTION +mosip.regproc.registration.status.service.disable-audit=true + +spring.cloud.config.enabled=false +spring.cloud.config.fail-fast=false +spring.config.import=optional:configserver: +health.config.enabled=false +management.endpoints.web.exposure.include=info,health,refresh +spring.info.git.location=classpath:service-git.properties + +mosip.auth.adapter.impl.basepackage=io.mosip.kernel.auth.defaultadapter +auth.server.admin.offline.token.validate=true +spring.security.method-security.enabled=false +mosip.global.end-points=/** +mosip.service.end-points=/** +# TokenHelper: @Value("#{${mosip.kernel.auth.appids.realm.map}}") — must be a SpEL map, not empty +mosip.kernel.auth.appids.realm.map={prereg:'preregistration',ida:'mosip',registrationclient:'mosip',regproc:'mosip',partner:'mosip',resident:'mosip',admin:'mosip',crereq:'mosip',creser:'mosip',datsha:'mosip'} +mosip.iam.adapter.clientid=mosip-regproc-client +mosip.iam.adapter.clientsecret=local +mosip.iam.adapter.appid=regproc +token.request.id=io.mosip.registration.processor +token.request.appid=regproc +token.request.version=1.0 +token.request.clientId=mosip-regproc-client +token.request.secretKey=local +token.request.issuerUrl=http://127.0.0.1:8080/auth/realms/mosip + +# UrlXmlConfig needs an absolute URI; applyLocalProfile overwrites this with file: .local/hazelcast-local.xml +vertx.cluster.configuration=localhost +registration.processor.zone=secure +mosip.regproc.eventbus.type=vertx +mosip.regproc.external.eventbus.port=5736 +mosip.regproc.external.server.port=8095 + +# HibernateDaoConfig (kernel-dataaccess-hibernate) reads these keys, not spring.datasource.* +javax.persistence.jdbc.driver=org.h2.Driver +javax.persistence.jdbc.url=jdbc:h2:mem:regproc;DB_CLOSE_DELAY=-1;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;INIT=CREATE SCHEMA IF NOT EXISTS regprc +javax.persistence.jdbc.user=sa +javax.persistence.jdbc.password= +javax.persistence.jdbc.schema=regprc +hibernate.hbm2ddl.auto=update +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=false +hibernate.format_sql=false +hibernate.jdbc.lob.non_contextual_creation=true + +mosip.regproc.external.eventbus.kafka.commit.type=single +mosip.regproc.external.eventbus.kafka.max.poll.records=100 +mosip.regproc.external.eventbus.kafka.poll.frequency=100 +mosip.regproc.external.eventbus.kafka.group.id=external-stage +mosip.regproc.eventbus.kafka.commit.type=${mosip.regproc.external.eventbus.kafka.commit.type} +mosip.regproc.eventbus.kafka.max.poll.records=${mosip.regproc.external.eventbus.kafka.max.poll.records} +mosip.regproc.eventbus.kafka.poll.frequency=${mosip.regproc.external.eventbus.kafka.poll.frequency} +mosip.regproc.eventbus.kafka.group.id=${mosip.regproc.external.eventbus.kafka.group.id} + +# EIS stub (start EIS with its own run-local first if you exercise the HTTP hop) +eisservice=http://127.0.0.1:8201/registrationprocessor/v1/eis/registration-processor/external-integration-service/v1.0 diff --git a/registration-processor/registration-processor-external-stage/src/main/resources/hazelcast-local.xml b/registration-processor/registration-processor-external-stage/src/main/resources/hazelcast-local.xml new file mode 100644 index 0000000000..a5d2d6357c --- /dev/null +++ b/registration-processor/registration-processor-external-stage/src/main/resources/hazelcast-local.xml @@ -0,0 +1,16 @@ + + + external-stage-local + + + + + + 127.0.0.1 + + + + diff --git a/registration-processor/registration-processor-external-stage/src/test/java/io/mosip/registrationprocessor/externalstage/ExternalStageApplicationTests.java b/registration-processor/registration-processor-external-stage/src/test/java/io/mosip/registrationprocessor/externalstage/ExternalStageApplicationTests.java index 9ee5455a42..f4c83cf4a6 100644 --- a/registration-processor/registration-processor-external-stage/src/test/java/io/mosip/registrationprocessor/externalstage/ExternalStageApplicationTests.java +++ b/registration-processor/registration-processor-external-stage/src/test/java/io/mosip/registrationprocessor/externalstage/ExternalStageApplicationTests.java @@ -1,9 +1,114 @@ package io.mosip.registrationprocessor.externalstage; -/*import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import java.util.Arrays; -public class ExternalStageApplicationTests extends TestCase -{ - -}*/ +import org.junit.After; +import org.junit.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import io.mosip.registration.processor.status.entity.BasePacketEntity; +import io.mosip.registration.processor.status.entity.BaseRegistrationEntity; +import jakarta.persistence.Inheritance; +import jakarta.persistence.MappedSuperclass; + +/** + * {@link ExternalStageApplication#applyLocalProfile} for run-local (profile {@code local}). + */ +public class ExternalStageApplicationTests { + + @After + public void clearProfile() { + System.clearProperty("spring.profiles.active"); + System.clearProperty("mosip.auth.adapter.impl.basepackage"); + } + + @Test + public void applyLocalProfileLoadsClasspathFile() { + System.setProperty("spring.profiles.active", "local"); + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + try { + ExternalStageApplication.applyLocalProfile(ctx); + assertTrue(Arrays.asList(ctx.getEnvironment().getActiveProfiles()).contains("local")); + assertEquals("8095", ctx.getEnvironment().getProperty("server.port")); + assertEquals("false", ctx.getEnvironment().getProperty("spring.cloud.config.enabled")); + assertTrue(ctx.getEnvironment().getProperty("mosip.kernel.auth.appids.realm.map").contains("regproc")); + assertEquals("false", ctx.getEnvironment().getProperty("registration.processor.signature.isEnabled")); + assertEquals("5", ctx.getEnvironment().getProperty("registration.processor.max.retry")); + assertTrue(ctx.getEnvironment().getProperty("vertx.cluster.configuration").startsWith("file:")); + } finally { + ctx.close(); + } + } + + @Test + public void applyLocalProfileNoOpWhenNotLocal() { + System.clearProperty("spring.profiles.active"); + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + try { + ExternalStageApplication.applyLocalProfile(ctx); + assertFalse(Arrays.asList(ctx.getEnvironment().getActiveProfiles()).contains("local")); + } finally { + ctx.close(); + } + } + + @Test + public void authAdapterPackageUsesSystemPropertyWithoutConfigServer() { + System.setProperty("spring.profiles.active", "local"); + System.setProperty("mosip.auth.adapter.impl.basepackage", "io.mosip.kernel.auth.defaultadapter"); + assertEquals("io.mosip.kernel.auth.defaultadapter", ExternalStageApplication.authAdapterPackage()); + } + + @Test + public void authAdapterPackageDefaultsWhenLocalAndUnset() { + System.setProperty("spring.profiles.active", "local"); + System.clearProperty("mosip.auth.adapter.impl.basepackage"); + assertEquals("io.mosip.kernel.auth.defaultadapter", ExternalStageApplication.authAdapterPackage()); + } + + @Test + public void restTemplateBuilderMatchesStatusConfigConstructor() { + assertNotNull(new org.springframework.boot.web.client.RestTemplateBuilder()); + } + + @Test + public void skipVertxConfigServerStoreRegistersPostProcessorWhenLocal() { + System.setProperty("spring.profiles.active", "local"); + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + try { + ExternalStageApplication.applyLocalProfile(ctx); + ExternalStageApplication.skipVertxConfigServerStore(ctx); + assertEquals(1, ctx.getBeanFactoryPostProcessors().size()); + assertEquals("jdbc:h2:mem:regproc;DB_CLOSE_DELAY=-1;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;INIT=CREATE SCHEMA IF NOT EXISTS regprc", + ctx.getEnvironment().getProperty("javax.persistence.jdbc.url")); + } finally { + ctx.close(); + } + } + + @Test + public void skipVertxConfigServerStoreNoOpWhenNotLocal() { + System.clearProperty("spring.profiles.active"); + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + try { + ExternalStageApplication.skipVertxConfigServerStore(ctx); + assertEquals(0, ctx.getBeanFactoryPostProcessors().size()); + } finally { + ctx.close(); + } + } + + @Test + public void hibernate7MappedSuperclassShimsOmitInheritance() { + assertNotNull(BasePacketEntity.class.getAnnotation(MappedSuperclass.class)); + assertNull(BasePacketEntity.class.getAnnotation(Inheritance.class)); + assertNotNull(BaseRegistrationEntity.class.getAnnotation(MappedSuperclass.class)); + assertNull(BaseRegistrationEntity.class.getAnnotation(Inheritance.class)); + } +} diff --git a/registration-processor/registration-processor-external-stage/src/test/java/io/mosip/registrationprocessor/externalstage/stage/ExternalStageTest.java b/registration-processor/registration-processor-external-stage/src/test/java/io/mosip/registrationprocessor/externalstage/stage/ExternalStageTest.java index f0c3e23074..90a2cc9ac3 100644 --- a/registration-processor/registration-processor-external-stage/src/test/java/io/mosip/registrationprocessor/externalstage/stage/ExternalStageTest.java +++ b/registration-processor/registration-processor-external-stage/src/test/java/io/mosip/registrationprocessor/externalstage/stage/ExternalStageTest.java @@ -23,6 +23,7 @@ import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.logger.LogDescription; import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.eventbus.MosipEventBusFactory; import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; @@ -60,6 +61,9 @@ public void createServer(Router router, int port) { public void testDeployVerticle() { externalStage.deployVerticle(); } + @Mock + private MosipEventBusFactory mosipEventBusFactory; + @Mock private AuditLogRequestBuilder auditLogRequestBuilder; @@ -104,6 +108,19 @@ public void testStart() { externalStage.start(); } + + @Test + public void testStartLocalSkipsBravePostUrl() { + System.setProperty("spring.profiles.active", "local"); + Vertx vertx = Vertx.vertx(); + try { + ReflectionTestUtils.setField(externalStage, "vertx", vertx); + externalStage.start(); + } finally { + System.clearProperty("spring.profiles.active"); + vertx.close(); + } + } @Test public void testisValidExternalSuccess() throws ApisResourceAccessException {