diff --git a/driver/src/main/java/org/neo4j/driver/Values.java b/driver/src/main/java/org/neo4j/driver/Values.java index ccb2cc19ed..02b50a09a9 100644 --- a/driver/src/main/java/org/neo4j/driver/Values.java +++ b/driver/src/main/java/org/neo4j/driver/Values.java @@ -38,6 +38,7 @@ import java.util.List; import java.util.Map; import java.util.function.Function; +import java.util.stream.IntStream; import java.util.stream.Stream; import org.neo4j.driver.exceptions.ClientException; import org.neo4j.driver.internal.AsValue; @@ -223,10 +224,7 @@ public static Value value(Object value) { * @return the array of values */ public static Value[] values(final Object... input) { - var values = new Value[input.length]; - for (var i = 0; i < input.length; i++) { - values[i] = value(input[i]); - } + var values = Arrays.stream(input).map(Values::value).toArray(Value[]::new); return values; } @@ -257,10 +255,7 @@ public static Value value(byte... input) { * @return the value */ public static Value value(String... input) { - var values = new StringValue[input.length]; - for (var i = 0; i < input.length; i++) { - values[i] = new StringValue(input[i]); - } + var values = Arrays.stream(input).map(StringValue::new).toArray(StringValue[]::new); return new ListValue(values); } @@ -270,10 +265,8 @@ public static Value value(String... input) { * @return the value */ public static Value value(boolean... input) { - var values = new Value[input.length]; - for (var i = 0; i < input.length; i++) { - values[i] = value(input[i]); - } + var values = + IntStream.range(0, input.length).mapToObj(i -> value(input[i])).toArray(Value[]::new); return new ListValue(values); } @@ -283,10 +276,8 @@ public static Value value(boolean... input) { * @return the value */ public static Value value(char... input) { - var values = new Value[input.length]; - for (var i = 0; i < input.length; i++) { - values[i] = value(input[i]); - } + var values = + IntStream.range(0, input.length).mapToObj(i -> value(input[i])).toArray(Value[]::new); return new ListValue(values); } @@ -296,10 +287,7 @@ public static Value value(char... input) { * @return the value */ public static Value value(long... input) { - var values = new Value[input.length]; - for (var i = 0; i < input.length; i++) { - values[i] = value(input[i]); - } + var values = Arrays.stream(input).mapToObj(Values::value).toArray(Value[]::new); return new ListValue(values); } @@ -309,10 +297,8 @@ public static Value value(long... input) { * @return the value */ public static Value value(short... input) { - var values = new Value[input.length]; - for (var i = 0; i < input.length; i++) { - values[i] = value(input[i]); - } + var values = + IntStream.range(0, input.length).mapToObj(i -> value(input[i])).toArray(Value[]::new); return new ListValue(values); } /** @@ -321,10 +307,7 @@ public static Value value(short... input) { * @return the value */ public static Value value(int... input) { - var values = new Value[input.length]; - for (var i = 0; i < input.length; i++) { - values[i] = value(input[i]); - } + var values = Arrays.stream(input).mapToObj(Values::value).toArray(Value[]::new); return new ListValue(values); } /** @@ -333,10 +316,7 @@ public static Value value(int... input) { * @return the value */ public static Value value(double... input) { - var values = new Value[input.length]; - for (var i = 0; i < input.length; i++) { - values[i] = value(input[i]); - } + var values = Arrays.stream(input).mapToObj(Values::value).toArray(Value[]::new); return new ListValue(values); } @@ -346,10 +326,8 @@ public static Value value(double... input) { * @return the value */ public static Value value(float... input) { - var values = new Value[input.length]; - for (var i = 0; i < input.length; i++) { - values[i] = value(input[i]); - } + var values = + IntStream.range(0, input.length).mapToObj(i -> value(input[i])).toArray(Value[]::new); return new ListValue(values); } diff --git a/driver/src/main/java/org/neo4j/driver/internal/InternalPath.java b/driver/src/main/java/org/neo4j/driver/internal/InternalPath.java index c1b3580612..49776f73ec 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/InternalPath.java +++ b/driver/src/main/java/org/neo4j/driver/internal/InternalPath.java @@ -132,7 +132,7 @@ public InternalPath(List segments, List nodes, List } private List newList(int size) { - return size == 0 ? Collections.emptyList() : new ArrayList(size); + return size == 0 ? Collections.emptyList() : new ArrayList<>(size); } @Override diff --git a/driver/src/main/java/org/neo4j/driver/internal/Scheme.java b/driver/src/main/java/org/neo4j/driver/internal/Scheme.java index 2db390a272..cd24f6a8e4 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/Scheme.java +++ b/driver/src/main/java/org/neo4j/driver/internal/Scheme.java @@ -18,6 +18,8 @@ */ package org.neo4j.driver.internal; +import java.util.List; + public class Scheme { public static final String BOLT_URI_SCHEME = "bolt"; public static final String BOLT_HIGH_TRUST_URI_SCHEME = "bolt+s"; @@ -36,9 +38,7 @@ public static void validateScheme(String scheme) { BOLT_HIGH_TRUST_URI_SCHEME, NEO4J_URI_SCHEME, NEO4J_LOW_TRUST_URI_SCHEME, - NEO4J_HIGH_TRUST_URI_SCHEME -> { - return; - } + NEO4J_HIGH_TRUST_URI_SCHEME -> {} default -> throw new IllegalArgumentException("Invalid address format " + scheme); } } @@ -52,15 +52,16 @@ public static boolean isLowTrustScheme(String scheme) { } public static boolean isSecurityScheme(String scheme) { - return scheme.equals(BOLT_LOW_TRUST_URI_SCHEME) - || scheme.equals(NEO4J_LOW_TRUST_URI_SCHEME) - || scheme.equals(BOLT_HIGH_TRUST_URI_SCHEME) - || scheme.equals(NEO4J_HIGH_TRUST_URI_SCHEME); + return List.of( + BOLT_LOW_TRUST_URI_SCHEME, + NEO4J_LOW_TRUST_URI_SCHEME, + BOLT_HIGH_TRUST_URI_SCHEME, + NEO4J_HIGH_TRUST_URI_SCHEME) + .contains(scheme); } public static boolean isRoutingScheme(String scheme) { - return scheme.equals(NEO4J_LOW_TRUST_URI_SCHEME) - || scheme.equals(NEO4J_HIGH_TRUST_URI_SCHEME) - || scheme.equals(NEO4J_URI_SCHEME); + return List.of(NEO4J_LOW_TRUST_URI_SCHEME, NEO4J_HIGH_TRUST_URI_SCHEME, NEO4J_URI_SCHEME) + .contains(scheme); } } diff --git a/driver/src/main/java/org/neo4j/driver/internal/SecuritySettings.java b/driver/src/main/java/org/neo4j/driver/internal/SecuritySettings.java index c22c436a28..fd2ef9d285 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/SecuritySettings.java +++ b/driver/src/main/java/org/neo4j/driver/internal/SecuritySettings.java @@ -18,10 +18,12 @@ */ package org.neo4j.driver.internal; +import java.io.Serial; import java.io.Serializable; import org.neo4j.driver.Config; public record SecuritySettings(boolean encrypted, Config.TrustStrategy trustStrategy) implements Serializable { + @Serial private static final long serialVersionUID = 4494615367164106576L; private static final boolean DEFAULT_ENCRYPTED = false; diff --git a/driver/src/main/java/org/neo4j/driver/internal/async/LeakLoggingNetworkSession.java b/driver/src/main/java/org/neo4j/driver/internal/async/LeakLoggingNetworkSession.java index 5183ce82fb..35494f17ba 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/async/LeakLoggingNetworkSession.java +++ b/driver/src/main/java/org/neo4j/driver/internal/async/LeakLoggingNetworkSession.java @@ -20,7 +20,9 @@ import static java.lang.System.lineSeparator; +import java.util.Arrays; import java.util.Set; +import java.util.stream.Collectors; import org.neo4j.driver.AccessMode; import org.neo4j.driver.AuthToken; import org.neo4j.driver.Bookmark; @@ -82,11 +84,9 @@ private void logLeakIfNeeded() { } private static String captureStackTrace() { - var result = new StringBuilder(); var elements = Thread.currentThread().getStackTrace(); - for (var element : elements) { - result.append("\t").append(element).append(lineSeparator()); - } - return result.toString(); + return Arrays.stream(elements) + .map(element -> "\t" + element + lineSeparator()) + .collect(Collectors.joining()); } } diff --git a/driver/src/main/java/org/neo4j/driver/internal/async/ResultCursorsHolder.java b/driver/src/main/java/org/neo4j/driver/internal/async/ResultCursorsHolder.java index 7d9031669c..c1a34f11eb 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/async/ResultCursorsHolder.java +++ b/driver/src/main/java/org/neo4j/driver/internal/async/ResultCursorsHolder.java @@ -21,6 +21,7 @@ import static org.neo4j.driver.internal.util.Futures.completedWithNull; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; @@ -54,13 +55,11 @@ private CompletableFuture[] retrieveAllFailures() { private static Throwable findFirstFailure(CompletableFuture[] completedFailureFutures) { // all given futures should be completed, it is thus safe to get their values - for (var failureFuture : completedFailureFutures) { - var failure = failureFuture.getNow(null); // does not block - if (failure != null) { - return failure; - } - } - return null; + return Arrays.stream(completedFailureFutures) + .map(failureFuture -> failureFuture.getNow(null)) + .filter(Objects::nonNull) + .findFirst() + .orElse(null); } private static CompletionStage retrieveFailure(CompletionStage cursorStage) { diff --git a/driver/src/main/java/org/neo4j/driver/internal/cluster/ClusterRoutingTable.java b/driver/src/main/java/org/neo4j/driver/internal/cluster/ClusterRoutingTable.java index b3173cd646..fe13724645 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/cluster/ClusterRoutingTable.java +++ b/driver/src/main/java/org/neo4j/driver/internal/cluster/ClusterRoutingTable.java @@ -169,22 +169,16 @@ public String toString() { private List newWithoutAddressIfPresent( List addresses, BoltServerAddress addressToSkip) { - List newList = new ArrayList<>(addresses.size()); - for (var address : addresses) { - if (!address.equals(addressToSkip)) { - newList.add(address); - } - } - return Collections.unmodifiableList(newList); + return addresses.stream() + .filter(address -> !address.equals(addressToSkip)) + .toList(); } private List newWithAddressReplacedIfPresent( List addresses, BoltServerAddress oldAddress, BoltServerAddress newAddress) { - List newList = new ArrayList<>(addresses.size()); - for (var address : addresses) { - newList.add(address.equals(oldAddress) ? newAddress : address); - } - return Collections.unmodifiableList(newList); + return addresses.stream() + .map(address -> address.equals(oldAddress) ? newAddress : address) + .toList(); } private List newWithReusedAddresses( diff --git a/driver/src/main/java/org/neo4j/driver/internal/cluster/RoutingTableRegistryImpl.java b/driver/src/main/java/org/neo4j/driver/internal/cluster/RoutingTableRegistryImpl.java index 71f3a74ec8..878e7afecc 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/cluster/RoutingTableRegistryImpl.java +++ b/driver/src/main/java/org/neo4j/driver/internal/cluster/RoutingTableRegistryImpl.java @@ -23,7 +23,6 @@ import java.time.Clock; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -33,6 +32,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; import org.neo4j.driver.Logger; import org.neo4j.driver.Logging; import org.neo4j.driver.internal.BoltServerAddress; @@ -165,10 +165,9 @@ private CompletionStage ensureDatabaseNameIsComplet public Set allServers() { // obviously we just had a snapshot of all servers in all routing tables // after we read it, the set could already be changed. - Set servers = new HashSet<>(); - for (var tableHandler : routingTableHandlers.values()) { - servers.addAll(tableHandler.servers()); - } + var servers = routingTableHandlers.values().stream() + .flatMap(tableHandler -> tableHandler.servers().stream()) + .collect(Collectors.toSet()); return servers; } diff --git a/driver/src/main/java/org/neo4j/driver/internal/cluster/loadbalancing/LoadBalancer.java b/driver/src/main/java/org/neo4j/driver/internal/cluster/loadbalancing/LoadBalancer.java index a3d4590f4b..2baf25fd14 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/cluster/loadbalancing/LoadBalancer.java +++ b/driver/src/main/java/org/neo4j/driver/internal/cluster/loadbalancing/LoadBalancer.java @@ -244,7 +244,6 @@ private static List getAddressesByMode(AccessMode mode, Routi return switch (mode) { case READ -> routingTable.readers(); case WRITE -> routingTable.writers(); - default -> throw unknownMode(mode); }; } @@ -252,7 +251,6 @@ private BoltServerAddress selectAddress(AccessMode mode, List return switch (mode) { case READ -> loadBalancingStrategy.selectReader(addresses); case WRITE -> loadBalancingStrategy.selectWriter(addresses); - default -> throw unknownMode(mode); }; } diff --git a/driver/src/main/java/org/neo4j/driver/internal/logging/ConsoleLogging.java b/driver/src/main/java/org/neo4j/driver/internal/logging/ConsoleLogging.java index 0dc358b813..c16376ecad 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/logging/ConsoleLogging.java +++ b/driver/src/main/java/org/neo4j/driver/internal/logging/ConsoleLogging.java @@ -21,6 +21,7 @@ import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME; import java.io.PrintWriter; +import java.io.Serial; import java.io.Serializable; import java.io.StringWriter; import java.time.LocalDateTime; @@ -39,6 +40,7 @@ * @see Logging#console(Level) */ public class ConsoleLogging implements Logging, Serializable { + @Serial private static final long serialVersionUID = 9205935204074879150L; private final Level level; diff --git a/driver/src/main/java/org/neo4j/driver/internal/logging/DevNullLogging.java b/driver/src/main/java/org/neo4j/driver/internal/logging/DevNullLogging.java index b66e8d65b2..ec18e82a57 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/logging/DevNullLogging.java +++ b/driver/src/main/java/org/neo4j/driver/internal/logging/DevNullLogging.java @@ -18,11 +18,13 @@ */ package org.neo4j.driver.internal.logging; +import java.io.Serial; import java.io.Serializable; import org.neo4j.driver.Logger; import org.neo4j.driver.Logging; public class DevNullLogging implements Logging, Serializable { + @Serial private static final long serialVersionUID = -2632752338512373821L; public static final Logging DEV_NULL_LOGGING = new DevNullLogging(); @@ -40,6 +42,7 @@ public Logger getLog(String name) { // An enum would be preferable, but would not be API compatible. // Reference: https://docs.oracle.com/en/java/javase/17/docs/specs/serialization/input.html#the-readresolve-method // andJoshua Bloch, Effective Java 3rd edition + @Serial private Object readResolve() { return DEV_NULL_LOGGING; } diff --git a/driver/src/main/java/org/neo4j/driver/internal/logging/JULogging.java b/driver/src/main/java/org/neo4j/driver/internal/logging/JULogging.java index 58ee48908f..15fca57ed0 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/logging/JULogging.java +++ b/driver/src/main/java/org/neo4j/driver/internal/logging/JULogging.java @@ -18,6 +18,7 @@ */ package org.neo4j.driver.internal.logging; +import java.io.Serial; import java.io.Serializable; import java.util.logging.Level; import org.neo4j.driver.Logger; @@ -30,6 +31,7 @@ * @see Logging#javaUtilLogging(Level) */ public class JULogging implements Logging, Serializable { + @Serial private static final long serialVersionUID = -1145576859241657833L; private final Level loggingLevel; diff --git a/driver/src/main/java/org/neo4j/driver/internal/logging/Slf4jLogging.java b/driver/src/main/java/org/neo4j/driver/internal/logging/Slf4jLogging.java index b030e2d686..3ed6500347 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/logging/Slf4jLogging.java +++ b/driver/src/main/java/org/neo4j/driver/internal/logging/Slf4jLogging.java @@ -18,6 +18,7 @@ */ package org.neo4j.driver.internal.logging; +import java.io.Serial; import java.io.Serializable; import org.neo4j.driver.Logger; import org.neo4j.driver.Logging; @@ -30,6 +31,7 @@ * @see Logging#slf4j() */ public class Slf4jLogging implements Logging, Serializable { + @Serial private static final long serialVersionUID = 4120390028025944991L; @Override diff --git a/driver/src/main/java/org/neo4j/driver/internal/messaging/response/FailureMessage.java b/driver/src/main/java/org/neo4j/driver/internal/messaging/response/FailureMessage.java index abf40cef17..751cf6a0db 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/messaging/response/FailureMessage.java +++ b/driver/src/main/java/org/neo4j/driver/internal/messaging/response/FailureMessage.java @@ -20,6 +20,7 @@ import static java.lang.String.format; +import java.util.Objects; import org.neo4j.driver.internal.messaging.Message; /** @@ -52,7 +53,6 @@ public boolean equals(Object o) { var that = (FailureMessage) o; - return !(code != null ? !code.equals(that.code) : that.code != null) - && !(message != null ? !message.equals(that.message) : that.message != null); + return Objects.equals(code, that.code) && Objects.equals(message, that.message); } } diff --git a/driver/src/main/java/org/neo4j/driver/internal/packstream/PackStream.java b/driver/src/main/java/org/neo4j/driver/internal/packstream/PackStream.java index 0b12e4e3ee..5db08708c1 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/packstream/PackStream.java +++ b/driver/src/main/java/org/neo4j/driver/internal/packstream/PackStream.java @@ -23,6 +23,7 @@ import static java.util.Collections.singletonList; import java.io.IOException; +import java.io.Serial; import java.nio.charset.Charset; import java.util.List; import java.util.Map; @@ -269,9 +270,9 @@ public void pack(Object value) throws IOException { } else if (value instanceof String[]) { pack(singletonList(value)); } else if (value instanceof List) { - pack((List) value); + pack((List) value); } else if (value instanceof Map) { - pack((Map) value); + pack((Map) value); } else { throw new UnPackable(format("Cannot pack object %s", value)); } @@ -543,6 +544,7 @@ public PackType peekNextType() throws IOException { } public static class PackStreamException extends IOException { + @Serial private static final long serialVersionUID = -1491422133282345421L; protected PackStreamException(String message) { @@ -551,6 +553,7 @@ protected PackStreamException(String message) { } public static class EndOfStream extends PackStreamException { + @Serial private static final long serialVersionUID = 5102836237108105603L; public EndOfStream(String message) { @@ -559,6 +562,7 @@ public EndOfStream(String message) { } public static class Overflow extends PackStreamException { + @Serial private static final long serialVersionUID = -923071934446993659L; public Overflow(String message) { @@ -567,6 +571,7 @@ public Overflow(String message) { } public static class Unexpected extends PackStreamException { + @Serial private static final long serialVersionUID = 5004685868740125469L; public Unexpected(String message) { @@ -575,6 +580,7 @@ public Unexpected(String message) { } public static class UnPackable extends PackStreamException { + @Serial private static final long serialVersionUID = 2408740707769711365L; public UnPackable(String message) { diff --git a/driver/src/main/java/org/neo4j/driver/internal/retry/RetrySettings.java b/driver/src/main/java/org/neo4j/driver/internal/retry/RetrySettings.java index 071325b63a..3e2eee7643 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/retry/RetrySettings.java +++ b/driver/src/main/java/org/neo4j/driver/internal/retry/RetrySettings.java @@ -18,9 +18,11 @@ */ package org.neo4j.driver.internal.retry; +import java.io.Serial; import java.io.Serializable; public record RetrySettings(long maxRetryTimeMs) implements Serializable { + @Serial private static final long serialVersionUID = -2895062473220745239L; public static final RetrySettings DEFAULT = diff --git a/driver/src/main/java/org/neo4j/driver/internal/security/InternalAuthToken.java b/driver/src/main/java/org/neo4j/driver/internal/security/InternalAuthToken.java index e7593ee6f7..f9ae994c88 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/security/InternalAuthToken.java +++ b/driver/src/main/java/org/neo4j/driver/internal/security/InternalAuthToken.java @@ -19,6 +19,7 @@ package org.neo4j.driver.internal.security; import java.util.Map; +import java.util.Objects; import org.neo4j.driver.AuthToken; import org.neo4j.driver.Value; @@ -54,7 +55,7 @@ public boolean equals(Object o) { var that = (InternalAuthToken) o; - return content != null ? content.equals(that.content) : that.content == null; + return Objects.equals(content, that.content); } @Override diff --git a/driver/src/main/java/org/neo4j/driver/internal/security/SecurityPlanImpl.java b/driver/src/main/java/org/neo4j/driver/internal/security/SecurityPlanImpl.java index c9df66411e..cd706bf7d5 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/security/SecurityPlanImpl.java +++ b/driver/src/main/java/org/neo4j/driver/internal/security/SecurityPlanImpl.java @@ -33,6 +33,7 @@ import java.security.cert.PKIXBuilderParameters; import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; +import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.net.ssl.CertPathTrustManagerParameters; @@ -130,13 +131,10 @@ private static void loadSystemCertificates(KeyStore trustedKeyStore) throws Gene tempFactory.init((KeyStore) null); // Get hold of the default trust manager - X509TrustManager x509TrustManager = null; - for (var trustManager : tempFactory.getTrustManagers()) { - if (trustManager instanceof X509TrustManager) { - x509TrustManager = (X509TrustManager) trustManager; - break; - } - } + var x509TrustManager = (X509TrustManager) Arrays.stream(tempFactory.getTrustManagers()) + .filter(trustManager -> trustManager instanceof X509TrustManager) + .findFirst() + .orElse(null); if (x509TrustManager == null) { throw new CertificateException("No system certificates found"); diff --git a/driver/src/main/java/org/neo4j/driver/internal/security/SecurityPlans.java b/driver/src/main/java/org/neo4j/driver/internal/security/SecurityPlans.java index 70cae39124..219612720e 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/security/SecurityPlans.java +++ b/driver/src/main/java/org/neo4j/driver/internal/security/SecurityPlans.java @@ -95,8 +95,6 @@ private static SecurityPlan createSecurityPlanImpl(boolean encrypted, Config.Tru hostnameVerificationEnabled, revocationCheckingStrategy); case TRUST_ALL_CERTIFICATES -> SecurityPlanImpl.forAllCertificates( hostnameVerificationEnabled, revocationCheckingStrategy); - default -> throw new ClientException("Unknown TLS authentication strategy: " - + trustStrategy.strategy().name()); }; } else { return insecure(); diff --git a/driver/src/main/java/org/neo4j/driver/internal/summary/InternalPlan.java b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalPlan.java index c18437b622..a43cfa43a3 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/summary/InternalPlan.java +++ b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalPlan.java @@ -102,17 +102,9 @@ public static Plan plan( return EXPLAIN_PLAN.create(operatorType, arguments, identifiers, children, null); } - public static final PlanCreator EXPLAIN_PLAN = new PlanCreator() { - @Override - public Plan create( - String operatorType, - Map arguments, - List identifiers, - List children, - Value originalPlanValue) { - return new InternalPlan<>(operatorType, arguments, identifiers, children); - } - }; + public static final PlanCreator EXPLAIN_PLAN = + (operatorType, arguments, identifiers, children, originalPlanValue) -> + new InternalPlan<>(operatorType, arguments, identifiers, children); /** Builds a regular plan without profiling information - eg. a plan that came as a result of an `EXPLAIN` query */ public static final Function EXPLAIN_PLAN_FROM_VALUE = new Converter<>(EXPLAIN_PLAN); diff --git a/driver/src/main/java/org/neo4j/driver/internal/summary/InternalProfiledPlan.java b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalProfiledPlan.java index c9d0949ffe..80b1e8f609 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/summary/InternalProfiledPlan.java +++ b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalProfiledPlan.java @@ -87,15 +87,8 @@ public long time() { return time; } - public static final PlanCreator PROFILED_PLAN = new PlanCreator() { - @Override - public ProfiledPlan create( - String operatorType, - Map arguments, - List identifiers, - List children, - Value originalPlanValue) { - return new InternalProfiledPlan( + public static final PlanCreator PROFILED_PLAN = + (operatorType, arguments, identifiers, children, originalPlanValue) -> new InternalProfiledPlan( operatorType, arguments, identifiers, @@ -106,8 +99,6 @@ public ProfiledPlan create( originalPlanValue.get("pageCacheMisses").asLong(0), originalPlanValue.get("pageCacheHitRatio").asDouble(0), originalPlanValue.get("time").asLong(0)); - } - }; /** * Builds a regular plan without profiling information - eg. a plan that came as a result of an `EXPLAIN` query diff --git a/driver/src/main/java/org/neo4j/driver/internal/summary/InternalResultSummary.java b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalResultSummary.java index 702d595b3f..fada2095b2 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/summary/InternalResultSummary.java +++ b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalResultSummary.java @@ -104,7 +104,7 @@ public ProfiledPlan profile() { @Override public List notifications() { - return notifications == null ? Collections.emptyList() : notifications; + return notifications == null ? Collections.emptyList() : notifications; } @Override diff --git a/driver/src/main/java/org/neo4j/driver/internal/summary/InternalSummaryCounters.java b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalSummaryCounters.java index 25dc5176d5..021656cec0 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/summary/InternalSummaryCounters.java +++ b/driver/src/main/java/org/neo4j/driver/internal/summary/InternalSummaryCounters.java @@ -18,6 +18,7 @@ */ package org.neo4j.driver.internal.summary; +import java.util.stream.IntStream; import org.neo4j.driver.summary.SummaryCounters; public record InternalSummaryCounters( @@ -39,17 +40,19 @@ public record InternalSummaryCounters( @Override public boolean containsUpdates() { - return isPositive(nodesCreated) - || isPositive(nodesDeleted) - || isPositive(relationshipsCreated) - || isPositive(relationshipsDeleted) - || isPositive(propertiesSet) - || isPositive(labelsAdded) - || isPositive(labelsRemoved) - || isPositive(indexesAdded) - || isPositive(indexesRemoved) - || isPositive(constraintsAdded) - || isPositive(constraintsRemoved); + return IntStream.of( + nodesCreated, + nodesDeleted, + relationshipsCreated, + relationshipsDeleted, + propertiesSet, + labelsAdded, + labelsRemoved, + indexesAdded, + indexesRemoved, + constraintsAdded, + constraintsRemoved) + .anyMatch(this::isPositive); } @Override diff --git a/driver/src/main/java/org/neo4j/driver/internal/util/CertificateTool.java b/driver/src/main/java/org/neo4j/driver/internal/util/CertificateTool.java index e2b7878e41..08246c3913 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/util/CertificateTool.java +++ b/driver/src/main/java/org/neo4j/driver/internal/util/CertificateTool.java @@ -159,7 +159,7 @@ public static void loadX509Cert(Certificate cert, String certAlias, KeyStore key */ public static String X509CertToString(String cert) { var cert64CharPerLine = cert.replaceAll("(.{64})", "$1\n"); - return BEGIN_CERT + "\n" + cert64CharPerLine + "\n" + END_CERT + "\n"; + return String.join("\n", BEGIN_CERT, cert64CharPerLine, END_CERT) + "\n"; } private CertificateTool() {} diff --git a/driver/src/main/java/org/neo4j/driver/internal/util/Extract.java b/driver/src/main/java/org/neo4j/driver/internal/util/Extract.java index a257b136ba..5839eeba81 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/util/Extract.java +++ b/driver/src/main/java/org/neo4j/driver/internal/util/Extract.java @@ -28,6 +28,7 @@ import static org.neo4j.driver.internal.util.Iterables.newHashMapWithSize; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; @@ -70,11 +71,7 @@ public static List list(Value[] data, Function mapFunction) { return singletonList(mapFunction.apply(data[0])); } default -> { - List result = new ArrayList<>(size); - for (var value : data) { - result.add(mapFunction.apply(value)); - } - return unmodifiableList(result); + return Arrays.stream(data).map(mapFunction).toList(); } } } diff --git a/driver/src/main/java/org/neo4j/driver/internal/util/Futures.java b/driver/src/main/java/org/neo4j/driver/internal/util/Futures.java index 4afe536293..c1e4f7b34f 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/util/Futures.java +++ b/driver/src/main/java/org/neo4j/driver/internal/util/Futures.java @@ -40,7 +40,7 @@ private Futures() {} @SuppressWarnings("unchecked") public static CompletableFuture completedWithNull() { - return (CompletableFuture) COMPLETED_WITH_NULL; + return (CompletableFuture) COMPLETED_WITH_NULL; } public static CompletableFuture completeWithNullIfNoError(CompletableFuture future, Throwable error) { diff --git a/driver/src/main/java/org/neo4j/driver/internal/util/Iterables.java b/driver/src/main/java/org/neo4j/driver/internal/util/Iterables.java index 882742a6b0..5d06f8e168 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/util/Iterables.java +++ b/driver/src/main/java/org/neo4j/driver/internal/util/Iterables.java @@ -38,10 +38,10 @@ public class Iterables { public static int count(Iterable it) { if (it instanceof Collection) { - return ((Collection) it).size(); + return ((Collection) it).size(); } var size = 0; - for (Object o : it) { + for (Object ignored : it) { size++; } return size; @@ -79,27 +79,24 @@ public static Map map(String... alternatingKeyValue) { } public static Iterable map(final Iterable it, final Function f) { - return new Iterable() { - @Override - public Iterator iterator() { - final var aIterator = it.iterator(); - return new Iterator() { - @Override - public boolean hasNext() { - return aIterator.hasNext(); - } - - @Override - public B next() { - return f.apply(aIterator.next()); - } - - @Override - public void remove() { - aIterator.remove(); - } - }; - } + return () -> { + final var aIterator = it.iterator(); + return new Iterator<>() { + @Override + public boolean hasNext() { + return aIterator.hasNext(); + } + + @Override + public B next() { + return f.apply(aIterator.next()); + } + + @Override + public void remove() { + aIterator.remove(); + } + }; }; } diff --git a/driver/src/main/java/org/neo4j/driver/internal/value/ListValue.java b/driver/src/main/java/org/neo4j/driver/internal/value/ListValue.java index 76c86108c7..4295a3fe02 100644 --- a/driver/src/main/java/org/neo4j/driver/internal/value/ListValue.java +++ b/driver/src/main/java/org/neo4j/driver/internal/value/ListValue.java @@ -72,26 +72,21 @@ public Value get(int index) { @Override public Iterable values(final Function mapFunction) { - return new Iterable() { + return () -> new Iterator<>() { + private int cursor = 0; + + @Override + public boolean hasNext() { + return cursor < values.length; + } + @Override - public Iterator iterator() { - return new Iterator() { - private int cursor = 0; - - @Override - public boolean hasNext() { - return cursor < values.length; - } - - @Override - public T next() { - return mapFunction.apply(values[cursor++]); - } - - @Override - public void remove() {} - }; + public T next() { + return mapFunction.apply(values[cursor++]); } + + @Override + public void remove() {} }; } diff --git a/driver/src/test/java/org/neo4j/driver/AuthTokensTest.java b/driver/src/test/java/org/neo4j/driver/AuthTokensTest.java index 339bd8f94a..cabd65886e 100644 --- a/driver/src/test/java/org/neo4j/driver/AuthTokensTest.java +++ b/driver/src/test/java/org/neo4j/driver/AuthTokensTest.java @@ -43,9 +43,9 @@ void basicAuthWithoutRealm() { var map = basic.toMap(); assertThat(map.size(), equalTo(3)); - assertThat(map.get("scheme"), equalTo((Value) new StringValue("basic"))); - assertThat(map.get("principal"), equalTo((Value) new StringValue("foo"))); - assertThat(map.get("credentials"), equalTo((Value) new StringValue("bar"))); + assertThat(map.get("scheme"), equalTo(new StringValue("basic"))); + assertThat(map.get("principal"), equalTo(new StringValue("foo"))); + assertThat(map.get("credentials"), equalTo(new StringValue("bar"))); } @Test @@ -55,10 +55,10 @@ void basicAuthWithRealm() { var map = basic.toMap(); assertThat(map.size(), equalTo(4)); - assertThat(map.get("scheme"), equalTo((Value) new StringValue("basic"))); - assertThat(map.get("principal"), equalTo((Value) new StringValue("foo"))); - assertThat(map.get("credentials"), equalTo((Value) new StringValue("bar"))); - assertThat(map.get("realm"), equalTo((Value) new StringValue("baz"))); + assertThat(map.get("scheme"), equalTo(new StringValue("basic"))); + assertThat(map.get("principal"), equalTo(new StringValue("foo"))); + assertThat(map.get("credentials"), equalTo(new StringValue("bar"))); + assertThat(map.get("realm"), equalTo(new StringValue("baz"))); } @Test @@ -68,10 +68,10 @@ void customAuthWithoutParameters() { var map = basic.toMap(); assertThat(map.size(), equalTo(4)); - assertThat(map.get("scheme"), equalTo((Value) new StringValue("my_scheme"))); - assertThat(map.get("principal"), equalTo((Value) new StringValue("foo"))); - assertThat(map.get("credentials"), equalTo((Value) new StringValue("bar"))); - assertThat(map.get("realm"), equalTo((Value) new StringValue("baz"))); + assertThat(map.get("scheme"), equalTo(new StringValue("my_scheme"))); + assertThat(map.get("principal"), equalTo(new StringValue("foo"))); + assertThat(map.get("credentials"), equalTo(new StringValue("bar"))); + assertThat(map.get("realm"), equalTo(new StringValue("baz"))); } @Test @@ -85,11 +85,11 @@ void customAuthParameters() { var map = basic.toMap(); assertThat(map.size(), equalTo(5)); - assertThat(map.get("scheme"), equalTo((Value) new StringValue("my_scheme"))); - assertThat(map.get("principal"), equalTo((Value) new StringValue("foo"))); - assertThat(map.get("credentials"), equalTo((Value) new StringValue("bar"))); - assertThat(map.get("realm"), equalTo((Value) new StringValue("baz"))); - assertThat(map.get("parameters"), equalTo((Value) new MapValue(expectedParameters))); + assertThat(map.get("scheme"), equalTo(new StringValue("my_scheme"))); + assertThat(map.get("principal"), equalTo(new StringValue("foo"))); + assertThat(map.get("credentials"), equalTo(new StringValue("bar"))); + assertThat(map.get("realm"), equalTo(new StringValue("baz"))); + assertThat(map.get("parameters"), equalTo(new MapValue(expectedParameters))); } @Test @@ -113,9 +113,9 @@ void basicKerberosAuthWithRealm() { var map = token.toMap(); assertThat(map.size(), equalTo(3)); - assertThat(map.get("scheme"), equalTo((Value) new StringValue("kerberos"))); - assertThat(map.get("principal"), equalTo((Value) new StringValue(""))); - assertThat(map.get("credentials"), equalTo((Value) new StringValue("base64"))); + assertThat(map.get("scheme"), equalTo(new StringValue("kerberos"))); + assertThat(map.get("principal"), equalTo(new StringValue(""))); + assertThat(map.get("credentials"), equalTo(new StringValue("base64"))); } @Test diff --git a/driver/src/test/java/org/neo4j/driver/integration/ScalarTypeIT.java b/driver/src/test/java/org/neo4j/driver/integration/ScalarTypeIT.java index 55da821286..fd5aedc991 100644 --- a/driver/src/test/java/org/neo4j/driver/integration/ScalarTypeIT.java +++ b/driver/src/test/java/org/neo4j/driver/integration/ScalarTypeIT.java @@ -25,10 +25,9 @@ import java.util.Arrays; import java.util.Collections; -import java.util.HashMap; -import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; +import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -60,7 +59,7 @@ static Stream typesToTest() { Arguments.of("RETURN ['hello'] as v", new ListValue(Values.value("hello"))), Arguments.of("RETURN [] as v", new ListValue()), Arguments.of("RETURN {k:'hello'} as v", parameters("k", Values.value("hello"))), - Arguments.of("RETURN {} as v", new MapValue(Collections.emptyMap()))); + Arguments.of("RETURN {} as v", new MapValue(Collections.emptyMap()))); } @ParameterizedTest @@ -86,10 +85,9 @@ static Stream collectionItems() { @MethodSource("collectionItems") void shouldEchoVeryLongMap(Value collectionItem) { // Given - Map input = new HashMap<>(); - for (var i = 0; i < 1000; i++) { - input.put(String.valueOf(i), collectionItem); - } + var input = IntStream.range(0, 1000) + .boxed() + .collect(Collectors.toMap(String::valueOf, i -> collectionItem, (a, b) -> b)); var mapValue = new MapValue(input); // When & Then @@ -100,10 +98,7 @@ void shouldEchoVeryLongMap(Value collectionItem) { @MethodSource("collectionItems") void shouldEchoVeryLongList(Value collectionItem) { // Given - var input = new Value[1000]; - for (var i = 0; i < 1000; i++) { - input[i] = collectionItem; - } + var input = IntStream.range(0, 1000).mapToObj(i -> collectionItem).toArray(Value[]::new); var listValue = new ListValue(input); // When & Then diff --git a/driver/src/test/java/org/neo4j/driver/integration/SessionIT.java b/driver/src/test/java/org/neo4j/driver/integration/SessionIT.java index 7f4709d3c0..ee7c3f1aad 100644 --- a/driver/src/test/java/org/neo4j/driver/integration/SessionIT.java +++ b/driver/src/test/java/org/neo4j/driver/integration/SessionIT.java @@ -64,6 +64,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; +import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -1181,9 +1182,9 @@ void shouldErrorDatabaseNameUsingTxWithRetriesWhenDatabaseIsAbsent() { var session = neo4j.driver().session(forDatabase("foo")); // When trying to run the query on a database that does not exist - var error = assertThrows(ClientException.class, () -> { - session.readTransaction(tx -> tx.run("RETURN 1").consume()); - }); + var error = assertThrows( + ClientException.class, + () -> session.readTransaction(tx -> tx.run("RETURN 1").consume())); assertThat(error.getMessage(), containsString("Database does not exist. Database name: 'foo'")); session.close(); } @@ -1226,10 +1227,9 @@ private void testExecuteReadTx(AccessMode sessionMode) { driver.session(builder().withDefaultAccessMode(sessionMode).build())) { var names = session.readTransaction(tx -> { var records = tx.run("MATCH (p:Person) RETURN p.name AS name").list(); - Set names1 = new HashSet<>(records.size()); - for (var record : records) { - names1.add(record.get("name").asString()); - } + Set names1 = records.stream() + .map(record -> record.get("name").asString()) + .collect(Collectors.toCollection(() -> new HashSet<>(records.size()))); return names1; }); diff --git a/driver/src/test/java/org/neo4j/driver/integration/SessionResetIT.java b/driver/src/test/java/org/neo4j/driver/integration/SessionResetIT.java index ed280c18b4..9b097ebb12 100644 --- a/driver/src/test/java/org/neo4j/driver/integration/SessionResetIT.java +++ b/driver/src/test/java/org/neo4j/driver/integration/SessionResetIT.java @@ -37,7 +37,6 @@ import static org.neo4j.driver.testutil.TestUtil.await; import java.nio.channels.ClosedChannelException; -import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Set; @@ -53,6 +52,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BooleanSupplier; +import java.util.stream.IntStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -76,7 +76,6 @@ class SessionResetIT { private static final String SHORT_QUERY_1 = "CREATE (n:Node {name: 'foo', occupation: 'bar'})"; private static final String SHORT_QUERY_2 = "MATCH (n:Node {name: 'foo'}) RETURN count(n)"; private static final String LONG_QUERY = "UNWIND range(0, 10000000) AS i CREATE (n:Node {idx: i}) DELETE n"; - ; private static final int STRESS_TEST_THREAD_COUNT = Runtime.getRuntime().availableProcessors() * 2; private static final long STRESS_TEST_DURATION_MS = SECONDS.toMillis(5); @@ -385,16 +384,14 @@ private static void assertTransactionTerminated(Future work) { private void testRandomQueryTermination(boolean autoCommit) throws InterruptedException { Set runningSessions = newSetFromMap(new ConcurrentHashMap<>()); var stop = new AtomicBoolean(); - List> futures = new ArrayList<>(); - - for (var i = 0; i < STRESS_TEST_THREAD_COUNT; i++) { - futures.add(executor.submit(() -> { - var random = ThreadLocalRandom.current(); - while (!stop.get()) { - runRandomQuery(autoCommit, random, runningSessions, stop); - } - })); - } + List> futures = IntStream.range(0, STRESS_TEST_THREAD_COUNT) + .mapToObj(i -> executor.submit(() -> { + var random = ThreadLocalRandom.current(); + while (!stop.get()) { + runRandomQuery(autoCommit, random, runningSessions, stop); + } + })) + .collect(toList()); var deadline = System.currentTimeMillis() + STRESS_TEST_DURATION_MS; while (!stop.get()) { diff --git a/driver/src/test/java/org/neo4j/driver/integration/async/AsyncSessionIT.java b/driver/src/test/java/org/neo4j/driver/integration/async/AsyncSessionIT.java index 543f6d6891..9155162808 100644 --- a/driver/src/test/java/org/neo4j/driver/integration/async/AsyncSessionIT.java +++ b/driver/src/test/java/org/neo4j/driver/integration/async/AsyncSessionIT.java @@ -57,6 +57,8 @@ import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -199,15 +201,11 @@ void shouldAllowNestedQueries() { @Test void shouldAllowMultipleAsyncRunsWithoutConsumingResults() { var queryCount = 13; - List> cursors = new ArrayList<>(); - for (var i = 0; i < queryCount; i++) { - cursors.add(session.runAsync("CREATE (:Person)")); - } + var cursors = IntStream.range(0, queryCount) + .mapToObj(i -> session.runAsync("CREATE (:Person)")) + .collect(Collectors.toList()); - List> records = new ArrayList<>(); - for (var cursor : awaitAll(cursors)) { - records.add(cursor.nextAsync()); - } + var records = awaitAll(cursors).stream().map(ResultCursor::nextAsync).collect(Collectors.toList()); awaitAll(records); @@ -836,10 +834,8 @@ private void testForEach(String query, int expectedSeenRecords) { private void testList(String query, List expectedList) { var cursor = await(session.runAsync(query)); var records = await(cursor.listAsync()); - List actualList = new ArrayList<>(); - for (var record : records) { - actualList.add(record.get(0).asObject()); - } + var actualList = + records.stream().map(record -> record.get(0).asObject()).collect(Collectors.toList()); assertEquals(expectedList, actualList); } diff --git a/driver/src/test/java/org/neo4j/driver/integration/async/AsyncTransactionIT.java b/driver/src/test/java/org/neo4j/driver/integration/async/AsyncTransactionIT.java index f4d1052504..2a7ed030bf 100644 --- a/driver/src/test/java/org/neo4j/driver/integration/async/AsyncTransactionIT.java +++ b/driver/src/test/java/org/neo4j/driver/integration/async/AsyncTransactionIT.java @@ -41,12 +41,12 @@ import static org.neo4j.driver.testutil.TestUtil.await; import java.io.IOException; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletionException; import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -449,11 +449,11 @@ void shouldFailForEachWhenActionFails() { var cursor = await(tx.runAsync("RETURN 'Hi!'")); var error = new RuntimeException(); - var e = assertThrows(RuntimeException.class, () -> { - await(cursor.forEachAsync(record -> { - throw error; - })); - }); + var e = assertThrows( + RuntimeException.class, + () -> await(cursor.forEachAsync(record -> { + throw error; + }))); assertEquals(error, e); } @@ -736,10 +736,8 @@ private void testList(String query, List expectedList) { var tx = await(session.beginTransactionAsync()); var cursor = await(tx.runAsync(query)); var records = await(cursor.listAsync()); - List actualList = new ArrayList<>(); - for (var record : records) { - actualList.add(record.get(0).asObject()); - } + var actualList = + records.stream().map(record -> record.get(0).asObject()).collect(Collectors.toList()); assertEquals(expectedList, actualList); } diff --git a/driver/src/test/java/org/neo4j/driver/integration/reactive/RxResultIT.java b/driver/src/test/java/org/neo4j/driver/integration/reactive/RxResultIT.java index 8693335e52..4e72e76e5a 100644 --- a/driver/src/test/java/org/neo4j/driver/integration/reactive/RxResultIT.java +++ b/driver/src/test/java/org/neo4j/driver/integration/reactive/RxResultIT.java @@ -178,9 +178,7 @@ void shouldHaveFieldNamesInResult() { .expectComplete() .verify(); StepVerifier.create(res.records()) - .assertNext(record -> { - assertEquals("[n]", record.keys().toString()); - }) + .assertNext(record -> assertEquals("[n]", record.keys().toString())) .expectComplete() .verify(); } @@ -292,9 +290,7 @@ void shouldStreamCorrectRecordsBackBeforeError() { .expectNext(1) .expectNext(1) .expectNext(1) - .expectErrorSatisfies(error -> { - assertThat(error.getMessage(), containsString("/ by zero")); - }) + .expectErrorSatisfies(error -> assertThat(error.getMessage(), containsString("/ by zero"))) .verify(); } @@ -306,9 +302,8 @@ void shouldErrorToAccessRecordAfterSessionClose() { // When StepVerifier.create(Flux.from(session.close()).thenMany(result.records())) - .expectErrorSatisfies(error -> { - assertThat(error.getMessage(), containsString("session is already closed")); - }) + .expectErrorSatisfies( + error -> assertThat(error.getMessage(), containsString("session is already closed"))) .verify(); } @@ -320,9 +315,8 @@ void shouldErrorToAccessKeysAfterSessionClose() { // When StepVerifier.create(Flux.from(session.close()).thenMany(result.keys())) - .expectErrorSatisfies(error -> { - assertThat(error.getMessage(), containsString("session is already closed")); - }) + .expectErrorSatisfies( + error -> assertThat(error.getMessage(), containsString("session is already closed"))) .verify(); } @@ -334,9 +328,8 @@ void shouldErrorToAccessSummaryAfterSessionClose() { // When StepVerifier.create(Flux.from(session.close()).thenMany(result.consume())) - .expectErrorSatisfies(error -> { - assertThat(error.getMessage(), containsString("session is already closed")); - }) + .expectErrorSatisfies( + error -> assertThat(error.getMessage(), containsString("session is already closed"))) .verify(); } diff --git a/driver/src/test/java/org/neo4j/driver/integration/reactive/RxSessionIT.java b/driver/src/test/java/org/neo4j/driver/integration/reactive/RxSessionIT.java index 397b370ad6..60f0ded0a9 100644 --- a/driver/src/test/java/org/neo4j/driver/integration/reactive/RxSessionIT.java +++ b/driver/src/test/java/org/neo4j/driver/integration/reactive/RxSessionIT.java @@ -89,9 +89,7 @@ void shouldBeAbleToReuseSessionAfterFailure() { // Then StepVerifier.create(res2.records()) - .assertNext(record -> { - assertEquals(record.get("1").asLong(), 1L); - }) + .assertNext(record -> assertEquals(record.get("1").asLong(), 1L)) .expectComplete() .verify(); } diff --git a/driver/src/test/java/org/neo4j/driver/integration/reactive/RxTransactionIT.java b/driver/src/test/java/org/neo4j/driver/integration/reactive/RxTransactionIT.java index bfeec943dd..b4618c4f8e 100644 --- a/driver/src/test/java/org/neo4j/driver/integration/reactive/RxTransactionIT.java +++ b/driver/src/test/java/org/neo4j/driver/integration/reactive/RxTransactionIT.java @@ -530,9 +530,7 @@ void shouldFailWhenListTransformationFunctionFails() { null); StepVerifier.create(records) - .expectErrorSatisfies(error -> { - assertEquals(e, error); - }) + .expectErrorSatisfies(error -> assertEquals(e, error)) .verify(); } @@ -542,9 +540,7 @@ void shouldFailToCommitWhenServerIsRestarted() { var result = tx.run("RETURN 1"); assertThrows(ServiceUnavailableException.class, () -> { - await(Flux.from(result.records()).doOnSubscribe(subscription -> { - neo4j.stopProxy(); - })); + await(Flux.from(result.records()).doOnSubscribe(subscription -> neo4j.stopProxy())); await(tx.commit()); }); diff --git a/driver/src/test/java/org/neo4j/driver/internal/InternalMapAccessorWithDefaultValueTest.java b/driver/src/test/java/org/neo4j/driver/internal/InternalMapAccessorWithDefaultValueTest.java index 074b251b3b..bfdbb68a3c 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/InternalMapAccessorWithDefaultValueTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/InternalMapAccessorWithDefaultValueTest.java @@ -59,25 +59,26 @@ var record = createRecord(); assertThat(record.get("NullValue", NullValue.NULL), equalTo(NullValue.NULL)); assertThat(record.get(wrongKey, NullValue.NULL), equalTo(NullValue.NULL)); - assertThat(record.get("BooleanValue", BooleanValue.FALSE), equalTo((Value) BooleanValue.TRUE)); - assertThat(record.get(wrongKey, BooleanValue.FALSE), equalTo((Value) BooleanValue.FALSE)); + assertThat(record.get("BooleanValue", BooleanValue.FALSE), equalTo(BooleanValue.TRUE)); + assertThat(record.get(wrongKey, BooleanValue.FALSE), equalTo(BooleanValue.FALSE)); - assertThat(record.get("StringValue", new StringValue("")), equalTo((Value) new StringValue("hello world"))); - assertThat(record.get(wrongKey, new StringValue("")), equalTo((Value) new StringValue(""))); + assertThat(record.get("StringValue", new StringValue("")), equalTo(new StringValue("hello world"))); + assertThat(record.get(wrongKey, new StringValue("")), equalTo(new StringValue(""))); - assertThat(record.get("IntegerValue", new IntegerValue(-1)), equalTo((Value) new IntegerValue(11))); - assertThat(record.get(wrongKey, new IntegerValue(-1)), equalTo((Value) new IntegerValue(-1))); + assertThat(record.get("IntegerValue", new IntegerValue(-1)), equalTo(new IntegerValue(11))); + assertThat(record.get(wrongKey, new IntegerValue(-1)), equalTo(new IntegerValue(-1))); - assertThat(record.get("FloatValue", new FloatValue(1.1)), equalTo((Value) new FloatValue(2.2))); - assertThat(record.get(wrongKey, new FloatValue(1.1)), equalTo((Value) new FloatValue(1.1))); + assertThat(record.get("FloatValue", new FloatValue(1.1)), equalTo(new FloatValue(2.2))); + assertThat(record.get(wrongKey, new FloatValue(1.1)), equalTo(new FloatValue(1.1))); // List - assertThat(record.get("ListValue", new ListValue()), equalTo((Value) - new ListValue(new IntegerValue(1), new IntegerValue(2)))); - assertThat(record.get(wrongKey, new ListValue()), equalTo((Value) new ListValue())); + assertThat( + record.get("ListValue", new ListValue()), + equalTo(new ListValue(new IntegerValue(1), new IntegerValue(2)))); + assertThat(record.get(wrongKey, new ListValue()), equalTo(new ListValue())); // Map - Value defaultMapValue = new MapValue(new HashMap()); + Value defaultMapValue = new MapValue(new HashMap<>()); Value realMapValue = new MapValue(createMap()); assertThat(record.get("MapValue", defaultMapValue), equalTo(realMapValue)); assertThat(record.get(wrongKey, defaultMapValue), equalTo(defaultMapValue)); diff --git a/driver/src/test/java/org/neo4j/driver/internal/InternalResultTest.java b/driver/src/test/java/org/neo4j/driver/internal/InternalResultTest.java index 9cf8be0473..77b0d16fff 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/InternalResultTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/InternalResultTest.java @@ -42,6 +42,7 @@ import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -62,6 +63,7 @@ import org.neo4j.driver.internal.messaging.v43.BoltProtocolV43; import org.neo4j.driver.internal.spi.Connection; import org.neo4j.driver.internal.value.NullValue; +import org.neo4j.driver.util.Pair; class InternalResultTest { @Test @@ -370,10 +372,10 @@ private Result createResult(int numberOfRecords) { } private List values(Record record) { - List result = new ArrayList<>(record.keys().size()); - for (var property : record.fields()) { - result.add(property.value()); - } + List result = record.fields().stream() + .map(Pair::value) + .collect(Collectors.toCollection( + () -> new ArrayList<>(record.keys().size()))); return result; } } diff --git a/driver/src/test/java/org/neo4j/driver/internal/SelfContainedNodeTest.java b/driver/src/test/java/org/neo4j/driver/internal/SelfContainedNodeTest.java index bbea54a990..6f6700c601 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/SelfContainedNodeTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/SelfContainedNodeTest.java @@ -44,7 +44,7 @@ void testIdentity() { var node = adamTheNode(); // Then - assertThat(node.id(), equalTo(1l)); + assertThat(node.id(), equalTo(1L)); } @Test diff --git a/driver/src/test/java/org/neo4j/driver/internal/ValuesTest.java b/driver/src/test/java/org/neo4j/driver/internal/ValuesTest.java index e7c867ecbe..3f1f5de5ea 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/ValuesTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/ValuesTest.java @@ -75,6 +75,7 @@ class ValuesTest { @Test + @SuppressWarnings("RedundantArrayCreation") void shouldConvertPrimitiveArrays() { assertThat(value(new short[] {1, 2, 3}), equalTo(new ListValue(values(1, 2, 3)))); @@ -268,7 +269,7 @@ void shouldHandleCollection() { var val = value(collection); // When/Then - assertThat(val.asList(), Matchers.containsInAnyOrder("hello", "world")); + assertThat(val.asList(), Matchers.containsInAnyOrder("hello", "world")); } @Test @@ -278,7 +279,7 @@ void shouldHandleIterator() { var val = value(iterator); // When/Then - assertThat(val.asList(), Matchers.containsInAnyOrder("hello", "world")); + assertThat(val.asList(), Matchers.containsInAnyOrder("hello", "world")); } @Test diff --git a/driver/src/test/java/org/neo4j/driver/internal/async/InternalAsyncSessionTest.java b/driver/src/test/java/org/neo4j/driver/internal/async/InternalAsyncSessionTest.java index ff867841e8..56e8a4e2a0 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/async/InternalAsyncSessionTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/async/InternalAsyncSessionTest.java @@ -121,7 +121,7 @@ private static Stream>> all private static Stream>> allBeginTxMethods() { return Stream.of( - session -> session.beginTransactionAsync(), + AsyncSession::beginTransactionAsync, session -> session.beginTransactionAsync(TransactionConfig.empty())); } @@ -368,9 +368,8 @@ private static class TxWork implements AsyncTransactionWork) null); } TxWork(int timesToThrow, final RuntimeException error) { diff --git a/driver/src/test/java/org/neo4j/driver/internal/async/connection/DecoratedConnectionTest.java b/driver/src/test/java/org/neo4j/driver/internal/async/connection/DecoratedConnectionTest.java index d13b879ba4..fbe5b99cee 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/async/connection/DecoratedConnectionTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/async/connection/DecoratedConnectionTest.java @@ -47,7 +47,7 @@ void shouldDelegateIsOpen(String open) { var connection = newConnection(mockConnection); - assertEquals(Boolean.valueOf(open).booleanValue(), connection.isOpen()); + assertEquals(Boolean.valueOf(open), connection.isOpen()); verify(mockConnection).isOpen(); } diff --git a/driver/src/test/java/org/neo4j/driver/internal/async/pool/NettyChannelHealthCheckerTest.java b/driver/src/test/java/org/neo4j/driver/internal/async/pool/NettyChannelHealthCheckerTest.java index e684cfc883..a1dfcb107d 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/async/pool/NettyChannelHealthCheckerTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/async/pool/NettyChannelHealthCheckerTest.java @@ -56,7 +56,6 @@ import org.junit.jupiter.params.provider.MethodSource; import org.neo4j.driver.AuthTokenManager; import org.neo4j.driver.AuthTokens; -import org.neo4j.driver.Value; import org.neo4j.driver.exceptions.AuthorizationExpiredException; import org.neo4j.driver.internal.async.inbound.InboundMessageDispatcher; import org.neo4j.driver.internal.messaging.BoltProtocolVersion; @@ -290,7 +289,7 @@ private void testPing(boolean resetMessageSuccessful) { assertFalse(healthy.isDone()); if (resetMessageSuccessful) { - dispatcher.handleSuccessMessage(Collections.emptyMap()); + dispatcher.handleSuccessMessage(Collections.emptyMap()); assertThat(await(healthy), is(true)); } else { dispatcher.handleFailureMessage("Neo.ClientError.General.Unknown", "Error!"); diff --git a/driver/src/test/java/org/neo4j/driver/internal/cluster/ClusterCompositionTest.java b/driver/src/test/java/org/neo4j/driver/internal/cluster/ClusterCompositionTest.java index 35cbee50ac..6b54a92839 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/cluster/ClusterCompositionTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/cluster/ClusterCompositionTest.java @@ -32,12 +32,12 @@ import static org.neo4j.driver.internal.util.ClusterCompositionUtil.E; import static org.neo4j.driver.internal.util.ClusterCompositionUtil.F; -import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; -import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.neo4j.driver.Record; import org.neo4j.driver.Value; @@ -207,10 +207,8 @@ private static Set addresses(BoltServerAddress... elements) { private static Map serversEntry(String role, BoltServerAddress... addresses) { Map map = new HashMap<>(); map.put("role", role); - List addressStrings = new ArrayList<>(); - for (var address : addresses) { - addressStrings.add(address.toString()); - } + var addressStrings = + Arrays.stream(addresses).map(BoltServerAddress::toString).collect(Collectors.toList()); map.put("addresses", addressStrings); return map; } diff --git a/driver/src/test/java/org/neo4j/driver/internal/cluster/ClusterRoutingTableTest.java b/driver/src/test/java/org/neo4j/driver/internal/cluster/ClusterRoutingTableTest.java index ba2ff644aa..de0ea28c71 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/cluster/ClusterRoutingTableTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/cluster/ClusterRoutingTableTest.java @@ -39,6 +39,7 @@ import java.time.Clock; import java.time.Duration; +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -53,7 +54,7 @@ void shouldReturnStaleIfTtlExpired() { RoutingTable routingTable = newRoutingTable(clock); // When - routingTable.update(createClusterComposition(1000, asList(A, B), asList(C), asList(D, E))); + routingTable.update(createClusterComposition(1000, asList(A, B), List.of(C), asList(D, E))); clock.progress(1234); // Then @@ -67,7 +68,7 @@ void shouldReturnStaleIfNoRouter() { RoutingTable routingTable = newRoutingTable(); // When - routingTable.update(createClusterComposition(EMPTY, asList(C), asList(D, E))); + routingTable.update(createClusterComposition(EMPTY, List.of(C), asList(D, E))); // Then assertTrue(routingTable.isStaleFor(READ)); @@ -80,7 +81,7 @@ void shouldBeStaleForReadsButNotWritesWhenNoReaders() { RoutingTable routingTable = newRoutingTable(); // When - routingTable.update(createClusterComposition(asList(A, B), asList(C), EMPTY)); + routingTable.update(createClusterComposition(asList(A, B), List.of(C), EMPTY)); // Then assertTrue(routingTable.isStaleFor(READ)); @@ -106,7 +107,7 @@ void shouldBeNotStaleWithReadersWritersAndRouters() { RoutingTable routingTable = newRoutingTable(); // When - routingTable.update(createClusterComposition(asList(A, B), asList(C), asList(D, E))); + routingTable.update(createClusterComposition(asList(A, B), List.of(C), asList(D, E))); // Then assertFalse(routingTable.isStaleFor(READ)); diff --git a/driver/src/test/java/org/neo4j/driver/internal/cluster/RoutingContextTest.java b/driver/src/test/java/org/neo4j/driver/internal/cluster/RoutingContextTest.java index 9a2c6b07dc..d5e6462e7e 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/cluster/RoutingContextTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/cluster/RoutingContextTest.java @@ -70,7 +70,7 @@ void boltUriDisablesServerSideRouting() { var uri = URI.create("bolt://localhost:7687/?key1=value1&key2=value2&key3=value3"); var context = new RoutingContext(uri); - assertEquals(false, context.isServerRoutingEnabled()); + assertFalse(context.isServerRoutingEnabled()); } @Test @@ -78,7 +78,7 @@ void neo4jUriEnablesServerSideRouting() { var uri = URI.create("neo4j://localhost:7687/?key1=value1&key2=value2&key3=value3"); var context = new RoutingContext(uri); - assertEquals(true, context.isServerRoutingEnabled()); + assertTrue(context.isServerRoutingEnabled()); } @Test diff --git a/driver/src/test/java/org/neo4j/driver/internal/cluster/RoutingProcedureClusterCompositionProviderTest.java b/driver/src/test/java/org/neo4j/driver/internal/cluster/RoutingProcedureClusterCompositionProviderTest.java index 04759351e1..9626eecdc0 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/cluster/RoutingProcedureClusterCompositionProviderTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/cluster/RoutingProcedureClusterCompositionProviderTest.java @@ -36,11 +36,12 @@ import static org.neo4j.driver.testutil.TestUtil.await; import java.time.Clock; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.neo4j.driver.Query; import org.neo4j.driver.Record; @@ -360,11 +361,7 @@ private static Map serverInfo(String role, String... addresses) } private static Set serverSet(String... addresses) { - Set result = new HashSet<>(); - for (var address : addresses) { - result.add(new BoltServerAddress(address)); - } - return result; + return Arrays.stream(addresses).map(BoltServerAddress::new).collect(Collectors.toSet()); } private static SingleDatabaseRoutingProcedureRunner newProcedureRunnerMock() { diff --git a/driver/src/test/java/org/neo4j/driver/internal/cluster/loadbalancing/LoadBalancerTest.java b/driver/src/test/java/org/neo4j/driver/internal/cluster/loadbalancing/LoadBalancerTest.java index adcbc9fcfc..8fba3d23d0 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/cluster/loadbalancing/LoadBalancerTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/cluster/loadbalancing/LoadBalancerTest.java @@ -56,11 +56,12 @@ import io.netty.util.concurrent.GlobalEventExecutor; import java.util.Arrays; import java.util.Collections; -import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.params.ParameterizedTest; @@ -157,11 +158,10 @@ void shouldSelectLeastConnectedAddress() { var loadBalancer = newLoadBalancer(connectionPool, routingTable); - Set seenAddresses = new HashSet<>(); - for (var i = 0; i < 10; i++) { - var connection = await(loadBalancer.acquireConnection(newBoltV4ConnectionContext())); - seenAddresses.add(connection.serverAddress()); - } + var seenAddresses = IntStream.range(0, 10) + .mapToObj(i -> await(loadBalancer.acquireConnection(newBoltV4ConnectionContext()))) + .map(Connection::serverAddress) + .collect(Collectors.toSet()); // server B should never be selected because it has many active connections assertEquals(2, seenAddresses.size()); @@ -178,11 +178,10 @@ void shouldRoundRobinWhenNoActiveConnections() { var loadBalancer = newLoadBalancer(connectionPool, routingTable); - Set seenAddresses = new HashSet<>(); - for (var i = 0; i < 10; i++) { - var connection = await(loadBalancer.acquireConnection(newBoltV4ConnectionContext())); - seenAddresses.add(connection.serverAddress()); - } + var seenAddresses = IntStream.range(0, 10) + .mapToObj(i -> await(loadBalancer.acquireConnection(newBoltV4ConnectionContext()))) + .map(Connection::serverAddress) + .collect(Collectors.toSet()); assertEquals(3, seenAddresses.size()); assertTrue(seenAddresses.containsAll(asList(A, B, C))); diff --git a/driver/src/test/java/org/neo4j/driver/internal/cluster/loadbalancing/RoutingTableAndConnectionPoolTest.java b/driver/src/test/java/org/neo4j/driver/internal/cluster/loadbalancing/RoutingTableAndConnectionPoolTest.java index 9645c03acc..27117f5fe9 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/cluster/loadbalancing/RoutingTableAndConnectionPoolTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/cluster/loadbalancing/RoutingTableAndConnectionPoolTest.java @@ -52,6 +52,8 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import org.junit.jupiter.api.Test; import org.neo4j.driver.AuthToken; import org.neo4j.driver.Bookmark; @@ -260,13 +262,8 @@ void shouldHandleAddAndRemoveFromRoutingTableAndConnectionPool() throws Throwabl // When acquireAndReleaseConnections(loadBalancer); var servers = routingTables.allServers(); - BoltServerAddress openServer = null; - for (var server : servers) { - if (connectionPool.isOpen(server)) { - openServer = server; - break; - } - } + var openServer = + servers.stream().filter(connectionPool::isOpen).findFirst().orElse(null); assertNotNull(servers); // if we remove the open server from servers, then the connection pool should remove the server from the pool. @@ -349,7 +346,7 @@ private CompletableFuture expiredClusterComposit private CompletableFuture clusterComposition( long expireAfterMs, BoltServerAddress... addresses) { - var servers = new HashSet(Arrays.asList(addresses)); + var servers = new HashSet<>(Arrays.asList(addresses)); var composition = new ClusterComposition(clock.millis() + expireAfterMs, servers, servers, servers, null); return CompletableFuture.completedFuture(new ClusterCompositionLookupResult(composition)); } @@ -363,14 +360,11 @@ public CompletionStage lookupClusterComposition( String impersonatedUser, AuthToken overrideAuthToken) { // when looking up a new routing table, we return a valid random routing table back - Set servers = new HashSet<>(); - for (var i = 0; i < 3; i++) { - var index = random.nextInt(SERVERS.size()); - var server = SERVERS.get(index); - if (server != null) { - servers.add(server); - } - } + var servers = IntStream.range(0, 3) + .map(i -> random.nextInt(SERVERS.size())) + .mapToObj(SERVERS::get) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); if (servers.size() == 0) { var address = SERVERS.stream() .filter(Objects::nonNull) diff --git a/driver/src/test/java/org/neo4j/driver/internal/logging/PrefixedLoggerTest.java b/driver/src/test/java/org/neo4j/driver/internal/logging/PrefixedLoggerTest.java index 226ea13a2c..2d3ec1a364 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/logging/PrefixedLoggerTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/logging/PrefixedLoggerTest.java @@ -18,7 +18,6 @@ */ package org.neo4j.driver.internal.logging; -import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -43,7 +42,7 @@ void shouldThrowWhenDelegateIsNull() { @Test void shouldAllowNullPrefix() { - assertNotNull(new PrefixedLogger(null, newLoggerMock())); + new PrefixedLogger(null, newLoggerMock()); } @Test diff --git a/driver/src/test/java/org/neo4j/driver/internal/packstream/PackStreamTest.java b/driver/src/test/java/org/neo4j/driver/internal/packstream/PackStreamTest.java index 998598db47..ce742a3b38 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/packstream/PackStreamTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/packstream/PackStreamTest.java @@ -34,6 +34,8 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import org.junit.jupiter.api.Test; import org.neo4j.driver.internal.util.Iterables; import org.neo4j.driver.internal.util.io.BufferedChannelInput; @@ -697,10 +699,9 @@ private void assertMap(int size) throws Throwable { // When var packer = machine.packer(); - var map = new HashMap(); - for (var i = 0; i < size; i++) { - map.put(Integer.toString(i), i); - } + var map = IntStream.range(0, size) + .boxed() + .collect(Collectors.toMap(i -> Integer.toString(i), i -> i, (a, b) -> b, HashMap::new)); packer.pack(map); // Then diff --git a/driver/src/test/java/org/neo4j/driver/internal/reactive/InternalRxSessionTest.java b/driver/src/test/java/org/neo4j/driver/internal/reactive/InternalRxSessionTest.java index d7597a062c..f1b204d4f4 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/reactive/InternalRxSessionTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/reactive/InternalRxSessionTest.java @@ -79,8 +79,7 @@ private static Stream> allSessionRunMethods() { private static Stream>> allBeginTxMethods() { return Stream.of( - rxSession -> rxSession.beginTransaction(), - rxSession -> rxSession.beginTransaction(TransactionConfig.empty())); + RxSession::beginTransaction, rxSession -> rxSession.beginTransaction(TransactionConfig.empty())); } private static Stream>> allRunTxMethods() { diff --git a/driver/src/test/java/org/neo4j/driver/internal/util/BookmarkUtil.java b/driver/src/test/java/org/neo4j/driver/internal/util/BookmarkUtil.java index 91231e84ca..799472457f 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/util/BookmarkUtil.java +++ b/driver/src/test/java/org/neo4j/driver/internal/util/BookmarkUtil.java @@ -41,7 +41,7 @@ public class BookmarkUtil { public static void assertBookmarkIsEmpty(Bookmark bookmark) { assertNotNull(bookmark); assertThat(bookmark, instanceOf(InternalBookmark.class)); - assertTrue(((InternalBookmark) bookmark).isEmpty()); + assertTrue(bookmark.isEmpty()); } /** @@ -51,7 +51,7 @@ public static void assertBookmarkIsEmpty(Bookmark bookmark) { public static void assertBookmarkIsNotEmpty(Bookmark bookmark) { assertNotNull(bookmark); assertThat(bookmark, instanceOf(InternalBookmark.class)); - assertFalse(((InternalBookmark) bookmark).isEmpty()); + assertFalse(bookmark.isEmpty()); } /** diff --git a/driver/src/test/java/org/neo4j/driver/internal/util/FuturesTest.java b/driver/src/test/java/org/neo4j/driver/internal/util/FuturesTest.java index 6eeb81e6df..9b289cdca0 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/util/FuturesTest.java +++ b/driver/src/test/java/org/neo4j/driver/internal/util/FuturesTest.java @@ -59,7 +59,7 @@ void shouldConvertCanceledNettyFutureToCompletionStage() { @Test void shouldConvertSucceededNettyFutureToCompletionStage() throws Exception { - var nettyFuture = new SucceededFuture(ImmediateEventExecutor.INSTANCE, "Hello"); + var nettyFuture = new SucceededFuture<>(ImmediateEventExecutor.INSTANCE, "Hello"); var future = Futures.asCompletionStage(nettyFuture).toCompletableFuture(); @@ -71,7 +71,7 @@ void shouldConvertSucceededNettyFutureToCompletionStage() throws Exception { @Test void shouldConvertFailedNettyFutureToCompletionStage() { var error = new RuntimeException("Hello"); - var nettyFuture = new FailedFuture(ImmediateEventExecutor.INSTANCE, error); + var nettyFuture = new FailedFuture<>(ImmediateEventExecutor.INSTANCE, error); var future = Futures.asCompletionStage(nettyFuture).toCompletableFuture(); diff --git a/driver/src/test/java/org/neo4j/driver/internal/util/Matchers.java b/driver/src/test/java/org/neo4j/driver/internal/util/Matchers.java index 42f933fb89..25e75d42ac 100644 --- a/driver/src/test/java/org/neo4j/driver/internal/util/Matchers.java +++ b/driver/src/test/java/org/neo4j/driver/internal/util/Matchers.java @@ -37,7 +37,7 @@ public final class Matchers { private Matchers() {} public static Matcher directDriver() { - return new TypeSafeMatcher() { + return new TypeSafeMatcher<>() { @Override protected boolean matchesSafely(Driver driver) { return hasConnectionProvider(driver, DirectConnectionProvider.class); @@ -51,7 +51,7 @@ public void describeTo(Description description) { } public static Matcher directDriverWithAddress(final BoltServerAddress address) { - return new TypeSafeMatcher() { + return new TypeSafeMatcher<>() { @Override protected boolean matchesSafely(Driver driver) { var provider = extractConnectionProvider(driver, DirectConnectionProvider.class); @@ -66,7 +66,7 @@ public void describeTo(Description description) { } public static Matcher clusterDriver() { - return new TypeSafeMatcher() { + return new TypeSafeMatcher<>() { @Override protected boolean matchesSafely(Driver driver) { return hasConnectionProvider(driver, LoadBalancer.class); @@ -80,7 +80,7 @@ public void describeTo(Description description) { } public static Matcher containsResultAvailableAfterAndResultConsumedAfter() { - return new TypeSafeMatcher() { + return new TypeSafeMatcher<>() { @Override protected boolean matchesSafely(ResultSummary summary) { return summary.resultAvailableAfter(TimeUnit.MILLISECONDS) >= 0L @@ -95,7 +95,7 @@ public void describeTo(Description description) { } public static Matcher arithmeticError() { - return new TypeSafeMatcher() { + return new TypeSafeMatcher<>() { @Override protected boolean matchesSafely(Throwable error) { return error instanceof ClientException @@ -114,7 +114,7 @@ public static Matcher syntaxError() { } public static Matcher syntaxError(String messagePrefix) { - return new TypeSafeMatcher() { + return new TypeSafeMatcher<>() { @Override protected boolean matchesSafely(Throwable error) { if (error instanceof ClientException clientError) { @@ -133,7 +133,7 @@ public void describeTo(Description description) { } public static Matcher connectionAcquisitionTimeoutError(int timeoutMillis) { - return new TypeSafeMatcher() { + return new TypeSafeMatcher<>() { @Override protected boolean matchesSafely(Throwable error) { if (error instanceof ClientException) { @@ -152,7 +152,7 @@ public void describeTo(Description description) { } public static Matcher blockingOperationInEventLoopError() { - return new TypeSafeMatcher() { + return new TypeSafeMatcher<>() { @Override protected boolean matchesSafely(Throwable error) { return error instanceof IllegalStateException diff --git a/driver/src/test/java/org/neo4j/driver/stress/AbstractStressTestBase.java b/driver/src/test/java/org/neo4j/driver/stress/AbstractStressTestBase.java index 88b6c16fc5..ff0273e96e 100644 --- a/driver/src/test/java/org/neo4j/driver/stress/AbstractStressTestBase.java +++ b/driver/src/test/java/org/neo4j/driver/stress/AbstractStressTestBase.java @@ -60,6 +60,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.logging.Level; +import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -226,12 +227,9 @@ List> createTestSpecificRxCommands() { private List> launchBlockingWorkerThreads(C context) { var commands = createBlockingCommands(); - List> futures = new ArrayList<>(); - - for (var i = 0; i < THREAD_COUNT; i++) { - var future = launchBlockingWorkerThread(executor, commands, context); - futures.add(future); - } + List> futures = IntStream.range(0, THREAD_COUNT) + .mapToObj(i -> launchBlockingWorkerThread(executor, commands, context)) + .collect(Collectors.toList()); return futures; } @@ -269,12 +267,10 @@ private Future launchBlockingWorkerThread( private List> launchRxWorkerThreads(C context) { var commands = createRxCommands(); - List> futures = new ArrayList<>(); + List> futures = IntStream.range(0, THREAD_COUNT) + .mapToObj(i -> launchRxWorkerThread(executor, commands, context)) + .collect(Collectors.toList()); - for (var i = 0; i < THREAD_COUNT; i++) { - var future = launchRxWorkerThread(executor, commands, context); - futures.add(future); - } return futures; } @@ -318,12 +314,9 @@ private CompletableFuture executeRxCommands(C context, List> private List> launchAsyncWorkerThreads(C context) { var commands = createAsyncCommands(); - List> futures = new ArrayList<>(); - - for (var i = 0; i < THREAD_COUNT; i++) { - var future = launchAsyncWorkerThread(executor, commands, context); - futures.add(future); - } + List> futures = IntStream.range(0, THREAD_COUNT) + .mapToObj(i -> launchAsyncWorkerThread(executor, commands, context)) + .collect(Collectors.toList()); return futures; } diff --git a/driver/src/test/java/org/neo4j/driver/stress/RxFailingQuery.java b/driver/src/test/java/org/neo4j/driver/stress/RxFailingQuery.java index f2a568e1e5..0097a40dfd 100644 --- a/driver/src/test/java/org/neo4j/driver/stress/RxFailingQuery.java +++ b/driver/src/test/java/org/neo4j/driver/stress/RxFailingQuery.java @@ -48,9 +48,8 @@ public CompletionStage execute(C context) { .records(), RxSession::close) .subscribe( - record -> { - assertThat(record.get(0).asInt(), either(equalTo(1)).or(equalTo(2))); - }, + record -> assertThat( + record.get(0).asInt(), either(equalTo(1)).or(equalTo(2))), error -> { var cause = Futures.completionExceptionCause(error); assertThat(cause, is(arithmeticError())); diff --git a/driver/src/test/java/org/neo4j/driver/stress/RxFailingQueryInTx.java b/driver/src/test/java/org/neo4j/driver/stress/RxFailingQueryInTx.java index 71cc5a3eeb..5dcc935a96 100644 --- a/driver/src/test/java/org/neo4j/driver/stress/RxFailingQueryInTx.java +++ b/driver/src/test/java/org/neo4j/driver/stress/RxFailingQueryInTx.java @@ -49,9 +49,8 @@ public CompletionStage execute(C context) { (tx, error) -> tx.rollback(), null) .subscribe( - record -> { - assertThat(record.get(0).asInt(), either(equalTo(1)).or(equalTo(2))); - }, + record -> assertThat( + record.get(0).asInt(), either(equalTo(1)).or(equalTo(2))), error -> { var cause = Futures.completionExceptionCause(error); assertThat(cause, is(arithmeticError())); diff --git a/driver/src/test/java/org/neo4j/driver/stress/RxFailingQueryWithRetries.java b/driver/src/test/java/org/neo4j/driver/stress/RxFailingQueryWithRetries.java index 3f4b866b7d..6c91879219 100644 --- a/driver/src/test/java/org/neo4j/driver/stress/RxFailingQueryWithRetries.java +++ b/driver/src/test/java/org/neo4j/driver/stress/RxFailingQueryWithRetries.java @@ -48,9 +48,8 @@ public CompletionStage execute(C context) { tx.run("UNWIND [10, 5, 0] AS x RETURN 10 / x").records()), RxSession::close) .subscribe( - record -> { - assertThat(record.get(0).asInt(), either(equalTo(1)).or(equalTo(2))); - }, + record -> assertThat( + record.get(0).asInt(), either(equalTo(1)).or(equalTo(2))), error -> { var cause = Futures.completionExceptionCause(error); assertThat(cause, is(arithmeticError())); diff --git a/driver/src/test/java/org/neo4j/driver/testutil/FileTools.java b/driver/src/test/java/org/neo4j/driver/testutil/FileTools.java index b296f0c2d8..5aed9527fa 100644 --- a/driver/src/test/java/org/neo4j/driver/testutil/FileTools.java +++ b/driver/src/test/java/org/neo4j/driver/testutil/FileTools.java @@ -113,16 +113,13 @@ public static void copyRecursively(File fromDirectory, File toDirectory, FileFil } public static void copyFile(File srcFile, File dstFile) throws IOException { - //noinspection ResultOfMethodCallIgnored var parentFile = dstFile.getParentFile(); if (parentFile != null) { + //noinspection ResultOfMethodCallIgnored parentFile.mkdirs(); } - FileInputStream input = null; - FileOutputStream output = null; - try { - input = new FileInputStream(srcFile); - output = new FileOutputStream(dstFile); + try (var input = new FileInputStream(srcFile); + var output = new FileOutputStream(dstFile)) { var bufferSize = 1024; var buffer = new byte[bufferSize]; int bytesRead; @@ -133,13 +130,6 @@ public static void copyFile(File srcFile, File dstFile) throws IOException { // Because the message from this cause may not mention which file it's about throw new IOException( "Could not copy '" + srcFile.getCanonicalPath() + "' to '" + dstFile.getCanonicalPath() + "'", e); - } finally { - if (input != null) { - input.close(); - } - if (output != null) { - output.close(); - } } } @@ -158,7 +148,7 @@ private static void waitAndThenTriggerGC() { public static void updateProperty(File propFile, String key, String value) throws IOException { Map propertiesMap = new HashMap<>(1); propertiesMap.put(key, value); - updateProperties(propFile, propertiesMap, Collections.emptySet()); + updateProperties(propFile, propertiesMap, Collections.emptySet()); } public static void updateProperties(File propFile, Map propertiesMap, Set excludes) diff --git a/driver/src/test/java/org/neo4j/driver/testutil/TestUtil.java b/driver/src/test/java/org/neo4j/driver/testutil/TestUtil.java index 6f66a8b162..b0e137d31c 100644 --- a/driver/src/test/java/org/neo4j/driver/testutil/TestUtil.java +++ b/driver/src/test/java/org/neo4j/driver/testutil/TestUtil.java @@ -63,6 +63,8 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeoutException; import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import org.mockito.ArgumentMatcher; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -164,10 +166,8 @@ public static > T await(U future) { public static void assertByteBufContains(ByteBuf buf, Number... values) { try { assertNotNull(buf); - var expectedReadableBytes = 0; - for (var value : values) { - expectedReadableBytes += bytesCount(value); - } + var expectedReadableBytes = + Arrays.stream(values).mapToInt(TestUtil::bytesCount).sum(); assertEquals(expectedReadableBytes, buf.readableBytes(), "Unexpected number of bytes"); for (var expectedValue : values) { var actualValue = read(buf, expectedValue.getClass()); @@ -451,16 +451,18 @@ public static Connection connectionMock(String databaseName, AccessMode mode, Bo when(connection.mode()).thenReturn(mode); when(connection.databaseName()).thenReturn(database(databaseName)); var version = protocol.version(); - if (version.equals(BoltProtocolV3.VERSION) - || version.equals(BoltProtocolV4.VERSION) - || version.equals(BoltProtocolV41.VERSION) - || version.equals(BoltProtocolV42.VERSION) - || version.equals(BoltProtocolV43.VERSION) - || version.equals(BoltProtocolV44.VERSION) - || version.equals(BoltProtocolV5.VERSION) - || version.equals(BoltProtocolV51.VERSION) - || version.equals(BoltProtocolV52.VERSION) - || version.equals(BoltProtocolV53.VERSION)) { + if (List.of( + BoltProtocolV3.VERSION, + BoltProtocolV4.VERSION, + BoltProtocolV41.VERSION, + BoltProtocolV42.VERSION, + BoltProtocolV43.VERSION, + BoltProtocolV44.VERSION, + BoltProtocolV5.VERSION, + BoltProtocolV51.VERSION, + BoltProtocolV52.VERSION, + BoltProtocolV53.VERSION) + .contains(version)) { setupSuccessResponse(connection, CommitMessage.class); setupSuccessResponse(connection, RollbackMessage.class); setupSuccessResponse(connection, BeginMessage.class); @@ -493,12 +495,10 @@ public static void interruptWhenInWaitingState(Thread thread) { } public static String randomString(int size) { - var sb = new StringBuilder(size); var random = ThreadLocalRandom.current(); - for (var i = 0; i < size; i++) { - sb.append(ALPHANUMERICS.charAt(random.nextInt(ALPHANUMERICS.length()))); - } - return sb.toString(); + return IntStream.range(0, size) + .mapToObj(i -> String.valueOf(ALPHANUMERICS.charAt(random.nextInt(ALPHANUMERICS.length())))) + .collect(Collectors.joining()); } public static ArgumentMatcher runWithMetaMessageWithQueryMatcher(String query) { diff --git a/driver/src/test/java/org/neo4j/driver/types/TypeSystemTest.java b/driver/src/test/java/org/neo4j/driver/types/TypeSystemTest.java index bc818693fe..3d25958620 100644 --- a/driver/src/test/java/org/neo4j/driver/types/TypeSystemTest.java +++ b/driver/src/test/java/org/neo4j/driver/types/TypeSystemTest.java @@ -54,7 +54,7 @@ class TypeSystemTest { private final Value nodeValue = new NodeValue(node); private final Value relationshipValue = new RelationshipValue(relationship); private final Value mapValue = value(Collections.singletonMap("type", "r")); - private final Value pathValue = new PathValue(new InternalPath(Arrays.asList(node, relationship, node))); + private final Value pathValue = new PathValue(new InternalPath(Arrays.asList(node, relationship, node))); private final Value booleanValue = value(true); private final Value listValue = value(Arrays.asList(1, 2, 3)); private final Value nullValue = value((Object) null); @@ -229,7 +229,7 @@ public void close() { } private Matcher hasType(final Type type) { - return new BaseMatcher() { + return new BaseMatcher<>() { @Override public boolean matches(Object o) { return (o instanceof Value || o == null) && type.isTypeOf((Value) o); diff --git a/examples/src/main/java/org/neo4j/docs/driver/ResultRetainExample.java b/examples/src/main/java/org/neo4j/docs/driver/ResultRetainExample.java index 70b191c4b2..178cd9f81e 100644 --- a/examples/src/main/java/org/neo4j/docs/driver/ResultRetainExample.java +++ b/examples/src/main/java/org/neo4j/docs/driver/ResultRetainExample.java @@ -26,21 +26,18 @@ public ResultRetainExample(String uri, String user, String password) { } // tag::result-retain[] + @SuppressWarnings("UnusedReturnValue") public int addEmployees(final String companyName) { try (var session = driver.session()) { - var employees = 0; var persons = session.executeRead(tx -> tx.run("MATCH (a:Person) RETURN a.name AS name").list()); - for (var person : persons) { - employees += session.executeWrite(tx -> { - var result = tx.run( - "MATCH (emp:Person {name: $person_name}) " + "MERGE (com:Company {name: $company_name}) " - + "MERGE (emp)-[:WORKS_FOR]->(com)", - parameters("person_name", person.get("name").asString(), "company_name", companyName)); - result.consume(); - return 1; - }); - } - return employees; + return persons.stream().mapToInt(person -> session.executeWrite(tx -> { + var result = tx.run( + "MATCH (emp:Person {name: $person_name}) " + "MERGE (com:Company {name: $company_name}) " + + "MERGE (emp)-[:WORKS_FOR]->(com)", + parameters("person_name", person.get("name").asString(), "company_name", companyName)); + result.consume(); + return 1; + })).sum(); } } // end::result-retain[] diff --git a/testkit-backend/src/main/java/neo4j/org/testkit/backend/messages/responses/serializer/GenUtils.java b/testkit-backend/src/main/java/neo4j/org/testkit/backend/messages/responses/serializer/GenUtils.java index 8fd58c08df..01c0919166 100644 --- a/testkit-backend/src/main/java/neo4j/org/testkit/backend/messages/responses/serializer/GenUtils.java +++ b/testkit-backend/src/main/java/neo4j/org/testkit/backend/messages/responses/serializer/GenUtils.java @@ -90,7 +90,6 @@ public static Class cypherTypeToJavaType(String typeString) { case "CypherTime" -> CypherTime.class; case "CypherDate" -> LocalDate.class; case "CypherDuration" -> IsoDuration.class; - case "CypherNull" -> null; default -> null; }; }