How to use apply method of org.testcontainers.containers.GenericContainer class

Best Testcontainers-java code snippet using org.testcontainers.containers.GenericContainer.apply

Source:ProxiedClusterDeployment.java Github

copy

Full Screen

1package deployments;2import com.arangodb.reactive.communication.ArangoTopology;3import com.arangodb.reactive.connection.HostDescription;4import org.slf4j.Logger;5import org.slf4j.LoggerFactory;6import org.testcontainers.containers.Container;7import org.testcontainers.containers.GenericContainer;8import org.testcontainers.containers.Network;9import org.testcontainers.containers.ToxiproxyContainer;10import org.testcontainers.containers.output.Slf4jLogConsumer;11import org.testcontainers.containers.wait.strategy.Wait;12import org.testcontainers.utility.MountableFile;13import java.time.Duration;14import java.util.AbstractMap;15import java.util.Collection;16import java.util.List;17import java.util.Map;18import java.util.concurrent.CompletableFuture;19import java.util.function.Consumer;20import java.util.stream.Collectors;21import java.util.stream.IntStream;22public class ProxiedClusterDeployment extends ProxiedContainerDeployment {23 private final Logger log = LoggerFactory.getLogger(ProxiedClusterDeployment.class);24 private final String DOCKER_COMMAND = "arangodb --auth.jwt-secret /jwtSecret ";25 private final List<GenericContainer<?>> agents;26 private final List<GenericContainer<?>> dbServers;27 private final Map<String, GenericContainer<?>> coordinators;28 private volatile Network network;29 private volatile ToxiproxyContainer toxiproxy;30 ProxiedClusterDeployment(int dbServers, int coordinators) {31 agents = IntStream.range(0, 3)32 .mapToObj(this::createAgent)33 .collect(Collectors.toList());34 this.dbServers = IntStream.range(0, dbServers)35 .mapToObj(i -> "dbServer" + i)36 .map(this::createDbServer)37 .collect(Collectors.toList());38 this.coordinators = IntStream.range(0, coordinators)39 .mapToObj(i -> "coordinator" + i)40 .map(name -> new AbstractMap.SimpleEntry<String, GenericContainer<?>>(name, createCoordinator(name)))41 .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));42 }43 @Override44 public List<HostDescription> getHosts() {45 return getProxiedHosts().stream()46 .map(ProxiedHost::getHostDescription)47 .collect(Collectors.toList());48 }49 @Override50 public ArangoTopology getTopology() {51 return ArangoTopology.CLUSTER;52 }53 @Override54 CompletableFuture<ContainerDeployment> asyncStart() {55 return CompletableFuture56 .runAsync(() -> {57 network = Network.newNetwork();58 agents.forEach(agent -> agent.withNetwork(network));59 dbServers.forEach(agent -> agent.withNetwork(network));60 coordinators.values().forEach(agent -> agent.withNetwork(network));61 toxiproxy = new ToxiproxyContainer().withNetwork(network);62 })63 .thenCompose(__ -> CompletableFuture.runAsync(toxiproxy::start).thenAccept(___ -> log.info("READY: toxiproxy")))64 .thenCompose(__ -> performActionOnGroup(agents, GenericContainer::start))65 .thenCompose(__ -> CompletableFuture.allOf(66 performActionOnGroup(dbServers, GenericContainer::start),67 performActionOnGroup(coordinators.values(), GenericContainer::start)68 ))69 .thenCompose(__ -> {70 CompletableFuture<Void> future = new CompletableFuture<>();71 try {72 Container.ExecResult result = coordinators.values().iterator().next().execInContainer(73 "arangosh",74 "--server.authentication=false",75 "--javascript.execute-string=require('org/arangodb/users').update('" + getUser() + "', '" + getPassword() + "')");76 if (result.getExitCode() != 0) {77 throw new RuntimeException(result.getStderr() + "\n" + result.getStdout());78 }79 future.complete(null);80 } catch (Exception e) {81 e.printStackTrace();82 future.completeExceptionally(e);83 }84 return future;85 })86 .thenAccept(__ -> coordinators.keySet().forEach(k -> toxiproxy.getProxy(k, 8529)))87 .thenCompose(__ -> CompletableFuture.runAsync(() -> ContainerUtils.waitForAuthenticationUpdate(this)))88 .thenAccept(__ -> log.info("Cluster is ready!"))89 .thenApply(__ -> this);90 }91 @Override92 CompletableFuture<ContainerDeployment> asyncStop() {93 return CompletableFuture.allOf(94 performActionOnGroup(agents, GenericContainer::stop),95 performActionOnGroup(dbServers, GenericContainer::stop),96 performActionOnGroup(coordinators.values(), GenericContainer::stop)97 )98 .thenAcceptAsync(__ -> network.close())99 .thenAccept(__ -> log.info("Cluster has been shutdown!"))100 .thenApply(__ -> this);101 }102 private GenericContainer<?> createContainer(String name, int port) {103 return new GenericContainer<>(getImage())104 .withEnv("ARANGO_LICENSE_KEY", getLicenseKey())105 .withCopyFileToContainer(MountableFile.forClasspathResource("deployments/jwtSecret"), "/jwtSecret")106 .withExposedPorts(port)107 .withNetworkAliases(name)108 .withLogConsumer(new Slf4jLogConsumer(log).withPrefix("[" + name + "]"))109 .waitingFor(Wait.forLogMessage(".*up and running.*", 1).withStartupTimeout(Duration.ofSeconds(60)));110 }111 private GenericContainer<?> createAgent(int count) {112 String joinParameter = count == 1 ? " " : "--starter.join agent1 ";113 return createContainer("agent" + count, 8531)114 .withCommand(DOCKER_COMMAND + "--cluster.start-dbserver false --cluster.start-coordinator false " + joinParameter);115 }116 private GenericContainer<?> createDbServer(String name) {117 return createContainer(name, 8530)118 .withCommand(DOCKER_COMMAND + "--cluster.start-dbserver true --cluster.start-coordinator false --starter.join agent1");119 }120 private GenericContainer<?> createCoordinator(String name) {121 return createContainer(name, 8529)122 .withCommand(DOCKER_COMMAND + "--cluster.start-dbserver false --cluster.start-coordinator true --starter.join agent1");123 }124 private CompletableFuture<Void> performActionOnGroup(Collection<GenericContainer<?>> group, Consumer<GenericContainer<?>> action) {125 return CompletableFuture.allOf(126 group.stream()127 .map(it -> CompletableFuture.runAsync(() -> action.accept(it)))128 .toArray(CompletableFuture[]::new)129 );130 }131 @Override132 public List<ProxiedHost> getProxiedHosts() {133 return coordinators.keySet().stream()134 .map(genericContainer -> ProxiedHost.builder()135 .proxiedHost(genericContainer)136 .proxiedPort(8529)137 .toxiproxy(toxiproxy)138 .build())139 .collect(Collectors.toList());140 }141}...

Full Screen

Full Screen

Source:Container.java Github

copy

Full Screen

...48 return container;49 };50 }51 @Override52 public Statement apply(Statement base, Description description) {53 try {54 DockerClientFactory.instance().client();55 }56 catch (Throwable ex) {57 return new SkipStatement();58 }59 this.container = this.containerFactory.get();60 return ((FailureDetectingExternalResource) this.container).apply(base, description);61 }62 public int getMappedPort() {63 return this.container.getMappedPort(this.port);64 }65 private static class SkipStatement extends Statement {66 @Override67 public void evaluate() {68 throw new AssumptionViolatedException("Could not find a valid Docker environment.");69 }70 }71}...

Full Screen

Full Screen

apply

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.containers;2import org.testcontainers.containers.output.Slf4jLogConsumer;3import org.testcontainers.containers.wait.strategy.Wait;4import org.testcontainers.images.builder.ImageFromDockerfile;5import org.testcontainers.utility.MountableFile;6import java.io.File;7import java.io.IOException;8import java.nio.file.Files;9import java.nio.file.Path;10import java.nio.file.Paths;11import java.util.concurrent.TimeUnit;12public class GenericContainerTest {13 public static void main(String[] args) throws IOException {14 String path = "C:/Users/akash/Desktop/1.java";15 Path path1 = Paths.get(path);16 String fileName = path1.getFileName().toString();17 Path path2 = Paths.get("C:/Users/akash/Desktop/1");18 Files.createDirectories(path2);19 Path path3 = Paths.get("C:/Users/akash/Desktop/1/" + fileName);20 Files.copy(path1, path3);21 "CMD [\"java\", \"" + fileName.substring(0, fileName.indexOf(".")) + "\"]";22 Path path4 = Paths.get("C:/Users/akash/Desktop/1/Dockerfile");23 Files.write(path4, dockerFile.getBytes());24 String dockerfilePath = "C:/Users/akash/Desktop/1";25 ImageFromDockerfile imageFromDockerfile = new ImageFromDockerfile()26 .withFileFromPath(".", Paths.get(dockerfilePath));27 GenericContainer container = new GenericContainer(imageFromDockerfile)28 .withExposedPorts(8080)29 .waitingFor(Wait.forHttp("/").forPort(8080).forStatusCode(200).withStartupTimeout(Duration.of(20, TimeUnit.SECONDS)))30 .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("testcontainers")));31 container.start();32 System.out.println(container.getMappedPort(8080));33 container.stop();34 Files.delete(path3);35 Files.delete(path4);36 Files.delete(path2);37 }38}

Full Screen

Full Screen

apply

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.containers;2import org.testcontainers.containers.output.Slf4jLogConsumer;3import org.testcontainers.containers.wait.strategy.Wait;4import org.testcontainers.containers.wait.strategy.WaitAllStrategy;5import org.testcontainers.containers.wait.strategy.WaitStrategy;6import org.testcontainers.utility.MountableFile;7import org.testcontainers.utility.TestcontainersConfiguration;8import org.testcontainers.utility.DockerImageName;9import org.testcontainers.utility.ResourceReaper;10import com.github.dockerjava.api.model.Capability;11import com.github.dockerjav

Full Screen

Full Screen

apply

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.containers;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.containers.Network;4import org.testcontainers.containers.output.Slf4jLogConsumer;5import org.testcontainers.containers.wait.strategy.Wait;6import org.testcontainers.utility.DockerImageName;7import org.slf4j.Logger;8import org.slf4j.LoggerFactory;9public class GenericContainerDemo {10 private static final Logger logger = LoggerFactory.getLogger(GenericContainerDemo.class);11 public static void main(String[] args) {12 try (Network network = Network.newNetwork()) {13 GenericContainer<?> container = new GenericContainer<>(DockerImageName.parse("ubuntu:latest"))14 .withNetwork(network)15 .withNetworkAliases("mycontainer")16 .withExposedPorts(8080)17 .withCommand("tail -f /dev/null")18 .waitingFor(Wait.forListeningPort())19 .withLogConsumer(new Slf4jLogConsumer(logger));20 container.start();21 System.out.println("Container started");22 System.out.println("Container IP: " + container.getContainerIpAddress());23 System.out.println("Container Port: " + container.getMappedPort(8080));24 System.out.println("Container Hostname: " + container.getContainerInfo().getNetworkSettings().getNetworks().get("bridge").getIpAddress());25 System.out.println("Container Hostname: " + container.getContainerInfo().getNetworkSettings().getNetworks().get("bridge").getAliases());26 System.out.println("Container Hostname: " + container.getContainerInfo().getNetworkSettings().getNetworks().get("bridge").getNetworkID());27 }28 }29}

Full Screen

Full Screen

apply

Using AI Code Generation

copy

Full Screen

1package org.testcontainers;2import java.io.IOException;3import java.util.concurrent.TimeUnit;4import org.testcontainers.containers.GenericContainer;5import org.testcontainers.containers.output.Slf4jLogConsumer;6import org.slf4j.Logger;7import org.slf4j.LoggerFactory;8public class TestContainer {9 private static final Logger LOG = LoggerFactory.getLogger(TestContainer.class);10 public static void main(String[] args) throws IOException, InterruptedException {11 try (GenericContainer container = new GenericContainer("alpine:3.8")12 .withCommand("sleep", "300")13 .withLogConsumer(new Slf4jLogConsumer(LOG))) {14 container.start();15 container.execInContainer("echo", "hello world");16 }17 }18}19package org.testcontainers;20import java.io.IOException;21import java.util.concurrent.TimeUnit;22import org.testcontainers.containers.GenericContainer;23import org.testcontainers.containers.output.Slf4jLogConsumer;24import org.slf4j.Logger;25import org.slf4j.LoggerFactory;26public class TestContainer {27 private static final Logger LOG = LoggerFactory.getLogger(TestContainer.class);28 public static void main(String[] args) throws IOException, InterruptedException {29 try (GenericContainer container = new GenericContainer("alpine:3.8")30 .withCommand("sleep", "300")31 .withLogConsumer(new Slf4jLogConsumer(LOG))) {32 container.start();33 container.apply((c) -> {34 c.execInContainer("echo", "hello world");35 return null;36 });37 }38 }39}

Full Screen

Full Screen

apply

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.GenericContainer;2public class TestContainersExample {3 public static void main(String[] args) {4 GenericContainer container = new GenericContainer("alpine:3.8")5 .withCommand("echo hello world")6 .withExposedPorts(80);7 container.start();8 String containerId = container.getContainerId();9 System.out.println("containerId = " + containerId);10 String ipAddress = container.getContainerIpAddress();11 System.out.println("ipAddress = " + ipAddress);

Full Screen

Full Screen

apply

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.GenericContainer;2public class 1 {3 public static void main(String[] args) {4 GenericContainer container = new GenericContainer("alpine:3.9.3")5 .withCommand("sh", "-c", "echo hello world");6 container.start();7 String output = container.apply(container -> {8 return container.execInContainer("cat", "/test").getStdout();9 });10 System.out.println(output);11 }12}13import org.testcontainers.containers.GenericContainer;14public class 2 {15 public static void main(String[] args) {16 GenericContainer container = new GenericContainer("alpine:3.9.3")17 .withCommand("sh", "-c", "echo hello world");18 container.start();19 String output = container.apply(container -> {20 return container.execInContainer("cat", "/test").getStdout();21 });22 System.out.println(output);23 }24}25import org.testcontainers.containers.GenericContainer;26public class 3 {27 public static void main(String[] args) {28 GenericContainer container = new GenericContainer("alpine:3.9.3")29 .withCommand("sh", "-c", "echo hello world");30 container.start();31 String output = container.apply(container -> {32 return container.execInContainer("cat", "/test").getStdout();33 });34 System.out.println(output);35 }36}37import org.testcontainers.containers.GenericContainer;38public class 4 {39 public static void main(String[] args) {40 GenericContainer container = new GenericContainer("alpine:3.9.3")41 .withCommand("sh", "-c", "echo hello world");42 container.start();43 String output = container.apply(container -> {

Full Screen

Full Screen

apply

Using AI Code Generation

copy

Full Screen

1import java.io.IOException;2import java.util.function.Consumer;3import org.testcontainers.containers.GenericContainer;4import org.testcontainers.containers.output.OutputFrame;5import org.testcontainers.containers.output.WaitingConsumer;6public class Container {7 public static void main(String[] args) throws IOException {8 WaitingConsumer consumer = new WaitingConsumer();9 GenericContainer container = new GenericContainer("alpine:3.6").withCommand("sh", "-c", "echo hello world");10 container.withLogConsumer(consumer);11 container.start();12 Consumer<OutputFrame> logConsumer = new Consumer<OutputFrame>() {13 public void accept(OutputFrame outputFrame) {14 System.out.println(outputFrame.getUtf8String());15 }16 };17 consumer.waitUntil(frame -> frame.getUtf8String().contains("hello world"), logConsumer);18 container.stop();19 }20}

Full Screen

Full Screen

apply

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.containers.output.Slf4jLogConsumer;3public class 1 {4 public static void main(String[] args) {5 GenericContainer container = new GenericContainer("openjdk:8-jre-alpine")6 .withCommand("java -version")7 .withLogConsumer(new Slf4jLogConsumer(1.class));8 container.start();9 container.stop();10 }11}12import org.testcontainers.containers.GenericContainer;13import org.testcontainers.containers.output.Slf4jLogConsumer;14public class 2 {15 public static void main(String[] args) {16 GenericContainer container = new GenericContainer("openjdk:8-jre-alpine")17 .withCommand("java -version")18 .withLogConsumer(new Slf4jLogConsumer(2.class));19 container.start();20 container.stop();21 }22}23import org.testcontainers.containers.GenericContainer;24import org.testcontainers.containers.output.Slf4jLogConsumer;25public class 3 {26 public static void main(String[] args) {27 GenericContainer container = new GenericContainer("openjdk:8-jre-alpine")28 .withCommand("java -version")29 .withLogConsumer(new Slf4jLog

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