All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.infusers.core.config.secrets.AppConfig Maven / Gradle / Ivy

There is a newer version: 2024.12.0008
Show newest version
package com.infusers.core.config.secrets;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException;

import com.infusers.core.logger.ILogger;
import com.infusers.core.secrets.SecretManager;
import com.infusers.core.secrets.SecretsService;
import com.infusers.core.secrets.dto.DBSecrets;

@Configuration
public class AppConfig {
	
	private ILogger log = new ILogger(AppConfig.class);
	private static final String CLASS_NAME = "SecretsService";

	@Autowired
	private SecretManager secretManager;

	@Autowired	
	private SecretsService secretsHolder;

	@Bean
	public DataSource dataSource() {		
	    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
		DBSecrets secrets = secretsHolder.getDBSecrets();
		
		if(this.secretManager.isCloudEnvironment()) {
			log.warnWithSeparator(CLASS_NAME+".dataSource() It's cloud environment!");
			
			if(secrets!=null && secrets.isValidCloud()) {
				dataSourceBuilder
						.url("jdbc:" + secrets.getEngine() + "://" + secrets.getHost() + ":" + secrets.getPort() + "/"+secrets.getDbname())
						.username(secrets.getUsername()).password(secrets.getPassword()).build();			
			}
			else {
				String error = CLASS_NAME+".dataSource() --> It is cloud environment, but secrets are NOT available. Something is NOT right here, needs attention!!";
				log.errorWithSeparator(error);
				throw new RuntimeException(error);				
			}
		}
		else {
			log.warnWithSeparator(CLASS_NAME+".dataSource() NOT a cloud environment, falling back to Inmemory DB.");
			
			if(secrets!=null && secrets.isValidNonCloud()) {
				dataSourceBuilder
					.url(secrets.getUrl())
					.username(secrets.getUsername()).password(secrets.getPassword()).build();			
			}
			else {
				String error = CLASS_NAME+".dataSource() --> NOT a cloud environment, but secrets are NOT available. Something is NOT right here, needs attention!!";
				log.errorWithSeparator(error);
				throw new RuntimeException(error);				
			}						
		}
		
	    try {
	        return dataSourceBuilder.build();
	    } 
	    catch (DataSourceLookupFailureException e) {
			log.errorWithSeparator(CLASS_NAME+".dataSource() --> Exception while creating DB connection. Something is NOT right here, needs attention!!"+e.getMessage());
	        throw new RuntimeException("Failed to create DataSource", e);
	    }		
	}	
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy