Best Testcontainers-java code snippet using org.testcontainers.utility.JVMHookResourceReaper.performCleanup
Source:ResourceReaper.java  
...82     * Perform a cleanup.83     * @deprecated no longer supported API, use {@link DockerClient} directly84     */85    @Deprecated86    public void performCleanup() {87        registeredContainers.forEach(this::removeContainer);88        registeredNetworks.forEach(this::removeNetwork);89        registeredImages.forEach(this::removeImage);90    }91    /**92     * Register a filter to be cleaned up.93     *94     * @param filter the filter95     * @deprecated only label filter is supported by the prune API, use {@link #registerLabelsFilterForCleanup(Map)}96     */97    @Deprecated98    public void registerFilterForCleanup(List<Map.Entry<String, String>> filter) {99        synchronized (DEATH_NOTE) {100            DEATH_NOTE.add(filter);101            DEATH_NOTE.notifyAll();102        }103    }104    /**105     * Register a label to be cleaned up.106     *107     * @param labels the filter108     */109    public void registerLabelsFilterForCleanup(Map<String, String> labels) {110        registerFilterForCleanup(111            labels112                .entrySet()113                .stream()114                .map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue()))115                .collect(Collectors.toList())116        );117    }118    /**119     * Register a container to be cleaned up, either on explicit call to stopAndRemoveContainer, or at JVM shutdown.120     *121     * @param containerId the ID of the container122     * @param imageName   the image name of the container (used for logging)123     * @deprecated no longer supported API124     */125    @Deprecated126    public void registerContainerForCleanup(String containerId, String imageName) {127        setHook();128        registeredContainers.put(containerId, imageName);129    }130    /**131     * Stop a potentially running container and remove it, including associated volumes.132     *133     * @param containerId the ID of the container134     * @deprecated use {@link DockerClient} directly135     */136    @Deprecated137    public void stopAndRemoveContainer(String containerId) {138        removeContainer(containerId, registeredContainers.get(containerId));139        registeredContainers.remove(containerId);140    }141    /**142     * Stop a potentially running container and remove it, including associated volumes.143     *144     * @param containerId the ID of the container145     * @param imageName   the image name of the container (used for logging)146     * @deprecated use {@link DockerClient} directly147     */148    @Deprecated149    public void stopAndRemoveContainer(String containerId, String imageName) {150        removeContainer(containerId, imageName);151        registeredContainers.remove(containerId);152    }153    private void removeContainer(String containerId, String imageName) {154        boolean running;155        try {156            InspectContainerResponse containerInfo = dockerClient.inspectContainerCmd(containerId).exec();157            running = containerInfo.getState() != null && Boolean.TRUE.equals(containerInfo.getState().getRunning());158        } catch (NotFoundException e) {159            LOGGER.trace("Was going to stop container but it apparently no longer exists: {}", containerId);160            return;161        } catch (Exception e) {162            LOGGER.trace(163                "Error encountered when checking container for shutdown (ID: {}) - it may not have been stopped, or may already be stopped. Root cause: {}",164                containerId,165                Throwables.getRootCause(e).getMessage()166            );167            return;168        }169        if (running) {170            try {171                LOGGER.trace("Stopping container: {}", containerId);172                dockerClient.killContainerCmd(containerId).exec();173                LOGGER.trace("Stopped container: {}", imageName);174            } catch (Exception e) {175                LOGGER.trace(176                    "Error encountered shutting down container (ID: {}) - it may not have been stopped, or may already be stopped. Root cause: {}",177                    containerId,178                    Throwables.getRootCause(e).getMessage()179                );180            }181        }182        try {183            dockerClient.inspectContainerCmd(containerId).exec();184        } catch (Exception e) {185            LOGGER.trace("Was going to remove container but it apparently no longer exists: {}", containerId);186            return;187        }188        try {189            LOGGER.trace("Removing container: {}", containerId);190            dockerClient.removeContainerCmd(containerId).withRemoveVolumes(true).withForce(true).exec();191            LOGGER.debug("Removed container and associated volume(s): {}", imageName);192        } catch (Exception e) {193            LOGGER.trace(194                "Error encountered shutting down container (ID: {}) - it may not have been stopped, or may already be stopped. Root cause: {}",195                containerId,196                Throwables.getRootCause(e).getMessage()197            );198        }199    }200    /**201     * Register a network to be cleaned up at JVM shutdown.202     *203     * @param id   the ID of the network204     * @deprecated no longer supported API205     */206    @Deprecated207    public void registerNetworkIdForCleanup(String id) {208        setHook();209        registeredNetworks.add(id);210    }211    /**212     * Removes a network by ID.213     * @param id214     * @deprecated use {@link DockerClient} directly215     */216    @Deprecated217    public void removeNetworkById(String id) {218        removeNetwork(id);219    }220    private void removeNetwork(String id) {221        try {222            List<Network> networks;223            try {224                // Try to find the network if it still exists225                // Listing by ID first prevents docker-java logging an error if we just go blindly into removeNetworkCmd226                networks = dockerClient.listNetworksCmd().withIdFilter(id).exec();227            } catch (Exception e) {228                LOGGER.trace(229                    "Error encountered when looking up network for removal (name: {}) - it may not have been removed",230                    id231                );232                return;233            }234            // at this point networks should contain either 0 or 1 entries, depending on whether the network exists235            // using a for loop we essentially treat the network like an optional, only applying the removal if it exists236            for (Network network : networks) {237                try {238                    dockerClient.removeNetworkCmd(network.getId()).exec();239                    registeredNetworks.remove(network.getId());240                    LOGGER.debug("Removed network: {}", id);241                } catch (Exception e) {242                    LOGGER.trace(243                        "Error encountered removing network (name: {}) - it may not have been removed",244                        network.getName()245                    );246                }247            }248        } finally {249            registeredNetworks.remove(id);250        }251    }252    /**253     * @deprecated no longer supported API254     */255    @Deprecated256    public void unregisterNetwork(String identifier) {257        registeredNetworks.remove(identifier);258    }259    /**260     * @deprecated no longer supported API261     */262    @Deprecated263    public void unregisterContainer(String identifier) {264        registeredContainers.remove(identifier);265    }266    /**267     * @deprecated no longer supported API268     */269    @Deprecated270    public void registerImageForCleanup(String dockerImageName) {271        setHook();272        registeredImages.add(dockerImageName);273    }274    private void removeImage(String dockerImageName) {275        LOGGER.trace("Removing image tagged {}", dockerImageName);276        try {277            dockerClient.removeImageCmd(dockerImageName).withForce(true).exec();278        } catch (Throwable e) {279            LOGGER.warn("Unable to delete image " + dockerImageName, e);280        }281    }282    void setHook() {283        if (hookIsSet.compareAndSet(false, true)) {284            // If the JVM stops without containers being stopped, try and stop the container.285            Runtime286                .getRuntime()287                .addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, this::performCleanup));288        }289    }290    /**291     *292     * @deprecated internal API293     */294    @Deprecated295    public Map<String, String> getLabels() {296        return MARKER_LABELS;297    }298    /**299     *300     * @deprecated internal API301     */...Source:JVMHookResourceReaper.java  
...13    public void init() {14        setHook();15    }16    @Override17    public synchronized void performCleanup() {18        super.performCleanup();19        synchronized (DEATH_NOTE) {20            DEATH_NOTE.forEach(filters -> prune(PruneType.CONTAINERS, filters));21            DEATH_NOTE.forEach(filters -> prune(PruneType.NETWORKS, filters));22            DEATH_NOTE.forEach(filters -> prune(PruneType.VOLUMES, filters));23            DEATH_NOTE.forEach(filters -> prune(PruneType.IMAGES, filters));24        }25    }26    private void prune(PruneType pruneType, List<Map.Entry<String, String>> filters) {27        String[] labels = filters28            .stream()29            .filter(it -> "label".equals(it.getKey()))30            .map(Map.Entry::getValue)31            .toArray(String[]::new);32        switch (pruneType) {...performCleanup
Using AI Code Generation
1import org.testcontainers.utility.JVMHookResourceReaper;2public class 1 {3    public static void main(String[] args) {4        JVMHookResourceReaper.performCleanup();5    }6}7import org.testcontainers.utility.ResourceReaper;8public class 2 {9    public static void main(String[] args) {10        ResourceReaper.cleanup();11    }12}13import org.testcontainers.utility.ResourceReaper;14public class 3 {15    public static void main(String[] args) {16        ResourceReaper.instance().cleanup();17    }18}19import org.testcontainers.utility.ResourceReaper;20public class 4 {21    public static void main(String[] args) {22        ResourceReaper.instance().cleanup();23    }24}25import org.testcontainers.utility.ResourceReaper;26public class 5 {27    public static void main(String[] args) {28        ResourceReaper.instance().cleanup();29    }30}31import org.testcontainers.utility.ResourceReaper;32public class 6 {33    public static void main(String[] args) {34        ResourceReaper.instance().cleanup();35    }36}37import org.testcontainers.utility.ResourceReaper;38public class 7 {39    public static void main(String[] args) {40        ResourceReaper.instance().cleanup();41    }42}43import org.testcontainers.utility.ResourceReaper;44public class 8 {45    public static void main(String[] args) {46        ResourceReaper.instance().cleanup();47    }48}49import org.testcontainers.utility.ResourceReaper;50public class 9 {51    public static void main(String[] args) {52        ResourceReaper.instance().cleanup();performCleanup
Using AI Code Generation
1import org.testcontainers.utility.JVMHookResourceReaper;2public class 1 {3    public static void main(String[] args) {4        JVMHookResourceReaper.performCleanup();5    }6}7import org.testcontainers.utility.JVMHookResourceReaper;8public class 2 {9    public static void main(String[] args) {10        JVMHookResourceReaper.performCleanup();11    }12}13import org.testcontainers.utility.JVMHookResourceReaper;14public class 3 {15    public static void main(String[] args) {16        JVMHookResourceReaper.performCleanup();17    }18}19import org.testcontainers.utility.JVMHookResourceReaper;20public class 4 {21    public static void main(String[] args) {22        JVMHookResourceReaper.performCleanup();23    }24}25import org.testcontainers.utility.JVMHookResourceReaper;26public class 5 {27    public static void main(String[] args) {28        JVMHookResourceReaper.performCleanup();29    }30}31import org.testcontainers.utility.JVMHookResourceReaper;32public class 6 {33    public static void main(String[] args) {34        JVMHookResourceReaper.performCleanup();35    }36}37import org.testcontainers.utility.JVMHookResourceReaper;38public class 7 {39    public static void main(String[] args) {40        JVMHookResourceReaper.performCleanup();41    }42}43import org.testcontainers.utility.JVMHookResourceReaper;44public class 8 {45    public static void main(String[] args) {46        JVMHookResourceReaper.performCleanup();performCleanup
Using AI Code Generation
1import org.testcontainers.utility.JVMHookResourceReaper;2public class 1 {3    public static void main(String[] args) {4        JVMHookResourceReaper.performCleanup();5    }6}performCleanup
Using AI Code Generation
1public class 1 {2    public static void main(String[] args) {3        JVMHookResourceReaper.performCleanup();4    }5}6public class 2 {7    public static void main(String[] args) {8        JVMHookResourceReaper.performCleanup();9    }10}performCleanup
Using AI Code Generation
1import org.testcontainers.utility.JVMHookResourceReaper;2import org.testcontainers.DockerClientFactory;3import org.testcontainers.utility.ResourceReaper;4import org.testcontainers.utility.TestcontainersConfiguration;5import org.testcontainers.utility.DockerMachineClient;6import org.testcontainers.utility.DockerMachineClientProviderStrategy;7import org.testcontainers.utility.DockerMachineClientProviderStrategy.DockerMachineClientException;performCleanup
Using AI Code Generation
1import org.testcontainers.utility.JVMHookResourceReaper;2import org.testcontainers.utility.ResourceReaper;3public class 1 {4    public static void main(String[] args) {5        ResourceReaper resourceReaper = new JVMHookResourceReaper();6        resourceReaper.performCleanup();7    }8}performCleanup
Using AI Code Generation
1public class 1 {2    public static void main(String args[]) throws Exception {3        JVMHookResourceReaper.performCleanup();4    }5}6public class 2 {7    public static void main(String args[]) throws Exception {8        MountableFile.performCleanup();9    }10}11public class 3 {12    public static void main(String args[]) throws Exception {13        TestcontainersConfiguration.performCleanup();14    }15}16public class 4 {17    public static void main(String args[]) throws Exception {18        TestcontainersConfiguration.performCleanup();19    }20}21public class 5 {22    public static void main(String args[]) throws Exception {23        TestcontainersConfiguration.performCleanup();24    }25}26public class 6 {27    public static void main(String args[]) throws Exception {28        TestcontainersConfiguration.performCleanup();29    }30}31public class 7 {32    public static void main(String args[]) throws Exception {33        TestcontainersConfiguration.performCleanup();34    }35}36public class 8 {37    public static void main(String args[]) throws Exception {38        TestcontainersConfiguration.performCleanup();39    }40}41public class 9 {42    public static void main(String args[]) throws Exception {43        TestcontainersConfiguration.performCleanup();44    }45}performCleanup
Using AI Code Generation
1import org.testcontainers.utility.ResourceReaper;2import org.testcontainers.utility.TestcontainersConfiguration;3public class TestContainersCleanup {4    public static void main(String[] args) {5        ResourceReaper reaper = new ResourceReaper("testcontainers");6        reaper.performCleanup();7    }8}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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
