How to use getClientForConfig method of org.testcontainers.dockerclient.DockerClientProviderStrategy class

Best Testcontainers-java code snippet using org.testcontainers.dockerclient.DockerClientProviderStrategy.getClientForConfig

Source:DockerClientProviderStrategy.java Github

copy

Full Screen

...38 */39@Slf4j40public abstract class DockerClientProviderStrategy {41 @Getter(lazy = true)42 private final DockerClient dockerClient = getClientForConfig(getTransportConfig());43 private String dockerHostIpAddress;44 private final RateLimiter PING_RATE_LIMITER = RateLimiterBuilder.newBuilder()45 .withRate(10, TimeUnit.SECONDS)46 .withConstantThroughput()47 .build();48 private static final AtomicBoolean FAIL_FAST_ALWAYS = new AtomicBoolean(false);49 /**50 * @return a short textual description of the strategy51 */52 public abstract String getDescription();53 protected boolean isApplicable() {54 return true;55 }56 protected boolean isPersistable() {57 return true;58 }59 /**60 * @return highest to lowest priority value61 */62 protected int getPriority() {63 return 0;64 }65 /**66 * @throws InvalidConfigurationException if this strategy fails67 */68 public abstract TransportConfig getTransportConfig() throws InvalidConfigurationException;69 /**70 * @return a usable, tested, Docker client configuration for the host system environment71 *72 * @deprecated use {@link #getDockerClient()}73 */74 @Deprecated75 public DockerClient getClient() {76 DockerClient dockerClient = getDockerClient();77 try {78 Unreliables.retryUntilSuccess(30, TimeUnit.SECONDS, () -> {79 return PING_RATE_LIMITER.getWhenReady(() -> {80 log.debug("Pinging docker daemon...");81 dockerClient.pingCmd().exec();82 log.debug("Pinged");83 return true;84 });85 });86 } catch (TimeoutException e) {87 IOUtils.closeQuietly(dockerClient);88 throw e;89 }90 return dockerClient;91 }92 /**93 * Determine the right DockerClientConfig to use for building clients by trial-and-error.94 *95 * @return a working DockerClientConfig, as determined by successful execution of a ping command96 */97 public static DockerClientProviderStrategy getFirstValidStrategy(List<DockerClientProviderStrategy> strategies) {98 if (FAIL_FAST_ALWAYS.get()) {99 throw new IllegalStateException("Previous attempts to find a Docker environment failed. Will not retry. Please see logs and check configuration");100 }101 List<String> configurationFailures = new ArrayList<>();102 List<DockerClientProviderStrategy> allStrategies = new ArrayList<>();103 // The environment has the highest priority104 allStrategies.add(new EnvironmentAndSystemPropertyClientProviderStrategy());105 // Next strategy to try out is the one configured using the Testcontainers configuration mechanism106 loadConfiguredStrategy().ifPresent(allStrategies::add);107 // Finally, add all other strategies ordered by their internal priority108 strategies109 .stream()110 .sorted(Comparator.comparing(DockerClientProviderStrategy::getPriority).reversed())111 .collect(Collectors.toCollection(() -> allStrategies));112 Predicate<DockerClientProviderStrategy> distinctStrategyClassPredicate = new Predicate<DockerClientProviderStrategy>() {113 final Set<Class<? extends DockerClientProviderStrategy>> classes = new HashSet<>();114 @Override115 public boolean test(DockerClientProviderStrategy dockerClientProviderStrategy) {116 return classes.add(dockerClientProviderStrategy.getClass());117 }118 };119 return allStrategies120 .stream()121 .filter(distinctStrategyClassPredicate)122 .filter(DockerClientProviderStrategy::isApplicable)123 .filter(strategy -> tryOutStrategy(configurationFailures, strategy))124 .findFirst()125 .orElseThrow(() -> {126 log.error("Could not find a valid Docker environment. Please check configuration. Attempted configurations were:");127 for (String failureMessage : configurationFailures) {128 log.error(" " + failureMessage);129 }130 log.error("As no valid configuration was found, execution cannot continue");131 FAIL_FAST_ALWAYS.set(true);132 return new IllegalStateException("Could not find a valid Docker environment. Please see logs and check configuration");133 });134 }135 private static boolean tryOutStrategy(List<String> configurationFailures, DockerClientProviderStrategy strategy) {136 try {137 log.debug("Trying out strategy: {}", strategy.getClass().getSimpleName());138 DockerClient dockerClient = strategy.getDockerClient();139 Info info;140 try {141 info = Unreliables.retryUntilSuccess(TestcontainersConfiguration.getInstance().getClientPingTimeout(), TimeUnit.SECONDS, () -> {142 return strategy.PING_RATE_LIMITER.getWhenReady(() -> {143 log.debug("Pinging docker daemon...");144 return dockerClient.infoCmd().exec();145 });146 });147 } catch (TimeoutException e) {148 IOUtils.closeQuietly(dockerClient);149 throw e;150 }151 log.info("Found Docker environment with {}", strategy.getDescription());152 log.debug(153 "Transport type: '{}', Docker host: '{}'",154 TestcontainersConfiguration.getInstance().getTransportType(),155 strategy.getTransportConfig().getDockerHost()156 );157 log.debug("Checking Docker OS type for {}", strategy.getDescription());158 String osType = info.getOsType();159 if (StringUtils.isBlank(osType)) {160 log.warn("Could not determine Docker OS type");161 } else if (!osType.equals("linux")) {162 log.warn("{} is currently not supported", osType);163 throw new InvalidConfigurationException(osType + " containers are currently not supported");164 }165 if (strategy.isPersistable()) {166 TestcontainersConfiguration.getInstance().updateUserConfig("docker.client.strategy", strategy.getClass().getName());167 }168 return true;169 } catch (Exception | ExceptionInInitializerError | NoClassDefFoundError e) {170 @Nullable String throwableMessage = e.getMessage();171 @SuppressWarnings("ThrowableResultOfMethodCallIgnored")172 Throwable rootCause = Throwables.getRootCause(e);173 @Nullable String rootCauseMessage = rootCause.getMessage();174 String failureDescription;175 if (throwableMessage != null && throwableMessage.equals(rootCauseMessage)) {176 failureDescription = String.format("%s: failed with exception %s (%s)",177 strategy.getClass().getSimpleName(),178 e.getClass().getSimpleName(),179 throwableMessage);180 } else {181 failureDescription = String.format("%s: failed with exception %s (%s). Root cause %s (%s)",182 strategy.getClass().getSimpleName(),183 e.getClass().getSimpleName(),184 throwableMessage,185 rootCause.getClass().getSimpleName(),186 rootCauseMessage187 );188 }189 configurationFailures.add(failureDescription);190 log.debug(failureDescription);191 return false;192 }193 }194 private static Optional<? extends DockerClientProviderStrategy> loadConfiguredStrategy() {195 String configuredDockerClientStrategyClassName = TestcontainersConfiguration.getInstance().getDockerClientStrategyClassName();196 return Stream197 .of(configuredDockerClientStrategyClassName)198 .filter(Objects::nonNull)199 .flatMap(it -> {200 try {201 Class<? extends DockerClientProviderStrategy> strategyClass = (Class) Thread.currentThread().getContextClassLoader().loadClass(it);202 return Stream.of(strategyClass.newInstance());203 } catch (ClassNotFoundException e) {204 log.warn("Can't instantiate a strategy from {} (ClassNotFoundException). " +205 "This probably means that cached configuration refers to a client provider " +206 "class that is not available in this version of Testcontainers. Other " +207 "strategies will be tried instead.", it);208 return Stream.empty();209 } catch (InstantiationException | IllegalAccessException e) {210 log.warn("Can't instantiate a strategy from {}", it, e);211 return Stream.empty();212 }213 })214 // Ignore persisted strategy if it's not persistable anymore215 .filter(DockerClientProviderStrategy::isPersistable)216 .peek(strategy -> log.info("Loaded {} from ~/.testcontainers.properties, will try it first", strategy.getClass().getName()))217 .findFirst();218 }219 public static DockerClient getClientForConfig(TransportConfig transportConfig) {220 final DockerHttpClient dockerHttpClient;221 String transportType = TestcontainersConfiguration.getInstance().getTransportType();222 switch (transportType) {223 case "okhttp":224 dockerHttpClient = new OkDockerHttpClient.Builder()225 .dockerHost(transportConfig.getDockerHost())226 .sslConfig(transportConfig.getSslConfig())227 .build();228 break;229 case "httpclient5":230 dockerHttpClient = new ZerodepDockerHttpClient.Builder()231 .dockerHost(transportConfig.getDockerHost())232 .sslConfig(transportConfig.getSslConfig())233 .build();...

Full Screen

Full Screen

getClientForConfig

Using AI Code Generation

copy

Full Screen

1import com.github.dockerjava.api.DockerClient;2import com.github.dockerjava.core.DockerClientConfig;3import com.github.dockerjava.core.DockerClientImpl;4import org.testcontainers.DockerClientFactory;5import org.testcontainers.dockerclient.DockerClientProviderStrategy;6public class DockerClientTest {7 public static void main(String[] args) {8 DockerClientProviderStrategy strategy = DockerClientFactory.instance().strategy();9 DockerClientConfig config = strategy.getDynamicConfig();10 DockerClient dockerClient = DockerClientImpl.getInstance(config);11 System.out.println(dockerClient.pingCmd().exec());12 }13}

Full Screen

Full Screen

getClientForConfig

Using AI Code Generation

copy

Full Screen

1 Class<?> clazz = Class.forName("org.testcontainers.dockerclient.DockerClientProviderStrategy");2 Method getClientForConfig = clazz.getDeclaredMethod("getClientForConfig", DockerClientConfig.class, DockerClientStrategy.class);3 getClientForConfig.setAccessible(true);4 DockerClient client = (DockerClient) getClientForConfig.invoke(null, config, strategy);5 return client;6}

Full Screen

Full Screen

getClientForConfig

Using AI Code Generation

copy

Full Screen

1DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();2DockerClient dockerClient = strategy.getClientForConfig(config);3DockerClient dockerClient = strategy.getClientForConfig(config);4DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();5DockerClient dockerClient = strategy.getClientForConfig(config);6DockerClient dockerClient = strategy.getClientForConfig(config);7DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();8DockerClient dockerClient = strategy.getClientForConfig(config);9DockerClient dockerClient = strategy.getClientForConfig(config);10DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();11DockerClient dockerClient = strategy.getClientForConfig(config);12DockerClient dockerClient = strategy.getClientForConfig(config);13DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();14DockerClient dockerClient = strategy.getClientForConfig(config);15DockerClient dockerClient = strategy.getClientForConfig(config);16DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();17DockerClient dockerClient = strategy.getClientForConfig(config);18DockerClient dockerClient = strategy.getClientForConfig(config);19DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();20DockerClient dockerClient = strategy.getClientForConfig(config

Full Screen

Full Screen

getClientForConfig

Using AI Code Generation

copy

Full Screen

1public class DockerClientProviderStrategyTest {2 public void testGetClientForConfig() throws Exception {3 DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();4 DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()5 .build();6 DockerClient client = strategy.getClientForConfig(config);7 assertNotNull(client);8 }9}10[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ test ---11[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ test ---12[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ test ---13[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ test ---14[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ test ---15[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ test ---

Full Screen

Full Screen

getClientForConfig

Using AI Code Generation

copy

Full Screen

1def dockerClient = DockerClientProviderStrategy.getClientForConfig()2def listContainersCmd = dockerClient.listContainersCmd()3def showAllContainers = listContainersCmd.withShowAll(true)4def showAllContainersExec = showAllContainers.exec()5def showAllContainersSize = showAllContainersExec.size()6def showAllContainersSizeString = showAllContainersSize.toString()7def showAllContainersString = showAllContainersExec.toString()8def showAllContainersStringSplitComma = showAllContainersString.split(",")9def showAllContainersStringSplitCommaSize = showAllContainersStringSplitComma.size()10def showAllContainersStringSplitCommaSizeString = showAllContainersStringSplitCommaSize.toString()11def showAllContainersStringSplitCommaSizeStringEqualsShowAllContainersSizeString = showAllContainersStringSplitCommaSizeString.equals(showAllContainersSizeString)12def showAllContainersStringSplitCommaSizeStringEqualsShowAllContainersSizeStringString = showAllContainersStringSplitCommaSizeStringEqualsShowAllContainersSizeString.toString()

Full Screen

Full Screen

getClientForConfig

Using AI Code Generation

copy

Full Screen

1DockerClientConfig dockerClientConfig = DockerClientConfig.createDefaultConfigBuilder()2.build();3DockerClient dockerClient = DockerClientProviderStrategy.getClientForConfig(dockerClientConfig);4DockerClientConfig dockerClientConfig = DockerClientConfig.createDefaultConfigBuilder()5.build();6DockerClient dockerClient = DockerClientProviderStrategy.getClientForConfig(dockerClientConfig);7DockerClientConfig dockerClientConfig = DockerClientConfig.createDefaultConfigBuilder()8.build();9DockerClient dockerClient = DockerClientProviderStrategy.getClientForConfig(dockerClientConfig);10DockerClientConfig dockerClientConfig = DockerClientConfig.createDefaultConfigBuilder()11.build();12DockerClient dockerClient = DockerClientProviderStrategy.getClientForConfig(dockerClientConfig);13DockerClientConfig dockerClientConfig = DockerClientConfig.createDefaultConfigBuilder()14.build();15DockerClient dockerClient = DockerClientProviderStrategy.getClientForConfig(dockerClientConfig

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