hdpos/src/main/java/com/example/services/DatabaseConnectDOTSOFT.java

68 lines
2.3 KiB
Java

package com.example.services;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DatabaseConnectDOTSOFT implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(DatabaseConnectDOTSOFT.class);
private Connection connection;
public DatabaseConnectDOTSOFT(String username) throws SQLException {
String environment = loadEnvironment();
try {
Properties dbProperties = loadDatabaseProperties();
String url = dbProperties.getProperty(environment + ".db.url");
String userpassword = dbProperties.getProperty(environment + ".db." + username + ".password");
connection = DriverManager.getConnection(url, username, userpassword);
logger.info("DOTSOFT Connection OK for user " + username + " on environment " + environment);
} catch (SQLException e) {
logger.error("Failed to connect to DOTSOFT database for user " + username + " on environment " + environment, e);
throw e; // re-throw the exception
}
}
public Connection getConnection() {
return connection;
}
@Override
public void close() throws SQLException {
if (connection != null && !connection.isClosed()) {
connection.close();
logger.info("DOTSOFT Connection closed");
}
}
private String loadEnvironment() {
Properties envProperties = loadProperties("env.properties");
return envProperties.getProperty("environment");
}
private Properties loadDatabaseProperties() {
Properties dbProperties = loadProperties("db.properties");
return dbProperties;
}
private Properties loadProperties(String fileName) {
Properties properties = new Properties();
try (InputStream input = getClass().getClassLoader().getResourceAsStream(fileName)) {
properties.load(input);
} catch (IOException e) {
e.printStackTrace();
// Handle the exception correctly for your application
}
return properties;
}
}