How to use ConnectionUrl class of org.testcontainers.jdbc package

Best Testcontainers-java code snippet using org.testcontainers.jdbc.ConnectionUrl

Source:SharedContainerDatabaseDriver.java Github

copy

Full Screen

...23import org.testcontainers.containers.JdbcDatabaseContainer;24import org.testcontainers.containers.JdbcDatabaseContainerProvider;25import org.testcontainers.delegate.DatabaseDelegate;26import org.testcontainers.ext.ScriptUtils;27import org.testcontainers.jdbc.ConnectionUrl;28import org.testcontainers.jdbc.JdbcDatabaseDelegate;29import org.testcontainers.shaded.org.apache.commons.io.IOUtils;30public class SharedContainerDatabaseDriver implements Driver {31 private static Logger LOGGER = LoggerFactory.getLogger(SharedContainerDatabaseDriver.class);32 private static final Map<String, Set<Connection>> containerConnections = new ConcurrentHashMap<>();33 private static final Map<String, JdbcDatabaseContainer> jdbcUrlContainerCache = new ConcurrentHashMap<>();34 private static final Set<String> initializedScripts = ConcurrentHashMap.newKeySet();35 private static final String JDBC_WITH_TC_PREFIX = "jdbc:tc:";36 private static final String FILE_PATH_PREFIX = "file:";37 private static final String SQL_DROP_FLYWAY_TABLE_IF_EXISTS = "DROP TABLE IF EXISTS flyway_schema_history";38 private Driver delegate;39 static {40 try {41 LOGGER.info("About to register shared container driver (supporting jdbc:tc) ...");42 DriverManager.registerDriver(new SharedContainerDatabaseDriver());43 LOGGER.info("... success");44 } catch (SQLException e) {45 LOGGER.warn("Failed to register driver", e);46 }47 }48 static JdbcDatabaseContainer getContainer(String jdbcUrl) {49 LOGGER.info("About to fetch container with URL: {}", jdbcUrl);50 return jdbcUrlContainerCache.get(jdbcUrl);51 }52 @Override53 public boolean acceptsURL(String url) throws SQLException {54 return url.startsWith(JDBC_WITH_TC_PREFIX);55 }56 @Override57 public Connection connect(String url, Properties properties) throws SQLException {58 LOGGER.debug("Current cache size: {}", jdbcUrlContainerCache.size());59 if (!acceptsURL(url)) {60 return null;61 }62 ConnectionUrl connectionUrl = ConnectionUrl.newInstance(url);63 String queryString = connectionUrl.getQueryString().orElse("");64 LOGGER.debug("Checking cache for key: {} -> with query: {}", connectionUrl.getDatabaseType(), queryString);65 JdbcDatabaseContainer container = jdbcUrlContainerCache.get(connectionUrl.getDatabaseType());66 if (container == null) {67 LOGGER.debug("... not found -> creating new instance");68 Map<String, String> parameters = connectionUrl.getContainerParameters();69 ServiceLoader<JdbcDatabaseContainerProvider> databaseContainers = ServiceLoader.load(JdbcDatabaseContainerProvider.class);70 for (JdbcDatabaseContainerProvider candidateContainerType : databaseContainers) {71 LOGGER.debug("Probing candidate ({}) for database type: {}", candidateContainerType, connectionUrl.getDatabaseType());72 if (candidateContainerType.supports(connectionUrl.getDatabaseType())) {73 LOGGER.info("Creating new instance with connection url: {} -> URL: {}", connectionUrl, connectionUrl.getUrl());74 container = candidateContainerType.newInstance(connectionUrl);75 container.withTmpFs(connectionUrl.getTmpfsOptions());76 delegate = container.getJdbcDriverInstance();77 }78 }79 if (container == null) {80 throw new UnsupportedOperationException("Database name " + connectionUrl.getDatabaseType() + " not supported");81 }82 jdbcUrlContainerCache.put(connectionUrl.getDatabaseType(), container);83 container.setParameters(parameters);84 container.start();85 LOGGER.debug("... container started...");86 }87 Connection connection = container.createConnection(queryString);88 LOGGER.debug("Connection to container: {} -> URL {}", connection, connection.getMetaData().getURL());89 DatabaseDelegate databaseDelegate = new JdbcDatabaseDelegate(container, queryString);90 runInitScriptIfRequired(connectionUrl, databaseDelegate);91 runClearFlywayIfRequired(connection);92 runInitFunctionIfRequired(connectionUrl, connection);93 return wrapConnection(connection, container, connectionUrl);94 }95 @Override96 public DriverPropertyInfo[] getPropertyInfo(String url, Properties properties) throws SQLException {97 return this.delegate.getPropertyInfo(url, properties);98 }99 @Override100 public int getMajorVersion() {101 return this.delegate.getMajorVersion();102 }103 @Override104 public int getMinorVersion() {105 return this.delegate.getMinorVersion();106 }107 @Override108 public boolean jdbcCompliant() {109 return this.delegate.jdbcCompliant();110 }111 @Override112 public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {113 return this.delegate.getParentLogger();114 }115 public static void killContainers() {116 jdbcUrlContainerCache.values().forEach(JdbcDatabaseContainer::stop);117 jdbcUrlContainerCache.clear();118 containerConnections.clear();119 }120 public static void killContainer(String jdbcUrl) {121 JdbcDatabaseContainer container = jdbcUrlContainerCache.get(jdbcUrl);122 if (container != null) {123 container.stop();124 jdbcUrlContainerCache.remove(jdbcUrl);125 containerConnections.remove(container.getContainerId());126 }127 }128 private void runInitScriptIfRequired(final ConnectionUrl connectionUrl, DatabaseDelegate databaseDelegate) throws SQLException {129 if (connectionUrl.getInitScriptPath().isPresent()) {130 String initScriptPath = connectionUrl.getInitScriptPath().get();131 LOGGER.debug("About to execute script: {}", initScriptPath);132 if (initializedScripts.contains(initScriptPath)) {133 LOGGER.debug("... aborted, already executed");134 return;135 }136 LOGGER.debug("... script execution added to history");137 initializedScripts.add(initScriptPath);138 try {139 URL resource;140 if (initScriptPath.startsWith(FILE_PATH_PREFIX)) {141 //relative workdir path142 resource = new URL(initScriptPath);143 } else {144 //classpath resource145 resource = Thread.currentThread().getContextClassLoader().getResource(initScriptPath);146 }147 if (resource == null) {148 LOGGER.warn("Could not load classpath init script: {}", initScriptPath);149 throw new SQLException("Could not load classpath init script: " + initScriptPath + ". Resource not found.");150 }151 String sql = IOUtils.toString(resource, StandardCharsets.UTF_8);152 LOGGER.debug("Running script {}", sql);153 ScriptUtils.executeDatabaseScript(databaseDelegate, initScriptPath, sql);154 } catch (IOException e) {155 LOGGER.warn("Could not load classpath init script: {}", initScriptPath);156 throw new SQLException("Could not load classpath init script: " + initScriptPath, e);157 } catch (ScriptException e) {158 LOGGER.error("Error while executing init script: {}", initScriptPath, e);159 throw new SQLException("Error while executing init script: " + initScriptPath, e);160 }161 }162 }163 private void runClearFlywayIfRequired(final Connection connection) throws SQLException {164 PreparedStatement preparedStatement = connection.prepareStatement(SQL_DROP_FLYWAY_TABLE_IF_EXISTS);165 preparedStatement.execute();166 }167 private void runInitFunctionIfRequired(final ConnectionUrl connectionUrl, Connection connection) throws SQLException {168 if (connectionUrl.getInitFunction().isPresent()) {169 String className = connectionUrl.getInitFunction().get().getClassName();170 String methodName = connectionUrl.getInitFunction().get().getMethodName();171 try {172 Class<?> initFunctionClazz = Class.forName(className);173 Method method = initFunctionClazz.getMethod(methodName, Connection.class);174 method.invoke(null, connection);175 } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {176 LOGGER.error("Error while executing init function: {}::{}", className, methodName, e);177 throw new SQLException("Error while executing init function: " + className + "::" + methodName, e);178 }179 }180 }181 private Connection wrapConnection(final Connection connection, final JdbcDatabaseContainer container, final ConnectionUrl connectionUrl) {182 final boolean isDaemon = connectionUrl.isInDaemonMode();183 Set<Connection> connections = containerConnections.computeIfAbsent(container.getContainerId(), k -> new HashSet<>());184 connections.add(connection);185 final Set<Connection> finalConnections = connections;186 return new SharedConnectionWrapper(connection, () -> {187 finalConnections.remove(connection);188 if (!isDaemon && finalConnections.isEmpty()) {189 container.stop();190 jdbcUrlContainerCache.remove(connectionUrl.getUrl());191 }192 });193 }194}...

Full Screen

Full Screen

Source:PgroongaContainerProvider.java Github

copy

Full Screen

1package com.frogdevelopment.testcontainers.containers;2import org.testcontainers.containers.JdbcDatabaseContainer;3import org.testcontainers.containers.JdbcDatabaseContainerProvider;4import org.testcontainers.containers.PostgreSQLContainer;5import org.testcontainers.jdbc.ConnectionUrl;6import org.testcontainers.utility.DockerImageName;7/**8 * Factory for pgroonga container, which is PostgreSQL with groonga extension.9 * PGroonga makes PostgreSQL fast full text search platform for all languages!10 */11public class PgroongaContainerProvider extends JdbcDatabaseContainerProvider {12 private static final String NAME = "pgroonga";13 private static final String DEFAULT_TAG = "2.2.7-alpine-13-slim";14 private static final String DEFAULT_IMAGE = "groonga/pgroonga";15 public static final String USER_PARAM = "user";16 public static final String PASSWORD_PARAM = "password";17 @Override18 public boolean supports(String databaseType) {19 return databaseType.equals(NAME);20 }21 @Override22 public JdbcDatabaseContainer newInstance() {23 return newInstance(DEFAULT_TAG);24 }25 @Override26 public JdbcDatabaseContainer newInstance(String tag) {27 return new PostgreSQLContainer(DockerImageName.parse(DEFAULT_IMAGE + ":" + tag).asCompatibleSubstituteFor("postgres"));28 }29 @Override30 public JdbcDatabaseContainer newInstance(ConnectionUrl connectionUrl) {31 return newInstanceFromConnectionUrl(connectionUrl, USER_PARAM, PASSWORD_PARAM);32 }33}...

Full Screen

Full Screen

Source:QuestDbContainerProvider.java Github

copy

Full Screen

1package io.questdb.testcontainers;2import org.testcontainers.containers.JdbcDatabaseContainer;3import org.testcontainers.containers.JdbcDatabaseContainerProvider;4import org.testcontainers.jdbc.ConnectionUrl;5public class QuestDbContainerProvider extends JdbcDatabaseContainerProvider {6 private static final String USER_PARAM = "user";7 private static final String PASSWORD_PARAM = "password";8 public QuestDbContainerProvider() {9 }10 public boolean supports(String databaseType) {11 return databaseType.equals("questdb");12 }13 public JdbcDatabaseContainer newInstance() {14 return this.newInstance("4.1.5");15 }16 public JdbcDatabaseContainer newInstance(String tag) {17 return new QuestDbContainer("questdb/questdb:" + tag);18 }19 public JdbcDatabaseContainer newInstance(ConnectionUrl connectionUrl) {20 return this.newInstanceFromConnectionUrl(connectionUrl, USER_PARAM, PASSWORD_PARAM);21 }22}...

Full Screen

Full Screen

ConnectionUrl

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.jdbc.ConnectionUrl;2public class 1 {3 public static void main(String[] args) {4 System.out.println(connectionUrl);5 }6}

Full Screen

Full Screen

ConnectionUrl

Using AI Code Generation

copy

Full Screen

1public class 1 {2 public static void main(String[] args) {3 }4}5create table test(id int);6public class 1 {7 public static void main(String[] args) {8 }9}10create table test(id int);11public class 1 {12 public static void main(String[] args) {

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testcontainers-java automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful