From 0c08020543fbf14ba7faf5055742a3eecc54d60d Mon Sep 17 00:00:00 2001 From: GeorgeC Date: Mon, 26 Aug 2024 12:16:14 -0400 Subject: [PATCH] Add DataSourceVerifier to check DB connection on startup New class `DataSourceVerifier` created to ensure that the database connection is successfully established when the application context is refreshed. It logs messages indicating the success or failure of this verification. --- .../dictionaryweights/DataSourceVerifier.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 dictionaryweights/src/main/java/edu/harvard/dbmi/avillach/dictionaryweights/DataSourceVerifier.java diff --git a/dictionaryweights/src/main/java/edu/harvard/dbmi/avillach/dictionaryweights/DataSourceVerifier.java b/dictionaryweights/src/main/java/edu/harvard/dbmi/avillach/dictionaryweights/DataSourceVerifier.java new file mode 100644 index 0000000..9e36308 --- /dev/null +++ b/dictionaryweights/src/main/java/edu/harvard/dbmi/avillach/dictionaryweights/DataSourceVerifier.java @@ -0,0 +1,39 @@ +package edu.harvard.dbmi.avillach.dictionary.datasource; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Service; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; + +@Service +public class DataSourceVerifier { + + private static final Logger LOG = LoggerFactory.getLogger(DataSourceVerifier.class); + + private final DataSource dataSource; + + @Autowired + public DataSourceVerifier(DataSource dataSource) { + this.dataSource = dataSource; + } + + @EventListener(ContextRefreshedEvent.class) + public void verifyDataSourceConnection() { + try (Connection connection = dataSource.getConnection()) { + if (connection != null) { + LOG.info("Datasource connection verified successfully."); + } else { + LOG.info("Failed to obtain a connection from the datasource."); + } + } catch (SQLException e) { + LOG.info("Error verifying datasource connection: {}", e.getMessage()); + } + } + +}