From ce01105dfff26ff05b51e11b146c8c24f8c01dbb Mon Sep 17 00:00:00 2001 From: Vanitha S <116701245+vanitha1822@users.noreply.github.com> Date: Fri, 27 Feb 2026 14:07:03 +0530 Subject: [PATCH 1/3] Fix the issue in Downloading Reports (#117) * fix: column datatype mismatch issue * fix: report download issue in AMM-2017 --- .../service/report/CRMReportServiceImpl.java | 107 ++++++++---------- 1 file changed, 50 insertions(+), 57 deletions(-) diff --git a/src/main/java/com/iemr/inventory/service/report/CRMReportServiceImpl.java b/src/main/java/com/iemr/inventory/service/report/CRMReportServiceImpl.java index 714043b7..526c63e2 100644 --- a/src/main/java/com/iemr/inventory/service/report/CRMReportServiceImpl.java +++ b/src/main/java/com/iemr/inventory/service/report/CRMReportServiceImpl.java @@ -223,31 +223,31 @@ public String getDailyStockDetailsReport(ItemStockEntryReport entryReport) { openingStock = ((Number) objects[10]).longValue(); } Long adjustedQuantity_FromDate = 0L; - if (objects[11] != null) { - adjustedQuantity_FromDate = ((Number) objects[11]).longValue(); + if (objects[15] != null) { + adjustedQuantity_FromDate = ((Number) objects[15]).longValue(); } Long quantityDispanced = 0L; - if (objects[12] != null) { - quantityDispanced = ((Number) objects[12]).longValue(); + if (objects[11] != null) { + quantityDispanced = ((Number) objects[11]).longValue(); } - String itemName = (String) objects[13]; - String facilityName = (String) objects[14]; - String itemCategoryName = (String) objects[15]; + String itemName = (String) objects[12]; + String facilityName = (String) objects[13]; + String itemCategoryName = (String) objects[14]; Long adjustedQuantity_ToDate = 0L; - if (objects[16] != null) { - adjustedQuantity_ToDate = ((Number) objects[16]).longValue(); + if (objects[15] != null) { + adjustedQuantity_ToDate = ((Number) objects[15]).longValue(); } Long adjustedQuantity_ToDate_Receipt = 0L; - if (objects[17] != null) { - adjustedQuantity_ToDate_Receipt = ((Number) objects[17]).longValue(); + if (objects[16] != null) { + adjustedQuantity_ToDate_Receipt = ((Number) objects[16]).longValue(); } Long adjustedQuantity_ToDate_Issue = 0L; - if (objects[18] != null) { - adjustedQuantity_ToDate_Issue = ((Number) objects[18]).longValue(); + if (objects[17] != null) { + adjustedQuantity_ToDate_Issue = ((Number) objects[17]).longValue(); } Long ClosingStock = 0L; - if (objects[19] != null) { - ClosingStock = ((Number) objects[19]).longValue(); + if (objects[18] != null) { + ClosingStock = ((Number) objects[18]).longValue(); } @@ -421,31 +421,31 @@ public String getMonthlyReport(ItemStockEntryReport entryReport) { openingStock = ((Number) objects[10]).longValue(); } Long adjustedQuantity_FromDate = 0L; - if (objects[11] != null) { - adjustedQuantity_FromDate = ((Number) objects[11]).longValue(); + if (objects[15] != null) { + adjustedQuantity_FromDate = ((Number) objects[15]).longValue(); } Long quantityDispanced = 0L; - if (objects[12] != null) { - quantityDispanced = ((Number) objects[12]).longValue(); + if (objects[11] != null) { + quantityDispanced = ((Number) objects[11]).longValue(); } - String itemName = (String) objects[13]; - String facilityName = (String) objects[14]; - String itemCategoryName = (String) objects[15]; + String itemName = (String) objects[12]; + String facilityName = (String) objects[13]; + String itemCategoryName = (String) objects[14]; Long adjustedQuantity_ToDate = 0L; - if (objects[16] != null) { - adjustedQuantity_ToDate = ((Number) objects[16]).longValue(); + if (objects[15] != null) { + adjustedQuantity_ToDate = ((Number) objects[15]).longValue(); } Long adjustedQuantity_ToDate_Receipt = 0L; - if (objects[17] != null) { - adjustedQuantity_ToDate_Receipt = ((Number) objects[17]).longValue(); + if (objects[16] != null) { + adjustedQuantity_ToDate_Receipt = ((Number) objects[16]).longValue(); } Long adjustedQuantity_ToDate_Issue = 0L; - if (objects[18] != null) { - adjustedQuantity_ToDate_Issue = ((Number) objects[18]).longValue(); + if (objects[17] != null) { + adjustedQuantity_ToDate_Issue = ((Number) objects[17]).longValue(); } Long ClosingStock = 0L; - if (objects[19] != null) { - ClosingStock = ((Number) objects[19]).longValue(); + if (objects[18] != null) { + ClosingStock = ((Number) objects[18]).longValue(); } // Long actualOpening = openingStock + adjustedQuantity_FromDate; Long actualOpening = openingStock; @@ -520,57 +520,50 @@ public String getYearlyReport(ItemStockEntryReport entryReport) { for (Object[] objects : reports) { if (objects != null && objects.length > 0) { - String batchNo = (String) objects[3]; + String batchNo = objects[3] != null ? objects[3].toString() : null; Long totalQuantityReceived = 0L; if (objects[4] != null) { - totalQuantityReceived = ((Number) objects[4]).longValue(); + totalQuantityReceived = Long.valueOf(objects[4].toString()); } Double unitCostPrice = 0.0; if (objects[5] != null) { - unitCostPrice = ((Number) objects[5]).doubleValue(); + unitCostPrice = Double.valueOf(objects[5].toString()); } Date expiryDate = (Date) objects[6]; Long openingStock = 0L; if (objects[10] != null) { - openingStock = ((Number) objects[10]).longValue(); + openingStock = Long.valueOf(objects[10].toString()); } Long adjustedQuantity_FromDate = 0L; - if (objects[11] != null) { - adjustedQuantity_FromDate = ((Number) objects[11]).longValue(); + if (objects[15] != null) { + adjustedQuantity_FromDate = Long.valueOf(objects[15].toString()); } Long quantityDispanced = 0L; - if (objects[12] != null) { - quantityDispanced = ((Number) objects[12]).longValue(); + if (objects[11] != null) { + quantityDispanced = Long.valueOf(objects[11].toString()); } - String itemName = (String) objects[13]; - String facilityName = (String) objects[14]; - String itemCategoryName = (String) objects[15]; + String itemName = objects[12] != null ? objects[12].toString() : null; + String facilityName = objects[13] != null ? objects[13].toString() : null; + String itemCategoryName = objects[14] != null ? objects[14].toString() : null; Long adjustedQuantity_ToDate = 0L; - if (objects[16] != null) { - adjustedQuantity_ToDate = ((Number) objects[16]).longValue(); + if (objects[15] != null) { + adjustedQuantity_ToDate = Long.valueOf(objects[15].toString()); } Long adjustedQuantity_ToDate_Receipt = 0L; - if (objects[17] != null) { - adjustedQuantity_ToDate_Receipt = ((Number) objects[17]).longValue(); + if (objects[16] != null) { + adjustedQuantity_ToDate_Receipt = Long.valueOf(objects[16].toString()); } Long adjustedQuantity_ToDate_Issue = 0L; - if (objects[18] != null) { - adjustedQuantity_ToDate_Issue = ((Number) objects[18]).longValue(); + if (objects[17] != null) { + adjustedQuantity_ToDate_Issue = Long.valueOf(objects[17].toString()); } Long ClosingStock = 0L; - if (objects[19] != null) { - ClosingStock = ((Number) objects[19]).longValue(); + if (objects[18] != null) { + ClosingStock = Long.valueOf(objects[18].toString()); } -// Long actualOpening = openingStock + adjustedQuantity_FromDate; Long actualOpening = openingStock; - Long actualDispensed = quantityDispanced;// - adjustedQuantity_ToDate; + Long actualDispensed = quantityDispanced; Long actualClosing = ClosingStock; -// if (actualOpening == 0 || actualOpening == null) { -// actualClosing = totalQuantityReceived - actualDispensed + adjustedQuantity_ToDate; -// } else { -// actualClosing = actualOpening - actualDispensed + adjustedQuantity_ToDate; -// totalQuantityReceived = 0L; -// } YearlyReport stockDetail = new YearlyReport(); stockDetail.setSlNo(slNo++); From 7fc1e8b4782f87ee5fedcf92cc707f3ca7e865ed Mon Sep 17 00:00:00 2001 From: KOPPIREDDY DURGA PRASAD <144464542+DurgaPrasad-54@users.noreply.github.com> Date: Thu, 12 Mar 2026 16:04:01 +0530 Subject: [PATCH 2/3] Cherry-pick health and version API enhancements to release-3.6.1 (#119) * feat(health,version): add health and version endpoints * fix(health): removed duplicates from healthservices * fix: The DEGRADED status was incorrectly returning HTTP 503 * fix(health): run checks concurrently, prevent thread starvation, and harden timeouts * fix(health): add proper @Deprecated metadata and javadoc for obsolete methods * fix(health): add proper @Deprecated metadata and javadoc for obsolete methods * refactor(health): remove obsolete deprecated health check methods * fix(health): mark timed-out components DOWN and make status maps thread-safe * fix(health): removed duplicates from health services * fix(health): harden advanced MySQL checks and throttle execution * fix(health): harden advanced MySQL checks and reflect DEGRADED status * fix(health): avoid nested executor deadlock in advanced MySQL checks * fix(health): scope PROCESSLIST lock-wait check to application DB user * fix(health): avoid blocking DB I/O under write lock and restore interrupt flag --- pom.xml | 26 + .../controller/health/HealthController.java | 86 +++ .../controller/version/VersionController.java | 68 +-- .../service/health/HealthService.java | 544 ++++++++++++++++++ .../utils/JwtUserIdValidationFilter.java | 4 +- 5 files changed, 694 insertions(+), 34 deletions(-) create mode 100644 src/main/java/com/iemr/inventory/controller/health/HealthController.java create mode 100644 src/main/java/com/iemr/inventory/service/health/HealthService.java diff --git a/pom.xml b/pom.xml index f23f68a5..adf80292 100644 --- a/pom.xml +++ b/pom.xml @@ -386,6 +386,32 @@ + + io.github.git-commit-id + git-commit-id-maven-plugin + 9.0.2 + + + get-the-git-infos + + revision + + initialize + + + + true + ${project.build.outputDirectory}/git.properties + + ^git.branch$ + ^git.commit.id.abbrev$ + ^git.build.version$ + ^git.build.time$ + + false + false + + org.springframework.boot spring-boot-maven-plugin diff --git a/src/main/java/com/iemr/inventory/controller/health/HealthController.java b/src/main/java/com/iemr/inventory/controller/health/HealthController.java new file mode 100644 index 00000000..59fb160b --- /dev/null +++ b/src/main/java/com/iemr/inventory/controller/health/HealthController.java @@ -0,0 +1,86 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + +package com.iemr.inventory.controller.health; + +import java.time.Instant; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.iemr.inventory.service.health.HealthService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; + +@RestController +@RequestMapping("/health") +@Tag(name = "Health Check", description = "APIs for checking infrastructure health status") +public class HealthController { + + private static final Logger logger = LoggerFactory.getLogger(HealthController.class); + + private final HealthService healthService; + + public HealthController(HealthService healthService) { + this.healthService = healthService; + } + + @GetMapping + @Operation(summary = "Check infrastructure health", + description = "Returns the health status of MySQL, Redis, and other configured services") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "Services are UP or DEGRADED (operational with warnings)"), + @ApiResponse(responseCode = "503", description = "One or more critical services are DOWN") + }) + public ResponseEntity> checkHealth() { + logger.info("Health check endpoint called"); + + try { + Map healthStatus = healthService.checkHealth(); + String overallStatus = (String) healthStatus.get("status"); + + // Return 503 only if DOWN; 200 for both UP and DEGRADED (DEGRADED = operational with warnings) + HttpStatus httpStatus = "DOWN".equals(overallStatus) ? HttpStatus.SERVICE_UNAVAILABLE : HttpStatus.OK; + + logger.debug("Health check completed with status: {}", overallStatus); + return new ResponseEntity<>(healthStatus, httpStatus); + + } catch (Exception e) { + logger.error("Unexpected error during health check", e); + + Map errorResponse = Map.of( + "status", "DOWN", + "timestamp", Instant.now().toString() + ); + + return new ResponseEntity<>(errorResponse, HttpStatus.SERVICE_UNAVAILABLE); + } + } +} + + diff --git a/src/main/java/com/iemr/inventory/controller/version/VersionController.java b/src/main/java/com/iemr/inventory/controller/version/VersionController.java index 472a0bb9..3fdab115 100644 --- a/src/main/java/com/iemr/inventory/controller/version/VersionController.java +++ b/src/main/java/com/iemr/inventory/controller/version/VersionController.java @@ -1,8 +1,8 @@ /* -* AMRIT – Accessible Medical Records via Integrated Technology -* Integrated EHR (Electronic Health Records) Solution +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution * -* Copyright (C) "Piramal Swasthya Management and Research Institute" +* Copyright (C) "Piramal Swasthya Management and Research Institute" * * This file is part of AMRIT. * @@ -21,57 +21,59 @@ */ package com.iemr.inventory.controller.version; -import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; -import java.io.InputStreamReader; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -import com.iemr.inventory.utils.response.OutputResponse; - -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; @RestController public class VersionController { - private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); + private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); + + private static final String UNKNOWN_VALUE = "unknown"; - @ApiOperation(value = "Get version details", consumes = "application/json", produces = "application/json") - @RequestMapping(value = "/version", method = { RequestMethod.GET }) - public String versionInformation() { - OutputResponse output = new OutputResponse(); + @Operation(summary = "Get version information") + @GetMapping(value = "/version", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> versionInformation() { + Map response = new LinkedHashMap<>(); try { logger.info("version Controller Start"); - output.setResponse(readGitProperties()); + Properties gitProperties = loadGitProperties(); + response.put("buildTimestamp", gitProperties.getProperty("git.build.time", UNKNOWN_VALUE)); + response.put("version", gitProperties.getProperty("git.build.version", UNKNOWN_VALUE)); + response.put("branch", gitProperties.getProperty("git.branch", UNKNOWN_VALUE)); + response.put("commitHash", gitProperties.getProperty("git.commit.id.abbrev", UNKNOWN_VALUE)); } catch (Exception e) { - output.setError(e); + logger.error("Failed to load version information", e); + response.put("buildTimestamp", UNKNOWN_VALUE); + response.put("version", UNKNOWN_VALUE); + response.put("branch", UNKNOWN_VALUE); + response.put("commitHash", UNKNOWN_VALUE); } - logger.info("version Controller End"); - return output.toString(); - } - - private String readGitProperties() throws Exception { - ClassLoader classLoader = getClass().getClassLoader(); - InputStream inputStream = classLoader.getResourceAsStream("git.properties"); - - return readFromInputStream(inputStream); + return ResponseEntity.ok(response); } - private String readFromInputStream(InputStream inputStream) throws IOException { - StringBuilder resultStringBuilder = new StringBuilder(); - try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) { - String line; - while ((line = br.readLine()) != null) { - resultStringBuilder.append(line).append("\n"); + private Properties loadGitProperties() throws IOException { + Properties properties = new Properties(); + try (InputStream input = getClass().getClassLoader() + .getResourceAsStream("git.properties")) { + if (input != null) { + properties.load(input); } } - return resultStringBuilder.toString(); + return properties; } } diff --git a/src/main/java/com/iemr/inventory/service/health/HealthService.java b/src/main/java/com/iemr/inventory/service/health/HealthService.java new file mode 100644 index 00000000..3583b00b --- /dev/null +++ b/src/main/java/com/iemr/inventory/service/health/HealthService.java @@ -0,0 +1,544 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + +package com.iemr.inventory.service.health; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.ExecutionException; +import java.util.function.Supplier; +import jakarta.annotation.PreDestroy; +import javax.sql.DataSource; +import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.HikariPoolMXBean; +import java.lang.management.ManagementFactory; +import javax.management.MBeanServer; +import javax.management.ObjectName; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; + +@Service +public class HealthService { + + private static final Logger logger = LoggerFactory.getLogger(HealthService.class); + + // Status constants + private static final String STATUS_KEY = "status"; + private static final String STATUS_UP = "UP"; + private static final String STATUS_DOWN = "DOWN"; + private static final String STATUS_DEGRADED = "DEGRADED"; + + // Severity levels and keys + private static final String SEVERITY_KEY = "severity"; + private static final String SEVERITY_OK = "OK"; + private static final String SEVERITY_WARNING = "WARNING"; + private static final String SEVERITY_CRITICAL = "CRITICAL"; + + // Response keys + private static final String ERROR_KEY = "error"; + private static final String MESSAGE_KEY = "message"; + private static final String RESPONSE_TIME_KEY = "responseTimeMs"; + + // Timeouts (in seconds) + private static final long MYSQL_TIMEOUT_SECONDS = 3; + private static final long REDIS_TIMEOUT_SECONDS = 3; + + // Advanced checks configuration + private static final long ADVANCED_CHECKS_TIMEOUT_MS = 500; // Strict timeout for advanced checks + private static final long ADVANCED_CHECKS_THROTTLE_SECONDS = 30; // Run at most once per 30 seconds + + // Performance threshold (milliseconds) - response time > 2000ms = DEGRADED + private static final long RESPONSE_TIME_THRESHOLD_MS = 2000; + + // Diagnostic event codes for concise logging + private static final String DIAGNOSTIC_LOCK_WAIT = "MYSQL_LOCK_WAIT"; + private static final String DIAGNOSTIC_SLOW_QUERIES = "MYSQL_SLOW_QUERIES"; + private static final String DIAGNOSTIC_POOL_EXHAUSTED = "MYSQL_POOL_EXHAUSTED"; + private static final String DIAGNOSTIC_LOG_TEMPLATE = "Diagnostic: {}"; + + private final DataSource dataSource; + private final RedisTemplate redisTemplate; + private final ExecutorService executorService; + + // Advanced checks throttling (thread-safe) + private volatile long lastAdvancedCheckTime = 0; + private volatile AdvancedCheckResult cachedAdvancedCheckResult = null; + private final ReentrantReadWriteLock advancedCheckLock = new ReentrantReadWriteLock(); + + // Advanced checks always enabled + private static final boolean ADVANCED_HEALTH_CHECKS_ENABLED = true; + + public HealthService(DataSource dataSource, + @Autowired(required = false) RedisTemplate redisTemplate) { + this.dataSource = dataSource; + this.redisTemplate = redisTemplate; + this.executorService = Executors.newFixedThreadPool(6); + } + + @PreDestroy + public void shutdown() { + if (executorService != null && !executorService.isShutdown()) { + try { + executorService.shutdown(); + if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + logger.warn("ExecutorService did not terminate gracefully"); + } + } catch (InterruptedException e) { + executorService.shutdownNow(); + Thread.currentThread().interrupt(); + logger.warn("ExecutorService shutdown interrupted", e); + } + } + } + + public Map checkHealth() { + Map response = new LinkedHashMap<>(); + response.put("timestamp", Instant.now().toString()); + + Map mysqlStatus = new ConcurrentHashMap<>(); + Map redisStatus = new ConcurrentHashMap<>(); + + if (!executorService.isShutdown()) { + performHealthChecks(mysqlStatus, redisStatus); + } + + ensurePopulated(mysqlStatus, "MySQL"); + ensurePopulated(redisStatus, "Redis"); + + Map> components = new LinkedHashMap<>(); + components.put("mysql", mysqlStatus); + components.put("redis", redisStatus); + + response.put("components", components); + response.put(STATUS_KEY, computeOverallStatus(components)); + + return response; + } + + private void performHealthChecks(Map mysqlStatus, Map redisStatus) { + Future mysqlFuture = null; + Future redisFuture = null; + try { + mysqlFuture = executorService.submit( + () -> performHealthCheck("MySQL", mysqlStatus, this::checkMySQLHealthSync)); + redisFuture = executorService.submit( + () -> performHealthCheck("Redis", redisStatus, this::checkRedisHealthSync)); + + awaitHealthChecks(mysqlFuture, redisFuture); + } catch (TimeoutException e) { + logger.warn("Health check aggregate timeout after {} seconds", getMaxTimeout()); + cancelFutures(mysqlFuture, redisFuture); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + logger.warn("Health check was interrupted"); + cancelFutures(mysqlFuture, redisFuture); + } catch (Exception e) { + logger.warn("Health check execution error: {}", e.getMessage()); + } + } + + private void awaitHealthChecks(Future mysqlFuture, Future redisFuture) throws TimeoutException, InterruptedException, ExecutionException { + long maxTimeout = getMaxTimeout(); + long deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(maxTimeout); + + mysqlFuture.get(maxTimeout, TimeUnit.SECONDS); + long remainingNs = deadlineNs - System.nanoTime(); + + if (remainingNs > 0) { + redisFuture.get(remainingNs, TimeUnit.NANOSECONDS); + } else { + redisFuture.cancel(true); + } + } + + private long getMaxTimeout() { + return Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; + } + + private void cancelFutures(Future mysqlFuture, Future redisFuture) { + if (mysqlFuture != null) mysqlFuture.cancel(true); + if (redisFuture != null) redisFuture.cancel(true); + } + + private void ensurePopulated(Map status, String componentName) { + if (!status.containsKey(STATUS_KEY)) { + status.put(STATUS_KEY, STATUS_DOWN); + status.put(SEVERITY_KEY, SEVERITY_CRITICAL); + status.put(ERROR_KEY, componentName + " health check did not complete in time"); + } + } + + private HealthCheckResult checkMySQLHealthSync() { + try (Connection connection = dataSource.getConnection(); + PreparedStatement stmt = connection.prepareStatement("SELECT 1 as health_check")) { + + stmt.setQueryTimeout((int) MYSQL_TIMEOUT_SECONDS); + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + // Basic health check passed, now run advanced checks asynchronously with fresh connection + boolean isDegraded = performAdvancedMySQLChecksWithThrottle(); + return new HealthCheckResult(true, null, isDegraded); + } + } + + return new HealthCheckResult(false, "No result from health check query", false); + + } catch (Exception e) { + logger.warn("MySQL health check failed: {}", e.getMessage(), e); + return new HealthCheckResult(false, "MySQL connection failed", false); + } + } + + private HealthCheckResult checkRedisHealthSync() { + if (redisTemplate == null) { + return new HealthCheckResult(true, "Redis not configured — skipped", false); + } + + try { + String pong = redisTemplate.execute((org.springframework.data.redis.core.RedisCallback) (connection) -> connection.ping()); + + if ("PONG".equals(pong)) { + return new HealthCheckResult(true, null, false); + } + + return new HealthCheckResult(false, "Redis PING failed", false); + + } catch (Exception e) { + logger.warn("Redis health check failed: {}", e.getMessage(), e); + return new HealthCheckResult(false, "Redis connection failed", false); + } + } + + private Map performHealthCheck(String componentName, + Map status, + Supplier checker) { + long startTime = System.currentTimeMillis(); + + try { + HealthCheckResult result = checker.get(); + long responseTime = System.currentTimeMillis() - startTime; + + // Determine status: DOWN (unhealthy), DEGRADED (healthy but with issues), or UP + String componentStatus; + if (!result.isHealthy) { + componentStatus = STATUS_DOWN; + } else if (result.isDegraded) { + componentStatus = STATUS_DEGRADED; + } else { + componentStatus = STATUS_UP; + } + status.put(STATUS_KEY, componentStatus); + + // Set response time + status.put(RESPONSE_TIME_KEY, responseTime); + + // Determine severity based on health, response time, and degradation flags + String severity = determineSeverity(result.isHealthy, responseTime, result.isDegraded); + status.put(SEVERITY_KEY, severity); + + // Include message or error based on health status + if (result.error != null) { + // Use MESSAGE_KEY for informational messages when healthy + // Use ERROR_KEY for actual error messages when unhealthy + String fieldKey = result.isHealthy ? MESSAGE_KEY : ERROR_KEY; + status.put(fieldKey, result.error); + } + + return status; + + } catch (Exception e) { + long responseTime = System.currentTimeMillis() - startTime; + logger.error("{} health check failed with exception: {}", componentName, e.getMessage(), e); + + status.put(STATUS_KEY, STATUS_DOWN); + status.put(RESPONSE_TIME_KEY, responseTime); + status.put(SEVERITY_KEY, SEVERITY_CRITICAL); + status.put(ERROR_KEY, "Health check failed with an unexpected error"); + + return status; + } + } + + private String determineSeverity(boolean isHealthy, long responseTimeMs, boolean isDegraded) { + if (!isHealthy) { + return SEVERITY_CRITICAL; + } + + if (isDegraded) { + return SEVERITY_WARNING; + } + + if (responseTimeMs > RESPONSE_TIME_THRESHOLD_MS) { + return SEVERITY_WARNING; + } + + return SEVERITY_OK; + } + + private String computeOverallStatus(Map> components) { + boolean hasCritical = false; + boolean hasDegraded = false; + + for (Map componentStatus : components.values()) { + String status = (String) componentStatus.get(STATUS_KEY); + String severity = (String) componentStatus.get(SEVERITY_KEY); + + if (STATUS_DOWN.equals(status) || SEVERITY_CRITICAL.equals(severity)) { + hasCritical = true; + } + + if (STATUS_DEGRADED.equals(status)) { + hasDegraded = true; + } + + if (SEVERITY_WARNING.equals(severity)) { + hasDegraded = true; + } + } + + if (hasCritical) { + return STATUS_DOWN; + } + + if (hasDegraded) { + return STATUS_DEGRADED; + } + + return STATUS_UP; + } + + // Internal advanced health checks for MySQL - do not expose details in responses + private boolean performAdvancedMySQLChecksWithThrottle() { + if (!ADVANCED_HEALTH_CHECKS_ENABLED) { + return false; // Advanced checks disabled + } + + long currentTime = System.currentTimeMillis(); + + // Check throttle window - use read lock first for fast path + advancedCheckLock.readLock().lock(); + try { + if (cachedAdvancedCheckResult != null && + (currentTime - lastAdvancedCheckTime) < ADVANCED_CHECKS_THROTTLE_SECONDS * 1000) { + // Return cached result - within throttle window + return cachedAdvancedCheckResult.isDegraded; + } + } finally { + advancedCheckLock.readLock().unlock(); + } + + // Outside throttle window - acquire write lock and run checks + advancedCheckLock.writeLock().lock(); + try { + // Double-check after acquiring write lock + if (cachedAdvancedCheckResult != null && + (currentTime - lastAdvancedCheckTime) < ADVANCED_CHECKS_THROTTLE_SECONDS * 1000) { + return cachedAdvancedCheckResult.isDegraded; + } + } finally { + advancedCheckLock.writeLock().unlock(); + } + + // Perform DB I/O outside the write lock to avoid lock contention + AdvancedCheckResult result; + try (Connection conn = dataSource.getConnection()) { + result = performAdvancedMySQLChecks(conn); + } catch (Exception ex) { + if (ex.getCause() instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + logger.debug("Could not acquire connection for advanced checks: {}", ex.getMessage()); + result = new AdvancedCheckResult(false); // don't mark degraded on acquisition failure + } + + // Re-acquire write lock only to update the cache atomically + advancedCheckLock.writeLock().lock(); + try { + lastAdvancedCheckTime = currentTime; + cachedAdvancedCheckResult = result; + return result.isDegraded; + } finally { + advancedCheckLock.writeLock().unlock(); + } + } + + private AdvancedCheckResult performAdvancedMySQLChecks(Connection connection) { + try { + boolean hasIssues = false; + + if (hasLockWaits(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_LOCK_WAIT); + hasIssues = true; + } + + if (hasSlowQueries(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_SLOW_QUERIES); + hasIssues = true; + } + + if (hasConnectionPoolExhaustion()) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_POOL_EXHAUSTED); + hasIssues = true; + } + + return new AdvancedCheckResult(hasIssues); + } catch (Exception e) { + logger.debug("Advanced MySQL checks encountered exception, marking degraded"); + return new AdvancedCheckResult(true); + } + } + + private boolean hasLockWaits(Connection connection) { + try (PreparedStatement stmt = connection.prepareStatement( + "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PROCESSLIST " + + "WHERE (state = 'Waiting for table metadata lock' " + + " OR state = 'Waiting for row lock' " + + " OR state = 'Waiting for lock') " + + "AND user = SUBSTRING_INDEX(USER(), '@', 1)")) { + stmt.setQueryTimeout(2); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int lockCount = rs.getInt(1); + return lockCount > 0; + } + } + } catch (Exception e) { + logger.debug("Could not check for lock waits"); + } + return false; + } + + private boolean hasSlowQueries(Connection connection) { + try (PreparedStatement stmt = connection.prepareStatement( + "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PROCESSLIST " + + "WHERE command != 'Sleep' AND time > ? " + + "AND user = SUBSTRING_INDEX(USER(), '@', 1)")) { + stmt.setQueryTimeout(2); + stmt.setInt(1, 10); // Queries running longer than 10 seconds + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int slowQueryCount = rs.getInt(1); + return slowQueryCount > 3; // Alert if more than 3 slow queries + } + } + } catch (Exception e) { + logger.debug("Could not check for slow queries"); + } + return false; + } + + private boolean hasConnectionPoolExhaustion() { + // Use HikariCP metrics if available + if (dataSource instanceof HikariDataSource hikariDataSource) { + try { + HikariPoolMXBean poolMXBean = hikariDataSource.getHikariPoolMXBean(); + + if (poolMXBean != null) { + int activeConnections = poolMXBean.getActiveConnections(); + int maxPoolSize = hikariDataSource.getMaximumPoolSize(); + + // Alert if > 80% of pool is exhausted + int threshold = (int) (maxPoolSize * 0.8); + return activeConnections > threshold; + } + } catch (Exception e) { + logger.debug("Could not retrieve HikariCP pool metrics"); + } + } + + // Fallback: try to get pool metrics via JMX if HikariCP is not directly available + return checkPoolMetricsViaJMX(); + } + + private boolean checkPoolMetricsViaJMX() { + try { + MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); + ObjectName objectName = new ObjectName("com.zaxxer.hikari:type=Pool (*)"); + var mBeans = mBeanServer.queryMBeans(objectName, null); + + for (var mBean : mBeans) { + if (evaluatePoolMetrics(mBeanServer, mBean.getObjectName())) { + return true; + } + } + } catch (Exception e) { + logger.debug("Could not access HikariCP pool metrics via JMX"); + } + + // No pool metrics available - disable this check + logger.debug("Pool exhaustion check disabled: HikariCP metrics unavailable"); + return false; + } + + private boolean evaluatePoolMetrics(MBeanServer mBeanServer, ObjectName objectName) { + try { + Integer activeConnections = (Integer) mBeanServer.getAttribute(objectName, "ActiveConnections"); + Integer maximumPoolSize = (Integer) mBeanServer.getAttribute(objectName, "MaximumPoolSize"); + + if (activeConnections != null && maximumPoolSize != null) { + int threshold = (int) (maximumPoolSize * 0.8); + return activeConnections > threshold; + } + } catch (Exception e) { + // Continue to next MBean + } + return false; + } + + private static class AdvancedCheckResult { + final boolean isDegraded; + + AdvancedCheckResult(boolean isDegraded) { + this.isDegraded = isDegraded; + } + } + + private static class HealthCheckResult { + final boolean isHealthy; + final String error; + final boolean isDegraded; + + HealthCheckResult(boolean isHealthy, String error, boolean isDegraded) { + this.isHealthy = isHealthy; + this.error = error; + this.isDegraded = isDegraded; + } + } +} + + diff --git a/src/main/java/com/iemr/inventory/utils/JwtUserIdValidationFilter.java b/src/main/java/com/iemr/inventory/utils/JwtUserIdValidationFilter.java index 6f37aa8b..80b857c8 100644 --- a/src/main/java/com/iemr/inventory/utils/JwtUserIdValidationFilter.java +++ b/src/main/java/com/iemr/inventory/utils/JwtUserIdValidationFilter.java @@ -113,7 +113,9 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo || path.startsWith(contextPath + "/swagger-ui") || path.startsWith(contextPath + "/v3/api-docs") || path.startsWith(contextPath + "/user/refreshToken") - || path.startsWith(contextPath + "/public")) { + || path.startsWith(contextPath + "/public") + || path.equals(contextPath + "/version") + || path.equals(contextPath + "/health")) { logger.info("Skipping filter for path: " + path); filterChain.doFilter(servletRequest, servletResponse); return; From bd5ee2a1ba6307e546b57e7727fc87056ade152c Mon Sep 17 00:00:00 2001 From: Vanitha S <116701245+vanitha1822@users.noreply.github.com> Date: Wed, 18 Mar 2026 13:02:05 +0530 Subject: [PATCH 3/3] fix: update pom version (#120) --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index adf80292..8ffbf077 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ 4.0.0 com.iemr.inventory inventory-api - 3.4.0 + 3.6.1 war Inventory-API Inventory Page