Skip to content

Commit

Permalink
Use var instead of types
Browse files Browse the repository at this point in the history
  • Loading branch information
Donnerbart committed Jun 20, 2024
1 parent a30123f commit 9183b5f
Show file tree
Hide file tree
Showing 11 changed files with 39 additions and 52 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
Expand All @@ -38,7 +37,7 @@ void withExtensionConfiguration_hivemqRunning() throws Exception {
final var client = container.getKubernetesClient();
final var namespace = "default";

final URL resource = getClass().getResource("/ese-config.xml");
final var resource = getClass().getResource("/ese-config.xml");

final var configMapData = Files.readString(Path.of(Objects.requireNonNull(resource).toURI()));
final var eseConfigMap = new ConfigMapBuilder().withNewMetadata()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class LogWaiterUtil implements BiConsumer<String, String> {

@Override
public void accept(final @NotNull String prefix, final @NotNull String line) {
final Map<String, CompletableFuture<String>> prefixPatterns = patterns.getOrDefault(prefix, Map.of());
final var prefixPatterns = patterns.getOrDefault(prefix, Map.of());
prefixPatterns.forEach((pattern, future) -> {
if (line.matches(pattern)) {
LOG.info("TEST Found log pattern on '{}': {}", prefix, pattern);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ public DeploymentStatusStartupCheckStrategy(@NotNull final OperatorHelmChartCont
K8sUtil.waitForHiveMQClusterState(client, "default", chartName, "Running");

// get the HiveMQ container logs inside the pod
final Pod pod = client.pods().inAnyNamespace().withLabel("app", "hivemq").list().getItems().getFirst();
final var pod = client.pods().inAnyNamespace().withLabel("app", "hivemq").list().getItems().getFirst();
final var containerResource = client.pods()
.inNamespace("default")
.withName(pod.getMetadata().getName())
Expand Down Expand Up @@ -280,8 +280,8 @@ public void eventReceived(final @NotNull Action action, final @NotNull Event eve
final var logPodName = getLogPodName(podName);
executorService.submit(() -> {
LOG.info("Started log watcher for {} in pod {} [{}]", containerName, podName, podUid);
try (final InputStream inputStream = logWatch.getOutput();
final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
try (final var inputStream = logWatch.getOutput();
final var reader = new BufferedReader(new InputStreamReader(inputStream))) {
reader.lines().forEach(line -> {
// skip the ISO8601 prefix for logging
final var matcher = LOGBACK_DATE_PREFIX.matcher(line);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ public static void waitForHiveMQClusterState(
final @NotNull String namespace,
final @NotNull String customResourceName,
final @NotNull String state) {
final Resource<GenericKubernetesResource> hivemqCustomResource =
K8sUtil.getHiveMQCluster(client, namespace, customResourceName);
final var hivemqCustomResource = K8sUtil.getHiveMQCluster(client, namespace, customResourceName);
hivemqCustomResource.waitUntilCondition(getHiveMQClusterStatus(state), 5, TimeUnit.MINUTES);
assertThat(hivemqCustomResource.get().get("status").toString()).contains(state);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ public record Version(int major, int minor, int patch) implements Comparable<Ver

@Override
public int compareTo(final @NotNull Version other) {
final int majorCompare = Integer.compare(this.major, other.major);
final var majorCompare = Integer.compare(this.major, other.major);
if (majorCompare != 0) {
return majorCompare;
}
final int minorCompare = Integer.compare(this.minor, other.minor);
final var minorCompare = Integer.compare(this.minor, other.minor);
if (minorCompare != 0) {
return minorCompare;
}
Expand All @@ -32,7 +32,7 @@ public boolean equals(final @Nullable Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
final Version that = (Version) o;
final var that = (Version) o;
if (major != that.major) {
return false;
}
Expand All @@ -57,15 +57,14 @@ static class Deserializer extends JsonDeserializer<Version> {
@Override
public @NotNull Version deserialize(final @NotNull JsonParser parser, final @NotNull DeserializationContext ctx)
throws IOException {
final String versionString = parser.getValueAsString();

final String[] versionParts = versionString.split("\\.");
final var versionString = parser.getValueAsString();
final var versionParts = versionString.split("\\.");
if (versionParts.length != 3) {
throw new IllegalArgumentException(String.format("Invalid version format: %s", versionString));
}
int major = Integer.parseInt(versionParts[0]);
int minor = Integer.parseInt(versionParts[1]);
int patch = Integer.parseInt(versionParts[2]);
final var major = Integer.parseInt(versionParts[0]);
final var minor = Integer.parseInt(versionParts[1]);
final var patch = Integer.parseInt(versionParts[2]);
return new Version(major, minor, patch);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ void withBridgeConfiguration_messageBridged() throws Exception {
hivemqContainer.getMqttPort(),
"SubscribeClient"),
(publishClient, subscribeClient, publishes) -> {
final String validTopic = "bridge/topic/test";
final var validTopic = "bridge/topic/test";
subscribeClient.subscribeWith().topicFilter(validTopic).send();
LOG.info("remote client subscribed");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@

import com.hivemq.helmcharts.AbstractHelmChartIT;
import com.hivemq.helmcharts.util.K8sUtil;
import io.fabric8.kubernetes.api.model.GenericKubernetesResource;
import io.fabric8.kubernetes.api.model.apps.StatefulSet;
import io.fabric8.kubernetes.client.dsl.Resource;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -51,8 +48,7 @@ void withBridgeConfiguration_enableDisableBridge() throws Exception {
await().until(extensionEnabledInitAppFuture::isDone);
await().until(extensionStartedBrokerFuture::isDone);

final Resource<GenericKubernetesResource> hivemqCustomResource =
K8sUtil.getHiveMQPlatform(client, platformNamespace, PLATFORM_RELEASE_NAME);
final var hivemqCustomResource = K8sUtil.getHiveMQPlatform(client, platformNamespace, PLATFORM_RELEASE_NAME);
// check that extensions are enabled
assertThat(hivemqCustomResource.get().getAdditionalProperties().get("spec").toString()).matches(
".*extensions=\\[.*?enabled=true,.*?id=hivemq-bridge-extension,.*?].*");
Expand Down Expand Up @@ -100,8 +96,7 @@ void withBridgeConfiguration_updateExtensionWithNewConfig() throws Exception {
await().until(extensionStartedBrokerFuture1::isDone);

// check that extensions are enabled
final Resource<GenericKubernetesResource> hivemqCustomResource =
K8sUtil.getHiveMQPlatform(client, platformNamespace, PLATFORM_RELEASE_NAME);
final var hivemqCustomResource = K8sUtil.getHiveMQPlatform(client, platformNamespace, PLATFORM_RELEASE_NAME);
assertThat(hivemqCustomResource.get().getAdditionalProperties().get("spec").toString()).matches(
".*extensions=\\[.*?enabled=true,.*?id=hivemq-bridge-extension,.*?].*");

Expand All @@ -120,7 +115,7 @@ void withBridgeConfiguration_updateExtensionWithNewConfig() throws Exception {
await().until(extensionEnabledInitAppFuture2::isDone);
await().until(extensionStartedBrokerFuture2::isDone);

final StatefulSet upgradedStatefulSet =
final var upgradedStatefulSet =
client.apps().statefulSets().inNamespace(platformNamespace).withName(PLATFORM_RELEASE_NAME).get();
assertThat(upgradedStatefulSet.getStatus().getAvailableReplicas()).isEqualTo(1);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.hivemq.helmcharts.compose;

import com.hivemq.helmcharts.AbstractHelmChartIT;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -52,7 +51,7 @@ void withDeployedOperator_upgradeUsingNewValues() throws Exception {
"--namespace",
operatorNamespace);

final Deployment upgradedDeployment = client.apps()
final var upgradedDeployment = client.apps()
.deployments()
.inNamespace(operatorNamespace)
.withName(operatorName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import org.junit.jupiter.api.Timeout;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
Expand All @@ -26,10 +25,10 @@ class HelmInitContainerIT extends AbstractHelmChartIT {
@Test
@Timeout(value = 5, unit = TimeUnit.MINUTES)
void withOverrideInitContainer_hivemqRunningWithVolumeMounts() throws Exception {
final String additionalVolumeFile = "/files/init-container-additional-volumes-test-values.yaml";
final String additionalInitContainerFile = "/files/init-containers-spec.yaml";
final var additionalVolumeFile = "/files/init-container-additional-volumes-test-values.yaml";
final var additionalInitContainerFile = "/files/init-containers-spec.yaml";

final String mountName = "init-container-volume";
final var mountName = "init-container-volume";

installPlatformChartAndWaitToBeRunning("--set-file",
"config.overrideInitContainers=" + additionalInitContainerFile,
Expand Down Expand Up @@ -57,9 +56,7 @@ void withOverrideInitContainer_hivemqRunningWithVolumeMounts() throws Exception
@Test
@Timeout(value = 5, unit = TimeUnit.MINUTES)
void whenAdditionalInitContainer_withConsulTemplate_thenLicenseUpdated() throws Exception {
K8sUtil.createConfigMap(client,
platformNamespace,
"consul-template-config-map.yml");
K8sUtil.createConfigMap(client, platformNamespace, "consul-template-config-map.yml");
installPlatformChartAndWaitToBeRunning("/files/additional-init-containers-test-values.yaml");

await().atMost(Duration.ofMinutes(2)).pollInterval(Duration.ofSeconds(5)).untilAsserted(() -> {
Expand All @@ -70,30 +67,29 @@ void whenAdditionalInitContainer_withConsulTemplate_thenLicenseUpdated() throws
assertThat(hivemqContainer.getVolumeMounts().stream()) //
.anyMatch(volumeMount -> volumeMount.getName().equals("license-volume") &&
volumeMount.getMountPath().equals("/opt/hivemq/license"));
final var additionalInitContainer = K8sUtil.getInitContainer(statefulSet.getSpec(), "consul-template-init-container");
final var additionalInitContainer =
K8sUtil.getInitContainer(statefulSet.getSpec(), "consul-template-init-container");
assertThat(additionalInitContainer.getVolumeMounts().stream()) //
.anyMatch(volumeMount -> volumeMount.getName().equals("license-volume") &&
volumeMount.getMountPath().equals("/opt/hivemq/license"));

final var volumes = statefulSet.getSpec().getTemplate().getSpec().getVolumes();
assertThat(volumes).isNotNull();
assertThat(volumes.stream()) //
.anyMatch(volume -> volume.getName().equals("license-volume") &&
volume.getEmptyDir() != null);
.anyMatch(volume -> volume.getName().equals("license-volume") && volume.getEmptyDir() != null);
});
waitForPlatformLog(".*License file license.lic is corrupt.");
}

private void assertThatFileContains(final @NotNull Pod pod) {
final String initContainerTextFile = "/init-container-test/init-container-test.txt";
final String expectedContent = "test init container";

try (InputStream in = client.pods()
final var initContainerTextFile = "/init-container-test/init-container-test.txt";
final var expectedContent = "test init container";
try (final var inputStream = client.pods()
.inNamespace(platformNamespace)
.withName(pod.getMetadata().getName())
.file(initContainerTextFile)
.read()) {
final String foundContent = new String(in.readAllBytes(), StandardCharsets.UTF_8);
final var foundContent = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
assertThat(foundContent).isEqualTo(expectedContent);
} catch (final IOException e) {
throw new AssertionError("Could not read test file of init container from pod", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ private FilenameUtils() {
public static @NotNull String removeExtension(final @NotNull String fileName) {
requireNonNullChars(fileName);

final int index = indexOfExtension(fileName);
final var index = indexOfExtension(fileName);
if (index == NOT_FOUND) {
return fileName;
}
Expand Down Expand Up @@ -116,13 +116,13 @@ private static void requireNonNullChars(final String path) {
private static int indexOfExtension(final @NotNull String fileName) throws IllegalArgumentException {
if (isSystemWindows()) {
// special handling for NTFS ADS: don't accept colon in the fileName
final int offset = fileName.indexOf(':', getAdsCriticalOffset(fileName));
final var offset = fileName.indexOf(':', getAdsCriticalOffset(fileName));
if (offset != -1) {
throw new IllegalArgumentException("NTFS ADS separator (':') in file name is forbidden.");
}
}
final int extensionPos = fileName.lastIndexOf(EXTENSION_SEPARATOR);
final int lastSeparator = indexOfLastSeparator(fileName);
final var extensionPos = fileName.lastIndexOf(EXTENSION_SEPARATOR);
final var lastSeparator = indexOfLastSeparator(fileName);
return lastSeparator > extensionPos ? NOT_FOUND : extensionPos;
}

Expand All @@ -143,8 +143,8 @@ private static boolean isSystemWindows() {
*/
private static int getAdsCriticalOffset(final @NotNull String fileName) {
// step 1: remove leading path segments
final int offset1 = fileName.lastIndexOf(SYSTEM_SEPARATOR);
final int offset2 = fileName.lastIndexOf(OTHER_SEPARATOR);
final var offset1 = fileName.lastIndexOf(SYSTEM_SEPARATOR);
final var offset2 = fileName.lastIndexOf(OTHER_SEPARATOR);
if (offset1 == -1) {
if (offset2 == -1) {
return 0;
Expand All @@ -170,8 +170,8 @@ private static int getAdsCriticalOffset(final @NotNull String fileName) {
* is no such character
*/
private static int indexOfLastSeparator(final @NotNull String fileName) {
final int lastUnixPos = fileName.lastIndexOf(UNIX_SEPARATOR);
final int lastWindowsPos = fileName.lastIndexOf(WINDOWS_SEPARATOR);
final var lastUnixPos = fileName.lastIndexOf(UNIX_SEPARATOR);
final var lastWindowsPos = fileName.lastIndexOf(WINDOWS_SEPARATOR);
return Math.max(lastUnixPos, lastWindowsPos);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public static void deployNginx(
client.resource(nginxService).create();

await().atMost(Duration.ofMinutes(3)).pollInterval(Duration.ofSeconds(1)).untilAsserted(() -> {
final Deployment nginx = client.apps().deployments().inNamespace(namespace).withName("nginx").get();
final var nginx = client.apps().deployments().inNamespace(namespace).withName("nginx").get();
assertThat(nginx).isNotNull();
assertThat(nginx.getStatus().getReadyReplicas()).isEqualTo(1);
});
Expand Down

0 comments on commit 9183b5f

Please sign in to comment.