package de.superx; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.sql.Connection; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import javax.sql.DataSource; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVRecord; import org.apache.log4j.Logger; import org.h2.tools.Server; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.runner.RunWith; import org.pentaho.di.core.database.DataSourceNamingException; import org.pentaho.di.core.database.DataSourceProviderFactory; import org.pentaho.di.core.database.DataSourceProviderInterface; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.jdbc.datasource.init.ScriptException; import org.springframework.jdbc.datasource.init.ScriptUtils; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import de.superx.bianalysis.models.Right; import de.superx.bianalysis.models.RightParam; import de.superx.bianalysis.service.UserRestrictionService; import de.superx.common.SxUser; import de.superx.jdbc.entity.Konstante; import de.superx.jdbc.repository.KonstanteRepository; import de.superx.spring.TestUserServiceImpl; import de.superx.spring.service.UserService; @Ignore @RunWith(SpringRunner.class) @ContextConfiguration(classes = { TestApplicationConfigPg.class }) public class BaseDbTest { // protected static void createTestDb() throws SQLException { // // TODO This kind of works but still problems with SxPool init // try (Connection con = DriverManager.getConnection(H2_MEM_URL)) { // DataSource ds = new SingleConnectionDataSource(con, true); // JdbcTemplate jt = new JdbcTemplate(ds); // jt.execute("RUNSCRIPT FROM '" + dbPath + File.separator + "head_eduetl.sql'"); // } // } private static Logger logger = Logger.getLogger(BaseDbTest.class); public static final String LOGGING_PROPERTIES_PATH = String.join(File.separator, "test", "conf", "logging_unittests.properties"); public static final String logConfigPath = new File(LOGGING_PROPERTIES_PATH).getAbsolutePath(); public static final String MANDANTEN_ID = "test"; @Autowired public DataSource dataSource; @Autowired public KonstanteRepository konstanteRepository; @Autowired private UserService userService; protected SxUser user; @After public void after() { user.getRightsMap().clear(); new JdbcTemplate(dataSource).execute("TRUNCATE table public.user_dimension_grants"); } @Before public void baseInit() throws SQLException { // Kettle DataSourceProvider try (Connection con = dataSource.getConnection()) { logger.info("Set Kettle DataSourceProvider to " + con.getMetaData().getURL()); } DataSourceProviderFactory .setDataSourceProviderInterface(new DataSourceProviderInterface() { @Override public DataSource getNamedDataSource(String datasourceName) throws DataSourceNamingException { return dataSource; } @Override public DataSource getNamedDataSource(String datasourceName, DatasourceType type) throws DataSourceNamingException { return getNamedDataSource(datasourceName); } }); // Testuser intialisieren TestUserServiceImpl tusi = (TestUserServiceImpl) userService; user = tusi.createTestUser(true, null); Map> rights = new HashMap<>(); rights.put("RIGHT_CS_BIA_STANDARDREPORTS_ADMIN", null); user.setRights(rights, null); new UserRestrictionService(user, dataSource); } protected void executeSqlScript(String filePath) throws ScriptException, SQLException { ScriptUtils.executeSqlScript(dataSource.getConnection(), new FileSystemResource(new File(filePath))); } protected void loadCsvFileIntoTable(String filePath, String tableName) throws IOException { loadCsvFileIntoTable(filePath, tableName, ';'); } protected void loadCsvFileIntoTable(String filePath, String tableName, char delimiter) throws IOException { Iterable records = null; Reader in = new FileReader(filePath); records = CSVFormat.RFC4180 .withDelimiter(delimiter) .withFirstRecordAsHeader() .withNullString("") .withTrim() .withEscape('\\') .parse(in); SimpleJdbcInsert insertActor = new SimpleJdbcInsert(dataSource).withTableName(tableName); for (CSVRecord record : records) { insertActor.execute(record.toMap()); } } protected void validateResultRowCount(String sqlSelect, int expectedRowCount) { JdbcTemplate jt = new JdbcTemplate(dataSource); List> resultRows = jt.queryForList(sqlSelect); assertEquals("Result has to be exactly " + expectedRowCount +" rows", expectedRowCount, resultRows.size()); } protected void validateSingleRow(String sqlSelect, Map expectedResult) { JdbcTemplate jt = new JdbcTemplate(dataSource); List> resultRows = jt.queryForList(sqlSelect); assertEquals("Result has to be exactly 1 row", 1, resultRows.size()); Map row = resultRows.get(0); for (Entry expected : expectedResult.entrySet()) { Object content = row.get(expected.getKey()); assertEquals("Expect field " + expected.getKey() + " with value " + expected.getValue(), expected.getValue(), content); } } protected void startDebugWebserver() throws SQLException { try (Connection con = dataSource.getConnection().unwrap(Connection.class)) { Server.startWebServer(con); // uncomment for local (e.g. dev env) debugging } } public void setApnr(String beschreibung, Integer apnr) { Optional optk = konstanteRepository.findByBeschreibung(beschreibung); if (optk.isPresent()) { Konstante konstante = optk.get(); konstante.apnr = apnr; konstanteRepository.save(konstante); } else { // should be present, but if not create new Konstante Konstante k = new Konstante(); k.apnr = apnr; k.beschreibung = beschreibung; k = konstanteRepository.save(k); } } protected TestUserServiceImpl getTestUserService() { return (TestUserServiceImpl) userService; } // public void setDbtDataBaseProperties(DbtManager manager) { // String password = ((HikariDataSource)dataSource).getPassword(); // String jdbcUrl = ((HikariDataSource)dataSource).getJdbcUrl(); // String cleanUrl = jdbcUrl.substring(5); // remove "jdbc:" // URI uri = URI.create(cleanUrl); // String host = uri.getHost(); // int port = uri.getPort(); // returns -1 if no port specified // String finalPort = String.valueOf(port != -1 ? Integer.valueOf(port) : "5432"); // String username = ""; // String dbName = ""; // try(Connection con = dataSource.getConnection()){ // username = con.getMetaData().getUserName(); // dbName = con.getCatalog(); // } catch (SQLException e) { // e.printStackTrace(); // } // // //manager.setTestDataBaseProperties(username, password, host, finalPort, dbName); // } // protected void setRightParamValue(Right right, RightParam rightParam, String paramValue) { setRightParamValue(right, rightParam, paramValue, true); } protected void setRightParamValue(Right right, RightParam rightParam, String paramValue, boolean truncate) { if(truncate) { new JdbcTemplate(dataSource).execute("TRUNCATE table public.user_dimension_grants"); } Map paramAndValue = user.getRightsMap().get(right.getString()); if(paramAndValue == null) { paramAndValue = new HashMap<>(); } paramAndValue.put(rightParam.getString(), paramValue); user.getRightsMap().put(right.getString(), paramAndValue); UserRestrictionService builder = new UserRestrictionService(user, dataSource); builder.applyMetadataRestrictions(); builder.applyOrgunitRestrictions(); } protected void setRight(Right right) { Map> rightsMap = user.getRightsMap(); rightsMap.clear(); rightsMap.put(right.getString(), null); } }