diff --git a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerCreate.java b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerCreate.java index 3b5ee1260f..f14f7ef0fe 100644 --- a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerCreate.java +++ b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerCreate.java @@ -16,21 +16,20 @@ package org.citrusframework.docker.command; -import java.util.stream.Stream; - -import org.citrusframework.context.TestContext; -import org.citrusframework.docker.actions.DockerExecuteAction; -import org.citrusframework.docker.client.DockerClient; -import org.citrusframework.docker.message.DockerMessageHeaders; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.command.CreateContainerResponse; -import com.github.dockerjava.api.command.InspectContainerCmd; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.model.Capability; import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.PortBinding; import com.github.dockerjava.api.model.Ports; import com.github.dockerjava.api.model.Volume; +import org.citrusframework.context.TestContext; +import org.citrusframework.docker.actions.DockerExecuteAction; +import org.citrusframework.docker.client.DockerClient; +import org.citrusframework.docker.message.DockerMessageHeaders; + +import java.util.stream.Stream; import static com.github.dockerjava.api.model.ExposedPort.tcp; import static com.github.dockerjava.api.model.ExposedPort.udp; @@ -51,30 +50,34 @@ public ContainerCreate() { } @Override - public void execute(DockerClient dockerClient, TestContext context) { - CreateContainerCmd command = dockerClient.getEndpointConfiguration().getDockerClient().createContainerCmd(getImageId(context)); + public void execute(DockerClient dockerClient, TestContext testContext) { + try (var command = dockerClient.getEndpointConfiguration().getDockerClient().createContainerCmd(getImageId(testContext))) { + executeDockerCommand(dockerClient, command, testContext); + } + } + private void executeDockerCommand(DockerClient dockerClient, CreateContainerCmd command, TestContext testContext) { if (hasParameter("name")) { - command.withName(getParameter("name", context)); + command.withName(getParameter("name", testContext)); } if (hasParameter("attach-stderr")) { - command.withAttachStderr(Boolean.valueOf(getParameter("attach-stderr", context))); + command.withAttachStderr(Boolean.valueOf(getParameter("attach-stderr", testContext))); } if (hasParameter("attach-stdin")) { - command.withAttachStdin(Boolean.valueOf(getParameter("attach-stdin", context))); + command.withAttachStdin(Boolean.valueOf(getParameter("attach-stdin", testContext))); } if (hasParameter("attach-stdout")) { - command.withAttachStdout(Boolean.valueOf(getParameter("attach-stdout", context))); + command.withAttachStdout(Boolean.valueOf(getParameter("attach-stdout", testContext))); } if (hasParameter("capability-add")) { if (getParameters().get("capability-add") instanceof Capability[]) { command.withCapAdd((Capability[]) getParameters().get("capability-add")); } else { - command.withCapAdd(getCapabilities("capability-add", context)); + command.withCapAdd(getCapabilities("capability-add", testContext)); } } @@ -82,46 +85,46 @@ public void execute(DockerClient dockerClient, TestContext context) { if (getParameters().get("capability-drop") instanceof Capability[]) { command.withCapAdd((Capability[]) getParameters().get("capability-drop")); } else { - command.withCapDrop(getCapabilities("capability-drop", context)); + command.withCapDrop(getCapabilities("capability-drop", testContext)); } } if (hasParameter("domain-name")) { - command.withDomainName(getParameter("domain-name", context)); + command.withDomainName(getParameter("domain-name", testContext)); } if (hasParameter("cmd")) { if (getParameters().get("cmd") instanceof String[] - || getParameters().get("cmd") instanceof Capability[]) { + || getParameters().get("cmd") instanceof Capability[]) { command.withCmd((String[]) getParameters().get("cmd")); } else { - command.withCmd(getParameter("cmd", context).split(DELIMITER)); + command.withCmd(getParameter("cmd", testContext).split(DELIMITER)); } } if (hasParameter("env")) { if (getParameters().get("env") instanceof String[] - || getParameters().get("env") instanceof Capability[]) { + || getParameters().get("env") instanceof Capability[]) { command.withEnv((String[]) getParameters().get("env")); } else { - command.withEnv(getParameter("env", context).split(DELIMITER)); + command.withEnv(getParameter("env", testContext).split(DELIMITER)); } } if (hasParameter("entrypoint")) { - command.withEntrypoint(getParameter("entrypoint", context)); + command.withEntrypoint(getParameter("entrypoint", testContext)); } if (hasParameter("hostname")) { - command.withHostName(getParameter("hostname", context)); + command.withHostName(getParameter("hostname", testContext)); } if (hasParameter("port-specs")) { if (getParameters().get("port-specs") instanceof String[] - || getParameters().get("port-specs") instanceof Capability[]) { + || getParameters().get("port-specs") instanceof Capability[]) { command.withPortSpecs((String[]) getParameters().get("port-specs")); } else { - command.withPortSpecs(getParameter("port-specs", context).split(DELIMITER)); + command.withPortSpecs(getParameter("port-specs", testContext).split(DELIMITER)); } } @@ -130,7 +133,7 @@ public void execute(DockerClient dockerClient, TestContext context) { if (getParameters().get("exposed-ports") instanceof ExposedPort[]) { exposedPorts = (ExposedPort[]) getParameters().get("exposed-ports"); } else { - exposedPorts = getExposedPorts(getParameter("exposed-ports", context), context); + exposedPorts = getExposedPorts(getParameter("exposed-ports", testContext), testContext); } command.withExposedPorts(exposedPorts); } @@ -141,33 +144,34 @@ public void execute(DockerClient dockerClient, TestContext context) { } if (getParameters().get("port-bindings") instanceof PortBinding[]) { command.withPortBindings((PortBinding[]) getParameters().get("port-bindings")); } else { - command.withPortBindings(getPortBindings(getParameter("port-bindings", context), exposedPorts, context)); + command.withPortBindings(getPortBindings(getParameter("port-bindings", testContext), exposedPorts, testContext)); } } else if (exposedPorts.length > 0) { - command.withPortBindings(getPortBindings("", exposedPorts, context)); + command.withPortBindings(getPortBindings("", exposedPorts, testContext)); } if (hasParameter("volumes")) { if (getParameters().get("volumes") instanceof Volume[] - || getParameters().get("volumes") instanceof ExposedPort[]) { + || getParameters().get("volumes") instanceof ExposedPort[]) { command.withVolumes((Volume[]) getParameters().get("volumes")); } else { - command.withVolumes(getVolumes(context)); + command.withVolumes(getVolumes(testContext)); } } if (hasParameter("working-dir")) { - command.withWorkingDir(getParameter("working-dir", context)); + command.withWorkingDir(getParameter("working-dir", testContext)); } CreateContainerResponse response = command.exec(); - context.setVariable(DockerMessageHeaders.CONTAINER_ID, response.getId()); + testContext.setVariable(DockerMessageHeaders.CONTAINER_ID, response.getId()); setCommandResult(response); if (!hasParameter("name")) { - InspectContainerCmd inspect = dockerClient.getEndpointConfiguration().getDockerClient().inspectContainerCmd(response.getId()); - InspectContainerResponse inspectResponse = inspect.exec(); - context.setVariable(DockerMessageHeaders.CONTAINER_NAME, inspectResponse.getName().substring(1)); + try (var inspect = dockerClient.getEndpointConfiguration().getDockerClient().inspectContainerCmd(response.getId())) { + InspectContainerResponse inspectResponse = inspect.exec(); + testContext.setVariable(DockerMessageHeaders.CONTAINER_NAME, inspectResponse.getName().substring(1)); + } } } diff --git a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerInspect.java b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerInspect.java index fe0382a0ad..6e3cf200de 100644 --- a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerInspect.java +++ b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerInspect.java @@ -16,11 +16,10 @@ package org.citrusframework.docker.command; +import com.github.dockerjava.api.command.InspectContainerResponse; import org.citrusframework.context.TestContext; import org.citrusframework.docker.actions.DockerExecuteAction; import org.citrusframework.docker.client.DockerClient; -import com.github.dockerjava.api.command.InspectContainerCmd; -import com.github.dockerjava.api.command.InspectContainerResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,12 +40,13 @@ public ContainerInspect() { @Override public void execute(DockerClient dockerClient, TestContext context) { - InspectContainerCmd command = dockerClient.getEndpointConfiguration().getDockerClient().inspectContainerCmd(getContainerId(context)); - InspectContainerResponse response = command.exec(); + try (var command = dockerClient.getEndpointConfiguration().getDockerClient().inspectContainerCmd(getContainerId(context))) { + InspectContainerResponse response = command.exec(); - setCommandResult(response); + setCommandResult(response); - logger.debug(response.toString()); + logger.debug(response.toString()); + } } /** diff --git a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerRemove.java b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerRemove.java index c0e4c5ae81..6f885aff63 100644 --- a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerRemove.java +++ b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerRemove.java @@ -16,10 +16,9 @@ package org.citrusframework.docker.command; +import com.github.dockerjava.api.model.ResponseItem; import org.citrusframework.context.TestContext; import org.citrusframework.docker.client.DockerClient; -import com.github.dockerjava.api.command.RemoveContainerCmd; -import com.github.dockerjava.api.model.ResponseItem; /** * @since 2.4 @@ -36,15 +35,15 @@ public ContainerRemove() { @Override public void execute(DockerClient dockerClient, TestContext context) { - RemoveContainerCmd command = dockerClient.getEndpointConfiguration().getDockerClient().removeContainerCmd(getContainerId(context)); + try (var command = dockerClient.getEndpointConfiguration().getDockerClient().removeContainerCmd(getContainerId(context))) { + if (hasParameter("force")) { + command.withForce(Boolean.valueOf(getParameter("force", context))); + } - if (hasParameter("force")) { - command.withForce(Boolean.valueOf(getParameter("force", context))); - } + command.exec(); - command.exec(); - - setCommandResult(success()); + setCommandResult(success()); + } } /** diff --git a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerStart.java b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerStart.java index d65da1295e..952a77b778 100644 --- a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerStart.java +++ b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerStart.java @@ -16,11 +16,10 @@ package org.citrusframework.docker.command; +import com.github.dockerjava.api.model.ResponseItem; import org.citrusframework.context.TestContext; import org.citrusframework.docker.actions.DockerExecuteAction; import org.citrusframework.docker.client.DockerClient; -import com.github.dockerjava.api.command.StartContainerCmd; -import com.github.dockerjava.api.model.ResponseItem; /** * @since 2.4 @@ -37,10 +36,11 @@ public ContainerStart() { @Override public void execute(DockerClient dockerClient, TestContext context) { - StartContainerCmd command = dockerClient.getEndpointConfiguration().getDockerClient().startContainerCmd(getContainerId(context)); - command.exec(); + try (var command = dockerClient.getEndpointConfiguration().getDockerClient().startContainerCmd(getContainerId(context))) { + command.exec(); - setCommandResult(success()); + setCommandResult(success()); + } } /** diff --git a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerStop.java b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerStop.java index c871c93ec4..afcc9519cb 100644 --- a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerStop.java +++ b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerStop.java @@ -16,11 +16,10 @@ package org.citrusframework.docker.command; +import com.github.dockerjava.api.model.ResponseItem; import org.citrusframework.context.TestContext; import org.citrusframework.docker.actions.DockerExecuteAction; import org.citrusframework.docker.client.DockerClient; -import com.github.dockerjava.api.command.StopContainerCmd; -import com.github.dockerjava.api.model.ResponseItem; /** * @since 2.4 @@ -37,10 +36,11 @@ public ContainerStop() { @Override public void execute(DockerClient dockerClient, TestContext context) { - StopContainerCmd command = dockerClient.getEndpointConfiguration().getDockerClient().stopContainerCmd(getContainerId(context)); - command.exec(); + try (var command = dockerClient.getEndpointConfiguration().getDockerClient().stopContainerCmd(getContainerId(context))) { + command.exec(); - setCommandResult(success()); + setCommandResult(success()); + } } /** diff --git a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerWait.java b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerWait.java index 9116532105..c0c9486b0a 100644 --- a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerWait.java +++ b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ContainerWait.java @@ -16,13 +16,12 @@ package org.citrusframework.docker.command; +import com.github.dockerjava.api.command.WaitContainerResultCallback; +import com.github.dockerjava.api.model.WaitResponse; import org.citrusframework.context.TestContext; import org.citrusframework.docker.actions.DockerExecuteAction; import org.citrusframework.docker.client.DockerClient; import org.citrusframework.docker.message.DockerMessageHeaders; -import com.github.dockerjava.api.command.WaitContainerCmd; -import com.github.dockerjava.api.command.WaitContainerResultCallback; -import com.github.dockerjava.api.model.WaitResponse; /** * @since 2.4 @@ -38,20 +37,20 @@ public ContainerWait() { @Override public void execute(DockerClient dockerClient, TestContext context) { - WaitContainerCmd command = dockerClient.getEndpointConfiguration().getDockerClient().waitContainerCmd(getContainerId(context)); - - WaitContainerResultCallback waitResult = new WaitContainerResultCallback() { - @Override - public void onNext(WaitResponse waitResponse) { - super.onNext(waitResponse); - setCommandResult(waitResponse); - } - }; + try (var command = dockerClient.getEndpointConfiguration().getDockerClient().waitContainerCmd(getContainerId(context))) { + WaitContainerResultCallback waitResult = new WaitContainerResultCallback() { + @Override + public void onNext(WaitResponse waitResponse) { + super.onNext(waitResponse); + setCommandResult(waitResponse); + } + }; - command.exec(waitResult); + command.exec(waitResult); - Integer statusCode = waitResult.awaitStatusCode(); - context.setVariable(DockerMessageHeaders.DOCKER_PREFIX + "statusCode", statusCode); + Integer statusCode = waitResult.awaitStatusCode(); + context.setVariable(DockerMessageHeaders.DOCKER_PREFIX + "statusCode", statusCode); + } } /** diff --git a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImageBuild.java b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImageBuild.java index 40683449d2..eab0ff4b16 100644 --- a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImageBuild.java +++ b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImageBuild.java @@ -16,8 +16,6 @@ package org.citrusframework.docker.command; -import java.util.Collections; - import com.github.dockerjava.api.command.BuildImageCmd; import com.github.dockerjava.api.command.BuildImageResultCallback; import com.github.dockerjava.api.model.BuildResponseItem; @@ -28,6 +26,8 @@ import org.citrusframework.spi.Resource; import org.citrusframework.util.FileUtils; +import java.util.Collections; + /** * @since 2.4 */ @@ -41,35 +41,39 @@ public ImageBuild() { } @Override - public void execute(DockerClient dockerClient, TestContext context) { - BuildImageCmd command = dockerClient.getEndpointConfiguration().getDockerClient().buildImageCmd(); + public void execute(DockerClient dockerClient, TestContext testContext) { + try (var command = dockerClient.getEndpointConfiguration().getDockerClient().buildImageCmd()) { + executeDockerCommand(command, testContext); + } + } + private void executeDockerCommand(BuildImageCmd command, TestContext testContext) { if (hasParameter("no-cache")) { - command.withNoCache(Boolean.valueOf(getParameter("no-cache", context))); + command.withNoCache(Boolean.valueOf(getParameter("no-cache", testContext))); } if (hasParameter("basedir")) { - command.withBaseDirectory(FileUtils.getFileResource(getParameter("basedir", context), context).getFile()); + command.withBaseDirectory(FileUtils.getFileResource(getParameter("basedir", testContext), testContext).getFile()); } if (hasParameter("dockerfile")) { if (getParameters().get("dockerfile") instanceof Resource) { command.withDockerfile(((Resource)getParameters().get("dockerfile")).getFile()); } else { - command.withDockerfile(FileUtils.getFileResource(getParameter("dockerfile", context), context).getFile()); + command.withDockerfile(FileUtils.getFileResource(getParameter("dockerfile", testContext), testContext).getFile()); } } if (hasParameter("quiet")) { - command.withNoCache(Boolean.valueOf(getParameter("quiet", context))); + command.withNoCache(Boolean.valueOf(getParameter("quiet", testContext))); } if (hasParameter("remove")) { - command.withRemove(Boolean.valueOf(getParameter("remove", context))); + command.withRemove(Boolean.valueOf(getParameter("remove", testContext))); } if (hasParameter("tag")) { - command.withTags(Collections.singleton(getParameter("tag", context))); + command.withTags(Collections.singleton(getParameter("tag", testContext))); } BuildImageResultCallback imageResult = new BuildImageResultCallback() { @@ -83,7 +87,7 @@ public void onNext(BuildResponseItem item) { command.exec(imageResult); String imageId = imageResult.awaitImageId(); - context.setVariable(DockerMessageHeaders.IMAGE_ID, imageId); + testContext.setVariable(DockerMessageHeaders.IMAGE_ID, imageId); } /** diff --git a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImageInspect.java b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImageInspect.java index 08d4c356cf..043f9744a0 100644 --- a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImageInspect.java +++ b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImageInspect.java @@ -16,11 +16,10 @@ package org.citrusframework.docker.command; +import com.github.dockerjava.api.command.InspectImageResponse; import org.citrusframework.context.TestContext; import org.citrusframework.docker.actions.DockerExecuteAction; import org.citrusframework.docker.client.DockerClient; -import com.github.dockerjava.api.command.InspectImageCmd; -import com.github.dockerjava.api.command.InspectImageResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,11 +40,12 @@ public ImageInspect() { @Override public void execute(DockerClient dockerClient, TestContext context) { - InspectImageCmd command = dockerClient.getEndpointConfiguration().getDockerClient().inspectImageCmd(getImageId(context)); - InspectImageResponse response = command.exec(); + try (var command = dockerClient.getEndpointConfiguration().getDockerClient().inspectImageCmd(getImageId(context))) { + InspectImageResponse response = command.exec(); - setCommandResult(response); - logger.debug(response.toString()); + setCommandResult(response); + logger.debug(response.toString()); + } } /** diff --git a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImagePull.java b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImagePull.java index 3d2d6ce631..56b59cb30f 100644 --- a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImagePull.java +++ b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImagePull.java @@ -16,13 +16,13 @@ package org.citrusframework.docker.command; +import com.github.dockerjava.api.command.PullImageCmd; +import com.github.dockerjava.api.command.PullImageResultCallback; +import com.github.dockerjava.api.model.PullResponseItem; import org.citrusframework.context.TestContext; import org.citrusframework.docker.actions.DockerExecuteAction; import org.citrusframework.docker.client.DockerClient; import org.citrusframework.exceptions.CitrusRuntimeException; -import com.github.dockerjava.api.command.PullImageCmd; -import com.github.dockerjava.api.command.PullImageResultCallback; -import com.github.dockerjava.api.model.PullResponseItem; /** * @since 2.4 @@ -38,30 +38,29 @@ public ImagePull() { @Override public void execute(DockerClient dockerClient, TestContext context) { - final PullImageCmd command = dockerClient.getEndpointConfiguration().getDockerClient().pullImageCmd(getImageId(context)); - PullImageResultCallback imageResult = new PullImageResultCallback() { - @Override - public void onNext(PullResponseItem item) { - setCommandResult(item); - super.onNext(item); + try (PullImageCmd command = dockerClient.getEndpointConfiguration().getDockerClient().pullImageCmd(getImageId(context))) { + PullImageResultCallback imageResult = new PullImageResultCallback() { + @Override + public void onNext(PullResponseItem item) { + setCommandResult(item); + super.onNext(item); + } + }; + + if (hasParameter("registry")) { + command.withRegistry(getParameter("registry", context)); } - }; - if (hasParameter("registry")) { - command.withRegistry(getParameter("registry", context)); - } - - if (hasParameter("repository")) { - command.withRepository(getParameter("repository", context)); - } + if (hasParameter("repository")) { + command.withRepository(getParameter("repository", context)); + } - if (hasParameter("tag")) { - command.withTag(getParameter("tag", context)); - } + if (hasParameter("tag")) { + command.withTag(getParameter("tag", context)); + } - command.exec(imageResult); + command.exec(imageResult); - try { imageResult.awaitCompletion(); } catch (InterruptedException e) { throw new CitrusRuntimeException("Failed to wait for command success", e); diff --git a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImageRemove.java b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImageRemove.java index 330e9dbcb4..40b239f6ce 100644 --- a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImageRemove.java +++ b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/ImageRemove.java @@ -16,11 +16,10 @@ package org.citrusframework.docker.command; +import com.github.dockerjava.api.model.ResponseItem; import org.citrusframework.context.TestContext; import org.citrusframework.docker.actions.DockerExecuteAction; import org.citrusframework.docker.client.DockerClient; -import com.github.dockerjava.api.command.RemoveImageCmd; -import com.github.dockerjava.api.model.ResponseItem; /** * @since 2.4 @@ -38,15 +37,15 @@ public ImageRemove() { @Override public void execute(DockerClient dockerClient, TestContext context) { - RemoveImageCmd command = dockerClient.getEndpointConfiguration().getDockerClient().removeImageCmd(getImageId(context)); + try (var command = dockerClient.getEndpointConfiguration().getDockerClient().removeImageCmd(getImageId(context))) { + if (hasParameter("force")) { + command.withForce(Boolean.valueOf(getParameter("force", context))); + } - if (hasParameter("force")) { - command.withForce(Boolean.valueOf(getParameter("force", context))); - } + command.exec(); - command.exec(); - - setCommandResult(success()); + setCommandResult(success()); + } } /** diff --git a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/Info.java b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/Info.java index 8face5fcc7..743e41bc85 100644 --- a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/Info.java +++ b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/Info.java @@ -39,7 +39,10 @@ public Info() { @Override public void execute(DockerClient dockerClient, TestContext context) { - setCommandResult(dockerClient.getEndpointConfiguration().getDockerClient().infoCmd().exec()); + try (var infoCmd = dockerClient.getEndpointConfiguration().getDockerClient().infoCmd()) { + setCommandResult(infoCmd.exec()); + } + logger.debug(getCommandResult().toString()); } diff --git a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/Ping.java b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/Ping.java index 07f7b2b764..838ab5166d 100644 --- a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/Ping.java +++ b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/Ping.java @@ -16,11 +16,10 @@ package org.citrusframework.docker.command; +import com.github.dockerjava.api.model.ResponseItem; import org.citrusframework.context.TestContext; import org.citrusframework.docker.actions.DockerExecuteAction; import org.citrusframework.docker.client.DockerClient; -import com.github.dockerjava.api.command.PingCmd; -import com.github.dockerjava.api.model.ResponseItem; /** * @since 2.4 @@ -38,8 +37,9 @@ public Ping() { @Override public void execute(DockerClient dockerClient, TestContext context) { - PingCmd command = dockerClient.getEndpointConfiguration().getDockerClient().pingCmd(); - command.exec(); + try (var command = dockerClient.getEndpointConfiguration().getDockerClient().pingCmd()) { + command.exec(); + } setCommandResult(success()); } diff --git a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/Version.java b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/Version.java index 63e55257f5..b6a124f954 100644 --- a/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/Version.java +++ b/connectors/citrus-docker/src/main/java/org/citrusframework/docker/command/Version.java @@ -19,7 +19,6 @@ import org.citrusframework.context.TestContext; import org.citrusframework.docker.actions.DockerExecuteAction; import org.citrusframework.docker.client.DockerClient; -import com.github.dockerjava.api.command.VersionCmd; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,8 +39,9 @@ public Version() { @Override public void execute(DockerClient dockerClient, TestContext context) { - VersionCmd command = dockerClient.getEndpointConfiguration().getDockerClient().versionCmd(); - setCommandResult(command.exec()); + try (var command = dockerClient.getEndpointConfiguration().getDockerClient().versionCmd()) { + setCommandResult(command.exec()); + } logger.debug(getCommandResult().toString()); } diff --git a/connectors/citrus-docker/src/test/java/org/citrusframework/docker/integration/AbstractDockerIT.java b/connectors/citrus-docker/src/test/java/org/citrusframework/docker/integration/AbstractDockerIT.java index bb6b1cd9f9..ca4fa114ec 100644 --- a/connectors/citrus-docker/src/test/java/org/citrusframework/docker/integration/AbstractDockerIT.java +++ b/connectors/citrus-docker/src/test/java/org/citrusframework/docker/integration/AbstractDockerIT.java @@ -16,20 +16,21 @@ package org.citrusframework.docker.integration; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -import org.citrusframework.testng.spring.TestNGCitrusSpringSupport; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.core.DockerClientImpl; import com.github.dockerjava.jaxrs.JerseyDockerCmdExecFactory; +import org.citrusframework.testng.spring.TestNGCitrusSpringSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.IHookCallBack; import org.testng.ITestResult; import org.testng.annotations.BeforeSuite; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static java.util.concurrent.Executors.newSingleThreadExecutor; + /** * @since 2.4 */ @@ -45,8 +46,9 @@ public class AbstractDockerIT extends TestNGCitrusSpringSupport { public void checkDockerEnvironment() { boolean enabled = Boolean.parseBoolean(System.getProperty("citrus.docker.it.enabled", Boolean.FALSE.toString())); if (enabled) { + var executor = newSingleThreadExecutor(); try { - Future future = Executors.newSingleThreadExecutor().submit(() -> { + Future future = executor.submit(() -> { DockerClient dockerClient = DockerClientImpl.getInstance() .withDockerCmdExecFactory(new JerseyDockerCmdExecFactory()); @@ -57,6 +59,8 @@ public void checkDockerEnvironment() { connected = future.get(5000, TimeUnit.MILLISECONDS); } catch (Exception e) { logger.warn("Skipping Docker test execution as no proper Docker environment is available on host system!", e); + } finally { + executor.shutdownNow(); } } } diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/AbstractAsyncTestAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/AbstractAsyncTestAction.java index 51f57b503f..c604413bfe 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/AbstractAsyncTestAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/AbstractAsyncTestAction.java @@ -16,18 +16,18 @@ package org.citrusframework.actions; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - import org.citrusframework.Completable; import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.CitrusRuntimeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Future; + +import static java.util.concurrent.Executors.newSingleThreadExecutor; + /** * Test action that performs in a separate thread. Action execution is not blocking the test execution chain. After * action has performed optional validation step is called. @@ -56,7 +56,7 @@ public final void doExecute(TestContext context) { } }); - ExecutorService executor = Executors.newSingleThreadExecutor(); + var executor = newSingleThreadExecutor(); finished = executor.submit(() -> { try { doExecuteAsync(context); @@ -69,6 +69,7 @@ public final void doExecute(TestContext context) { context.addException(new CitrusRuntimeException(e)); } } finally { + executor.shutdownNow(); result.complete(context); } }); diff --git a/core/citrus-base/src/main/java/org/citrusframework/actions/SendMessageAction.java b/core/citrus-base/src/main/java/org/citrusframework/actions/SendMessageAction.java index c4dbb3ec10..53f6fcabd6 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/actions/SendMessageAction.java +++ b/core/citrus-base/src/main/java/org/citrusframework/actions/SendMessageAction.java @@ -16,12 +16,6 @@ package org.citrusframework.actions; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - import org.citrusframework.CitrusSettings; import org.citrusframework.Completable; import org.citrusframework.context.TestContext; @@ -36,6 +30,7 @@ import org.citrusframework.message.builder.SendMessageBuilderSupport; import org.citrusframework.util.IsJsonPredicate; import org.citrusframework.util.IsXmlPredicate; +import org.citrusframework.util.StringUtils; import org.citrusframework.validation.SchemaValidator; import org.citrusframework.validation.context.SchemaValidationContext; import org.citrusframework.validation.json.JsonMessageValidationContext; @@ -44,7 +39,12 @@ import org.citrusframework.variable.dictionary.DataDictionary; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.citrusframework.util.StringUtils; + +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +import static java.util.concurrent.Executors.newSingleThreadExecutor; /** * This action sends a messages to a specified message endpoint. The action holds a reference to @@ -152,7 +152,7 @@ public void doExecute(final TestContext context) { if (forkMode) { logger.debug("Forking message sending action ..."); - ExecutorService taskExecutor = Executors.newSingleThreadExecutor(); + var taskExecutor = newSingleThreadExecutor(); taskExecutor.execute(() -> { try { validateMessage(message, context); @@ -164,6 +164,7 @@ public void doExecute(final TestContext context) { context.addException(new CitrusRuntimeException(e)); } } finally { + taskExecutor.shutdownNow(); finished.complete(context); } }); diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/Timer.java b/core/citrus-base/src/main/java/org/citrusframework/container/Timer.java index aa73cdd67a..59ea25bad5 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/Timer.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/Timer.java @@ -16,18 +16,18 @@ package org.citrusframework.container; -import java.util.TimerTask; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicInteger; - import org.citrusframework.AbstractTestContainerBuilder; import org.citrusframework.TestActionBuilder; import org.citrusframework.context.TestContext; import org.citrusframework.exceptions.CitrusRuntimeException; +import org.citrusframework.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.citrusframework.util.StringUtils; + +import java.util.TimerTask; +import java.util.concurrent.atomic.AtomicInteger; + +import static java.util.concurrent.Executors.newSingleThreadExecutor; /** * @since 2.5 @@ -63,8 +63,12 @@ public Timer(Builder builder) { @Override public void doExecute(final TestContext context) { if (fork) { - ExecutorService taskExecutor = Executors.newSingleThreadExecutor(); - taskExecutor.execute(() -> configureAndRunTimer(context)); + var taskExecutor = newSingleThreadExecutor(); + try { + taskExecutor.execute(() -> configureAndRunTimer(context)); + } finally { + taskExecutor.shutdownNow(); + } } else { configureAndRunTimer(context); } diff --git a/core/citrus-base/src/main/java/org/citrusframework/container/Wait.java b/core/citrus-base/src/main/java/org/citrusframework/container/Wait.java index b9bcdeb3cc..b02056d8f9 100644 --- a/core/citrus-base/src/main/java/org/citrusframework/container/Wait.java +++ b/core/citrus-base/src/main/java/org/citrusframework/container/Wait.java @@ -16,15 +16,6 @@ package org.citrusframework.container; -import java.time.Duration; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - import org.citrusframework.AbstractTestActionBuilder; import org.citrusframework.TestActionBuilder; import org.citrusframework.actions.AbstractTestAction; @@ -38,6 +29,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.time.Duration; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static java.util.concurrent.Executors.newSingleThreadExecutor; + /** * Pause the test execution until the condition is met or the wait time has been exceeded. * @@ -87,15 +87,16 @@ public void doExecute(final TestContext context) { logger.debug(String.format("Waiting for condition %s", condition.getName())); } - ExecutorService executor = Executors.newSingleThreadExecutor(); - Future future = executor.submit(callable); + var executor = newSingleThreadExecutor(); long checkStartTime = System.currentTimeMillis(); try { + Future future = executor.submit(callable); conditionSatisfied = future.get(intervalMs, TimeUnit.MILLISECONDS); } catch (InterruptedException | TimeoutException | ExecutionException e) { - logger.warn(String.format("Condition check interrupted with '%s'", e.getClass().getSimpleName())); + logger.warn("Condition check interrupted with '{}'", e.getClass().getSimpleName()); + } finally { + executor.shutdownNow(); } - executor.shutdown(); if (Boolean.TRUE.equals(conditionSatisfied)) { logger.info(condition.getSuccessMessage(context)); diff --git a/core/citrus-base/src/test/java/org/citrusframework/container/AsyncTest.java b/core/citrus-base/src/test/java/org/citrusframework/container/AsyncTest.java index 5283be9dc9..9fe47b2ff9 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/container/AsyncTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/container/AsyncTest.java @@ -16,12 +16,6 @@ package org.citrusframework.container; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - import org.citrusframework.TestAction; import org.citrusframework.UnitTestSupport; import org.citrusframework.actions.FailAction; @@ -33,6 +27,12 @@ import org.testng.Assert; import org.testng.annotations.Test; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.reset; @@ -158,14 +158,19 @@ public void testWaitForFinishError() throws Exception { private void waitForDone(Async container, TestContext context, long timeout) throws InterruptedException, ExecutionException, TimeoutException { CompletableFuture done = new CompletableFuture<>(); - Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> { - if (container.isDone(context)) { - done.complete(true); - } else { - logger.debug("Async action execution not finished yet ..."); - } - }, 100, timeout / 10, TimeUnit.MILLISECONDS); - - done.get(timeout, TimeUnit.MILLISECONDS); + var executor = newSingleThreadScheduledExecutor(); + try { + executor.scheduleAtFixedRate(() -> { + if (container.isDone(context)) { + done.complete(true); + } else { + logger.debug("Async action execution not finished yet ..."); + } + }, 100, timeout / 10, TimeUnit.MILLISECONDS); + + done.get(timeout, TimeUnit.MILLISECONDS); + } finally { + executor.shutdownNow(); + } } } diff --git a/core/citrus-base/src/test/java/org/citrusframework/endpoint/direct/DirectEndpointAdapterTest.java b/core/citrus-base/src/test/java/org/citrusframework/endpoint/direct/DirectEndpointAdapterTest.java index eac37ce042..c2a5d2f42e 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/endpoint/direct/DirectEndpointAdapterTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/endpoint/direct/DirectEndpointAdapterTest.java @@ -16,8 +16,6 @@ package org.citrusframework.endpoint.direct; -import java.util.concurrent.Executors; - import org.citrusframework.context.TestContext; import org.citrusframework.context.TestContextFactory; import org.citrusframework.message.DefaultMessage; @@ -30,6 +28,8 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import static java.util.concurrent.Executors.newSingleThreadExecutor; + public class DirectEndpointAdapterTest { private MessageQueue queue = new DefaultMessageQueue("testQueue"); @@ -59,13 +59,18 @@ public void purgeQueue() { public void testEndpointAdapter() { final Message request = new DefaultMessage("Hi!"); - Executors.newSingleThreadExecutor().execute(() -> { - Message receivedMessage = endpointAdapter.getEndpoint().createConsumer().receive(context, endpointConfiguration.getTimeout()); - Assert.assertNotNull(receivedMessage); - Assert.assertEquals(receivedMessage.getPayload(), request.getPayload()); + var executorService = newSingleThreadExecutor(); + try { + executorService.execute(() -> { + Message receivedMessage = endpointAdapter.getEndpoint().createConsumer().receive(context, endpointConfiguration.getTimeout()); + Assert.assertNotNull(receivedMessage); + Assert.assertEquals(receivedMessage.getPayload(), request.getPayload()); - endpointAdapter.getEndpoint().createProducer().send(new DefaultMessage("OK"), context); - }); + endpointAdapter.getEndpoint().createProducer().send(new DefaultMessage("OK"), context); + }); + } finally { + executorService.shutdownNow(); + } Message response = endpointAdapter.handleMessage(request); Assert.assertNotNull(response); diff --git a/core/citrus-base/src/test/java/org/citrusframework/message/ZipMessageTest.java b/core/citrus-base/src/test/java/org/citrusframework/message/ZipMessageTest.java index 996198b932..267308fe37 100644 --- a/core/citrus-base/src/test/java/org/citrusframework/message/ZipMessageTest.java +++ b/core/citrus-base/src/test/java/org/citrusframework/message/ZipMessageTest.java @@ -16,6 +16,11 @@ package org.citrusframework.message; +import org.citrusframework.spi.Resources; +import org.citrusframework.util.FileUtils; +import org.testng.Assert; +import org.testng.annotations.Test; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; @@ -24,11 +29,6 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipFile; -import org.citrusframework.spi.Resources; -import org.citrusframework.util.FileUtils; -import org.testng.Assert; -import org.testng.annotations.Test; - /** * @since 2.7.5 */ @@ -43,11 +43,12 @@ public void testAddSingleFile() throws Exception { Assert.assertTrue(archive.exists()); - ZipFile zipFile = new ZipFile(archive.getAbsolutePath()); - Assert.assertEquals(zipFile.size(), 1); + try (var zipFile = new ZipFile(archive.getAbsolutePath())) { + Assert.assertEquals(zipFile.size(), 1); - Assert.assertNotNull(zipFile.getEntry("/foo.txt")); - Assert.assertEquals(FileUtils.readToString(zipFile.getInputStream(new ZipEntry("/foo.txt"))), "Foo!"); + Assert.assertNotNull(zipFile.getEntry("/foo.txt")); + Assert.assertEquals(FileUtils.readToString(zipFile.getInputStream(new ZipEntry("/foo.txt"))), "Foo!"); + } } @Test @@ -59,19 +60,20 @@ public void testAddDirectory() throws Exception { Assert.assertTrue(archive.exists()); - ZipFile zipFile = new ZipFile(archive.getAbsolutePath()); - Assert.assertEquals(zipFile.size(), 5); - - Assert.assertNotNull(zipFile.getEntry("/archive/")); - Assert.assertTrue(zipFile.getEntry("/archive/").isDirectory()); - Assert.assertNotNull(zipFile.getEntry("archive/foo.txt")); - Assert.assertEquals(FileUtils.readToString(zipFile.getInputStream(new ZipEntry("archive/foo.txt"))), "Foo!"); - Assert.assertNotNull(zipFile.getEntry("archive/bar.txt")); - Assert.assertEquals(FileUtils.readToString(zipFile.getInputStream(new ZipEntry("archive/bar.txt"))), "Bar!"); - Assert.assertNotNull(zipFile.getEntry("archive/dir/")); - Assert.assertTrue(zipFile.getEntry("archive/dir/").isDirectory()); - Assert.assertNotNull(zipFile.getEntry("archive/dir/sub_foo.txt")); - Assert.assertEquals(FileUtils.readToString(zipFile.getInputStream(new ZipEntry("archive/dir/sub_foo.txt"))), "SubFoo!"); + try (var zipFile = new ZipFile(archive.getAbsolutePath())) { + Assert.assertEquals(zipFile.size(), 5); + + Assert.assertNotNull(zipFile.getEntry("/archive/")); + Assert.assertTrue(zipFile.getEntry("/archive/").isDirectory()); + Assert.assertNotNull(zipFile.getEntry("archive/foo.txt")); + Assert.assertEquals(FileUtils.readToString(zipFile.getInputStream(new ZipEntry("archive/foo.txt"))), "Foo!"); + Assert.assertNotNull(zipFile.getEntry("archive/bar.txt")); + Assert.assertEquals(FileUtils.readToString(zipFile.getInputStream(new ZipEntry("archive/bar.txt"))), "Bar!"); + Assert.assertNotNull(zipFile.getEntry("archive/dir/")); + Assert.assertTrue(zipFile.getEntry("archive/dir/").isDirectory()); + Assert.assertNotNull(zipFile.getEntry("archive/dir/sub_foo.txt")); + Assert.assertEquals(FileUtils.readToString(zipFile.getInputStream(new ZipEntry("archive/dir/sub_foo.txt"))), "SubFoo!"); + } } @Test @@ -86,13 +88,14 @@ public void testNewDirectoryStructure() throws Exception { Assert.assertTrue(archive.exists()); - ZipFile zipFile = new ZipFile(archive.getAbsolutePath()); - Assert.assertEquals(zipFile.size(), 2); + try (var zipFile = new ZipFile(archive.getAbsolutePath())) { + Assert.assertEquals(zipFile.size(), 2); - Assert.assertNotNull(zipFile.getEntry("/foos/")); - Assert.assertTrue(zipFile.getEntry("/foos/").isDirectory()); - Assert.assertNotNull(zipFile.getEntry("foos/foo.txt")); - Assert.assertEquals(FileUtils.readToString(zipFile.getInputStream(new ZipEntry("foos/foo.txt"))), "Foo!"); + Assert.assertNotNull(zipFile.getEntry("/foos/")); + Assert.assertTrue(zipFile.getEntry("/foos/").isDirectory()); + Assert.assertNotNull(zipFile.getEntry("foos/foo.txt")); + Assert.assertEquals(FileUtils.readToString(zipFile.getInputStream(new ZipEntry("foos/foo.txt"))), "Foo!"); + } } @Test @@ -108,15 +111,16 @@ public void testEmptyDirectory() throws Exception { Assert.assertTrue(archive.exists()); - ZipFile zipFile = new ZipFile(archive.getAbsolutePath()); - Assert.assertEquals(zipFile.size(), 3); + try (var zipFile = new ZipFile(archive.getAbsolutePath())) { + Assert.assertEquals(zipFile.size(), 3); - Assert.assertNotNull(zipFile.getEntry("/foos/")); - Assert.assertTrue(zipFile.getEntry("/foos/").isDirectory()); - Assert.assertNotNull(zipFile.getEntry("/bars/")); - Assert.assertTrue(zipFile.getEntry("/bars/").isDirectory()); - Assert.assertNotNull(zipFile.getEntry("bars/bar.txt")); - Assert.assertEquals(FileUtils.readToString(zipFile.getInputStream(new ZipEntry("bars/bar.txt"))), "Bar!"); + Assert.assertNotNull(zipFile.getEntry("/foos/")); + Assert.assertTrue(zipFile.getEntry("/foos/").isDirectory()); + Assert.assertNotNull(zipFile.getEntry("/bars/")); + Assert.assertTrue(zipFile.getEntry("/bars/").isDirectory()); + Assert.assertNotNull(zipFile.getEntry("bars/bar.txt")); + Assert.assertEquals(FileUtils.readToString(zipFile.getInputStream(new ZipEntry("bars/bar.txt"))), "Bar!"); + } } private Path createTempDir() throws IOException { diff --git a/endpoints/citrus-camel/src/main/java/org/citrusframework/camel/message/CamelRouteProcessor.java b/endpoints/citrus-camel/src/main/java/org/citrusframework/camel/message/CamelRouteProcessor.java index ec45c17a97..90abc66401 100644 --- a/endpoints/citrus-camel/src/main/java/org/citrusframework/camel/message/CamelRouteProcessor.java +++ b/endpoints/citrus-camel/src/main/java/org/citrusframework/camel/message/CamelRouteProcessor.java @@ -16,19 +16,19 @@ package org.citrusframework.camel.message; -import java.util.UUID; - -import org.citrusframework.camel.dsl.CamelContextAware; -import org.citrusframework.exceptions.CitrusRuntimeException; -import org.citrusframework.message.MessageProcessor; -import org.citrusframework.spi.ReferenceResolver; -import org.citrusframework.spi.ReferenceResolverAware; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.OutputDefinition; import org.apache.camel.model.RouteDefinition; +import org.citrusframework.camel.dsl.CamelContextAware; +import org.citrusframework.exceptions.CitrusRuntimeException; +import org.citrusframework.message.MessageProcessor; +import org.citrusframework.spi.ReferenceResolver; +import org.citrusframework.spi.ReferenceResolverAware; + +import java.util.UUID; /** * Message processor builds new route from given processor definition and delegates to the Apache Camel route. @@ -135,9 +135,8 @@ public RouteProcessor(String routeId, RouteBuilder routeBuilder) { @Override public void process(Exchange exchange) throws Exception { - try { - routeBuilder.getContext().createProducerTemplate() - .send("direct:" + routeId, exchange); + try (var producerTemplate = routeBuilder.getContext().createProducerTemplate()) { + producerTemplate.send("direct:" + routeId, exchange); } finally { routeBuilder.getContext().removeRoute(routeId); } diff --git a/endpoints/citrus-ftp/src/main/java/org/citrusframework/ftp/client/ScpClient.java b/endpoints/citrus-ftp/src/main/java/org/citrusframework/ftp/client/ScpClient.java index b29117b472..515b43a539 100644 --- a/endpoints/citrus-ftp/src/main/java/org/citrusframework/ftp/client/ScpClient.java +++ b/endpoints/citrus-ftp/src/main/java/org/citrusframework/ftp/client/ScpClient.java @@ -16,10 +16,6 @@ package org.citrusframework.ftp.client; -import java.io.File; -import java.io.IOException; -import java.util.Optional; - import org.apache.sshd.client.SshClient; import org.apache.sshd.client.keyverifier.AcceptAllServerKeyVerifier; import org.apache.sshd.client.keyverifier.KnownHostsServerKeyVerifier; @@ -42,6 +38,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; +import java.io.IOException; +import java.util.Optional; + /** * @since 2.7.6 */ @@ -118,8 +118,7 @@ protected FtpMessage retrieveFile(GetCommand command, TestContext context) { @Override protected void connectAndLogin() { - try { - SshClient client = SshClient.setUpDefaultClient(); + try (var client = SshClient.setUpDefaultClient()) { client.start(); if (getEndpointConfiguration().isStrictHostChecking()) { diff --git a/endpoints/citrus-jms/src/main/java/org/citrusframework/jms/endpoint/JmsTopicSubscriber.java b/endpoints/citrus-jms/src/main/java/org/citrusframework/jms/endpoint/JmsTopicSubscriber.java index fbdb8d1804..eab4550be3 100644 --- a/endpoints/citrus-jms/src/main/java/org/citrusframework/jms/endpoint/JmsTopicSubscriber.java +++ b/endpoints/citrus-jms/src/main/java/org/citrusframework/jms/endpoint/JmsTopicSubscriber.java @@ -16,14 +16,6 @@ package org.citrusframework.jms.endpoint; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSException; import jakarta.jms.Topic; @@ -43,6 +35,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static java.util.concurrent.Executors.newSingleThreadExecutor; + /** * @since 2.7.6 */ @@ -60,7 +61,7 @@ public class JmsTopicSubscriber extends JmsConsumer implements Runnable { /** Delegate in-memory message queue caching all inbound messages */ private DirectEndpoint messageQueue; - private Executor subscription = Executors.newSingleThreadExecutor(); + private Executor subscription = newSingleThreadExecutor(); private CompletableFuture stopped = new CompletableFuture<>(); private CompletableFuture started = new CompletableFuture<>(); diff --git a/endpoints/citrus-jmx/src/main/java/org/citrusframework/jmx/client/JmxClient.java b/endpoints/citrus-jmx/src/main/java/org/citrusframework/jmx/client/JmxClient.java index 358d16ffd4..8cf8a8ef03 100644 --- a/endpoints/citrus-jmx/src/main/java/org/citrusframework/jmx/client/JmxClient.java +++ b/endpoints/citrus-jmx/src/main/java/org/citrusframework/jmx/client/JmxClient.java @@ -16,26 +16,6 @@ package org.citrusframework.jmx.client; -import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.util.Collections; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import javax.management.Attribute; -import javax.management.InstanceNotFoundException; -import javax.management.JMException; -import javax.management.MBeanServerConnection; -import javax.management.MalformedObjectNameException; -import javax.management.Notification; -import javax.management.NotificationListener; -import javax.management.ObjectName; -import javax.management.openmbean.CompositeData; -import javax.management.remote.JMXConnectionNotification; -import javax.management.remote.JMXConnector; -import javax.management.remote.JMXConnectorFactory; -import javax.management.remote.JMXServiceURL; - import org.citrusframework.context.TestContext; import org.citrusframework.endpoint.AbstractEndpoint; import org.citrusframework.exceptions.CitrusRuntimeException; @@ -54,6 +34,26 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.management.Attribute; +import javax.management.InstanceNotFoundException; +import javax.management.JMException; +import javax.management.MBeanServerConnection; +import javax.management.MalformedObjectNameException; +import javax.management.Notification; +import javax.management.NotificationListener; +import javax.management.ObjectName; +import javax.management.openmbean.CompositeData; +import javax.management.remote.JMXConnectionNotification; +import javax.management.remote.JMXConnector; +import javax.management.remote.JMXConnectorFactory; +import javax.management.remote.JMXServiceURL; +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.util.Collections; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + /** * @since 2.5 */ @@ -181,11 +181,12 @@ private MBeanServerConnection getNetworkConnection() { try { JMXServiceURL url = new JMXServiceURL(getEndpointConfiguration().getServerUrl()); String[] creds = {getEndpointConfiguration().getUsername(), getEndpointConfiguration().getPassword()}; - JMXConnector networkConnector = JMXConnectorFactory.connect(url, Collections.singletonMap(JMXConnector.CREDENTIALS, creds)); - connectionId = networkConnector.getConnectionId(); + try (var networkConnector = JMXConnectorFactory.connect(url, Collections.singletonMap(JMXConnector.CREDENTIALS, creds))) { + connectionId = networkConnector.getConnectionId(); - networkConnector.addConnectionNotificationListener(this, null, null); - return networkConnector.getMBeanServerConnection(); + networkConnector.addConnectionNotificationListener(this, null, null); + return networkConnector.getMBeanServerConnection(); + } } catch (IOException e) { throw new CitrusRuntimeException("Failed to connect to network MBean server '" + getEndpointConfiguration().getServerUrl() + "'", e); } diff --git a/endpoints/citrus-spring-integration/src/test/java/org/citrusframework/channel/ChannelEndpointAdapterTest.java b/endpoints/citrus-spring-integration/src/test/java/org/citrusframework/channel/ChannelEndpointAdapterTest.java index d6c465f7b1..15a6b1d575 100644 --- a/endpoints/citrus-spring-integration/src/test/java/org/citrusframework/channel/ChannelEndpointAdapterTest.java +++ b/endpoints/citrus-spring-integration/src/test/java/org/citrusframework/channel/ChannelEndpointAdapterTest.java @@ -20,12 +20,13 @@ import org.citrusframework.message.DefaultMessage; import org.citrusframework.message.Message; import org.citrusframework.testng.AbstractTestNGUnitTest; -import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.integration.channel.QueueChannel; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import static java.util.concurrent.Executors.newSingleThreadExecutor; + public class ChannelEndpointAdapterTest extends AbstractTestNGUnitTest { private QueueChannel channel = new QueueChannel(); @@ -57,13 +58,18 @@ public void purgeChannel() { public void testEndpointAdapter() { final Message request = new DefaultMessage("Hi!"); - new SimpleAsyncTaskExecutor().execute(() -> { - Message receivedMessage = endpointAdapter.getEndpoint().createConsumer().receive(context, endpointConfiguration.getTimeout()); - Assert.assertNotNull(receivedMessage); - Assert.assertEquals(receivedMessage.getPayload(), request.getPayload()); + var executor = newSingleThreadExecutor(); + try { + executor.execute(() -> { + Message receivedMessage = endpointAdapter.getEndpoint().createConsumer().receive(context, endpointConfiguration.getTimeout()); + Assert.assertNotNull(receivedMessage); + Assert.assertEquals(receivedMessage.getPayload(), request.getPayload()); - endpointAdapter.getEndpoint().createProducer().send(new DefaultMessage("OK"), context); - }); + endpointAdapter.getEndpoint().createProducer().send(new DefaultMessage("OK"), context); + }); + } finally { + executor.shutdown(); + } Message response = endpointAdapter.handleMessage(request); Assert.assertNotNull(response); diff --git a/runtime/citrus-groovy/src/main/java/org/citrusframework/message/builder/script/GroovyScriptPayloadBuilder.java b/runtime/citrus-groovy/src/main/java/org/citrusframework/message/builder/script/GroovyScriptPayloadBuilder.java index 8caea26ade..c999218c54 100644 --- a/runtime/citrus-groovy/src/main/java/org/citrusframework/message/builder/script/GroovyScriptPayloadBuilder.java +++ b/runtime/citrus-groovy/src/main/java/org/citrusframework/message/builder/script/GroovyScriptPayloadBuilder.java @@ -26,6 +26,8 @@ import org.citrusframework.validation.script.TemplateBasedScriptBuilder; import org.codehaus.groovy.control.CompilationFailedException; +import java.io.IOException; + public class GroovyScriptPayloadBuilder implements ScriptPayloadBuilder { /** Default path to script template */ @@ -73,10 +75,8 @@ public Object buildPayload(TestContext context) { * @return */ protected String buildMarkupBuilderScript(String scriptData) { - try { - ClassLoader parent = GroovyScriptPayloadBuilder.class.getClassLoader(); - GroovyClassLoader loader = new GroovyClassLoader(parent); - + ClassLoader parent = GroovyScriptPayloadBuilder.class.getClassLoader(); + try (GroovyClassLoader loader = new GroovyClassLoader(parent)) { Class groovyClass = loader.parseClass(TemplateBasedScriptBuilder.fromTemplateResource(scriptTemplateResource) .withCode(scriptData) .build()); @@ -87,7 +87,7 @@ protected String buildMarkupBuilderScript(String scriptData) { GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance(); return (String) groovyObject.invokeMethod("run", new Object[] {}); - } catch (CompilationFailedException | InstantiationException | IllegalAccessException e) { + } catch (CompilationFailedException | IllegalAccessException | InstantiationException | IOException e) { throw new CitrusRuntimeException(e); } } diff --git a/runtime/citrus-groovy/src/main/java/org/citrusframework/script/GroovyAction.java b/runtime/citrus-groovy/src/main/java/org/citrusframework/script/GroovyAction.java index 9186ffe84f..fc35e9dbe3 100644 --- a/runtime/citrus-groovy/src/main/java/org/citrusframework/script/GroovyAction.java +++ b/runtime/citrus-groovy/src/main/java/org/citrusframework/script/GroovyAction.java @@ -16,11 +16,6 @@ package org.citrusframework.script; -import java.io.IOException; -import java.nio.charset.Charset; -import java.security.AccessController; -import java.security.PrivilegedAction; - import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyObject; import org.citrusframework.AbstractTestActionBuilder; @@ -34,6 +29,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.nio.charset.Charset; +import java.security.AccessController; +import java.security.PrivilegedAction; + /** * Action executes groovy scripts either specified inline or from external file resource. * @@ -79,14 +79,7 @@ public GroovyAction(Builder builder) { @Override public void doExecute(TestContext context) { - try { - GroovyClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<>() { - public GroovyClassLoader run() { - ClassLoader parent = getClass().getClassLoader(); - return new GroovyClassLoader(parent); - } - }); - + try (var loader = getPrivilegedGroovyLoader()) { assertScriptProvided(); String rawCode = StringUtils.hasText(script) ? script.trim() : FileUtils.readToString(FileUtils.getFileResource(scriptResourcePath, context)); @@ -134,6 +127,15 @@ public GroovyClassLoader run() { } } + private GroovyClassLoader getPrivilegedGroovyLoader() { + return AccessController.doPrivileged(new PrivilegedAction<>() { + public GroovyClassLoader run() { + ClassLoader parent = getClass().getClassLoader(); + return new GroovyClassLoader(parent); + } + }); + } + private void assertScriptProvided() { if (!StringUtils.hasText(script) && scriptResourcePath == null) { throw new CitrusRuntimeException("Neither inline script nor " + diff --git a/validation/citrus-validation-groovy/src/main/java/org/citrusframework/validation/script/GroovyScriptMessageValidator.java b/validation/citrus-validation-groovy/src/main/java/org/citrusframework/validation/script/GroovyScriptMessageValidator.java index 34774d3967..83f4e36d88 100644 --- a/validation/citrus-validation-groovy/src/main/java/org/citrusframework/validation/script/GroovyScriptMessageValidator.java +++ b/validation/citrus-validation-groovy/src/main/java/org/citrusframework/validation/script/GroovyScriptMessageValidator.java @@ -16,10 +16,6 @@ package org.citrusframework.validation.script; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.List; - import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyObject; import org.citrusframework.context.TestContext; @@ -37,6 +33,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.List; + /** * Groovy script message validator passing the message to a validation script. * Tester needs to write validation code in Groovy. @@ -77,17 +78,20 @@ public void validateMessage(Message receivedMessage, Message controlMessage, Tes if (StringUtils.hasText(validationScript)) { logger.debug("Start groovy message validation ..."); - GroovyClassLoader loader = AccessController.doPrivileged((PrivilegedAction) () -> new GroovyClassLoader(GroovyScriptMessageValidator.class.getClassLoader())); - Class groovyClass = loader.parseClass(TemplateBasedScriptBuilder.fromTemplateResource(scriptTemplateResource) - .withCode(validationScript) - .build()); + try (var loader = getPrivilegedGroovyLoader()) { + Class groovyClass = loader.parseClass(TemplateBasedScriptBuilder.fromTemplateResource(scriptTemplateResource) + .withCode(validationScript) + .build()); - if (groovyClass == null) { - throw new CitrusRuntimeException("Failed to load groovy validation script resource"); - } + if (groovyClass == null) { + throw new CitrusRuntimeException("Failed to load groovy validation script resource"); + } - GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance(); - ((GroovyScriptExecutor) groovyObject).validate(receivedMessage, context); + GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance(); + ((GroovyScriptExecutor) groovyObject).validate(receivedMessage, context); + } catch (IOException e) { + throw new CitrusRuntimeException("Failed to load groovy validation script resource", e); + } logger.debug("Groovy message validation successful: All values OK"); } @@ -98,6 +102,10 @@ public void validateMessage(Message receivedMessage, Message controlMessage, Tes } } + private static GroovyClassLoader getPrivilegedGroovyLoader() { + return AccessController.doPrivileged((PrivilegedAction) () -> new GroovyClassLoader(GroovyScriptMessageValidator.class.getClassLoader())); + } + @Override public ScriptValidationContext findValidationContext(List validationContexts) { for (ValidationContext validationContext : validationContexts) { diff --git a/validation/citrus-validation-groovy/src/main/java/org/citrusframework/validation/script/sql/GroovySqlResultSetValidator.java b/validation/citrus-validation-groovy/src/main/java/org/citrusframework/validation/script/sql/GroovySqlResultSetValidator.java index 44f3af0f68..0d7d382b86 100644 --- a/validation/citrus-validation-groovy/src/main/java/org/citrusframework/validation/script/sql/GroovySqlResultSetValidator.java +++ b/validation/citrus-validation-groovy/src/main/java/org/citrusframework/validation/script/sql/GroovySqlResultSetValidator.java @@ -16,10 +16,6 @@ package org.citrusframework.validation.script.sql; -import java.lang.reflect.InvocationTargetException; -import java.util.List; -import java.util.Map; - import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyObject; import org.citrusframework.context.TestContext; @@ -36,6 +32,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import java.util.Map; + /** * Groovy script validator capable of validating SQL result sets. * @@ -76,17 +77,20 @@ public void validateSqlResultSet(List> resultSet, if (StringUtils.hasText(validationScript)) { logger.debug("Start groovy SQL result set validation"); - GroovyClassLoader loader = new GroovyClassLoader(GroovyScriptMessageValidator.class.getClassLoader()); - Class groovyClass = loader.parseClass(TemplateBasedScriptBuilder.fromTemplateResource(scriptTemplateResource) - .withCode(validationScript) - .build()); + try (var loader = new GroovyClassLoader(GroovyScriptMessageValidator.class.getClassLoader())) { + Class groovyClass = loader.parseClass(TemplateBasedScriptBuilder.fromTemplateResource(scriptTemplateResource) + .withCode(validationScript) + .build()); - if (groovyClass == null) { - throw new CitrusRuntimeException("Failed to load groovy validation script resource"); - } + if (groovyClass == null) { + throw new CitrusRuntimeException("Failed to load groovy validation script resource"); + } - GroovyObject groovyObject = (GroovyObject) groovyClass.getDeclaredConstructor().newInstance(); - ((SqlResultSetScriptExecutor) groovyObject).validate(resultSet, context); + GroovyObject groovyObject = (GroovyObject) groovyClass.getDeclaredConstructor().newInstance(); + ((SqlResultSetScriptExecutor) groovyObject).validate(resultSet, context); + } catch (IOException e) { + throw new CitrusRuntimeException("Failed to load groovy validation script resource", e); + } logger.debug("Groovy SQL result set validation successful: All values OK"); } diff --git a/validation/citrus-validation-xml/src/test/java/org/citrusframework/xml/schema/WsdlXsdSchemaTest.java b/validation/citrus-validation-xml/src/test/java/org/citrusframework/xml/schema/WsdlXsdSchemaTest.java index eb6249874f..ec168fe989 100644 --- a/validation/citrus-validation-xml/src/test/java/org/citrusframework/xml/schema/WsdlXsdSchemaTest.java +++ b/validation/citrus-validation-xml/src/test/java/org/citrusframework/xml/schema/WsdlXsdSchemaTest.java @@ -16,11 +16,6 @@ package org.citrusframework.xml.schema; -import java.io.IOException; -import java.net.URL; -import java.net.URLClassLoader; -import javax.xml.parsers.ParserConfigurationException; - import org.citrusframework.spi.Resource; import org.citrusframework.spi.Resources; import org.citrusframework.util.FileUtils; @@ -28,6 +23,11 @@ import org.testng.annotations.Test; import org.xml.sax.SAXException; +import javax.xml.parsers.ParserConfigurationException; +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; + public class WsdlXsdSchemaTest { @Test @@ -77,18 +77,20 @@ public void testWsdlSchemaWsdlImports() throws ParserConfigurationException, IOE } @Test - public void testWsdlSchemaWsdlImportsFromJar() throws ParserConfigurationException, IOException, SAXException { + public void testWsdlSchemaWsdlImportsFromJar() throws IOException { Resource classPathResource = Resources.create("sample.jar", WsdlXsdSchemaTest.class); - URLClassLoader urlClassLoader = URLClassLoader.newInstance(new URL[]{classPathResource.getURL()}); - URL url = urlClassLoader.getResource("SampleServiceWithWsdlImports.wsdl"); - WsdlXsdSchema wsdl = new WsdlXsdSchema(Resources.create(url)); - wsdl.initialize(); - Assert.assertEquals(wsdl.getSchemaResources().size(), 3); + try (var urlClassLoader = URLClassLoader.newInstance(new URL[]{classPathResource.getURL()})) { + URL url = urlClassLoader.getResource("SampleServiceWithWsdlImports.wsdl"); + WsdlXsdSchema wsdl = new WsdlXsdSchema(Resources.create(url)); + wsdl.initialize(); - Assert.assertEquals(wsdl.getTargetNamespace(), "http://www.citrusframework.org/SampleService/"); + Assert.assertEquals(wsdl.getSchemaResources().size(), 3); - Assert.assertNotNull(wsdl.getSource()); + Assert.assertEquals(wsdl.getTargetNamespace(), "http://www.citrusframework.org/SampleService/"); + + Assert.assertNotNull(wsdl.getSource()); + } } @Test