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

Best Testcontainers-java code snippet using org.testcontainers.jdbc.ConnectionUrl.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;2import java.sql.Connection;3import java.sql.DriverManager;4import java.sql.SQLException;5public class 1 {6 public static void main(String[] args) throws SQLException {7 Connection connection = DriverManager.getConnection(ConnectionUrl.forContainer("mysql:8.0.22"));8 System.out.println(connection);9 }10}11import org.testcontainers.jdbc.ConnectionUrl;12import java.sql.Connection;13import java.sql.DriverManager;14import java.sql.SQLException;15public class 2 {16 public static void main(String[] args) throws SQLException {17 Connection connection = DriverManager.getConnection(ConnectionUrl.forContainer("mysql:8.0.22")18 .withDatabaseName("test_db")19 .withUsername("test_user")20 .withPassword("test_password")21 .build());22 System.out.println(connection);23 }24}25import org.testcontainers.jdbc.ConnectionUrl;26import java.sql.Connection;27import java.sql.DriverManager;28import java.sql.SQLException;29public class 3 {30 public static void main(String[] args) throws SQLException {31 Connection connection = DriverManager.getConnection(ConnectionUrl.forContainer("mysql:8.0.22")32 .withDatabaseName("test_db")33 .withUsername("test_user")34 .withPassword("test_password")35 .withInitScript("classpath:init.sql")36 .build());37 System.out.println(connection);38 }39}40import org.testcontainers.jdbc.ConnectionUrl;41import java.sql.Connection;42import java.sql.DriverManager;43import java.sql.SQLException;44public class 4 {45 public static void main(String[] args) throws SQLException {46 Connection connection = DriverManager.getConnection(ConnectionUrl.forContainer("mysql:8.0.22")47 .withDatabaseName("test_db")48 .withUsername("test_user")49 .withPassword("test_password")50 .withInitScript("classpath:init.sql")51 .withInitScript("classpath:init2.sql")52 .build());53 System.out.println(connection);54 }55}56import org.testcontainers.jdbc.ConnectionUrl;57import java.sql.Connection;58import java.sql

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.getJdbcUrl() = " + connectionUrl.getJdbcUrl());5 System.out.println("connectionUrl.getDatabaseType() = " + connectionUrl.getDatabaseType());6 System.out.println("connectionUrl.getInitScriptPath() = " + connectionUrl.getInitScriptPath());7 System.out.println("connectionUrl.getInitFunction() = " + connectionUrl.getInitFunction());8 }9}10connectionUrl.getDatabaseType() = mysql11connectionUrl.getInitScriptPath() = file:./src/test/resources/sql/init.sql12connectionUrl.getInitFunction() = org.testcontainers.jdbc.ContainerDatabaseDriverTest::initFunction13import org.testcontainers.jdbc.ContainerDatabaseDriver;14import org.testcontainers.jdbc.ConnectionUrl;15import java.sql.Connection;16import java.sql.Driver;17import java.sql.DriverManager;18import java.sql.SQLException;19import java.util.Properties;20public class 2 {21 public static void main(String[] args) throws SQLException {22 Driver driver = new ContainerDatabaseDriver();23 Properties properties = new Properties();24 Connection connection = driver.connect(connectionUrl.getJdbcUrl(), properties);25 System.out.println("connection.getMetaData().getURL() = " + connection.getMetaData().getURL());26 System.out.println("connection.getMetaData().getUserName() = " + connection.getMetaData().getUserName());27 }28}29connection.getMetaData().getUserName() = root30import

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.getJdbcUrl());5 }6}7import org.testcontainers.jdbc.ConnectionUrl;8public class 2 {9 public static void main(String[] args) {10 System.out.println(connectionUrl.getInitScriptPath());11 }12}13import org.testcontainers.jdbc.ConnectionUrl;14public class 3 {15 public static void main(String[] args) {16 System.out.println(connectionUrl.getDriverClassName());17 }18}19import org.testcontainers.jdbc.ConnectionUrl;20public class 4 {21 public static void main(String[] args) {22 System.out.println(connectionUrl.getDriverConfiguration().getDriverClassName());23 }24}25import org.testcontainers.jdbc.ConnectionUrl;26public class 5 {27 public static void main(String[] args) {28 System.out.println(connectionUrl.getDriverConfiguration().getDatabaseType());29 }30}

Full Screen

Full Screen

ConnectionUrl

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

ConnectionUrl

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.jdbc.ConnectionUrl;2import java.sql.Connection;3import java.sql.DriverManager;4import java.sql.ResultSet;5import java.sql.Statement;6import java.sql.SQLException;7public class TestContainersJDBCConnectionUrl {8 public static void main(String[] args) throws SQLException {9 Connection connection = DriverManager.getConnection(connectionUrl.toString(), connectionUrl.getUsername(), connectionUrl.getPassword());10 Statement statement = connection.createStatement();11 ResultSet resultSet = statement.executeQuery("SELECT 1");12 while (resultSet.next()) {13 System.out.println(resultSet.getInt(1));14 }15 }16}17import org.testcontainers.jdbc.ConnectionUrl;18import java.sql.Connection;19import java.sql.DriverManager;20import java.sql.ResultSet;21import java.sql.Statement;22import java.sql.SQLException;23public class TestContainersJDBCConnectionUrl {24 public static void main(String[] args) throws SQLException {25 Connection connection = DriverManager.getConnection(connectionUrl.toString(), connectionUrl.getUsername(), connectionUrl.getPassword());26 Statement statement = connection.createStatement();27 ResultSet resultSet = statement.executeQuery("SELECT 1");28 while (resultSet.next()) {29 System.out.println(resultSet.getInt(1));30 }31 }32}

Full Screen

Full Screen

ConnectionUrl

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.jdbc;2import java.sql.Connection;3import java.sql.DriverManager;4import java.sql.SQLException;5import java.sql.Statement;6public class ConnectionUrl {7 public static void main(String[] args) throws SQLException {8 Statement statement = connection.createStatement();9 statement.executeUpdate("INSERT INTO person (name, age) VALUES ('name', 25)");10 statement.close();11 connection.close();12 }13}

Full Screen

Full Screen

ConnectionUrl

Using AI Code Generation

copy

Full Screen

1import java.sql.Connection;2import java.sql.DriverManager;3import java.sql.SQLException;4import java.sql.Statement;5import org.testcontainers.containers.JdbcDatabaseContainer;6import org.testcontainers.containers.MySQLContainer;7import org.testcontainers.jdbc.ConnectionUrl;8public class TestContainerConnectionUrl {9 public static void main(String[] args) throws SQLException {10 JdbcDatabaseContainer<?> container = new MySQLContainer<>()11 .withDatabaseName("test")12 .withUsername("test")13 .withPassword("test");14 container.start();15 String containerJdbcUrl = ConnectionUrl.getJdbcUrl("com.mysql.jdbc.Driver", container.getContainerIpAddress(), container.getFirstMappedPort(), "test");16 System.out.println("JDBC URL for the container is " + containerJdbcUrl);17 Connection connection = DriverManager.getConnection(containerJdbcUrl, "test", "test");18 Statement statement = connection.createStatement();19 statement.executeUpdate("CREATE TABLE PERSON (id INTEGER, name VARCHAR(255))");20 statement.executeUpdate("INSERT INTO PERSON VALUES (1, 'test')");21 statement.close();22 connection.close();23 container.stop();24 }25}

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful